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
list | 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
list | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fbb4e75fcea66495c0e1fff8c2924190cd7c10e9
| 29,583,734,762,225 |
80a9824f3039d0958d7164526f4370f5b60249a8
|
/src/main/java/raidzero/robot/auto/sequences/TestTurretAngleSequence.java
|
6c145a435f61e6a3c6b72db3974d5ce35d4e3934
|
[] |
no_license
|
TASRobotics/RaidZero-FRC-2020
|
https://github.com/TASRobotics/RaidZero-FRC-2020
|
9b6f9be2ed64cc7be80935650ef9c2b34406c0a6
|
65d5d72ba06b2a9b154991973555a13c5d7f519c
|
refs/heads/master
| 2023-03-11T01:05:49.838000 | 2020-03-05T01:28:54 | 2020-03-05T01:28:54 | 231,868,782 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package raidzero.robot.auto.sequences;
import java.util.Arrays;
import raidzero.robot.auto.actions.*;
public class TestTurretAngleSequence extends AutoSequence {
public TestTurretAngleSequence() {
}
@Override
public void sequence() {
addAction(new SeriesAction(
Arrays.asList(
new TurnTurretToAngle(90),
new FeedBalls(2.0)
)
));
System.out.println("Added actions.");
}
@Override
public void onEnded() {
System.out.println("TestTurretAngleSequence ended!");
}
@Override
public String getName() {
return "Test TurnTurretToAngle Sequence";
}
}
|
UTF-8
|
Java
| 688 |
java
|
TestTurretAngleSequence.java
|
Java
|
[] | null |
[] |
package raidzero.robot.auto.sequences;
import java.util.Arrays;
import raidzero.robot.auto.actions.*;
public class TestTurretAngleSequence extends AutoSequence {
public TestTurretAngleSequence() {
}
@Override
public void sequence() {
addAction(new SeriesAction(
Arrays.asList(
new TurnTurretToAngle(90),
new FeedBalls(2.0)
)
));
System.out.println("Added actions.");
}
@Override
public void onEnded() {
System.out.println("TestTurretAngleSequence ended!");
}
@Override
public String getName() {
return "Test TurnTurretToAngle Sequence";
}
}
| 688 | 0.613372 | 0.607558 | 33 | 19.878788 | 18.662485 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.242424 | false | false |
3
|
b4d733381abd53fa9e910e951aeff8f1b78fd338
| 18,202,071,403,832 |
62f8e44c858507e80fdb8d759f7611e95abeb0ed
|
/src/main/java/bio/terra/service/dataset/flight/delete/DeleteDatasetGcpValidateStep.java
|
72786b9d72cdd7db5a81c23085437613e998eb06
|
[
"BSD-3-Clause"
] |
permissive
|
DataBiosphere/jade-data-repo
|
https://github.com/DataBiosphere/jade-data-repo
|
cfe5557a0f59fa6eefc95729fc6367afc20d1b85
|
33c63a7fcac82aae2de37617e3d78b1076f8cacd
|
refs/heads/develop
| 2023-08-23T16:04:57.810000 | 2023-08-16T21:05:44 | 2023-08-16T21:05:44 | 157,737,730 | 19 | 6 |
BSD-3-Clause
| false | 2023-09-12T15:15:27 | 2018-11-15T16:04:29 | 2023-01-31T17:07:18 | 2023-09-12T15:15:26 | 21,884 | 13 | 5 | 13 |
Java
| false | false |
package bio.terra.service.dataset.flight.delete;
import bio.terra.service.dataset.Dataset;
import bio.terra.service.dataset.DatasetService;
import bio.terra.service.filedata.google.firestore.FireStoreDependencyDao;
import bio.terra.service.snapshot.SnapshotDao;
import bio.terra.stairway.FlightContext;
import java.util.UUID;
public class DeleteDatasetGcpValidateStep extends DeleteDatasetValidateStep {
public DeleteDatasetGcpValidateStep(
SnapshotDao snapshotDao,
FireStoreDependencyDao dependencyDao,
DatasetService datasetService,
UUID datasetId) {
super(snapshotDao, dependencyDao, datasetService, datasetId);
}
@Override
boolean hasSnapshotReference(Dataset dataset, FlightContext context) throws InterruptedException {
return dependencyDao.datasetHasSnapshotReference(dataset);
}
}
|
UTF-8
|
Java
| 835 |
java
|
DeleteDatasetGcpValidateStep.java
|
Java
|
[] | null |
[] |
package bio.terra.service.dataset.flight.delete;
import bio.terra.service.dataset.Dataset;
import bio.terra.service.dataset.DatasetService;
import bio.terra.service.filedata.google.firestore.FireStoreDependencyDao;
import bio.terra.service.snapshot.SnapshotDao;
import bio.terra.stairway.FlightContext;
import java.util.UUID;
public class DeleteDatasetGcpValidateStep extends DeleteDatasetValidateStep {
public DeleteDatasetGcpValidateStep(
SnapshotDao snapshotDao,
FireStoreDependencyDao dependencyDao,
DatasetService datasetService,
UUID datasetId) {
super(snapshotDao, dependencyDao, datasetService, datasetId);
}
@Override
boolean hasSnapshotReference(Dataset dataset, FlightContext context) throws InterruptedException {
return dependencyDao.datasetHasSnapshotReference(dataset);
}
}
| 835 | 0.814371 | 0.814371 | 24 | 33.791668 | 27.925465 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
7dc32d1735d1c2bef7d0a4821d832e1f755bb995
| 22,754,736,774,031 |
c62059a5c65bc2e92b5c978791a7413a77ea75dd
|
/src/main/java/sac/dao/PessoaDAO.java
|
27c41658390e2c8257227e46265903494b03b103
|
[] |
no_license
|
GeovanaSF/sac
|
https://github.com/GeovanaSF/sac
|
c490edab0d661dbdfb1e26764ed5b7cd1d3bd229
|
bf9244ea0a79cc165d163acdd815ee6362aea0ce
|
refs/heads/master
| 2023-06-15T09:45:01.633000 | 2021-07-06T23:40:21 | 2021-07-06T23:40:21 | 378,790,593 | 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 sac.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import sac.domain.Pessoa;
import sac.domain.Usuario;
/**
*
* @author
*/
public class PessoaDAO implements DAO<Pessoa> {
private static final String QUERY_INSERT = "INSERT INTO Pessoa (perfil_id, endereco_id, nome, cpf, telefone, email, senha, salt) VALUES (?,?,?,?,?,?,?,?)";
private static final String QUERY_UPDATE = "UPDATE Pessoa SET perfil_id=?, endereco_id=?, nome=?, cpf=?, telefone=? WHERE pessoa_id=?";
private static final String QUERY_UPDATE_ = "UPDATE Pessoa SET nome=?, telefone=? WHERE pessoa_id=?";
private static final String QUERY_UPDATE_SENHA = "UPDATE Pessoa SET senha=?, salt=? WHERE pessoa_id=?";
private static final String QUERY_REMOVE = "DELETE FROM Pessoa WHERE pessoa_id=?";
private static final String QUERY_GET = "SELECT pessoa_id, perfil_id, endereco_id, nome, cpf, telefone FROM Pessoa";
private static final String QUERY_GETPESSOA = "SELECT \n"
+ " P.pessoa_id, P.nome, P.cpf, P.telefone, E.cidade_id, C.estado_id, P.email, P.senha,\n"
+ " E.rua, E.numero, E.complemento, E.bairro, E.cep, P.endereco_id, P.perfil_id, PF.nome as perfil\n"
+ " FROM PESSOA P\n"
+ "JOIN ENDERECO E ON P.endereco_id = E.endereco_id\n"
+ "JOIN CIDADE C ON E.cidade_id = C.cidade_id\n"
+ "JOIN PERFIL PF ON P.perfil_id = PF.perfil_id";
private static final String QUERY_GETUSUARIO = "select pessoa_id, email, senha, salt, perfil_id from pessoa where email = ?";
private final Connection conn;
public PessoaDAO(Connection conn) throws DAOException {
this.conn = conn;
}
@Override
public Pessoa getById(int id) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GET + " WHERE pessoa_id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
return new Pessoa(rs.getInt("pessoa_id"), rs.getInt("perfil_id"),
rs.getInt("endereco_id"), rs.getString("nome"),
rs.getString("cpf"), rs.getString("telefone"));
}
return null;
}
public sac.model.Pessoa getPessoaById(int id) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETPESSOA + " WHERE pessoa_id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
return new sac.model.Pessoa(rs.getInt("pessoa_id"), rs.getString("nome"), rs.getString("cpf"), rs.getString("telefone"),
rs.getInt("cidade_id"), rs.getInt("estado_id"), rs.getString("email"), rs.getString("senha"),
rs.getInt("perfil_id"), rs.getString("rua"), rs.getString("numero"), rs.getString("complemento"),
rs.getString("bairro"), rs.getString("cep"), rs.getString("endereco_id"), rs.getString("perfil"));
}
return null;
}
public sac.model.Pessoa getPessoaByUserId(int id) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETPESSOA + " WHERE P.pessoa_id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
return new sac.model.Pessoa(rs.getInt("pessoa_id"), rs.getString("nome"), rs.getString("cpf"), rs.getString("telefone"),
rs.getInt("cidade_id"), rs.getInt("estado_id"), rs.getString("email"), rs.getString("senha"),
rs.getInt("perfil_id"), rs.getString("rua"), rs.getString("numero"), rs.getString("complemento"),
rs.getString("bairro"), rs.getString("cep"), rs.getString("endereco_id"), rs.getString("perfil"));
}
return null;
}
public List<sac.model.Pessoa> getPessoaByPerfilId(int id) throws DAOException, SQLException {
List<sac.model.Pessoa> lista = null;
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETPESSOA + " WHERE P.perfil_id <> ?");
ps.setInt(1, id);
rs = ps.executeQuery();
lista = new ArrayList<>();
while (rs.next()) {
lista.add(new sac.model.Pessoa(rs.getInt("pessoa_id"), rs.getString("nome"), rs.getString("cpf"), rs.getString("telefone"),
rs.getInt("cidade_id"), rs.getInt("estado_id"), rs.getString("email"), rs.getString("senha"),
rs.getInt("perfil_id"), rs.getString("rua"), rs.getString("numero"), rs.getString("complemento"),
rs.getString("bairro"), rs.getString("cep"), rs.getString("endereco_id"), rs.getString("perfil")));
}
return lista;
}
@Override
public Pessoa getSingle(String email) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GET + " WHERE nome like '%?%'");
ps.setString(1, email);
rs = ps.executeQuery();
if (rs.next()) {
return new Pessoa(rs.getInt("pessoa_id"), rs.getInt("perfil_id"),
rs.getInt("endereco_id"), rs.getString("nome"),
rs.getString("cpf"), rs.getString("telefone"));
}
return null;
}
@Override
public List<Pessoa> getList() throws DAOException, SQLException {
List<Pessoa> lista = null;
Statement ps = null;
ResultSet rs = null;
ps = conn.createStatement();
rs = ps.executeQuery(QUERY_GET);
lista = new ArrayList<>();
while (rs.next()) {
lista.add(new Pessoa(rs.getInt("pessoa_id"), rs.getInt("perfil_id"),
rs.getInt("endereco_id"), rs.getString("nome"),
rs.getString("cpf"), rs.getString("telefone")));
}
return lista;
}
@Override
public Integer insert(Pessoa obj) throws DAOException, SQLException {
int key = 0;
PreparedStatement stmt = conn.prepareStatement(QUERY_INSERT,
Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, obj.getPerfil_Id());
stmt.setObject(2, obj.getEndereco_Id());
stmt.setString(3, obj.getNome());
stmt.setString(4, obj.getCpf());
stmt.setString(5, obj.getTelefone());
stmt.setString(6, obj.getEmail());
stmt.setString(7, obj.getSenha());
stmt.setString(8, obj.getKey());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
// Retrieve the auto generated key(s).
key = rs.getInt(1);
}
return key;
}
@Override
public void update(Pessoa obj) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_UPDATE);
stmt.setInt(1, obj.getPerfil_Id());
stmt.setObject(2, obj.getEndereco_Id());
stmt.setString(3, obj.getNome());
stmt.setString(4, obj.getCpf());
stmt.setString(5, obj.getTelefone());
stmt.setInt(6, obj.getPessoa_Id());
stmt.executeUpdate();
}
public void updateDados(Pessoa obj) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_UPDATE_);
stmt.setString(1, obj.getNome());
stmt.setString(2, obj.getTelefone());
stmt.setInt(3, obj.getPessoa_Id());
stmt.executeUpdate();
}
public void updateSenha(Pessoa obj) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_UPDATE_SENHA);
stmt.setString(1, obj.getSenha());
stmt.setString(2, obj.getKey());
stmt.setInt(3, obj.getPessoa_Id());
stmt.executeUpdate();
}
@Override
public void remove(int id) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_REMOVE);
stmt.setInt(1, id);
stmt.executeUpdate();
}
public Usuario getUserByEmail(String login) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETUSUARIO);
ps.setString(1, login);
rs = ps.executeQuery();
if (rs.next()) {
return new Usuario(rs.getInt("pessoa_id"),
rs.getString("email"), rs.getString("senha"), rs.getString("salt"), rs.getInt("perfil_id"));
}
return null;
}
}
|
UTF-8
|
Java
| 8,965 |
java
|
PessoaDAO.java
|
Java
|
[] | 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 sac.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import sac.domain.Pessoa;
import sac.domain.Usuario;
/**
*
* @author
*/
public class PessoaDAO implements DAO<Pessoa> {
private static final String QUERY_INSERT = "INSERT INTO Pessoa (perfil_id, endereco_id, nome, cpf, telefone, email, senha, salt) VALUES (?,?,?,?,?,?,?,?)";
private static final String QUERY_UPDATE = "UPDATE Pessoa SET perfil_id=?, endereco_id=?, nome=?, cpf=?, telefone=? WHERE pessoa_id=?";
private static final String QUERY_UPDATE_ = "UPDATE Pessoa SET nome=?, telefone=? WHERE pessoa_id=?";
private static final String QUERY_UPDATE_SENHA = "UPDATE Pessoa SET senha=?, salt=? WHERE pessoa_id=?";
private static final String QUERY_REMOVE = "DELETE FROM Pessoa WHERE pessoa_id=?";
private static final String QUERY_GET = "SELECT pessoa_id, perfil_id, endereco_id, nome, cpf, telefone FROM Pessoa";
private static final String QUERY_GETPESSOA = "SELECT \n"
+ " P.pessoa_id, P.nome, P.cpf, P.telefone, E.cidade_id, C.estado_id, P.email, P.senha,\n"
+ " E.rua, E.numero, E.complemento, E.bairro, E.cep, P.endereco_id, P.perfil_id, PF.nome as perfil\n"
+ " FROM PESSOA P\n"
+ "JOIN ENDERECO E ON P.endereco_id = E.endereco_id\n"
+ "JOIN CIDADE C ON E.cidade_id = C.cidade_id\n"
+ "JOIN PERFIL PF ON P.perfil_id = PF.perfil_id";
private static final String QUERY_GETUSUARIO = "select pessoa_id, email, senha, salt, perfil_id from pessoa where email = ?";
private final Connection conn;
public PessoaDAO(Connection conn) throws DAOException {
this.conn = conn;
}
@Override
public Pessoa getById(int id) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GET + " WHERE pessoa_id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
return new Pessoa(rs.getInt("pessoa_id"), rs.getInt("perfil_id"),
rs.getInt("endereco_id"), rs.getString("nome"),
rs.getString("cpf"), rs.getString("telefone"));
}
return null;
}
public sac.model.Pessoa getPessoaById(int id) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETPESSOA + " WHERE pessoa_id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
return new sac.model.Pessoa(rs.getInt("pessoa_id"), rs.getString("nome"), rs.getString("cpf"), rs.getString("telefone"),
rs.getInt("cidade_id"), rs.getInt("estado_id"), rs.getString("email"), rs.getString("senha"),
rs.getInt("perfil_id"), rs.getString("rua"), rs.getString("numero"), rs.getString("complemento"),
rs.getString("bairro"), rs.getString("cep"), rs.getString("endereco_id"), rs.getString("perfil"));
}
return null;
}
public sac.model.Pessoa getPessoaByUserId(int id) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETPESSOA + " WHERE P.pessoa_id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
return new sac.model.Pessoa(rs.getInt("pessoa_id"), rs.getString("nome"), rs.getString("cpf"), rs.getString("telefone"),
rs.getInt("cidade_id"), rs.getInt("estado_id"), rs.getString("email"), rs.getString("senha"),
rs.getInt("perfil_id"), rs.getString("rua"), rs.getString("numero"), rs.getString("complemento"),
rs.getString("bairro"), rs.getString("cep"), rs.getString("endereco_id"), rs.getString("perfil"));
}
return null;
}
public List<sac.model.Pessoa> getPessoaByPerfilId(int id) throws DAOException, SQLException {
List<sac.model.Pessoa> lista = null;
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETPESSOA + " WHERE P.perfil_id <> ?");
ps.setInt(1, id);
rs = ps.executeQuery();
lista = new ArrayList<>();
while (rs.next()) {
lista.add(new sac.model.Pessoa(rs.getInt("pessoa_id"), rs.getString("nome"), rs.getString("cpf"), rs.getString("telefone"),
rs.getInt("cidade_id"), rs.getInt("estado_id"), rs.getString("email"), rs.getString("senha"),
rs.getInt("perfil_id"), rs.getString("rua"), rs.getString("numero"), rs.getString("complemento"),
rs.getString("bairro"), rs.getString("cep"), rs.getString("endereco_id"), rs.getString("perfil")));
}
return lista;
}
@Override
public Pessoa getSingle(String email) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GET + " WHERE nome like '%?%'");
ps.setString(1, email);
rs = ps.executeQuery();
if (rs.next()) {
return new Pessoa(rs.getInt("pessoa_id"), rs.getInt("perfil_id"),
rs.getInt("endereco_id"), rs.getString("nome"),
rs.getString("cpf"), rs.getString("telefone"));
}
return null;
}
@Override
public List<Pessoa> getList() throws DAOException, SQLException {
List<Pessoa> lista = null;
Statement ps = null;
ResultSet rs = null;
ps = conn.createStatement();
rs = ps.executeQuery(QUERY_GET);
lista = new ArrayList<>();
while (rs.next()) {
lista.add(new Pessoa(rs.getInt("pessoa_id"), rs.getInt("perfil_id"),
rs.getInt("endereco_id"), rs.getString("nome"),
rs.getString("cpf"), rs.getString("telefone")));
}
return lista;
}
@Override
public Integer insert(Pessoa obj) throws DAOException, SQLException {
int key = 0;
PreparedStatement stmt = conn.prepareStatement(QUERY_INSERT,
Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, obj.getPerfil_Id());
stmt.setObject(2, obj.getEndereco_Id());
stmt.setString(3, obj.getNome());
stmt.setString(4, obj.getCpf());
stmt.setString(5, obj.getTelefone());
stmt.setString(6, obj.getEmail());
stmt.setString(7, obj.getSenha());
stmt.setString(8, obj.getKey());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
// Retrieve the auto generated key(s).
key = rs.getInt(1);
}
return key;
}
@Override
public void update(Pessoa obj) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_UPDATE);
stmt.setInt(1, obj.getPerfil_Id());
stmt.setObject(2, obj.getEndereco_Id());
stmt.setString(3, obj.getNome());
stmt.setString(4, obj.getCpf());
stmt.setString(5, obj.getTelefone());
stmt.setInt(6, obj.getPessoa_Id());
stmt.executeUpdate();
}
public void updateDados(Pessoa obj) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_UPDATE_);
stmt.setString(1, obj.getNome());
stmt.setString(2, obj.getTelefone());
stmt.setInt(3, obj.getPessoa_Id());
stmt.executeUpdate();
}
public void updateSenha(Pessoa obj) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_UPDATE_SENHA);
stmt.setString(1, obj.getSenha());
stmt.setString(2, obj.getKey());
stmt.setInt(3, obj.getPessoa_Id());
stmt.executeUpdate();
}
@Override
public void remove(int id) throws DAOException, SQLException {
PreparedStatement stmt = conn.prepareStatement(QUERY_REMOVE);
stmt.setInt(1, id);
stmt.executeUpdate();
}
public Usuario getUserByEmail(String login) throws DAOException, SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ps = conn.prepareStatement(QUERY_GETUSUARIO);
ps.setString(1, login);
rs = ps.executeQuery();
if (rs.next()) {
return new Usuario(rs.getInt("pessoa_id"),
rs.getString("email"), rs.getString("senha"), rs.getString("salt"), rs.getInt("perfil_id"));
}
return null;
}
}
| 8,965 | 0.604796 | 0.601562 | 235 | 37.148937 | 35.932903 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.097872 | false | false |
3
|
306eae183fb0ec4992bcd67e185dc3d7989367a3
| 386,547,066,586 |
0d7bb74c8c5a6b9ad143640a2263a455c2a98e58
|
/entity/management/src/main/java/cn/fintecher/pangolin/entity/managentment/ClockConfig.java
|
3c1f54664ab7bc0089a0cfc93620e8121675032b
|
[] |
no_license
|
yixinsiyu/pangolin-credit-card-server-fz
|
https://github.com/yixinsiyu/pangolin-credit-card-server-fz
|
c39905846caa2d8db940d6af7d46c95ad324ff2b
|
6ad85e6b2aedbd2e5a686d6f1fb4de24e25760b8
|
refs/heads/master
| 2021-09-25T00:25:07.644000 | 2018-10-16T05:52:41 | 2018-10-16T05:52:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.fintecher.pangolin.entity.managentment;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.List;
@Data
@Document
@ApiModel("打卡设置")
public class ClockConfig implements Serializable {
@Id
private String id;
@ApiModelProperty("所属机构")
private String organization;
@ApiModelProperty("公司名称")
private String organizationName;
@ApiModelProperty("打卡配置")
private List<ClockConfigDetail> clockConfigDetails;
}
|
UTF-8
|
Java
| 694 |
java
|
ClockConfig.java
|
Java
|
[] | null |
[] |
package cn.fintecher.pangolin.entity.managentment;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.List;
@Data
@Document
@ApiModel("打卡设置")
public class ClockConfig implements Serializable {
@Id
private String id;
@ApiModelProperty("所属机构")
private String organization;
@ApiModelProperty("公司名称")
private String organizationName;
@ApiModelProperty("打卡配置")
private List<ClockConfigDetail> clockConfigDetails;
}
| 694 | 0.780967 | 0.780967 | 28 | 22.642857 | 19.603598 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
3
|
fdb913518e40641e16e8158e6d9ef11a8ae97a44
| 16,793,322,141,436 |
639e868f48de24a83d2e1160702b6d7db3966c67
|
/Webshop/src/se/cristian/webshop/service/validation/DuplicateValidator.java
|
73fd729e9dbb5f70ceb7efe3e37294e62458798f
|
[] |
no_license
|
CristianOrtega2016/WebShopProject
|
https://github.com/CristianOrtega2016/WebShopProject
|
913cce36149a9b70a0dd320dded1f7c81322d47d
|
3ee8e874eacf8d903cf94e9189560523bf64de6a
|
refs/heads/master
| 2020-09-16T11:03:12.831000 | 2016-09-08T18:12:14 | 2016-09-08T18:12:14 | 67,611,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package se.cristian.webshop.service.validation;
public interface DuplicateValidator
{
boolean alreadyExists(String email);
}
|
UTF-8
|
Java
| 128 |
java
|
DuplicateValidator.java
|
Java
|
[] | null |
[] |
package se.cristian.webshop.service.validation;
public interface DuplicateValidator
{
boolean alreadyExists(String email);
}
| 128 | 0.820313 | 0.820313 | 6 | 20.333334 | 19.980547 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
aa8e20c16fced410a22698dcdeadfe8a5e0216be
| 26,182,120,651,032 |
388f88df1f49b5414c22b97304ec295801f7f0f3
|
/classhidra4ape/src/it/classhidra/core/controller/tags/tagSelect.java
|
3de03308023a4ffbf70629769e0efd8721eba4ba
|
[] |
no_license
|
surban1974/classhidra
|
https://github.com/surban1974/classhidra
|
c3f1dcb9546d7d13a235d431492985555fe7a4ac
|
f0937bed637265e42659c92d863c12c239f55166
|
refs/heads/master
| 2023-08-30T04:44:13.153000 | 2023-08-25T13:50:16 | 2023-08-25T13:50:16 | 5,340,773 | 0 | 0 | null | false | 2022-12-16T07:12:39 | 2012-08-08T11:25:37 | 2022-04-18T19:12:08 | 2022-12-16T07:12:36 | 1,205,176 | 0 | 0 | 13 |
Java
| false | false |
/**
* Creation date: (07/04/2006)
* @author: Svyatoslav Urbanovych svyatoslav.urbanovych@gmail.com
*/
/********************************************************************************
*
* Copyright (C) 2005 Svyatoslav Urbanovych
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*********************************************************************************/
package it.classhidra.core.controller.tags;
import it.classhidra.core.controller.action;
import it.classhidra.core.controller.bsConstants;
import it.classhidra.core.controller.bsController;
import it.classhidra.core.controller.i_action;
import it.classhidra.core.controller.i_bean;
import it.classhidra.core.controller.info_navigation;
import it.classhidra.core.tool.util.util_format;
import it.classhidra.core.tool.util.util_reflect;
import it.classhidra.core.tool.util.util_tag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.*;
import java.io.IOException;
import java.util.HashMap;
public class tagSelect extends tagInput{
private static final long serialVersionUID = -1L;
private String multiple=null;
public int doEndTag() throws JspException {
StringBuffer results = new StringBuffer("</select>");
JspWriter writer = pageContext.getOut();
try {
writer.print(results.toString());
} catch (IOException e) {
throw new JspException(e.toString());
}
value=null;
return EVAL_BODY_INCLUDE;
}
protected String createTagBody() {
HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
i_action formAction=null;
i_bean formBean=null;
if(bean!=null){
HashMap pool = (HashMap)request.getAttribute(bsController.CONST_BEAN_$INSTANCEACTIONPOOL);
if(pool!=null) formAction = (i_action)pool.get(bean);
}
if(formAction!=null) bean = null;
else formAction = (i_action)request.getAttribute(bsController.CONST_BEAN_$INSTANCEACTION);
if(formAction==null) formAction = new action();
if(bean==null) formBean = formAction.get_bean();
if(method_prefix==null) method_prefix="get";
Object writeValue=null;
String prefixName=null;
if(bean!=null && request.getAttribute(tagBean.CONST_HEAP_BEANS)!=null && ((HashMap)request.getAttribute(tagBean.CONST_HEAP_BEANS)).get(bean)!=null){
prefixName = ((HashMap)request.getAttribute(tagBean.CONST_HEAP_BEANS)).get(bean).toString();
}
if(prefixName==null)
prefixName=name;
else prefixName+="."+name;
String asyncUpdateUrl=null;
// if(value==null){
if(bean==null && name!=null){
writeValue = formBean.get(name);
try{
if(writeValue!=null) value = util_format.makeFormatedString(formatOutput,formatLanguage,formatCountry,writeValue);
}catch(Exception e){}
}else{
Object anotherBean = null;
if(name!=null){
if(bean.equals(bsConstants.CONST_TAG_REQUESTPARAMETER)) anotherBean = request.getParameter(name);
if(bean.equals(bsConstants.CONST_TAG_SYSTEMPROPERTY)) anotherBean = System.getProperty(name);
}
if(anotherBean==null) anotherBean = request.getAttribute(bean);
if(anotherBean==null) anotherBean = request.getSession().getAttribute(bean);
if(anotherBean==null) anotherBean = request.getSession().getServletContext().getAttribute(bean);
if(name!=null){
if(anotherBean==null) anotherBean = request.getAttribute(name);
if(anotherBean==null) anotherBean = request.getSession().getAttribute(name);
if(anotherBean==null) anotherBean = request.getSession().getServletContext().getAttribute(name);
}
if(anotherBean==null) anotherBean = util_tag.getBeanAsBSTag(bean,this);
try{
if(anotherBean==null) anotherBean = ((info_navigation)request.getSession().getAttribute(bsConstants.CONST_BEAN_$NAVIGATION)).find(bean).get_content();
}catch(Exception e){
}
if(anotherBean!=null){
if(name==null){
writeValue = anotherBean;
name=bean;
try{
value = util_format.makeFormatedString(formatOutput,formatLanguage,formatCountry,writeValue);
}catch(Exception e){
}
}
else{
try{
writeValue = util_reflect.prepareWriteValueForTag(anotherBean,method_prefix,name,null);
if(writeValue!=null) value = util_format.makeFormatedString(formatOutput,formatLanguage,formatCountry,writeValue);
}catch(Exception e){}
}
}
}
// }
if(asyncUpdate!=null && !asyncUpdate.equalsIgnoreCase("false")){
try{
asyncUpdateUrl=formAction.get_infoaction().getPath();
if(bsController.getAppInit().get_actioncall_separator()!=null && !bsController.getAppInit().get_actioncall_separator().equals("")){
if(!asyncUpdate.equalsIgnoreCase("true"))
asyncUpdateUrl+=bsController.getAppInit().get_actioncall_separator()+asyncUpdate+"?";
else
asyncUpdateUrl+=bsController.getAppInit().get_actioncall_separator()+"asyncupdate?";
}else asyncUpdateUrl+="?";
asyncUpdateUrl+="middleAction=undef&";
if(name!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+=prefixName+"='+this.value+'&target="+prefixName+"&";
else asyncUpdateUrl+=name+"='+this.value+'&target="+name+"&";
if(formatInput!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$format_"+prefixName+"="+formatInput+"&";
else asyncUpdateUrl+="$format_"+name+"="+formatInput+"&";
}
if(formatOutput!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$formatOutput_"+prefixName+"="+formatOutput+"&";
else asyncUpdateUrl+="$formatOutput_"+name+"="+formatOutput+"&";
}
if(formatLanguage!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$formatLanguage_"+prefixName+"="+formatLanguage+"&";
else asyncUpdateUrl+="$formatLanguage_"+name+"="+formatLanguage+"&";
}
if(formatCountry!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$formatCountry_"+prefixName+"="+formatCountry+"&";
else asyncUpdateUrl+="$formatCountry_"+name+"="+formatCountry+"&";
}
if(replaceOnBlank!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$replaceOnBlank_"+prefixName+"="+replaceOnBlank+"&";
else asyncUpdateUrl+="$replaceOnBlank_"+name+"="+replaceOnBlank+"&";
}
if(replaceOnErrorFormat!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$replaceOnErrorFormat_"+prefixName+"="+replaceOnErrorFormat+"&";
else asyncUpdateUrl+="$replaceOnErrorFormat_"+name+"="+replaceOnErrorFormat+"&";
}
}
}catch(Exception e){
}
}
StringBuffer results = new StringBuffer("<select ");
if(name!=null){
results.append(" name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append(prefixName);
else results.append(name);
results.append('"');
}
if(objId!=null){
results.append(" id=\"");
results.append(objId);
results.append('"');
}else{
if(name!=null){
results.append(" id=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append(prefixName);
else results.append(name);
results.append('"');
}
}
if (type != null) {
results.append(" type=\"");
results.append(type == null ? "text" : type);
results.append('"');
}
if (readonly != null) {
results.append(" readonly=\"");
results.append(readonly);
results.append('"');
}
if (size != null) {
results.append(" size=\"");
results.append(size);
results.append('"');
}
if (src != null) {
results.append(" src=\"");
results.append(src);
results.append('"');
}
if (tabindex != null) {
results.append(" tabindex=\"");
results.append(tabindex);
results.append('"');
}
if (usemap != null) {
results.append(" usemap=\"");
results.append(usemap);
results.append('"');
}
if (accesskey != null) {
results.append(" accesskey=\"");
results.append(accesskey);
results.append('"');
}
if (align != null) {
results.append(" align=\"");
results.append(align);
results.append('"');
}
if (alt != null) {
results.append(" alt=\"");
results.append(alt);
results.append('"');
}
if (border != null) {
results.append(" border=\"");
results.append(border);
results.append('"');
}
if (checked != null) {
results.append(" checked=\"");
results.append(checked);
results.append('"');
}
if (disabled != null) {
results.append(" disabled=\"");
results.append(disabled);
results.append('"');
}
if (width != null) {
results.append(" width=\"");
results.append(width);
results.append('"');
}
if (height != null) {
results.append(" height=\"");
results.append(height);
results.append('"');
}
if (ismap != null) {
results.append(" ismap=\"");
results.append(ismap);
results.append('"');
}
if (maxlength != null) {
results.append(" maxlength=\"");
results.append(maxlength);
results.append('"');
}
if (multiple != null) {
results.append(" multiple =\"");
results.append(multiple);
results.append('"');
}
if (autofocus != null) {
results.append(" autofocus=\"");
results.append(autofocus);
results.append('"');
}
if (form != null) {
results.append(" form=\"");
results.append(form);
results.append('"');
}
if (required != null) {
results.append(" required=\"");
results.append(required);
results.append('"');
}
if(value!=null)
if(formatOutput!=null) value=util_format.prepareContentString(formatOutput,value);
if(replaceOnBlank != null) value=util_format.replace(value,replaceOnBlank,"");
try{
results.append(" value=\"");
results.append(value);
results.append('"');
}catch(Exception e){}
if (styleClass != null) {
results.append(" class=\"");
results.append(styleClass);
results.append('"');
}
if (style != null) {
results.append(" style=\"");
results.append(style);
results.append('"');
}
if (accept != null) {
results.append(" accept=\"");
results.append(accept);
results.append('"');
}
if (lang != null) {
results.append(" lang=\"");
results.append(lang);
results.append('"');
}
if (title != null) {
results.append(" title=\"");
results.append(title);
results.append('"');
}
if (dir != null) {
results.append(" dir=\"");
results.append(dir);
results.append('"');
}
if (onclick != null) {
results.append(" onclick=\"");
results.append(onclick);
results.append('"');
}
if (ondblclick != null) {
results.append(" ondblclick=\"");
results.append(ondblclick);
results.append('"');
}
if (onhelp != null) {
results.append(" onhelp=\"");
results.append(onhelp);
results.append('"');
}
if (onkeydown != null) {
results.append(" onkeydown=\"");
results.append(onkeydown);
results.append('"');
}
if (onkeypress != null) {
results.append(" onkeypress=\"");
results.append(onkeypress);
results.append('"');
}
if (onkeyup != null) {
results.append(" onkeyup=\"");
results.append(onkeyup);
results.append('"');
}
if (onmousedown != null) {
results.append(" onmousedown=\"");
results.append(onmousedown);
results.append('"');
}
if (onmousemove != null) {
results.append(" onmousemove=\"");
results.append(onmousemove);
results.append('"');
}
if (onmouseout != null) {
results.append(" onmouseout=\"");
results.append(onmouseout);
results.append('"');
}
if (onmouseover != null) {
results.append(" onmouseover=\"");
results.append(onmouseover);
results.append('"');
}
if (onmouseup != null) {
results.append(" onmouseup=\"");
results.append(onmouseup);
results.append('"');
}
if (onblur != null) {
results.append(" onblur=\"");
results.append(onblur);
results.append('"');
}
if (onchange != null) {
results.append(" onchange=\"");
results.append("this.value=this[this.selectedIndex].value;");
if(asyncUpdateUrl!=null){
if(asyncUpdateJsFunction!=null)
results.append(asyncUpdateJsFunction+"('"+asyncUpdateUrl+"',this.name);");
else results.append("dhtmlLoadScript('"+asyncUpdateUrl+"');");
}
results.append(onchange);
results.append('"');
}else{
if(asyncUpdateUrl!=null){
results.append(" onchange=\"");
if(asyncUpdateJsFunction!=null)
results.append(asyncUpdateJsFunction+"('"+asyncUpdateUrl+"',this.name);");
else results.append("dhtmlLoadScript('"+asyncUpdateUrl+"');");
results.append('"');
}
}
if (onfocus != null) {
results.append(" onfocus=\"");
results.append(onfocus);
results.append('"');
}
if (onselect != null) {
results.append(" onselect=\"");
results.append(onselect);
results.append('"');
}
if (oncontextmenu != null) {
results.append(" oncontextmenu=\"");
results.append(oncontextmenu);
results.append('"');
}
if (onformchange != null) {
results.append(" onformchange=\"");
results.append(onformchange);
results.append('"');
}
if (onforminput != null) {
results.append(" onforminput=\"");
results.append(onforminput);
results.append('"');
}
if (oninput != null) {
results.append(" oninput=\"");
results.append(oninput);
results.append('"');
}
if (oninvalid != null) {
results.append(" oninvalid=\"");
results.append(oninvalid);
results.append('"');
}
if (ondrag != null) {
results.append(" ondrag=\"");
results.append(ondrag);
results.append('"');
}
if (ondragend != null) {
results.append(" ondragend=\"");
results.append(ondragend);
results.append('"');
}
if (ondragenter != null) {
results.append(" ondragenter=\"");
results.append(ondragenter);
results.append('"');
}
if (ondragleave != null) {
results.append(" ondragleave=\"");
results.append(ondragleave);
results.append('"');
}
if (ondragover != null) {
results.append(" ondragover=\"");
results.append(ondragover);
results.append('"');
}
if (ondragstart != null) {
results.append(" ondragstart=\"");
results.append(ondragstart);
results.append('"');
}
if (ondrop != null) {
results.append(" ondrop=\"");
results.append(ondrop);
results.append('"');
}
if (onmousewheel != null) {
results.append(" onmousewheel=\"");
results.append(onmousewheel);
results.append('"');
}
results.append(" $modelWire=\"");
results.append("select:"+prefixName);
results.append('"');
results.append('>');
if(name!=null && formatInput!=null){
results.append("<input name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append("$format_"+prefixName);
else results.append("$format_"+name);
results.append("\" type=\"hidden\" value=\"");
results.append(formatInput);
results.append("\">");
}
if(name!=null && replaceOnBlank!=null){
results.append("<input name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append("$replaceOnBlank_"+prefixName);
else results.append("$replaceOnBlank_"+name);
results.append("\" type=\"hidden\" value=\"");
results.append(replaceOnBlank);
results.append("\">");
}
if(name!=null && replaceOnErrorFormat!=null){
results.append("<input name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append("$replaceOnErrorFormat_"+prefixName);
else results.append("$replaceOnErrorFormat_"+name);
results.append("\" type=\"hidden\" value=\"");
results.append(replaceOnErrorFormat);
results.append("\">");
}
prefixName=null;
return results.toString();
}
public int doStartTag() throws JspException {
StringBuffer results = new StringBuffer();
results.append(this.createTagBody());
JspWriter writer = pageContext.getOut();
try {
writer.print(results.toString());
} catch (IOException e) {
throw new JspException(e.toString());
}
return EVAL_BODY_INCLUDE;
}
public void release() {
super.release();
multiple=null;
}
public String getMultiple() {
return multiple;
}
public void setMultiple(String multiple) {
this.multiple = multiple;
}
}
|
UTF-8
|
Java
| 17,632 |
java
|
tagSelect.java
|
Java
|
[
{
"context": "/**\r\n* Creation date: (07/04/2006)\r\n* @author: Svyatoslav Urbanovych svyatoslav.urbanovych@gmail.com\r\n*/\r\n\r\n/*********",
"end": 68,
"score": 0.9998967051506042,
"start": 47,
"tag": "NAME",
"value": "Svyatoslav Urbanovych"
},
{
"context": "te: (07/04/2006)\r\n* @author: Svyatoslav Urbanovych svyatoslav.urbanovych@gmail.com\r\n*/\r\n\r\n/*****************************************",
"end": 100,
"score": 0.9999179244041443,
"start": 69,
"tag": "EMAIL",
"value": "svyatoslav.urbanovych@gmail.com"
},
{
"context": "************************\r\n*\r\n*\tCopyright (C) 2005 Svyatoslav Urbanovych\r\n*\r\n* This program is free software; you can redi",
"end": 237,
"score": 0.9998950958251953,
"start": 216,
"tag": "NAME",
"value": "Svyatoslav Urbanovych"
}
] | null |
[] |
/**
* Creation date: (07/04/2006)
* @author: <NAME> <EMAIL>
*/
/********************************************************************************
*
* Copyright (C) 2005 <NAME>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*********************************************************************************/
package it.classhidra.core.controller.tags;
import it.classhidra.core.controller.action;
import it.classhidra.core.controller.bsConstants;
import it.classhidra.core.controller.bsController;
import it.classhidra.core.controller.i_action;
import it.classhidra.core.controller.i_bean;
import it.classhidra.core.controller.info_navigation;
import it.classhidra.core.tool.util.util_format;
import it.classhidra.core.tool.util.util_reflect;
import it.classhidra.core.tool.util.util_tag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.*;
import java.io.IOException;
import java.util.HashMap;
public class tagSelect extends tagInput{
private static final long serialVersionUID = -1L;
private String multiple=null;
public int doEndTag() throws JspException {
StringBuffer results = new StringBuffer("</select>");
JspWriter writer = pageContext.getOut();
try {
writer.print(results.toString());
} catch (IOException e) {
throw new JspException(e.toString());
}
value=null;
return EVAL_BODY_INCLUDE;
}
protected String createTagBody() {
HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
i_action formAction=null;
i_bean formBean=null;
if(bean!=null){
HashMap pool = (HashMap)request.getAttribute(bsController.CONST_BEAN_$INSTANCEACTIONPOOL);
if(pool!=null) formAction = (i_action)pool.get(bean);
}
if(formAction!=null) bean = null;
else formAction = (i_action)request.getAttribute(bsController.CONST_BEAN_$INSTANCEACTION);
if(formAction==null) formAction = new action();
if(bean==null) formBean = formAction.get_bean();
if(method_prefix==null) method_prefix="get";
Object writeValue=null;
String prefixName=null;
if(bean!=null && request.getAttribute(tagBean.CONST_HEAP_BEANS)!=null && ((HashMap)request.getAttribute(tagBean.CONST_HEAP_BEANS)).get(bean)!=null){
prefixName = ((HashMap)request.getAttribute(tagBean.CONST_HEAP_BEANS)).get(bean).toString();
}
if(prefixName==null)
prefixName=name;
else prefixName+="."+name;
String asyncUpdateUrl=null;
// if(value==null){
if(bean==null && name!=null){
writeValue = formBean.get(name);
try{
if(writeValue!=null) value = util_format.makeFormatedString(formatOutput,formatLanguage,formatCountry,writeValue);
}catch(Exception e){}
}else{
Object anotherBean = null;
if(name!=null){
if(bean.equals(bsConstants.CONST_TAG_REQUESTPARAMETER)) anotherBean = request.getParameter(name);
if(bean.equals(bsConstants.CONST_TAG_SYSTEMPROPERTY)) anotherBean = System.getProperty(name);
}
if(anotherBean==null) anotherBean = request.getAttribute(bean);
if(anotherBean==null) anotherBean = request.getSession().getAttribute(bean);
if(anotherBean==null) anotherBean = request.getSession().getServletContext().getAttribute(bean);
if(name!=null){
if(anotherBean==null) anotherBean = request.getAttribute(name);
if(anotherBean==null) anotherBean = request.getSession().getAttribute(name);
if(anotherBean==null) anotherBean = request.getSession().getServletContext().getAttribute(name);
}
if(anotherBean==null) anotherBean = util_tag.getBeanAsBSTag(bean,this);
try{
if(anotherBean==null) anotherBean = ((info_navigation)request.getSession().getAttribute(bsConstants.CONST_BEAN_$NAVIGATION)).find(bean).get_content();
}catch(Exception e){
}
if(anotherBean!=null){
if(name==null){
writeValue = anotherBean;
name=bean;
try{
value = util_format.makeFormatedString(formatOutput,formatLanguage,formatCountry,writeValue);
}catch(Exception e){
}
}
else{
try{
writeValue = util_reflect.prepareWriteValueForTag(anotherBean,method_prefix,name,null);
if(writeValue!=null) value = util_format.makeFormatedString(formatOutput,formatLanguage,formatCountry,writeValue);
}catch(Exception e){}
}
}
}
// }
if(asyncUpdate!=null && !asyncUpdate.equalsIgnoreCase("false")){
try{
asyncUpdateUrl=formAction.get_infoaction().getPath();
if(bsController.getAppInit().get_actioncall_separator()!=null && !bsController.getAppInit().get_actioncall_separator().equals("")){
if(!asyncUpdate.equalsIgnoreCase("true"))
asyncUpdateUrl+=bsController.getAppInit().get_actioncall_separator()+asyncUpdate+"?";
else
asyncUpdateUrl+=bsController.getAppInit().get_actioncall_separator()+"asyncupdate?";
}else asyncUpdateUrl+="?";
asyncUpdateUrl+="middleAction=undef&";
if(name!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+=prefixName+"='+this.value+'&target="+prefixName+"&";
else asyncUpdateUrl+=name+"='+this.value+'&target="+name+"&";
if(formatInput!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$format_"+prefixName+"="+formatInput+"&";
else asyncUpdateUrl+="$format_"+name+"="+formatInput+"&";
}
if(formatOutput!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$formatOutput_"+prefixName+"="+formatOutput+"&";
else asyncUpdateUrl+="$formatOutput_"+name+"="+formatOutput+"&";
}
if(formatLanguage!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$formatLanguage_"+prefixName+"="+formatLanguage+"&";
else asyncUpdateUrl+="$formatLanguage_"+name+"="+formatLanguage+"&";
}
if(formatCountry!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$formatCountry_"+prefixName+"="+formatCountry+"&";
else asyncUpdateUrl+="$formatCountry_"+name+"="+formatCountry+"&";
}
if(replaceOnBlank!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$replaceOnBlank_"+prefixName+"="+replaceOnBlank+"&";
else asyncUpdateUrl+="$replaceOnBlank_"+name+"="+replaceOnBlank+"&";
}
if(replaceOnErrorFormat!=null){
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
asyncUpdateUrl+="$replaceOnErrorFormat_"+prefixName+"="+replaceOnErrorFormat+"&";
else asyncUpdateUrl+="$replaceOnErrorFormat_"+name+"="+replaceOnErrorFormat+"&";
}
}
}catch(Exception e){
}
}
StringBuffer results = new StringBuffer("<select ");
if(name!=null){
results.append(" name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append(prefixName);
else results.append(name);
results.append('"');
}
if(objId!=null){
results.append(" id=\"");
results.append(objId);
results.append('"');
}else{
if(name!=null){
results.append(" id=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append(prefixName);
else results.append(name);
results.append('"');
}
}
if (type != null) {
results.append(" type=\"");
results.append(type == null ? "text" : type);
results.append('"');
}
if (readonly != null) {
results.append(" readonly=\"");
results.append(readonly);
results.append('"');
}
if (size != null) {
results.append(" size=\"");
results.append(size);
results.append('"');
}
if (src != null) {
results.append(" src=\"");
results.append(src);
results.append('"');
}
if (tabindex != null) {
results.append(" tabindex=\"");
results.append(tabindex);
results.append('"');
}
if (usemap != null) {
results.append(" usemap=\"");
results.append(usemap);
results.append('"');
}
if (accesskey != null) {
results.append(" accesskey=\"");
results.append(accesskey);
results.append('"');
}
if (align != null) {
results.append(" align=\"");
results.append(align);
results.append('"');
}
if (alt != null) {
results.append(" alt=\"");
results.append(alt);
results.append('"');
}
if (border != null) {
results.append(" border=\"");
results.append(border);
results.append('"');
}
if (checked != null) {
results.append(" checked=\"");
results.append(checked);
results.append('"');
}
if (disabled != null) {
results.append(" disabled=\"");
results.append(disabled);
results.append('"');
}
if (width != null) {
results.append(" width=\"");
results.append(width);
results.append('"');
}
if (height != null) {
results.append(" height=\"");
results.append(height);
results.append('"');
}
if (ismap != null) {
results.append(" ismap=\"");
results.append(ismap);
results.append('"');
}
if (maxlength != null) {
results.append(" maxlength=\"");
results.append(maxlength);
results.append('"');
}
if (multiple != null) {
results.append(" multiple =\"");
results.append(multiple);
results.append('"');
}
if (autofocus != null) {
results.append(" autofocus=\"");
results.append(autofocus);
results.append('"');
}
if (form != null) {
results.append(" form=\"");
results.append(form);
results.append('"');
}
if (required != null) {
results.append(" required=\"");
results.append(required);
results.append('"');
}
if(value!=null)
if(formatOutput!=null) value=util_format.prepareContentString(formatOutput,value);
if(replaceOnBlank != null) value=util_format.replace(value,replaceOnBlank,"");
try{
results.append(" value=\"");
results.append(value);
results.append('"');
}catch(Exception e){}
if (styleClass != null) {
results.append(" class=\"");
results.append(styleClass);
results.append('"');
}
if (style != null) {
results.append(" style=\"");
results.append(style);
results.append('"');
}
if (accept != null) {
results.append(" accept=\"");
results.append(accept);
results.append('"');
}
if (lang != null) {
results.append(" lang=\"");
results.append(lang);
results.append('"');
}
if (title != null) {
results.append(" title=\"");
results.append(title);
results.append('"');
}
if (dir != null) {
results.append(" dir=\"");
results.append(dir);
results.append('"');
}
if (onclick != null) {
results.append(" onclick=\"");
results.append(onclick);
results.append('"');
}
if (ondblclick != null) {
results.append(" ondblclick=\"");
results.append(ondblclick);
results.append('"');
}
if (onhelp != null) {
results.append(" onhelp=\"");
results.append(onhelp);
results.append('"');
}
if (onkeydown != null) {
results.append(" onkeydown=\"");
results.append(onkeydown);
results.append('"');
}
if (onkeypress != null) {
results.append(" onkeypress=\"");
results.append(onkeypress);
results.append('"');
}
if (onkeyup != null) {
results.append(" onkeyup=\"");
results.append(onkeyup);
results.append('"');
}
if (onmousedown != null) {
results.append(" onmousedown=\"");
results.append(onmousedown);
results.append('"');
}
if (onmousemove != null) {
results.append(" onmousemove=\"");
results.append(onmousemove);
results.append('"');
}
if (onmouseout != null) {
results.append(" onmouseout=\"");
results.append(onmouseout);
results.append('"');
}
if (onmouseover != null) {
results.append(" onmouseover=\"");
results.append(onmouseover);
results.append('"');
}
if (onmouseup != null) {
results.append(" onmouseup=\"");
results.append(onmouseup);
results.append('"');
}
if (onblur != null) {
results.append(" onblur=\"");
results.append(onblur);
results.append('"');
}
if (onchange != null) {
results.append(" onchange=\"");
results.append("this.value=this[this.selectedIndex].value;");
if(asyncUpdateUrl!=null){
if(asyncUpdateJsFunction!=null)
results.append(asyncUpdateJsFunction+"('"+asyncUpdateUrl+"',this.name);");
else results.append("dhtmlLoadScript('"+asyncUpdateUrl+"');");
}
results.append(onchange);
results.append('"');
}else{
if(asyncUpdateUrl!=null){
results.append(" onchange=\"");
if(asyncUpdateJsFunction!=null)
results.append(asyncUpdateJsFunction+"('"+asyncUpdateUrl+"',this.name);");
else results.append("dhtmlLoadScript('"+asyncUpdateUrl+"');");
results.append('"');
}
}
if (onfocus != null) {
results.append(" onfocus=\"");
results.append(onfocus);
results.append('"');
}
if (onselect != null) {
results.append(" onselect=\"");
results.append(onselect);
results.append('"');
}
if (oncontextmenu != null) {
results.append(" oncontextmenu=\"");
results.append(oncontextmenu);
results.append('"');
}
if (onformchange != null) {
results.append(" onformchange=\"");
results.append(onformchange);
results.append('"');
}
if (onforminput != null) {
results.append(" onforminput=\"");
results.append(onforminput);
results.append('"');
}
if (oninput != null) {
results.append(" oninput=\"");
results.append(oninput);
results.append('"');
}
if (oninvalid != null) {
results.append(" oninvalid=\"");
results.append(oninvalid);
results.append('"');
}
if (ondrag != null) {
results.append(" ondrag=\"");
results.append(ondrag);
results.append('"');
}
if (ondragend != null) {
results.append(" ondragend=\"");
results.append(ondragend);
results.append('"');
}
if (ondragenter != null) {
results.append(" ondragenter=\"");
results.append(ondragenter);
results.append('"');
}
if (ondragleave != null) {
results.append(" ondragleave=\"");
results.append(ondragleave);
results.append('"');
}
if (ondragover != null) {
results.append(" ondragover=\"");
results.append(ondragover);
results.append('"');
}
if (ondragstart != null) {
results.append(" ondragstart=\"");
results.append(ondragstart);
results.append('"');
}
if (ondrop != null) {
results.append(" ondrop=\"");
results.append(ondrop);
results.append('"');
}
if (onmousewheel != null) {
results.append(" onmousewheel=\"");
results.append(onmousewheel);
results.append('"');
}
results.append(" $modelWire=\"");
results.append("select:"+prefixName);
results.append('"');
results.append('>');
if(name!=null && formatInput!=null){
results.append("<input name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append("$format_"+prefixName);
else results.append("$format_"+name);
results.append("\" type=\"hidden\" value=\"");
results.append(formatInput);
results.append("\">");
}
if(name!=null && replaceOnBlank!=null){
results.append("<input name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append("$replaceOnBlank_"+prefixName);
else results.append("$replaceOnBlank_"+name);
results.append("\" type=\"hidden\" value=\"");
results.append(replaceOnBlank);
results.append("\">");
}
if(name!=null && replaceOnErrorFormat!=null){
results.append("<input name=\"");
if(solveBeanName!=null && solveBeanName.equalsIgnoreCase("true"))
results.append("$replaceOnErrorFormat_"+prefixName);
else results.append("$replaceOnErrorFormat_"+name);
results.append("\" type=\"hidden\" value=\"");
results.append(replaceOnErrorFormat);
results.append("\">");
}
prefixName=null;
return results.toString();
}
public int doStartTag() throws JspException {
StringBuffer results = new StringBuffer();
results.append(this.createTagBody());
JspWriter writer = pageContext.getOut();
try {
writer.print(results.toString());
} catch (IOException e) {
throw new JspException(e.toString());
}
return EVAL_BODY_INCLUDE;
}
public void release() {
super.release();
multiple=null;
}
public String getMultiple() {
return multiple;
}
public void setMultiple(String multiple) {
this.multiple = multiple;
}
}
| 17,578 | 0.623639 | 0.622221 | 566 | 29.148411 | 24.096153 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.365724 | false | false |
3
|
4cf96472c767c0e8fa81fa4cd0735e7e39b5135f
| 26,783,416,106,287 |
6228a6d6c1c40d398304a8e14a82da6158129776
|
/s2kestrel/src/org/seasar/framework/exception/ClassNotFoundRuntimeException.java
|
4ebd67ade9df1448eff4fa46dbdc4afb6faf986a
|
[] |
no_license
|
seasarorg/s2kestrel
|
https://github.com/seasarorg/s2kestrel
|
30103030a637e54b21aaadb5d54f7815c2bd5d4c
|
2822ae3eac760bf46d841be7440a7c9c6ddcd170
|
refs/heads/master
| 2021-01-23T19:46:08.407000 | 2006-01-17T15:47:26 | 2006-01-17T15:47:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.seasar.framework.exception;
/**
* @author higa
*
* ClassNotFoundExceptionをラップする実行時例外です。
*/
public class ClassNotFoundRuntimeException extends SRuntimeException {
/**
* @param messageCode
*/
public ClassNotFoundRuntimeException(ClassNotFoundException cause) {
super("ESSR0044", new Object[]{cause}, cause);
}
}
|
SHIFT_JIS
|
Java
| 383 |
java
|
ClassNotFoundRuntimeException.java
|
Java
|
[
{
"context": "g.seasar.framework.exception;\r\n\r\n\r\n/**\r\n * @author higa\r\n *\r\n * ClassNotFoundExceptionをラップする実行時例外です。\r\n */",
"end": 65,
"score": 0.9995821714401245,
"start": 61,
"tag": "USERNAME",
"value": "higa"
}
] | null |
[] |
package org.seasar.framework.exception;
/**
* @author higa
*
* ClassNotFoundExceptionをラップする実行時例外です。
*/
public class ClassNotFoundRuntimeException extends SRuntimeException {
/**
* @param messageCode
*/
public ClassNotFoundRuntimeException(ClassNotFoundException cause) {
super("ESSR0044", new Object[]{cause}, cause);
}
}
| 383 | 0.712676 | 0.701408 | 17 | 18.882353 | 23.903931 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false |
3
|
e00ff8db85958b11d62c3b76709f9f23121e567f
| 6,098,853,616,352 |
1d562744018f1619dc87fde68d841a536121e73b
|
/checkers/src/checkers/oigj/quals/Dominator.java
|
d6069adf5bab4c707183d99abf4c82f8a5d3b327
|
[] |
no_license
|
saf/Funcheck
|
https://github.com/saf/Funcheck
|
da41d42cdd29a5197fc1a3bdfd3fdcf36cc96850
|
ca5c2fc40d39cd8e6c7b2bd468a19b03a0ab86f6
|
refs/heads/master
| 2020-04-02T13:53:14.711000 | 2011-08-16T20:11:31 | 2011-08-16T20:11:31 | 942,381 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package checkers.oigj.quals;
import java.lang.annotation.*;
import checkers.quals.SubtypeOf;
import checkers.quals.TypeQualifier;
@Documented
@Retention(RetentionPolicy.RUNTIME)
//@Target( { FIELD, LOCAL_VARIABLE, METHOD, PARAMETER, TYPE })
@TypeQualifier
@SubtypeOf({ World.class })
public @interface Dominator {}
|
UTF-8
|
Java
| 318 |
java
|
Dominator.java
|
Java
|
[] | null |
[] |
package checkers.oigj.quals;
import java.lang.annotation.*;
import checkers.quals.SubtypeOf;
import checkers.quals.TypeQualifier;
@Documented
@Retention(RetentionPolicy.RUNTIME)
//@Target( { FIELD, LOCAL_VARIABLE, METHOD, PARAMETER, TYPE })
@TypeQualifier
@SubtypeOf({ World.class })
public @interface Dominator {}
| 318 | 0.779874 | 0.779874 | 13 | 23.461538 | 17.238667 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false |
3
|
f0bc3adb39ae2991e60e001ce87a1b020ca8cc6d
| 27,247,272,577,552 |
a6485f1114ea5326d03dd1d26345d6969e2f601e
|
/core/src/main/java/org/sonatype/goodies/dropwizard/logging/LoggerNameFilter.java
|
0ac0229538e4e05bb8ff703f6c740ffbf244b338
|
[
"Apache-2.0"
] |
permissive
|
sonatype/dropwizard-support
|
https://github.com/sonatype/dropwizard-support
|
fc67e6f3a5c753610a5f490023ae02d75fb5840c
|
629ff76d4e9d1d8a7f37f2f4e248e5b314de9527
|
refs/heads/main
| 2023-09-03T17:42:28.172000 | 2021-12-21T19:23:08 | 2021-12-21T19:23:08 | 137,290,527 | 4 | 7 |
Apache-2.0
| false | 2023-01-09T07:01:47 | 2018-06-14T01:30:02 | 2021-12-21T19:23:12 | 2023-01-09T07:01:42 | 6,469 | 4 | 6 | 18 |
Java
| false | false |
/*
* Copyright (c) 2018-present Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.sonatype.goodies.dropwizard.logging;
import java.util.Set;
import javax.validation.constraints.NotEmpty;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.filter.FilterFactory;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Filter events by logger-name.
*
* @since ???
*/
public class LoggerNameFilter
extends Filter<ILoggingEvent>
{
private final String[] include;
public LoggerNameFilter(final Factory config) {
checkNotNull(config);
// convert set to array for optimal iteration
this.include = config.getInclude().toArray(new String[0]);
}
@Override
public FilterReply decide(final ILoggingEvent event) {
String loggerName = event.getLoggerName();
for (String prefix : include) {
if (loggerName.startsWith(prefix)) {
return FilterReply.ACCEPT;
}
}
return FilterReply.DENY;
}
//
// Factory
//
@JsonTypeName("logger-name")
public static class Factory
implements FilterFactory<ILoggingEvent>
{
@NotEmpty
@JsonProperty
private Set<String> include;
public Set<String> getInclude() {
return include;
}
public void setInclude(final Set<String> include) {
this.include = checkNotNull(include);
}
@Override
public Filter<ILoggingEvent> build() {
return new LoggerNameFilter(this);
}
}
}
|
UTF-8
|
Java
| 2,296 |
java
|
LoggerNameFilter.java
|
Java
|
[] | null |
[] |
/*
* Copyright (c) 2018-present Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.sonatype.goodies.dropwizard.logging;
import java.util.Set;
import javax.validation.constraints.NotEmpty;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.filter.FilterFactory;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Filter events by logger-name.
*
* @since ???
*/
public class LoggerNameFilter
extends Filter<ILoggingEvent>
{
private final String[] include;
public LoggerNameFilter(final Factory config) {
checkNotNull(config);
// convert set to array for optimal iteration
this.include = config.getInclude().toArray(new String[0]);
}
@Override
public FilterReply decide(final ILoggingEvent event) {
String loggerName = event.getLoggerName();
for (String prefix : include) {
if (loggerName.startsWith(prefix)) {
return FilterReply.ACCEPT;
}
}
return FilterReply.DENY;
}
//
// Factory
//
@JsonTypeName("logger-name")
public static class Factory
implements FilterFactory<ILoggingEvent>
{
@NotEmpty
@JsonProperty
private Set<String> include;
public Set<String> getInclude() {
return include;
}
public void setInclude(final Set<String> include) {
this.include = checkNotNull(include);
}
@Override
public Filter<ILoggingEvent> build() {
return new LoggerNameFilter(this);
}
}
}
| 2,296 | 0.727352 | 0.719948 | 80 | 27.700001 | 27.614037 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false |
3
|
772484a79f5898cbc677c90f6bce623b5fb61b43
| 27,152,783,289,725 |
01a80902e90498e0834452d15f71868fa7d92323
|
/src/Node.java
|
10eba96dcf614f8aff824db555fb076c50001089
|
[] |
no_license
|
RamazanAriskaliev/DecisionTreeID3
|
https://github.com/RamazanAriskaliev/DecisionTreeID3
|
7e615e6b264d59d7be29c5517c105d700aae804c
|
7edcc2f5c55e20420fd6c711ec321eaf2a866ef2
|
refs/heads/master
| 2021-01-23T01:51:40.888000 | 2017-03-25T19:18:22 | 2017-03-25T19:18:22 | 85,941,162 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.Serializable;
import java.util.Map;
/**
* Created by Ramazan on 20.03.2017.
*/
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Node{
@XmlElement
public Node parent;
@XmlElement
public Map<String, Node> children;
@XmlElement
public LearningSet examples;
public double entropy;
public boolean isUsed;
private Atribute atribute;
public Node() {
setExamples(null);
setEntropy(0.0);
setParent(null);
setChildren(null);
setUsed(false);
atribute = new Atribute("","");
}
public Node(LearningSet learningSet) {
this.examples = learningSet;
setEntropy(0.0);
setParent(null);
setChildren(null);
setUsed(false);
atribute = new Atribute("","");
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public Map<String, Node> getChildren() {
return children;
}
public void setChildren(Map<String, Node> children) {
this.children = children;
}
public LearningSet getExamples() {
return examples;
}
public void setExamples(LearningSet examples) {
this.examples = examples;
}
public double getEntropy() {
return entropy;
}
public void setEntropy(double entropy) {
this.entropy = entropy;
}
public boolean isUsed() {
return isUsed;
}
public void setUsed(boolean used) {
isUsed = used;
}
public Atribute getAtribute() {
return atribute;
}
public void setAtribute(Atribute atribute) {
this.atribute = atribute;
}
public void print(int level, String edgeName) {
for (int i = 1; i < level; i++) {
System.out.print("\t");
}
System.out.println((edgeName.equals("")?"":edgeName+":")+atribute.getName()+ (atribute.getValue()==null? "" :(":"+ atribute.getValue())));
if(children != null){
for (String edge : children.keySet()) {
children.get(edge).print(level + 1, edge);
}
}
}
}
|
UTF-8
|
Java
| 2,349 |
java
|
Node.java
|
Java
|
[
{
"context": "alizable;\nimport java.util.Map;\n\n/**\n * Created by Ramazan on 20.03.2017.\n */\nimport javax.xml.bind.annotati",
"end": 77,
"score": 0.9994794726371765,
"start": 70,
"tag": "NAME",
"value": "Ramazan"
}
] | null |
[] |
import java.io.Serializable;
import java.util.Map;
/**
* Created by Ramazan on 20.03.2017.
*/
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Node{
@XmlElement
public Node parent;
@XmlElement
public Map<String, Node> children;
@XmlElement
public LearningSet examples;
public double entropy;
public boolean isUsed;
private Atribute atribute;
public Node() {
setExamples(null);
setEntropy(0.0);
setParent(null);
setChildren(null);
setUsed(false);
atribute = new Atribute("","");
}
public Node(LearningSet learningSet) {
this.examples = learningSet;
setEntropy(0.0);
setParent(null);
setChildren(null);
setUsed(false);
atribute = new Atribute("","");
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public Map<String, Node> getChildren() {
return children;
}
public void setChildren(Map<String, Node> children) {
this.children = children;
}
public LearningSet getExamples() {
return examples;
}
public void setExamples(LearningSet examples) {
this.examples = examples;
}
public double getEntropy() {
return entropy;
}
public void setEntropy(double entropy) {
this.entropy = entropy;
}
public boolean isUsed() {
return isUsed;
}
public void setUsed(boolean used) {
isUsed = used;
}
public Atribute getAtribute() {
return atribute;
}
public void setAtribute(Atribute atribute) {
this.atribute = atribute;
}
public void print(int level, String edgeName) {
for (int i = 1; i < level; i++) {
System.out.print("\t");
}
System.out.println((edgeName.equals("")?"":edgeName+":")+atribute.getName()+ (atribute.getValue()==null? "" :(":"+ atribute.getValue())));
if(children != null){
for (String edge : children.keySet()) {
children.get(edge).print(level + 1, edge);
}
}
}
}
| 2,349 | 0.593444 | 0.587484 | 107 | 20.953272 | 20.63496 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.448598 | false | false |
3
|
9ccfeda28e6df4a83512ca872d0785b0da13d922
| 3,350,074,550,379 |
816111fcb1e6ceceada7d9dba91aaeb320c17bf3
|
/src/main/java/com/rogo/inv/iadprojf1/entity/Piloting.java
|
6aa98d357ba7c9ed31472e8e73acffb4b77c0984
|
[] |
no_license
|
quest-prophets/iad_proj_f1
|
https://github.com/quest-prophets/iad_proj_f1
|
efa8dfd2604265007784f1cb578734fe0b5ae6e1
|
54d418e958f37fbdc1fd390943cef19244ba0df9
|
refs/heads/master
| 2020-04-16T07:14:54.199000 | 2019-03-17T18:15:44 | 2019-03-17T18:15:44 | 165,378,989 | 0 | 0 | null | false | 2019-01-26T13:46:21 | 2019-01-12T11:16:45 | 2019-01-26T11:29:11 | 2019-01-26T13:46:21 | 811 | 0 | 0 | 0 |
Java
| false | null |
package com.rogo.inv.iadprojf1.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.base.Objects;
import com.google.gson.Gson;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(
name = "piloting",
uniqueConstraints = @UniqueConstraint(columnNames = {"car_id", "racer_id"})
)
@Data @NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Piloting {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
//@OneToOne(mappedBy = "race_result", fetch = FetchType.LAZY)
private int id;
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "car_id")
@JsonBackReference
private Car car;
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "racer_id")
@JsonBackReference
private User racer;
/* ================================
constructors
================================ */
public Piloting(@NotNull Car car, @NotNull User racer) {
this.car = car;
this.racer = racer;
}
}
|
UTF-8
|
Java
| 1,281 |
java
|
Piloting.java
|
Java
|
[] | null |
[] |
package com.rogo.inv.iadprojf1.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.base.Objects;
import com.google.gson.Gson;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(
name = "piloting",
uniqueConstraints = @UniqueConstraint(columnNames = {"car_id", "racer_id"})
)
@Data @NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Piloting {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
//@OneToOne(mappedBy = "race_result", fetch = FetchType.LAZY)
private int id;
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "car_id")
@JsonBackReference
private Car car;
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "racer_id")
@JsonBackReference
private User racer;
/* ================================
constructors
================================ */
public Piloting(@NotNull Car car, @NotNull User racer) {
this.car = car;
this.racer = racer;
}
}
| 1,281 | 0.669789 | 0.669009 | 46 | 26.847826 | 20.19467 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false |
3
|
14a3efc261ece6643657638e8ae8f9f560297017
| 27,539,330,353,958 |
8abfa9b335c0e4198a899f5f80f46fd7c38265a7
|
/jsedemo/src/com/neuedu/solar/demo/MyFrame03.java
|
32154a2bb41c4df1e4b5317c0ae03603460123f8
|
[] |
no_license
|
ldamei/javademo
|
https://github.com/ldamei/javademo
|
6b704400b6a93e1df1aaf25bebafeb81c401c3c8
|
6492460bef15449630c7a458fe1f2002b3f3612d
|
refs/heads/master
| 2020-09-08T16:44:14.638000 | 2019-12-06T06:07:52 | 2019-12-06T06:07:52 | 221,187,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.neuedu.solar.demo;
import com.neuedu.solar.common.CommonFrame;
import com.neuedu.solar.common.FrameUtil;
import com.neuedu.solar.constant.Constant;
import java.awt.*;
/**
* @author ldamei
* @date 2019/12/4 15:24
*/
public class MyFrame03 extends CommonFrame {
int longAxis = 400; // 半长轴
int shortAxis = 200; // 半短轴
double theta = 0.0; // 参数theta
int x; // x坐标
int y; // y坐标
double speed = 0.1; // 线速度斜率的改变量
static Image img = FrameUtil.getImage("03.Earth.png");
public void paint(Graphics g){
// 椭圆轨迹
// x = a * cos(theta)
// y = b * sin(theta)
g.drawImage(img,x,y,null);
x = Constant.FRAME_WIDTH / 2 + (int)(longAxis * Math.cos(theta));
y = Constant.FRAME_HEIGHT / 2 + (int)(shortAxis * Math.sin(theta));
theta += speed;
}
public static void main(String[] args) {
new MyFrame03().loadFrame("按照椭圆轨迹运动");
}
}
|
UTF-8
|
Java
| 1,009 |
java
|
MyFrame03.java
|
Java
|
[
{
"context": "tant.Constant;\n\nimport java.awt.*;\n\n/**\n * @author ldamei\n * @date 2019/12/4 15:24\n */\npublic class MyFrame",
"end": 203,
"score": 0.9996902346611023,
"start": 197,
"tag": "USERNAME",
"value": "ldamei"
}
] | null |
[] |
package com.neuedu.solar.demo;
import com.neuedu.solar.common.CommonFrame;
import com.neuedu.solar.common.FrameUtil;
import com.neuedu.solar.constant.Constant;
import java.awt.*;
/**
* @author ldamei
* @date 2019/12/4 15:24
*/
public class MyFrame03 extends CommonFrame {
int longAxis = 400; // 半长轴
int shortAxis = 200; // 半短轴
double theta = 0.0; // 参数theta
int x; // x坐标
int y; // y坐标
double speed = 0.1; // 线速度斜率的改变量
static Image img = FrameUtil.getImage("03.Earth.png");
public void paint(Graphics g){
// 椭圆轨迹
// x = a * cos(theta)
// y = b * sin(theta)
g.drawImage(img,x,y,null);
x = Constant.FRAME_WIDTH / 2 + (int)(longAxis * Math.cos(theta));
y = Constant.FRAME_HEIGHT / 2 + (int)(shortAxis * Math.sin(theta));
theta += speed;
}
public static void main(String[] args) {
new MyFrame03().loadFrame("按照椭圆轨迹运动");
}
}
| 1,009 | 0.601273 | 0.57052 | 36 | 25.194445 | 20.33172 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
3
|
4e60b77e40e535a2308d328c11c97334242e5e96
| 19,224,273,665,437 |
2aa185cd867777e7880ac19f7963c74782b0ecb5
|
/BookShop/src/main/java/entity/Order.java
|
137bbe4d228db6a5f6bb2ad65de291f6746af64b
|
[] |
no_license
|
jonasa64/javabookshop
|
https://github.com/jonasa64/javabookshop
|
9506d80a1869e504f04faf713540bb0188ab055e
|
299dc65922135a9ea87442ddb63f5c2df7461c21
|
refs/heads/master
| 2022-07-07T02:58:47.618000 | 2019-06-28T12:13:23 | 2019-06-28T12:13:23 | 194,268,116 | 0 | 0 | null | false | 2022-06-21T01:22:15 | 2019-06-28T12:11:30 | 2019-06-28T12:13:52 | 2022-06-21T01:22:14 | 3,628 | 0 | 0 | 1 |
Java
| false | false |
/*
* 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 entity;
import java.util.Date;
/**
*
* @author Jonas
*/
public class Order {
private int id;
private int userId;
private int bookId;
private int totalPrice;
private Date orderDate;
private int quatiay;
public Order(int id, int userId, int bookId, int totalPrice, Date orderDate, int quatiay) {
this.id = id;
this.userId = userId;
this.bookId = bookId;
this.totalPrice = totalPrice;
this.orderDate = orderDate;
this.quatiay = quatiay;
}
public Order(int userId, int bookId, int totalPrice, int quatiay) {
this.userId = userId;
this.bookId = bookId;
this.totalPrice = totalPrice;
this.quatiay = quatiay;
}
public int getId() {
return id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public int getQuatiay() {
return quatiay;
}
public void setQuatiay(int quatiay) {
this.quatiay = quatiay;
}
@Override
public String toString() {
return "Order{" + "id=" + id + ", userId=" + userId + ", bookId=" + bookId + ", totalPrice=" + totalPrice + ", orderDate=" + orderDate + ", quatiay=" + quatiay + '}';
}
}
|
UTF-8
|
Java
| 1,978 |
java
|
Order.java
|
Java
|
[
{
"context": "entity;\n\nimport java.util.Date;\n\n/**\n *\n * @author Jonas\n */\npublic class Order {\n private int id;\n ",
"end": 249,
"score": 0.999541163444519,
"start": 244,
"tag": "NAME",
"value": "Jonas"
}
] | 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 entity;
import java.util.Date;
/**
*
* @author Jonas
*/
public class Order {
private int id;
private int userId;
private int bookId;
private int totalPrice;
private Date orderDate;
private int quatiay;
public Order(int id, int userId, int bookId, int totalPrice, Date orderDate, int quatiay) {
this.id = id;
this.userId = userId;
this.bookId = bookId;
this.totalPrice = totalPrice;
this.orderDate = orderDate;
this.quatiay = quatiay;
}
public Order(int userId, int bookId, int totalPrice, int quatiay) {
this.userId = userId;
this.bookId = bookId;
this.totalPrice = totalPrice;
this.quatiay = quatiay;
}
public int getId() {
return id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public int getQuatiay() {
return quatiay;
}
public void setQuatiay(int quatiay) {
this.quatiay = quatiay;
}
@Override
public String toString() {
return "Order{" + "id=" + id + ", userId=" + userId + ", bookId=" + bookId + ", totalPrice=" + totalPrice + ", orderDate=" + orderDate + ", quatiay=" + quatiay + '}';
}
}
| 1,978 | 0.584934 | 0.584934 | 100 | 18.780001 | 24.236988 | 174 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false |
3
|
7bdb4553fa962571f9a75db2aa883cbb1bd944f1
| 2,439,541,478,008 |
9847955e662b74c9b62b528f218af274db7db732
|
/quest/src/altaqias/ragatanga/capiao/utils/FormatUtil.java
|
7fde08f5bf8f9803c5fa136fc8171ca559e9e64b
|
[] |
no_license
|
jonathaslacerda/altaqias-capiao
|
https://github.com/jonathaslacerda/altaqias-capiao
|
dbe2f37320b1333286a210b31e3a9320cc80d0b4
|
9420ef868e36c78f55030fa6bc6f66184dba988c
|
refs/heads/master
| 2021-01-19T17:16:42.741000 | 2017-02-19T12:42:48 | 2017-02-19T12:42:48 | 82,293,084 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package altaqias.ragatanga.capiao.utils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.text.MaskFormatter;
import org.apache.commons.lang3.StringUtils;
public abstract class FormatUtil {
private static final String MASK_CPF = "###.###.###-##";
private static final String MASK_CEP = "#####-###";
private static final String MASK_CNPJ = "##.###.###/####-##";
private static final String MASK_FONE = "(##) ####-####";
private static final String MASK_DINHEIRO = "#,##0.00";
private static final String MASK_DECIMAL = "#,##0.00";
private static final String MASK_DECIMAL_3 = "#,##0.000";
private static final String MASK_DINHEIRO_ASTERISCOS = "**.***.***.***,**";
public static final String MASK_DATE = "dd/MM/yyyy";
public static final String MASK_TIMESTAMP = "dd/MM/yyyy HH:mm:ss";
public static final String MASK_DATE_DB = "yyyy-MM-dd";
public static final String MASK_TIMESTAMP_DB = "yyyy-MM-dd HH:mm:ss";
public static String normalizar(String texto){
texto = Normalizer.normalize(texto, Normalizer.Form.NFD);
texto = texto.replaceAll("[^\\p{ASCII}]", "");
texto = texto.replaceAll("\\W", "");
texto = texto.replaceAll("[_]", "");
return texto;
}
public static String normalizarDecimal(String texto){
texto = Normalizer.normalize(texto, Normalizer.Form.NFD);
texto = texto.replaceAll("[^0123456789,]", "");
texto = texto.replaceAll(",",".");
return texto;
}
public static String formatarDocumento(String documento){
String docNormalizado = normalizar(documento);
if(docNormalizado.length() > 11){
return formatarCNPJ(docNormalizado);
}
return formatarCPF(docNormalizado);
}
public static String formatarDocumentoComLabel(String documento){
String docNormalizado = normalizar(documento);
if(docNormalizado.length() > 11){
return "CNPJ: " + formatarCNPJ(docNormalizado);
}
return "CPF: " + formatarCPF(docNormalizado);
}
private static String formatarCNPJ(String cnpj){
return formatar(MASK_CNPJ, cnpj);
}
private static String formatarCPF(String cpf){
return formatar(MASK_CPF, cpf);
}
public static String formatarCep(String cep){
String cepNormalizado = normalizar(cep);
return formatar(MASK_CEP, cepNormalizado);
}
public static String formatarTelefone(String fone){
String foneNormalizado = normalizar(fone);
return formatar(MASK_FONE, foneNormalizado);
}
public static String formatarDinheiro(Double dinheiro){
DecimalFormat d = new DecimalFormat(MASK_DINHEIRO);
return d.format(dinheiro);
}
public static String formatarDinheiro(String dinheiro){
double valor = new Double(dinheiro);
DecimalFormat d = new DecimalFormat(MASK_DINHEIRO);
return d.format(valor);
}
public static String formatarDinheiroAsteriscos(String dinheiro) {
String valorFormatado = formatarDinheiro(dinheiro);
return StringUtils.leftPad(valorFormatado, MASK_DINHEIRO_ASTERISCOS.length(), MASK_DINHEIRO_ASTERISCOS);
}
public static String formatarDinheiroAsteriscos(Double dinheiro) {
String valorFormatado = formatarDinheiro(dinheiro);
return StringUtils.leftPad(valorFormatado, MASK_DINHEIRO_ASTERISCOS.length(), MASK_DINHEIRO_ASTERISCOS);
}
public static String formatarBigDecimal(BigDecimal bigDecimal){
DecimalFormat formatter = new DecimalFormat(MASK_DECIMAL);
return formatter.format(bigDecimal);
}
public static String formatarBigDecimal(BigDecimal bigDecimal, boolean tresCasas){
DecimalFormat formatter = new DecimalFormat(tresCasas?MASK_DECIMAL_3:MASK_DECIMAL);
return formatter.format(bigDecimal);
}
private static String formatar(String mascara, String texto){
MaskFormatter mask;
try {
mask = new MaskFormatter(mascara);
mask.setValueContainsLiteralCharacters(false);
return mask.valueToString(texto);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatarData(Date data, String mask){
return new SimpleDateFormat(mask).format(data);
}
public static String formatarData(Date data){
return new SimpleDateFormat(MASK_DATE).format(data);
}
public static String formatarDataExtenso(Date data) {
SimpleDateFormat dfmt = new SimpleDateFormat("EEEE, d 'de' MMMM 'de' yyyy");
return dfmt.format(data);
}
public static String formataCodigoCliente(String codigo){
return StringUtils.leftPad(codigo, 6, '0');
}
public static String formataCodigoApresentante(String codigo){
return StringUtils.leftPad(codigo, 6, '0');
}
}
|
UTF-8
|
Java
| 4,749 |
java
|
FormatUtil.java
|
Java
|
[] | null |
[] |
package altaqias.ragatanga.capiao.utils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.text.MaskFormatter;
import org.apache.commons.lang3.StringUtils;
public abstract class FormatUtil {
private static final String MASK_CPF = "###.###.###-##";
private static final String MASK_CEP = "#####-###";
private static final String MASK_CNPJ = "##.###.###/####-##";
private static final String MASK_FONE = "(##) ####-####";
private static final String MASK_DINHEIRO = "#,##0.00";
private static final String MASK_DECIMAL = "#,##0.00";
private static final String MASK_DECIMAL_3 = "#,##0.000";
private static final String MASK_DINHEIRO_ASTERISCOS = "**.***.***.***,**";
public static final String MASK_DATE = "dd/MM/yyyy";
public static final String MASK_TIMESTAMP = "dd/MM/yyyy HH:mm:ss";
public static final String MASK_DATE_DB = "yyyy-MM-dd";
public static final String MASK_TIMESTAMP_DB = "yyyy-MM-dd HH:mm:ss";
public static String normalizar(String texto){
texto = Normalizer.normalize(texto, Normalizer.Form.NFD);
texto = texto.replaceAll("[^\\p{ASCII}]", "");
texto = texto.replaceAll("\\W", "");
texto = texto.replaceAll("[_]", "");
return texto;
}
public static String normalizarDecimal(String texto){
texto = Normalizer.normalize(texto, Normalizer.Form.NFD);
texto = texto.replaceAll("[^0123456789,]", "");
texto = texto.replaceAll(",",".");
return texto;
}
public static String formatarDocumento(String documento){
String docNormalizado = normalizar(documento);
if(docNormalizado.length() > 11){
return formatarCNPJ(docNormalizado);
}
return formatarCPF(docNormalizado);
}
public static String formatarDocumentoComLabel(String documento){
String docNormalizado = normalizar(documento);
if(docNormalizado.length() > 11){
return "CNPJ: " + formatarCNPJ(docNormalizado);
}
return "CPF: " + formatarCPF(docNormalizado);
}
private static String formatarCNPJ(String cnpj){
return formatar(MASK_CNPJ, cnpj);
}
private static String formatarCPF(String cpf){
return formatar(MASK_CPF, cpf);
}
public static String formatarCep(String cep){
String cepNormalizado = normalizar(cep);
return formatar(MASK_CEP, cepNormalizado);
}
public static String formatarTelefone(String fone){
String foneNormalizado = normalizar(fone);
return formatar(MASK_FONE, foneNormalizado);
}
public static String formatarDinheiro(Double dinheiro){
DecimalFormat d = new DecimalFormat(MASK_DINHEIRO);
return d.format(dinheiro);
}
public static String formatarDinheiro(String dinheiro){
double valor = new Double(dinheiro);
DecimalFormat d = new DecimalFormat(MASK_DINHEIRO);
return d.format(valor);
}
public static String formatarDinheiroAsteriscos(String dinheiro) {
String valorFormatado = formatarDinheiro(dinheiro);
return StringUtils.leftPad(valorFormatado, MASK_DINHEIRO_ASTERISCOS.length(), MASK_DINHEIRO_ASTERISCOS);
}
public static String formatarDinheiroAsteriscos(Double dinheiro) {
String valorFormatado = formatarDinheiro(dinheiro);
return StringUtils.leftPad(valorFormatado, MASK_DINHEIRO_ASTERISCOS.length(), MASK_DINHEIRO_ASTERISCOS);
}
public static String formatarBigDecimal(BigDecimal bigDecimal){
DecimalFormat formatter = new DecimalFormat(MASK_DECIMAL);
return formatter.format(bigDecimal);
}
public static String formatarBigDecimal(BigDecimal bigDecimal, boolean tresCasas){
DecimalFormat formatter = new DecimalFormat(tresCasas?MASK_DECIMAL_3:MASK_DECIMAL);
return formatter.format(bigDecimal);
}
private static String formatar(String mascara, String texto){
MaskFormatter mask;
try {
mask = new MaskFormatter(mascara);
mask.setValueContainsLiteralCharacters(false);
return mask.valueToString(texto);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatarData(Date data, String mask){
return new SimpleDateFormat(mask).format(data);
}
public static String formatarData(Date data){
return new SimpleDateFormat(MASK_DATE).format(data);
}
public static String formatarDataExtenso(Date data) {
SimpleDateFormat dfmt = new SimpleDateFormat("EEEE, d 'de' MMMM 'de' yyyy");
return dfmt.format(data);
}
public static String formataCodigoCliente(String codigo){
return StringUtils.leftPad(codigo, 6, '0');
}
public static String formataCodigoApresentante(String codigo){
return StringUtils.leftPad(codigo, 6, '0');
}
}
| 4,749 | 0.71573 | 0.709202 | 144 | 30.979166 | 26.427172 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.902778 | false | false |
3
|
c03735d7daffd9cfbcbcbfe49337545b5aa81270
| 27,092,653,768,013 |
20ecfcaea334a6371edd0c24733b087000ea0106
|
/src/main/java/com/glaf/base/modules/sys/service/SysApplicationService.java
|
1eb0fffdadc107f2889d37a4207f798c33529a44
|
[
"Apache-2.0"
] |
permissive
|
gitee2008/glaf
|
https://github.com/gitee2008/glaf
|
a0d312390dac3e44426dc15e23afb9c34bdac0d9
|
5fa5a7d48f7fc8d2409ee38c2ee070563e8d8dbd
|
refs/heads/master
| 2022-12-21T11:11:13.229000 | 2020-10-20T13:37:16 | 2020-10-20T13:37:16 | 97,379,234 | 2 | 4 |
Apache-2.0
| false | 2022-12-16T15:51:41 | 2017-07-16T11:37:04 | 2020-10-20T13:38:55 | 2022-12-16T15:51:37 | 655,053 | 1 | 4 | 31 |
JavaScript
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.base.modules.sys.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.glaf.base.modules.sys.model.SysApplication;
import com.glaf.base.modules.sys.query.SysApplicationQuery;
import com.glaf.core.util.PageResult;
@Transactional(readOnly = true)
public interface SysApplicationService {
@Transactional
void batchCreate(List<SysApplication> rows);
/**
* 保存
*
* @param bean
* SysApplication
* @return boolean
*/
@Transactional
boolean create(SysApplication bean);
/**
* 删除
*
* @param id
* int
* @return boolean
*/
@Transactional
boolean delete(long id);
/**
* 删除
*
* @param bean
* SysApplication
* @return boolean
*/
@Transactional
boolean delete(SysApplication bean);
/**
* 批量删除
*
* @param id
* @return
*/
@Transactional
boolean deleteAll(long[] id);
/**
* 按编码查找对象
*
* @param code
* String
* @return SysApplication
*/
SysApplication findByCode(String code);
/**
* 获取对象
*
* @param id
* @return
*/
SysApplication findById(long id);
/**
* 按名称查找对象
*
* @param name
* String
* @return SysApplication
*/
SysApplication findByName(String name);
List<SysApplication> getAllSysApplications();
PageResult getApplicationList(int pageNo, int pageSize, SysApplicationQuery query);
/**
* 获取分页列表
*
* @param parentId
* int
* @param pageNo
* int
* @param pageSize
* int
* @return
*/
PageResult getApplicationList(long parentId, int pageNo, int pageSize);
/**
* 获取某个模块的全部子节点及子孙节点
*
* @param parentId
* long
* @return List
*/
List<SysApplication> getApplicationListWithChildren(long parentId);
/**
* 获取某个用户的全部模块列表
*
* @return List
*/
List<SysApplication> getSysApplicationByUserId(String actorId);
/**
* 根据查询参数获取记录总数
*
* @return
*/
int getSysApplicationCountByQueryCriteria(SysApplicationQuery query);
/**
* 根据查询参数获取一页的数据
*
* @return
*/
List<SysApplication> getSysApplicationsByQueryCriteria(int start, int pageSize, SysApplicationQuery query);
List<SysApplication> getSysApplicationsByRoleCode(String roleCode);
List<SysApplication> getSysApplicationsByRoleId(String roleId);
/**
* 设置删除标记
*
* @param id
* @param deleteFlag
*/
@Transactional
void markDeleteFlag(long id, int deleteFlag);
/**
* 设置删除标记
*
* @param ids
* @param deleteFlag
*/
@Transactional
void markDeleteFlag(long[] ids, int deleteFlag);
@Transactional
void saveRoleApplications(String roleId, List<Long> appIds);
/**
* 排序
*
* @param bean
* SysApplication
* @param operate
* int 操作
*/
@Transactional
void sort(long parent, SysApplication bean, int operate);
/**
* 更新
*
* @param bean
* SysApplication
* @return boolean
*/
@Transactional
boolean update(SysApplication bean);
}
|
UTF-8
|
Java
| 4,013 |
java
|
SysApplicationService.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.base.modules.sys.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.glaf.base.modules.sys.model.SysApplication;
import com.glaf.base.modules.sys.query.SysApplicationQuery;
import com.glaf.core.util.PageResult;
@Transactional(readOnly = true)
public interface SysApplicationService {
@Transactional
void batchCreate(List<SysApplication> rows);
/**
* 保存
*
* @param bean
* SysApplication
* @return boolean
*/
@Transactional
boolean create(SysApplication bean);
/**
* 删除
*
* @param id
* int
* @return boolean
*/
@Transactional
boolean delete(long id);
/**
* 删除
*
* @param bean
* SysApplication
* @return boolean
*/
@Transactional
boolean delete(SysApplication bean);
/**
* 批量删除
*
* @param id
* @return
*/
@Transactional
boolean deleteAll(long[] id);
/**
* 按编码查找对象
*
* @param code
* String
* @return SysApplication
*/
SysApplication findByCode(String code);
/**
* 获取对象
*
* @param id
* @return
*/
SysApplication findById(long id);
/**
* 按名称查找对象
*
* @param name
* String
* @return SysApplication
*/
SysApplication findByName(String name);
List<SysApplication> getAllSysApplications();
PageResult getApplicationList(int pageNo, int pageSize, SysApplicationQuery query);
/**
* 获取分页列表
*
* @param parentId
* int
* @param pageNo
* int
* @param pageSize
* int
* @return
*/
PageResult getApplicationList(long parentId, int pageNo, int pageSize);
/**
* 获取某个模块的全部子节点及子孙节点
*
* @param parentId
* long
* @return List
*/
List<SysApplication> getApplicationListWithChildren(long parentId);
/**
* 获取某个用户的全部模块列表
*
* @return List
*/
List<SysApplication> getSysApplicationByUserId(String actorId);
/**
* 根据查询参数获取记录总数
*
* @return
*/
int getSysApplicationCountByQueryCriteria(SysApplicationQuery query);
/**
* 根据查询参数获取一页的数据
*
* @return
*/
List<SysApplication> getSysApplicationsByQueryCriteria(int start, int pageSize, SysApplicationQuery query);
List<SysApplication> getSysApplicationsByRoleCode(String roleCode);
List<SysApplication> getSysApplicationsByRoleId(String roleId);
/**
* 设置删除标记
*
* @param id
* @param deleteFlag
*/
@Transactional
void markDeleteFlag(long id, int deleteFlag);
/**
* 设置删除标记
*
* @param ids
* @param deleteFlag
*/
@Transactional
void markDeleteFlag(long[] ids, int deleteFlag);
@Transactional
void saveRoleApplications(String roleId, List<Long> appIds);
/**
* 排序
*
* @param bean
* SysApplication
* @param operate
* int 操作
*/
@Transactional
void sort(long parent, SysApplication bean, int operate);
/**
* 更新
*
* @param bean
* SysApplication
* @return boolean
*/
@Transactional
boolean update(SysApplication bean);
}
| 4,013 | 0.672282 | 0.671229 | 192 | 18.791666 | 21.566233 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.953125 | false | false |
3
|
83a4023144f4d1a704786714be09fb8da8b4c3b8
| 27,092,653,766,936 |
3e3967711013ea57849f97a07bab1550c90be8ab
|
/src/main/java/men/brakh/enrollment/security/authentication/credentials/EmployeeCredentials.java
|
ef7dc27ed1f96961f47bc14fcc58e3055ef40272
|
[] |
no_license
|
N1ghtF1re/wt-labs
|
https://github.com/N1ghtF1re/wt-labs
|
329dd02df7b604e8589896ee39213596c098db89
|
4550840b7e0659e2e4fcb6664ad660a9bf294003
|
refs/heads/master
| 2020-07-24T16:42:02.925000 | 2020-03-02T13:30:02 | 2020-03-02T13:30:02 | 207,985,627 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package men.brakh.enrollment.security.authentication.credentials;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import men.brakh.enrollment.domain.BaseEntity;
@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
@Entity(name = "employee_credentials")
public class EmployeeCredentials implements BaseEntity<Integer> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String password;
private Integer employeeId;
}
|
UTF-8
|
Java
| 667 |
java
|
EmployeeCredentials.java
|
Java
|
[] | null |
[] |
package men.brakh.enrollment.security.authentication.credentials;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import men.brakh.enrollment.domain.BaseEntity;
@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
@Entity(name = "employee_credentials")
public class EmployeeCredentials implements BaseEntity<Integer> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String password;
private Integer employeeId;
}
| 667 | 0.826087 | 0.826087 | 26 | 24.653847 | 18.945148 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
34bd85f72ec1d966dee0d6f20c7457e1b7d5b3dc
| 11,012,296,200,357 |
2979ad767cbb8e79d0e517733f379490c41978a2
|
/src/main/java/codersafterdark/compatskills/common/compats/gamestages/gamestagelocks/GameStageLockHandler.java
|
cfc4d2fe325e2efa46a8821ea335ff209322375b
|
[
"MIT"
] |
permissive
|
Coders-After-Dark/CompatSkills
|
https://github.com/Coders-After-Dark/CompatSkills
|
ab4482ddd7f9b0077e85df7232dbefc7ae821647
|
cd7ea68639bc4a62c86fe2878bacb6897f1abc10
|
refs/heads/master
| 2021-06-08T04:04:42.121000 | 2019-10-24T16:54:58 | 2019-10-24T16:54:58 | 125,918,571 | 6 | 10 |
MIT
| false | 2020-12-01T09:16:25 | 2018-03-19T20:49:58 | 2020-05-21T03:46:59 | 2019-10-24T16:55:12 | 21,704 | 5 | 3 | 20 |
Java
| false | false |
package codersafterdark.compatskills.common.compats.gamestages.gamestagelocks;
import codersafterdark.compatskills.utils.Utils;
import codersafterdark.reskillable.api.data.PlayerData;
import codersafterdark.reskillable.api.data.PlayerDataHandler;
import codersafterdark.reskillable.api.data.RequirementHolder;
import codersafterdark.reskillable.base.LevelLockHandler;
import net.darkhax.gamestages.event.GameStageEvent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class GameStageLockHandler {
@SubscribeEvent(priority = EventPriority.HIGH)
public void gameStageAdded(GameStageEvent.Add event) {
EntityPlayer player = event.getEntityPlayer();
if (Utils.skipPlayer(player)) {
return;
}
PlayerData data = PlayerDataHandler.get(player);
String eventGameStage = event.getStageName();
RequirementHolder requirementHolder = LevelLockHandler.getLockByKey(new GameStageLock(eventGameStage));
if (!requirementHolder.equals(LevelLockHandler.EMPTY_LOCK) && !data.matchStats(requirementHolder)) {
event.setCanceled(true);
TextComponentTranslation error = new TextComponentTranslation("compatskills.error.gamestage");
player.sendStatusMessage(Utils.getError(requirementHolder, data, error), false);
}
}
}
|
UTF-8
|
Java
| 1,517 |
java
|
GameStageLockHandler.java
|
Java
|
[] | null |
[] |
package codersafterdark.compatskills.common.compats.gamestages.gamestagelocks;
import codersafterdark.compatskills.utils.Utils;
import codersafterdark.reskillable.api.data.PlayerData;
import codersafterdark.reskillable.api.data.PlayerDataHandler;
import codersafterdark.reskillable.api.data.RequirementHolder;
import codersafterdark.reskillable.base.LevelLockHandler;
import net.darkhax.gamestages.event.GameStageEvent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class GameStageLockHandler {
@SubscribeEvent(priority = EventPriority.HIGH)
public void gameStageAdded(GameStageEvent.Add event) {
EntityPlayer player = event.getEntityPlayer();
if (Utils.skipPlayer(player)) {
return;
}
PlayerData data = PlayerDataHandler.get(player);
String eventGameStage = event.getStageName();
RequirementHolder requirementHolder = LevelLockHandler.getLockByKey(new GameStageLock(eventGameStage));
if (!requirementHolder.equals(LevelLockHandler.EMPTY_LOCK) && !data.matchStats(requirementHolder)) {
event.setCanceled(true);
TextComponentTranslation error = new TextComponentTranslation("compatskills.error.gamestage");
player.sendStatusMessage(Utils.getError(requirementHolder, data, error), false);
}
}
}
| 1,517 | 0.77851 | 0.77851 | 30 | 49.599998 | 30.555523 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false |
3
|
d40cabcda271231b709756ea59182e023ac23983
| 13,194,139,593,944 |
a39bc3968034858c5540f5e58db38541c1c1f9f9
|
/src/test/java/com/github/joraclista/model/EmptyTableName.java
|
a71426568f5c5673fa836a6c2dc6b93514183a40
|
[] |
no_license
|
joraclista/dynamodb-full-scan-api
|
https://github.com/joraclista/dynamodb-full-scan-api
|
2fedbe1988463425197427410972502e0f11a729
|
ce7fd897aed836ba5ada86f32235546cb617f339
|
refs/heads/master
| 2021-04-27T06:43:58.119000 | 2018-02-23T15:03:23 | 2018-02-23T15:03:23 | 122,617,869 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.joraclista.model;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import lombok.Data;
/**
* Created by Alisa
* version 1.0.
*/
@DynamoDBTable(tableName = "")
@Data
public class EmptyTableName {
@DynamoDBHashKey
private String id;
}
|
UTF-8
|
Java
| 357 |
java
|
EmptyTableName.java
|
Java
|
[
{
"context": "amoDBTable;\nimport lombok.Data;\n\n/**\n * Created by Alisa\n * version 1.0.\n */\n@DynamoDBTable(tableName = \"\"",
"end": 222,
"score": 0.9966917037963867,
"start": 217,
"tag": "NAME",
"value": "Alisa"
}
] | null |
[] |
package com.github.joraclista.model;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import lombok.Data;
/**
* Created by Alisa
* version 1.0.
*/
@DynamoDBTable(tableName = "")
@Data
public class EmptyTableName {
@DynamoDBHashKey
private String id;
}
| 357 | 0.770308 | 0.759104 | 18 | 18.888889 | 21.099997 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false |
3
|
ad154521dfbc0f6cf6e774da72264e85718d9dc2
| 31,404,800,885,643 |
0d9b3abb66b746c549e8f333a44df1a27258db57
|
/job-exercise/src/main/java/com/job/exercise/service/UserListService.java
|
7f086555af2f87c9e773051bc1930dea432154fa
|
[] |
no_license
|
martelaxe/job-exercise
|
https://github.com/martelaxe/job-exercise
|
6fc3394cb1f56f95f6d84fb803bb1d3d92d0ee66
|
98eb22380136e3068b045f922227e824eb832056
|
refs/heads/master
| 2020-05-17T22:20:37.189000 | 2019-04-29T18:00:43 | 2019-04-29T18:00:43 | 183,998,558 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.job.exercise.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.job.exercise.model.UserList;
import com.job.exercise.repository.UserListRepository;
@Service
public class UserListService {
@Autowired
UserListRepository userListRepository;
public List<UserList> getAllUserList(){
List<UserList> userLists = new ArrayList<UserList>();
userListRepository.findAll().forEach(userList-> userLists.add(userList));
return userLists;
}
public UserList getUserListbyUserId(int id) {
return userListRepository.findById(id).get();
}
public void saveOrUpdate(UserList userList) {
userListRepository.save(userList);
}
public void deleteUserList(int id) {
userListRepository.deleteById(id);
}
}
|
UTF-8
|
Java
| 923 |
java
|
UserListService.java
|
Java
|
[] | null |
[] |
package com.job.exercise.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.job.exercise.model.UserList;
import com.job.exercise.repository.UserListRepository;
@Service
public class UserListService {
@Autowired
UserListRepository userListRepository;
public List<UserList> getAllUserList(){
List<UserList> userLists = new ArrayList<UserList>();
userListRepository.findAll().forEach(userList-> userLists.add(userList));
return userLists;
}
public UserList getUserListbyUserId(int id) {
return userListRepository.findById(id).get();
}
public void saveOrUpdate(UserList userList) {
userListRepository.save(userList);
}
public void deleteUserList(int id) {
userListRepository.deleteById(id);
}
}
| 923 | 0.730228 | 0.730228 | 38 | 22.289474 | 22.058424 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.131579 | false | false |
3
|
810f4df192fed4c628be54fbfc59cae5b7448103
| 28,819,230,577,156 |
d16629f1c4734ddfaccee155954c1efe029dd177
|
/src/test/java/cat/aubricoc/sudoku/config/ConfigurationParserTest.java
|
c5487a5ed9a6dd74bc6401731f41dd93f2329c02
|
[] |
no_license
|
aubricoc/sudoku-solver
|
https://github.com/aubricoc/sudoku-solver
|
4843e135937820319d5894e7db124e7a6046b671
|
dc3e6534a0cd2f7cf6f35456ef0b7d328edc7f5c
|
refs/heads/master
| 2020-12-19T06:02:14.545000 | 2020-01-26T17:38:10 | 2020-01-26T17:38:10 | 235,640,607 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cat.aubricoc.sudoku.config;
import cat.aubricoc.sudoku.exception.InvalidMulthreadingParameterException;
import cat.aubricoc.sudoku.exception.RequiredFileException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ConfigurationParserTest {
private static final String FILE = "/file.sudoku";
@Test
public void testParseNoArgs() {
assertThrows(RequiredFileException.class, () -> ConfigurationParser.parse());
}
@Test
public void testParseEmptyString() {
assertThrows(RequiredFileException.class, () -> ConfigurationParser.parse(""));
}
@Test
public void testParseWithoutMultithreading() {
Configuration config = ConfigurationParser.parse(FILE);
verifyResult(config, false);
}
@Test
public void testParseWithoutMultithreadingValue() {
assertThrows(InvalidMulthreadingParameterException.class, () -> ConfigurationParser.parse(FILE, "-p"));
}
@Test
public void testParseWithMultithreadingValueInvalid() {
assertThrows(InvalidMulthreadingParameterException.class, () -> ConfigurationParser.parse(FILE, "-p", "a"));
}
@Test
public void testParseWithMultithreadingFalse() {
Configuration config = ConfigurationParser.parse(FILE, "-p", "0");
verifyResult(config, false);
}
@Test
public void testParseWithMultithreadingTrue() {
Configuration config = ConfigurationParser.parse(FILE, "-p", "1");
verifyResult(config, true);
}
private void verifyResult(Configuration config, boolean multithreading) {
assertNotNull(config);
assertEquals(multithreading, config.isMultithreading());
assertEquals(FILE, config.getFile());
}
}
|
UTF-8
|
Java
| 1,913 |
java
|
ConfigurationParserTest.java
|
Java
|
[] | null |
[] |
package cat.aubricoc.sudoku.config;
import cat.aubricoc.sudoku.exception.InvalidMulthreadingParameterException;
import cat.aubricoc.sudoku.exception.RequiredFileException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ConfigurationParserTest {
private static final String FILE = "/file.sudoku";
@Test
public void testParseNoArgs() {
assertThrows(RequiredFileException.class, () -> ConfigurationParser.parse());
}
@Test
public void testParseEmptyString() {
assertThrows(RequiredFileException.class, () -> ConfigurationParser.parse(""));
}
@Test
public void testParseWithoutMultithreading() {
Configuration config = ConfigurationParser.parse(FILE);
verifyResult(config, false);
}
@Test
public void testParseWithoutMultithreadingValue() {
assertThrows(InvalidMulthreadingParameterException.class, () -> ConfigurationParser.parse(FILE, "-p"));
}
@Test
public void testParseWithMultithreadingValueInvalid() {
assertThrows(InvalidMulthreadingParameterException.class, () -> ConfigurationParser.parse(FILE, "-p", "a"));
}
@Test
public void testParseWithMultithreadingFalse() {
Configuration config = ConfigurationParser.parse(FILE, "-p", "0");
verifyResult(config, false);
}
@Test
public void testParseWithMultithreadingTrue() {
Configuration config = ConfigurationParser.parse(FILE, "-p", "1");
verifyResult(config, true);
}
private void verifyResult(Configuration config, boolean multithreading) {
assertNotNull(config);
assertEquals(multithreading, config.isMultithreading());
assertEquals(FILE, config.getFile());
}
}
| 1,913 | 0.717198 | 0.716153 | 58 | 31.982759 | 31.51436 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false |
3
|
c71d55252dbeb1becc4ecfa570aaa6f59bfb4e70
| 6,640,019,471,626 |
dfcff679231dee88766aaa23736bb34d6454d8f4
|
/spring2sample/src/com/ervacon/spring2sample/web/FormController.java
|
5e2a4e44d19d42bb5575ba354d5d5f2ec1ceefc1
|
[] |
no_license
|
Ervacon/spring-samples
|
https://github.com/Ervacon/spring-samples
|
f261f5ca16d13d523d74ad71d639fe6ec7f5a4fb
|
0ca5b445ab99a6427d9eba387cd11f6629416623
|
refs/heads/master
| 2021-01-20T23:27:07.047000 | 2015-02-02T21:00:58 | 2015-02-02T21:00:58 | 30,207,884 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ervacon.spring2sample.web;
import java.beans.PropertyEditorSupport;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.ervacon.spring2sample.domain.Colour;
import com.ervacon.spring2sample.domain.Country;
import com.ervacon.spring2sample.domain.Skill;
import com.ervacon.spring2sample.domain.User;
import com.ervacon.spring2sample.service.UserManager;
public class FormController extends SimpleFormController {
private UserManager userManager;
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Country.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(userManager.findCountryByCode(text));
}
public String getAsText() {
return getValue() == null ? "" : ((Country) getValue()).getCode();
}
});
binder.registerCustomEditor(Colour.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(Colour.valueOf(text));
}
});
binder.registerCustomEditor(Skill.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(Skill.valueOf(text));
};
});
}
protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
return
new ModelMap(this.userManager.findAllCountries())
.addObject("skills", Skill.values())
.addObject("colours", Colour.values());
}
protected Object formBackingObject(HttpServletRequest request) throws Exception {
long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
return this.userManager.findUserById(id);
}
protected void doSubmitAction(Object command) throws Exception {
this.userManager.saveUser((User) command);
}
}
|
UTF-8
|
Java
| 2,247 |
java
|
FormController.java
|
Java
|
[] | null |
[] |
package com.ervacon.spring2sample.web;
import java.beans.PropertyEditorSupport;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.ervacon.spring2sample.domain.Colour;
import com.ervacon.spring2sample.domain.Country;
import com.ervacon.spring2sample.domain.Skill;
import com.ervacon.spring2sample.domain.User;
import com.ervacon.spring2sample.service.UserManager;
public class FormController extends SimpleFormController {
private UserManager userManager;
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Country.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(userManager.findCountryByCode(text));
}
public String getAsText() {
return getValue() == null ? "" : ((Country) getValue()).getCode();
}
});
binder.registerCustomEditor(Colour.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(Colour.valueOf(text));
}
});
binder.registerCustomEditor(Skill.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(Skill.valueOf(text));
};
});
}
protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
return
new ModelMap(this.userManager.findAllCountries())
.addObject("skills", Skill.values())
.addObject("colours", Colour.values());
}
protected Object formBackingObject(HttpServletRequest request) throws Exception {
long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
return this.userManager.findUserById(id);
}
protected void doSubmitAction(Object command) throws Exception {
this.userManager.saveUser((User) command);
}
}
| 2,247 | 0.789052 | 0.786382 | 66 | 33.045456 | 29.753244 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.833333 | false | false |
3
|
9c2dd9e9c185e42c43f372f5f097a166f0a170b4
| 15,530,601,768,890 |
2ac74657de3cb81bab734d18094e945a442a167d
|
/sechub-pds/src/main/java/com/mercedesbenz/sechub/pds/PDSFlywayFactory.java
|
a825f148eb21c8c19bc96b212c68853cb4ebccf2
|
[
"MIT",
"ANTLR-PD",
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-oracle-openjdk-exception-2.0",
"MPL-1.1",
"MPL-2.0",
"CC-PDDC",
"LicenseRef-scancode-warranty-disclaimer",
"EPL-2.0",
"GPL-2.0-only",
"EPL-1.0",
"CC0-1.0",
"Classpath-exception-2.0",
"Apache-2.0",
"LGPL-2.1-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-public-domain",
"GPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"Apache-1.1",
"MPL-1.0",
"CDDL-1.1",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
de-jcup/sechub
|
https://github.com/de-jcup/sechub
|
64055bb7ccd5496e32207c140e5812997e97583b
|
488d2d23b9ae74043e8747467623d291c7371b38
|
refs/heads/develop
| 2023-07-22T18:01:47.280000 | 2023-07-18T15:50:27 | 2023-07-18T15:50:27 | 199,480,695 | 0 | 1 |
MIT
| true | 2023-03-20T03:00:02 | 2019-07-29T15:37:19 | 2022-05-06T15:46:38 | 2023-03-20T03:00:00 | 20,073 | 0 | 1 | 4 |
Java
| false | false |
// SPDX-License-Identifier: MIT
package com.mercedesbenz.sechub.pds;
import java.util.List;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.output.RepairOutput;
import org.flywaydb.core.api.output.RepairResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("!" + PDSProfiles.TEST) // spring profile "test" has no Flyway enabled
public class PDSFlywayFactory {
private static final Logger LOG = LoggerFactory.getLogger(PDSFlywayFactory.class);
@Value("${pds.migration.flyway.autorepair:true}")
@PDSMustBeDocumented(value = "When enabled, flyway migration problems will be automatically repaired", scope = "migration")
boolean repairAutomatically;
@Bean
public FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
if (repairAutomatically) {
LOG.info("Start flyway repair");
RepairResult result = flyway.repair();
logRepairs("align migration", result.migrationsAligned);
logRepairs("delete migration", result.migrationsDeleted);
logRepairs("remove migration", result.migrationsRemoved);
LOG.info("Flyway repair done for flyway version:{}", result.flywayVersion);
}
return new FlywayMigrationInitializer(flyway);
}
private void logRepairs(String message, List<RepairOutput> outputList) {
for (RepairOutput output : outputList) {
logRepair(message, output);
}
}
private void logRepair(String repairAction, RepairOutput output) {
LOG.info("Flyway repair did {}: version={},description={},", repairAction, output.version, output.description);
}
}
|
UTF-8
|
Java
| 1,995 |
java
|
PDSFlywayFactory.java
|
Java
|
[] | null |
[] |
// SPDX-License-Identifier: MIT
package com.mercedesbenz.sechub.pds;
import java.util.List;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.output.RepairOutput;
import org.flywaydb.core.api.output.RepairResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("!" + PDSProfiles.TEST) // spring profile "test" has no Flyway enabled
public class PDSFlywayFactory {
private static final Logger LOG = LoggerFactory.getLogger(PDSFlywayFactory.class);
@Value("${pds.migration.flyway.autorepair:true}")
@PDSMustBeDocumented(value = "When enabled, flyway migration problems will be automatically repaired", scope = "migration")
boolean repairAutomatically;
@Bean
public FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
if (repairAutomatically) {
LOG.info("Start flyway repair");
RepairResult result = flyway.repair();
logRepairs("align migration", result.migrationsAligned);
logRepairs("delete migration", result.migrationsDeleted);
logRepairs("remove migration", result.migrationsRemoved);
LOG.info("Flyway repair done for flyway version:{}", result.flywayVersion);
}
return new FlywayMigrationInitializer(flyway);
}
private void logRepairs(String message, List<RepairOutput> outputList) {
for (RepairOutput output : outputList) {
logRepair(message, output);
}
}
private void logRepair(String repairAction, RepairOutput output) {
LOG.info("Flyway repair did {}: version={},description={},", repairAction, output.version, output.description);
}
}
| 1,995 | 0.733835 | 0.732832 | 55 | 35.290909 | 32.926735 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672727 | false | false |
3
|
b206c63db08a6a444ea8893a1d8e7a15247c0bba
| 11,819,750,034,909 |
2784da1585b6a531fa131472436d5286b31a810c
|
/people/src/main/java/com/csi/itaca/people/model/dto/AccountClasificationDTO.java
|
11987329b81acafdfdb217bbd508ebe0b6d720f2
|
[] |
no_license
|
gitjguerra/Itaca
|
https://github.com/gitjguerra/Itaca
|
93a543e37921814c08fbf504672bfa289d9f2c2d
|
c54a93673a1e12f24e4f6716575311cb5504d101
|
refs/heads/master
| 2020-04-10T19:51:39.784000 | 2018-12-10T23:44:06 | 2018-12-10T23:44:06 | 161,249,567 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.csi.itaca.people.model.dto;
import com.csi.itaca.people.model.AccountClasification;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class AccountClasificationDTO implements AccountClasification {
private Long id;
private String value;
}
|
UTF-8
|
Java
| 379 |
java
|
AccountClasificationDTO.java
|
Java
|
[] | null |
[] |
package com.csi.itaca.people.model.dto;
import com.csi.itaca.people.model.AccountClasification;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class AccountClasificationDTO implements AccountClasification {
private Long id;
private String value;
}
| 379 | 0.831135 | 0.831135 | 19 | 18.947369 | 19.296778 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false |
3
|
fd033bdc9b4bcd9ffcc9afb6809fa29b381001af
| 22,686,017,285,711 |
5cf033292d24f777b5a56c4981ed6ad62bf6482c
|
/app/src/main/java/com/company/myapp/fragment/ListViewTest2Fragment.java
|
a59b54eba904826c9600b50cfd3ff35f2cffc357
|
[] |
no_license
|
893573771/BaseApp
|
https://github.com/893573771/BaseApp
|
c5e44b12c5b1f5ca1092c0fb8b030eb69f4ec465
|
eb9374e77392f618950a71c65dafd1c878881cf2
|
refs/heads/master
| 2020-12-27T21:16:55.771000 | 2016-05-31T07:47:45 | 2016-05-31T07:47:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company.myapp.fragment;
import android.view.View;
import android.widget.AdapterView;
import com.company.myapp.R;
import com.company.myapp.adapter.ListView2Adapter;
import com.ghy.baseapp.base.AbsAdapterItem;
import com.ghy.baseapp.base.AbsBaseListFragment;
import com.ghy.baseapp.helper.ToastHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by GHY on 2016/5/10.
*/
public class ListViewTest2Fragment extends AbsBaseListFragment {
private List mList;
@Override
protected AbsAdapterItem getAbsAdapterItem() {
return new ListView2Adapter();
}
@Override
protected int getHeaderLayout() {
return R.layout.item_list_view_header1;
}
@Override
protected int getFooterLayout() {
return R.layout.item_list_view_footer1;
}
@Override
protected void init() {
mList = new ArrayList();
for (int i = 0; i < 50; i++) {
mList.add("this is item " + i);
}
setData(mList);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
if (position == 0) {
ToastHelper.getInstance().showToast("点击了Header");
} else if (position == mList.size() + 1) {
ToastHelper.getInstance().showToast("点击了Footer");
} else {
ToastHelper.getInstance().showToast("点击了 " + mList.get(position - 1));
}
}
}
|
UTF-8
|
Java
| 1,519 |
java
|
ListViewTest2Fragment.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by GHY on 2016/5/10.\n */\npublic class ListViewTest2Fragm",
"end": 388,
"score": 0.9996037483215332,
"start": 385,
"tag": "USERNAME",
"value": "GHY"
}
] | null |
[] |
package com.company.myapp.fragment;
import android.view.View;
import android.widget.AdapterView;
import com.company.myapp.R;
import com.company.myapp.adapter.ListView2Adapter;
import com.ghy.baseapp.base.AbsAdapterItem;
import com.ghy.baseapp.base.AbsBaseListFragment;
import com.ghy.baseapp.helper.ToastHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by GHY on 2016/5/10.
*/
public class ListViewTest2Fragment extends AbsBaseListFragment {
private List mList;
@Override
protected AbsAdapterItem getAbsAdapterItem() {
return new ListView2Adapter();
}
@Override
protected int getHeaderLayout() {
return R.layout.item_list_view_header1;
}
@Override
protected int getFooterLayout() {
return R.layout.item_list_view_footer1;
}
@Override
protected void init() {
mList = new ArrayList();
for (int i = 0; i < 50; i++) {
mList.add("this is item " + i);
}
setData(mList);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
if (position == 0) {
ToastHelper.getInstance().showToast("点击了Header");
} else if (position == mList.size() + 1) {
ToastHelper.getInstance().showToast("点击了Footer");
} else {
ToastHelper.getInstance().showToast("点击了 " + mList.get(position - 1));
}
}
}
| 1,519 | 0.644237 | 0.632245 | 58 | 24.879311 | 22.319836 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
31d1eb99b20768ac5806e1b5490f94f443b8436c
| 6,116,033,454,047 |
5c3b4db5c59256d6b08866c03d43881287aaa04b
|
/SD/app/src/main/java/com/example/fan/sd/MainActivity.java
|
e0b80eed05b417dc46d20350293a20ea2b6e3f32
|
[] |
no_license
|
z30121454/AD
|
https://github.com/z30121454/AD
|
f340b8af6550a4460adf7b2f95878c8d15e37de6
|
fd30b39cbb98221c969dafc105e958fea2e09882
|
refs/heads/master
| 2020-11-26T11:48:08.317000 | 2019-12-19T13:41:40 | 2019-12-19T13:41:40 | 229,061,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.fan.sd;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class MainActivity extends AppCompatActivity {
//寫入按鈕與讀取按鈕
private Button myBtIn, myBtOut;
//輸入儲存文字的EditText
private EditText myWriteEt;
//顯示讀取文字的TextView
private TextView myTvOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBtIn = (Button) findViewById(R.id.myBtIn);
myWriteEt = (EditText) findViewById(R.id.myWriteEt);
myBtOut = (Button) findViewById(R.id.myBtOut);
myTvOut = (TextView) findViewById(R.id.myTvOut);
myBtIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
File mSDFile;
//檢查有沒有SD卡
if (Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)) {
Toast.makeText(MainActivity.this, "請插入SD卡", Toast.LENGTH_SHORT).show();
return;
} else {
//取得SD卡儲存路徑
mSDFile = Environment.getExternalStorageDirectory();
}
//建立儲存路徑
File mFile = new File(mSDFile.getParent() + "/" + mSDFile.getName() + "/MyAndroid");
//建立此檔案路徑
if (!mFile.exists()) {
mFile.mkdirs();
}
//取得mEdit文字並儲存寫入至SD卡文件裡
FileWriter mFileWriter = new FileWriter(mSDFile.getParent() + "/" + mSDFile.getName() + "/MyAndroid/File.txt");
mFileWriter.write(myWriteEt.getText().toString());
mFileWriter.close();
Toast.makeText(MainActivity.this, "已儲存文字", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
myBtOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
//取得SD卡儲存路徑
File mSDFile = Environment.getExternalStorageDirectory();
FileReader mFileReader = new FileReader(mSDFile.getParent() + "/" + mSDFile.getName() + "/MyAndroid/File.txt");
BufferedReader mBufferedReader = new BufferedReader(mFileReader);
String mReadText = "";
String mTextLine = mBufferedReader.readLine();
//取出文字字串裝入String裡
while (mTextLine != null) {
mReadText += mTextLine + "\n";
mTextLine = mBufferedReader.readLine();
}
//文字放入mText裡,並清空myWriteEt
myTvOut.setText(mReadText);
Toast.makeText(MainActivity.this, "已讀取文字", Toast.LENGTH_SHORT).show();
myWriteEt.setText("");
} catch (Exception e) {
}
}
});
}
}
|
UTF-8
|
Java
| 3,791 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.fan.sd;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class MainActivity extends AppCompatActivity {
//寫入按鈕與讀取按鈕
private Button myBtIn, myBtOut;
//輸入儲存文字的EditText
private EditText myWriteEt;
//顯示讀取文字的TextView
private TextView myTvOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBtIn = (Button) findViewById(R.id.myBtIn);
myWriteEt = (EditText) findViewById(R.id.myWriteEt);
myBtOut = (Button) findViewById(R.id.myBtOut);
myTvOut = (TextView) findViewById(R.id.myTvOut);
myBtIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
File mSDFile;
//檢查有沒有SD卡
if (Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)) {
Toast.makeText(MainActivity.this, "請插入SD卡", Toast.LENGTH_SHORT).show();
return;
} else {
//取得SD卡儲存路徑
mSDFile = Environment.getExternalStorageDirectory();
}
//建立儲存路徑
File mFile = new File(mSDFile.getParent() + "/" + mSDFile.getName() + "/MyAndroid");
//建立此檔案路徑
if (!mFile.exists()) {
mFile.mkdirs();
}
//取得mEdit文字並儲存寫入至SD卡文件裡
FileWriter mFileWriter = new FileWriter(mSDFile.getParent() + "/" + mSDFile.getName() + "/MyAndroid/File.txt");
mFileWriter.write(myWriteEt.getText().toString());
mFileWriter.close();
Toast.makeText(MainActivity.this, "已儲存文字", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
myBtOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
//取得SD卡儲存路徑
File mSDFile = Environment.getExternalStorageDirectory();
FileReader mFileReader = new FileReader(mSDFile.getParent() + "/" + mSDFile.getName() + "/MyAndroid/File.txt");
BufferedReader mBufferedReader = new BufferedReader(mFileReader);
String mReadText = "";
String mTextLine = mBufferedReader.readLine();
//取出文字字串裝入String裡
while (mTextLine != null) {
mReadText += mTextLine + "\n";
mTextLine = mBufferedReader.readLine();
}
//文字放入mText裡,並清空myWriteEt
myTvOut.setText(mReadText);
Toast.makeText(MainActivity.this, "已讀取文字", Toast.LENGTH_SHORT).show();
myWriteEt.setText("");
} catch (Exception e) {
}
}
});
}
}
| 3,791 | 0.531084 | 0.531084 | 92 | 37.010868 | 27.925169 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false |
3
|
992d28ffa29b23f169f5d9425d307b02351df0e1
| 24,137,716,213,894 |
7f563a18ba8f03bb7cdfff172e728a75fd792478
|
/src/test/TestTabellone.java
|
6dd2af94bd0b83e555f15bbce97ea09a4b8fb960
|
[] |
no_license
|
GiuseTripodi/ScaleESerpenti
|
https://github.com/GiuseTripodi/ScaleESerpenti
|
9d23b16c3898492767a0809b617b26ed18a4391a
|
000ed2e70aadf8b5ad191b868efa2fbba2e310d8
|
refs/heads/master
| 2022-11-05T01:27:57.637000 | 2020-07-01T16:36:30 | 2020-07-01T16:36:30 | 271,504,125 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test;
import Componenti.*;
import GiocoEtabellone.ConcreteTabellone;
import GiocoEtabellone.Tabellone;
import SupportClass.Posizione;
public class TestTabellone {
public static void main(String ... args){
int numeroRighe = 4;
int numeroColonne = 5;
int numCelle = 20;
Posizione p = new Posizione();
p.setInformazioniTabellone(numeroRighe,numeroColonne,numCelle);
ConcreteTabellone t = new ConcreteTabellone(numeroRighe, numeroColonne,numCelle);
//aggiungo un po di componenti
Posizione p1 = new Posizione(4,numeroRighe,numeroColonne,numCelle);
Sosta sosta = new Sosta(p1, Sosta.TipoSosta.LOCANDA);
t.add(sosta);
p.setNumeroCella(2);
t.add(new ScalaFine(p));
p.setNumeroCella(7);
t.add(new SerpenteInizio(p));
t.stampa();
System.out.println("------------------");
t.remove(sosta);
t.stampa();
}
}
|
UTF-8
|
Java
| 965 |
java
|
TestTabellone.java
|
Java
|
[] | null |
[] |
package test;
import Componenti.*;
import GiocoEtabellone.ConcreteTabellone;
import GiocoEtabellone.Tabellone;
import SupportClass.Posizione;
public class TestTabellone {
public static void main(String ... args){
int numeroRighe = 4;
int numeroColonne = 5;
int numCelle = 20;
Posizione p = new Posizione();
p.setInformazioniTabellone(numeroRighe,numeroColonne,numCelle);
ConcreteTabellone t = new ConcreteTabellone(numeroRighe, numeroColonne,numCelle);
//aggiungo un po di componenti
Posizione p1 = new Posizione(4,numeroRighe,numeroColonne,numCelle);
Sosta sosta = new Sosta(p1, Sosta.TipoSosta.LOCANDA);
t.add(sosta);
p.setNumeroCella(2);
t.add(new ScalaFine(p));
p.setNumeroCella(7);
t.add(new SerpenteInizio(p));
t.stampa();
System.out.println("------------------");
t.remove(sosta);
t.stampa();
}
}
| 965 | 0.635233 | 0.625907 | 35 | 26.571428 | 22.726053 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false |
3
|
0b781b0cdde468d5ef3bc294bf5812f131889a81
| 12,927,851,609,396 |
17e37ca416a82f4081f01df86941ca6e5ae4c914
|
/nhm-ide/cse.nhm.ide.ui/src/cse/nhm/ide/ui/VersionSwitchingMenu.java
|
08d4b96f9a21b581b73f64b4e4cb7120ac524063
|
[] |
no_license
|
decc/national-household-model-core-components
|
https://github.com/decc/national-household-model-core-components
|
d0c8e08c9d23da4c6812df9e07b69eadf7fa16a4
|
31b72cdb3ddaf834a3ba57954d42f531004786b9
|
refs/heads/master
| 2020-05-26T00:33:53.193000 | 2017-08-29T14:23:05 | 2017-08-29T14:23:05 | 57,210,476 | 0 | 1 | null | false | 2017-04-04T13:45:41 | 2016-04-27T12:08:08 | 2016-05-20T11:26:41 | 2017-04-04T13:45:41 | 41,739 | 0 | 0 | 3 |
Java
| null | null |
package cse.nhm.ide.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.PlatformUI;
import cse.nhm.ide.ui.PluginPreferences.VersionPreference;
import cse.nhm.ide.ui.builder.RevalidateJob;
public class VersionSwitchingMenu extends ContributionItem {
public VersionSwitchingMenu() {
}
public VersionSwitchingMenu(String id) {
super(id);
}
@Override
public void fill(final Menu menu, final int index) {
final ISelection selection =
PlatformUI
.getWorkbench()
.getActiveWorkbenchWindow()
.getSelectionService()
.getSelection();
final List<IProject> projects = new ArrayList<>();
if (selection instanceof IStructuredSelection) {
final IStructuredSelection sel =
(IStructuredSelection) selection;
for (final Object o : sel.toList()) {
if (o instanceof IProject) {
projects.add((IProject) o);
} else if (o instanceof IAdaptable) {
final IProject p =
(IProject)
((IAdaptable) o).getAdapter(IProject.class);
if (p != null) projects.add(p);
}
}
}
if (projects.isEmpty()) return;
final VersionPreference selected;
if (projects.size() == 1) {
selected = VersionPreference.forProject(projects.get(0));
} else {
selected = null;
}
final MenuItem item = new MenuItem(menu, SWT.CASCADE, index);
item.setText("Model version...");
item.setMenu(createVersionSelectionMenu(menu, projects, selected));
}
private Menu createVersionSelectionMenu(final Menu parent, final List<IProject> projects, VersionPreference selected) {
final Menu subMenu = new Menu(parent);
final SelectionListener listener = new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
final Object o = e.getSource();
if (o instanceof MenuItem) {
final Object d = ((MenuItem) o).getData("version");
if (d instanceof VersionPreference) {
final VersionPreference choice = (VersionPreference) d;
for (final IProject p : projects) {
choice.save(p);
final RevalidateJob revalidate = new RevalidateJob(p);
revalidate.schedule(100);
}
}
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
};
int index = 0;
for (final VersionPreference pref : VersionPreference.values()) {
final MenuItem item = new MenuItem(subMenu, SWT.CHECK, index++);
item.setText(String.valueOf(pref));
item.addSelectionListener(listener);
if (pref.equals(selected)) {
item.setSelection(true);
}
item.setData("version", pref);
}
return subMenu;
}
}
|
UTF-8
|
Java
| 3,071 |
java
|
VersionSwitchingMenu.java
|
Java
|
[] | null |
[] |
package cse.nhm.ide.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.PlatformUI;
import cse.nhm.ide.ui.PluginPreferences.VersionPreference;
import cse.nhm.ide.ui.builder.RevalidateJob;
public class VersionSwitchingMenu extends ContributionItem {
public VersionSwitchingMenu() {
}
public VersionSwitchingMenu(String id) {
super(id);
}
@Override
public void fill(final Menu menu, final int index) {
final ISelection selection =
PlatformUI
.getWorkbench()
.getActiveWorkbenchWindow()
.getSelectionService()
.getSelection();
final List<IProject> projects = new ArrayList<>();
if (selection instanceof IStructuredSelection) {
final IStructuredSelection sel =
(IStructuredSelection) selection;
for (final Object o : sel.toList()) {
if (o instanceof IProject) {
projects.add((IProject) o);
} else if (o instanceof IAdaptable) {
final IProject p =
(IProject)
((IAdaptable) o).getAdapter(IProject.class);
if (p != null) projects.add(p);
}
}
}
if (projects.isEmpty()) return;
final VersionPreference selected;
if (projects.size() == 1) {
selected = VersionPreference.forProject(projects.get(0));
} else {
selected = null;
}
final MenuItem item = new MenuItem(menu, SWT.CASCADE, index);
item.setText("Model version...");
item.setMenu(createVersionSelectionMenu(menu, projects, selected));
}
private Menu createVersionSelectionMenu(final Menu parent, final List<IProject> projects, VersionPreference selected) {
final Menu subMenu = new Menu(parent);
final SelectionListener listener = new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
final Object o = e.getSource();
if (o instanceof MenuItem) {
final Object d = ((MenuItem) o).getData("version");
if (d instanceof VersionPreference) {
final VersionPreference choice = (VersionPreference) d;
for (final IProject p : projects) {
choice.save(p);
final RevalidateJob revalidate = new RevalidateJob(p);
revalidate.schedule(100);
}
}
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
};
int index = 0;
for (final VersionPreference pref : VersionPreference.values()) {
final MenuItem item = new MenuItem(subMenu, SWT.CHECK, index++);
item.setText(String.valueOf(pref));
item.addSelectionListener(listener);
if (pref.equals(selected)) {
item.setSelection(true);
}
item.setData("version", pref);
}
return subMenu;
}
}
| 3,071 | 0.707262 | 0.705308 | 110 | 26.918182 | 22.340397 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.909091 | false | false |
3
|
41c959495000eb1b0ca0b436c0c410642daa2951
| 25,632,364,862,854 |
11b7cd2fdd22ce0889fbe98d14a75c964955a35a
|
/src/renderer/Render.java
|
c4f2483bbc1e6f5b27406e8b4052c362a67bbd23
|
[] |
no_license
|
liorperetz/introSE
|
https://github.com/liorperetz/introSE
|
0cc642e5f1de17cb144e24f4797e7b5a17c7a4cf
|
b6626f3fb2ac301eb1446a2b5e831aeac4d0c3a9
|
refs/heads/main
| 2023-07-16T16:29:54.993000 | 2021-09-09T12:08:47 | 2021-09-09T12:08:47 | 346,018,481 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package renderer;
import elements.Camera;
import primitives.Color;
import primitives.Ray;
import scene.Scene;
import java.util.MissingResourceException;
import static primitives.Util.alignZero;
/**
* Render class creates the color matrix from the scene
*
* @author Reuven Klein
* @author Lior Peretz
*/
public class Render {
/**
* imageWriter write pixel's colors to image
*/
ImageWriter _imageWriter;
/**
* the camera that watch the scene
*/
Camera _camera;
/**
* rayTracer to trace rays from the camera and color the pixels
*/
RayTracerBase _rayTracer;
private int threadsCount = 0;//number of desired threads
private static final int SPARE_THREADS = 2; // Spare threads if trying to use all the cores
private boolean print = false; // printing progress percentage
/**
* Set multi-threading <br>
* - if the parameter is 0 - number of cores less 2 is taken
*
* @param threads number of threads
* @return the Render object itself
*/
public Render setMultithreading(int threads) {
if (threads < 0)
throw new IllegalArgumentException("Multithreading parameter must be 0 or higher");
if (threads != 0)
this.threadsCount = threads;
else {
int cores = Runtime.getRuntime().availableProcessors() - SPARE_THREADS;
this.threadsCount = cores <= 2 ? 1 : cores;
}
return this;
}
/**
* Set debug printing on
*
* @return the Render object itself
*/
public Render setDebugPrint() {
print = true;
return this;
}
/**
* Pixel is an internal helper class whose objects are associated with a Render
* object that they are generated in scope of. It is used for multithreading in
* the Renderer and for follow up its progress.<br/>
* There is a main follow up object and several secondary objects - one in each
* thread.
*
* @author Dan
*
*/
private class Pixel {
private long maxRows = 0;
private long maxCols = 0;
private long pixels = 0;
public volatile int row = 0;
public volatile int col = -1;
private long counter = 0;
private int percents = 0;
private long nextCounter = 0;
/**
* The constructor for initializing the main follow up Pixel object
*
* @param maxRows the amount of pixel rows
* @param maxCols the amount of pixel columns
*/
public Pixel(int maxRows, int maxCols) {
this.maxRows = maxRows;
this.maxCols = maxCols;
this.pixels = (long) maxRows * maxCols;
this.nextCounter = this.pixels / 100;
if (Render.this.print)
System.out.printf("\r %02d%%", this.percents);
}
/**
* Default constructor for secondary Pixel objects
*/
public Pixel() {
}
/**
* Internal function for thread-safe manipulating of main follow up Pixel object
* - this function is critical section for all the threads, and main Pixel
* object data is the shared data of this critical section.<br/>
* The function provides next pixel number each call.
*
* @param target target secondary Pixel object to copy the row/column of the
* next pixel
* @return the progress percentage for follow up: if it is 0 - nothing to print,
* if it is -1 - the task is finished, any other value - the progress
* percentage (only when it changes)
*/
private synchronized int nextP(Pixel target) {
++col;
++this.counter;
if (col < this.maxCols) {
target.row = this.row;
target.col = this.col;
if (Render.this.print && this.counter == this.nextCounter) {
++this.percents;
this.nextCounter = this.pixels * (this.percents + 1) / 100;
return this.percents;
}
return 0;
}
++row;
if (row < this.maxRows) {
col = 0;
target.row = this.row;
target.col = this.col;
if (Render.this.print && this.counter == this.nextCounter) {
++this.percents;
this.nextCounter = this.pixels * (this.percents + 1) / 100;
return this.percents;
}
return 0;
}
return -1;
}
/**
* Public function for getting next pixel number into secondary Pixel object.
* The function prints also progress percentage in the console window.
*
* @param target target secondary Pixel object to copy the row/column of the
* next pixel
* @return true if the work still in progress, -1 if it's done
*/
public boolean nextPixel(Pixel target) {
int percent = nextP(target);
if (Render.this.print && percent > 0)
synchronized (this) {
notifyAll();
}
if (percent >= 0)
return true;
if (Render.this.print)
synchronized (this) {
notifyAll();
}
return false;
}
/**
* Debug print of progress percentage - must be run from the main thread
*/
public void print() {
if (Render.this.print)
while (this.percents < 100)
try {
synchronized (this) {
wait();
}
System.out.printf("\r %02d%%", this.percents);
System.out.flush();
} catch (Exception e) {
}
}
}
/**
* Cast ray from camera in order to color a pixel
* @param nX resolution on X axis (number of pixels in row)
* @param nY resolution on Y axis (number of pixels in column)
* @param col pixel's column number (pixel index in row)
* @param row pixel's row number (pixel index in column)
*/
private void castRay(int nX, int nY, int col, int row) {
Ray ray = _camera.constructRayThroughPixel(nX, nY, col, row);
Color color = _rayTracer.traceRay(ray);
_imageWriter.writePixel(col, row, color);
}
/**
* This function renders image's pixel color map from the scene included with
* the Renderer object - with multi-threading
*/
private void renderImageThreaded() {
final int nX = _imageWriter.getNx();
final int nY = _imageWriter.getNy();
final Pixel thePixel = new Pixel(nY, nX);
// Generate threads
Thread[] threads = new Thread[threadsCount];
for (int i = threadsCount - 1; i >= 0; --i) {
threads[i] = new Thread(() -> {
Pixel pixel = new Pixel();
while (thePixel.nextPixel(pixel))
castRay(nX, nY, pixel.col, pixel.row);
});
}
// Start threads
for (Thread thread : threads)
thread.start();
// Print percents on the console
thePixel.print();
// Ensure all threads have finished
for (Thread thread : threads)
try {
thread.join();
} catch (Exception e) {
}
if (print)
System.out.print("\r100%");
}
/**
* color each pixel of the view plane
*/
public void renderImage() {
//trow exception if one of the fields was not set yet
try {
if (_imageWriter == null) {
throw new MissingResourceException("missing resource value", ImageWriter.class.getName(), "");
}
if (_rayTracer == null) {
throw new MissingResourceException("missing resource value", RayTracerBase.class.getName(), "");
}
if (_camera == null) {
throw new MissingResourceException("missing resource value", Camera.class.getName(), "");
}
_rayTracer.set_upVector(_camera.get_vUp());
//rendering the image
final int nX= _imageWriter.getNx();//amount of pixels in x axis (width)
final int nY=_imageWriter.getNy();//amount of pixels in y axis (height)
//iterate each pixel of the view plane, send ray from the camera through it
//and determine the color
if (threadsCount == 0)
for (int i = 0; i < nY; ++i)
for (int j = 0; j < nX; ++j)
castRay(nX, nY, j, i);
else
renderImageThreaded();
} catch (MissingResourceException exception) {
throw new UnsupportedOperationException("Not all fields were set yet" + exception.getClassName());
}
}
/**
* create a squared grid in the image
* @param interval square's side length (in pixels)
* @param color wished color of the grid
*/
public void printGrid(int interval, Color color) {
//cannot coloring pixels if imageWriter was not defined yet
if (_imageWriter == null) {
throw new MissingResourceException("missing resource", ImageWriter.class.getName(), "");
}
int nX = _imageWriter.getNx();//amount of pixels in x axis (width)
int nY = _imageWriter.getNy();//amount of pixels in y axis (height)
//coloring the grid's pixels
for (int i = 0; i < nY; i++) {
for (int j = 0; j < nX; j++) {
//coloring only the grid according to the interval dimensions
if (i % interval == 0) {
_imageWriter.writePixel(j, i, color);
} else if (j % interval == 0) {
_imageWriter.writePixel(j, i, color);
}
}
}
}
/**
* delegation using. function writeToImage produces unoptimized png file of the image according to
* pixel color matrix in the directory of the project
*/
public void writeToImage(){
//cannot write to image if imageWriter was not defined yet
if (_imageWriter == null) {
throw new MissingResourceException("missing resource", ImageWriter.class.getName(), "");
}
_imageWriter.writeToImage();
}
//chaining setters methods
/**
* imageWriter chaining setter
* @param imageWriter ImageWriter object
* @return current Render instance
*/
public Render setImageWriter(ImageWriter imageWriter) {
_imageWriter = imageWriter;
return this;
}
/**
* camera chaining setter
* @param camera Camera object
* @return current Render instance
*/
public Render setCamera(Camera camera) {
_camera = camera;
return this;
}
/**
* rayTracer chaining setter
* @param rayTracer RayTracerBase object
* @return current Render instance
*/
public Render setRayTracer(RayTracerBase rayTracer) {
_rayTracer = rayTracer;
return this;
}
}
|
UTF-8
|
Java
| 11,456 |
java
|
Render.java
|
Java
|
[
{
"context": "ates the color matrix from the scene\n *\n * @author Reuven Klein\n * @author Lior Peretz\n */\npublic class Render {\n",
"end": 284,
"score": 0.999887228012085,
"start": 272,
"tag": "NAME",
"value": "Reuven Klein"
},
{
"context": "om the scene\n *\n * @author Reuven Klein\n * @author Lior Peretz\n */\npublic class Render {\n /**\n * imageWri",
"end": 307,
"score": 0.9998760223388672,
"start": 296,
"tag": "NAME",
"value": "Lior Peretz"
},
{
"context": "- one in each\n * thread.\n *\n * @author Dan\n *\n */\n private class Pixel {\n ",
"end": 2014,
"score": 0.9997228384017944,
"start": 2011,
"tag": "NAME",
"value": "Dan"
}
] | null |
[] |
package renderer;
import elements.Camera;
import primitives.Color;
import primitives.Ray;
import scene.Scene;
import java.util.MissingResourceException;
import static primitives.Util.alignZero;
/**
* Render class creates the color matrix from the scene
*
* @author <NAME>
* @author <NAME>
*/
public class Render {
/**
* imageWriter write pixel's colors to image
*/
ImageWriter _imageWriter;
/**
* the camera that watch the scene
*/
Camera _camera;
/**
* rayTracer to trace rays from the camera and color the pixels
*/
RayTracerBase _rayTracer;
private int threadsCount = 0;//number of desired threads
private static final int SPARE_THREADS = 2; // Spare threads if trying to use all the cores
private boolean print = false; // printing progress percentage
/**
* Set multi-threading <br>
* - if the parameter is 0 - number of cores less 2 is taken
*
* @param threads number of threads
* @return the Render object itself
*/
public Render setMultithreading(int threads) {
if (threads < 0)
throw new IllegalArgumentException("Multithreading parameter must be 0 or higher");
if (threads != 0)
this.threadsCount = threads;
else {
int cores = Runtime.getRuntime().availableProcessors() - SPARE_THREADS;
this.threadsCount = cores <= 2 ? 1 : cores;
}
return this;
}
/**
* Set debug printing on
*
* @return the Render object itself
*/
public Render setDebugPrint() {
print = true;
return this;
}
/**
* Pixel is an internal helper class whose objects are associated with a Render
* object that they are generated in scope of. It is used for multithreading in
* the Renderer and for follow up its progress.<br/>
* There is a main follow up object and several secondary objects - one in each
* thread.
*
* @author Dan
*
*/
private class Pixel {
private long maxRows = 0;
private long maxCols = 0;
private long pixels = 0;
public volatile int row = 0;
public volatile int col = -1;
private long counter = 0;
private int percents = 0;
private long nextCounter = 0;
/**
* The constructor for initializing the main follow up Pixel object
*
* @param maxRows the amount of pixel rows
* @param maxCols the amount of pixel columns
*/
public Pixel(int maxRows, int maxCols) {
this.maxRows = maxRows;
this.maxCols = maxCols;
this.pixels = (long) maxRows * maxCols;
this.nextCounter = this.pixels / 100;
if (Render.this.print)
System.out.printf("\r %02d%%", this.percents);
}
/**
* Default constructor for secondary Pixel objects
*/
public Pixel() {
}
/**
* Internal function for thread-safe manipulating of main follow up Pixel object
* - this function is critical section for all the threads, and main Pixel
* object data is the shared data of this critical section.<br/>
* The function provides next pixel number each call.
*
* @param target target secondary Pixel object to copy the row/column of the
* next pixel
* @return the progress percentage for follow up: if it is 0 - nothing to print,
* if it is -1 - the task is finished, any other value - the progress
* percentage (only when it changes)
*/
private synchronized int nextP(Pixel target) {
++col;
++this.counter;
if (col < this.maxCols) {
target.row = this.row;
target.col = this.col;
if (Render.this.print && this.counter == this.nextCounter) {
++this.percents;
this.nextCounter = this.pixels * (this.percents + 1) / 100;
return this.percents;
}
return 0;
}
++row;
if (row < this.maxRows) {
col = 0;
target.row = this.row;
target.col = this.col;
if (Render.this.print && this.counter == this.nextCounter) {
++this.percents;
this.nextCounter = this.pixels * (this.percents + 1) / 100;
return this.percents;
}
return 0;
}
return -1;
}
/**
* Public function for getting next pixel number into secondary Pixel object.
* The function prints also progress percentage in the console window.
*
* @param target target secondary Pixel object to copy the row/column of the
* next pixel
* @return true if the work still in progress, -1 if it's done
*/
public boolean nextPixel(Pixel target) {
int percent = nextP(target);
if (Render.this.print && percent > 0)
synchronized (this) {
notifyAll();
}
if (percent >= 0)
return true;
if (Render.this.print)
synchronized (this) {
notifyAll();
}
return false;
}
/**
* Debug print of progress percentage - must be run from the main thread
*/
public void print() {
if (Render.this.print)
while (this.percents < 100)
try {
synchronized (this) {
wait();
}
System.out.printf("\r %02d%%", this.percents);
System.out.flush();
} catch (Exception e) {
}
}
}
/**
* Cast ray from camera in order to color a pixel
* @param nX resolution on X axis (number of pixels in row)
* @param nY resolution on Y axis (number of pixels in column)
* @param col pixel's column number (pixel index in row)
* @param row pixel's row number (pixel index in column)
*/
private void castRay(int nX, int nY, int col, int row) {
Ray ray = _camera.constructRayThroughPixel(nX, nY, col, row);
Color color = _rayTracer.traceRay(ray);
_imageWriter.writePixel(col, row, color);
}
/**
* This function renders image's pixel color map from the scene included with
* the Renderer object - with multi-threading
*/
private void renderImageThreaded() {
final int nX = _imageWriter.getNx();
final int nY = _imageWriter.getNy();
final Pixel thePixel = new Pixel(nY, nX);
// Generate threads
Thread[] threads = new Thread[threadsCount];
for (int i = threadsCount - 1; i >= 0; --i) {
threads[i] = new Thread(() -> {
Pixel pixel = new Pixel();
while (thePixel.nextPixel(pixel))
castRay(nX, nY, pixel.col, pixel.row);
});
}
// Start threads
for (Thread thread : threads)
thread.start();
// Print percents on the console
thePixel.print();
// Ensure all threads have finished
for (Thread thread : threads)
try {
thread.join();
} catch (Exception e) {
}
if (print)
System.out.print("\r100%");
}
/**
* color each pixel of the view plane
*/
public void renderImage() {
//trow exception if one of the fields was not set yet
try {
if (_imageWriter == null) {
throw new MissingResourceException("missing resource value", ImageWriter.class.getName(), "");
}
if (_rayTracer == null) {
throw new MissingResourceException("missing resource value", RayTracerBase.class.getName(), "");
}
if (_camera == null) {
throw new MissingResourceException("missing resource value", Camera.class.getName(), "");
}
_rayTracer.set_upVector(_camera.get_vUp());
//rendering the image
final int nX= _imageWriter.getNx();//amount of pixels in x axis (width)
final int nY=_imageWriter.getNy();//amount of pixels in y axis (height)
//iterate each pixel of the view plane, send ray from the camera through it
//and determine the color
if (threadsCount == 0)
for (int i = 0; i < nY; ++i)
for (int j = 0; j < nX; ++j)
castRay(nX, nY, j, i);
else
renderImageThreaded();
} catch (MissingResourceException exception) {
throw new UnsupportedOperationException("Not all fields were set yet" + exception.getClassName());
}
}
/**
* create a squared grid in the image
* @param interval square's side length (in pixels)
* @param color wished color of the grid
*/
public void printGrid(int interval, Color color) {
//cannot coloring pixels if imageWriter was not defined yet
if (_imageWriter == null) {
throw new MissingResourceException("missing resource", ImageWriter.class.getName(), "");
}
int nX = _imageWriter.getNx();//amount of pixels in x axis (width)
int nY = _imageWriter.getNy();//amount of pixels in y axis (height)
//coloring the grid's pixels
for (int i = 0; i < nY; i++) {
for (int j = 0; j < nX; j++) {
//coloring only the grid according to the interval dimensions
if (i % interval == 0) {
_imageWriter.writePixel(j, i, color);
} else if (j % interval == 0) {
_imageWriter.writePixel(j, i, color);
}
}
}
}
/**
* delegation using. function writeToImage produces unoptimized png file of the image according to
* pixel color matrix in the directory of the project
*/
public void writeToImage(){
//cannot write to image if imageWriter was not defined yet
if (_imageWriter == null) {
throw new MissingResourceException("missing resource", ImageWriter.class.getName(), "");
}
_imageWriter.writeToImage();
}
//chaining setters methods
/**
* imageWriter chaining setter
* @param imageWriter ImageWriter object
* @return current Render instance
*/
public Render setImageWriter(ImageWriter imageWriter) {
_imageWriter = imageWriter;
return this;
}
/**
* camera chaining setter
* @param camera Camera object
* @return current Render instance
*/
public Render setCamera(Camera camera) {
_camera = camera;
return this;
}
/**
* rayTracer chaining setter
* @param rayTracer RayTracerBase object
* @return current Render instance
*/
public Render setRayTracer(RayTracerBase rayTracer) {
_rayTracer = rayTracer;
return this;
}
}
| 11,445 | 0.545042 | 0.540154 | 342 | 32.497074 | 26.05558 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415205 | false | false |
3
|
5c68b09c37b37a7f81e196f452146555bdde28cb
| 15,350,213,149,790 |
dcc53b6a32ca36558d8e116e101d1b3159f37f1f
|
/src/main/java/com/zjh/daily_test/lru/Main.java
|
5c1c09c0553c94921f86f0eb727842b80f20b007
|
[] |
no_license
|
ZenoJHZhang/dailyTest
|
https://github.com/ZenoJHZhang/dailyTest
|
4b4e833894e131685130782438c2c846a0edc481
|
7c6a544ba7fdaebea6a358b936d3015d05a6463b
|
refs/heads/master
| 2020-05-16T09:12:13.174000 | 2020-02-21T08:42:55 | 2020-02-21T08:42:55 | 182,941,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zjh.daily_test.lru;
import java.util.Map;
/**
* 类的说明
*
* @author 张江浩
* @version 1.00
* @date 2020/2/13 14:43
*/
public class Main {
public static void main(String[] args) {
LruTest lruTest = new LruTest(2, 0.75f);
lruTest.put("1","zjh");
lruTest.put("2","zjh");
lruTest.put("3","zjh");
lruTest.put("4","zjh");
lruTest.put("5","zjh");
lruTest.forEach((key, value) -> System.out.println(key));
lruTest.put("6","zjh");
lruTest.forEach((key, value) -> System.out.println(key));
System.out.println("第二次===================");
for (Map.Entry<String,String> entry: lruTest.entrySet()
) {
System.out.println(entry.getKey());
}
}
}
|
UTF-8
|
Java
| 796 |
java
|
Main.java
|
Java
|
[
{
"context": "\nimport java.util.Map;\n\n/**\n * 类的说明\n *\n * @author 张江浩\n * @version 1.00\n * @date 2020/2/13 14:43\n */\npub",
"end": 85,
"score": 0.9998020529747009,
"start": 82,
"tag": "NAME",
"value": "张江浩"
}
] | null |
[] |
package com.zjh.daily_test.lru;
import java.util.Map;
/**
* 类的说明
*
* @author 张江浩
* @version 1.00
* @date 2020/2/13 14:43
*/
public class Main {
public static void main(String[] args) {
LruTest lruTest = new LruTest(2, 0.75f);
lruTest.put("1","zjh");
lruTest.put("2","zjh");
lruTest.put("3","zjh");
lruTest.put("4","zjh");
lruTest.put("5","zjh");
lruTest.forEach((key, value) -> System.out.println(key));
lruTest.put("6","zjh");
lruTest.forEach((key, value) -> System.out.println(key));
System.out.println("第二次===================");
for (Map.Entry<String,String> entry: lruTest.entrySet()
) {
System.out.println(entry.getKey());
}
}
}
| 796 | 0.527062 | 0.496134 | 34 | 21.82353 | 20.633312 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.676471 | false | false |
3
|
e0d0bca9fca3bc36d27430eb8f30931f32ef8505
| 22,462,679,004,278 |
0ec03591c37a99f70fdc063a245b76fa909c1b21
|
/dingxin-modules/dingxin-file-service/src/main/java/com/dingxin/file/controller/SysFastDFSUploadController.java
|
ab357af74f5ff314f47763cd02fa2a7ac7bb85c5
|
[] |
no_license
|
shenhuxi/springcloudBase
|
https://github.com/shenhuxi/springcloudBase
|
ac248981ea73dac8ae0a023026d68e27b55d805c
|
28b07ad567d21ca723660c0e9f5b1eb1fe20ef82
|
refs/heads/master
| 2020-05-04T14:06:49.123000 | 2019-04-03T01:19:13 | 2019-04-03T01:19:14 | 179,185,193 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dingxin.file.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.dingxin.common.annotation.UserOperate;
import com.dingxin.common.constant.OperateConstant;
import com.dingxin.common.controller.BaseController;
import com.dingxin.common.util.ResultObject;
import com.dingxin.common.vo.system.SysUserVo;
import com.dingxin.file.constant.FileConstant;
import com.dingxin.file.entity.SysFile;
import com.dingxin.file.service.SysFastDFSService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/fastdfs")
public class SysFastDFSUploadController extends BaseController {
@Autowired
private SysFastDFSService sysFastDFSService;
/**
* 上传单个文件
*
* @param
* @return
*/
@PostMapping("/upload/image")
@UserOperate(name = OperateConstant.SAVE, business = "文件管理-文件上传-单文件上传")
@ApiOperation(value = "上传单个文件", notes = "")
@ApiImplicitParam(name = "MultipartFile", value = "文件", required = true, paramType = "body", dataType = "MultipartFile")
public ResultObject uploadSingle(@RequestParam("files") MultipartFile[] files,
@RequestParam(value = "module", defaultValue = FileConstant.COMMON_PATH) String module,
@RequestParam(value = "business", defaultValue = "文件上传") String business, HttpServletRequest request) {
try {
SysUserVo userVo = getLoginUser();
for (MultipartFile file : files) {
if (!file.getContentType().startsWith("image")) {
return ResultObject.fail("上传类型为非图片");
}
}
if (files.length == 0) {
return ResultObject.fail("上传文件为空");
}
if (userVo == null) {
return ResultObject.fail("未登录");
}
List<SysFile> list = sysFastDFSService.saveFiles(files, userVo);
return ResultObject.ok(list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResultObject.fail("上传文件失败");
}
}
/**
* 上传多个文件
*
* @param files
* @return
*/
@PostMapping("/upload/multi")
@UserOperate(name = OperateConstant.SAVE, business = "文件管理-文件上传-多文件上传")
@ApiOperation(value = "上传多个文件", notes = "")
@ApiImplicitParam(name = "MultipartFile", value = "文件", required = true, paramType = "body", dataType = "MultipartFile")
public ResultObject uploadMulti(@RequestParam("files") MultipartFile[] files,
@RequestParam(value = "module", defaultValue = FileConstant.COMMON_PATH) String module,
@RequestParam(value = "business", defaultValue = "文件上传") String business, HttpServletRequest request) {
if (files.length == 0) {
return ResultObject.fail("上传文件为空");
}
try {
SysUserVo userVo = getLoginUser();
List<SysFile> list = sysFastDFSService.saveFiles(files, userVo);
return ResultObject.ok(list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResultObject.fail("上传文件失败");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResultObject.fail("上传文件失败");
}
}
/**
* 删除文件
*
* @param paths
* @return
*/
@UserOperate(name = OperateConstant.SAVE, business = "文件管理-文件上传-文件删除")
@ApiOperation(value = "删除文件", notes = "")
@ApiImplicitParam(name = "String[]", value = "路径数组", required = true, paramType = "body", dataType = "String[]")
@DeleteMapping("/delete/file")
public ResultObject deleteFile(String[] paths) {
if (paths.length <= 0) {
return ResultObject.fail("参数错误");
}
for (String path : paths) {
sysFastDFSService.delete_file(path);
}
return ResultObject.ok("删除成功");
}
}
|
UTF-8
|
Java
| 4,280 |
java
|
SysFastDFSUploadController.java
|
Java
|
[] | null |
[] |
package com.dingxin.file.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.dingxin.common.annotation.UserOperate;
import com.dingxin.common.constant.OperateConstant;
import com.dingxin.common.controller.BaseController;
import com.dingxin.common.util.ResultObject;
import com.dingxin.common.vo.system.SysUserVo;
import com.dingxin.file.constant.FileConstant;
import com.dingxin.file.entity.SysFile;
import com.dingxin.file.service.SysFastDFSService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/fastdfs")
public class SysFastDFSUploadController extends BaseController {
@Autowired
private SysFastDFSService sysFastDFSService;
/**
* 上传单个文件
*
* @param
* @return
*/
@PostMapping("/upload/image")
@UserOperate(name = OperateConstant.SAVE, business = "文件管理-文件上传-单文件上传")
@ApiOperation(value = "上传单个文件", notes = "")
@ApiImplicitParam(name = "MultipartFile", value = "文件", required = true, paramType = "body", dataType = "MultipartFile")
public ResultObject uploadSingle(@RequestParam("files") MultipartFile[] files,
@RequestParam(value = "module", defaultValue = FileConstant.COMMON_PATH) String module,
@RequestParam(value = "business", defaultValue = "文件上传") String business, HttpServletRequest request) {
try {
SysUserVo userVo = getLoginUser();
for (MultipartFile file : files) {
if (!file.getContentType().startsWith("image")) {
return ResultObject.fail("上传类型为非图片");
}
}
if (files.length == 0) {
return ResultObject.fail("上传文件为空");
}
if (userVo == null) {
return ResultObject.fail("未登录");
}
List<SysFile> list = sysFastDFSService.saveFiles(files, userVo);
return ResultObject.ok(list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResultObject.fail("上传文件失败");
}
}
/**
* 上传多个文件
*
* @param files
* @return
*/
@PostMapping("/upload/multi")
@UserOperate(name = OperateConstant.SAVE, business = "文件管理-文件上传-多文件上传")
@ApiOperation(value = "上传多个文件", notes = "")
@ApiImplicitParam(name = "MultipartFile", value = "文件", required = true, paramType = "body", dataType = "MultipartFile")
public ResultObject uploadMulti(@RequestParam("files") MultipartFile[] files,
@RequestParam(value = "module", defaultValue = FileConstant.COMMON_PATH) String module,
@RequestParam(value = "business", defaultValue = "文件上传") String business, HttpServletRequest request) {
if (files.length == 0) {
return ResultObject.fail("上传文件为空");
}
try {
SysUserVo userVo = getLoginUser();
List<SysFile> list = sysFastDFSService.saveFiles(files, userVo);
return ResultObject.ok(list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResultObject.fail("上传文件失败");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResultObject.fail("上传文件失败");
}
}
/**
* 删除文件
*
* @param paths
* @return
*/
@UserOperate(name = OperateConstant.SAVE, business = "文件管理-文件上传-文件删除")
@ApiOperation(value = "删除文件", notes = "")
@ApiImplicitParam(name = "String[]", value = "路径数组", required = true, paramType = "body", dataType = "String[]")
@DeleteMapping("/delete/file")
public ResultObject deleteFile(String[] paths) {
if (paths.length <= 0) {
return ResultObject.fail("参数错误");
}
for (String path : paths) {
sysFastDFSService.delete_file(path);
}
return ResultObject.ok("删除成功");
}
}
| 4,280 | 0.727182 | 0.726434 | 121 | 32.140495 | 28.501213 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
3
|
54025b5e2cc6fb78579231b305c948d99eaa746b
| 13,520,557,060,351 |
5f22cac4d93f00577b4c317246f4fbc0f57d8add
|
/app/src/main/java/com/qadsdk/impl/videocache/net/SourceHelper.java
|
a488fe414aea042977fa1637da68f535dcf9e969
|
[] |
no_license
|
yangboy985/ZKVideoCache
|
https://github.com/yangboy985/ZKVideoCache
|
e28110d94019291fd5b1fc1edf432438d17ee45d
|
53c99ec409a44a9518782d1ab961bf27f75f517a
|
refs/heads/master
| 2023-02-14T15:47:55.453000 | 2020-12-28T07:11:25 | 2020-12-28T07:11:25 | 324,937,314 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.qadsdk.impl.videocache.net;
import android.text.TextUtils;
import com.qadsdk.base.dev.util.Logger;
import com.qadsdk.impl.videocache.VideoCacheEntrance;
import com.qadsdk.impl.videocache.bean.VideoInfo;
import com.qadsdk.impl.videocache.utils.NetUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
public class SourceHelper {
private static final String TAG = "SourceHelper";
private static final int MAX_RETRY_TIMES = 3;
private VideoInfo mInfo;
private NetSourceRequester mRequester;
private boolean isConnected = false;
public SourceHelper(VideoInfo info) {
mInfo = info;
mRequester = new NetSourceRequester(info);
}
public int read(byte[] bytes, int off, int len) throws IOException {
return mRequester.read(bytes, off, len);
}
public synchronized boolean tryConnect() {
tryConnect(-1);
return isConnected;
}
public synchronized boolean tryConnect(long offset) {
if (!NetUtil.isNetworkConnected(VideoCacheEntrance.appContext)) {
Logger.e(TAG, "network is't connect");
return false;
}
int times = 0;
do {
times++;
isConnected = mRequester.tryConnect(offset == -1 ? mInfo.getOffset() : offset);
} while (!isConnected && times <= MAX_RETRY_TIMES);
return isConnected;
}
public boolean respClient(OutputStream os, long offset) throws IOException {
String respMsg = "HTTP/1.1 500 INTERNAL SERVER ERROR\n\n";
boolean isValidResp = false;
if (!mInfo.isComplete() && !isConnected) {
tryConnect();
}
if (isConnected || mInfo.isComplete()) {
respMsg = createRespMsg(offset);
if (TextUtils.isEmpty(respMsg)) {
respMsg = "HTTP/1.1 400 BAD REQUEST\n\n";
} else {
isValidResp = true;
}
} else {
String httpErrMsg = mRequester.getHttpErrorResp();
if (httpErrMsg != null) {
respMsg = httpErrMsg;
}
}
os.write(respMsg.getBytes("UTF-8"));
Logger.i(TAG, "[resp msg]: " + respMsg);
return isValidResp;
}
private String createRespMsg(long offset) {
if (mInfo.getLength() > 0 && offset >= mInfo.getLength()) {
return null;
}
boolean isPartial = offset > 0 && mInfo.getLength() > 0;
String mime = mInfo.getContentType();
long contentLength = mInfo.getLength() > 0 ? mInfo.getLength() - offset : 0;
long sourceLength = mInfo.getLength();
StringBuilder respMsgBuilder = new StringBuilder()
.append(isPartial ? "HTTP/1.1 206 PARTIAL CONTENT\n" : "HTTP/1.1 200 OK\n")
.append("Accept-Ranges: bytes\n");
// 数据一定要准确,不准确就不要传
if (contentLength > 0 && sourceLength > 0) {
respMsgBuilder.append(String.format(Locale.getDefault(), "Content-Length: %d\n", contentLength));
if (isPartial) {
respMsgBuilder.append(String.format(Locale.getDefault(), "Content-Range: bytes %d-%d/%d\n", offset, sourceLength - 1, sourceLength));
}
}
respMsgBuilder.append(!TextUtils.isEmpty(mime) ? String.format(Locale.getDefault(), "Content-Type: %s\n", mime) : "")
.append("\n");
return respMsgBuilder.toString();
}
public void releaseHelper() {
isConnected = false;
mRequester.releaseConnection();
}
}
|
UTF-8
|
Java
| 3,703 |
java
|
SourceHelper.java
|
Java
|
[] | null |
[] |
package com.qadsdk.impl.videocache.net;
import android.text.TextUtils;
import com.qadsdk.base.dev.util.Logger;
import com.qadsdk.impl.videocache.VideoCacheEntrance;
import com.qadsdk.impl.videocache.bean.VideoInfo;
import com.qadsdk.impl.videocache.utils.NetUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
public class SourceHelper {
private static final String TAG = "SourceHelper";
private static final int MAX_RETRY_TIMES = 3;
private VideoInfo mInfo;
private NetSourceRequester mRequester;
private boolean isConnected = false;
public SourceHelper(VideoInfo info) {
mInfo = info;
mRequester = new NetSourceRequester(info);
}
public int read(byte[] bytes, int off, int len) throws IOException {
return mRequester.read(bytes, off, len);
}
public synchronized boolean tryConnect() {
tryConnect(-1);
return isConnected;
}
public synchronized boolean tryConnect(long offset) {
if (!NetUtil.isNetworkConnected(VideoCacheEntrance.appContext)) {
Logger.e(TAG, "network is't connect");
return false;
}
int times = 0;
do {
times++;
isConnected = mRequester.tryConnect(offset == -1 ? mInfo.getOffset() : offset);
} while (!isConnected && times <= MAX_RETRY_TIMES);
return isConnected;
}
public boolean respClient(OutputStream os, long offset) throws IOException {
String respMsg = "HTTP/1.1 500 INTERNAL SERVER ERROR\n\n";
boolean isValidResp = false;
if (!mInfo.isComplete() && !isConnected) {
tryConnect();
}
if (isConnected || mInfo.isComplete()) {
respMsg = createRespMsg(offset);
if (TextUtils.isEmpty(respMsg)) {
respMsg = "HTTP/1.1 400 BAD REQUEST\n\n";
} else {
isValidResp = true;
}
} else {
String httpErrMsg = mRequester.getHttpErrorResp();
if (httpErrMsg != null) {
respMsg = httpErrMsg;
}
}
os.write(respMsg.getBytes("UTF-8"));
Logger.i(TAG, "[resp msg]: " + respMsg);
return isValidResp;
}
private String createRespMsg(long offset) {
if (mInfo.getLength() > 0 && offset >= mInfo.getLength()) {
return null;
}
boolean isPartial = offset > 0 && mInfo.getLength() > 0;
String mime = mInfo.getContentType();
long contentLength = mInfo.getLength() > 0 ? mInfo.getLength() - offset : 0;
long sourceLength = mInfo.getLength();
StringBuilder respMsgBuilder = new StringBuilder()
.append(isPartial ? "HTTP/1.1 206 PARTIAL CONTENT\n" : "HTTP/1.1 200 OK\n")
.append("Accept-Ranges: bytes\n");
// 数据一定要准确,不准确就不要传
if (contentLength > 0 && sourceLength > 0) {
respMsgBuilder.append(String.format(Locale.getDefault(), "Content-Length: %d\n", contentLength));
if (isPartial) {
respMsgBuilder.append(String.format(Locale.getDefault(), "Content-Range: bytes %d-%d/%d\n", offset, sourceLength - 1, sourceLength));
}
}
respMsgBuilder.append(!TextUtils.isEmpty(mime) ? String.format(Locale.getDefault(), "Content-Type: %s\n", mime) : "")
.append("\n");
return respMsgBuilder.toString();
}
public void releaseHelper() {
isConnected = false;
mRequester.releaseConnection();
}
}
| 3,703 | 0.588347 | 0.579363 | 100 | 34.73 | 28.19392 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.66 | false | false |
3
|
e5aa319856617fc7b2640af33a92f9b36a8f2427
| 29,119,878,304,534 |
39f7fcf16a55cf6f9291ac27495d01bfe7dfe9ad
|
/src/main/java/lambdas/ch04/BiConsumerTest.java
|
fcab9eaf00f2f8dd6817dd90075a381e8afb5752
|
[] |
no_license
|
samitkumarpatel/java8
|
https://github.com/samitkumarpatel/java8
|
c74e02b19e02eadc69369905bb23219e5db44e35
|
46b6ae36a83559c2eb0258db744ff58957019e14
|
refs/heads/master
| 2022-05-29T16:14:15.554000 | 2022-05-22T22:29:24 | 2022-05-22T22:29:24 | 213,223,933 | 0 | 0 | null | false | 2022-05-14T18:12:29 | 2019-10-06T18:44:43 | 2021-10-23T22:38:13 | 2022-05-14T18:12:29 | 11 | 0 | 0 | 0 |
Java
| false | false |
package lambdas.ch04;
import java.util.HashMap;
import java.util.Map;
public class BiConsumerTest {
public static void main(String[] args) {
Map<Integer, String> lengthString = new HashMap<>();
lengthString.put(4, "java");
lengthString.put(6, "spring");
lengthString.put(7, "lambdas");
System.out.println("Usual way: ");
// Typical way.
for (Map.Entry<Integer, String> entrySet : lengthString.entrySet()) {
System.out.print("Key is:" + entrySet.getKey());
System.out.println(" Value is:" + entrySet.getValue());
}
System.out.println("\nUsing Lambdas: ");
// Using Lambda
lengthString.forEach((key, value) -> System.out.println("Key is:" + key + " Value is:" + value));
}
}
|
UTF-8
|
Java
| 737 |
java
|
BiConsumerTest.java
|
Java
|
[] | null |
[] |
package lambdas.ch04;
import java.util.HashMap;
import java.util.Map;
public class BiConsumerTest {
public static void main(String[] args) {
Map<Integer, String> lengthString = new HashMap<>();
lengthString.put(4, "java");
lengthString.put(6, "spring");
lengthString.put(7, "lambdas");
System.out.println("Usual way: ");
// Typical way.
for (Map.Entry<Integer, String> entrySet : lengthString.entrySet()) {
System.out.print("Key is:" + entrySet.getKey());
System.out.println(" Value is:" + entrySet.getValue());
}
System.out.println("\nUsing Lambdas: ");
// Using Lambda
lengthString.forEach((key, value) -> System.out.println("Key is:" + key + " Value is:" + value));
}
}
| 737 | 0.644505 | 0.63772 | 27 | 25.296297 | 25.195259 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.777778 | false | false |
3
|
ee515525af36a4e21e3507f2a366ede694e0c198
| 21,869,973,526,577 |
e7223a27a8bb0a273661b4e4d522873ffeb6ab70
|
/app/src/main/java/com/example/admin/menuapp5/Web.java
|
63798cf1af9fce4a09190159fd188efdff8e166b
|
[] |
no_license
|
bufferingspirit/MenuApp5
|
https://github.com/bufferingspirit/MenuApp5
|
fd7e0106418d218a2eb7828d5c7292cb40b9712e
|
0718b3799f094203c703d4e9854cd73c85b02de2
|
refs/heads/master
| 2021-01-04T02:35:28.120000 | 2017-08-07T13:50:20 | 2017-08-07T13:50:20 | 99,513,295 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.admin.menuapp5;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by Admin on 8/6/2017.
*/
public class Web extends android.support.v4.app.Fragment {
View view;
WebView wv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_menu_web, container, false);
wv = (WebView) view.findViewById(R.id.webView);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState != null)
wv.restoreState(savedInstanceState);
else{
wv.setWebViewClient(new WebViewClient());
wv.loadUrl("http://www.google.com");
}
getActivity().setTitle("Web");
}
/*@Override
public void onSaveInstanceState(Bundle outState) {
wv.saveState(outState);
}*/
}
|
UTF-8
|
Java
| 1,233 |
java
|
Web.java
|
Java
|
[
{
"context": "t android.webkit.WebViewClient;\n\n/**\n * Created by Admin on 8/6/2017.\n */\n\npublic class Web extends androi",
"end": 292,
"score": 0.6980364322662354,
"start": 287,
"tag": "USERNAME",
"value": "Admin"
}
] | null |
[] |
package com.example.admin.menuapp5;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by Admin on 8/6/2017.
*/
public class Web extends android.support.v4.app.Fragment {
View view;
WebView wv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_menu_web, container, false);
wv = (WebView) view.findViewById(R.id.webView);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState != null)
wv.restoreState(savedInstanceState);
else{
wv.setWebViewClient(new WebViewClient());
wv.loadUrl("http://www.google.com");
}
getActivity().setTitle("Web");
}
/*@Override
public void onSaveInstanceState(Bundle outState) {
wv.saveState(outState);
}*/
}
| 1,233 | 0.684509 | 0.678021 | 47 | 25.25532 | 25.345669 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531915 | false | false |
3
|
003adb78a5f8f3309627ff5b050c179cb1bb9e2e
| 7,610,682,090,452 |
6daf833065aeeae45c8083b8e7d99f0fbc3e07bd
|
/src/main/java/fpij/collections/DoubleAndTotal.java
|
ec2c828984f46910839382483367374cb854d391
|
[] |
no_license
|
jesimone57/venkat_java8
|
https://github.com/jesimone57/venkat_java8
|
c8063455b2466810472197718a7b56af7bb2f6b0
|
b7d6df795c294ec41658e99120b965895da6f820
|
refs/heads/master
| 2021-01-01T04:06:04.843000 | 2016-05-23T17:34:55 | 2016-05-23T17:34:55 | 59,360,693 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fpij.collections;
import java.util.Arrays;
import java.util.List;
/**
* Created by jsimone on 12/8/15.
*/
public class DoubleAndTotal {
static final List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
public static void main(String[] args) {
// imperative style
int total = 0;
for (Integer num: nums) {
total += num * 2;
}
System.out.println(total);
// functional style. map/reduce pattern
System.out.println( nums.stream()
.map(i -> i * 2)
.reduce(0, (carry, elem) -> carry + elem));
// using sum
System.out.println( nums.stream()
.mapToInt(Integer::intValue)
.map(i -> i * 2)
.sum());
}
}
|
UTF-8
|
Java
| 786 |
java
|
DoubleAndTotal.java
|
Java
|
[
{
"context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by jsimone on 12/8/15.\n */\npublic class DoubleAndTotal {\n\n ",
"end": 101,
"score": 0.9996702075004578,
"start": 94,
"tag": "USERNAME",
"value": "jsimone"
}
] | null |
[] |
package fpij.collections;
import java.util.Arrays;
import java.util.List;
/**
* Created by jsimone on 12/8/15.
*/
public class DoubleAndTotal {
static final List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
public static void main(String[] args) {
// imperative style
int total = 0;
for (Integer num: nums) {
total += num * 2;
}
System.out.println(total);
// functional style. map/reduce pattern
System.out.println( nums.stream()
.map(i -> i * 2)
.reduce(0, (carry, elem) -> carry + elem));
// using sum
System.out.println( nums.stream()
.mapToInt(Integer::intValue)
.map(i -> i * 2)
.sum());
}
}
| 786 | 0.517812 | 0.497455 | 33 | 22.818182 | 18.833326 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false |
3
|
a28e7ff428ba09e1ac7eef01aa415e45570501fe
| 9,277,129,374,416 |
cee8ffdf537af4bc50ad987251d74a62af4fe1f3
|
/app/src/main/java/ru/sberbank/converter/data/db/DatabaseOpenHelper.java
|
63bf3861e6c2b3cc0a9a1320ba08b2e3bdf1d956
|
[] |
no_license
|
maxlord/cb-converter
|
https://github.com/maxlord/cb-converter
|
0d352ff817b28103b3473e1c22ccfee2a482ffa1
|
92a890a3bc55f10c90d18ca1db24ac49792ffbe8
|
refs/heads/master
| 2021-01-12T05:33:36.423000 | 2017-01-17T14:19:09 | 2017-01-17T14:19:09 | 77,125,705 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.sberbank.converter.data.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import ru.sberbank.converter.BuildConfig;
import ru.sberbank.converter.data.db.entity.Currency;
/**
* Помощник для работы с БД
*
* @author Lord (Kuleshov M.V.)
* @since 23.12.16
*/
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "main.db";
public static final String CURRENCY_TABLE = "currency";
private static final String CURRENCY_TABLE_DDL = "CREATE TABLE currency (" +
Currency.COLUMN_ID + " VARCHAR(10) PRIMARY KEY, " +
Currency.COLUMN_NUM_CODE + " VARCHAR(3) NOT NULL, " +
Currency.COLUMN_CHAR_CODE + " VARCHAR(3) NOT NULL, " +
Currency.COLUMN_NOMINAL + " INTEGER NOT NULL, " +
Currency.COLUMN_NAME + " VARCHAR(255) NOT NULL, " +
Currency.COLUMN_VALUE + " REAL NOT NULL" +
")";
private static final String CURRENCY_RUB_INSERT = "INSERT INTO currency (" +
Currency.COLUMN_ID + ", " +
Currency.COLUMN_NUM_CODE + ", " +
Currency.COLUMN_CHAR_CODE + ", " +
Currency.COLUMN_NOMINAL + ", " +
Currency.COLUMN_NAME + ", " +
Currency.COLUMN_VALUE + ") VALUES ('R00000', '000', 'RUB', 1, 'Российский рубль', 1)";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, BuildConfig.DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CURRENCY_TABLE_DDL);
// Вставляем информацию о российском рубле, потому что веб-сервис не содержит этой информации
db.execSQL(CURRENCY_RUB_INSERT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
UTF-8
|
Java
| 1,825 |
java
|
DatabaseOpenHelper.java
|
Java
|
[
{
"context": "cy;\n\n/**\n * Помощник для работы с БД\n *\n * @author Lord (Kuleshov M.V.)\n * @since 23.12.16\n */\npublic cla",
"end": 316,
"score": 0.9886106848716736,
"start": 312,
"tag": "NAME",
"value": "Lord"
},
{
"context": "*\n * Помощник для работы с БД\n *\n * @author Lord (Kuleshov M.V.)\n * @since 23.12.16\n */\npublic class DatabaseOpenH",
"end": 330,
"score": 0.999150812625885,
"start": 318,
"tag": "NAME",
"value": "Kuleshov M.V"
}
] | null |
[] |
package ru.sberbank.converter.data.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import ru.sberbank.converter.BuildConfig;
import ru.sberbank.converter.data.db.entity.Currency;
/**
* Помощник для работы с БД
*
* @author Lord (<NAME>.)
* @since 23.12.16
*/
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "main.db";
public static final String CURRENCY_TABLE = "currency";
private static final String CURRENCY_TABLE_DDL = "CREATE TABLE currency (" +
Currency.COLUMN_ID + " VARCHAR(10) PRIMARY KEY, " +
Currency.COLUMN_NUM_CODE + " VARCHAR(3) NOT NULL, " +
Currency.COLUMN_CHAR_CODE + " VARCHAR(3) NOT NULL, " +
Currency.COLUMN_NOMINAL + " INTEGER NOT NULL, " +
Currency.COLUMN_NAME + " VARCHAR(255) NOT NULL, " +
Currency.COLUMN_VALUE + " REAL NOT NULL" +
")";
private static final String CURRENCY_RUB_INSERT = "INSERT INTO currency (" +
Currency.COLUMN_ID + ", " +
Currency.COLUMN_NUM_CODE + ", " +
Currency.COLUMN_CHAR_CODE + ", " +
Currency.COLUMN_NOMINAL + ", " +
Currency.COLUMN_NAME + ", " +
Currency.COLUMN_VALUE + ") VALUES ('R00000', '000', 'RUB', 1, 'Российский рубль', 1)";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, BuildConfig.DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CURRENCY_TABLE_DDL);
// Вставляем информацию о российском рубле, потому что веб-сервис не содержит этой информации
db.execSQL(CURRENCY_RUB_INSERT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| 1,819 | 0.709866 | 0.696439 | 52 | 31.942308 | 26.728271 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.788462 | false | false |
3
|
b9e1647c6715800c84dea010abc1a4e2944eded3
| 30,889,404,810,894 |
36dd76e7a70f6e0f696aa7ca14f2cac85626ccbd
|
/src/main/java/com/example/Vaadin7_Builder/view/AccountingViewServises/UpdateAccountingFlatGrid.java
|
07ec2c109cd1f990e7e382c685453db4f39d6f0f
|
[] |
no_license
|
klymnazar/Vaadin7_Builder
|
https://github.com/klymnazar/Vaadin7_Builder
|
595f7020e021b967348dd20ae9a8069017def0b5
|
441e68375932f93615fe4b782de6eab00a4d07b2
|
refs/heads/master
| 2022-07-06T21:00:33.475000 | 2020-02-15T17:56:35 | 2020-02-15T17:56:35 | 191,734,256 | 0 | 0 | null | false | 2022-01-21T23:37:42 | 2019-06-13T09:38:27 | 2020-02-15T17:56:49 | 2022-01-21T23:37:40 | 226 | 0 | 0 | 3 |
Java
| false | false |
package com.example.Vaadin7_Builder.view.AccountingViewServises;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import com.example.Vaadin7_Builder.model.Flat;
import com.example.Vaadin7_Builder.service.FlatService;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.FooterRow;
public class UpdateAccountingFlatGrid {
FlatService flatService = new FlatService();
private DecimalFormat decimalFormat = new DecimalFormat("0.00");
private String generalExpenses = "General";
private String bcExpenses = "B.C.";
private String cmExpenses = "C.M.";
public void updateAccountingFlatGrid(Grid flatGrid)
throws SQLException {
flatGrid.getContainerDataSource().removeAllItems();
double flatArea = 0;
int flatCost = 0;
int expensesRow = 0;
int availableSumRow = 0;
double mAvailableSumRow = 0;
int generalExpensesRow = 0;
double mGeneralExpensesRow = 0;
int bcExpensesRow = 0;
double mBCExpensesRow = 0;
int cmExpensesRow = 0;
double mCMExpensesRow = 0;
double mTotalBCExpensesRow = 0;
double mTotalCMExpensesRow = 0;
double bankPaymentSum = 0;
int number = 1;
List<Flat> flatList = flatService.getFlatsFromOrderedFlatTable();
Iterator<Flat> itr = flatList.iterator();
while (itr.hasNext()) {
Flat flatFromList = itr.next();
Flat flatFromBuyerTable = flatService.getFlatByFlatIdFromFlatBuyerTable(flatFromList.getIdFlatTable());
int expensesGeneral = flatService
.getExpensesFlatInfoFromExpensesTableByFlatId(flatFromList.getIdFlatTable(), generalExpenses);
int expensesBC = flatService.getExpensesFlatInfoFromExpensesTableByFlatId(flatFromList.getIdFlatTable(),
bcExpenses);
int expensesCM = flatService.getExpensesFlatInfoFromExpensesTableByFlatId(flatFromList.getIdFlatTable(),
cmExpenses);
double paymentSum = flatService.getPaymentSumFromBankTableByFlatTableId(flatFromList.getIdFlatTable());
double flatCost_m$ = flatFromBuyerTable.getFlatCost() / flatFromList.getFlatArea();
if (flatCost_m$ == 0) {
flatCost_m$ = 0.000000001;
}
int expenses = expensesGeneral + expensesBC + expensesCM;
int availableSum = flatFromBuyerTable.getFlatCost() - expenses;
flatArea = flatArea + flatFromList.getFlatArea();
flatCost = flatCost + flatFromBuyerTable.getFlatCost();
expensesRow = expensesRow + expenses;
availableSumRow = availableSumRow + availableSum;
mAvailableSumRow = mAvailableSumRow + availableSum / flatCost_m$;
generalExpensesRow = generalExpensesRow + expensesGeneral;
mGeneralExpensesRow = mGeneralExpensesRow + (expensesGeneral) / flatCost_m$;
bcExpensesRow = bcExpensesRow + expensesBC;
mBCExpensesRow = mBCExpensesRow + (expensesBC) / flatCost_m$;
cmExpensesRow = cmExpensesRow + expensesCM;
mCMExpensesRow = mCMExpensesRow + (expensesCM) / flatCost_m$;
mTotalBCExpensesRow = mTotalBCExpensesRow + (expensesBC / flatCost_m$)
+ (expensesGeneral / flatCost_m$ / 2);
mTotalCMExpensesRow = mTotalCMExpensesRow + (expensesCM / flatCost_m$)
+ (expensesGeneral / flatCost_m$ / 2);
bankPaymentSum = bankPaymentSum + paymentSum;
flatGrid.addRow(number, flatFromList.getIdFlatTable(), flatFromList.getBuildingCorps(),
flatFromList.getFlatRooms(), flatFromList.getFlatFloor(), flatFromList.getFlatNumber(),
flatFromList.getFlatArea(), flatFromList.getFlatSet(), flatFromBuyerTable.getFlatBuyerFirstname(),
flatFromBuyerTable.getFlatBuyerLastname(), flatFromBuyerTable.getFlatBuyerSurname(),
flatFromBuyerTable.getFlatNotes(), flatFromBuyerTable.getFlatContractDate(),
flatFromBuyerTable.getFlatContractNumber(), flatCost_m$, flatFromBuyerTable.getFlatCost(), expenses,
"Expenses", availableSum, availableSum / flatCost_m$, flatFromBuyerTable.getFlatSellerName(),
expensesGeneral, expensesGeneral / flatCost_m$, expensesBC, expensesBC / flatCost_m$,
expensesBC / flatCost_m$ + expensesGeneral / flatCost_m$ / 2, expensesCM, expensesCM / flatCost_m$,
expensesCM / flatCost_m$ + expensesGeneral / flatCost_m$ / 2, paymentSum,
paymentSum / flatFromList.getFlatArea());
number++;
}
FooterRow flatGridFooterRow = flatGrid.getFooterRow(0);
flatGridFooterRow.getCell("buildingCorps").setText("Total:");
flatGridFooterRow.getCell("flatArea").setText(decimalFormat.format(flatArea));
flatGridFooterRow.getCell("$, flatCost").setText(decimalFormat.format(flatCost));
flatGridFooterRow.getCell("$, expenses").setText(decimalFormat.format(expensesRow));
flatGridFooterRow.getCell("$, availableSum").setText(decimalFormat.format(availableSumRow));
flatGridFooterRow.getCell("m2, availableSum").setText(decimalFormat.format(mAvailableSumRow));
flatGridFooterRow.getCell("$, 50/50GeneralExpenses").setText(decimalFormat.format(generalExpensesRow));
flatGridFooterRow.getCell("m2, 50/50GeneralExpenses").setText(decimalFormat.format(mGeneralExpensesRow));
flatGridFooterRow.getCell("$, BCExpenses").setText(decimalFormat.format(bcExpensesRow));
flatGridFooterRow.getCell("m2, BCExpenses").setText(decimalFormat.format(mBCExpensesRow));
flatGridFooterRow.getCell("m2, totalBCExpenses").setText(decimalFormat.format(mTotalBCExpensesRow) + "m2"
+ ", left - " + decimalFormat.format(flatArea * 70 / 100 - mTotalBCExpensesRow) + "m2");
flatGridFooterRow.getCell("$, CMExpenses").setText(decimalFormat.format(cmExpensesRow));
flatGridFooterRow.getCell("m2, CMExpenses").setText(decimalFormat.format(mCMExpensesRow));
flatGridFooterRow.getCell("m2, totalCMExpenses").setText(decimalFormat.format(mTotalCMExpensesRow) + "m2"
+ ", left - " + decimalFormat.format(flatArea * 30 / 100 - mTotalCMExpensesRow) + "m2");
flatGridFooterRow.getCell("bankPaymentSum").setText(decimalFormat.format(bankPaymentSum));
}
}
|
UTF-8
|
Java
| 5,820 |
java
|
UpdateAccountingFlatGrid.java
|
Java
|
[] | null |
[] |
package com.example.Vaadin7_Builder.view.AccountingViewServises;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import com.example.Vaadin7_Builder.model.Flat;
import com.example.Vaadin7_Builder.service.FlatService;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.FooterRow;
public class UpdateAccountingFlatGrid {
FlatService flatService = new FlatService();
private DecimalFormat decimalFormat = new DecimalFormat("0.00");
private String generalExpenses = "General";
private String bcExpenses = "B.C.";
private String cmExpenses = "C.M.";
public void updateAccountingFlatGrid(Grid flatGrid)
throws SQLException {
flatGrid.getContainerDataSource().removeAllItems();
double flatArea = 0;
int flatCost = 0;
int expensesRow = 0;
int availableSumRow = 0;
double mAvailableSumRow = 0;
int generalExpensesRow = 0;
double mGeneralExpensesRow = 0;
int bcExpensesRow = 0;
double mBCExpensesRow = 0;
int cmExpensesRow = 0;
double mCMExpensesRow = 0;
double mTotalBCExpensesRow = 0;
double mTotalCMExpensesRow = 0;
double bankPaymentSum = 0;
int number = 1;
List<Flat> flatList = flatService.getFlatsFromOrderedFlatTable();
Iterator<Flat> itr = flatList.iterator();
while (itr.hasNext()) {
Flat flatFromList = itr.next();
Flat flatFromBuyerTable = flatService.getFlatByFlatIdFromFlatBuyerTable(flatFromList.getIdFlatTable());
int expensesGeneral = flatService
.getExpensesFlatInfoFromExpensesTableByFlatId(flatFromList.getIdFlatTable(), generalExpenses);
int expensesBC = flatService.getExpensesFlatInfoFromExpensesTableByFlatId(flatFromList.getIdFlatTable(),
bcExpenses);
int expensesCM = flatService.getExpensesFlatInfoFromExpensesTableByFlatId(flatFromList.getIdFlatTable(),
cmExpenses);
double paymentSum = flatService.getPaymentSumFromBankTableByFlatTableId(flatFromList.getIdFlatTable());
double flatCost_m$ = flatFromBuyerTable.getFlatCost() / flatFromList.getFlatArea();
if (flatCost_m$ == 0) {
flatCost_m$ = 0.000000001;
}
int expenses = expensesGeneral + expensesBC + expensesCM;
int availableSum = flatFromBuyerTable.getFlatCost() - expenses;
flatArea = flatArea + flatFromList.getFlatArea();
flatCost = flatCost + flatFromBuyerTable.getFlatCost();
expensesRow = expensesRow + expenses;
availableSumRow = availableSumRow + availableSum;
mAvailableSumRow = mAvailableSumRow + availableSum / flatCost_m$;
generalExpensesRow = generalExpensesRow + expensesGeneral;
mGeneralExpensesRow = mGeneralExpensesRow + (expensesGeneral) / flatCost_m$;
bcExpensesRow = bcExpensesRow + expensesBC;
mBCExpensesRow = mBCExpensesRow + (expensesBC) / flatCost_m$;
cmExpensesRow = cmExpensesRow + expensesCM;
mCMExpensesRow = mCMExpensesRow + (expensesCM) / flatCost_m$;
mTotalBCExpensesRow = mTotalBCExpensesRow + (expensesBC / flatCost_m$)
+ (expensesGeneral / flatCost_m$ / 2);
mTotalCMExpensesRow = mTotalCMExpensesRow + (expensesCM / flatCost_m$)
+ (expensesGeneral / flatCost_m$ / 2);
bankPaymentSum = bankPaymentSum + paymentSum;
flatGrid.addRow(number, flatFromList.getIdFlatTable(), flatFromList.getBuildingCorps(),
flatFromList.getFlatRooms(), flatFromList.getFlatFloor(), flatFromList.getFlatNumber(),
flatFromList.getFlatArea(), flatFromList.getFlatSet(), flatFromBuyerTable.getFlatBuyerFirstname(),
flatFromBuyerTable.getFlatBuyerLastname(), flatFromBuyerTable.getFlatBuyerSurname(),
flatFromBuyerTable.getFlatNotes(), flatFromBuyerTable.getFlatContractDate(),
flatFromBuyerTable.getFlatContractNumber(), flatCost_m$, flatFromBuyerTable.getFlatCost(), expenses,
"Expenses", availableSum, availableSum / flatCost_m$, flatFromBuyerTable.getFlatSellerName(),
expensesGeneral, expensesGeneral / flatCost_m$, expensesBC, expensesBC / flatCost_m$,
expensesBC / flatCost_m$ + expensesGeneral / flatCost_m$ / 2, expensesCM, expensesCM / flatCost_m$,
expensesCM / flatCost_m$ + expensesGeneral / flatCost_m$ / 2, paymentSum,
paymentSum / flatFromList.getFlatArea());
number++;
}
FooterRow flatGridFooterRow = flatGrid.getFooterRow(0);
flatGridFooterRow.getCell("buildingCorps").setText("Total:");
flatGridFooterRow.getCell("flatArea").setText(decimalFormat.format(flatArea));
flatGridFooterRow.getCell("$, flatCost").setText(decimalFormat.format(flatCost));
flatGridFooterRow.getCell("$, expenses").setText(decimalFormat.format(expensesRow));
flatGridFooterRow.getCell("$, availableSum").setText(decimalFormat.format(availableSumRow));
flatGridFooterRow.getCell("m2, availableSum").setText(decimalFormat.format(mAvailableSumRow));
flatGridFooterRow.getCell("$, 50/50GeneralExpenses").setText(decimalFormat.format(generalExpensesRow));
flatGridFooterRow.getCell("m2, 50/50GeneralExpenses").setText(decimalFormat.format(mGeneralExpensesRow));
flatGridFooterRow.getCell("$, BCExpenses").setText(decimalFormat.format(bcExpensesRow));
flatGridFooterRow.getCell("m2, BCExpenses").setText(decimalFormat.format(mBCExpensesRow));
flatGridFooterRow.getCell("m2, totalBCExpenses").setText(decimalFormat.format(mTotalBCExpensesRow) + "m2"
+ ", left - " + decimalFormat.format(flatArea * 70 / 100 - mTotalBCExpensesRow) + "m2");
flatGridFooterRow.getCell("$, CMExpenses").setText(decimalFormat.format(cmExpensesRow));
flatGridFooterRow.getCell("m2, CMExpenses").setText(decimalFormat.format(mCMExpensesRow));
flatGridFooterRow.getCell("m2, totalCMExpenses").setText(decimalFormat.format(mTotalCMExpensesRow) + "m2"
+ ", left - " + decimalFormat.format(flatArea * 30 / 100 - mTotalCMExpensesRow) + "m2");
flatGridFooterRow.getCell("bankPaymentSum").setText(decimalFormat.format(bankPaymentSum));
}
}
| 5,820 | 0.7689 | 0.757732 | 124 | 45.935482 | 35.614819 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.040323 | false | false |
3
|
16dfec5df6f161370a21b5f513993f88d53877f4
| 2,078,764,221,081 |
722991afb22c276c4954c1bf177fc4b1878f8d45
|
/src/scene/report/ReportController.java
|
3c878e5d4958139b22ac47cd19df08d1e85413db
|
[] |
no_license
|
DylanTanZ/organizer
|
https://github.com/DylanTanZ/organizer
|
aace29e4a09b99a5895eb44e3ac2427054244acd
|
2a6009771e8f0e4aef079fea255bcf8520526016
|
refs/heads/master
| 2021-01-23T01:51:09.649000 | 2017-08-03T07:08:57 | 2017-08-03T07:08:57 | 95,512,864 | 0 | 0 | null | true | 2017-06-27T03:16:49 | 2017-06-27T03:16:49 | 2017-05-31T03:23:35 | 2017-06-13T03:00:36 | 9,331 | 0 | 0 | 0 | null | null | null |
package scene.report;
import scene.survey.SurveyQn;
import javafx.fxml.Initializable;
import resources.database.DB;
import javax.sql.rowset.CachedRowSet;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ResourceBundle;
/**
* Created by User on 1/8/2017.
*/
public class ReportController implements Initializable{
ArrayList<SurveyQn> dataList;
@Override
public void initialize(URL location, ResourceBundle resources) {
CachedRowSet data=DB.read("select * from surveyTable ");
try {
while(data.next()){
SurveyQn sq=new SurveyQn();
sq.setId(data.getInt("id"));
// get eventrate
sq.setEventRate(data.RATE("Question1"));
//get venueRate
sq.setVenueRate(data.getRATE("Question2"));
//he
sq.setAns4(data.getString("Question4"));
sq.setAns5(data.getString("Question5"));
// ,data.getString(1),data.getString(2),
// data.getString(0));
dataList.add(sq);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,286 |
java
|
ReportController.java
|
Java
|
[] | null |
[] |
package scene.report;
import scene.survey.SurveyQn;
import javafx.fxml.Initializable;
import resources.database.DB;
import javax.sql.rowset.CachedRowSet;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ResourceBundle;
/**
* Created by User on 1/8/2017.
*/
public class ReportController implements Initializable{
ArrayList<SurveyQn> dataList;
@Override
public void initialize(URL location, ResourceBundle resources) {
CachedRowSet data=DB.read("select * from surveyTable ");
try {
while(data.next()){
SurveyQn sq=new SurveyQn();
sq.setId(data.getInt("id"));
// get eventrate
sq.setEventRate(data.RATE("Question1"));
//get venueRate
sq.setVenueRate(data.getRATE("Question2"));
//he
sq.setAns4(data.getString("Question4"));
sq.setAns5(data.getString("Question5"));
// ,data.getString(1),data.getString(2),
// data.getString(0));
dataList.add(sq);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 1,286 | 0.559876 | 0.548212 | 46 | 25.956522 | 20.451382 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
3
|
c7a6d2d99d74f484e498916e02ed9ec00b603f22
| 31,593,779,489,710 |
c5fb0c020bd5e555aeeb5c750d9d978e96256b17
|
/linjiashop-mobile-api/src/main/java/cn/enilu/flash/mobile/controller/UserController.java
|
fcef71a96e1f353c71e5f702d442b3cd2d33aa45
|
[
"MIT"
] |
permissive
|
liu-peiyu/linjiashop
|
https://github.com/liu-peiyu/linjiashop
|
6ef8c65869ea62af14f8ca2ffe71663ad821d76a
|
2859b724746ddf213a0e04ff9763acebed537d69
|
refs/heads/master
| 2020-11-30T09:45:55.908000 | 2019-12-27T08:20:35 | 2019-12-27T08:20:35 | 230,368,107 | 1 | 0 |
MIT
| true | 2019-12-27T03:41:23 | 2019-12-27T03:41:22 | 2019-12-27T03:36:22 | 2019-12-26T09:40:27 | 13,297 | 0 | 0 | 0 | null | false | false |
package cn.enilu.flash.mobile.controller;
import cn.enilu.flash.bean.entity.shop.ShopUser;
import cn.enilu.flash.bean.vo.UserInfo;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.shop.ShopUserService;
import cn.enilu.flash.web.controller.BaseController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :enilu
* @date :Created in 11/6/2019 4:20 PM
*/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private ShopUserService shopUserService;
@RequestMapping(value = "/getInfo",method = RequestMethod.GET)
public Object getInfo(){
String token = getToken();
Long idUser = JwtUtil.getUserId(token);
ShopUser shopUser = shopUserService.get(idUser);
UserInfo userInfo = new UserInfo();
BeanUtils.copyProperties(shopUser,userInfo);
return Rets.success(shopUser);
}
}
|
UTF-8
|
Java
| 1,219 |
java
|
UserController.java
|
Java
|
[
{
"context": ".bind.annotation.RestController;\n\n/**\n * @author :enilu\n * @date :Created in 11/6/2019 4:20 PM\n */\n@RestC",
"end": 636,
"score": 0.9997014403343201,
"start": 631,
"tag": "USERNAME",
"value": "enilu"
}
] | null |
[] |
package cn.enilu.flash.mobile.controller;
import cn.enilu.flash.bean.entity.shop.ShopUser;
import cn.enilu.flash.bean.vo.UserInfo;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.shop.ShopUserService;
import cn.enilu.flash.web.controller.BaseController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :enilu
* @date :Created in 11/6/2019 4:20 PM
*/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private ShopUserService shopUserService;
@RequestMapping(value = "/getInfo",method = RequestMethod.GET)
public Object getInfo(){
String token = getToken();
Long idUser = JwtUtil.getUserId(token);
ShopUser shopUser = shopUserService.get(idUser);
UserInfo userInfo = new UserInfo();
BeanUtils.copyProperties(shopUser,userInfo);
return Rets.success(shopUser);
}
}
| 1,219 | 0.762963 | 0.754732 | 33 | 35.81818 | 20.555107 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false |
3
|
9d0d1841466ee32bd8888565a3a6d7404c987b73
| 32,873,679,748,028 |
c8ee6fc67d3c1e55e1bd81f2089004ded8902bae
|
/cw-app-biz/src/main/java/com/cw/biz/common/dto/BaseDto.java
|
af9c2ad37c53990f71491e83218fa71bbdbfdac2
|
[] |
no_license
|
Away-Leo/cw-app
|
https://github.com/Away-Leo/cw-app
|
3f08e69355b8dbda10c36b606ae22f518df07ba7
|
034dfe5534ace27e75e2af680d4e43c95758672e
|
refs/heads/master
| 2022-10-26T21:19:36.461000 | 2019-08-10T21:21:38 | 2019-08-10T21:21:38 | 196,578,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cw.biz.common.dto;
import java.io.Serializable;
/**
*
*/
public class BaseDto implements Serializable {
}
|
UTF-8
|
Java
| 123 |
java
|
BaseDto.java
|
Java
|
[] | null |
[] |
package com.cw.biz.common.dto;
import java.io.Serializable;
/**
*
*/
public class BaseDto implements Serializable {
}
| 123 | 0.715447 | 0.715447 | 10 | 11.3 | 15.956503 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
3
|
58dbe9e3f6b546c60d0b14d8bd5e33f8b5a0976f
| 2,903,397,893,557 |
e564d39ec9a0f7ec090294a57499d84081016d9a
|
/src/main/java/tamedia_hiring_challenge/id_counter/HllCounter.java
|
63a3156f00bc63b46bc90b8e5f92663a2259bf03
|
[
"Apache-2.0"
] |
permissive
|
ciric92/kafka-challenge
|
https://github.com/ciric92/kafka-challenge
|
badf99e43f18345573c8dd35a254dcf31f5fb420
|
2affc4b77d2d8f6e66dcc1b48b998e5c92ca47cc
|
refs/heads/master
| 2017-09-12T11:40:26.612000 | 2017-07-17T20:25:51 | 2017-07-17T20:25:51 | 96,539,891 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tamedia_hiring_challenge.id_counter;
import java.nio.charset.Charset;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import net.agkn.hll.HLL;
public class HllCounter implements Counter {
private HLL hll = new HLL(13, 5);
@Override
public void addToCount(String id) {
Hasher hash = Hashing.murmur3_128().newHasher();
hash.putString(id, Charset.defaultCharset());
hll.addRaw(hash.hash().asLong());
}
@Override
public long getCount() {
return hll.cardinality();
}
@Override
public void reset() {
hll = new HLL(13, 5);
}
}
|
UTF-8
|
Java
| 588 |
java
|
HllCounter.java
|
Java
|
[] | null |
[] |
package tamedia_hiring_challenge.id_counter;
import java.nio.charset.Charset;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import net.agkn.hll.HLL;
public class HllCounter implements Counter {
private HLL hll = new HLL(13, 5);
@Override
public void addToCount(String id) {
Hasher hash = Hashing.murmur3_128().newHasher();
hash.putString(id, Charset.defaultCharset());
hll.addRaw(hash.hash().asLong());
}
@Override
public long getCount() {
return hll.cardinality();
}
@Override
public void reset() {
hll = new HLL(13, 5);
}
}
| 588 | 0.712585 | 0.695578 | 31 | 17.967741 | 17.362331 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.16129 | false | false |
3
|
526c7615278ce44dcbfd2a7960f5cb15c5aa8d90
| 4,389,456,643,654 |
9acd2fbed9717c0a5bcb1d467e2b4c57bb505b61
|
/system-web/src/main/java/com/lwb/result/RestResult.java
|
42fbc2a559668b6446dce8e4967d96e22bef7544
|
[
"Apache-2.0"
] |
permissive
|
06112497liu/framework-learn
|
https://github.com/06112497liu/framework-learn
|
42aca0c1163b1fa086f74daeb19dbe6da0b6da21
|
4d3174a44718bf5aea27a1cdd03ac47150ab4797
|
refs/heads/master
| 2021-04-09T17:02:54.139000 | 2018-05-09T07:14:54 | 2018-05-09T07:15:15 | 125,689,612 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lwb.result;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* @author liuweibo
* @date 2018/5/3
*/
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class RestResult<T> {
public static final int CODE_SUCCESS = 200;
public String msg = "";
private int status;
private T data;
public long responseTime = System.currentTimeMillis();
public RestResult() {
this.status = 200;
this.msg = "ok";
}
public RestResult(T data) {
this.status = 200;
this.msg = "ok";
this.data = data;
}
public RestResult(int status, String msg) {
this.status = status;
this.msg = msg;
}
public RestResult(int status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public static RestResult ok() {
return new RestResult();
}
public static RestResult ok(Object data) {
return new RestResult(data);
}
public static RestResult fail(int status, String message) {
return new RestResult(status, message);
}
public static RestResult fail(int status, String message, Object data) {
return new RestResult(status, message, data);
}
public static int getCodeSuccess() {
return CODE_SUCCESS;
}
public long getResponseTime() {
return responseTime;
}
public void setResponseTime(long responseTime) {
this.responseTime = responseTime;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
UTF-8
|
Java
| 1,901 |
java
|
RestResult.java
|
Java
|
[
{
"context": "ml.jackson.annotation.JsonInclude;\n\n/**\n * @author liuweibo\n * @date 2018/5/3\n */\n@JsonInclude(value = JsonIn",
"end": 103,
"score": 0.9994497299194336,
"start": 95,
"tag": "USERNAME",
"value": "liuweibo"
}
] | null |
[] |
package com.lwb.result;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* @author liuweibo
* @date 2018/5/3
*/
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class RestResult<T> {
public static final int CODE_SUCCESS = 200;
public String msg = "";
private int status;
private T data;
public long responseTime = System.currentTimeMillis();
public RestResult() {
this.status = 200;
this.msg = "ok";
}
public RestResult(T data) {
this.status = 200;
this.msg = "ok";
this.data = data;
}
public RestResult(int status, String msg) {
this.status = status;
this.msg = msg;
}
public RestResult(int status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public static RestResult ok() {
return new RestResult();
}
public static RestResult ok(Object data) {
return new RestResult(data);
}
public static RestResult fail(int status, String message) {
return new RestResult(status, message);
}
public static RestResult fail(int status, String message, Object data) {
return new RestResult(status, message, data);
}
public static int getCodeSuccess() {
return CODE_SUCCESS;
}
public long getResponseTime() {
return responseTime;
}
public void setResponseTime(long responseTime) {
this.responseTime = responseTime;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
| 1,901 | 0.594424 | 0.586533 | 96 | 18.802084 | 18.44791 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40625 | false | false |
3
|
0e24f94864afbb5bab7ad7cda3e0f261ddda8807
| 7,524,782,764,311 |
05a480070571b04e00a436dfeae753f79e827e86
|
/src/main/java/com/patterns/structural/proxy/example1/Image.java
|
03df5e294760888e1a15c708ed3663983caca10e
|
[] |
no_license
|
sashamartian/PatternsInJava
|
https://github.com/sashamartian/PatternsInJava
|
e1326d572224e5b42b0816633c0632995605ddd3
|
559dd315bb97957f06648b00caf8fec46ad95819
|
refs/heads/master
| 2020-04-05T22:57:48.762000 | 2016-11-01T10:00:36 | 2016-11-01T10:00:36 | 68,100,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main.java.com.patterns.structural.proxy.example1;
public interface Image {
void display();
}
|
UTF-8
|
Java
| 106 |
java
|
Image.java
|
Java
|
[] | null |
[] |
package main.java.com.patterns.structural.proxy.example1;
public interface Image {
void display();
}
| 106 | 0.754717 | 0.745283 | 5 | 20.200001 | 20.721004 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
3
|
27d9f17f95d7646be7abe43ea7faf735332341bc
| 21,801,254,047,243 |
175b70523df076bb377f9acbc58697ba4186fedb
|
/SPM_Project/src/enums/Day.java
|
2dfc3e275ac9c8809a293c6e853fbf4b910a0647
|
[] |
no_license
|
samesh97/SPM_Project
|
https://github.com/samesh97/SPM_Project
|
56d4ffda838cf002b443487783317283a00dbdde
|
545d180d2570f1a9f95c4c4ba682fca9bed6f3ba
|
refs/heads/master
| 2023-01-29T12:14:55.330000 | 2020-10-02T15:07:14 | 2020-10-02T15:07:14 | 285,659,705 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package enums;
public class Day
{
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
public static final int SUNDAY = 7;
public static String getString(int day)
{
if(day == MONDAY)
{
return "Monday";
}
else if(day == TUESDAY)
{
return "Tuesday";
}
else if(day == WEDNESDAY)
{
return "Wednesday";
}
else if(day == THURSDAY)
{
return "Thursday";
}
else if(day == FRIDAY)
{
return "Friday";
}
else if(day == SATURDAY)
{
return "Saturday";
}
else if(day == SUNDAY)
{
return "Sunday";
}
else
{
return "";
}
}
}
|
UTF-8
|
Java
| 769 |
java
|
Day.java
|
Java
|
[] | null |
[] |
package enums;
public class Day
{
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
public static final int SUNDAY = 7;
public static String getString(int day)
{
if(day == MONDAY)
{
return "Monday";
}
else if(day == TUESDAY)
{
return "Tuesday";
}
else if(day == WEDNESDAY)
{
return "Wednesday";
}
else if(day == THURSDAY)
{
return "Thursday";
}
else if(day == FRIDAY)
{
return "Friday";
}
else if(day == SATURDAY)
{
return "Saturday";
}
else if(day == SUNDAY)
{
return "Sunday";
}
else
{
return "";
}
}
}
| 769 | 0.607282 | 0.598179 | 50 | 14.38 | 13.275375 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.04 | false | false |
3
|
c7cbf5317c2e1a4d950d27362190e3ac4fcfaff8
| 26,001,732,074,905 |
229c3f35d0fbf8ff00ad6057717672b6e342fd9c
|
/epl362/src/viewpoints/PatientSideEffects.java
|
40c2a08ac1c43a250cb29e991cc8969ff01ba50f
|
[] |
no_license
|
Gkyrli01/WebService
|
https://github.com/Gkyrli01/WebService
|
504d19b354edc76f717129222dd0908ba6464a74
|
a8d2ada8802866c975dff38c90e0a8a01da50078
|
refs/heads/master
| 2021-01-20T06:43:11.650000 | 2017-05-11T13:26:43 | 2017-05-11T13:26:43 | 89,914,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package viewpoints;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PatientSideEffects")
public class PatientSideEffects {
@XmlElement(name="patient")
public Patient patient;
@XmlElement(name="sideEffect")
public SideEffect sideEffect;
public PatientSideEffects(int patientId,String sideEffect) {
patient=Patient.returnPatientById(patientId);
this.sideEffect=new SideEffect(sideEffect);
}
public static String select="SELECT * FROM [webService].[dbo].[PatientSideEffects]";
public static String delete="DELETE FROM [webService].[dbo].[PatientSideEffects]";
/**
* Shouldn't be used.
* @param sideEffectName
* @param patientId
* @return
*/
public static PatientSideEffects returnPatientSideEffectsById(String sideEffectName ,int patientId) {
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select+" WHERE SideEffectName='"+sideEffectName+"' AND patientId="+patientId);
try {
return new PatientSideEffects(pop.getInt(1),pop.getString(2));
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns a patient's side effects.
* @param id
* @return
*/
public static PatientSideEffects[] returnPatientSideEffectsByPatient(int id) {
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select+" WHERE patientId="+id);
ArrayList<PatientSideEffects>arras=new ArrayList<PatientSideEffects>();
try {
pop.first();
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
while(pop.next()){
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
PatientSideEffects[] zwa=new PatientSideEffects[arras.size()];
int i=0;
for (PatientSideEffects doctor : arras) {
zwa[i]=doctor;
i++;
}
return zwa;
}
/**
* Returns all patients sideeffects.
* @return
*/
public PatientSideEffects[] returnPatientSideEffects() {
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select);
ArrayList<PatientSideEffects>arras=new ArrayList<PatientSideEffects>();
try {
pop.first();
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
while(pop.next()){
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
PatientSideEffects[] zwa=new PatientSideEffects[arras.size()];
int i=0;
for (PatientSideEffects doctor : arras) {
zwa[i]=doctor;
i++;
}
return zwa;
}
public int booleanToInt(boolean what) {
if(what){
return 1;
}
return 0;
}
public int checkNull(Object what) {
if(what==null){
return -1;
}
return 0;
}
/**
* Inserts a patient sideeffect.
* @return
*/
public boolean insert(){
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select);
try {
pop.moveToInsertRow();
pop.updateString(2, sideEffect.name);
pop.updateInt(1, patient.id);
pop.insertRow();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
//return "INSERT INTO Doctor VALUES ('"+doctorName+"')";
}
public PatientSideEffects() {
// TODO Auto-generated constructor stub
}
public void delete(){
GetConnection ok=new GetConnection();
ok.getDBConnection();
ok.delete(delete+" WHERE SideEffectName='"+sideEffect.name+"' AND patientId="+patient.id);
}
/*
public static void main(String[] args) {
PatientSideEffects ok=new PatientSideEffects();
ok.returnPatientSideEffectsByPatient(3);
}*/
/*
public static void main(String[] args) {
PatientSideEffects ola=new PatientSideEffects(3, "psuxas");
//ola.insert();
//System.out.println(ola.returnPatientSideEffects()[0].patient.Description);
//ola.delete();
}*/
}
|
UTF-8
|
Java
| 4,386 |
java
|
PatientSideEffects.java
|
Java
|
[] | null |
[] |
package viewpoints;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PatientSideEffects")
public class PatientSideEffects {
@XmlElement(name="patient")
public Patient patient;
@XmlElement(name="sideEffect")
public SideEffect sideEffect;
public PatientSideEffects(int patientId,String sideEffect) {
patient=Patient.returnPatientById(patientId);
this.sideEffect=new SideEffect(sideEffect);
}
public static String select="SELECT * FROM [webService].[dbo].[PatientSideEffects]";
public static String delete="DELETE FROM [webService].[dbo].[PatientSideEffects]";
/**
* Shouldn't be used.
* @param sideEffectName
* @param patientId
* @return
*/
public static PatientSideEffects returnPatientSideEffectsById(String sideEffectName ,int patientId) {
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select+" WHERE SideEffectName='"+sideEffectName+"' AND patientId="+patientId);
try {
return new PatientSideEffects(pop.getInt(1),pop.getString(2));
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns a patient's side effects.
* @param id
* @return
*/
public static PatientSideEffects[] returnPatientSideEffectsByPatient(int id) {
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select+" WHERE patientId="+id);
ArrayList<PatientSideEffects>arras=new ArrayList<PatientSideEffects>();
try {
pop.first();
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
while(pop.next()){
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
PatientSideEffects[] zwa=new PatientSideEffects[arras.size()];
int i=0;
for (PatientSideEffects doctor : arras) {
zwa[i]=doctor;
i++;
}
return zwa;
}
/**
* Returns all patients sideeffects.
* @return
*/
public PatientSideEffects[] returnPatientSideEffects() {
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select);
ArrayList<PatientSideEffects>arras=new ArrayList<PatientSideEffects>();
try {
pop.first();
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
while(pop.next()){
arras.add(new PatientSideEffects(pop.getInt(1),pop.getString(2)));
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
PatientSideEffects[] zwa=new PatientSideEffects[arras.size()];
int i=0;
for (PatientSideEffects doctor : arras) {
zwa[i]=doctor;
i++;
}
return zwa;
}
public int booleanToInt(boolean what) {
if(what){
return 1;
}
return 0;
}
public int checkNull(Object what) {
if(what==null){
return -1;
}
return 0;
}
/**
* Inserts a patient sideeffect.
* @return
*/
public boolean insert(){
GetConnection ok=new GetConnection();
ok.getDBConnection();
ResultSet pop=ok.select(select);
try {
pop.moveToInsertRow();
pop.updateString(2, sideEffect.name);
pop.updateInt(1, patient.id);
pop.insertRow();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
//return "INSERT INTO Doctor VALUES ('"+doctorName+"')";
}
public PatientSideEffects() {
// TODO Auto-generated constructor stub
}
public void delete(){
GetConnection ok=new GetConnection();
ok.getDBConnection();
ok.delete(delete+" WHERE SideEffectName='"+sideEffect.name+"' AND patientId="+patient.id);
}
/*
public static void main(String[] args) {
PatientSideEffects ok=new PatientSideEffects();
ok.returnPatientSideEffectsByPatient(3);
}*/
/*
public static void main(String[] args) {
PatientSideEffects ola=new PatientSideEffects(3, "psuxas");
//ola.insert();
//System.out.println(ola.returnPatientSideEffects()[0].patient.Description);
//ola.delete();
}*/
}
| 4,386 | 0.678751 | 0.673963 | 167 | 24.263474 | 23.640574 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.179641 | false | false |
3
|
2fad42708460be8acd61323f286a668d19bdbb85
| 2,817,498,603,738 |
5e07551956e46b68a46c1f867d5279af14416de5
|
/main/src/main/java/com/github/sergeioff/mathematicalExpressionParser/main/Main.java
|
bf03cac80da58926604a7b2b2ffc5366dfe42f4b
|
[] |
no_license
|
sergeioff/mathematicalExpressionParser
|
https://github.com/sergeioff/mathematicalExpressionParser
|
651eacb3022ee3b582cff65bb97777cbc8ead0dc
|
6ed296e9816b052e09bbf0caf3561e4466fedb8d
|
refs/heads/master
| 2021-01-11T01:33:00.203000 | 2016-10-16T11:57:30 | 2016-10-16T11:57:30 | 70,691,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.sergeioff.mathematicalExpressionParser.main;
import com.github.sergeioff.mathematicalExpressionParser.parser.Parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Shows how to use mathematical com.github.sergeioff.parser.
* @see Parser
* @author sergeioff
*/
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Hello! Enter mathematical expression:");
for (String line; !(line = reader.readLine()).equals("exit"); ) {
try {
Parser parser = new Parser(line);
System.out.printf("Result of parsing \"%s\":\n%.2f\n", parser.getLine(), parser.compute());
System.out.println("For exit enter \"exit\".");
System.out.println("Enter a new mathematical expression:");
} catch (IllegalArgumentException e) {
System.err.println("Not a valid line! Please re-enter.");
}
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
|
UTF-8
|
Java
| 1,243 |
java
|
Main.java
|
Java
|
[
{
"context": "package com.github.sergeioff.mathematicalExpressionParser.main;\n\nimport com.gi",
"end": 28,
"score": 0.9687848091125488,
"start": 19,
"tag": "USERNAME",
"value": "sergeioff"
},
{
"context": "ematicalExpressionParser.main;\n\nimport com.github.sergeioff.mathematicalExpressionParser.parser.Parser;\n\nimpo",
"end": 92,
"score": 0.9935460090637207,
"start": 83,
"tag": "USERNAME",
"value": "sergeioff"
},
{
"context": "github.sergeioff.parser.\n * @see Parser\n * @author sergeioff\n */\npublic class Main {\n public static void ma",
"end": 333,
"score": 0.9992753267288208,
"start": 324,
"tag": "USERNAME",
"value": "sergeioff"
}
] | null |
[] |
package com.github.sergeioff.mathematicalExpressionParser.main;
import com.github.sergeioff.mathematicalExpressionParser.parser.Parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Shows how to use mathematical com.github.sergeioff.parser.
* @see Parser
* @author sergeioff
*/
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Hello! Enter mathematical expression:");
for (String line; !(line = reader.readLine()).equals("exit"); ) {
try {
Parser parser = new Parser(line);
System.out.printf("Result of parsing \"%s\":\n%.2f\n", parser.getLine(), parser.compute());
System.out.println("For exit enter \"exit\".");
System.out.println("Enter a new mathematical expression:");
} catch (IllegalArgumentException e) {
System.err.println("Not a valid line! Please re-enter.");
}
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
| 1,243 | 0.608206 | 0.607401 | 32 | 37.84375 | 30.959761 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
a49b9079582ae8d2480c602f4c98bb14563f35cf
| 29,600,914,668,548 |
51d3c13e5bf6a546a01ac56d70fea5ce27a2f870
|
/src/MemFS/src/exposed/source/filesystem/contract/FolderParent.java
|
89ecc73dd99b7cb9bc267f5332ce796b8586acd7
|
[] |
no_license
|
startrunner/geekycamp-memfs
|
https://github.com/startrunner/geekycamp-memfs
|
d240e7050015e30800c734000800eef123905039
|
6feb56467a28a4cdafccae5b8a16c95722e48281
|
refs/heads/master
| 2020-03-27T20:36:05.769000 | 2018-09-03T09:31:22 | 2018-09-03T09:31:22 | 147,080,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package exposed.source.filesystem.contract;
import java.io.IOException;
import java.util.Iterator;
public interface FolderParent extends FileSystemEntry {
Iterator<Folder> iterateFolders() throws IOException;
Folder getFolder(String folderName, EntryDoesNotExistBehavior missingBehavior) throws IOException;
Folder getFolderOrNull(String relativePath) throws IOException;
boolean folderExists(String folderName);
}
|
UTF-8
|
Java
| 435 |
java
|
FolderParent.java
|
Java
|
[] | null |
[] |
package exposed.source.filesystem.contract;
import java.io.IOException;
import java.util.Iterator;
public interface FolderParent extends FileSystemEntry {
Iterator<Folder> iterateFolders() throws IOException;
Folder getFolder(String folderName, EntryDoesNotExistBehavior missingBehavior) throws IOException;
Folder getFolderOrNull(String relativePath) throws IOException;
boolean folderExists(String folderName);
}
| 435 | 0.818391 | 0.818391 | 13 | 32.46154 | 31.205561 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false |
3
|
c3b26572867943aae5c845bb6e17e13856c4fc18
| 2,542,620,662,026 |
f7692cd35315255fb23209a8cf144f665a507560
|
/api-framework/src/main/java/com/neoremind/apiframework/util/CollectionUtil.java
|
3f3f77d9dbe033d7945ef279acb74d13faa4b829
|
[
"Apache-2.0"
] |
permissive
|
neoremind/rest-api-framework
|
https://github.com/neoremind/rest-api-framework
|
24be8f416c977dfefe957f40a867ba99966f5124
|
4688df65cc1b4a90b08a0674770e31e4ba4e4ae3
|
refs/heads/master
| 2023-07-17T15:55:02.675000 | 2018-01-03T08:45:10 | 2018-01-03T08:45:10 | 116,081,094 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.neoremind.apiframework.util;
import com.neoremind.apiframework.able.Closure;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection utility
*
* @author xu.zhang
*/
public class CollectionUtil {
/**
* Executes the given closure on each element in the collection.
* <p>
* If the input collection or closure is null, there is no change made.
*
* @param collection the collection to get the input from, may be null
* @param closure the closure to perform, may be null
*/
public static void forAllDo(Collection collection, Closure closure) {
if (collection != null && closure != null) {
for (Iterator it = collection.iterator(); it.hasNext(); ) {
closure.execute(it.next());
}
}
}
/**
* Check if <code>Collection</code> is <code>null</code> or empty array<code>[]</code>。
*
* @param collection collection
* @return If empty return true
* @see Collection
*/
public static boolean isEmpty(Collection<?> collection) {
return (collection == null) || (collection.size() == 0);
}
}
|
UTF-8
|
Java
| 1,168 |
java
|
CollectionUtil.java
|
Java
|
[
{
"context": "Iterator;\n\n/**\n * Collection utility\n *\n * @author xu.zhang\n */\npublic class CollectionUtil {\n\n /**\n *",
"end": 196,
"score": 0.8627681136131287,
"start": 188,
"tag": "NAME",
"value": "xu.zhang"
}
] | null |
[] |
package com.neoremind.apiframework.util;
import com.neoremind.apiframework.able.Closure;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection utility
*
* @author xu.zhang
*/
public class CollectionUtil {
/**
* Executes the given closure on each element in the collection.
* <p>
* If the input collection or closure is null, there is no change made.
*
* @param collection the collection to get the input from, may be null
* @param closure the closure to perform, may be null
*/
public static void forAllDo(Collection collection, Closure closure) {
if (collection != null && closure != null) {
for (Iterator it = collection.iterator(); it.hasNext(); ) {
closure.execute(it.next());
}
}
}
/**
* Check if <code>Collection</code> is <code>null</code> or empty array<code>[]</code>。
*
* @param collection collection
* @return If empty return true
* @see Collection
*/
public static boolean isEmpty(Collection<?> collection) {
return (collection == null) || (collection.size() == 0);
}
}
| 1,168 | 0.620069 | 0.619211 | 41 | 27.439024 | 27.056444 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341463 | false | false |
3
|
045c6ecd2b80f3c1f5431085a50edb2f815101db
| 2,542,620,658,503 |
33c905ac06f8373fff3cc57f3c7df775a7bbfb98
|
/java/src/main/java/WeightedQuickUnion.java
|
8002ee186cbab400664953a116cb84402c28bfe3
|
[
"MIT"
] |
permissive
|
ezhilvendhan/algo
|
https://github.com/ezhilvendhan/algo
|
0cd1223fcf272e42f20d97e38a34738e0a83db1c
|
97b8996027ca954ae6fe557e7ebe594ca6dd653d
|
refs/heads/master
| 2021-01-23T07:27:14.233000 | 2015-10-07T06:11:40 | 2015-10-07T06:11:40 | 12,794,863 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class WeightedQuickUnion {
private int[] data;
private int[] size;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Input Size: ");
int size = scanner.nextInt();
WeightedQuickUnion wQu = new WeightedQuickUnion(size);
System.out.println("For union enter like: 2 3");
System.out.println("For isConnected enter like: is 2 3");
int x,y;
String[] tmp;
while(scanner.hasNext()) {
tmp = scanner.nextLine().split("\\s+");
if(tmp.length == 2) {
x = Integer.valueOf(tmp[0]);
y = Integer.valueOf(tmp[1]);
if(wQu.isValidInput(x, y)) {
if(!wQu.isConnected(x, y)) {
wQu.union(x, y);
System.out.println(x + " is now connected with " + y);
} else {
System.out.println(x + " is already connected with " + y);
}
} else {
System.out.println("Invalid input");
}
} else if(tmp.length == 3) {
x = Integer.valueOf(tmp[1]);
y = Integer.valueOf(tmp[2]);
if(wQu.isValidInput(x, y)) {
System.out.println(wQu.isConnected(x, y));
} else {
System.out.println("Invalid input");
}
}
}
}
public WeightedQuickUnion(int size) {
this.data = new int[size];
this.size = new int[size];
for(int idx = 0; idx < data.length; idx++) {
data[idx] = idx;
}
}
public int root(int x) {
while(data[x] != x) {
//Path Compression
//data[x] = data[data[x]];
x = data[x];
}
return x;
}
public boolean isConnected(int x, int y) {
return root(x) == root(y);
}
public void union(int x, int y) {
int rootOfX = root(x);
int rootOfY = root(y);
if(size[rootOfX] > size[rootOfY]) {
data[rootOfX] = rootOfY;
++size[rootOfY];
} else {
data[rootOfX] = rootOfY;
++size[rootOfX];
}
}
public boolean isValidInput(int x, int y) {
return (x < data.length && y < data.length);
}
}
|
UTF-8
|
Java
| 2,454 |
java
|
WeightedQuickUnion.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class WeightedQuickUnion {
private int[] data;
private int[] size;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Input Size: ");
int size = scanner.nextInt();
WeightedQuickUnion wQu = new WeightedQuickUnion(size);
System.out.println("For union enter like: 2 3");
System.out.println("For isConnected enter like: is 2 3");
int x,y;
String[] tmp;
while(scanner.hasNext()) {
tmp = scanner.nextLine().split("\\s+");
if(tmp.length == 2) {
x = Integer.valueOf(tmp[0]);
y = Integer.valueOf(tmp[1]);
if(wQu.isValidInput(x, y)) {
if(!wQu.isConnected(x, y)) {
wQu.union(x, y);
System.out.println(x + " is now connected with " + y);
} else {
System.out.println(x + " is already connected with " + y);
}
} else {
System.out.println("Invalid input");
}
} else if(tmp.length == 3) {
x = Integer.valueOf(tmp[1]);
y = Integer.valueOf(tmp[2]);
if(wQu.isValidInput(x, y)) {
System.out.println(wQu.isConnected(x, y));
} else {
System.out.println("Invalid input");
}
}
}
}
public WeightedQuickUnion(int size) {
this.data = new int[size];
this.size = new int[size];
for(int idx = 0; idx < data.length; idx++) {
data[idx] = idx;
}
}
public int root(int x) {
while(data[x] != x) {
//Path Compression
//data[x] = data[data[x]];
x = data[x];
}
return x;
}
public boolean isConnected(int x, int y) {
return root(x) == root(y);
}
public void union(int x, int y) {
int rootOfX = root(x);
int rootOfY = root(y);
if(size[rootOfX] > size[rootOfY]) {
data[rootOfX] = rootOfY;
++size[rootOfY];
} else {
data[rootOfX] = rootOfY;
++size[rootOfX];
}
}
public boolean isValidInput(int x, int y) {
return (x < data.length && y < data.length);
}
}
| 2,454 | 0.46414 | 0.459658 | 78 | 30.461538 | 19.224512 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602564 | false | false |
3
|
0b1d802e75e2d5cf6ceb169b326abae6ba306ccb
| 27,625,229,688,915 |
75a92fdc2ff44342f09e032cbd8411f6e85bf23b
|
/workspace-forms/payroll/src/main/java/net/hedtech/banner/payroll/Pdaflex/model/PdrflexAdapter.java
|
d3ae9b90474e666e758ecd480a86d3c07d7ff755
|
[] |
no_license
|
rosesun123/payroll
|
https://github.com/rosesun123/payroll
|
ccdcb071aa08872c50f47bbfa88a0c98dde927d9
|
b0b970e301d691ed75bd8047ba4adf7f2a6558c8
|
refs/heads/master
| 2017-11-09T09:08:59.426000 | 2015-10-23T10:35:33 | 2015-10-23T10:35:33 | 69,495,243 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.hedtech.banner.payroll.Pdaflex.model;
import java.util.Date;
import java.math.BigDecimal;
import org.jdesktop.databuffer.DataRow;
import morphis.foundations.core.appdatalayer.data.BaseRowAdapter;
import morphis.foundations.core.appdatalayer.data.DAO;
import morphis.foundations.core.appdatalayer.data.DbManager;
import morphis.foundations.core.types.*;
import morphis.foundations.core.appsupportlib.model.*;
import morphis.foundations.core.appdatalayer.data.configuration.*;
public class PdrflexAdapter extends BaseRowAdapter{
public PdrflexAdapter(DataRow row, IDBBusinessObject businessObject) {
super(row, businessObject);
}
//Data Columns
public void setPdrflexBdcaCode(NString value){
this.setValue("PDRFLEX_BDCA_CODE", value.getValue());
}
public NString getPdrflexBdcaCode(){
NString v = new NString((String)this.getValue("PDRFLEX_BDCA_CODE"));
return v;
}
public void setBdcaDesc(NString value){
this.setValue("BDCA_DESC", value.getValue());
}
public NString getBdcaDesc(){
NString v = new NString((String)this.getValue("BDCA_DESC"));
return v;
}
public void setPdrflexStartDate(NDate value){
this.setValue("PDRFLEX_START_DATE", value.getValue());
}
public NDate getPdrflexStartDate(){
NDate v = new NDate((Date)this.getValue("PDRFLEX_START_DATE"));
return v;
}
public void setPdrflexEndDate(NDate value){
this.setValue("PDRFLEX_END_DATE", value.getValue());
}
public NDate getPdrflexEndDate(){
NDate v = new NDate((Date)this.getValue("PDRFLEX_END_DATE"));
return v;
}
public void setPdrflexPlanCode(NString value){
this.setValue("PDRFLEX_PLAN_CODE", value.getValue());
}
public NString getPdrflexPlanCode(){
NString v = new NString((String)this.getValue("PDRFLEX_PLAN_CODE"));
return v;
}
public void setPlanDesc(NString value){
this.setValue("PLAN_DESC", value.getValue());
}
public NString getPlanDesc(){
NString v = new NString((String)this.getValue("PLAN_DESC"));
return v;
}
public void setPdrflexBdclCode(NString value){
this.setValue("PDRFLEX_BDCL_CODE", value.getValue());
}
public NString getPdrflexBdclCode(){
NString v = new NString((String)this.getValue("PDRFLEX_BDCL_CODE"));
return v;
}
public void setBdclDesc(NString value){
this.setValue("BDCL_DESC", value.getValue());
}
public NString getBdclDesc(){
NString v = new NString((String)this.getValue("BDCL_DESC"));
return v;
}
public void setPdrflexStatus(NString value){
this.setValue("PDRFLEX_STATUS", value.getValue());
}
public NString getPdrflexStatus(){
NString v = new NString((String)this.getValue("PDRFLEX_STATUS"));
return v;
}
public void setAmount1(NNumber value){
this.setValue("AMOUNT1", value.getValue());
}
public NNumber getAmount1(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT1"));
return v;
}
public void setAmount2(NNumber value){
this.setValue("AMOUNT2", value.getValue());
}
public NNumber getAmount2(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT2"));
return v;
}
public void setAmount3(NNumber value){
this.setValue("AMOUNT3", value.getValue());
}
public NNumber getAmount3(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT3"));
return v;
}
public void setAmount4(NNumber value){
this.setValue("AMOUNT4", value.getValue());
}
public NNumber getAmount4(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT4"));
return v;
}
public void setPdrflexPidm(NNumber value){
this.setValue("PDRFLEX_PIDM", value.getValue());
}
public NNumber getPdrflexPidm(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_PIDM"));
return v;
}
public void setPtrbdcaAmt1Ind(NString value){
this.setValue("PTRBDCA_AMT1_IND", value.getValue());
}
public NString getPtrbdcaAmt1Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT1_IND"));
return v;
}
public void setPtrbdcaAmt2Ind(NString value){
this.setValue("PTRBDCA_AMT2_IND", value.getValue());
}
public NString getPtrbdcaAmt2Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT2_IND"));
return v;
}
public void setPtrbdcaAmt3Ind(NString value){
this.setValue("PTRBDCA_AMT3_IND", value.getValue());
}
public NString getPtrbdcaAmt3Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT3_IND"));
return v;
}
public void setPtrbdcaAmt4Ind(NString value){
this.setValue("PTRBDCA_AMT4_IND", value.getValue());
}
public NString getPtrbdcaAmt4Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT4_IND"));
return v;
}
public void setPdrflexAmount1(NNumber value){
this.setValue("PDRFLEX_AMOUNT1", value.getValue());
}
public NNumber getPdrflexAmount1(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT1"));
return v;
}
public void setPdrflexAmount2(NNumber value){
this.setValue("PDRFLEX_AMOUNT2", value.getValue());
}
public NNumber getPdrflexAmount2(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT2"));
return v;
}
public void setPdrflexAmount3(NNumber value){
this.setValue("PDRFLEX_AMOUNT3", value.getValue());
}
public NNumber getPdrflexAmount3(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT3"));
return v;
}
public void setPdrflexAmount4(NNumber value){
this.setValue("PDRFLEX_AMOUNT4", value.getValue());
}
public NNumber getPdrflexAmount4(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT4"));
return v;
}
public void setPriorStatus(NString value){
this.setValue("PRIOR_STATUS", value.getValue());
}
public NString getPriorStatus(){
NString v = new NString((String)this.getValue("PRIOR_STATUS"));
return v;
}
public void setFlexAmt(NNumber value){
this.setValue("FLEX_AMT", value.getValue());
}
public NNumber getFlexAmt(){
NNumber v = new NNumber((BigDecimal)this.getValue("FLEX_AMT"));
return v;
}
public void setAmt1Title(NString value){
this.setValue("AMT1_TITLE", value.getValue());
}
public NString getAmt1Title(){
NString v = new NString((String)this.getValue("AMT1_TITLE"));
return v;
}
public void setAmt2Title(NString value){
this.setValue("AMT2_TITLE", value.getValue());
}
public NString getAmt2Title(){
NString v = new NString((String)this.getValue("AMT2_TITLE"));
return v;
}
public void setAmt3Title(NString value){
this.setValue("AMT3_TITLE", value.getValue());
}
public NString getAmt3Title(){
NString v = new NString((String)this.getValue("AMT3_TITLE"));
return v;
}
public void setAmt4Title(NString value){
this.setValue("AMT4_TITLE", value.getValue());
}
public NString getAmt4Title(){
NString v = new NString((String)this.getValue("AMT4_TITLE"));
return v;
}
public void setCalcFactor(NNumber value){
this.setValue("CALC_FACTOR", value.getValue());
}
public NNumber getCalcFactor(){
NNumber v = new NNumber((BigDecimal)this.getValue("CALC_FACTOR"));
return v;
}
public void setDednFreq(NNumber value){
this.setValue("DEDN_FREQ", value.getValue());
}
public NNumber getDednFreq(){
NNumber v = new NNumber((BigDecimal)this.getValue("DEDN_FREQ"));
return v;
}
public void setBeneAge(NInteger value){
this.setValue("BENE_AGE", value.getValue());
}
public NNumber getBeneAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("BENE_AGE"));
return v;
}
public void setPersAge(NInteger value){
this.setValue("PERS_AGE", value.getValue());
}
public NNumber getPersAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("PERS_AGE"));
return v;
}
public void setDepeAge(NInteger value){
this.setValue("DEPE_AGE", value.getValue());
}
public NNumber getDepeAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("DEPE_AGE"));
return v;
}
public void setEmplAge(NNumber value){
this.setValue("EMPL_AGE", value.getValue());
}
public NNumber getEmplAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("EMPL_AGE"));
return v;
}
public void setBdtyCode(NString value){
this.setValue("BDTY_CODE", value.getValue());
}
public NString getBdtyCode(){
NString v = new NString((String)this.getValue("BDTY_CODE"));
return v;
}
public void setPriorLife(NNumber value){
this.setValue("PRIOR_LIFE", value.getValue());
}
public NNumber getPriorLife(){
NNumber v = new NNumber((BigDecimal)this.getValue("PRIOR_LIFE"));
return v;
}
public void setCalcRule(NString value){
this.setValue("CALC_RULE", value.getValue());
}
public NString getCalcRule(){
NString v = new NString((String)this.getValue("CALC_RULE"));
return v;
}
public void setPtrbdcaOption1Ind(NString value){
this.setValue("PTRBDCA_OPTION1_IND", value.getValue());
}
public NString getPtrbdcaOption1Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_OPTION1_IND"));
return v;
}
public void setPdrflexApprInd(NString value){
this.setValue("PDRFLEX_APPR_IND", value.getValue());
}
public NString getPdrflexApprInd(){
NString v = new NString((String)this.getValue("PDRFLEX_APPR_IND"));
return v;
}
public void setPdrflexLifOvrUdrAmt(NNumber value){
this.setValue("PDRFLEX_LIF_OVR_UDR_AMT", value.getValue());
}
public NNumber getPdrflexLifOvrUdrAmt(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_LIF_OVR_UDR_AMT"));
return v;
}
public void setPdrflexActivityDate(NDate value){
this.setValue("PDRFLEX_ACTIVITY_DATE", value.getValue());
}
public NDate getPdrflexActivityDate(){
NDate v = new NDate((Date)this.getValue("PDRFLEX_ACTIVITY_DATE"));
return v;
}
public void setPdrflexProcessInd(NString value){
this.setValue("PDRFLEX_PROCESS_IND", value.getValue());
}
public NString getPdrflexProcessInd(){
NString v = new NString((String)this.getValue("PDRFLEX_PROCESS_IND"));
return v;
}
public void setROWID(byte[] bytes) {
this.setROWID(DbManager.getDataBaseFactory().createRowid(bytes));
}
public void setROWID(java.sql.RowId rowId) {
this.setValue(DAOConfiguration.MODEL_ROWID, rowId);
}
}
|
UTF-8
|
Java
| 10,290 |
java
|
PdrflexAdapter.java
|
Java
|
[] | null |
[] |
package net.hedtech.banner.payroll.Pdaflex.model;
import java.util.Date;
import java.math.BigDecimal;
import org.jdesktop.databuffer.DataRow;
import morphis.foundations.core.appdatalayer.data.BaseRowAdapter;
import morphis.foundations.core.appdatalayer.data.DAO;
import morphis.foundations.core.appdatalayer.data.DbManager;
import morphis.foundations.core.types.*;
import morphis.foundations.core.appsupportlib.model.*;
import morphis.foundations.core.appdatalayer.data.configuration.*;
public class PdrflexAdapter extends BaseRowAdapter{
public PdrflexAdapter(DataRow row, IDBBusinessObject businessObject) {
super(row, businessObject);
}
//Data Columns
public void setPdrflexBdcaCode(NString value){
this.setValue("PDRFLEX_BDCA_CODE", value.getValue());
}
public NString getPdrflexBdcaCode(){
NString v = new NString((String)this.getValue("PDRFLEX_BDCA_CODE"));
return v;
}
public void setBdcaDesc(NString value){
this.setValue("BDCA_DESC", value.getValue());
}
public NString getBdcaDesc(){
NString v = new NString((String)this.getValue("BDCA_DESC"));
return v;
}
public void setPdrflexStartDate(NDate value){
this.setValue("PDRFLEX_START_DATE", value.getValue());
}
public NDate getPdrflexStartDate(){
NDate v = new NDate((Date)this.getValue("PDRFLEX_START_DATE"));
return v;
}
public void setPdrflexEndDate(NDate value){
this.setValue("PDRFLEX_END_DATE", value.getValue());
}
public NDate getPdrflexEndDate(){
NDate v = new NDate((Date)this.getValue("PDRFLEX_END_DATE"));
return v;
}
public void setPdrflexPlanCode(NString value){
this.setValue("PDRFLEX_PLAN_CODE", value.getValue());
}
public NString getPdrflexPlanCode(){
NString v = new NString((String)this.getValue("PDRFLEX_PLAN_CODE"));
return v;
}
public void setPlanDesc(NString value){
this.setValue("PLAN_DESC", value.getValue());
}
public NString getPlanDesc(){
NString v = new NString((String)this.getValue("PLAN_DESC"));
return v;
}
public void setPdrflexBdclCode(NString value){
this.setValue("PDRFLEX_BDCL_CODE", value.getValue());
}
public NString getPdrflexBdclCode(){
NString v = new NString((String)this.getValue("PDRFLEX_BDCL_CODE"));
return v;
}
public void setBdclDesc(NString value){
this.setValue("BDCL_DESC", value.getValue());
}
public NString getBdclDesc(){
NString v = new NString((String)this.getValue("BDCL_DESC"));
return v;
}
public void setPdrflexStatus(NString value){
this.setValue("PDRFLEX_STATUS", value.getValue());
}
public NString getPdrflexStatus(){
NString v = new NString((String)this.getValue("PDRFLEX_STATUS"));
return v;
}
public void setAmount1(NNumber value){
this.setValue("AMOUNT1", value.getValue());
}
public NNumber getAmount1(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT1"));
return v;
}
public void setAmount2(NNumber value){
this.setValue("AMOUNT2", value.getValue());
}
public NNumber getAmount2(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT2"));
return v;
}
public void setAmount3(NNumber value){
this.setValue("AMOUNT3", value.getValue());
}
public NNumber getAmount3(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT3"));
return v;
}
public void setAmount4(NNumber value){
this.setValue("AMOUNT4", value.getValue());
}
public NNumber getAmount4(){
NNumber v = new NNumber((BigDecimal)this.getValue("AMOUNT4"));
return v;
}
public void setPdrflexPidm(NNumber value){
this.setValue("PDRFLEX_PIDM", value.getValue());
}
public NNumber getPdrflexPidm(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_PIDM"));
return v;
}
public void setPtrbdcaAmt1Ind(NString value){
this.setValue("PTRBDCA_AMT1_IND", value.getValue());
}
public NString getPtrbdcaAmt1Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT1_IND"));
return v;
}
public void setPtrbdcaAmt2Ind(NString value){
this.setValue("PTRBDCA_AMT2_IND", value.getValue());
}
public NString getPtrbdcaAmt2Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT2_IND"));
return v;
}
public void setPtrbdcaAmt3Ind(NString value){
this.setValue("PTRBDCA_AMT3_IND", value.getValue());
}
public NString getPtrbdcaAmt3Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT3_IND"));
return v;
}
public void setPtrbdcaAmt4Ind(NString value){
this.setValue("PTRBDCA_AMT4_IND", value.getValue());
}
public NString getPtrbdcaAmt4Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_AMT4_IND"));
return v;
}
public void setPdrflexAmount1(NNumber value){
this.setValue("PDRFLEX_AMOUNT1", value.getValue());
}
public NNumber getPdrflexAmount1(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT1"));
return v;
}
public void setPdrflexAmount2(NNumber value){
this.setValue("PDRFLEX_AMOUNT2", value.getValue());
}
public NNumber getPdrflexAmount2(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT2"));
return v;
}
public void setPdrflexAmount3(NNumber value){
this.setValue("PDRFLEX_AMOUNT3", value.getValue());
}
public NNumber getPdrflexAmount3(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT3"));
return v;
}
public void setPdrflexAmount4(NNumber value){
this.setValue("PDRFLEX_AMOUNT4", value.getValue());
}
public NNumber getPdrflexAmount4(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_AMOUNT4"));
return v;
}
public void setPriorStatus(NString value){
this.setValue("PRIOR_STATUS", value.getValue());
}
public NString getPriorStatus(){
NString v = new NString((String)this.getValue("PRIOR_STATUS"));
return v;
}
public void setFlexAmt(NNumber value){
this.setValue("FLEX_AMT", value.getValue());
}
public NNumber getFlexAmt(){
NNumber v = new NNumber((BigDecimal)this.getValue("FLEX_AMT"));
return v;
}
public void setAmt1Title(NString value){
this.setValue("AMT1_TITLE", value.getValue());
}
public NString getAmt1Title(){
NString v = new NString((String)this.getValue("AMT1_TITLE"));
return v;
}
public void setAmt2Title(NString value){
this.setValue("AMT2_TITLE", value.getValue());
}
public NString getAmt2Title(){
NString v = new NString((String)this.getValue("AMT2_TITLE"));
return v;
}
public void setAmt3Title(NString value){
this.setValue("AMT3_TITLE", value.getValue());
}
public NString getAmt3Title(){
NString v = new NString((String)this.getValue("AMT3_TITLE"));
return v;
}
public void setAmt4Title(NString value){
this.setValue("AMT4_TITLE", value.getValue());
}
public NString getAmt4Title(){
NString v = new NString((String)this.getValue("AMT4_TITLE"));
return v;
}
public void setCalcFactor(NNumber value){
this.setValue("CALC_FACTOR", value.getValue());
}
public NNumber getCalcFactor(){
NNumber v = new NNumber((BigDecimal)this.getValue("CALC_FACTOR"));
return v;
}
public void setDednFreq(NNumber value){
this.setValue("DEDN_FREQ", value.getValue());
}
public NNumber getDednFreq(){
NNumber v = new NNumber((BigDecimal)this.getValue("DEDN_FREQ"));
return v;
}
public void setBeneAge(NInteger value){
this.setValue("BENE_AGE", value.getValue());
}
public NNumber getBeneAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("BENE_AGE"));
return v;
}
public void setPersAge(NInteger value){
this.setValue("PERS_AGE", value.getValue());
}
public NNumber getPersAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("PERS_AGE"));
return v;
}
public void setDepeAge(NInteger value){
this.setValue("DEPE_AGE", value.getValue());
}
public NNumber getDepeAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("DEPE_AGE"));
return v;
}
public void setEmplAge(NNumber value){
this.setValue("EMPL_AGE", value.getValue());
}
public NNumber getEmplAge(){
NNumber v = new NNumber((BigDecimal)this.getValue("EMPL_AGE"));
return v;
}
public void setBdtyCode(NString value){
this.setValue("BDTY_CODE", value.getValue());
}
public NString getBdtyCode(){
NString v = new NString((String)this.getValue("BDTY_CODE"));
return v;
}
public void setPriorLife(NNumber value){
this.setValue("PRIOR_LIFE", value.getValue());
}
public NNumber getPriorLife(){
NNumber v = new NNumber((BigDecimal)this.getValue("PRIOR_LIFE"));
return v;
}
public void setCalcRule(NString value){
this.setValue("CALC_RULE", value.getValue());
}
public NString getCalcRule(){
NString v = new NString((String)this.getValue("CALC_RULE"));
return v;
}
public void setPtrbdcaOption1Ind(NString value){
this.setValue("PTRBDCA_OPTION1_IND", value.getValue());
}
public NString getPtrbdcaOption1Ind(){
NString v = new NString((String)this.getValue("PTRBDCA_OPTION1_IND"));
return v;
}
public void setPdrflexApprInd(NString value){
this.setValue("PDRFLEX_APPR_IND", value.getValue());
}
public NString getPdrflexApprInd(){
NString v = new NString((String)this.getValue("PDRFLEX_APPR_IND"));
return v;
}
public void setPdrflexLifOvrUdrAmt(NNumber value){
this.setValue("PDRFLEX_LIF_OVR_UDR_AMT", value.getValue());
}
public NNumber getPdrflexLifOvrUdrAmt(){
NNumber v = new NNumber((BigDecimal)this.getValue("PDRFLEX_LIF_OVR_UDR_AMT"));
return v;
}
public void setPdrflexActivityDate(NDate value){
this.setValue("PDRFLEX_ACTIVITY_DATE", value.getValue());
}
public NDate getPdrflexActivityDate(){
NDate v = new NDate((Date)this.getValue("PDRFLEX_ACTIVITY_DATE"));
return v;
}
public void setPdrflexProcessInd(NString value){
this.setValue("PDRFLEX_PROCESS_IND", value.getValue());
}
public NString getPdrflexProcessInd(){
NString v = new NString((String)this.getValue("PDRFLEX_PROCESS_IND"));
return v;
}
public void setROWID(byte[] bytes) {
this.setROWID(DbManager.getDataBaseFactory().createRowid(bytes));
}
public void setROWID(java.sql.RowId rowId) {
this.setValue(DAOConfiguration.MODEL_ROWID, rowId);
}
}
| 10,290 | 0.702721 | 0.696113 | 576 | 16.864584 | 23.132898 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.220486 | false | false |
3
|
b721dff7651af57707bcc742df8ad362e664d47b
| 27,625,229,692,091 |
c677dc3603089ce7f5b595f0e9494638c683225c
|
/src/main/java/com/business/web/controller/BusinessUploadController.java
|
57450a82cde588db58bcf9cf3a053324a015c008
|
[] |
no_license
|
ConvergentMobile/lbl_pro_v1
|
https://github.com/ConvergentMobile/lbl_pro_v1
|
8c7d7e8f0789471bbac7b4c5241e4859164f85d6
|
838e26f7377f6635cb2a64affa254703949d570d
|
refs/heads/master
| 2020-05-28T02:28:37.625000 | 2017-08-28T02:50:41 | 2017-08-28T02:50:41 | 34,703,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.business.web.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import au.com.bytecode.opencsv.CSVReader;
import com.business.common.dto.ExportReportDTO;
import com.business.common.dto.LblErrorDTO;
import com.business.common.dto.LocalBusinessDTO;
import com.business.common.dto.UploadReportDTO;
import com.business.common.dto.UsersDTO;
import com.business.common.util.BingThread;
import com.business.common.util.ControllerUtil;
import com.business.common.util.LBLConstants;
import com.business.common.util.SmartyStreetsThread;
import com.business.common.util.UploadBeanValidateUtil;
import com.business.common.util.UploadDataAddExecutorService;
import com.business.common.util.UploadDataErrorsAddExecutorService;
import com.business.common.util.UploadDataUpdateExecutorService;
import com.business.common.util.ValidationExecutorService;
import com.business.service.BingService;
import com.business.service.BusinessService;
import com.business.service.UploadService;
import com.business.web.bean.BussinessData;
import com.business.web.bean.LblErrorBean;
import com.business.web.bean.LocalBusinessBean;
import com.business.web.bean.UploadBusinessBean;
import com.business.web.bean.UsersBean;
/**
*
* @author Vasanth
*
* BusinessUploadController class which gets the data from the View
* Layer and sends to the Business Logic Layer and returns respective
* results to View Layer
*
*
*
*/
@Controller
public class BusinessUploadController {
public int totalDataCount;
private ControllerUtil controllerUtil = new ControllerUtil();
Logger logger = Logger.getLogger(BusinessUploadController.class);
Set<LocalBusinessDTO> duplicateRecord = new HashSet<LocalBusinessDTO>();
List<LocalBusinessDTO> updateBusinessRecords = null;
List<LocalBusinessDTO> listofDeletesbyActionCode = null;
List<LblErrorDTO> listOfErrorUpdatesByActionCode = null;
List<LblErrorDTO> listofErrorDeletesbyActionCode = null;
Set<LblErrorDTO> incorrectDatas = new HashSet<LblErrorDTO>();
ResourceBundle bundle = ResourceBundle.getBundle("messages");
String fileName = bundle.getString("businessApp.lable.reportDirectory");
@Autowired
private BusinessService service;
@Autowired
private BingService bingService;
@Autowired
private UploadService uploadService;
/***
*
* This method returns to uplodbusiness page
*
* @param model
* @return
*/
@RequestMapping(value = "/uploadBusiness.htm", method = RequestMethod.GET)
public String uploadBusinessInformationRequest(Model model) {
logger.info("start :: uploadBusinessInformationRequest method");
model.addAttribute("uploadBusiness", new LocalBusinessBean());
logger.info("end :: uploadBusinessInformationRequest method");
return "uploadBusinessInfo";
}
/***
*
* This method validate the records in the excel sheet and with database and
* uploads the excel sheet data to database and returns to list page
*
* @param bean
* @param model
* @return
*/
@RequestMapping(value = "/uploadBusiness.htm", method = RequestMethod.POST)
public String uploadBusinessInformation(
@ModelAttribute("uploadBusiness") LocalBusinessBean bean,
Model model, HttpServletRequest request, HttpSession session,
HSSFWorkbook workbook, HttpServletResponse response) {
logger.info("start :: uploadBusinessInformation method");
String pageName = request.getParameter("page");
Integer role = (Integer) session.getAttribute("roleId");
CommonsMultipartFile file = bean.getTargetFile();
logger.info("File Name == " + file.getOriginalFilename());
String fName = file.getOriginalFilename();
logger.info("File Name : " + fName);
Map<String, Long> brandsCountsMap = new HashMap<String, Long>();
String headerpopup = "";
List<UploadBusinessBean> listDataFromXLS = null;
if (!fName.contains(".csv")) {
listDataFromXLS = getListDataFromXLS(file, brandsCountsMap,
headerpopup);
} else {
listDataFromXLS = getListFromCSV(file, brandsCountsMap, headerpopup);
}
boolean isClientIdExists = true;
Set<Integer> clients = new HashSet<Integer>();
for (UploadBusinessBean business : listDataFromXLS) {
Integer clientId = business.getClientId();
clients.add(clientId);
}
if (clients != null) {
for (Integer clientId : clients) {
String brandByClientId = service.getBrandByClientId(clientId);
if (brandByClientId == null) {
logger.error("Client does not exists in LBL: " + clientId);
isClientIdExists = false;
break;
}
}
}
String message = "";
int correctDataCount = 0;
int inCorrectDataCount = 0;
headerpopup = "Invalid Bulk Upload Template";
if (isClientIdExists == false) {
headerpopup = "Client Does Not Exist. Contact Account Manager for Assistance";
listDataFromXLS = null;
}
Integer locations = 0;
Integer invoicedlocations = 0;
for (Integer clientId : clients) {
locations = locations
+ service.getCountForBrand(clientId, listDataFromXLS);
invoicedlocations = invoicedlocations
+ service.getlocationInvoicedByClient(clientId);
}
if (locations.intValue() > invoicedlocations.intValue()) {
headerpopup = "This upload will exceed the number of locations included in your current contract. Please contact your Sales Rep to increase the number of locations allowed for upload.";
listDataFromXLS = null;
}
boolean isStoreDuplicate = false;
if (listDataFromXLS != null) {
isStoreDuplicate = isStoreDuplicateInExcel(listDataFromXLS);
}
if (isStoreDuplicate == true) {
headerpopup = "Attempting to upload Duplicated Locations. Please check your file and try again.";
listDataFromXLS = null;
}
if (listDataFromXLS != null && listDataFromXLS.size() > 0) {
message = "Upload complete, results can be seen in Business Listings.";
headerpopup = "";
totalDataCount = listDataFromXLS.size();
try {
ValidationExecutorService.executeService(service,
listDataFromXLS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
List<UploadBusinessBean> validBusinessList = ValidationExecutorService.validBusinessList;
List<LblErrorBean> erroredBusinessList = ValidationExecutorService.erroredBusinessList;
logger.info("Total valid records updating/Adding to Bing are:"
+ validBusinessList.size());
/*BingThread bingThread = new BingThread(bingService,
validBusinessList);
bingThread.start();*/
List<UploadBusinessBean> deleteList = ValidationExecutorService.deleteBusinessList;
int deleteCount = 0;
for (UploadBusinessBean uploadBean : deleteList) {
if (uploadBean != null
&& uploadBean.getActionCode().equalsIgnoreCase("D")) {
deleteCount++;
uploadService.deleteBusiness(uploadBean);
}
}
logger.info("Total stores marked for delete are: " + deleteCount);
logger.info("Toatal valid records found are: "
+ validBusinessList.size());
logger.info("Toatal Errored records found are: "
+ erroredBusinessList);
List<LocalBusinessDTO> correctDatas = new ArrayList<LocalBusinessDTO>();
List<LblErrorDTO> inCorrectData = new ArrayList<LblErrorDTO>();
LocalBusinessDTO businessDTO = null;
for (UploadBusinessBean uploadBusinessBean : validBusinessList) {
businessDTO = new LocalBusinessDTO();
BeanUtils.copyProperties(uploadBusinessBean, businessDTO);
correctDatas.add(businessDTO);
}
LblErrorDTO errorDTO = null;
for (LblErrorBean errorBean : erroredBusinessList) {
errorDTO = new LblErrorDTO();
BeanUtils.copyProperties(errorBean, errorDTO);
inCorrectData.add(errorDTO);
}
List<LocalBusinessDTO> correctRecords = new ArrayList<LocalBusinessDTO>();
correctRecords = checkRecordsInListings(correctDatas,
brandsCountsMap);
for (LocalBusinessDTO localBusinessDTO : correctRecords) {
Long recordsCount = Long.valueOf(1);
String brandName = localBusinessDTO.getClient();
if (brandsCountsMap.containsKey(brandName)) {
recordsCount = brandsCountsMap.get(brandName) + 1;
}
brandsCountsMap.put(brandName, recordsCount);
}
List<LblErrorDTO> inCorrectDataList = checkRecordsInListingErrors(
inCorrectData, brandsCountsMap);
for (LblErrorDTO lblErrorDTO : inCorrectDataList) {
Long recordsCount = Long.valueOf(1);
String brandName = lblErrorDTO.getClient();
if (brandsCountsMap.containsKey(brandName)) {
recordsCount = brandsCountsMap.get(brandName) + 1;
}
brandsCountsMap.put(brandName, recordsCount);
}
List<LblErrorDTO> correctDBErrorRecords = correctDBErrorRecords(correctDatas);
Date date = new Date();
String uploadUserName = (String) session.getAttribute("userName");
String uploadJobId = uploadUserName + "_"
+ System.currentTimeMillis();
session.setAttribute("uploadJobId", uploadJobId);
logger.info("Start: Add listings");
UploadDataAddExecutorService uploadAddService = new UploadDataAddExecutorService();
try {
uploadAddService.addBusinessList(correctRecords, date,
uploadJobId, service);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("End: Add listings");
logger.info("Start: update listings");
// String userName = (String) session.getAttribute("userName");
UploadDataUpdateExecutorService uploadUpdateService = new UploadDataUpdateExecutorService();
try {
uploadUpdateService.updateBusinessList(updateBusinessRecords,
date, uploadJobId, service, uploadUserName);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("End: update listings");
logger.info("reomve Correct ErrorData from business error ::"
+ correctDBErrorRecords);
// deleteBusinessByActionCode in business table
service.deleteBusinessByActionCode(listofDeletesbyActionCode);
// remove the CorrectErrorData from business table
service.reomveCorrectErrorData(correctDBErrorRecords);
logger.info("Start: Add Error listings");
UploadDataErrorsAddExecutorService errorService = new UploadDataErrorsAddExecutorService();
try {
errorService.insertErrorBusiness(inCorrectDataList, date,
uploadJobId, service);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("End: Add Error listings");
// insert error records to error table
// service.insertErrorBusiness(inCorrectDataList, date,
// uploadJobId);
// updateErrorBusinessByActionCode in business error table
service.updateErrorBusinessByActionCode(
listOfErrorUpdatesByActionCode, date, uploadJobId);
// deleteErrorBusinessByActioncode in business error table
service.deleteErrorBusinessByActioncode(listofErrorDeletesbyActionCode);
SmartyStreetsThread st = new SmartyStreetsThread(service,
correctRecords, updateBusinessRecords, inCorrectDataList,
listOfErrorUpdatesByActionCode);
st.start();
logger.info("Total Records: " + totalDataCount);
logger.info("Total Corect Records: " + correctRecords.size());
logger.info("Total Updated Records: "
+ updateBusinessRecords.size());
logger.info("Total Deleted Records: " + deleteList.size());
logger.info("Total Error Records: " + inCorrectDataList.size());
logger.info("Total error updated Records: "
+ listOfErrorUpdatesByActionCode.size());
logger.info("Total error deleted Records: "
+ listofErrorDeletesbyActionCode.size());
if (correctRecords != null) {
correctDataCount = correctRecords.size();
int updateSize = 0;
if (updateBusinessRecords != null) {
updateSize = updateBusinessRecords.size();
}
int deleteSize = 0;
if (listofDeletesbyActionCode != null) {
deleteSize = listofDeletesbyActionCode.size();
}
correctDataCount = correctDataCount + updateSize - deleteSize;
if (correctDataCount < 0) {
correctDataCount = 0;
}
}
if (inCorrectDataList != null) {
inCorrectDataCount = inCorrectDataList.size();
int updateSize = 0;
if (listOfErrorUpdatesByActionCode != null) {
updateSize = listOfErrorUpdatesByActionCode.size();
}
int deleteSize = 0;
if (listofErrorDeletesbyActionCode != null) {
deleteSize = listofErrorDeletesbyActionCode.size();
}
inCorrectDataCount = inCorrectDataCount + updateSize
- deleteSize;
if (inCorrectDataCount < 0) {
inCorrectDataCount = 0;
}
}
if (correctRecords.size() > 0 || inCorrectDataList.size() > 0) {
Set<String> brandNames = brandsCountsMap.keySet();
for (String brand : brandNames) {
UploadReportDTO uploadReportDTO = new UploadReportDTO();
uploadReportDTO.setDate(date);
uploadReportDTO.setNumberOfRecords(String
.valueOf(brandsCountsMap.get(brand)));
String userName = (String) request.getSession()
.getAttribute("userName");
uploadReportDTO.setUserName(userName);
uploadReportDTO.setBrand(brand);
boolean uploadReportInfo = service
.uploadReportDTO(uploadReportDTO);
}
}
model.addAttribute("showPopup", "showMessage");
}
model.addAttribute("headerPopup", headerpopup);
try {
response.getWriter().write(headerpopup);
} catch (IOException e) {
e.printStackTrace();
}
List<LocalBusinessDTO> listOfBusinessInfo = service
.getListOfBusinessInfo();
model.addAttribute("allBusinessInfo", listOfBusinessInfo);
model.addAttribute("searchBusiness", new LocalBusinessDTO());
logger.info("Total Data Count == " + totalDataCount);
logger.info("Correct Data Count == " + correctDataCount);
logger.info("Incorrect Data Count == " + inCorrectDataCount);
model.addAttribute("listingsUploaded", totalDataCount);
model.addAttribute("listingsCompleted", correctDataCount);
model.addAttribute("listingsWithErrors", inCorrectDataCount);
model.addAttribute("message", message);
duplicateRecord.clear();
// return "allBusinessInfo";
model.addAttribute("uploadBusiness", new LocalBusinessBean());
model.addAttribute("businessSearch", new LocalBusinessDTO());
if (pageName.equals("businessListings")) {
session.setAttribute("listOfBusinessInfo", listOfBusinessInfo);
controllerUtil.listingsAddAttributes(1, model, request,
listOfBusinessInfo);
List<LblErrorDTO> listOfErrorBusinessInfo = service
.getListOfErrors();
int activeListSize = listOfBusinessInfo.size();
int errorListSize = listOfErrorBusinessInfo.size();
model.addAttribute("errorListSize", errorListSize);
model.addAttribute("activeListSize", activeListSize);
logger.info("end :: uploadBusinessInformation method");
return "business-listings";
} else if (pageName.equals("dashboard")) {
List<LocalBusinessDTO> listOfBrandsInfo = service.getListOfBrands();
List<ExportReportDTO> listingActivityInfo = service
.getListingActivityInf();
Collections.sort(listingActivityInfo);
List<UsersDTO> usersList = service.getAllUsersList((Integer) role);
model.addAttribute("usersListInfo", usersList);
model.addAttribute("brandSize", listOfBusinessInfo.size());
model.addAttribute("listingActivityInfo", listingActivityInfo);
model.addAttribute("brandsInfo", listOfBrandsInfo);
logger.info("end :: uploadBusinessInformation method");
LocalBusinessDTO dto = new LocalBusinessDTO();
dashBoardCommonInfo(model, session, dto);
return "dashboard";
} else if (pageName.equals("uploadExport")) {
logger.info("end :: uploadBusinessInformation method");
return "upload-export";
} else if (pageName.equals("dashboardclient")) {
List<LocalBusinessDTO> listOfBusinessInfo1 = service
.getListOfBusinessInfo();
Integer userId = (Integer) session.getAttribute("userID");
List<UsersDTO> userInfo = service.userInfo(userId);
UsersDTO usersDTO = userInfo.get(0);
UsersBean bean1 = new UsersBean();
BeanUtils.copyProperties(usersDTO, bean1);
List<ExportReportDTO> listingActivityInfo = service
.getListingActivityInf();
Collections.sort(listingActivityInfo);
model.addAttribute("adminUser", bean1);
model.addAttribute("listingActivityInfo", listingActivityInfo);
session.setAttribute("listOfBusinessInfo", listOfBusinessInfo1);
controllerUtil.listingsAddAttributes(1, model, request,
listOfBusinessInfo1);
logger.info("end :: uploadBusinessInformation method");
return "dashboard-client";
}
session.setAttribute("listOfBusinessInfo", listOfBusinessInfo);
List<LblErrorDTO> listOfErrorBusinessInfo = service.getListOfErrors();
int activeListSize = listOfBusinessInfo.size();
int errorListSize = listOfErrorBusinessInfo.size();
model.addAttribute("errorListSize", errorListSize);
model.addAttribute("activeListSize", activeListSize);
controllerUtil.listingsAddAttributes(1, model, request,
listOfBusinessInfo);
logger.info("end :: uploadBusinessInformation method");
return "business-listings";
}
private void dashBoardCommonInfo(Model model, HttpSession session,
LocalBusinessDTO dto) {
Integer userId = (Integer) session.getAttribute("userID");
List<UsersDTO> userInfo = service.userInfo(userId);
UsersDTO usersDTO = userInfo.get(0);
String name = usersDTO.getName();
String lastName = usersDTO.getLastName();
String fullName = name + " " + lastName;
usersDTO.setFullName(fullName);
UsersBean bean = new UsersBean();
BeanUtils.copyProperties(usersDTO, bean);
model.addAttribute("adminUser", bean);
model.addAttribute("searchBusiness", dto);
}
/***
* this method check's the data in excel sheet and returns correct data to
* checkbusinessinfo method
*
*
* @param listDataFromXLS
* @return
* @return
*/
public BussinessData checkBusinessInfoFormat(
List<UploadBusinessBean> listDataFromXLS) {
UploadBeanValidateUtil validateUtil = new UploadBeanValidateUtil();
return validateUtil.validateBusiness(service, listDataFromXLS);
}
/***
* This method validate the email format in excel sheet
*
* @param id
* @return
*/
public boolean checkEmailFormat(String id) {
Pattern pattern = Pattern
.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
Matcher matcher = pattern.matcher(id);
return matcher.matches();
}
/***
* this method validate the hours of operation
*
* @param time
* @return
*/
public boolean isHours(String time) {
Pattern pattern = Pattern.compile("([01]?[0-9]|2[0-3]):[0-5][0-9]");
Matcher matcher = pattern.matcher(time);
return matcher.matches();
}
public boolean isPhoneNumber(String phoneNumber) {
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(phoneNumber);
return m.matches();
}
/***
*
* this method skip the duplicate records in the excel sheet and returns the
* records
*
*
* @param records
* @return
*/
public boolean isStoreDuplicateInExcel(List<UploadBusinessBean> records) {
boolean isStoreDuplicate = false;
for (int x = 0; x < records.size(); x++) {
UploadBusinessBean xRecord = records.get(x);
for (int y = x + 1; y < records.size(); y++) {
UploadBusinessBean yRecord = records.get(y);
if (xRecord.getStore().equals(yRecord.getStore())
&& xRecord.getClientId().equals(yRecord.getClientId())
&& xRecord.getCompanyName().equalsIgnoreCase(
yRecord.getCompanyName())
&& xRecord.getSuite().equalsIgnoreCase(
yRecord.getSuite())
&& xRecord.getLocationAddress().equalsIgnoreCase(
yRecord.getLocationAddress())
&& xRecord.getLocationCity().equalsIgnoreCase(
yRecord.getLocationCity())
&& xRecord.getLocationState().equalsIgnoreCase(
yRecord.getLocationState())
&& xRecord.getLocationPhone().equals(
yRecord.getLocationPhone())
&& xRecord.getLocationZipCode().equalsIgnoreCase(
yRecord.getLocationZipCode())) {
isStoreDuplicate = true;
}
}
}
return isStoreDuplicate;
}
/***
*
* this method check's the data in the excel sheet with database and returns
* the correct data to businessinfo method
*
* @param records
* @return
*/
public List<LocalBusinessDTO> checkRecordsInListings(
List<LocalBusinessDTO> records, Map<String, Long> brandsCountsMap) {
List<LocalBusinessDTO> insertRecord = new ArrayList<LocalBusinessDTO>();
listofDeletesbyActionCode = new ArrayList<LocalBusinessDTO>();
updateBusinessRecords = new ArrayList<LocalBusinessDTO>();
List<LocalBusinessDTO> listOfBusinessInfo = service
.getListOfBusinessInfo();
List<LblErrorDTO> listOfErorBusinessInfo = service
.getListOfErorBusinessInfo();
List<LblErrorDTO> listOfErorBusinessInfos = new ArrayList<LblErrorDTO>();
for (int i = 0; i < records.size(); i++) {
LocalBusinessDTO excelRecord = records.get(i);
for (LblErrorDTO lblErrorDTO : listOfErorBusinessInfo) {
if (lblErrorDTO.getStore().equals(excelRecord.getStore())
&& lblErrorDTO.getClientId().equals(
excelRecord.getClientId())) {
listOfErorBusinessInfos.add(lblErrorDTO);
}
}
boolean isDuplicate = false;
for (int j = 0; j < listOfBusinessInfo.size(); j++) {
/* Business Name, Address, Suite, City, State, Zip and Phone */
LocalBusinessDTO dbRecord = listOfBusinessInfo.get(j);
if (dbRecord.getStore().equals(excelRecord.getStore())
&& dbRecord.getClientId().equals(
excelRecord.getClientId())) {
if (excelRecord.getActionCode().equalsIgnoreCase("D")) {
excelRecord.setId(dbRecord.getId());
listofDeletesbyActionCode.add(excelRecord);
} else {
excelRecord.setId(dbRecord.getId());
updateBusinessRecords.add(excelRecord);
}
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
if (!service.isBusinessExcelRecordUnique(excelRecord)) {
insertRecord.add(excelRecord);
}
} /*
* else { decreaseDuplicateRecordsLength(brandsCountsMap,
* excelRecord); }
*/
}
if (!listOfErorBusinessInfos.isEmpty()
&& listOfErorBusinessInfos.size() > 0) {
service.deleteErrorBusinessByActioncode(listOfErorBusinessInfos);
}
return insertRecord;
}
public List<LblErrorDTO> checkRecordsInListingErrors(
List<LblErrorDTO> records, Map<String, Long> brandsCountsMap) {
List<LblErrorDTO> insertErrorRecord = new ArrayList<LblErrorDTO>();
listofErrorDeletesbyActionCode = new ArrayList<LblErrorDTO>();
listOfErrorUpdatesByActionCode = new ArrayList<LblErrorDTO>();
List<LblErrorDTO> listOfErrorRecords = service
.getListOfErorBusinessInfo();
for (int i = 0; i < records.size(); i++) {
LblErrorDTO excelErrorRecord = records.get(i);
boolean isDuplicate = false;
for (int j = 0; j < listOfErrorRecords.size(); j++) {
LblErrorDTO dbRecord = listOfErrorRecords.get(j);
if (dbRecord.getStore().equals(excelErrorRecord.getStore())
&& dbRecord.getClientId().equals(
excelErrorRecord.getClientId())) {
if (excelErrorRecord.getActionCode().equalsIgnoreCase("D")) {
excelErrorRecord.setId(dbRecord.getId());
listofErrorDeletesbyActionCode.add(excelErrorRecord);
} else {
excelErrorRecord.setId(dbRecord.getId());
listOfErrorUpdatesByActionCode.add(excelErrorRecord);
}
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
insertErrorRecord.add(excelErrorRecord);
}/*
* else { decreaseErrorDuplicateRecordsLength(brandsCountsMap,
* excelErrorRecord); }
*/
}
return insertErrorRecord;
}
public List<LblErrorDTO> correctDBErrorRecords(
List<LocalBusinessDTO> records) {
List<LblErrorDTO> insertErrorRecord = new ArrayList<LblErrorDTO>();
List<LblErrorDTO> listOfErrorRecords = service
.getListOfErorBusinessInfo();
for (int i = 0; i < records.size(); i++) {
LocalBusinessDTO excelRecord = records.get(i);
for (int j = 0; j < listOfErrorRecords.size(); j++) {
LblErrorDTO dbRecord = listOfErrorRecords.get(j);
/*
* logger.info(dbRecord.getStore() + ".equals(" +
* excelRecord.getStore() + " , " + dbRecord.getClientId() +
* ".equals(" + excelRecord.getClientId());
*/
if (dbRecord.getStore().equals(excelRecord.getStore())
&& dbRecord.getClientId().equals(
excelRecord.getClientId())) {
records.remove(i);
i--;
insertErrorRecord.add(dbRecord);
break;
}
}
}
logger.info("Correct Suitable Records == " + insertErrorRecord.size());
logger.info("Duplicate Records == " + duplicateRecord.size());
return insertErrorRecord;
}
/***
* this method takes the list of information from excel
*
* @param infile
* @return
*/
public boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
return false;
}
return true;
}
private List<UploadBusinessBean> getListDataFromXLS(
CommonsMultipartFile infile, Map<String, Long> brandsCountsMap,
String headerpopup) {
List<UploadBusinessBean> tListData = new ArrayList<UploadBusinessBean>();
try {
Sheet sheet = (Sheet) WorkbookFactory.create(
infile.getInputStream()).getSheetAt(0);
DataFormatter df = new DataFormatter();
Iterator<Row> rowIterator = sheet.rowIterator();
boolean header = true;
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
boolean rowEmpty = isRowEmpty(row);
if (rowEmpty == false) {
if (header) {
header = false;
headerpopup = "";
if (!headersValid(row, df)) {
headerpopup = "Invalid Bulk Upload Template";
return tListData;
}
continue;
}
UploadBusinessBean uploadBusinessBean = new UploadBusinessBean();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell == null) // Process only the rows with some
// data
continue;
int columnIndex = cell.getColumnIndex();
// System.out.println("columnIndex" + columnIndex);
String formatCellValue = df.formatCellValue(cell);
// System.out.println("formatCellValue" +
// formatCellValue);
org.apache.commons.beanutils.BeanUtils
.setProperty(
uploadBusinessBean,
LBLConstants.UPLOAD_BEAN_PROPERTIES[columnIndex],
formatCellValue);
}
tListData.add(uploadBusinessBean);
}
}
} catch (Exception e) {
headerpopup = "Invalid Bulk Upload Template";
logger.error("Exception : " + e);
e.printStackTrace();
}
logger.info("Excel sheet Records size == " + tListData.size());
logger.info(tListData);
return tListData;
}
private boolean allValuesInRowAreEmpty(String[] row) {
boolean returnValue = true;
for (String s : row) {
if (s.length() != 0) {
returnValue = false;
}
}
return returnValue;
}
private List<UploadBusinessBean> getListFromCSV(CommonsMultipartFile file,
Map<String, Long> brandsCountsMap, String headerpopup) {
List<UploadBusinessBean> tListData = new ArrayList<UploadBusinessBean>();
boolean value = isheaderValid(file);
if (!value) {
headerpopup = "Invalid Bulk Upload Template";
return tListData;
}
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
CSVReader reader = new CSVReader(bufferedReader, ',', '"', 1);
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
UploadBusinessBean uploadBusinessBean = new UploadBusinessBean();
if (nextLine != null) {
for (int i = 0; i < nextLine.length; i++) {
try {
org.apache.commons.beanutils.BeanUtils.setProperty(
uploadBusinessBean,
LBLConstants.UPLOAD_BEAN_PROPERTIES[i],
nextLine[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
tListData.add(uploadBusinessBean);
}
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Excel CSV sheet Records size == " + tListData.size());
logger.info(tListData);
return tListData;
}
private boolean isheaderValid(CommonsMultipartFile file) {
boolean isHeadersValid = true;
CSVParser parser;
try {
InputStream inputStream = file.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
parser = new CSVParser(bufferedReader,
CSVFormat.DEFAULT.withHeader());
Map<String, Integer> headerMap = parser.getHeaderMap();
List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
list.add(entry.getKey());
}
for (int i = 0; i < list.size(); i++) {
String anotherString = LBLConstants.UPLOAD_EXCEL_HEADERS[i];
if (!list.get(i).equalsIgnoreCase(anotherString)) {
isHeadersValid = false;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return isHeadersValid;
}
private boolean isheaderValid(Map<String, Integer> headerMap) {
boolean isHeadersValid = true;
List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
list.add(entry.getKey());
}
for (int i = 0; i < list.size(); i++) {
String anotherString = LBLConstants.UPLOAD_EXCEL_HEADERS[i];
if (!list.get(i).equalsIgnoreCase(anotherString)) {
isHeadersValid = false;
break;
}
}
return isHeadersValid;
// TODO Auto-generated method stub
}
private boolean headersValid(List<String> list) {
boolean isHeadersValid = true;
for (int i = 0; i < list.size(); i++) {
// System.out.println(list.get(i));
String anotherString = LBLConstants.UPLOAD_EXCEL_HEADERS[i];
// System.out.println(anotherString);
if (!list.get(i).equalsIgnoreCase(anotherString)) {
isHeadersValid = false;
break;
}
}
return isHeadersValid;
}
/**
* headersValidation
*
* @param row
* @param df
* @return
*/
public boolean headersValid(Row row, DataFormatter df) {
Iterator<Cell> cellIterator = row.cellIterator();
boolean isHeadersValid = true;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell == null
|| (!df.formatCellValue(cell).equalsIgnoreCase(
LBLConstants.UPLOAD_EXCEL_HEADERS[cell
.getColumnIndex()]))) {
isHeadersValid = false;
break;
}
}
return isHeadersValid;
}
}
|
UTF-8
|
Java
| 32,963 |
java
|
BusinessUploadController.java
|
Java
|
[
{
"context": "siness.web.bean.UsersBean;\r\n\r\n/**\r\n * \r\n * @author Vasanth\r\n * \r\n * BusinessUploadController class w",
"end": 2683,
"score": 0.999390184879303,
"start": 2676,
"tag": "NAME",
"value": "Vasanth"
},
{
"context": "g uploadUserName = (String) session.getAttribute(\"userName\");\r\n\t\t\tString uploadJobId = uploadUserName + \"_\"\r",
"end": 10354,
"score": 0.8298265933990479,
"start": 10346,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " String userName = (String) session.getAttribute(\"userName\");\r\n\t\t\tUploadDataUpdateExecutorService uploadUpda",
"end": 10982,
"score": 0.8726208806037903,
"start": 10974,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package com.business.web.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import au.com.bytecode.opencsv.CSVReader;
import com.business.common.dto.ExportReportDTO;
import com.business.common.dto.LblErrorDTO;
import com.business.common.dto.LocalBusinessDTO;
import com.business.common.dto.UploadReportDTO;
import com.business.common.dto.UsersDTO;
import com.business.common.util.BingThread;
import com.business.common.util.ControllerUtil;
import com.business.common.util.LBLConstants;
import com.business.common.util.SmartyStreetsThread;
import com.business.common.util.UploadBeanValidateUtil;
import com.business.common.util.UploadDataAddExecutorService;
import com.business.common.util.UploadDataErrorsAddExecutorService;
import com.business.common.util.UploadDataUpdateExecutorService;
import com.business.common.util.ValidationExecutorService;
import com.business.service.BingService;
import com.business.service.BusinessService;
import com.business.service.UploadService;
import com.business.web.bean.BussinessData;
import com.business.web.bean.LblErrorBean;
import com.business.web.bean.LocalBusinessBean;
import com.business.web.bean.UploadBusinessBean;
import com.business.web.bean.UsersBean;
/**
*
* @author Vasanth
*
* BusinessUploadController class which gets the data from the View
* Layer and sends to the Business Logic Layer and returns respective
* results to View Layer
*
*
*
*/
@Controller
public class BusinessUploadController {
public int totalDataCount;
private ControllerUtil controllerUtil = new ControllerUtil();
Logger logger = Logger.getLogger(BusinessUploadController.class);
Set<LocalBusinessDTO> duplicateRecord = new HashSet<LocalBusinessDTO>();
List<LocalBusinessDTO> updateBusinessRecords = null;
List<LocalBusinessDTO> listofDeletesbyActionCode = null;
List<LblErrorDTO> listOfErrorUpdatesByActionCode = null;
List<LblErrorDTO> listofErrorDeletesbyActionCode = null;
Set<LblErrorDTO> incorrectDatas = new HashSet<LblErrorDTO>();
ResourceBundle bundle = ResourceBundle.getBundle("messages");
String fileName = bundle.getString("businessApp.lable.reportDirectory");
@Autowired
private BusinessService service;
@Autowired
private BingService bingService;
@Autowired
private UploadService uploadService;
/***
*
* This method returns to uplodbusiness page
*
* @param model
* @return
*/
@RequestMapping(value = "/uploadBusiness.htm", method = RequestMethod.GET)
public String uploadBusinessInformationRequest(Model model) {
logger.info("start :: uploadBusinessInformationRequest method");
model.addAttribute("uploadBusiness", new LocalBusinessBean());
logger.info("end :: uploadBusinessInformationRequest method");
return "uploadBusinessInfo";
}
/***
*
* This method validate the records in the excel sheet and with database and
* uploads the excel sheet data to database and returns to list page
*
* @param bean
* @param model
* @return
*/
@RequestMapping(value = "/uploadBusiness.htm", method = RequestMethod.POST)
public String uploadBusinessInformation(
@ModelAttribute("uploadBusiness") LocalBusinessBean bean,
Model model, HttpServletRequest request, HttpSession session,
HSSFWorkbook workbook, HttpServletResponse response) {
logger.info("start :: uploadBusinessInformation method");
String pageName = request.getParameter("page");
Integer role = (Integer) session.getAttribute("roleId");
CommonsMultipartFile file = bean.getTargetFile();
logger.info("File Name == " + file.getOriginalFilename());
String fName = file.getOriginalFilename();
logger.info("File Name : " + fName);
Map<String, Long> brandsCountsMap = new HashMap<String, Long>();
String headerpopup = "";
List<UploadBusinessBean> listDataFromXLS = null;
if (!fName.contains(".csv")) {
listDataFromXLS = getListDataFromXLS(file, brandsCountsMap,
headerpopup);
} else {
listDataFromXLS = getListFromCSV(file, brandsCountsMap, headerpopup);
}
boolean isClientIdExists = true;
Set<Integer> clients = new HashSet<Integer>();
for (UploadBusinessBean business : listDataFromXLS) {
Integer clientId = business.getClientId();
clients.add(clientId);
}
if (clients != null) {
for (Integer clientId : clients) {
String brandByClientId = service.getBrandByClientId(clientId);
if (brandByClientId == null) {
logger.error("Client does not exists in LBL: " + clientId);
isClientIdExists = false;
break;
}
}
}
String message = "";
int correctDataCount = 0;
int inCorrectDataCount = 0;
headerpopup = "Invalid Bulk Upload Template";
if (isClientIdExists == false) {
headerpopup = "Client Does Not Exist. Contact Account Manager for Assistance";
listDataFromXLS = null;
}
Integer locations = 0;
Integer invoicedlocations = 0;
for (Integer clientId : clients) {
locations = locations
+ service.getCountForBrand(clientId, listDataFromXLS);
invoicedlocations = invoicedlocations
+ service.getlocationInvoicedByClient(clientId);
}
if (locations.intValue() > invoicedlocations.intValue()) {
headerpopup = "This upload will exceed the number of locations included in your current contract. Please contact your Sales Rep to increase the number of locations allowed for upload.";
listDataFromXLS = null;
}
boolean isStoreDuplicate = false;
if (listDataFromXLS != null) {
isStoreDuplicate = isStoreDuplicateInExcel(listDataFromXLS);
}
if (isStoreDuplicate == true) {
headerpopup = "Attempting to upload Duplicated Locations. Please check your file and try again.";
listDataFromXLS = null;
}
if (listDataFromXLS != null && listDataFromXLS.size() > 0) {
message = "Upload complete, results can be seen in Business Listings.";
headerpopup = "";
totalDataCount = listDataFromXLS.size();
try {
ValidationExecutorService.executeService(service,
listDataFromXLS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
List<UploadBusinessBean> validBusinessList = ValidationExecutorService.validBusinessList;
List<LblErrorBean> erroredBusinessList = ValidationExecutorService.erroredBusinessList;
logger.info("Total valid records updating/Adding to Bing are:"
+ validBusinessList.size());
/*BingThread bingThread = new BingThread(bingService,
validBusinessList);
bingThread.start();*/
List<UploadBusinessBean> deleteList = ValidationExecutorService.deleteBusinessList;
int deleteCount = 0;
for (UploadBusinessBean uploadBean : deleteList) {
if (uploadBean != null
&& uploadBean.getActionCode().equalsIgnoreCase("D")) {
deleteCount++;
uploadService.deleteBusiness(uploadBean);
}
}
logger.info("Total stores marked for delete are: " + deleteCount);
logger.info("Toatal valid records found are: "
+ validBusinessList.size());
logger.info("Toatal Errored records found are: "
+ erroredBusinessList);
List<LocalBusinessDTO> correctDatas = new ArrayList<LocalBusinessDTO>();
List<LblErrorDTO> inCorrectData = new ArrayList<LblErrorDTO>();
LocalBusinessDTO businessDTO = null;
for (UploadBusinessBean uploadBusinessBean : validBusinessList) {
businessDTO = new LocalBusinessDTO();
BeanUtils.copyProperties(uploadBusinessBean, businessDTO);
correctDatas.add(businessDTO);
}
LblErrorDTO errorDTO = null;
for (LblErrorBean errorBean : erroredBusinessList) {
errorDTO = new LblErrorDTO();
BeanUtils.copyProperties(errorBean, errorDTO);
inCorrectData.add(errorDTO);
}
List<LocalBusinessDTO> correctRecords = new ArrayList<LocalBusinessDTO>();
correctRecords = checkRecordsInListings(correctDatas,
brandsCountsMap);
for (LocalBusinessDTO localBusinessDTO : correctRecords) {
Long recordsCount = Long.valueOf(1);
String brandName = localBusinessDTO.getClient();
if (brandsCountsMap.containsKey(brandName)) {
recordsCount = brandsCountsMap.get(brandName) + 1;
}
brandsCountsMap.put(brandName, recordsCount);
}
List<LblErrorDTO> inCorrectDataList = checkRecordsInListingErrors(
inCorrectData, brandsCountsMap);
for (LblErrorDTO lblErrorDTO : inCorrectDataList) {
Long recordsCount = Long.valueOf(1);
String brandName = lblErrorDTO.getClient();
if (brandsCountsMap.containsKey(brandName)) {
recordsCount = brandsCountsMap.get(brandName) + 1;
}
brandsCountsMap.put(brandName, recordsCount);
}
List<LblErrorDTO> correctDBErrorRecords = correctDBErrorRecords(correctDatas);
Date date = new Date();
String uploadUserName = (String) session.getAttribute("userName");
String uploadJobId = uploadUserName + "_"
+ System.currentTimeMillis();
session.setAttribute("uploadJobId", uploadJobId);
logger.info("Start: Add listings");
UploadDataAddExecutorService uploadAddService = new UploadDataAddExecutorService();
try {
uploadAddService.addBusinessList(correctRecords, date,
uploadJobId, service);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("End: Add listings");
logger.info("Start: update listings");
// String userName = (String) session.getAttribute("userName");
UploadDataUpdateExecutorService uploadUpdateService = new UploadDataUpdateExecutorService();
try {
uploadUpdateService.updateBusinessList(updateBusinessRecords,
date, uploadJobId, service, uploadUserName);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("End: update listings");
logger.info("reomve Correct ErrorData from business error ::"
+ correctDBErrorRecords);
// deleteBusinessByActionCode in business table
service.deleteBusinessByActionCode(listofDeletesbyActionCode);
// remove the CorrectErrorData from business table
service.reomveCorrectErrorData(correctDBErrorRecords);
logger.info("Start: Add Error listings");
UploadDataErrorsAddExecutorService errorService = new UploadDataErrorsAddExecutorService();
try {
errorService.insertErrorBusiness(inCorrectDataList, date,
uploadJobId, service);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("End: Add Error listings");
// insert error records to error table
// service.insertErrorBusiness(inCorrectDataList, date,
// uploadJobId);
// updateErrorBusinessByActionCode in business error table
service.updateErrorBusinessByActionCode(
listOfErrorUpdatesByActionCode, date, uploadJobId);
// deleteErrorBusinessByActioncode in business error table
service.deleteErrorBusinessByActioncode(listofErrorDeletesbyActionCode);
SmartyStreetsThread st = new SmartyStreetsThread(service,
correctRecords, updateBusinessRecords, inCorrectDataList,
listOfErrorUpdatesByActionCode);
st.start();
logger.info("Total Records: " + totalDataCount);
logger.info("Total Corect Records: " + correctRecords.size());
logger.info("Total Updated Records: "
+ updateBusinessRecords.size());
logger.info("Total Deleted Records: " + deleteList.size());
logger.info("Total Error Records: " + inCorrectDataList.size());
logger.info("Total error updated Records: "
+ listOfErrorUpdatesByActionCode.size());
logger.info("Total error deleted Records: "
+ listofErrorDeletesbyActionCode.size());
if (correctRecords != null) {
correctDataCount = correctRecords.size();
int updateSize = 0;
if (updateBusinessRecords != null) {
updateSize = updateBusinessRecords.size();
}
int deleteSize = 0;
if (listofDeletesbyActionCode != null) {
deleteSize = listofDeletesbyActionCode.size();
}
correctDataCount = correctDataCount + updateSize - deleteSize;
if (correctDataCount < 0) {
correctDataCount = 0;
}
}
if (inCorrectDataList != null) {
inCorrectDataCount = inCorrectDataList.size();
int updateSize = 0;
if (listOfErrorUpdatesByActionCode != null) {
updateSize = listOfErrorUpdatesByActionCode.size();
}
int deleteSize = 0;
if (listofErrorDeletesbyActionCode != null) {
deleteSize = listofErrorDeletesbyActionCode.size();
}
inCorrectDataCount = inCorrectDataCount + updateSize
- deleteSize;
if (inCorrectDataCount < 0) {
inCorrectDataCount = 0;
}
}
if (correctRecords.size() > 0 || inCorrectDataList.size() > 0) {
Set<String> brandNames = brandsCountsMap.keySet();
for (String brand : brandNames) {
UploadReportDTO uploadReportDTO = new UploadReportDTO();
uploadReportDTO.setDate(date);
uploadReportDTO.setNumberOfRecords(String
.valueOf(brandsCountsMap.get(brand)));
String userName = (String) request.getSession()
.getAttribute("userName");
uploadReportDTO.setUserName(userName);
uploadReportDTO.setBrand(brand);
boolean uploadReportInfo = service
.uploadReportDTO(uploadReportDTO);
}
}
model.addAttribute("showPopup", "showMessage");
}
model.addAttribute("headerPopup", headerpopup);
try {
response.getWriter().write(headerpopup);
} catch (IOException e) {
e.printStackTrace();
}
List<LocalBusinessDTO> listOfBusinessInfo = service
.getListOfBusinessInfo();
model.addAttribute("allBusinessInfo", listOfBusinessInfo);
model.addAttribute("searchBusiness", new LocalBusinessDTO());
logger.info("Total Data Count == " + totalDataCount);
logger.info("Correct Data Count == " + correctDataCount);
logger.info("Incorrect Data Count == " + inCorrectDataCount);
model.addAttribute("listingsUploaded", totalDataCount);
model.addAttribute("listingsCompleted", correctDataCount);
model.addAttribute("listingsWithErrors", inCorrectDataCount);
model.addAttribute("message", message);
duplicateRecord.clear();
// return "allBusinessInfo";
model.addAttribute("uploadBusiness", new LocalBusinessBean());
model.addAttribute("businessSearch", new LocalBusinessDTO());
if (pageName.equals("businessListings")) {
session.setAttribute("listOfBusinessInfo", listOfBusinessInfo);
controllerUtil.listingsAddAttributes(1, model, request,
listOfBusinessInfo);
List<LblErrorDTO> listOfErrorBusinessInfo = service
.getListOfErrors();
int activeListSize = listOfBusinessInfo.size();
int errorListSize = listOfErrorBusinessInfo.size();
model.addAttribute("errorListSize", errorListSize);
model.addAttribute("activeListSize", activeListSize);
logger.info("end :: uploadBusinessInformation method");
return "business-listings";
} else if (pageName.equals("dashboard")) {
List<LocalBusinessDTO> listOfBrandsInfo = service.getListOfBrands();
List<ExportReportDTO> listingActivityInfo = service
.getListingActivityInf();
Collections.sort(listingActivityInfo);
List<UsersDTO> usersList = service.getAllUsersList((Integer) role);
model.addAttribute("usersListInfo", usersList);
model.addAttribute("brandSize", listOfBusinessInfo.size());
model.addAttribute("listingActivityInfo", listingActivityInfo);
model.addAttribute("brandsInfo", listOfBrandsInfo);
logger.info("end :: uploadBusinessInformation method");
LocalBusinessDTO dto = new LocalBusinessDTO();
dashBoardCommonInfo(model, session, dto);
return "dashboard";
} else if (pageName.equals("uploadExport")) {
logger.info("end :: uploadBusinessInformation method");
return "upload-export";
} else if (pageName.equals("dashboardclient")) {
List<LocalBusinessDTO> listOfBusinessInfo1 = service
.getListOfBusinessInfo();
Integer userId = (Integer) session.getAttribute("userID");
List<UsersDTO> userInfo = service.userInfo(userId);
UsersDTO usersDTO = userInfo.get(0);
UsersBean bean1 = new UsersBean();
BeanUtils.copyProperties(usersDTO, bean1);
List<ExportReportDTO> listingActivityInfo = service
.getListingActivityInf();
Collections.sort(listingActivityInfo);
model.addAttribute("adminUser", bean1);
model.addAttribute("listingActivityInfo", listingActivityInfo);
session.setAttribute("listOfBusinessInfo", listOfBusinessInfo1);
controllerUtil.listingsAddAttributes(1, model, request,
listOfBusinessInfo1);
logger.info("end :: uploadBusinessInformation method");
return "dashboard-client";
}
session.setAttribute("listOfBusinessInfo", listOfBusinessInfo);
List<LblErrorDTO> listOfErrorBusinessInfo = service.getListOfErrors();
int activeListSize = listOfBusinessInfo.size();
int errorListSize = listOfErrorBusinessInfo.size();
model.addAttribute("errorListSize", errorListSize);
model.addAttribute("activeListSize", activeListSize);
controllerUtil.listingsAddAttributes(1, model, request,
listOfBusinessInfo);
logger.info("end :: uploadBusinessInformation method");
return "business-listings";
}
private void dashBoardCommonInfo(Model model, HttpSession session,
LocalBusinessDTO dto) {
Integer userId = (Integer) session.getAttribute("userID");
List<UsersDTO> userInfo = service.userInfo(userId);
UsersDTO usersDTO = userInfo.get(0);
String name = usersDTO.getName();
String lastName = usersDTO.getLastName();
String fullName = name + " " + lastName;
usersDTO.setFullName(fullName);
UsersBean bean = new UsersBean();
BeanUtils.copyProperties(usersDTO, bean);
model.addAttribute("adminUser", bean);
model.addAttribute("searchBusiness", dto);
}
/***
* this method check's the data in excel sheet and returns correct data to
* checkbusinessinfo method
*
*
* @param listDataFromXLS
* @return
* @return
*/
public BussinessData checkBusinessInfoFormat(
List<UploadBusinessBean> listDataFromXLS) {
UploadBeanValidateUtil validateUtil = new UploadBeanValidateUtil();
return validateUtil.validateBusiness(service, listDataFromXLS);
}
/***
* This method validate the email format in excel sheet
*
* @param id
* @return
*/
public boolean checkEmailFormat(String id) {
Pattern pattern = Pattern
.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
Matcher matcher = pattern.matcher(id);
return matcher.matches();
}
/***
* this method validate the hours of operation
*
* @param time
* @return
*/
public boolean isHours(String time) {
Pattern pattern = Pattern.compile("([01]?[0-9]|2[0-3]):[0-5][0-9]");
Matcher matcher = pattern.matcher(time);
return matcher.matches();
}
public boolean isPhoneNumber(String phoneNumber) {
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(phoneNumber);
return m.matches();
}
/***
*
* this method skip the duplicate records in the excel sheet and returns the
* records
*
*
* @param records
* @return
*/
public boolean isStoreDuplicateInExcel(List<UploadBusinessBean> records) {
boolean isStoreDuplicate = false;
for (int x = 0; x < records.size(); x++) {
UploadBusinessBean xRecord = records.get(x);
for (int y = x + 1; y < records.size(); y++) {
UploadBusinessBean yRecord = records.get(y);
if (xRecord.getStore().equals(yRecord.getStore())
&& xRecord.getClientId().equals(yRecord.getClientId())
&& xRecord.getCompanyName().equalsIgnoreCase(
yRecord.getCompanyName())
&& xRecord.getSuite().equalsIgnoreCase(
yRecord.getSuite())
&& xRecord.getLocationAddress().equalsIgnoreCase(
yRecord.getLocationAddress())
&& xRecord.getLocationCity().equalsIgnoreCase(
yRecord.getLocationCity())
&& xRecord.getLocationState().equalsIgnoreCase(
yRecord.getLocationState())
&& xRecord.getLocationPhone().equals(
yRecord.getLocationPhone())
&& xRecord.getLocationZipCode().equalsIgnoreCase(
yRecord.getLocationZipCode())) {
isStoreDuplicate = true;
}
}
}
return isStoreDuplicate;
}
/***
*
* this method check's the data in the excel sheet with database and returns
* the correct data to businessinfo method
*
* @param records
* @return
*/
public List<LocalBusinessDTO> checkRecordsInListings(
List<LocalBusinessDTO> records, Map<String, Long> brandsCountsMap) {
List<LocalBusinessDTO> insertRecord = new ArrayList<LocalBusinessDTO>();
listofDeletesbyActionCode = new ArrayList<LocalBusinessDTO>();
updateBusinessRecords = new ArrayList<LocalBusinessDTO>();
List<LocalBusinessDTO> listOfBusinessInfo = service
.getListOfBusinessInfo();
List<LblErrorDTO> listOfErorBusinessInfo = service
.getListOfErorBusinessInfo();
List<LblErrorDTO> listOfErorBusinessInfos = new ArrayList<LblErrorDTO>();
for (int i = 0; i < records.size(); i++) {
LocalBusinessDTO excelRecord = records.get(i);
for (LblErrorDTO lblErrorDTO : listOfErorBusinessInfo) {
if (lblErrorDTO.getStore().equals(excelRecord.getStore())
&& lblErrorDTO.getClientId().equals(
excelRecord.getClientId())) {
listOfErorBusinessInfos.add(lblErrorDTO);
}
}
boolean isDuplicate = false;
for (int j = 0; j < listOfBusinessInfo.size(); j++) {
/* Business Name, Address, Suite, City, State, Zip and Phone */
LocalBusinessDTO dbRecord = listOfBusinessInfo.get(j);
if (dbRecord.getStore().equals(excelRecord.getStore())
&& dbRecord.getClientId().equals(
excelRecord.getClientId())) {
if (excelRecord.getActionCode().equalsIgnoreCase("D")) {
excelRecord.setId(dbRecord.getId());
listofDeletesbyActionCode.add(excelRecord);
} else {
excelRecord.setId(dbRecord.getId());
updateBusinessRecords.add(excelRecord);
}
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
if (!service.isBusinessExcelRecordUnique(excelRecord)) {
insertRecord.add(excelRecord);
}
} /*
* else { decreaseDuplicateRecordsLength(brandsCountsMap,
* excelRecord); }
*/
}
if (!listOfErorBusinessInfos.isEmpty()
&& listOfErorBusinessInfos.size() > 0) {
service.deleteErrorBusinessByActioncode(listOfErorBusinessInfos);
}
return insertRecord;
}
public List<LblErrorDTO> checkRecordsInListingErrors(
List<LblErrorDTO> records, Map<String, Long> brandsCountsMap) {
List<LblErrorDTO> insertErrorRecord = new ArrayList<LblErrorDTO>();
listofErrorDeletesbyActionCode = new ArrayList<LblErrorDTO>();
listOfErrorUpdatesByActionCode = new ArrayList<LblErrorDTO>();
List<LblErrorDTO> listOfErrorRecords = service
.getListOfErorBusinessInfo();
for (int i = 0; i < records.size(); i++) {
LblErrorDTO excelErrorRecord = records.get(i);
boolean isDuplicate = false;
for (int j = 0; j < listOfErrorRecords.size(); j++) {
LblErrorDTO dbRecord = listOfErrorRecords.get(j);
if (dbRecord.getStore().equals(excelErrorRecord.getStore())
&& dbRecord.getClientId().equals(
excelErrorRecord.getClientId())) {
if (excelErrorRecord.getActionCode().equalsIgnoreCase("D")) {
excelErrorRecord.setId(dbRecord.getId());
listofErrorDeletesbyActionCode.add(excelErrorRecord);
} else {
excelErrorRecord.setId(dbRecord.getId());
listOfErrorUpdatesByActionCode.add(excelErrorRecord);
}
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
insertErrorRecord.add(excelErrorRecord);
}/*
* else { decreaseErrorDuplicateRecordsLength(brandsCountsMap,
* excelErrorRecord); }
*/
}
return insertErrorRecord;
}
public List<LblErrorDTO> correctDBErrorRecords(
List<LocalBusinessDTO> records) {
List<LblErrorDTO> insertErrorRecord = new ArrayList<LblErrorDTO>();
List<LblErrorDTO> listOfErrorRecords = service
.getListOfErorBusinessInfo();
for (int i = 0; i < records.size(); i++) {
LocalBusinessDTO excelRecord = records.get(i);
for (int j = 0; j < listOfErrorRecords.size(); j++) {
LblErrorDTO dbRecord = listOfErrorRecords.get(j);
/*
* logger.info(dbRecord.getStore() + ".equals(" +
* excelRecord.getStore() + " , " + dbRecord.getClientId() +
* ".equals(" + excelRecord.getClientId());
*/
if (dbRecord.getStore().equals(excelRecord.getStore())
&& dbRecord.getClientId().equals(
excelRecord.getClientId())) {
records.remove(i);
i--;
insertErrorRecord.add(dbRecord);
break;
}
}
}
logger.info("Correct Suitable Records == " + insertErrorRecord.size());
logger.info("Duplicate Records == " + duplicateRecord.size());
return insertErrorRecord;
}
/***
* this method takes the list of information from excel
*
* @param infile
* @return
*/
public boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
return false;
}
return true;
}
private List<UploadBusinessBean> getListDataFromXLS(
CommonsMultipartFile infile, Map<String, Long> brandsCountsMap,
String headerpopup) {
List<UploadBusinessBean> tListData = new ArrayList<UploadBusinessBean>();
try {
Sheet sheet = (Sheet) WorkbookFactory.create(
infile.getInputStream()).getSheetAt(0);
DataFormatter df = new DataFormatter();
Iterator<Row> rowIterator = sheet.rowIterator();
boolean header = true;
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
boolean rowEmpty = isRowEmpty(row);
if (rowEmpty == false) {
if (header) {
header = false;
headerpopup = "";
if (!headersValid(row, df)) {
headerpopup = "Invalid Bulk Upload Template";
return tListData;
}
continue;
}
UploadBusinessBean uploadBusinessBean = new UploadBusinessBean();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell == null) // Process only the rows with some
// data
continue;
int columnIndex = cell.getColumnIndex();
// System.out.println("columnIndex" + columnIndex);
String formatCellValue = df.formatCellValue(cell);
// System.out.println("formatCellValue" +
// formatCellValue);
org.apache.commons.beanutils.BeanUtils
.setProperty(
uploadBusinessBean,
LBLConstants.UPLOAD_BEAN_PROPERTIES[columnIndex],
formatCellValue);
}
tListData.add(uploadBusinessBean);
}
}
} catch (Exception e) {
headerpopup = "Invalid Bulk Upload Template";
logger.error("Exception : " + e);
e.printStackTrace();
}
logger.info("Excel sheet Records size == " + tListData.size());
logger.info(tListData);
return tListData;
}
private boolean allValuesInRowAreEmpty(String[] row) {
boolean returnValue = true;
for (String s : row) {
if (s.length() != 0) {
returnValue = false;
}
}
return returnValue;
}
private List<UploadBusinessBean> getListFromCSV(CommonsMultipartFile file,
Map<String, Long> brandsCountsMap, String headerpopup) {
List<UploadBusinessBean> tListData = new ArrayList<UploadBusinessBean>();
boolean value = isheaderValid(file);
if (!value) {
headerpopup = "Invalid Bulk Upload Template";
return tListData;
}
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
CSVReader reader = new CSVReader(bufferedReader, ',', '"', 1);
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
UploadBusinessBean uploadBusinessBean = new UploadBusinessBean();
if (nextLine != null) {
for (int i = 0; i < nextLine.length; i++) {
try {
org.apache.commons.beanutils.BeanUtils.setProperty(
uploadBusinessBean,
LBLConstants.UPLOAD_BEAN_PROPERTIES[i],
nextLine[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
tListData.add(uploadBusinessBean);
}
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Excel CSV sheet Records size == " + tListData.size());
logger.info(tListData);
return tListData;
}
private boolean isheaderValid(CommonsMultipartFile file) {
boolean isHeadersValid = true;
CSVParser parser;
try {
InputStream inputStream = file.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
parser = new CSVParser(bufferedReader,
CSVFormat.DEFAULT.withHeader());
Map<String, Integer> headerMap = parser.getHeaderMap();
List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
list.add(entry.getKey());
}
for (int i = 0; i < list.size(); i++) {
String anotherString = LBLConstants.UPLOAD_EXCEL_HEADERS[i];
if (!list.get(i).equalsIgnoreCase(anotherString)) {
isHeadersValid = false;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return isHeadersValid;
}
private boolean isheaderValid(Map<String, Integer> headerMap) {
boolean isHeadersValid = true;
List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
list.add(entry.getKey());
}
for (int i = 0; i < list.size(); i++) {
String anotherString = LBLConstants.UPLOAD_EXCEL_HEADERS[i];
if (!list.get(i).equalsIgnoreCase(anotherString)) {
isHeadersValid = false;
break;
}
}
return isHeadersValid;
// TODO Auto-generated method stub
}
private boolean headersValid(List<String> list) {
boolean isHeadersValid = true;
for (int i = 0; i < list.size(); i++) {
// System.out.println(list.get(i));
String anotherString = LBLConstants.UPLOAD_EXCEL_HEADERS[i];
// System.out.println(anotherString);
if (!list.get(i).equalsIgnoreCase(anotherString)) {
isHeadersValid = false;
break;
}
}
return isHeadersValid;
}
/**
* headersValidation
*
* @param row
* @param df
* @return
*/
public boolean headersValid(Row row, DataFormatter df) {
Iterator<Cell> cellIterator = row.cellIterator();
boolean isHeadersValid = true;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell == null
|| (!df.formatCellValue(cell).equalsIgnoreCase(
LBLConstants.UPLOAD_EXCEL_HEADERS[cell
.getColumnIndex()]))) {
isHeadersValid = false;
break;
}
}
return isHeadersValid;
}
}
| 32,963 | 0.695871 | 0.693687 | 999 | 30.995996 | 24.590662 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.01001 | false | false |
3
|
6d683682c5e9a79fdd799ecfbe18191c39ef3931
| 9,019,431,340,150 |
0a0d22317e773ca97976f1a039577148c7f02d7a
|
/project/app/src/main/java/com/jonas/firebaseauth/ListNomes.java
|
54fe96432a21a19b22cff4dee585cbb0c43507dc
|
[] |
no_license
|
jonassilvati/AuthFirebasePhone
|
https://github.com/jonassilvati/AuthFirebasePhone
|
fc7bf6bd3f454156cd6dc0eac3cda03a8a53fa30
|
9a93d4782ba8ba67ccc941b6201855d4f0635d83
|
refs/heads/master
| 2020-09-04T11:55:36.435000 | 2019-11-05T11:14:17 | 2019-11-05T11:14:17 | 219,726,112 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jonas.firebaseauth;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jonas.firebaseauth.dao.NomeDao;
import com.jonas.firebaseauth.model.Nome;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
import static com.jonas.firebaseauth.HomeActivity.MODE;
import static com.jonas.firebaseauth.HomeActivity.MODE_INSERT;
public class ListNomes extends AppCompatActivity {
public static final String ID_NOME = "id_nome";
public RecyclerView mRecyclerView;
public NomeAdapter nomeAdapter;
public NomeDao nomeDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_nomes);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startPersistNome();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//get recycler
mRecyclerView = findViewById(R.id.recycler);
//get list of nomes
nomeDao = new NomeDao(ListNomes.this);
setupRecycler();
}
public void startPersistNome(){
Intent intent = new Intent(getBaseContext(), PersistNome.class);
intent.putExtra(MODE, MODE_INSERT);
startActivity(intent);
}
public void setupRecycler(){
ArrayList<Nome> items = (ArrayList<Nome>) nomeDao.getNomes();
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
// Adiciona o adapter que irá anexar os objetos à lista.
nomeAdapter = new NomeAdapter(items, ListNomes.this);
mRecyclerView.setAdapter(nomeAdapter);
// Configurando um divider entre linhas, para uma melhor visualização.
mRecyclerView.addItemDecoration(
new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
@Override
protected void onPostResume() {
super.onPostResume();
setupRecycler();
}
}
|
UTF-8
|
Java
| 2,581 |
java
|
ListNomes.java
|
Java
|
[] | null |
[] |
package com.jonas.firebaseauth;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jonas.firebaseauth.dao.NomeDao;
import com.jonas.firebaseauth.model.Nome;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
import static com.jonas.firebaseauth.HomeActivity.MODE;
import static com.jonas.firebaseauth.HomeActivity.MODE_INSERT;
public class ListNomes extends AppCompatActivity {
public static final String ID_NOME = "id_nome";
public RecyclerView mRecyclerView;
public NomeAdapter nomeAdapter;
public NomeDao nomeDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_nomes);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startPersistNome();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//get recycler
mRecyclerView = findViewById(R.id.recycler);
//get list of nomes
nomeDao = new NomeDao(ListNomes.this);
setupRecycler();
}
public void startPersistNome(){
Intent intent = new Intent(getBaseContext(), PersistNome.class);
intent.putExtra(MODE, MODE_INSERT);
startActivity(intent);
}
public void setupRecycler(){
ArrayList<Nome> items = (ArrayList<Nome>) nomeDao.getNomes();
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
// Adiciona o adapter que irá anexar os objetos à lista.
nomeAdapter = new NomeAdapter(items, ListNomes.this);
mRecyclerView.setAdapter(nomeAdapter);
// Configurando um divider entre linhas, para uma melhor visualização.
mRecyclerView.addItemDecoration(
new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
@Override
protected void onPostResume() {
super.onPostResume();
setupRecycler();
}
}
| 2,581 | 0.712068 | 0.712068 | 79 | 31.620253 | 24.192427 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582278 | false | false |
3
|
aaed4386eb2d00ed9f81b6d864ee8507c0ef1b7b
| 11,785,390,263,395 |
17fd1c8217225446cdbbb0c8ef48dd00da13e098
|
/src/main/java/model/mapping/Bus.java
|
c181b48297e3fd13e65eac8f9b75201bee389383
|
[] |
no_license
|
tsuchodolskij/BD2_Rental_Service
|
https://github.com/tsuchodolskij/BD2_Rental_Service
|
4bb626a24b6316cdcd90b21df22b58c682125ae7
|
f97a87727808e92e63f4e839f0d1be7ed1c6f08b
|
refs/heads/master
| 2020-04-17T16:26:54 | 2019-01-21T03:14:45 | 2019-01-21T03:14:45 | 166,740,419 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package model.mapping;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import model.tableview.AllBuses;
import javax.persistence.*;
import java.sql.Date;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name="Bus")
@Entity
public class Bus {
@Id
@Column(name="Registration_number", nullable=false)
private String registrationNumber;
@Column(name = "Tech_evaluation_date", nullable = false)
private Date techEvaluationDate;
@Column(name = "Size_capacity", nullable = false)
private Long sizeCapacity;
@Column(name="OC_AC", nullable=false)
private Long ocAc;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "District_name", nullable = false),
@JoinColumn(name = "Agency_ID", nullable = false)
})
private Agency agency;
@OneToMany(mappedBy = "bus")
private List<Driver> drivers;
public AllBuses toAllBuses(){
return AllBuses.builder()
.registration(registrationNumber)
.capacity(sizeCapacity)
.evaluationDate(techEvaluationDate)
.district(agency.getAgencyPk().getDistrict().getName())
.build();
}
}
|
UTF-8
|
Java
| 1,279 |
java
|
Bus.java
|
Java
|
[] | null |
[] |
package model.mapping;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import model.tableview.AllBuses;
import javax.persistence.*;
import java.sql.Date;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name="Bus")
@Entity
public class Bus {
@Id
@Column(name="Registration_number", nullable=false)
private String registrationNumber;
@Column(name = "Tech_evaluation_date", nullable = false)
private Date techEvaluationDate;
@Column(name = "Size_capacity", nullable = false)
private Long sizeCapacity;
@Column(name="OC_AC", nullable=false)
private Long ocAc;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "District_name", nullable = false),
@JoinColumn(name = "Agency_ID", nullable = false)
})
private Agency agency;
@OneToMany(mappedBy = "bus")
private List<Driver> drivers;
public AllBuses toAllBuses(){
return AllBuses.builder()
.registration(registrationNumber)
.capacity(sizeCapacity)
.evaluationDate(techEvaluationDate)
.district(agency.getAgencyPk().getDistrict().getName())
.build();
}
}
| 1,279 | 0.666145 | 0.666145 | 52 | 23.615385 | 19.461159 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442308 | false | false |
3
|
8d94c52e2f592b0785e3e9890d387c4bc2984a76
| 26,018,911,911,891 |
2c50410a671956784d2c4ef75ee7df17e2e1662c
|
/opendatakraken-core/src/main/java/org/opendatakraken/core/db/DictionaryConverter.java
|
09fbc0b5bcdf65b83893b20a54475cbd04f7675d
|
[
"MIT"
] |
permissive
|
opendk/opendatakraken
|
https://github.com/opendk/opendatakraken
|
ce138ab90c0d7374c9caaa1538d3a47337c8173f
|
6aafd06d40946b0f02eb0f223abf66e919da8275
|
refs/heads/master
| 2021-04-17T19:47:20.731000 | 2017-10-24T15:15:35 | 2017-10-24T15:15:35 | 41,373,849 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.opendatakraken.core.db;
import javax.xml.parsers.*;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;
/**
* Class for replication of database tables between databases
* @author Nicola Marangoni
*/
public class DictionaryConverter {
static final org.slf4j.Logger logger = LoggerFactory.getLogger(DictionaryConverter.class);
// Declarations of bean properties
// Source properties
private DBConnection sourceCon = null;
private String sourceSchema = "";
private String sourceTable = "";
private String sourceQuery = "";
// Target properties
private DBConnection targetCon = null;
// Mapping properties
private String mappingDefFile = "";
private String[] sourceMapColumns = null;
private String[] targetMapColumns = null;
private String[] targetDefaultColumns = null;
private String[] targetDefaultValues = null;
// Declarations of internally used variables
org.w3c.dom.Document typeConvertionMatrix = null;
org.w3c.dom.Document typeOptionMatrix = null;
//
private int columnCount = 0;
private int[] columnPkPosition = null;
private int[] columnJdbcType = null;
//
private String[] sourceColumnNames = null;
private String[] sourceColumnType = null;
private String[] sourceColumnTypeAttribute = null;
private int[] sourceColumnLength = null;
private int[] sourceColumnPrecision = null;
private int[] sourceColumnScale = null;
private String[] sourceColumnDefinition = null;
//
private String[] targetColumnNames = null;
private String[] targetColumnType = null;
private String[] targetColumnTypeAttribute = null;
private int[] targetColumnLength = null;
private int[] targetColumnPrecision = null;
private int[] targetColumnScale = null;
private String[] targetColumnDefinition = null;
// Constructor
public DictionaryConverter() {
super();
}
// Set source properties methods
public void setSourceSchema(String property) {
sourceSchema = property;
}
public void setSourceTable(String property) {
sourceTable = property;
}
public void setSourceQuery(String property) {
sourceQuery = property;
}
public void setSourceConnection(DBConnection property) {
sourceCon = property;
}
public void setTargetConnection(DBConnection property) {
targetCon = property;
}
// Set optional mapping properties
public void setMappingDefFile(String property) {
mappingDefFile = property;
}
public void setSourceMapColumns(String[] property) {
sourceMapColumns = property;
}
public void setTargetMapColumns(String[] property) {
targetMapColumns = property;
}
public void setTargetDefaultColumns(String[] property) {
targetDefaultColumns = property;
}
// Get methods
public String[] getSourceColumnNames() {
return sourceColumnNames;
}
public String[] getSourceColumnDefinition() {
return sourceColumnDefinition;
}
public String[] getTargetColumnNames() {
return targetColumnNames;
}
public String[] getTargetColumnDefinition() {
return targetColumnDefinition;
}
public int[] getColumnJdbcType() {
return columnJdbcType;
}
public int[] getSourceColumnPkPositions() {
return columnPkPosition;
}
public void retrieveColumns() throws Exception {
DictionaryExtractor sourceDictionary = new DictionaryExtractor();
sourceDictionary.setSourceConnection(sourceCon);
sourceDictionary.setSourceSchema(sourceSchema);
sourceDictionary.setSourceTable(sourceTable);
sourceDictionary.setSourceQuery(sourceQuery);
//
sourceDictionary.retrieveColumns();
//
columnCount = sourceDictionary.getColumnCount();
sourceColumnNames = sourceDictionary.getColumnNames();
sourceColumnType = sourceDictionary.getColumnTypes();
sourceColumnTypeAttribute = sourceDictionary.getColumnTypeAttribute();
sourceColumnLength = sourceDictionary.getColumnLength();
sourceColumnPrecision = sourceDictionary.getColumnPrecision();
sourceColumnScale = sourceDictionary.getColumnScale();
columnJdbcType = sourceDictionary.getColumnJdbcType();
String sourceProductName;
String targetProductName;
sourceProductName = sourceCon.getDatabaseProductName();
targetProductName = targetCon.getDatabaseProductName();
logger.info("Source RDBMS product: " + sourceProductName);
logger.info("Target RDBMS product: " + targetProductName);
sourceColumnDefinition = new String[columnCount];
targetColumnNames = new String[columnCount];
targetColumnType = new String[columnCount];
targetColumnTypeAttribute = new String[columnCount];
targetColumnLength = new int[columnCount];
targetColumnPrecision = new int[columnCount];
targetColumnScale = new int[columnCount];
targetColumnDefinition = new String[columnCount];
columnPkPosition = new int[columnCount];
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
// Load type convertion matrix
typeConvertionMatrix = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
typeConvertionMatrix = docBuilder.parse(Thread.currentThread().getContextClassLoader().getResource("datatypes/typeConvertionMatrix.xml").toString());
typeConvertionMatrix.getDocumentElement().normalize();
}
catch(Exception e) {
logger.error("Cannot load option file: " + e.getMessage());
e.printStackTrace();
throw e;
}
// Load type option matrix
typeOptionMatrix = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
typeOptionMatrix = docBuilder.parse(Thread.currentThread().getContextClassLoader().getResource("datatypes/typeOptionMatrix.xml").toString());
typeOptionMatrix.getDocumentElement().normalize();
}
catch(Exception e) {
logger.error("Cannot load option file: " + e.getMessage());
e.printStackTrace();
throw e;
}
TypeConverter typeConverter = new TypeConverter();
typeConverter.setTypeConvertionMatrix(typeConvertionMatrix);
typeConverter.setTypeOptionMatrix(typeOptionMatrix);
for (int i = 0; i < columnCount; i++) {
//sourceColumnNames[i] = rsmd.getColumnName(i).toUpperCase();
targetColumnNames[i] = sourceColumnNames[i];
targetColumnNames[i] = targetCon.getColumnIdentifier(targetColumnNames[i]);
logger.info("get mapped column...");
if (sourceMapColumns != null) {
for (int mc = 0; mc < sourceMapColumns.length; mc++) {
if (sourceMapColumns[mc].equalsIgnoreCase(sourceColumnNames[i])) {
sourceColumnNames[i] = targetMapColumns[mc];
targetColumnNames[i] = targetMapColumns[mc];
}
}
}
logger.info("got mapped column");
//******************************
// Use type converter
typeConverter.setSourceProductName(sourceProductName);
typeConverter.setTargetProductName(targetProductName);
typeConverter.setSourceColumnType(sourceColumnType[i]);
typeConverter.setSourceColumnTypeAttribute(sourceColumnTypeAttribute[i]);
typeConverter.setSourceColumnLength(sourceColumnLength[i]);
typeConverter.setSourceColumnPrecision(sourceColumnPrecision[i]);
typeConverter.setSourceColumnScale(sourceColumnScale[i]);
logger.debug("convert datatype...");
typeConverter.convert();
logger.debug("datatype converted");
sourceColumnDefinition[i] = typeConverter.getSourceColumnDefinition();
targetColumnType[i] = typeConverter.getTargetColumnType();
targetColumnTypeAttribute[i] = typeConverter.getTargetColumnTypeAttribute();
targetColumnLength[i] = typeConverter.getTargetColumnLength();
targetColumnPrecision[i] = typeConverter.getTargetColumnPrecision();
targetColumnScale[i] = typeConverter.getTargetColumnScale();
targetColumnDefinition[i] = typeConverter.getTargetColumnDefinition();
logger.debug("Source column " + (i) + " Name: " + sourceColumnNames[i] + " Type: " + sourceColumnType[i] + " Attribute: " + sourceColumnTypeAttribute[i] + " Length: " + sourceColumnLength[i] + " Precision: " + sourceColumnPrecision[i] + " Scale: " +sourceColumnScale[i] + " Definition: " + sourceColumnDefinition[i]);
logger.debug("Target column " + (i) + " Name: " + targetColumnNames[i] + " Type: " + targetColumnType[i] + " Attribute: " + targetColumnTypeAttribute[i] + " Length: " + targetColumnLength[i] + " Precision: " + targetColumnPrecision[i] + " Scale: " +targetColumnScale[i] + " Definition: " + targetColumnDefinition[i]);
}
}
public void retrieveMappingDefinition() throws Exception {
// Load mapping definition file
logger.info("LOADING MAP DEFINITION FILE " + mappingDefFile + "...");
org.w3c.dom.Document mappingXML = null;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
mappingXML = docBuilder.parse(mappingDefFile);
mappingXML.getDocumentElement().normalize();
// Local variables
NodeList nList;
Node nNode;
Element eElement;
// get source to target column mapping
nList = mappingXML.getElementsByTagName("columnMapping");
sourceMapColumns = new String[nList.getLength()];
targetMapColumns = new String[nList.getLength()];
for (int i = 0; i < nList.getLength(); i++) {
nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
eElement = (Element)nNode;
sourceMapColumns[i] = eElement.getElementsByTagName("source").item(0).getChildNodes().item(0).getNodeValue();
targetMapColumns[i] = eElement.getElementsByTagName("target").item(0).getChildNodes().item(0).getNodeValue();
}
}
// get default value to target column mapping
nList = mappingXML.getElementsByTagName("defaultValue");
targetDefaultColumns = new String[nList.getLength()];
targetDefaultValues = new String[nList.getLength()];
for (int i = 0; i < nList.getLength(); i++) {
nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
eElement = (Element)nNode;
targetDefaultColumns[i] = eElement.getElementsByTagName("column").item(0).getChildNodes().item(0).getNodeValue();
targetDefaultValues[i] = eElement.getElementsByTagName("value").item(0).getChildNodes().item(0).getNodeValue();
}
}
logger.info("LOADED MAP DEFINITION FILE");
}
}
|
UTF-8
|
Java
| 11,225 |
java
|
DictionaryConverter.java
|
Java
|
[
{
"context": "on of database tables between databases\n * @author Nicola Marangoni\n */\npublic class DictionaryConverter {\n\n\tstatic f",
"end": 214,
"score": 0.9998717308044434,
"start": 198,
"tag": "NAME",
"value": "Nicola Marangoni"
}
] | null |
[] |
package org.opendatakraken.core.db;
import javax.xml.parsers.*;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;
/**
* Class for replication of database tables between databases
* @author <NAME>
*/
public class DictionaryConverter {
static final org.slf4j.Logger logger = LoggerFactory.getLogger(DictionaryConverter.class);
// Declarations of bean properties
// Source properties
private DBConnection sourceCon = null;
private String sourceSchema = "";
private String sourceTable = "";
private String sourceQuery = "";
// Target properties
private DBConnection targetCon = null;
// Mapping properties
private String mappingDefFile = "";
private String[] sourceMapColumns = null;
private String[] targetMapColumns = null;
private String[] targetDefaultColumns = null;
private String[] targetDefaultValues = null;
// Declarations of internally used variables
org.w3c.dom.Document typeConvertionMatrix = null;
org.w3c.dom.Document typeOptionMatrix = null;
//
private int columnCount = 0;
private int[] columnPkPosition = null;
private int[] columnJdbcType = null;
//
private String[] sourceColumnNames = null;
private String[] sourceColumnType = null;
private String[] sourceColumnTypeAttribute = null;
private int[] sourceColumnLength = null;
private int[] sourceColumnPrecision = null;
private int[] sourceColumnScale = null;
private String[] sourceColumnDefinition = null;
//
private String[] targetColumnNames = null;
private String[] targetColumnType = null;
private String[] targetColumnTypeAttribute = null;
private int[] targetColumnLength = null;
private int[] targetColumnPrecision = null;
private int[] targetColumnScale = null;
private String[] targetColumnDefinition = null;
// Constructor
public DictionaryConverter() {
super();
}
// Set source properties methods
public void setSourceSchema(String property) {
sourceSchema = property;
}
public void setSourceTable(String property) {
sourceTable = property;
}
public void setSourceQuery(String property) {
sourceQuery = property;
}
public void setSourceConnection(DBConnection property) {
sourceCon = property;
}
public void setTargetConnection(DBConnection property) {
targetCon = property;
}
// Set optional mapping properties
public void setMappingDefFile(String property) {
mappingDefFile = property;
}
public void setSourceMapColumns(String[] property) {
sourceMapColumns = property;
}
public void setTargetMapColumns(String[] property) {
targetMapColumns = property;
}
public void setTargetDefaultColumns(String[] property) {
targetDefaultColumns = property;
}
// Get methods
public String[] getSourceColumnNames() {
return sourceColumnNames;
}
public String[] getSourceColumnDefinition() {
return sourceColumnDefinition;
}
public String[] getTargetColumnNames() {
return targetColumnNames;
}
public String[] getTargetColumnDefinition() {
return targetColumnDefinition;
}
public int[] getColumnJdbcType() {
return columnJdbcType;
}
public int[] getSourceColumnPkPositions() {
return columnPkPosition;
}
public void retrieveColumns() throws Exception {
DictionaryExtractor sourceDictionary = new DictionaryExtractor();
sourceDictionary.setSourceConnection(sourceCon);
sourceDictionary.setSourceSchema(sourceSchema);
sourceDictionary.setSourceTable(sourceTable);
sourceDictionary.setSourceQuery(sourceQuery);
//
sourceDictionary.retrieveColumns();
//
columnCount = sourceDictionary.getColumnCount();
sourceColumnNames = sourceDictionary.getColumnNames();
sourceColumnType = sourceDictionary.getColumnTypes();
sourceColumnTypeAttribute = sourceDictionary.getColumnTypeAttribute();
sourceColumnLength = sourceDictionary.getColumnLength();
sourceColumnPrecision = sourceDictionary.getColumnPrecision();
sourceColumnScale = sourceDictionary.getColumnScale();
columnJdbcType = sourceDictionary.getColumnJdbcType();
String sourceProductName;
String targetProductName;
sourceProductName = sourceCon.getDatabaseProductName();
targetProductName = targetCon.getDatabaseProductName();
logger.info("Source RDBMS product: " + sourceProductName);
logger.info("Target RDBMS product: " + targetProductName);
sourceColumnDefinition = new String[columnCount];
targetColumnNames = new String[columnCount];
targetColumnType = new String[columnCount];
targetColumnTypeAttribute = new String[columnCount];
targetColumnLength = new int[columnCount];
targetColumnPrecision = new int[columnCount];
targetColumnScale = new int[columnCount];
targetColumnDefinition = new String[columnCount];
columnPkPosition = new int[columnCount];
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
// Load type convertion matrix
typeConvertionMatrix = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
typeConvertionMatrix = docBuilder.parse(Thread.currentThread().getContextClassLoader().getResource("datatypes/typeConvertionMatrix.xml").toString());
typeConvertionMatrix.getDocumentElement().normalize();
}
catch(Exception e) {
logger.error("Cannot load option file: " + e.getMessage());
e.printStackTrace();
throw e;
}
// Load type option matrix
typeOptionMatrix = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
typeOptionMatrix = docBuilder.parse(Thread.currentThread().getContextClassLoader().getResource("datatypes/typeOptionMatrix.xml").toString());
typeOptionMatrix.getDocumentElement().normalize();
}
catch(Exception e) {
logger.error("Cannot load option file: " + e.getMessage());
e.printStackTrace();
throw e;
}
TypeConverter typeConverter = new TypeConverter();
typeConverter.setTypeConvertionMatrix(typeConvertionMatrix);
typeConverter.setTypeOptionMatrix(typeOptionMatrix);
for (int i = 0; i < columnCount; i++) {
//sourceColumnNames[i] = rsmd.getColumnName(i).toUpperCase();
targetColumnNames[i] = sourceColumnNames[i];
targetColumnNames[i] = targetCon.getColumnIdentifier(targetColumnNames[i]);
logger.info("get mapped column...");
if (sourceMapColumns != null) {
for (int mc = 0; mc < sourceMapColumns.length; mc++) {
if (sourceMapColumns[mc].equalsIgnoreCase(sourceColumnNames[i])) {
sourceColumnNames[i] = targetMapColumns[mc];
targetColumnNames[i] = targetMapColumns[mc];
}
}
}
logger.info("got mapped column");
//******************************
// Use type converter
typeConverter.setSourceProductName(sourceProductName);
typeConverter.setTargetProductName(targetProductName);
typeConverter.setSourceColumnType(sourceColumnType[i]);
typeConverter.setSourceColumnTypeAttribute(sourceColumnTypeAttribute[i]);
typeConverter.setSourceColumnLength(sourceColumnLength[i]);
typeConverter.setSourceColumnPrecision(sourceColumnPrecision[i]);
typeConverter.setSourceColumnScale(sourceColumnScale[i]);
logger.debug("convert datatype...");
typeConverter.convert();
logger.debug("datatype converted");
sourceColumnDefinition[i] = typeConverter.getSourceColumnDefinition();
targetColumnType[i] = typeConverter.getTargetColumnType();
targetColumnTypeAttribute[i] = typeConverter.getTargetColumnTypeAttribute();
targetColumnLength[i] = typeConverter.getTargetColumnLength();
targetColumnPrecision[i] = typeConverter.getTargetColumnPrecision();
targetColumnScale[i] = typeConverter.getTargetColumnScale();
targetColumnDefinition[i] = typeConverter.getTargetColumnDefinition();
logger.debug("Source column " + (i) + " Name: " + sourceColumnNames[i] + " Type: " + sourceColumnType[i] + " Attribute: " + sourceColumnTypeAttribute[i] + " Length: " + sourceColumnLength[i] + " Precision: " + sourceColumnPrecision[i] + " Scale: " +sourceColumnScale[i] + " Definition: " + sourceColumnDefinition[i]);
logger.debug("Target column " + (i) + " Name: " + targetColumnNames[i] + " Type: " + targetColumnType[i] + " Attribute: " + targetColumnTypeAttribute[i] + " Length: " + targetColumnLength[i] + " Precision: " + targetColumnPrecision[i] + " Scale: " +targetColumnScale[i] + " Definition: " + targetColumnDefinition[i]);
}
}
public void retrieveMappingDefinition() throws Exception {
// Load mapping definition file
logger.info("LOADING MAP DEFINITION FILE " + mappingDefFile + "...");
org.w3c.dom.Document mappingXML = null;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
mappingXML = docBuilder.parse(mappingDefFile);
mappingXML.getDocumentElement().normalize();
// Local variables
NodeList nList;
Node nNode;
Element eElement;
// get source to target column mapping
nList = mappingXML.getElementsByTagName("columnMapping");
sourceMapColumns = new String[nList.getLength()];
targetMapColumns = new String[nList.getLength()];
for (int i = 0; i < nList.getLength(); i++) {
nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
eElement = (Element)nNode;
sourceMapColumns[i] = eElement.getElementsByTagName("source").item(0).getChildNodes().item(0).getNodeValue();
targetMapColumns[i] = eElement.getElementsByTagName("target").item(0).getChildNodes().item(0).getNodeValue();
}
}
// get default value to target column mapping
nList = mappingXML.getElementsByTagName("defaultValue");
targetDefaultColumns = new String[nList.getLength()];
targetDefaultValues = new String[nList.getLength()];
for (int i = 0; i < nList.getLength(); i++) {
nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
eElement = (Element)nNode;
targetDefaultColumns[i] = eElement.getElementsByTagName("column").item(0).getChildNodes().item(0).getNodeValue();
targetDefaultValues[i] = eElement.getElementsByTagName("value").item(0).getChildNodes().item(0).getNodeValue();
}
}
logger.info("LOADED MAP DEFINITION FILE");
}
}
| 11,215 | 0.687483 | 0.685791 | 291 | 37.57732 | 37.215496 | 337 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.371134 | false | false |
3
|
d7580c6ccf730a12263ca2bb1e7db15f1f83ccf9
| 23,287,312,745,944 |
40c037d31d32d8dd70c9f1602a7d8ff48b7821b1
|
/src/test/java/backend/BaseTest.java
|
8352f4dfd3b8edef7a5985bc9f15e196fba7422d
|
[] |
no_license
|
leemurus/Tic-tac-toe
|
https://github.com/leemurus/Tic-tac-toe
|
9a5e29f5af65bda18a5bbc16b7d2471b90614282
|
4cb4061d22799e49dab64955cb58e3af071d1938
|
refs/heads/master
| 2022-12-26T12:46:49.250000 | 2020-04-06T00:03:48 | 2020-04-06T00:03:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package backend;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class BaseTest {
private Field field;
@Before
public void setUp() {
field = new Field(3);
}
@After
public void tearDown() {
field = null;
}
@Test
public void testGetMethodBigNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.getCell(3, 3);
field.getCell(1, 20);
field.getCell(20, 1);
field.getCell(20, 20);
});
}
@Test
public void testGetMethodNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.getCell(-10, 10);
field.getCell(10, -10);
field.getCell(-10, -10);
});
}
@Test
public void testSetMethodBigNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.setCell(3, 3, Figure.CROSS);
field.setCell(1, 20, Figure.CROSS);
field.setCell(20, 1, Figure.CROSS);
field.setCell(20, 20, Figure.CROSS);
});
}
@Test
public void testSetMethodNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.setCell(-20, 1, Figure.CROSS);
field.setCell(1, -20, Figure.CROSS);
field.setCell(-20, -20, Figure.CROSS);
});
}
@Test
public void testGetSetMethods() {
field.setCell(0, 0, Figure.ZERO);
assertEquals(field.getCell(0, 0), Figure.ZERO);
}
}
|
UTF-8
|
Java
| 1,678 |
java
|
BaseTest.java
|
Java
|
[] | null |
[] |
package backend;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class BaseTest {
private Field field;
@Before
public void setUp() {
field = new Field(3);
}
@After
public void tearDown() {
field = null;
}
@Test
public void testGetMethodBigNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.getCell(3, 3);
field.getCell(1, 20);
field.getCell(20, 1);
field.getCell(20, 20);
});
}
@Test
public void testGetMethodNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.getCell(-10, 10);
field.getCell(10, -10);
field.getCell(-10, -10);
});
}
@Test
public void testSetMethodBigNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.setCell(3, 3, Figure.CROSS);
field.setCell(1, 20, Figure.CROSS);
field.setCell(20, 1, Figure.CROSS);
field.setCell(20, 20, Figure.CROSS);
});
}
@Test
public void testSetMethodNegativeNumbers() {
assertThrows(IllegalArgumentException.class, () -> {
field.setCell(-20, 1, Figure.CROSS);
field.setCell(1, -20, Figure.CROSS);
field.setCell(-20, -20, Figure.CROSS);
});
}
@Test
public void testGetSetMethods() {
field.setCell(0, 0, Figure.ZERO);
assertEquals(field.getCell(0, 0), Figure.ZERO);
}
}
| 1,678 | 0.576877 | 0.546484 | 66 | 24.424242 | 19.818159 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.878788 | false | false |
3
|
4a2eb2f2b0e13541cbb4065796ca5328552762a6
| 13,984,413,535,955 |
8ca051b82cff6c96a8f28129d7bd5475d78e15a8
|
/app/src/main/java/edu/gsu/httpscs/nipuna2017summer/ActivityC.java
|
d30f043159880cae420a268fb84e11fdaa793a2a
|
[] |
no_license
|
nipunasenanayake/Nipuna2017Summer
|
https://github.com/nipunasenanayake/Nipuna2017Summer
|
3dd29d4e1d4144a5dfac1365aedc55ff53ca1db2
|
906bc21479e959fd291e01ce662211f9bd1282d2
|
refs/heads/master
| 2021-06-18T11:29:04.639000 | 2017-07-04T03:10:46 | 2017-07-04T03:10:46 | 93,599,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.gsu.httpscs.nipuna2017summer;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ActivityC extends BaseActivity {
@OnClick(R.id.activity_c_a)
public void toA(View v){
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
}
@OnClick (R.id.activity_c_b)
public void toB(View v){
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
startActivity(intent);
}
@OnClick (R.id.activity_c_c)
public void toC(View v){
Intent intent = new Intent(getApplicationContext(), ActivityC.class);
startActivity(intent);
}
@OnClick (R.id.activity_c_d)
public void toD(View v){
Intent intent = new Intent(getApplicationContext(), ActivityD.class);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c);
showToast("onCreateC");
ButterKnife.bind(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
showToast("onNewIntentC");
}
}
|
UTF-8
|
Java
| 1,368 |
java
|
ActivityC.java
|
Java
|
[] | null |
[] |
package edu.gsu.httpscs.nipuna2017summer;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ActivityC extends BaseActivity {
@OnClick(R.id.activity_c_a)
public void toA(View v){
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
}
@OnClick (R.id.activity_c_b)
public void toB(View v){
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
startActivity(intent);
}
@OnClick (R.id.activity_c_c)
public void toC(View v){
Intent intent = new Intent(getApplicationContext(), ActivityC.class);
startActivity(intent);
}
@OnClick (R.id.activity_c_d)
public void toD(View v){
Intent intent = new Intent(getApplicationContext(), ActivityD.class);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c);
showToast("onCreateC");
ButterKnife.bind(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
showToast("onNewIntentC");
}
}
| 1,368 | 0.677632 | 0.673977 | 52 | 25.307692 | 21.875116 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false |
3
|
074f489909d0defa659897fa661de7910bff63af
| 17,093,969,881,643 |
c089d0aa001163995aca03dd3d8aba7bef3b2f2a
|
/JPADemo/src/main/java/com/vroomcar/JPADemo/service/RideService.java
|
be2782c1486315fc1aacaae25f854b995688b8cd
|
[] |
no_license
|
swatibawankule/VroomCarRepo
|
https://github.com/swatibawankule/VroomCarRepo
|
15e1f808372994df35d9e32d6eb7b820161154e3
|
b87692590415b80ea0891f1515287ec4b89b2153
|
refs/heads/master
| 2020-08-24T01:25:22.261000 | 2019-10-22T06:42:04 | 2019-10-22T06:42:04 | 216,740,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vroomcar.JPADemo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.vroomcar.JPADemo.Exception.RideNotPresentException;
import com.vroomcar.JPADemo.beans.Ride;
import com.vroomcar.JPADemo.repository.RideJpaRepository;
@Component
public class RideService implements IRideService {
@Autowired
RideJpaRepository rideJPARepository;
@Override
public List<Ride> getAllRides() {
List<Ride> list = new ArrayList<>();
rideJPARepository.findAll().forEach(e -> list.add(e));
return list;
}
@Override
public Ride getRideById(long rideId) {
Ride obj = rideJPARepository.findById(rideId).get();
return obj;
}
public Ride getRideByRiderName(String name) {
Ride ride = rideJPARepository.findByriderName(name);
return ride;
}
@Override
public synchronized boolean addRide(Ride ride) {
Ride rideexisiting = rideJPARepository.findByriderName(ride.getRiderName());
if (null!= rideexisiting) {
System.out.println("more than one elements");
return false;
} else {
rideJPARepository.save(ride);
return true;
}
}
@Override
public void updateRide(Ride ride) {
// TODO Auto-generated method stub
}
@Override
public void deleteRide(int rideId) throws RideNotPresentException {
Ride rideTobeDeleted = rideJPARepository.findByrideid(rideId);
if(null == rideTobeDeleted) {
throw new RideNotPresentException();
}
else
rideJPARepository.delete(rideTobeDeleted);
}
}
|
UTF-8
|
Java
| 1,825 |
java
|
RideService.java
|
Java
|
[] | null |
[] |
package com.vroomcar.JPADemo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.vroomcar.JPADemo.Exception.RideNotPresentException;
import com.vroomcar.JPADemo.beans.Ride;
import com.vroomcar.JPADemo.repository.RideJpaRepository;
@Component
public class RideService implements IRideService {
@Autowired
RideJpaRepository rideJPARepository;
@Override
public List<Ride> getAllRides() {
List<Ride> list = new ArrayList<>();
rideJPARepository.findAll().forEach(e -> list.add(e));
return list;
}
@Override
public Ride getRideById(long rideId) {
Ride obj = rideJPARepository.findById(rideId).get();
return obj;
}
public Ride getRideByRiderName(String name) {
Ride ride = rideJPARepository.findByriderName(name);
return ride;
}
@Override
public synchronized boolean addRide(Ride ride) {
Ride rideexisiting = rideJPARepository.findByriderName(ride.getRiderName());
if (null!= rideexisiting) {
System.out.println("more than one elements");
return false;
} else {
rideJPARepository.save(ride);
return true;
}
}
@Override
public void updateRide(Ride ride) {
// TODO Auto-generated method stub
}
@Override
public void deleteRide(int rideId) throws RideNotPresentException {
Ride rideTobeDeleted = rideJPARepository.findByrideid(rideId);
if(null == rideTobeDeleted) {
throw new RideNotPresentException();
}
else
rideJPARepository.delete(rideTobeDeleted);
}
}
| 1,825 | 0.695342 | 0.695342 | 81 | 21.530865 | 22.71242 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.469136 | false | false |
3
|
a1c85a6bbbfc176fa739d0ab1d04a993f13b8939
| 8,761,733,299,884 |
27404ea4a24b1542b6afc92bc3f2da2dbb2027d0
|
/src/com/wartis/introduction/Duons_1155.java
|
f717cdc80a26a0d46978593598031faa29be2cd6
|
[] |
no_license
|
wartis/java_algorithms
|
https://github.com/wartis/java_algorithms
|
c028d2d6f24e67aa949529b9591b018be2c32c08
|
d7bc410c026bb56ba475af82dc40f6ce5946b429
|
refs/heads/master
| 2021-01-01T02:40:01.581000 | 2020-02-12T15:23:49 | 2020-02-12T15:23:49 | 239,145,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wartis.introduction;
import java.util.Scanner;
public class Duons_1155 {
public static void main(String ... args) {
Scanner scanner = new Scanner(System.in, "ISO-8859-1");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int d = scanner.nextInt();
int e = scanner.nextInt();
int f = scanner.nextInt();
int g = scanner.nextInt();
int h = scanner.nextInt();
new DuonsSolver(a, b, c, d, e, f, g, h).solve();
}
}
class DuonsSolver {
private int A, B, C, D, E, F, G, H;
public DuonsSolver(int a, int b, int c, int d, int e, int f, int g, int h) {
A = a;
B = b;
C = c;
D = d;
E = e;
F = f;
G = g;
H = h;
}
void solve() {
if (A+C+H+F != G+E+B+D) {
System.out.println("IMPOSSIBLE");
return;
}
while (A+C+H+F != 0) {
if (A>0 && G>0) {
A--;
G--;
System.out.println("EH+");
System.out.println("AE-");
System.out.println("GH-");
}
if (A>0 && E>0){
A--;
E--;
System.out.println("AE-");
}
if (A>0 && B>0){
A--;
B--;
System.out.println("AB-");
}
if (A>0 && D>0){
A--;
D--;
System.out.println("AD-");
}
if (C>0 && E>0) {
C--;
E--;
System.out.println("AB+");
System.out.println("AE-");
System.out.println("BC-");
}
if (C>0 && B>0){
C--;
B--;
System.out.println("CB-");
}
if (C>0 && D>0) {
C--;
D--;
System.out.println("CD-");
}
if (C>0 && G>0){
C--;
G--;
System.out.println("CG-");
}
if (H>0 && B>0) {
H--;
B--;
System.out.println("EA+");
System.out.println("AB-");
System.out.println("EH-");
}
if (H>0 && G>0){
H--;
G--;
System.out.println("HG-");
}
if (H>0 && E>0) {
H--;
E--;
System.out.println("HE-");
}
if (H>0 && D>0){
H--;
D--;
System.out.println("HD-");
}
if (F>0 && D>0) {
F--;
D--;
System.out.println("EH+");
System.out.println("FE-");
System.out.println("DH-");
}
if (F>0 && B>0) {
F--;
B--;
System.out.println("FB-");
}
if (F>0 && E>0) {
F--;
E--;
System.out.println("FE-");
}
if (F>0 && G>0) {
F--;
G--;
System.out.println("FG-");
}
}
}
}
|
UTF-8
|
Java
| 3,397 |
java
|
Duons_1155.java
|
Java
|
[] | null |
[] |
package com.wartis.introduction;
import java.util.Scanner;
public class Duons_1155 {
public static void main(String ... args) {
Scanner scanner = new Scanner(System.in, "ISO-8859-1");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int d = scanner.nextInt();
int e = scanner.nextInt();
int f = scanner.nextInt();
int g = scanner.nextInt();
int h = scanner.nextInt();
new DuonsSolver(a, b, c, d, e, f, g, h).solve();
}
}
class DuonsSolver {
private int A, B, C, D, E, F, G, H;
public DuonsSolver(int a, int b, int c, int d, int e, int f, int g, int h) {
A = a;
B = b;
C = c;
D = d;
E = e;
F = f;
G = g;
H = h;
}
void solve() {
if (A+C+H+F != G+E+B+D) {
System.out.println("IMPOSSIBLE");
return;
}
while (A+C+H+F != 0) {
if (A>0 && G>0) {
A--;
G--;
System.out.println("EH+");
System.out.println("AE-");
System.out.println("GH-");
}
if (A>0 && E>0){
A--;
E--;
System.out.println("AE-");
}
if (A>0 && B>0){
A--;
B--;
System.out.println("AB-");
}
if (A>0 && D>0){
A--;
D--;
System.out.println("AD-");
}
if (C>0 && E>0) {
C--;
E--;
System.out.println("AB+");
System.out.println("AE-");
System.out.println("BC-");
}
if (C>0 && B>0){
C--;
B--;
System.out.println("CB-");
}
if (C>0 && D>0) {
C--;
D--;
System.out.println("CD-");
}
if (C>0 && G>0){
C--;
G--;
System.out.println("CG-");
}
if (H>0 && B>0) {
H--;
B--;
System.out.println("EA+");
System.out.println("AB-");
System.out.println("EH-");
}
if (H>0 && G>0){
H--;
G--;
System.out.println("HG-");
}
if (H>0 && E>0) {
H--;
E--;
System.out.println("HE-");
}
if (H>0 && D>0){
H--;
D--;
System.out.println("HD-");
}
if (F>0 && D>0) {
F--;
D--;
System.out.println("EH+");
System.out.println("FE-");
System.out.println("DH-");
}
if (F>0 && B>0) {
F--;
B--;
System.out.println("FB-");
}
if (F>0 && E>0) {
F--;
E--;
System.out.println("FE-");
}
if (F>0 && G>0) {
F--;
G--;
System.out.println("FG-");
}
}
}
}
| 3,397 | 0.303209 | 0.290845 | 136 | 23.985294 | 14.396684 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.742647 | false | false |
3
|
7114665ccc3e06ec68798c6323689d52a6c63fe1
| 35,003,983,471,522 |
5e22bc0718a65f73055cebfc40f41686fae2d1d8
|
/src/main/java/com/edison/algorithm/linkedlist/排序链表.java
|
eb30816d22a13f9e10fc96bf1444c49615810c7e
|
[] |
no_license
|
EdsionGeng/day_day_algorithm
|
https://github.com/EdsionGeng/day_day_algorithm
|
100107b3a21141c216e33c3a36971b087f5e4ab8
|
ff409749071081bf0a0ce4632e695a606ddf9197
|
refs/heads/master
| 2023-01-12T21:14:59.802000 | 2022-12-29T02:38:04 | 2022-12-29T02:38:04 | 223,535,879 | 2 | 0 | null | false | 2022-11-16T06:15:26 | 2019-11-23T05:24:19 | 2022-06-07T15:02:34 | 2022-11-16T06:15:23 | 10,894 | 2 | 0 | 3 |
Java
| false | false |
package com.edison.algorithm.linkedlist;
import com.edison.algorithm.struct.ListNode;
public class 排序链表 {
public ListNode sortList(ListNode head) {
return null;
}
public static ListNode mergeTwoList(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
cur = cur.next;
l1 = l1.next;
} else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if (l1 == null) {
cur.next = l2;
}
if (l2 == null) {
cur.next = l1;
}
return dummyHead.next;
}
}
|
UTF-8
|
Java
| 812 |
java
|
排序链表.java
|
Java
|
[] | null |
[] |
package com.edison.algorithm.linkedlist;
import com.edison.algorithm.struct.ListNode;
public class 排序链表 {
public ListNode sortList(ListNode head) {
return null;
}
public static ListNode mergeTwoList(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
cur = cur.next;
l1 = l1.next;
} else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if (l1 == null) {
cur.next = l2;
}
if (l2 == null) {
cur.next = l1;
}
return dummyHead.next;
}
}
| 812 | 0.46393 | 0.442786 | 37 | 20.648649 | 16.91188 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405405 | false | false |
3
|
3d6ee2d99da695a029cd398ea6c929fc8c275ec2
| 21,062,519,635,514 |
dc24702f9057a6a2c209c8c1ecca4dc494d932b2
|
/app/src/main/java/com/midtermmad3125/ui/WeatherListActivity.java
|
a135679c6388059641f0486b8f5aa1ef68aed26d
|
[] |
no_license
|
ilyasderaiya/W2019_MAD3125_MidTerm
|
https://github.com/ilyasderaiya/W2019_MAD3125_MidTerm
|
75df5e80484724d28645b969ca753ad6ed647743
|
323a41e06c904936174ceadf22639ce99e9e4c5c
|
refs/heads/master
| 2020-05-06T20:30:30.876000 | 2019-04-09T01:39:02 | 2019-04-09T01:39:02 | 180,241,493 | 0 | 0 | null | true | 2019-04-08T22:19:23 | 2019-04-08T22:19:22 | 2019-04-08T22:08:25 | 2019-04-08T22:08:23 | 0 | 0 | 0 | 0 | null | false | false |
package com.midtermmad3125.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.midtermmad3125.CustomAdapter;
import com.midtermmad3125.Details;
import com.midtermmad3125.Model;
import com.midtermmad3125.R;
import com.midtermmad3125.utils.ReadJSONUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
public class WeatherListActivity extends AppCompatActivity
{
ArrayList<String> date = new ArrayList<>();
ArrayList<Double> minimumTemp = new ArrayList<>();
ArrayList<Double> maxTemp = new ArrayList<>();
ArrayList<String> wdetails = new ArrayList<>();
ArrayList<String> wdescription = new ArrayList<>();
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_list);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
loadJson();
CustomAdapter customAdapter = new CustomAdapter(WeatherListActivity.this, date, minimumTemp, maxTemp, wdetails, wdescription);
recyclerView.setAdapter(customAdapter);
}
private void loadJson() {
try{
//String jsonString = ReadJSONUtils.loadJSONFromAsset(getApplicationContext(),"moscow_weather");
//JSONObject mObj = new JSONObject(jsonString);
JSONObject mObj = new JSONObject(loadJSONFromAsset());
JSONObject cityObj = mObj.getJSONObject("city");
JSONArray list = mObj.getJSONArray("list");
for(int i = 0; i < list.length(); i++) {
JSONObject dObj = list.getJSONObject(i);
date.add(ReadJSONUtils.getDateFromTimeStamp(dObj.getLong("dt")));
//Object For Temp Details
JSONObject tempObj = dObj.getJSONObject("temp");
minimumTemp.add(tempObj.getDouble("min"));
maxTemp.add(tempObj.getDouble("max"));
//Array for Weather Details
JSONArray weatherObj = dObj.getJSONArray("weather");
for(int j = 0; j < weatherObj.length(); j++) {
JSONObject wObj = weatherObj.getJSONObject(j);
wdetails.add(wObj.getString("main"));
wdescription.add(wObj.getString("description"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("moscow_weather.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
|
UTF-8
|
Java
| 3,378 |
java
|
WeatherListActivity.java
|
Java
|
[
{
"context": "package com.midtermmad3125.ui;\n\nimport android.support.v7.app.AppCompatAc",
"end": 23,
"score": 0.5406663417816162,
"start": 18,
"tag": "USERNAME",
"value": "mmad3"
},
{
"context": "clerView;\nimport android.util.Log;\n\nimport com.midtermmad3125.CustomAdapter;\nimport com.midtermmad3125.Details;",
"end": 259,
"score": 0.882387638092041,
"start": 248,
"tag": "USERNAME",
"value": "termmad3125"
},
{
"context": "t com.midtermmad3125.CustomAdapter;\nimport com.midtermmad3125.Details;\nimport com.midtermmad3125.Model;\nimport ",
"end": 300,
"score": 0.7105841636657715,
"start": 289,
"tag": "USERNAME",
"value": "termmad3125"
},
{
"context": "\nimport com.midtermmad3125.Details;\nimport com.midtermmad3125.Model;\nimport com.midtermmad3125.R;\nimport com.mi",
"end": 335,
"score": 0.7909830212593079,
"start": 324,
"tag": "USERNAME",
"value": "termmad3125"
},
{
"context": "s;\nimport com.midtermmad3125.Model;\nimport com.midtermmad3125.R;\nimport com.midtermmad3125.utils.ReadJSONUtils;",
"end": 368,
"score": 0.8913396000862122,
"start": 357,
"tag": "USERNAME",
"value": "termmad3125"
},
{
"context": "el;\nimport com.midtermmad3125.R;\nimport com.midtermmad3125.utils.ReadJSONUtils;\n\nimport org.json.JSONArray",
"end": 395,
"score": 0.6407332420349121,
"start": 389,
"tag": "USERNAME",
"value": "mmad31"
}
] | null |
[] |
package com.midtermmad3125.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.midtermmad3125.CustomAdapter;
import com.midtermmad3125.Details;
import com.midtermmad3125.Model;
import com.midtermmad3125.R;
import com.midtermmad3125.utils.ReadJSONUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
public class WeatherListActivity extends AppCompatActivity
{
ArrayList<String> date = new ArrayList<>();
ArrayList<Double> minimumTemp = new ArrayList<>();
ArrayList<Double> maxTemp = new ArrayList<>();
ArrayList<String> wdetails = new ArrayList<>();
ArrayList<String> wdescription = new ArrayList<>();
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_list);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
loadJson();
CustomAdapter customAdapter = new CustomAdapter(WeatherListActivity.this, date, minimumTemp, maxTemp, wdetails, wdescription);
recyclerView.setAdapter(customAdapter);
}
private void loadJson() {
try{
//String jsonString = ReadJSONUtils.loadJSONFromAsset(getApplicationContext(),"moscow_weather");
//JSONObject mObj = new JSONObject(jsonString);
JSONObject mObj = new JSONObject(loadJSONFromAsset());
JSONObject cityObj = mObj.getJSONObject("city");
JSONArray list = mObj.getJSONArray("list");
for(int i = 0; i < list.length(); i++) {
JSONObject dObj = list.getJSONObject(i);
date.add(ReadJSONUtils.getDateFromTimeStamp(dObj.getLong("dt")));
//Object For Temp Details
JSONObject tempObj = dObj.getJSONObject("temp");
minimumTemp.add(tempObj.getDouble("min"));
maxTemp.add(tempObj.getDouble("max"));
//Array for Weather Details
JSONArray weatherObj = dObj.getJSONArray("weather");
for(int j = 0; j < weatherObj.length(); j++) {
JSONObject wObj = weatherObj.getJSONObject(j);
wdetails.add(wObj.getString("main"));
wdescription.add(wObj.getString("description"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("moscow_weather.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
| 3,378 | 0.641504 | 0.632623 | 101 | 32.445545 | 27.047255 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673267 | false | false |
3
|
3dbddf9ae424ac7a4afdc11549fc0075a3a959e7
| 18,451,179,532,108 |
da7b495d979da76af855dda56cd5f221938409fa
|
/src/main/java/io/choerodon/agile/domain/agile/converter/PiDONameConverter.java
|
4faae2a9d9e6047265ec8735df8e3dbc34f603cd
|
[
"Apache-2.0"
] |
permissive
|
pologood/agile-service
|
https://github.com/pologood/agile-service
|
ae5dc2aaa7d06ff2da284e782fad06174d6c9032
|
9c531535942b8d0e251002b4d06e42fa66eae461
|
refs/heads/master
| 2020-06-10T21:19:07.660000 | 2019-06-25T01:56:09 | 2019-06-25T01:56:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.choerodon.agile.domain.agile.converter;
import io.choerodon.agile.api.dto.PiNameDTO;
import io.choerodon.agile.infra.dataobject.PiDO;
import io.choerodon.core.convertor.ConvertorI;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
/**
* Created by HuangFuqiang@choerodon.io on 2019/4/18.
* Email: fuqianghuang01@gmail.com
*/
@Component
public class PiDONameConverter implements ConvertorI<Object, PiDO, PiNameDTO> {
@Override
public PiNameDTO doToDto(PiDO piDO) {
PiNameDTO piNameDTO = new PiNameDTO();
BeanUtils.copyProperties(piDO, piNameDTO);
return piNameDTO;
}
}
|
UTF-8
|
Java
| 664 |
java
|
PiDONameConverter.java
|
Java
|
[
{
"context": "framework.stereotype.Component;\n\n/**\n * Created by HuangFuqiang@choerodon.io on 2019/4/18.\n * Email: fuqianghuang01@gmail.com\n",
"end": 330,
"score": 0.9998223185539246,
"start": 305,
"tag": "EMAIL",
"value": "HuangFuqiang@choerodon.io"
},
{
"context": " HuangFuqiang@choerodon.io on 2019/4/18.\n * Email: fuqianghuang01@gmail.com\n */\n@Component\npublic class PiDONameConverter imp",
"end": 379,
"score": 0.999925971031189,
"start": 355,
"tag": "EMAIL",
"value": "fuqianghuang01@gmail.com"
}
] | null |
[] |
package io.choerodon.agile.domain.agile.converter;
import io.choerodon.agile.api.dto.PiNameDTO;
import io.choerodon.agile.infra.dataobject.PiDO;
import io.choerodon.core.convertor.ConvertorI;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
/**
* Created by <EMAIL> on 2019/4/18.
* Email: <EMAIL>
*/
@Component
public class PiDONameConverter implements ConvertorI<Object, PiDO, PiNameDTO> {
@Override
public PiNameDTO doToDto(PiDO piDO) {
PiNameDTO piNameDTO = new PiNameDTO();
BeanUtils.copyProperties(piDO, piNameDTO);
return piNameDTO;
}
}
| 629 | 0.760542 | 0.746988 | 22 | 29.181818 | 23.076231 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
3
|
2015c2cbd50d9c2875843b090ddfd5dd7ee62f3e
| 4,028,679,341,300 |
95d16cc430928f5f22d2d3b8346d38af45bb88a8
|
/orientacao-a-objetos/src/TestaAgencia.java
|
f773501e26851700a10232cd323018432a81c0f0
|
[] |
no_license
|
munizzele/exercicios-orientado-a-objetos-java
|
https://github.com/munizzele/exercicios-orientado-a-objetos-java
|
4a00b61bd29363447fe25147138140fbfc8315e4
|
2e86ee7862fbee43fad6727ead27c089b9086129
|
refs/heads/master
| 2022-11-14T04:21:29.242000 | 2020-06-26T14:48:01 | 2020-06-26T14:48:01 | 241,424,468 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class TestaAgencia {
public static void main ( String [] args ) {
Agencia a1 = new Agencia (2) ;
a1 . numero = 1234;
Agencia a2 = new Agencia (4) ;
a2 . numero = 5678;
System . out . println ( a1 . numero ) ;
System . out . println ( a2 . numero ) ;
}
}
|
UTF-8
|
Java
| 277 |
java
|
TestaAgencia.java
|
Java
|
[] | null |
[] |
public class TestaAgencia {
public static void main ( String [] args ) {
Agencia a1 = new Agencia (2) ;
a1 . numero = 1234;
Agencia a2 = new Agencia (4) ;
a2 . numero = 5678;
System . out . println ( a1 . numero ) ;
System . out . println ( a2 . numero ) ;
}
}
| 277 | 0.595668 | 0.537906 | 10 | 26.6 | 14.650598 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.1 | false | false |
3
|
486a1d3f43f698817f56ee218978d87db9988402
| 22,316,650,114,271 |
7546c3b50565040bc0d084eca188645f90d2e444
|
/app/src/main/java/projekt_android/photoeditor/activities/Gallery.java
|
8c6a72734a46c1dd5075ba2939eef0ce541378ac
|
[] |
no_license
|
homaralex/photo-editor
|
https://github.com/homaralex/photo-editor
|
1bb6436c39945b4813c8e3e8d6096431018fd919
|
9740dd6c4866cb82856a1c000e947d7f50991eea
|
refs/heads/master
| 2020-03-28T18:31:10.565000 | 2015-01-22T13:35:57 | 2015-01-22T13:35:57 | 27,543,564 | 1 | 0 | null | false | 2015-01-22T13:35:59 | 2014-12-04T14:16:44 | 2015-01-22T13:35:58 | 2015-01-22T13:35:58 | 2,212 | 0 | 0 | 0 |
Java
| null | null |
package projekt_android.photoeditor.activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.GridView;
import java.util.List;
import projekt_android.photoeditor.adapters.GalleryImageAdapter;
import projekt_android.photoeditor.R;
import projekt_android.photoeditor.database.GalleryDataSource;
public class Gallery extends Activity {
private static final int GRID_VIEW_NUM_COLUMNS = 3;
private GalleryDataSource dataSource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
dataSource = new GalleryDataSource(getApplication());
dataSource.open();
Log.i(Gallery.class.getName(), "Trying to get all saved urls from database");
List<String> urls = dataSource.getAllUrls();
Log.i(Gallery.class.getName(), "Urls obtained");
GridView grid = (GridView)findViewById(R.id.galleryGridView);
grid.setNumColumns(GRID_VIEW_NUM_COLUMNS);
grid.setAdapter(new GalleryImageAdapter(urls, this));
}
@Override
public void onDestroy(){
super.onDestroy();
dataSource.close();
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
UTF-8
|
Java
| 1,719 |
java
|
Gallery.java
|
Java
|
[] | null |
[] |
package projekt_android.photoeditor.activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.GridView;
import java.util.List;
import projekt_android.photoeditor.adapters.GalleryImageAdapter;
import projekt_android.photoeditor.R;
import projekt_android.photoeditor.database.GalleryDataSource;
public class Gallery extends Activity {
private static final int GRID_VIEW_NUM_COLUMNS = 3;
private GalleryDataSource dataSource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
dataSource = new GalleryDataSource(getApplication());
dataSource.open();
Log.i(Gallery.class.getName(), "Trying to get all saved urls from database");
List<String> urls = dataSource.getAllUrls();
Log.i(Gallery.class.getName(), "Urls obtained");
GridView grid = (GridView)findViewById(R.id.galleryGridView);
grid.setNumColumns(GRID_VIEW_NUM_COLUMNS);
grid.setAdapter(new GalleryImageAdapter(urls, this));
}
@Override
public void onDestroy(){
super.onDestroy();
dataSource.close();
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 1,719 | 0.697499 | 0.696917 | 54 | 30.833334 | 24.392431 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574074 | false | false |
3
|
f131957d5f6299eefe4f849eebb89eca9a2c4f1c
| 16,003,048,191,107 |
25d992b543f0d252af55f3cd0c85927645b5c204
|
/src/com/company/JavaBasic11.java
|
ff0008e7ff6eb47086203b91a029b5dcfd9819aa
|
[] |
no_license
|
pulkitagrawal20/NAAD
|
https://github.com/pulkitagrawal20/NAAD
|
f9962331b62a097073a6aa26f55674c3014b87aa
|
05e05ba873ea435208386abb54cbce52ba7f440e
|
refs/heads/master
| 2023-04-01T07:38:06.047000 | 2021-04-03T15:23:37 | 2021-04-03T15:23:37 | 352,115,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//Java Program to Remove All Whitespaces from a String:
package com.company;
import java.util.Scanner;
public class JavaBasic11 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
String s1,s2;
System.out.println("Enter spaced string");
s1=s.nextLine();
s2=s1.replaceAll("\\s+","");
System.out.println("resulted string is:\n"+s2);
}
}
|
UTF-8
|
Java
| 417 |
java
|
JavaBasic11.java
|
Java
|
[] | null |
[] |
//Java Program to Remove All Whitespaces from a String:
package com.company;
import java.util.Scanner;
public class JavaBasic11 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
String s1,s2;
System.out.println("Enter spaced string");
s1=s.nextLine();
s2=s1.replaceAll("\\s+","");
System.out.println("resulted string is:\n"+s2);
}
}
| 417 | 0.633094 | 0.613909 | 15 | 26.799999 | 18.879265 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
6e83c6c73f96914274df7e1f731cb8469869efa7
| 33,011,118,639,002 |
01c6bfbe0502370d05b7aa94dfe89234d40444c2
|
/src/main/java/com/vektorraum/voicecontrol/service/voicemail/VoiceMailTranscriptionService.java
|
15d330271876e8db61fe3231632315b878d2c86c
|
[
"Apache-2.0"
] |
permissive
|
fvalka/voicecontrol
|
https://github.com/fvalka/voicecontrol
|
b61b4959cf44765483cf858a25c5ff8c3a80ff39
|
02ebf0c7b6de116beb9987151132ff6a5dbafb3b
|
refs/heads/master
| 2020-08-12T08:01:23.282000 | 2019-10-23T08:05:48 | 2019-10-23T08:05:48 | 214,724,236 | 1 | 0 | null | false | 2019-10-12T23:50:35 | 2019-10-12T22:29:40 | 2019-10-12T23:47:52 | 2019-10-12T23:50:34 | 137 | 0 | 0 | 0 |
Java
| false | false |
package com.vektorraum.voicecontrol.service.voicemail;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.speech.v1p1beta1.*;
import com.google.protobuf.ByteString;
import com.vektorraum.voicecontrol.event.VoiceMailDownloadCompleteEvent;
import com.vektorraum.voicecontrol.event.VoiceMailTranscriptionsEvent;
import com.vektorraum.voicecontrol.model.Transcription;
import com.vektorraum.voicecontrol.service.voicemail.config.VoiceMailConfig;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Transcribes voice mail messages from speech to text using the Google Cloud Platform speech to text service
*
* Triggered by a {@link VoiceMailDownloadCompleteEvent}
*/
@Service
@Slf4j
public class VoiceMailTranscriptionService {
private VoiceMailConfig voiceMailConfig;
private ApplicationEventPublisher eventPublisher;
@Autowired
public VoiceMailTranscriptionService(VoiceMailConfig voiceMailConfig, ApplicationEventPublisher eventPublisher) {
this.voiceMailConfig = voiceMailConfig;
this.eventPublisher = eventPublisher;
}
@EventListener
@Async
public void transcribeVoiceMail(@NotNull VoiceMailDownloadCompleteEvent event) {
if (!voiceMailConfig.isTranscriptionEnabled()) {
log.debug("Transcription disabled, skipping event handling");
return;
}
try (SpeechClient speechClient = SpeechClient.create()) {
byte[] rawAudio = Files.readAllBytes(event.getFile().toPath());
RecognitionConfig config = getTranscriptionConfiguration();
RecognitionAudio content = RecognitionAudio.newBuilder()
.setContent(ByteString.copyFrom(rawAudio))
.build();
OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> futureResponse =
speechClient.longRunningRecognizeAsync(config, content);
LongRunningRecognizeResponse response = futureResponse.get(voiceMailConfig.getTranscriptionTimeout(), TimeUnit.SECONDS);
if(response.getResultsList().isEmpty()) {
log.warn("Transcription failed, received only an empty result");
return;
}
List<Transcription> transcriptions = response.getResultsList().stream()
.flatMap(it -> it.getAlternativesList().stream())
.map(it -> Transcription.builder()
.confidence(it.getConfidence())
.transcription(it.getTranscript())
.build())
.filter(it -> it.getConfidence() >= voiceMailConfig.getTranscriptionConfidenceCutOff())
.collect(Collectors.toList());
if(!transcriptions.isEmpty()) {
log.info("Received the following transcriptions={} for the event={}", transcriptions, event);
VoiceMailTranscriptionsEvent eventOut = VoiceMailTranscriptionsEvent.builder()
.callSid(event.getCallSid())
.recordingSid(event.getRecordingSid())
.transcriptions(transcriptions)
.source(this)
.build();
eventPublisher.publishEvent(eventOut);
} else {
log.info("Received no transcriptions for event={}", event);
}
} catch (Exception ex) {
log.error("Could not transcribe voice mail event={}", event, ex);
}
}
@NotNull
private RecognitionConfig getTranscriptionConfiguration() {
return RecognitionConfig.newBuilder()
.setLanguageCode(voiceMailConfig.getTranscriptionLanguages().get(0))
.addAllAlternativeLanguageCodes(
voiceMailConfig.getTranscriptionLanguages())
.setSampleRateHertz(8000)
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setUseEnhanced(true)
.build();
}
}
|
UTF-8
|
Java
| 4,562 |
java
|
VoiceMailTranscriptionService.java
|
Java
|
[] | null |
[] |
package com.vektorraum.voicecontrol.service.voicemail;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.speech.v1p1beta1.*;
import com.google.protobuf.ByteString;
import com.vektorraum.voicecontrol.event.VoiceMailDownloadCompleteEvent;
import com.vektorraum.voicecontrol.event.VoiceMailTranscriptionsEvent;
import com.vektorraum.voicecontrol.model.Transcription;
import com.vektorraum.voicecontrol.service.voicemail.config.VoiceMailConfig;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Transcribes voice mail messages from speech to text using the Google Cloud Platform speech to text service
*
* Triggered by a {@link VoiceMailDownloadCompleteEvent}
*/
@Service
@Slf4j
public class VoiceMailTranscriptionService {
private VoiceMailConfig voiceMailConfig;
private ApplicationEventPublisher eventPublisher;
@Autowired
public VoiceMailTranscriptionService(VoiceMailConfig voiceMailConfig, ApplicationEventPublisher eventPublisher) {
this.voiceMailConfig = voiceMailConfig;
this.eventPublisher = eventPublisher;
}
@EventListener
@Async
public void transcribeVoiceMail(@NotNull VoiceMailDownloadCompleteEvent event) {
if (!voiceMailConfig.isTranscriptionEnabled()) {
log.debug("Transcription disabled, skipping event handling");
return;
}
try (SpeechClient speechClient = SpeechClient.create()) {
byte[] rawAudio = Files.readAllBytes(event.getFile().toPath());
RecognitionConfig config = getTranscriptionConfiguration();
RecognitionAudio content = RecognitionAudio.newBuilder()
.setContent(ByteString.copyFrom(rawAudio))
.build();
OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> futureResponse =
speechClient.longRunningRecognizeAsync(config, content);
LongRunningRecognizeResponse response = futureResponse.get(voiceMailConfig.getTranscriptionTimeout(), TimeUnit.SECONDS);
if(response.getResultsList().isEmpty()) {
log.warn("Transcription failed, received only an empty result");
return;
}
List<Transcription> transcriptions = response.getResultsList().stream()
.flatMap(it -> it.getAlternativesList().stream())
.map(it -> Transcription.builder()
.confidence(it.getConfidence())
.transcription(it.getTranscript())
.build())
.filter(it -> it.getConfidence() >= voiceMailConfig.getTranscriptionConfidenceCutOff())
.collect(Collectors.toList());
if(!transcriptions.isEmpty()) {
log.info("Received the following transcriptions={} for the event={}", transcriptions, event);
VoiceMailTranscriptionsEvent eventOut = VoiceMailTranscriptionsEvent.builder()
.callSid(event.getCallSid())
.recordingSid(event.getRecordingSid())
.transcriptions(transcriptions)
.source(this)
.build();
eventPublisher.publishEvent(eventOut);
} else {
log.info("Received no transcriptions for event={}", event);
}
} catch (Exception ex) {
log.error("Could not transcribe voice mail event={}", event, ex);
}
}
@NotNull
private RecognitionConfig getTranscriptionConfiguration() {
return RecognitionConfig.newBuilder()
.setLanguageCode(voiceMailConfig.getTranscriptionLanguages().get(0))
.addAllAlternativeLanguageCodes(
voiceMailConfig.getTranscriptionLanguages())
.setSampleRateHertz(8000)
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setUseEnhanced(true)
.build();
}
}
| 4,562 | 0.661333 | 0.658483 | 104 | 42.865383 | 32.047459 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false |
3
|
ae9837f2d560cc968dba9539402d470583632b2b
| 14,181,982,047,446 |
40413c5e5361dfcdbaa6839b6a2120dc142fd494
|
/result/result-pdf/src/main/java/com/github/mengxianun/result/pdf/PDFResultConverter.java
|
c3243e3a01ad7287528e5eb2d88be0eeb5e1951c
|
[
"MIT"
] |
permissive
|
mengxianun/air-data
|
https://github.com/mengxianun/air-data
|
7f3149f95f015df4defa8ba184f7052790c338ad
|
f2a193a8e00db70c0cdb1e3c664fdc16c4ebd70d
|
refs/heads/master
| 2020-03-27T08:40:58.639000 | 2019-01-21T03:31:54 | 2019-01-21T03:31:54 | 146,277,175 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.mengxianun.result.pdf;
import com.github.mengxianun.core.AbstractResultConverter;
import com.google.gson.JsonElement;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
public class PDFResultConverter extends AbstractResultConverter {
private PDFResultConverter() {
}
private PDFResultConverter(Map<String, Object> properties, Map<String, Object> header, JsonElement data) {
super.dataInit(properties, header, data);
this.initStyle();
}
public static PDFResultConverter getInstance(Map<String, Object> properties, Map<String, Object> header, JsonElement data) {
return new PDFResultConverter(properties, header, data);
}
// 式样
BaseFont bfChinese = null;
Font titleFont = null;
Font dataFont = null;
@Override
protected InputStream export() throws Exception {
Document doc = new Document();
ByteArrayOutputStream baos = null;
try {
Rectangle rectPageSize = new Rectangle(PageSize.A4);
doc = new Document(rectPageSize);// 可配其余4个参数,如(rectPageSize,60,60,60,60)页面边距
baos = new ByteArrayOutputStream();//构建字节输出流
PdfWriter.getInstance(doc,baos);//将PDF文档对象写入到流
doc.open();
//信息数据表
//创建PdfTable对象
PdfPTable table=new PdfPTable(headers.size());
//表头添加表格内容
if (!data.isEmpty()) {
Map<String, Object> map = data.get(0);
for (String key : map.keySet()) {
table.addCell(getPDFCell(getDisplayName(key), titleFont));
}
}
//遍历数据集合进行添加
for (int i = 0; i < data.size(); i++) {
for (Map.Entry<String, Object> entry : data.get(i).entrySet()) {
table.addCell(getPDFCell(entry.getValue().toString(), dataFont));
}
}
table.setWidthPercentage(110);//表宽度设置可不受页面边距影响
doc.add(table);
if(doc != null){
doc.close();
}
return new ByteArrayInputStream(baos.toByteArray());
} catch(Exception e) {
throw e;
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
}
}
}
}
private static PdfPCell getPDFCell(String string, Font font) {
//创建单元格对象,将内容与字体放入段落中作为单元格内容
PdfPCell cell=new PdfPCell(new Paragraph(string,font));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//设置最小单元格高度
cell.setMinimumHeight(30);
return cell;
}
private void initStyle() {
// 解决中文问题
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
titleFont = new Font(bfChinese,18,Font.BOLD);//表头
dataFont = new Font(bfChinese,12,Font.NORMAL);
}
}
|
UTF-8
|
Java
| 3,148 |
java
|
PDFResultConverter.java
|
Java
|
[
{
"context": "package com.github.mengxianun.result.pdf;\n\nimport com.github.mengxianun.core.Ab",
"end": 29,
"score": 0.9976946711540222,
"start": 19,
"tag": "USERNAME",
"value": "mengxianun"
},
{
"context": ".github.mengxianun.result.pdf;\n\nimport com.github.mengxianun.core.AbstractResultConverter;\nimport com.google.g",
"end": 71,
"score": 0.9966684579849243,
"start": 61,
"tag": "USERNAME",
"value": "mengxianun"
}
] | null |
[] |
package com.github.mengxianun.result.pdf;
import com.github.mengxianun.core.AbstractResultConverter;
import com.google.gson.JsonElement;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
public class PDFResultConverter extends AbstractResultConverter {
private PDFResultConverter() {
}
private PDFResultConverter(Map<String, Object> properties, Map<String, Object> header, JsonElement data) {
super.dataInit(properties, header, data);
this.initStyle();
}
public static PDFResultConverter getInstance(Map<String, Object> properties, Map<String, Object> header, JsonElement data) {
return new PDFResultConverter(properties, header, data);
}
// 式样
BaseFont bfChinese = null;
Font titleFont = null;
Font dataFont = null;
@Override
protected InputStream export() throws Exception {
Document doc = new Document();
ByteArrayOutputStream baos = null;
try {
Rectangle rectPageSize = new Rectangle(PageSize.A4);
doc = new Document(rectPageSize);// 可配其余4个参数,如(rectPageSize,60,60,60,60)页面边距
baos = new ByteArrayOutputStream();//构建字节输出流
PdfWriter.getInstance(doc,baos);//将PDF文档对象写入到流
doc.open();
//信息数据表
//创建PdfTable对象
PdfPTable table=new PdfPTable(headers.size());
//表头添加表格内容
if (!data.isEmpty()) {
Map<String, Object> map = data.get(0);
for (String key : map.keySet()) {
table.addCell(getPDFCell(getDisplayName(key), titleFont));
}
}
//遍历数据集合进行添加
for (int i = 0; i < data.size(); i++) {
for (Map.Entry<String, Object> entry : data.get(i).entrySet()) {
table.addCell(getPDFCell(entry.getValue().toString(), dataFont));
}
}
table.setWidthPercentage(110);//表宽度设置可不受页面边距影响
doc.add(table);
if(doc != null){
doc.close();
}
return new ByteArrayInputStream(baos.toByteArray());
} catch(Exception e) {
throw e;
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
}
}
}
}
private static PdfPCell getPDFCell(String string, Font font) {
//创建单元格对象,将内容与字体放入段落中作为单元格内容
PdfPCell cell=new PdfPCell(new Paragraph(string,font));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//设置最小单元格高度
cell.setMinimumHeight(30);
return cell;
}
private void initStyle() {
// 解决中文问题
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
titleFont = new Font(bfChinese,18,Font.BOLD);//表头
dataFont = new Font(bfChinese,12,Font.NORMAL);
}
}
| 3,148 | 0.708791 | 0.701236 | 113 | 24.769911 | 24.784025 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.345133 | false | false |
3
|
f0268f2dddc65a3bab2349ca539ac873bcbeeb71
| 7,902,739,828,186 |
5a8dc007eea999546d1c403ad95a8edfc7b9bc3c
|
/DesignPattern/src/main/java/orz/an/design/pattern/base/lsv/AbstractGun.java
|
5adbf3ba99cfacdfdce7253587d005466f32685d
|
[] |
no_license
|
anzhiyi1988/MyCode
|
https://github.com/anzhiyi1988/MyCode
|
2800259c8a711fc0d7ae2f54b049914664db07d4
|
2d38dca4ba82a811a89be426ce08e9778d6b972b
|
refs/heads/master
| 2023-01-08T22:57:46.992000 | 2022-12-20T10:56:43 | 2022-12-20T10:56:43 | 116,620,677 | 0 | 0 | null | false | 2023-01-05T05:19:05 | 2018-01-08T02:45:38 | 2022-03-15T10:51:41 | 2023-01-05T05:19:05 | 71,067 | 0 | 0 | 21 |
JavaScript
| false | false |
package orz.an.design.pattern.base.lsv;
/**
* @author anzhy
* @version 1.0
* @created 07-8��-2018 11:52:52
*/
public abstract class AbstractGun {
public abstract void shoot();
}
|
UTF-8
|
Java
| 193 |
java
|
AbstractGun.java
|
Java
|
[
{
"context": "e orz.an.design.pattern.base.lsv;\n\n\n/**\n * @author anzhy\n * @version 1.0\n * @created 07-8��-2018 11:52:52\n",
"end": 62,
"score": 0.9996762275695801,
"start": 57,
"tag": "USERNAME",
"value": "anzhy"
}
] | null |
[] |
package orz.an.design.pattern.base.lsv;
/**
* @author anzhy
* @version 1.0
* @created 07-8��-2018 11:52:52
*/
public abstract class AbstractGun {
public abstract void shoot();
}
| 193 | 0.661376 | 0.582011 | 13 | 13.615385 | 15.061609 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false |
0
|
b17919a69f32fe9dd66368397e44f4babfdfa5ae
| 9,320,079,036,363 |
8d36d58cff3a5b431b445ba5ae8a40f61314f75d
|
/modules/vm-loaded/src/com/trifork/hotruby/objects/RubyBinding.java
|
85a782f88303120a3f95166d66575c599914aa2e
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
krestenkrab/hotruby
|
https://github.com/krestenkrab/hotruby
|
cc67a79834ba4e7e37a7d0621533bc37bc59cd53
|
c16ebc1ca711fee1394e546c0bcb4209ecab6b7c
|
refs/heads/master
| 2021-01-18T14:49:30.999000 | 2009-12-05T15:57:34 | 2009-12-05T15:57:34 | 400,377 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.trifork.hotruby.objects;
import com.trifork.hotruby.ast.LocalVariable;
import com.trifork.hotruby.ast.LocalVariableAccess;
import com.trifork.hotruby.classes.RubyClassBinding;
import com.trifork.hotruby.runtime.ExposedLocals;
import com.trifork.hotruby.runtime.LoadedRubyRuntime;
import com.trifork.hotruby.runtime.MetaModule;
import com.trifork.hotruby.runtime.RubyBlock;
import com.trifork.hotruby.runtime.RubyMethod;
import com.trifork.hotruby.runtime.Selector;
public class RubyBinding extends RubyObject implements IRubyBinding {
interface SelectBinding { RubyMethod get_RubyBinding(); }
public RubyMethod select(Selector sel) {
if(sel instanceof SelectBinding) { return ((SelectBinding)sel).get_RubyBinding(); }
else { return LoadedRubyRuntime.resolve_method((RubyObject)this,sel,SelectBinding.class); }
}
public RubyClass get_class() { return RubyClassBinding.instance; }
public RubyBlock get_block() {
// TODO Auto-generated method stub
return null;
}
public MetaModule get_lexical_context() {
// TODO Auto-generated method stub
return null;
}
public ExposedLocals get_locals() {
// TODO Auto-generated method stub
return null;
}
public IRubyObject get_self() {
// TODO Auto-generated method stub
return null;
}
public LocalVariableAccess access_local(String name, int level) {
// TODO Auto-generated method stub
return null;
}
public LocalVariable get_local(String name, int level, boolean create) {
// TODO Auto-generated method stub
return null;
}
}
|
UTF-8
|
Java
| 1,526 |
java
|
RubyBinding.java
|
Java
|
[] | null |
[] |
package com.trifork.hotruby.objects;
import com.trifork.hotruby.ast.LocalVariable;
import com.trifork.hotruby.ast.LocalVariableAccess;
import com.trifork.hotruby.classes.RubyClassBinding;
import com.trifork.hotruby.runtime.ExposedLocals;
import com.trifork.hotruby.runtime.LoadedRubyRuntime;
import com.trifork.hotruby.runtime.MetaModule;
import com.trifork.hotruby.runtime.RubyBlock;
import com.trifork.hotruby.runtime.RubyMethod;
import com.trifork.hotruby.runtime.Selector;
public class RubyBinding extends RubyObject implements IRubyBinding {
interface SelectBinding { RubyMethod get_RubyBinding(); }
public RubyMethod select(Selector sel) {
if(sel instanceof SelectBinding) { return ((SelectBinding)sel).get_RubyBinding(); }
else { return LoadedRubyRuntime.resolve_method((RubyObject)this,sel,SelectBinding.class); }
}
public RubyClass get_class() { return RubyClassBinding.instance; }
public RubyBlock get_block() {
// TODO Auto-generated method stub
return null;
}
public MetaModule get_lexical_context() {
// TODO Auto-generated method stub
return null;
}
public ExposedLocals get_locals() {
// TODO Auto-generated method stub
return null;
}
public IRubyObject get_self() {
// TODO Auto-generated method stub
return null;
}
public LocalVariableAccess access_local(String name, int level) {
// TODO Auto-generated method stub
return null;
}
public LocalVariable get_local(String name, int level, boolean create) {
// TODO Auto-generated method stub
return null;
}
}
| 1,526 | 0.774574 | 0.774574 | 48 | 30.791666 | 25.166908 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false |
0
|
0dfe46e89294befa96ac9737d35ece5ae686010c
| 30,279,519,488,948 |
4fd8929c958e08eb1a75301ce903d1d8ad878ac0
|
/app/src/main/java/com/csx/easyreadproject/ui/movie/model/MovieDetailModel.java
|
1db92119f701f0b0da06ce5c936867549a9ebef0
|
[] |
no_license
|
paihuai00/EasyReadProject
|
https://github.com/paihuai00/EasyReadProject
|
dcc46b9637d57d04ac478a1ab95b9d7254644cd6
|
1fbb8f68aab19b8df13a891af26b263dfa214439
|
refs/heads/master
| 2020-03-09T23:41:06.700000 | 2018-05-31T09:06:06 | 2018-05-31T09:06:06 | 129,063,704 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.csx.easyreadproject.ui.movie.model;
import com.csx.easyreadproject.api.Api;
import com.csx.easyreadproject.beans.MovieDetailBean;
import com.csx.easyreadproject.ui.movie.contract.MovieDetailContract;
import com.csx.mlibrary.helper.RetrofitCreateHelper;
import com.csx.mlibrary.helper.RxHelper;
import io.reactivex.Observable;
/**
* @Created by cuishuxiang
* @date 2018/5/8.
* @description:
*/
public class MovieDetailModel implements MovieDetailContract.Model {
@Override
public Observable<MovieDetailBean> requestMovieDetail(String id) {
return RetrofitCreateHelper.createApi(Api.class, Api.Movie_HOST)
.getMovieDetailData(id)
.compose(RxHelper.<MovieDetailBean>rxSchedulerHelper());
}
}
|
UTF-8
|
Java
| 764 |
java
|
MovieDetailModel.java
|
Java
|
[
{
"context": "mport io.reactivex.Observable;\n\n/**\n * @Created by cuishuxiang\n * @date 2018/5/8.\n * @description:\n */\npublic cl",
"end": 373,
"score": 0.9995188117027283,
"start": 362,
"tag": "USERNAME",
"value": "cuishuxiang"
}
] | null |
[] |
package com.csx.easyreadproject.ui.movie.model;
import com.csx.easyreadproject.api.Api;
import com.csx.easyreadproject.beans.MovieDetailBean;
import com.csx.easyreadproject.ui.movie.contract.MovieDetailContract;
import com.csx.mlibrary.helper.RetrofitCreateHelper;
import com.csx.mlibrary.helper.RxHelper;
import io.reactivex.Observable;
/**
* @Created by cuishuxiang
* @date 2018/5/8.
* @description:
*/
public class MovieDetailModel implements MovieDetailContract.Model {
@Override
public Observable<MovieDetailBean> requestMovieDetail(String id) {
return RetrofitCreateHelper.createApi(Api.class, Api.Movie_HOST)
.getMovieDetailData(id)
.compose(RxHelper.<MovieDetailBean>rxSchedulerHelper());
}
}
| 764 | 0.755236 | 0.747382 | 27 | 27.296297 | 26.756536 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
0
|
eb6a111163fbfa30321c2ae500807181ac50908b
| 14,834,817,087,142 |
7582f183ab771ea3677437051e56946aaa2a30d8
|
/app/src/main/java/com/example/tadeu17/dronetrack/connectActivity.java
|
fa575c070987a8e588b17110c4ee7877683d5708
|
[] |
no_license
|
andrenns/PMS
|
https://github.com/andrenns/PMS
|
ce2d99e3c2e33b20dd42deb96ce1f39e7d4909f7
|
3a0ef587977d9475e977b144d42759629eabb5c4
|
refs/heads/master
| 2020-06-18T20:52:48.763000 | 2019-07-11T18:20:42 | 2019-07-11T18:20:42 | 196,444,057 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.tadeu17.dronetrack;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class connectActivity extends AppCompatActivity {
OkHttpClient client;
Request takePhoto;
Request turnOff;
Request photoMode;
Response response;
ContextWrapper con;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
client = new OkHttpClient();
takePhoto = new Request.Builder()
.url("http://10.5.5.9/gp/gpControl/command/shutter?p=1")
.build();
turnOff = new Request.Builder()
.url("http://10.5.5.9/gp/gpControl/command/system/sleep")
.build();
photoMode = new Request.Builder()
.url("http://10.5.5.9/gp/gpControl/command/mode?p=1")
.build();
con = new ContextWrapper(getApplicationContext());
StrictMode.setThreadPolicy(policy);
}
public void turnON(View view){
WakeOnLan.wakeup("10.5.5.255", "064169123770");
}
public void takePhoto(View view)
{
try {
response = client.newCall(takePhoto).execute();
}
catch(IOException e)
{
Toast.makeText(con,"Failure!", Toast.LENGTH_LONG).show();
}
}
public void turnOFF(View view){
try {
response = client.newCall(turnOff).execute();
}
catch(IOException e)
{
Toast.makeText(con,"Failure!", Toast.LENGTH_LONG).show();
}
}
public void photoMode(View view)
{
try {
response = client.newCall(photoMode).execute();
}
catch(IOException e)
{
Toast.makeText(con,"Failure!", Toast.LENGTH_LONG).show();
}
}
}
|
UTF-8
|
Java
| 2,361 |
java
|
connectActivity.java
|
Java
|
[
{
"context": "package com.example.tadeu17.dronetrack;\n\nimport android.content.ContextWrappe",
"end": 27,
"score": 0.997960090637207,
"start": 20,
"tag": "USERNAME",
"value": "tadeu17"
},
{
"context": "void turnON(View view){\n WakeOnLan.wakeup(\"10.5.5.255\", \"064169123770\");\n }\n\n\n public void ",
"end": 1574,
"score": 0.9997537732124329,
"start": 1564,
"tag": "IP_ADDRESS",
"value": "10.5.5.255"
}
] | null |
[] |
package com.example.tadeu17.dronetrack;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class connectActivity extends AppCompatActivity {
OkHttpClient client;
Request takePhoto;
Request turnOff;
Request photoMode;
Response response;
ContextWrapper con;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
client = new OkHttpClient();
takePhoto = new Request.Builder()
.url("http://10.5.5.9/gp/gpControl/command/shutter?p=1")
.build();
turnOff = new Request.Builder()
.url("http://10.5.5.9/gp/gpControl/command/system/sleep")
.build();
photoMode = new Request.Builder()
.url("http://10.5.5.9/gp/gpControl/command/mode?p=1")
.build();
con = new ContextWrapper(getApplicationContext());
StrictMode.setThreadPolicy(policy);
}
public void turnON(View view){
WakeOnLan.wakeup("10.5.5.255", "064169123770");
}
public void takePhoto(View view)
{
try {
response = client.newCall(takePhoto).execute();
}
catch(IOException e)
{
Toast.makeText(con,"Failure!", Toast.LENGTH_LONG).show();
}
}
public void turnOFF(View view){
try {
response = client.newCall(turnOff).execute();
}
catch(IOException e)
{
Toast.makeText(con,"Failure!", Toast.LENGTH_LONG).show();
}
}
public void photoMode(View view)
{
try {
response = client.newCall(photoMode).execute();
}
catch(IOException e)
{
Toast.makeText(con,"Failure!", Toast.LENGTH_LONG).show();
}
}
}
| 2,361 | 0.6205 | 0.603981 | 90 | 25.233334 | 22.538879 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.477778 | false | false |
0
|
7e750965180f0e3fef523563bb648ab862edc73d
| 14,834,817,085,070 |
23ae14c4ee04c5e232435d446639b3034b95e2bc
|
/src/main/java/de/mhlz/cardscan/model/repository/CardSetRepository.java
|
49b303d34cac2b11d6ff22cb439acec4a0d1b8f2
|
[] |
no_license
|
mehulsbhatt/cardscan-1
|
https://github.com/mehulsbhatt/cardscan-1
|
33fcebe71c7d1fe9d49bdce1a495f10679f20815
|
b5835caaa131dc817b9041ed6b6e4468d87bb858
|
refs/heads/master
| 2018-05-30T07:36:12.806000 | 2015-02-24T13:21:14 | 2015-02-24T13:21:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.mhlz.cardscan.model.repository;
import de.mhlz.cardscan.model.CardSet;
import org.springframework.data.repository.CrudRepository;
import java.util.Set;
public interface CardSetRepository extends CrudRepository<CardSet, Long> {
CardSet findOneByName(String name);
CardSet findOneByCode(String code);
}
|
UTF-8
|
Java
| 327 |
java
|
CardSetRepository.java
|
Java
|
[] | null |
[] |
package de.mhlz.cardscan.model.repository;
import de.mhlz.cardscan.model.CardSet;
import org.springframework.data.repository.CrudRepository;
import java.util.Set;
public interface CardSetRepository extends CrudRepository<CardSet, Long> {
CardSet findOneByName(String name);
CardSet findOneByCode(String code);
}
| 327 | 0.798165 | 0.798165 | 15 | 20.799999 | 24.552528 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false |
0
|
85391e5ff505b58a74b7768db489fa5084b8c6b6
| 33,337,536,206,200 |
4aef82c83000c3a491afc89682713f9b6b77e09f
|
/src/main/java/edu/codifyme/leetcode/mocktest/google/array/LongestLineOfConsecutiveOne.java
|
51723cd8d6aab376016a888f4bc612f58a663f3a
|
[] |
no_license
|
mainak1984/CodifyMe
|
https://github.com/mainak1984/CodifyMe
|
804756d9483d496ca7f1aaba0f4a79c348080ab3
|
1374316415fb760270b31f147befe623f7aaa4a5
|
refs/heads/master
| 2021-06-21T21:42:21.213000 | 2021-04-30T07:42:50 | 2021-04-30T07:42:50 | 219,310,362 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.codifyme.leetcode.mocktest.google.array;
/**
* 562. Longest Line of Consecutive One in Matrix
* MEDIUM: https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/
*
* Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical,
* diagonal or anti-diagonal.
* Example:
* Input:
* [[0,1,1,0],
* [0,1,1,0],
* [0,0,0,1]]
* Output: 3
* Hint: The number of elements in the given matrix will not exceed 10,000.
*
* Approach:
* Brute force, browse through all possible direction and get the Max
*
* Better Approach:
* Use a 3D DP, 3rd dimension is for each direction (size 4)
*
* Even Better approach:
* As every line depends only on previous line, rewrite on it
*/
public class LongestLineOfConsecutiveOne {
public static int HOR = 0;
public static int VER = 1;
public static int DIAG = 2;
public static int ADIAG = 3;
public int longestLine(int[][] M) {
if (M.length < 1) {
return 0;
}
int[][] dp = new int[M[0].length+2][4];
int max = 0;
for (int i = 1; i < M.length+1; i++) {
int old = 0;
for (int j = 1; j < M[0].length+1; j++) {
if (M[i-1][j-1] == 1) {
// Horizontal
dp[j][HOR] = dp[j-1][HOR]+1;
dp[j][VER] = dp[j][VER]+1;
int prev = dp[j][DIAG];
dp[j][DIAG] = old + 1;
old = prev;
dp[j][ADIAG] = dp[j+1][ADIAG]+1;
max = Math.max(max, Math.max(Math.max(dp[j][HOR], dp[j][VER]), Math.max(dp[j][DIAG], dp[j][ADIAG])));
} else {
old = dp[j][DIAG];
dp[j][HOR] = 0;
dp[j][VER] = 0;
dp[j][DIAG] = 0;
dp[j][ADIAG] = 0;
}
}
}
return max;
}
// 2D DP; vert starting from right, so, no need of prev state
// public int longestLine(int[][] M) {
// if (M.length == 0) return 0;
// int n = M[0].length;
// int[] hor = new int[n];
// int[] vert = new int[n];
// int[] diag = new int[n];
// int[] verDia = new int[n];
// int res = 0;
// for (int i = 0; i < M.length; i++) {
// int[] one = new int[n];
// int[] two = new int[n];
// for (int j = 0; j < M[0].length; j++) {
// if (M[i][j] == 1) {
// hor[j] = j == 0 ? 1 : hor[j - 1] + 1;
// vert[j] = vert[j] + 1;
// one[j] = j == 0 ? 1 : diag[j - 1] + 1;
// two[j] = j == n - 1 ? 1 :verDia[j + 1] + 1;
// res = Math.max(Math.max(res,hor[j]),Math.max(vert[j],one[j]));
// res = Math.max(res,two[j]);
// } else {
// hor[j] = vert[j] = 0;
// }
// }
// diag = one;
// verDia = two;
//
// }
// return res;
// }
// BRUTE Force
// public int longestLine(int[][] M) {
// if (M.length == 0) return 0;
// int ones = 0;
// // horizontal
// for (int i = 0; i < M.length; i++) {
// int count = 0;
// for (int j = 0; j < M[0].length; j++) {
// if (M[i][j] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // vertical
// for (int i = 0; i < M[0].length; i++) {
// int count = 0;
// for (int j = 0; j < M.length; j++) {
// if (M[j][i] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // upper diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = 0, y = i; x < M.length && y < M[0].length; x++, y++) {
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // lower diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = i, y = 0; x < M.length && y < M[0].length; x++, y++) {
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // upper anti-diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = 0, y = M[0].length - i - 1; x < M.length && y >= 0; x++, y--) {
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // lower anti-diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = i, y = M[0].length - 1; x < M.length && y >= 0; x++, y--) {
// // System.out.println(x+" "+y);
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// return ones;
// }
}
|
UTF-8
|
Java
| 5,578 |
java
|
LongestLineOfConsecutiveOne.java
|
Java
|
[] | null |
[] |
package edu.codifyme.leetcode.mocktest.google.array;
/**
* 562. Longest Line of Consecutive One in Matrix
* MEDIUM: https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/
*
* Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical,
* diagonal or anti-diagonal.
* Example:
* Input:
* [[0,1,1,0],
* [0,1,1,0],
* [0,0,0,1]]
* Output: 3
* Hint: The number of elements in the given matrix will not exceed 10,000.
*
* Approach:
* Brute force, browse through all possible direction and get the Max
*
* Better Approach:
* Use a 3D DP, 3rd dimension is for each direction (size 4)
*
* Even Better approach:
* As every line depends only on previous line, rewrite on it
*/
public class LongestLineOfConsecutiveOne {
public static int HOR = 0;
public static int VER = 1;
public static int DIAG = 2;
public static int ADIAG = 3;
public int longestLine(int[][] M) {
if (M.length < 1) {
return 0;
}
int[][] dp = new int[M[0].length+2][4];
int max = 0;
for (int i = 1; i < M.length+1; i++) {
int old = 0;
for (int j = 1; j < M[0].length+1; j++) {
if (M[i-1][j-1] == 1) {
// Horizontal
dp[j][HOR] = dp[j-1][HOR]+1;
dp[j][VER] = dp[j][VER]+1;
int prev = dp[j][DIAG];
dp[j][DIAG] = old + 1;
old = prev;
dp[j][ADIAG] = dp[j+1][ADIAG]+1;
max = Math.max(max, Math.max(Math.max(dp[j][HOR], dp[j][VER]), Math.max(dp[j][DIAG], dp[j][ADIAG])));
} else {
old = dp[j][DIAG];
dp[j][HOR] = 0;
dp[j][VER] = 0;
dp[j][DIAG] = 0;
dp[j][ADIAG] = 0;
}
}
}
return max;
}
// 2D DP; vert starting from right, so, no need of prev state
// public int longestLine(int[][] M) {
// if (M.length == 0) return 0;
// int n = M[0].length;
// int[] hor = new int[n];
// int[] vert = new int[n];
// int[] diag = new int[n];
// int[] verDia = new int[n];
// int res = 0;
// for (int i = 0; i < M.length; i++) {
// int[] one = new int[n];
// int[] two = new int[n];
// for (int j = 0; j < M[0].length; j++) {
// if (M[i][j] == 1) {
// hor[j] = j == 0 ? 1 : hor[j - 1] + 1;
// vert[j] = vert[j] + 1;
// one[j] = j == 0 ? 1 : diag[j - 1] + 1;
// two[j] = j == n - 1 ? 1 :verDia[j + 1] + 1;
// res = Math.max(Math.max(res,hor[j]),Math.max(vert[j],one[j]));
// res = Math.max(res,two[j]);
// } else {
// hor[j] = vert[j] = 0;
// }
// }
// diag = one;
// verDia = two;
//
// }
// return res;
// }
// BRUTE Force
// public int longestLine(int[][] M) {
// if (M.length == 0) return 0;
// int ones = 0;
// // horizontal
// for (int i = 0; i < M.length; i++) {
// int count = 0;
// for (int j = 0; j < M[0].length; j++) {
// if (M[i][j] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // vertical
// for (int i = 0; i < M[0].length; i++) {
// int count = 0;
// for (int j = 0; j < M.length; j++) {
// if (M[j][i] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // upper diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = 0, y = i; x < M.length && y < M[0].length; x++, y++) {
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // lower diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = i, y = 0; x < M.length && y < M[0].length; x++, y++) {
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // upper anti-diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = 0, y = M[0].length - i - 1; x < M.length && y >= 0; x++, y--) {
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// // lower anti-diagonal
// for (int i = 0; i < M[0].length || i < M.length; i++) {
// int count = 0;
// for (int x = i, y = M[0].length - 1; x < M.length && y >= 0; x++, y--) {
// // System.out.println(x+" "+y);
// if (M[x][y] == 1) {
// count++;
// ones = Math.max(ones, count);
// } else count = 0;
// }
// }
// return ones;
// }
}
| 5,578 | 0.37863 | 0.3564 | 165 | 32.806061 | 22.419931 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.921212 | false | false |
0
|
676222e7f6c0fdb41d3c0d1eb8268f4c9e616168
| 3,246,995,329,829 |
72ab931f2eadeaba5bd1f5c445aff8c57c1e4912
|
/src/case_study/models/person/employee/Employee.java
|
98425ed1d218c876e6a71862061f9c6c9bb24eaa
|
[] |
no_license
|
de140/A0321I1_NguyenNgocLePhuc_Module2
|
https://github.com/de140/A0321I1_NguyenNgocLePhuc_Module2
|
e7f9b5214a5a76106e24c4399a9d7a21dbfb93de
|
d8685fb4cfdfba34fc767f698fadbfeec3f3cbfa
|
refs/heads/main
| 2023-07-17T16:14:06.901000 | 2021-08-31T14:37:46 | 2021-08-31T14:37:46 | 377,529,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package case_study.models.person.employee;
import case_study.models.person.Person;
public class Employee extends Person {
private static int autoID = 1;
private String idEmp = "EMP00";
protected Degree degree;
protected Position position;
private double salary;
public Employee() {
}
public Employee(Degree degree, Position position, double salary) {
if (Employee.autoID >= 10 && Employee.autoID < 100) {
this.idEmp = "EMP0" + Employee.autoID++;
} else {
this.idEmp = "EMP00" + Employee.autoID++;
}
this.degree = degree;
this.position = position;
this.salary = salary;
}
public Employee(String idCode, String fullName, String dateOfBirth, String gender, String phone, String email, Degree degree, Position position, double salary) {
super(idCode, fullName, dateOfBirth, gender, phone, email);
if (Employee.autoID >= 10 && Employee.autoID < 100) {
this.idEmp = "EMP0" + Employee.autoID++;
} else {
this.idEmp = "EMP00" + Employee.autoID++;
}
this.degree = degree;
this.position = position;
this.salary = salary;
}
public static int getAutoID() {
return autoID;
}
public static void setAutoID(int autoID) {
Employee.autoID = autoID;
}
public String getIdEmp() {
return idEmp;
}
public void setIdEmp(String idEmp) {
this.idEmp = idEmp;
}
public Degree getDegree() {
return degree;
}
public void setDegree(Degree degree) {
this.degree = degree;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getFileLine() {
return idEmp + "," + fullName +
"," + dateOfBirth + "," + gender +
"," + phone + "," + email +
"," + degree + "," + position +
"," + salary + "\n";
}
public void parse(String line) {
String[] params = line.split(",");
try {
idEmp = params[0];
fullName = params[1];
dateOfBirth = params[2];
gender = params[3];
phone = params[4];
email = params[5];
degree = new Degree(params[6]);
position = new Position(params[7]);
salary = Double.parseDouble(params[8]);
} catch (ArrayIndexOutOfBoundsException e) {
}
}
@Override
public String toString() {
return "Employee {" +
"ID: " + idEmp +
", " +
super.toString() +
", Degree: " + degree +
", Position: " + position +
", Salary: " + salary +
'}';
}
}
|
UTF-8
|
Java
| 3,031 |
java
|
Employee.java
|
Java
|
[] | null |
[] |
package case_study.models.person.employee;
import case_study.models.person.Person;
public class Employee extends Person {
private static int autoID = 1;
private String idEmp = "EMP00";
protected Degree degree;
protected Position position;
private double salary;
public Employee() {
}
public Employee(Degree degree, Position position, double salary) {
if (Employee.autoID >= 10 && Employee.autoID < 100) {
this.idEmp = "EMP0" + Employee.autoID++;
} else {
this.idEmp = "EMP00" + Employee.autoID++;
}
this.degree = degree;
this.position = position;
this.salary = salary;
}
public Employee(String idCode, String fullName, String dateOfBirth, String gender, String phone, String email, Degree degree, Position position, double salary) {
super(idCode, fullName, dateOfBirth, gender, phone, email);
if (Employee.autoID >= 10 && Employee.autoID < 100) {
this.idEmp = "EMP0" + Employee.autoID++;
} else {
this.idEmp = "EMP00" + Employee.autoID++;
}
this.degree = degree;
this.position = position;
this.salary = salary;
}
public static int getAutoID() {
return autoID;
}
public static void setAutoID(int autoID) {
Employee.autoID = autoID;
}
public String getIdEmp() {
return idEmp;
}
public void setIdEmp(String idEmp) {
this.idEmp = idEmp;
}
public Degree getDegree() {
return degree;
}
public void setDegree(Degree degree) {
this.degree = degree;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getFileLine() {
return idEmp + "," + fullName +
"," + dateOfBirth + "," + gender +
"," + phone + "," + email +
"," + degree + "," + position +
"," + salary + "\n";
}
public void parse(String line) {
String[] params = line.split(",");
try {
idEmp = params[0];
fullName = params[1];
dateOfBirth = params[2];
gender = params[3];
phone = params[4];
email = params[5];
degree = new Degree(params[6]);
position = new Position(params[7]);
salary = Double.parseDouble(params[8]);
} catch (ArrayIndexOutOfBoundsException e) {
}
}
@Override
public String toString() {
return "Employee {" +
"ID: " + idEmp +
", " +
super.toString() +
", Degree: " + degree +
", Position: " + position +
", Salary: " + salary +
'}';
}
}
| 3,031 | 0.529858 | 0.52062 | 113 | 25.831858 | 22.538816 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.60177 | false | false |
0
|
b6fbc21e2dd828083a73b6783f0996acfc1da1c7
| 3,246,995,331,401 |
3d1ac7529794a7904566247e52fc374fceb1f480
|
/src/client/Client.java
|
86debdc49ddff37789fb14b1bef854415ffeb657
|
[] |
no_license
|
LSzczepanek/NetworkClientServer
|
https://github.com/LSzczepanek/NetworkClientServer
|
d95d2c2c003fcde346d44cc356cc5ba78942a650
|
27f72d5414210adabb271b2ba9963330f6ab3800
|
refs/heads/master
| 2021-01-17T17:26:06.505000 | 2016-10-21T19:50:22 | 2016-10-21T19:50:22 | 70,393,941 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.ServerRuntimeException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Client {
private static String msg = null;
private static String nickname = null;
private static Socket clientSocket = null;
private static BufferedReader fromServer = null;
private static PrintWriter output = null;
private static int frequency;
static String serverAnswer;
private static SocketAddress connectionAddressToServer;
private static int attempts = 0;
public static void main(String[] args) throws IOException {
if (tryToConnectToServer()) {
do {
if (serverStatusCheck(ClientHelper.getServerAddress(), clientSocket.getPort())) {
startSendingRandomNumbers();
} else {
chooseAfterLostConnection();
}
} while (!(msg.equals("close")));
fromServer.close();
output.close();
clientSocket.close();
}
}
private static boolean tryToConnectToServer(){
if (makeConnection(checkSave())) {
System.out.println("Connecting to saved server succeed!!");
return true;
}
else if(makeConnection(false)){
System.out.println("Connected with the server!!");
return true;
}else{
System.out.println("All connections failed, closing the Client!");
return false;
}
}
private static boolean checkSave() {
String[] lastSave = ClientHelper.readFromFile();
if (lastSave != null) {
System.out.println("Saved nickname is: " + lastSave[0]);
System.out.println("Saved SocketAddress is: " + lastSave[1] + ":" + lastSave[2]);
try {
if (ClientHelper.loadSave(lastSave)) {
nickname = lastSave[0];
return true;
}
} catch (IOException e) {
System.out.println("Something went wrong while loading settings...");
return false;
}
}
return false;
}
private static void chooseAfterLostConnection() throws IOException {
System.out.println("Do you want try to recconnect to the last sever type y?"
+ "\nIf you want look for new servers type n");
ClientHelper.cleanSystemInStream();
int choice = ((int) System.in.read());
if (choice == ClientHelper.Y) {
clientSocket.close();
System.out.println("Tries to reconnect...");
makeConnection(true);
} else if (choice == ClientHelper.N) {
ClientHelper.cleanSystemInStream();
if (!makeConnection(false)) {
attempts++;
} else {
attempts = 0;
}
if (attempts >= 3) {
System.out.println(
"After 3rd failed attempt clinet is going to be closed!!! \nSeems like there are not anymore any servers!!!");
msg = "close";
return;
}
} else {
System.out.println("You typed wrong!! Choose again!!");
}
}
public static boolean serverStatusCheck(InetAddress serverAddress, int port) {
boolean isOnline = true;
try {
Socket sock = new Socket();
final int timeOut = (int) TimeUnit.SECONDS.toMillis(2); // 5 sec
// wait
// period
sock.connect(new InetSocketAddress(serverAddress.getHostAddress(), port), timeOut);
sock.close();
} catch (Exception e) {
System.out.println("Server is dead");
isOnline = false;
}
return isOnline;
}
/**
*
* Making connection.
*
* @param isReconnect
* when true connection will try to reconnect insted of making
* new connection
* @return true if connection will pass
*/
private static boolean makeConnection(boolean isReconnect) {
Scanner input = new Scanner(System.in);
clientSocket = new Socket();
boolean serverAcceptance;
if (isReconnect) {
connectionAddressToServer = ClientHelper.reconnectToLastServer();
serverAcceptance = false;
} else {
ClientHelper.clearConnections();
System.out.println("Client starts searching for servers...");
connectionAddressToServer = ClientHelper.lookForServer();
serverAcceptance = true;
}
try {
clientSocket.connect(connectionAddressToServer);
fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
output = new PrintWriter(clientSocket.getOutputStream());
setNickname(input, serverAcceptance);
setFrequency(input);
if (isReconnect) {
System.out.println("Reconnect succeed");
}
if (!isReconnect) {
ClientHelper.saveLastServer(nickname);
}
return true;
} catch (Exception e) {
if (isReconnect) {
System.out.println("Reconnect failed");
}
System.out.println("Error while making a connection!!!");
return false;
}
}
static void setNickname(Scanner input, boolean serverAcceptance) throws IOException {
do {
if (serverAcceptance) {
System.out.print("Type your nickname: ");
ClientHelper.cleanSystemInStream();
nickname = input.nextLine();
}
output.println(nickname);
output.flush();
serverAnswer = fromServer.readLine();
if (serverAnswer.equalsIgnoreCase("Succed")) {
System.out.println("Nickname accepted");
serverAcceptance = false;
} else {
System.out.println("Nickname rejected\nPut another nickname");
serverAcceptance = true;
}
} while (serverAcceptance);
}
static void setFrequency(Scanner input) throws IOException {
do {
System.out.println("Wybierz czestotliwosc wysylania liczb od 10-10 000: ");
ClientHelper.cleanSystemInStream();
frequency = input.nextInt();
if (frequency < 10 || frequency > 10000) {
System.out.println("Czestotliwosc spoza zakresu!");
}
} while (frequency < 10 || frequency > 10000);
}
private static void startSendingRandomNumbers() {
msg = Integer.toString(((int) (Math.random() * 100)));
output.println(msg);
output.flush();
System.out.println("Msg sent: " + msg);
try {
Thread.sleep(frequency);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 6,157 |
java
|
Client.java
|
Java
|
[] | null |
[] |
package client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.ServerRuntimeException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Client {
private static String msg = null;
private static String nickname = null;
private static Socket clientSocket = null;
private static BufferedReader fromServer = null;
private static PrintWriter output = null;
private static int frequency;
static String serverAnswer;
private static SocketAddress connectionAddressToServer;
private static int attempts = 0;
public static void main(String[] args) throws IOException {
if (tryToConnectToServer()) {
do {
if (serverStatusCheck(ClientHelper.getServerAddress(), clientSocket.getPort())) {
startSendingRandomNumbers();
} else {
chooseAfterLostConnection();
}
} while (!(msg.equals("close")));
fromServer.close();
output.close();
clientSocket.close();
}
}
private static boolean tryToConnectToServer(){
if (makeConnection(checkSave())) {
System.out.println("Connecting to saved server succeed!!");
return true;
}
else if(makeConnection(false)){
System.out.println("Connected with the server!!");
return true;
}else{
System.out.println("All connections failed, closing the Client!");
return false;
}
}
private static boolean checkSave() {
String[] lastSave = ClientHelper.readFromFile();
if (lastSave != null) {
System.out.println("Saved nickname is: " + lastSave[0]);
System.out.println("Saved SocketAddress is: " + lastSave[1] + ":" + lastSave[2]);
try {
if (ClientHelper.loadSave(lastSave)) {
nickname = lastSave[0];
return true;
}
} catch (IOException e) {
System.out.println("Something went wrong while loading settings...");
return false;
}
}
return false;
}
private static void chooseAfterLostConnection() throws IOException {
System.out.println("Do you want try to recconnect to the last sever type y?"
+ "\nIf you want look for new servers type n");
ClientHelper.cleanSystemInStream();
int choice = ((int) System.in.read());
if (choice == ClientHelper.Y) {
clientSocket.close();
System.out.println("Tries to reconnect...");
makeConnection(true);
} else if (choice == ClientHelper.N) {
ClientHelper.cleanSystemInStream();
if (!makeConnection(false)) {
attempts++;
} else {
attempts = 0;
}
if (attempts >= 3) {
System.out.println(
"After 3rd failed attempt clinet is going to be closed!!! \nSeems like there are not anymore any servers!!!");
msg = "close";
return;
}
} else {
System.out.println("You typed wrong!! Choose again!!");
}
}
public static boolean serverStatusCheck(InetAddress serverAddress, int port) {
boolean isOnline = true;
try {
Socket sock = new Socket();
final int timeOut = (int) TimeUnit.SECONDS.toMillis(2); // 5 sec
// wait
// period
sock.connect(new InetSocketAddress(serverAddress.getHostAddress(), port), timeOut);
sock.close();
} catch (Exception e) {
System.out.println("Server is dead");
isOnline = false;
}
return isOnline;
}
/**
*
* Making connection.
*
* @param isReconnect
* when true connection will try to reconnect insted of making
* new connection
* @return true if connection will pass
*/
private static boolean makeConnection(boolean isReconnect) {
Scanner input = new Scanner(System.in);
clientSocket = new Socket();
boolean serverAcceptance;
if (isReconnect) {
connectionAddressToServer = ClientHelper.reconnectToLastServer();
serverAcceptance = false;
} else {
ClientHelper.clearConnections();
System.out.println("Client starts searching for servers...");
connectionAddressToServer = ClientHelper.lookForServer();
serverAcceptance = true;
}
try {
clientSocket.connect(connectionAddressToServer);
fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
output = new PrintWriter(clientSocket.getOutputStream());
setNickname(input, serverAcceptance);
setFrequency(input);
if (isReconnect) {
System.out.println("Reconnect succeed");
}
if (!isReconnect) {
ClientHelper.saveLastServer(nickname);
}
return true;
} catch (Exception e) {
if (isReconnect) {
System.out.println("Reconnect failed");
}
System.out.println("Error while making a connection!!!");
return false;
}
}
static void setNickname(Scanner input, boolean serverAcceptance) throws IOException {
do {
if (serverAcceptance) {
System.out.print("Type your nickname: ");
ClientHelper.cleanSystemInStream();
nickname = input.nextLine();
}
output.println(nickname);
output.flush();
serverAnswer = fromServer.readLine();
if (serverAnswer.equalsIgnoreCase("Succed")) {
System.out.println("Nickname accepted");
serverAcceptance = false;
} else {
System.out.println("Nickname rejected\nPut another nickname");
serverAcceptance = true;
}
} while (serverAcceptance);
}
static void setFrequency(Scanner input) throws IOException {
do {
System.out.println("Wybierz czestotliwosc wysylania liczb od 10-10 000: ");
ClientHelper.cleanSystemInStream();
frequency = input.nextInt();
if (frequency < 10 || frequency > 10000) {
System.out.println("Czestotliwosc spoza zakresu!");
}
} while (frequency < 10 || frequency > 10000);
}
private static void startSendingRandomNumbers() {
msg = Integer.toString(((int) (Math.random() * 100)));
output.println(msg);
output.flush();
System.out.println("Msg sent: " + msg);
try {
Thread.sleep(frequency);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 6,157 | 0.688647 | 0.683125 | 236 | 25.088984 | 23.067434 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.627119 | false | false |
0
|
a9d6e6de9ef7bbc814dbddec6c396377c481764c
| 10,806,137,723,140 |
a8b5f8d61fc29de2779df9c61840f0b171680db6
|
/src/kv_requestCoordinator/Server.java
|
d3264b703b98b786c048226cfab461aeb8c210b8
|
[] |
no_license
|
vipulkashyap111/CSC-591-DIC
|
https://github.com/vipulkashyap111/CSC-591-DIC
|
a2761da0d6505be22240208bc5f0e7456fba726a
|
d5163198a96cbfde07c88cc028521353aaff7010
|
refs/heads/master
| 2021-05-01T12:38:09.131000 | 2016-12-27T14:29:37 | 2016-12-27T14:29:37 | 74,242,237 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kv_requestCoordinator;
import kv_utility.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by gmeneze on 11/26/16.
*/
public class Server {
private static ExecutorService workers; /* Workers threads */
private static ConcurrentHashMap<String, ClientRequestHandler> activeClientList;
private static ServerSocket clientRequest;
private static InetAddress hostAddress;
private static ClientRequestHandler currReq;
private static String newClientReqId;
public static void setUpServer() throws IOException, ClassNotFoundException {
//hostAddress = InetAddress.getLocalHost();
clientRequest = new ServerSocket(ProjectConstants.RC_LISTEN_PORT, ProjectConstants.REQUEST_BACK_LOG);
activeClientList = new ConcurrentHashMap<String, ClientRequestHandler>();
workers = Executors.newFixedThreadPool(ProjectConstants.NUM_OF_WORKERS);
}
public static void cleanUpServer() {
try {
clientRequest.close(); /* Close the server socket connection */
workers.shutdown();
workers.awaitTermination(ProjectConstants.ONE, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void startServer() {
try {
setUpServer();
while (ProjectGlobal.is_RC_on) {
currReq = new ClientRequestHandler(clientRequest.accept());
workers.execute(currReq);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
cleanUpServer();
}
}
public static void main(String[] args) {
if (args.length > 1 || args.length == 0) {
System.err.println("Invalid number of arguments");
System.out.println("Run server as : java Server <proxy-ip-address>");
System.exit(1);
}
/* Test Code */
/*
RequestCoordinator rc = new RequestCoordinator();
ClientRequestPacket testRequestPacket = new ClientRequestPacket();
testRequestPacket.setIp_address("0");
System.out.println("ip address is: " + testRequestPacket.getIp_address());
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("50");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("25");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("75");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("12");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("37");
ClientResponsePacket responsePacket = rc.addNode(testRequestPacket);
System.out.println(" syncips size : " + responsePacket.getMemNodeSyncHelper().syncIps.size());
for(MemNodeSyncDetails details : responsePacket.getMemNodeSyncHelper().syncIps)
{
System.out.println("node Ip : " + details.getIp_Address() + " start range: " + details.getStart_range() + " end range: " + details.getEnd_range());
}
*/
/* Test Code ends */
String proxyIpAddress = args[0];
Socket proxySocket = null;
ClientRequestPacket requestPacket = new ClientRequestPacket();
ClientResponsePacket res_packet = null;
hostAddress = null;
try {
hostAddress = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(1);
}
try {
proxySocket = new Socket(proxyIpAddress, ProjectConstants.PR_LISTEN_PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
requestPacket.setCommand(ProjectConstants.GET_RC);
PacketTransfer.sendRequest(requestPacket, proxySocket);
res_packet = PacketTransfer.recv_response(proxySocket);
if (res_packet.getResponse_code() == ProjectConstants.SUCCESS) {
Socket rcSocket = null;
try {
rcSocket = new Socket(res_packet.getRc().ip, ProjectConstants.RC_LISTEN_PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
requestPacket.setCommand(ProjectConstants.SYNC_RC_NODE);
PacketTransfer.sendRequest(requestPacket, rcSocket);
res_packet = PacketTransfer.recv_response(rcSocket);
if (res_packet.getRcNodeSyncHelper() != null) {
System.out.println("Get Ring object is: " + res_packet.getRcNodeSyncHelper().getRing().toString());
Ring.setInstance(res_packet.getRcNodeSyncHelper().getRing());
} else {
System.out.println("getRcNodeSyncHelper object is empty dummy!");
}
}
try {
proxySocket = new Socket(proxyIpAddress, ProjectConstants.PR_LISTEN_PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
requestPacket.setCommand(ProjectConstants.ADD_RC_NODES);
requestPacket.setIp_address(hostAddress.getHostAddress());
PacketTransfer.sendRequest(requestPacket, proxySocket);
res_packet = PacketTransfer.recv_response(proxySocket);
System.out.println("Response Recieved : " + res_packet.getResponse_code());
startServer();
}
}
|
UTF-8
|
Java
| 5,785 |
java
|
Server.java
|
Java
|
[
{
"context": " java.util.concurrent.TimeUnit;\n\n/**\n * Created by gmeneze on 11/26/16.\n */\npublic class Server {\n privat",
"end": 398,
"score": 0.9996261596679688,
"start": 391,
"tag": "USERNAME",
"value": "gmeneze"
}
] | null |
[] |
package kv_requestCoordinator;
import kv_utility.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by gmeneze on 11/26/16.
*/
public class Server {
private static ExecutorService workers; /* Workers threads */
private static ConcurrentHashMap<String, ClientRequestHandler> activeClientList;
private static ServerSocket clientRequest;
private static InetAddress hostAddress;
private static ClientRequestHandler currReq;
private static String newClientReqId;
public static void setUpServer() throws IOException, ClassNotFoundException {
//hostAddress = InetAddress.getLocalHost();
clientRequest = new ServerSocket(ProjectConstants.RC_LISTEN_PORT, ProjectConstants.REQUEST_BACK_LOG);
activeClientList = new ConcurrentHashMap<String, ClientRequestHandler>();
workers = Executors.newFixedThreadPool(ProjectConstants.NUM_OF_WORKERS);
}
public static void cleanUpServer() {
try {
clientRequest.close(); /* Close the server socket connection */
workers.shutdown();
workers.awaitTermination(ProjectConstants.ONE, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void startServer() {
try {
setUpServer();
while (ProjectGlobal.is_RC_on) {
currReq = new ClientRequestHandler(clientRequest.accept());
workers.execute(currReq);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
cleanUpServer();
}
}
public static void main(String[] args) {
if (args.length > 1 || args.length == 0) {
System.err.println("Invalid number of arguments");
System.out.println("Run server as : java Server <proxy-ip-address>");
System.exit(1);
}
/* Test Code */
/*
RequestCoordinator rc = new RequestCoordinator();
ClientRequestPacket testRequestPacket = new ClientRequestPacket();
testRequestPacket.setIp_address("0");
System.out.println("ip address is: " + testRequestPacket.getIp_address());
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("50");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("25");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("75");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("12");
rc.addNode(testRequestPacket);
testRequestPacket.setIp_address("37");
ClientResponsePacket responsePacket = rc.addNode(testRequestPacket);
System.out.println(" syncips size : " + responsePacket.getMemNodeSyncHelper().syncIps.size());
for(MemNodeSyncDetails details : responsePacket.getMemNodeSyncHelper().syncIps)
{
System.out.println("node Ip : " + details.getIp_Address() + " start range: " + details.getStart_range() + " end range: " + details.getEnd_range());
}
*/
/* Test Code ends */
String proxyIpAddress = args[0];
Socket proxySocket = null;
ClientRequestPacket requestPacket = new ClientRequestPacket();
ClientResponsePacket res_packet = null;
hostAddress = null;
try {
hostAddress = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(1);
}
try {
proxySocket = new Socket(proxyIpAddress, ProjectConstants.PR_LISTEN_PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
requestPacket.setCommand(ProjectConstants.GET_RC);
PacketTransfer.sendRequest(requestPacket, proxySocket);
res_packet = PacketTransfer.recv_response(proxySocket);
if (res_packet.getResponse_code() == ProjectConstants.SUCCESS) {
Socket rcSocket = null;
try {
rcSocket = new Socket(res_packet.getRc().ip, ProjectConstants.RC_LISTEN_PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
requestPacket.setCommand(ProjectConstants.SYNC_RC_NODE);
PacketTransfer.sendRequest(requestPacket, rcSocket);
res_packet = PacketTransfer.recv_response(rcSocket);
if (res_packet.getRcNodeSyncHelper() != null) {
System.out.println("Get Ring object is: " + res_packet.getRcNodeSyncHelper().getRing().toString());
Ring.setInstance(res_packet.getRcNodeSyncHelper().getRing());
} else {
System.out.println("getRcNodeSyncHelper object is empty dummy!");
}
}
try {
proxySocket = new Socket(proxyIpAddress, ProjectConstants.PR_LISTEN_PORT);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
requestPacket.setCommand(ProjectConstants.ADD_RC_NODES);
requestPacket.setIp_address(hostAddress.getHostAddress());
PacketTransfer.sendRequest(requestPacket, proxySocket);
res_packet = PacketTransfer.recv_response(proxySocket);
System.out.println("Response Recieved : " + res_packet.getResponse_code());
startServer();
}
}
| 5,785 | 0.634745 | 0.630423 | 153 | 36.816994 | 29.27879 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633987 | false | false |
0
|
e6d1085fbc1d36e74359b253f643a7418de9e272
| 22,187,801,056,029 |
f9193d0be370e5616bc7ec1b250e48ecf6dcf2c0
|
/PassosyncApp2/app/src/main/java/com/myapplication/passosyncapp2/interfaces/RetrofitInterface.java
|
06db13776f9b1f4794c6ca32e34d4167de6f2721
|
[] |
no_license
|
amir102Khan/passosyncAssignment2
|
https://github.com/amir102Khan/passosyncAssignment2
|
d3cd815b244754f4374c57bb1fb56d87d3a8bcf8
|
8f3de82ee4d5f7f0a8fdda08b56f88c6a22c22e3
|
refs/heads/main
| 2023-06-17T16:32:28.500000 | 2021-07-07T15:36:51 | 2021-07-07T15:36:51 | 383,845,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.myapplication.passosyncapp2.interfaces;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface RetrofitInterface {
@GET("top-headlines")
Call<ResponseBody> getLatestNews(@Query("country") String country,
@Query("category") String category,
@Query("apiKey") String apiKey);
}
|
UTF-8
|
Java
| 435 |
java
|
RetrofitInterface.java
|
Java
|
[] | null |
[] |
package com.myapplication.passosyncapp2.interfaces;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface RetrofitInterface {
@GET("top-headlines")
Call<ResponseBody> getLatestNews(@Query("country") String country,
@Query("category") String category,
@Query("apiKey") String apiKey);
}
| 435 | 0.65977 | 0.648276 | 15 | 28 | 25.043961 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false |
0
|
1bbe36311eeba475f0707aa448301c2a2e5a5ccc
| 26,740,466,425,868 |
2530cab745b8f232551f03e26ec0638e8b2fd306
|
/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl/FetchingCacheServiceImplTests.java
|
64f6feed2bf8b61aac73bd507265e2fef36a342c
|
[
"Apache-2.0"
] |
permissive
|
LucasRolim/genieNetFlix
|
https://github.com/LucasRolim/genieNetFlix
|
aa5d5c8ac583627ab173a604c95fc6caf9d34d38
|
157919eb032bd9200356d2f32bf5223da527e5cd
|
refs/heads/master
| 2020-04-19T19:11:42.874000 | 2019-01-28T21:26:42 | 2019-01-30T06:08:25 | 168,382,229 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.agent.execution.services.impl;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.execution.exceptions.DownloadException;
import com.netflix.genie.agent.utils.locks.CloseableLock;
import com.netflix.genie.agent.utils.locks.impl.FileLockFactory;
import com.netflix.genie.test.categories.UnitTest;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Tests for fetching cache service implementation.
*/
@Slf4j
@Category(UnitTest.class)
public class FetchingCacheServiceImplTests {
/**
* Temporary folder.
*/
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private URI uri;
private ExecutorService executorService = Executors.newFixedThreadPool(2);
//Boolean flag representing that a downloadCompleted
private AtomicBoolean downloadCompleted = new AtomicBoolean(false);
//CloseableLock used for the downloadComplete condition while simulating a download
private ReentrantLock simulateDownloadLock = new ReentrantLock();
//Condition used during download simulation for waiting
private Condition downloadComplete = simulateDownloadLock.newCondition();
private ArgumentDelegates.CacheArguments cacheArguments;
private File targetFile;
private ThreadPoolTaskExecutor cleanUpTaskExecutor;
/**
* Set up.
*
* @throws Exception the exception
*/
@Before
public void setUp() throws Exception {
uri = new URI("https://my-server.com/path/to/config/config.xml");
cacheArguments = Mockito.mock(ArgumentDelegates.CacheArguments.class);
Mockito.when(
cacheArguments.getCacheDirectory()
).thenReturn(temporaryFolder.getRoot());
targetFile = new File(temporaryFolder.getRoot(), "target");
cleanUpTaskExecutor = new ThreadPoolTaskExecutor();
cleanUpTaskExecutor.setCorePoolSize(1);
cleanUpTaskExecutor.initialize();
}
/**
* Start two concurrent resource fetches.
* Make sure only one cache does the download/enters the critical section
*
* @throws Exception the exception
*/
@Test
public void cacheConcurrentFetches() throws Exception {
final AtomicInteger numOfCacheMisses = new AtomicInteger(0);
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final ReentrantLock lockBackingMock = new ReentrantLock();
//Latch to represent that lock acquisition was attempted
final CountDownLatch lockAquisitionAttempted = new CountDownLatch(2);
//A mock lock backed by a reentrant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final Resource resource2 = Mockito.mock(Resource.class);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
numOfCacheMisses.incrementAndGet();
return simulateDownloadWithWait();
}
);
Mockito.when(resource.exists()).thenReturn(true);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Set up the second cache
Mockito.when(
resourceLoader2.getResource(Mockito.anyString())
).thenReturn(resource2);
Mockito.when(
resource2.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
numOfCacheMisses.incrementAndGet();
return simulateDownloadWithWait();
}
);
Mockito.when(resource2.exists()).thenReturn(true);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
downloadCompleted.set(false);
numOfCacheMisses.set(0);
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
executorService.submit(() -> {
try {
cache2.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for both threads to try to lock
lockAquisitionAttempted.await();
//Either one thread would have tried a download or would try shortly.
//So, either one thread is waiting on a download or will try to download.
//Regardless since both threads have atleast tried to lock once,
//signal download completed
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Only one thread reached the critical section
Assert.assertTrue(numOfCacheMisses.get() == 1);
}
/**
* Start two concurrent resource fetches.
* Make the first one to start download fail
* Make sure a cache files exist because the other fetch succeeds
*
* @throws Exception the exception
*/
@Test
public void cacheConcurrentFetchFailOne() throws Exception {
final AtomicInteger numOfCacheMisses = new AtomicInteger(0);
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final CountDownLatch lockAquisitionAttempted = new CountDownLatch(2);
final ReentrantLock lockBackingMock = new ReentrantLock();
//A mock lock backed by a reentant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking facrory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final Resource resource2 = Mockito.mock(Resource.class);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
//first thread trying to download
if (numOfCacheMisses.incrementAndGet() == 1) {
return simulateDownloadFailureWithWait();
} else { // second thread doing the download
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Set up the second cache
Mockito.when(
resourceLoader2.getResource(Mockito.anyString())
).thenReturn(resource2);
Mockito.when(
resource2.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
//first thread trying to download
if (numOfCacheMisses.incrementAndGet() == 1) {
return simulateDownloadFailureWithWait();
} else { // second thread doing the download
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
}
);
Mockito.when(resource2.exists()).thenReturn(true);
Mockito.when(resource2.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
downloadCompleted.set(false);
numOfCacheMisses.set(0);
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
executorService.submit(() -> {
try {
cache2.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for both threads to try to lock
lockAquisitionAttempted.await();
//Either one thread would have tried a download or would try shortly.
//So, either one thread is waiting on a download or will try to download.
//Regardless since both threads have atleast tried to lock once,
//signal download completed
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Both threads reached the critical section
Assert.assertTrue(numOfCacheMisses.get() == 2);
//Proper directory structure and files exist for the resource
Assert.assertTrue(
directoryStructureExists(
cache1.getResourceCacheId(uri),
lastModifiedTimeStamp,
cache1
)
);
}
/**
* Make one cache download a resource version.
* While first one is downloading, make another thread
* delete the same version
* In the end, the previous resource should not exist
*
* @throws Exception the exception
*/
@Test
public void fetchAndDeleteResourceConcurrently() throws Exception {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final CountDownLatch lockAquisitionAttempted = new CountDownLatch(2);
final ReentrantLock lockBackingMock = new ReentrantLock();
//A mock lock backed by a reentant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
//Latch to represent that download was started
final CountDownLatch downloadBegin = new CountDownLatch(1);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
downloadBegin.countDown();
simulateDownloadWithWait();
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
final String resourceCacheId = cache1.getResourceCacheId(uri);
//Set the second cache
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Download was started, first thread in critical section
downloadBegin.await();
//Start deletetion.
executorService.submit(() -> {
try {
//Pass in lastDownloadedVersion = lastModifiedTimeStamp + 1 to trigger
//the deletion of the resource version = lastModifiedTimeStamp
cache2.cleanUpOlderResourceVersions(
resourceCacheId,
lastModifiedTimeStamp + 1
);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
lockAquisitionAttempted.await();
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Make sure the resource is deleted
assertResourceDeleted(cache1, resourceCacheId, lastModifiedTimeStamp);
}
/**
* Make one cache delete a resource version.
* While first one is deleting, make another thread
* download the same version
* In the end, the resource should exist
*
* @throws Exception the exception
*/
@Test
public void deleteAndFetchResourceConcurrently() throws Exception {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final AtomicInteger numJobsInLockMethod = new AtomicInteger(0);
final ReentrantLock lockBackingMock = new ReentrantLock();
final CountDownLatch downLoadJobEnteredLockMethod = new CountDownLatch(1);
final CountDownLatch deletionDone = new CountDownLatch(1);
final CountDownLatch deletionJObEnteredLockMethod = new CountDownLatch(1);
final CountDownLatch deletionSuccessVerified = new CountDownLatch(1);
//A mock lock backed by a reentant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
//deletion thread since its submitted first as the only thread
if (numJobsInLockMethod.incrementAndGet() == 1) {
//make deletion wait until download thread enters the lock method
deletionJObEnteredLockMethod.countDown();
downLoadJobEnteredLockMethod.await();
} else { //download thread
downLoadJobEnteredLockMethod.countDown();
//wait until main thread verifies that deletion was successful
deletionSuccessVerified.await();
}
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
final String resourceCacheId = cache1.getResourceCacheId(uri);
//Set the second cache
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Download the resource which needs to be deleted, else deletion will be a no op
//Set up a separate cache for it.
final ResourceLoader resourceLoader3 = Mockito.mock(ResourceLoader.class);
final Resource resource3 = Mockito.mock(Resource.class);
Mockito.when(resource3.exists()).thenReturn(true);
Mockito.when(resource3.lastModified()).thenReturn(lastModifiedTimeStamp);
Mockito.when(
resource3.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
);
Mockito.when(
resourceLoader3.getResource(Mockito.anyString())
).thenReturn(resource3);
final FetchingCacheServiceImpl cache3 = new FetchingCacheServiceImpl(
resourceLoader3,
cacheArguments,
new FileLockFactory(),
cleanUpTaskExecutor
);
cache3.get(uri, targetFile);
//Assert that the cache download was successful
assertResourceDownloaded(cache3, resourceCacheId, lastModifiedTimeStamp);
//Before submitting the deletion and download jobs make sure conditions are set correctly
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Start deletion
executorService.submit(() -> {
try {
//Pass in lastDownloadedVersion = lastModifiedTimeStamp + 1 to trigger
//the deletion of the resource version = lastModifiedTimeStamp
cache2.cleanUpOlderResourceVersions(
resourceCacheId,
lastModifiedTimeStamp + 1
);
} catch (Exception e) {
e.printStackTrace();
} finally {
deletionDone.countDown();
allFetchesDone.countDown();
}
});
//Deletion thread in lock method
deletionJObEnteredLockMethod.await();
//Start download of the version being deleted.
//This one will make the deletion thread move ahead in lock method
//once it reaches lock method
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for deletion job to be done
deletionDone.await();
//Assert that deletion was successful
assertResourceDeleted(cache1, resourceCacheId, lastModifiedTimeStamp);
//Make the download thread stop waiting in lock method
deletionSuccessVerified.countDown();
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Make sure the resource downloaded is present
assertResourceDownloaded(cache2, resourceCacheId, lastModifiedTimeStamp);
}
private void assertResourceDeleted(
final FetchingCacheServiceImpl cacheService,
final String resourceCacheId,
final long lastModifiedTimeStamp
) {
Assert.assertFalse(
cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertFalse(
cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertTrue(
cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
}
private void assertResourceDownloaded(
final FetchingCacheServiceImpl cacheService,
final String resourceCacheId,
final long lastModifiedTimeStamp
) {
Assert.assertTrue(
cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertFalse(
cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertTrue(
cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
}
/**
* Simulate a download while waiting until notified.
*
* @return inputstream from download
*/
public InputStream simulateDownloadWithWait() {
simulateDownloadLock.lock();
try {
while (!downloadCompleted.get()) {
downloadComplete.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
simulateDownloadLock.unlock();
}
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
/**
* Simulate a download failure while waiting until notified.
*
* @return inputstream from download
* @throws DownloadException simulated error
*/
public InputStream simulateDownloadFailureWithWait() throws DownloadException {
simulateDownloadWithWait();
throw new DownloadException("Simulated error downloading resource");
}
/**
* Verify that all the files exist after a successful download.
*
* @param resourceCacheId resource id for the cache
* @param lastModifiedTimeStamp resource version
* @param cacheService cache service instance
* @return
*/
private boolean directoryStructureExists(
final String resourceCacheId,
final long lastModifiedTimeStamp,
final FetchingCacheServiceImpl cacheService
) {
return cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
&& cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
&& !cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists();
}
/**
* Clean up.
*
* @throws Exception the exception
*/
@After
public void cleanUp() {
cleanUpTaskExecutor.shutdown();
}
}
|
UTF-8
|
Java
| 27,739 |
java
|
FetchingCacheServiceImplTests.java
|
Java
|
[
{
"context": "/*\n *\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License",
"end": 32,
"score": 0.981072723865509,
"start": 25,
"tag": "NAME",
"value": "Netflix"
}
] | null |
[] |
/*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.agent.execution.services.impl;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.execution.exceptions.DownloadException;
import com.netflix.genie.agent.utils.locks.CloseableLock;
import com.netflix.genie.agent.utils.locks.impl.FileLockFactory;
import com.netflix.genie.test.categories.UnitTest;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Tests for fetching cache service implementation.
*/
@Slf4j
@Category(UnitTest.class)
public class FetchingCacheServiceImplTests {
/**
* Temporary folder.
*/
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private URI uri;
private ExecutorService executorService = Executors.newFixedThreadPool(2);
//Boolean flag representing that a downloadCompleted
private AtomicBoolean downloadCompleted = new AtomicBoolean(false);
//CloseableLock used for the downloadComplete condition while simulating a download
private ReentrantLock simulateDownloadLock = new ReentrantLock();
//Condition used during download simulation for waiting
private Condition downloadComplete = simulateDownloadLock.newCondition();
private ArgumentDelegates.CacheArguments cacheArguments;
private File targetFile;
private ThreadPoolTaskExecutor cleanUpTaskExecutor;
/**
* Set up.
*
* @throws Exception the exception
*/
@Before
public void setUp() throws Exception {
uri = new URI("https://my-server.com/path/to/config/config.xml");
cacheArguments = Mockito.mock(ArgumentDelegates.CacheArguments.class);
Mockito.when(
cacheArguments.getCacheDirectory()
).thenReturn(temporaryFolder.getRoot());
targetFile = new File(temporaryFolder.getRoot(), "target");
cleanUpTaskExecutor = new ThreadPoolTaskExecutor();
cleanUpTaskExecutor.setCorePoolSize(1);
cleanUpTaskExecutor.initialize();
}
/**
* Start two concurrent resource fetches.
* Make sure only one cache does the download/enters the critical section
*
* @throws Exception the exception
*/
@Test
public void cacheConcurrentFetches() throws Exception {
final AtomicInteger numOfCacheMisses = new AtomicInteger(0);
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final ReentrantLock lockBackingMock = new ReentrantLock();
//Latch to represent that lock acquisition was attempted
final CountDownLatch lockAquisitionAttempted = new CountDownLatch(2);
//A mock lock backed by a reentrant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final Resource resource2 = Mockito.mock(Resource.class);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
numOfCacheMisses.incrementAndGet();
return simulateDownloadWithWait();
}
);
Mockito.when(resource.exists()).thenReturn(true);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Set up the second cache
Mockito.when(
resourceLoader2.getResource(Mockito.anyString())
).thenReturn(resource2);
Mockito.when(
resource2.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
numOfCacheMisses.incrementAndGet();
return simulateDownloadWithWait();
}
);
Mockito.when(resource2.exists()).thenReturn(true);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
downloadCompleted.set(false);
numOfCacheMisses.set(0);
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
executorService.submit(() -> {
try {
cache2.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for both threads to try to lock
lockAquisitionAttempted.await();
//Either one thread would have tried a download or would try shortly.
//So, either one thread is waiting on a download or will try to download.
//Regardless since both threads have atleast tried to lock once,
//signal download completed
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Only one thread reached the critical section
Assert.assertTrue(numOfCacheMisses.get() == 1);
}
/**
* Start two concurrent resource fetches.
* Make the first one to start download fail
* Make sure a cache files exist because the other fetch succeeds
*
* @throws Exception the exception
*/
@Test
public void cacheConcurrentFetchFailOne() throws Exception {
final AtomicInteger numOfCacheMisses = new AtomicInteger(0);
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final CountDownLatch lockAquisitionAttempted = new CountDownLatch(2);
final ReentrantLock lockBackingMock = new ReentrantLock();
//A mock lock backed by a reentant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking facrory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final Resource resource2 = Mockito.mock(Resource.class);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
//first thread trying to download
if (numOfCacheMisses.incrementAndGet() == 1) {
return simulateDownloadFailureWithWait();
} else { // second thread doing the download
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Set up the second cache
Mockito.when(
resourceLoader2.getResource(Mockito.anyString())
).thenReturn(resource2);
Mockito.when(
resource2.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
//first thread trying to download
if (numOfCacheMisses.incrementAndGet() == 1) {
return simulateDownloadFailureWithWait();
} else { // second thread doing the download
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
}
);
Mockito.when(resource2.exists()).thenReturn(true);
Mockito.when(resource2.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
downloadCompleted.set(false);
numOfCacheMisses.set(0);
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
executorService.submit(() -> {
try {
cache2.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for both threads to try to lock
lockAquisitionAttempted.await();
//Either one thread would have tried a download or would try shortly.
//So, either one thread is waiting on a download or will try to download.
//Regardless since both threads have atleast tried to lock once,
//signal download completed
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Both threads reached the critical section
Assert.assertTrue(numOfCacheMisses.get() == 2);
//Proper directory structure and files exist for the resource
Assert.assertTrue(
directoryStructureExists(
cache1.getResourceCacheId(uri),
lastModifiedTimeStamp,
cache1
)
);
}
/**
* Make one cache download a resource version.
* While first one is downloading, make another thread
* delete the same version
* In the end, the previous resource should not exist
*
* @throws Exception the exception
*/
@Test
public void fetchAndDeleteResourceConcurrently() throws Exception {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final CountDownLatch lockAquisitionAttempted = new CountDownLatch(2);
final ReentrantLock lockBackingMock = new ReentrantLock();
//A mock lock backed by a reentant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
//Latch to represent that download was started
final CountDownLatch downloadBegin = new CountDownLatch(1);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
downloadBegin.countDown();
simulateDownloadWithWait();
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
final String resourceCacheId = cache1.getResourceCacheId(uri);
//Set the second cache
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Download was started, first thread in critical section
downloadBegin.await();
//Start deletetion.
executorService.submit(() -> {
try {
//Pass in lastDownloadedVersion = lastModifiedTimeStamp + 1 to trigger
//the deletion of the resource version = lastModifiedTimeStamp
cache2.cleanUpOlderResourceVersions(
resourceCacheId,
lastModifiedTimeStamp + 1
);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
lockAquisitionAttempted.await();
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Make sure the resource is deleted
assertResourceDeleted(cache1, resourceCacheId, lastModifiedTimeStamp);
}
/**
* Make one cache delete a resource version.
* While first one is deleting, make another thread
* download the same version
* In the end, the resource should exist
*
* @throws Exception the exception
*/
@Test
public void deleteAndFetchResourceConcurrently() throws Exception {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final AtomicInteger numJobsInLockMethod = new AtomicInteger(0);
final ReentrantLock lockBackingMock = new ReentrantLock();
final CountDownLatch downLoadJobEnteredLockMethod = new CountDownLatch(1);
final CountDownLatch deletionDone = new CountDownLatch(1);
final CountDownLatch deletionJObEnteredLockMethod = new CountDownLatch(1);
final CountDownLatch deletionSuccessVerified = new CountDownLatch(1);
//A mock lock backed by a reentant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
//deletion thread since its submitted first as the only thread
if (numJobsInLockMethod.incrementAndGet() == 1) {
//make deletion wait until download thread enters the lock method
deletionJObEnteredLockMethod.countDown();
downLoadJobEnteredLockMethod.await();
} else { //download thread
downLoadJobEnteredLockMethod.countDown();
//wait until main thread verifies that deletion was successful
deletionSuccessVerified.await();
}
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
final String resourceCacheId = cache1.getResourceCacheId(uri);
//Set the second cache
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Download the resource which needs to be deleted, else deletion will be a no op
//Set up a separate cache for it.
final ResourceLoader resourceLoader3 = Mockito.mock(ResourceLoader.class);
final Resource resource3 = Mockito.mock(Resource.class);
Mockito.when(resource3.exists()).thenReturn(true);
Mockito.when(resource3.lastModified()).thenReturn(lastModifiedTimeStamp);
Mockito.when(
resource3.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
);
Mockito.when(
resourceLoader3.getResource(Mockito.anyString())
).thenReturn(resource3);
final FetchingCacheServiceImpl cache3 = new FetchingCacheServiceImpl(
resourceLoader3,
cacheArguments,
new FileLockFactory(),
cleanUpTaskExecutor
);
cache3.get(uri, targetFile);
//Assert that the cache download was successful
assertResourceDownloaded(cache3, resourceCacheId, lastModifiedTimeStamp);
//Before submitting the deletion and download jobs make sure conditions are set correctly
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Start deletion
executorService.submit(() -> {
try {
//Pass in lastDownloadedVersion = lastModifiedTimeStamp + 1 to trigger
//the deletion of the resource version = lastModifiedTimeStamp
cache2.cleanUpOlderResourceVersions(
resourceCacheId,
lastModifiedTimeStamp + 1
);
} catch (Exception e) {
e.printStackTrace();
} finally {
deletionDone.countDown();
allFetchesDone.countDown();
}
});
//Deletion thread in lock method
deletionJObEnteredLockMethod.await();
//Start download of the version being deleted.
//This one will make the deletion thread move ahead in lock method
//once it reaches lock method
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for deletion job to be done
deletionDone.await();
//Assert that deletion was successful
assertResourceDeleted(cache1, resourceCacheId, lastModifiedTimeStamp);
//Make the download thread stop waiting in lock method
deletionSuccessVerified.countDown();
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Make sure the resource downloaded is present
assertResourceDownloaded(cache2, resourceCacheId, lastModifiedTimeStamp);
}
private void assertResourceDeleted(
final FetchingCacheServiceImpl cacheService,
final String resourceCacheId,
final long lastModifiedTimeStamp
) {
Assert.assertFalse(
cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertFalse(
cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertTrue(
cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
}
private void assertResourceDownloaded(
final FetchingCacheServiceImpl cacheService,
final String resourceCacheId,
final long lastModifiedTimeStamp
) {
Assert.assertTrue(
cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertFalse(
cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
Assert.assertTrue(
cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
);
}
/**
* Simulate a download while waiting until notified.
*
* @return inputstream from download
*/
public InputStream simulateDownloadWithWait() {
simulateDownloadLock.lock();
try {
while (!downloadCompleted.get()) {
downloadComplete.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
simulateDownloadLock.unlock();
}
return Mockito.spy(
new ByteArrayInputStream("".getBytes(Charset.forName("UTF-8")))
);
}
/**
* Simulate a download failure while waiting until notified.
*
* @return inputstream from download
* @throws DownloadException simulated error
*/
public InputStream simulateDownloadFailureWithWait() throws DownloadException {
simulateDownloadWithWait();
throw new DownloadException("Simulated error downloading resource");
}
/**
* Verify that all the files exist after a successful download.
*
* @param resourceCacheId resource id for the cache
* @param lastModifiedTimeStamp resource version
* @param cacheService cache service instance
* @return
*/
private boolean directoryStructureExists(
final String resourceCacheId,
final long lastModifiedTimeStamp,
final FetchingCacheServiceImpl cacheService
) {
return cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
&& cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
&& !cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists();
}
/**
* Clean up.
*
* @throws Exception the exception
*/
@After
public void cleanUp() {
cleanUpTaskExecutor.shutdown();
}
}
| 27,739 | 0.63016 | 0.626627 | 796 | 33.847988 | 26.360294 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425879 | false | false |
0
|
cbf3760f33d426b7a5c919118bf0f1fdaa5573df
| 28,827,820,546,233 |
3223402b7758bbaeb7c8221a293ab8c4beb36ec6
|
/app/src/main/java/de/uni_koblenz/soma/LocationService.java
|
df1112758a68b1e8e1ad56fb9f98ea70b3458c62
|
[] |
no_license
|
tiefenau/SoMA-androidv0.1
|
https://github.com/tiefenau/SoMA-androidv0.1
|
70b3caa9e4e9312d667f6754a37ce58c7f3b2375
|
d86029cc08f93ea8d4098e9419861285b9758108
|
refs/heads/master
| 2021-01-25T10:50:58.479000 | 2017-06-09T18:43:29 | 2017-06-09T18:43:29 | 93,887,413 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.uni_koblenz.soma;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class LocationService extends Service {
private static final String TAG = "LocationService";
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private static final int LOCATION_INTERVAL = 5000;
private static final float LOCATION_DISTANCE = 10f;
private DatabaseHelper database = null;
public LocationService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service starting");
database = new DatabaseHelper(this);
startForeground(101, updateNotificationBar());
Log.i(TAG, "Service started");
}
private void initialize() {
initializeLocationManager();
initializeLocationListener();
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, locationListener);
} catch( SecurityException e ){
Log.w(TAG, "Service could not be started: No Permission for location");
stopSelf();
}
//updateNotificationBar();
}
@Override
public void onDestroy() {
Log.i(TAG, "Service stopped");
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
sendBroadcast(new Intent("de.uni_koblenz.soma.RESTART"));
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("de.uni_koblenz.soma.RESTART"));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, intent.toString()+ " ; " + flags + " ; " + startId);
initialize();
return START_REDELIVER_INTENT;
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "onStart");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private void initializeLocationManager() {
if(locationManager == null) locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
private void initializeLocationListener() {
if(locationListener == null) locationListener = new LocationListener(LocationManager.GPS_PROVIDER, database);
}
private Notification updateNotificationBar() {
long dataCount = database.getLocationsCount();
String contentText = "Ihre persönlichen Daten werden gesammelt"; // TODO
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Intent notificationIntent = new Intent(this, SoMAActivity.class);
notificationIntent.setAction("de.uni_koblenz.soma.RESUME");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
NotificationCompat.Builder notification =
new NotificationCompat.Builder(this)
.setContentTitle("SoMA")
.setContentText(contentText)
.setSubText("Data: " + dataCount)
.setSmallIcon(android.R.drawable.ic_menu_mylocation)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true);
NotificationManager mNotificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(101, notification.build());
Log.d(TAG, "updateNotification: dataCount: " + dataCount + ", notificationIntent: " + contentText);
return notification.build();
}
}
|
UTF-8
|
Java
| 4,822 |
java
|
LocationService.java
|
Java
|
[] | null |
[] |
package de.uni_koblenz.soma;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class LocationService extends Service {
private static final String TAG = "LocationService";
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private static final int LOCATION_INTERVAL = 5000;
private static final float LOCATION_DISTANCE = 10f;
private DatabaseHelper database = null;
public LocationService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service starting");
database = new DatabaseHelper(this);
startForeground(101, updateNotificationBar());
Log.i(TAG, "Service started");
}
private void initialize() {
initializeLocationManager();
initializeLocationListener();
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, locationListener);
} catch( SecurityException e ){
Log.w(TAG, "Service could not be started: No Permission for location");
stopSelf();
}
//updateNotificationBar();
}
@Override
public void onDestroy() {
Log.i(TAG, "Service stopped");
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
sendBroadcast(new Intent("de.uni_koblenz.soma.RESTART"));
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("de.uni_koblenz.soma.RESTART"));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, intent.toString()+ " ; " + flags + " ; " + startId);
initialize();
return START_REDELIVER_INTENT;
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "onStart");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private void initializeLocationManager() {
if(locationManager == null) locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
private void initializeLocationListener() {
if(locationListener == null) locationListener = new LocationListener(LocationManager.GPS_PROVIDER, database);
}
private Notification updateNotificationBar() {
long dataCount = database.getLocationsCount();
String contentText = "Ihre persönlichen Daten werden gesammelt"; // TODO
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Intent notificationIntent = new Intent(this, SoMAActivity.class);
notificationIntent.setAction("de.uni_koblenz.soma.RESUME");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
NotificationCompat.Builder notification =
new NotificationCompat.Builder(this)
.setContentTitle("SoMA")
.setContentText(contentText)
.setSubText("Data: " + dataCount)
.setSmallIcon(android.R.drawable.ic_menu_mylocation)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true);
NotificationManager mNotificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(101, notification.build());
Log.d(TAG, "updateNotification: dataCount: " + dataCount + ", notificationIntent: " + contentText);
return notification.build();
}
}
| 4,822 | 0.651317 | 0.646754 | 131 | 34.801525 | 29.141251 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671756 | false | false |
0
|
d923f8285e07eda4424a724b29f23599264e193c
| 14,894,946,615,819 |
0ee4a7747684475337ca9a979a8bd08d3ff27afa
|
/app/src/main/java/com/example/jeferson/cardroid/Principal.java
|
9afc64953381841d609d4e2241f464298402e1e6
|
[] |
no_license
|
JefersonM123/CarDroid
|
https://github.com/JefersonM123/CarDroid
|
b8144cca6110000800fe0d998c5a4f203663c42b
|
62a2ed2f5bc0c81e6e98968a88663f554a4939bb
|
refs/heads/master
| 2016-09-23T04:07:27.392000 | 2016-06-19T16:50:35 | 2016-06-19T16:50:35 | 60,223,767 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.jeferson.cardroid;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class Principal extends Activity
{
boolean Conectado = false;
int ENABLE_BLUETOOTH = 1;
ConexaoBT Conexao;
String statusMessage;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
final ListView Lista = (ListView)findViewById(R.id.lvBt);
ListarPareados();
Lista.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> Parent, View view, int Posicao, long id)
{
Conectar(Lista, view, Posicao, id);
}
});
}
public void btnEnviar_click(View view)
{
if(Conectado)
Toast.makeText(getApplication().getBaseContext(), "Teste", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplication().getBaseContext(), "Conecte-se a um dispositivo primeiro.", Toast.LENGTH_LONG).show();
}
public void btnConectar_click(View view)
{
try
{
BluetoothAdapter adaptador = BluetoothAdapter.getDefaultAdapter();
//Toast.makeText(getApplication().getBaseContext(), "" + Conexao.getId(), Toast.LENGTH_LONG).show();
if (adaptador == null)
throw new Exception("Aparelho não suporta Bluetooth!");
if(!adaptador.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, ENABLE_BLUETOOTH);
Toast.makeText(getApplication().getBaseContext(), "Solicitando ativação do Bluetooth...", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplication().getBaseContext(), "Bluetooth já ativado...", Toast.LENGTH_LONG).show();
}catch(Exception ex)
{
Toast.makeText(getApplication().getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
public void ListarPareados()
{
try
{
ListView Lista = (ListView)findViewById(R.id.lvBt); //ListView da activity_pricipal
BluetoothAdapter adaptador = BluetoothAdapter.getDefaultAdapter(); //Propriedades do Bluetooth
Set<BluetoothDevice> pareados = adaptador.getBondedDevices(); //Dispositivos reconhecidos pelo aparelho
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
if (pareados.size() > 0)
for (BluetoothDevice Device : pareados)
adapter.add(Device.getName() + "\n" + Device.getAddress());
Lista.setAdapter(adapter);
}
catch (Exception ex)
{
Toast.makeText(getApplication().getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
public void Conectar(ListView L, View V, int Posicao, long Id)
{
try
{
String Item =(String)L.getAdapter().getItem(Posicao);
Intent Retorno = new Intent();
Retorno.putExtra("btNomeDisp", Item.substring(0, Item.indexOf("\n")));
Retorno.putExtra("btEndDisp", Item.substring(Item.indexOf("\n") + 1, Item.length()));
setResult(RESULT_OK, Retorno);
Toast.makeText(getApplication().getBaseContext(), "Você selecionou " + Retorno.getStringExtra("btNomeDisp") + "\n" + "Endereço:" + Retorno.getStringExtra("btEndDisp"), Toast.LENGTH_LONG).show();
Conexao = new ConexaoBT(Retorno.getStringExtra("btEndDisp"));
Conexao.Executar();
}
catch (Exception ex)
{
Toast.makeText(getApplication().getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == ENABLE_BLUETOOTH)
{
if (resultCode == RESULT_OK)
Toast.makeText(getApplication().getBaseContext(), "Bluetooth ativado.", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplication().getBaseContext(), "Bluetooth não ativado.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onBackPressed()
{
Toast.makeText(getApplication().getBaseContext(), "Bluetooth não ativado.", Toast.LENGTH_LONG).show();
}
public void btnFrente_click(View view)
{
Conexao.Envia('F');
}
public void btnRe_click(View view)
{
Conexao.Envia('R');
}
public void btnDireita_click(View view)
{
Conexao.Envia('D');
}
public void btnEsquerda_click(View view)
{
Conexao.Envia('E');
}
public void btnParar_click(View view)
{
Conexao.Envia('P');
}
}
|
UTF-8
|
Java
| 5,321 |
java
|
Principal.java
|
Java
|
[
{
"context": "package com.example.jeferson.cardroid;\n\nimport android.app.Activity;\nimport an",
"end": 28,
"score": 0.9978544116020203,
"start": 20,
"tag": "USERNAME",
"value": "jeferson"
}
] | null |
[] |
package com.example.jeferson.cardroid;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class Principal extends Activity
{
boolean Conectado = false;
int ENABLE_BLUETOOTH = 1;
ConexaoBT Conexao;
String statusMessage;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
final ListView Lista = (ListView)findViewById(R.id.lvBt);
ListarPareados();
Lista.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> Parent, View view, int Posicao, long id)
{
Conectar(Lista, view, Posicao, id);
}
});
}
public void btnEnviar_click(View view)
{
if(Conectado)
Toast.makeText(getApplication().getBaseContext(), "Teste", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplication().getBaseContext(), "Conecte-se a um dispositivo primeiro.", Toast.LENGTH_LONG).show();
}
public void btnConectar_click(View view)
{
try
{
BluetoothAdapter adaptador = BluetoothAdapter.getDefaultAdapter();
//Toast.makeText(getApplication().getBaseContext(), "" + Conexao.getId(), Toast.LENGTH_LONG).show();
if (adaptador == null)
throw new Exception("Aparelho não suporta Bluetooth!");
if(!adaptador.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, ENABLE_BLUETOOTH);
Toast.makeText(getApplication().getBaseContext(), "Solicitando ativação do Bluetooth...", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplication().getBaseContext(), "Bluetooth já ativado...", Toast.LENGTH_LONG).show();
}catch(Exception ex)
{
Toast.makeText(getApplication().getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
public void ListarPareados()
{
try
{
ListView Lista = (ListView)findViewById(R.id.lvBt); //ListView da activity_pricipal
BluetoothAdapter adaptador = BluetoothAdapter.getDefaultAdapter(); //Propriedades do Bluetooth
Set<BluetoothDevice> pareados = adaptador.getBondedDevices(); //Dispositivos reconhecidos pelo aparelho
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
if (pareados.size() > 0)
for (BluetoothDevice Device : pareados)
adapter.add(Device.getName() + "\n" + Device.getAddress());
Lista.setAdapter(adapter);
}
catch (Exception ex)
{
Toast.makeText(getApplication().getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
public void Conectar(ListView L, View V, int Posicao, long Id)
{
try
{
String Item =(String)L.getAdapter().getItem(Posicao);
Intent Retorno = new Intent();
Retorno.putExtra("btNomeDisp", Item.substring(0, Item.indexOf("\n")));
Retorno.putExtra("btEndDisp", Item.substring(Item.indexOf("\n") + 1, Item.length()));
setResult(RESULT_OK, Retorno);
Toast.makeText(getApplication().getBaseContext(), "Você selecionou " + Retorno.getStringExtra("btNomeDisp") + "\n" + "Endereço:" + Retorno.getStringExtra("btEndDisp"), Toast.LENGTH_LONG).show();
Conexao = new ConexaoBT(Retorno.getStringExtra("btEndDisp"));
Conexao.Executar();
}
catch (Exception ex)
{
Toast.makeText(getApplication().getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == ENABLE_BLUETOOTH)
{
if (resultCode == RESULT_OK)
Toast.makeText(getApplication().getBaseContext(), "Bluetooth ativado.", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplication().getBaseContext(), "Bluetooth não ativado.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onBackPressed()
{
Toast.makeText(getApplication().getBaseContext(), "Bluetooth não ativado.", Toast.LENGTH_LONG).show();
}
public void btnFrente_click(View view)
{
Conexao.Envia('F');
}
public void btnRe_click(View view)
{
Conexao.Envia('R');
}
public void btnDireita_click(View view)
{
Conexao.Envia('D');
}
public void btnEsquerda_click(View view)
{
Conexao.Envia('E');
}
public void btnParar_click(View view)
{
Conexao.Envia('P');
}
}
| 5,321 | 0.619612 | 0.618671 | 157 | 32.840763 | 37.026329 | 206 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.624204 | false | false |
0
|
a2655239bc29c9a1e317e0c3f78df5bfc746a16e
| 27,333,171,931,127 |
1664be81a10e2d4a8cf5c93de60fc479d2d2e490
|
/api-ventas/src/main/java/com/mitocode/devops/model/DetalleVenta.java
|
69419355cb964f04e6dce7d2a98bd52f626e42da
|
[] |
no_license
|
JulioAvalos/api-ventas
|
https://github.com/JulioAvalos/api-ventas
|
e8b9d7145a74f6545aef3dbf80e1a10deaaa15d9
|
1e1eff93bce60423acc6ae88100247206e96105f
|
refs/heads/master
| 2020-12-20T02:57:16.118000 | 2020-02-01T06:28:27 | 2020-02-01T06:28:27 | 235,940,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mitocode.devops.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@EqualsAndHashCode(exclude = "producto")
public class DetalleVenta {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idDetalleVenta;
private int cantidad;
@ManyToOne
@JoinColumn(name = "id_producto", nullable = false, foreignKey = @ForeignKey(name="fk_producto"))
private Producto producto;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "id_venta", nullable = false, foreignKey = @ForeignKey(name="fk_venta"))
private Venta venta;
}
|
UTF-8
|
Java
| 694 |
java
|
DetalleVenta.java
|
Java
|
[] | null |
[] |
package com.mitocode.devops.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@EqualsAndHashCode(exclude = "producto")
public class DetalleVenta {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idDetalleVenta;
private int cantidad;
@ManyToOne
@JoinColumn(name = "id_producto", nullable = false, foreignKey = @ForeignKey(name="fk_producto"))
private Producto producto;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "id_venta", nullable = false, foreignKey = @ForeignKey(name="fk_venta"))
private Venta venta;
}
| 694 | 0.731988 | 0.731988 | 29 | 22.931034 | 25.385214 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413793 | false | false |
0
|
15d35fffe56ae303e5b0c1ab97e623727c66a4bb
| 16,217,796,524,936 |
d1c667fcbf6deac48dc8eb12853763e534e7f238
|
/sdk/java-typesafe-api/src/main/java/com/ebay/cloud/cms/typsafe/restful/FieldJsonBuilder.java
|
e5adfd2141aec47fa63e79da86389d8422b222a6
|
[
"Apache-2.0"
] |
permissive
|
huayl/YiDB
|
https://github.com/huayl/YiDB
|
62abca7aff1500bb0133eab7548ea09ab784a260
|
a178e1f76d0eb6eab48a2ab03bf48500f1c8a21f
|
refs/heads/master
| 2022-05-02T12:00:32.040000 | 2022-03-03T23:36:57 | 2022-03-03T23:36:57 | 48,884,133 | 0 | 0 |
Apache-2.0
| true | 2022-03-04T02:02:58 | 2016-01-01T17:14:08 | 2018-05-31T16:59:39 | 2022-03-04T02:02:57 | 12,950 | 0 | 0 | 0 |
Java
| false | false |
/**
*
*/
package com.ebay.cloud.cms.typsafe.restful;
import org.codehaus.jackson.JsonNode;
import com.ebay.cloud.cms.typsafe.service.CMSClientConfig;
/**
* @author liasu
*
*/
public class FieldJsonBuilder extends JsonBuilder {
protected final String fieldName;
public FieldJsonBuilder(CMSClientConfig config, String fieldName) {
super(config);
this.fieldName = fieldName;
}
@Override
public String buildJson(Object object) {
if (object instanceof String) {
return (String) object;
}
JsonNode node = buildJsonNode(object);
if (node.has(fieldName)) {
return node.get(fieldName).toString();
}
return null;
}
}
|
UTF-8
|
Java
| 732 |
java
|
FieldJsonBuilder.java
|
Java
|
[
{
"context": "s.typsafe.service.CMSClientConfig;\n\n/**\n * @author liasu\n * \n */\npublic class FieldJsonBuilder extends Jso",
"end": 176,
"score": 0.9991834759712219,
"start": 171,
"tag": "USERNAME",
"value": "liasu"
}
] | null |
[] |
/**
*
*/
package com.ebay.cloud.cms.typsafe.restful;
import org.codehaus.jackson.JsonNode;
import com.ebay.cloud.cms.typsafe.service.CMSClientConfig;
/**
* @author liasu
*
*/
public class FieldJsonBuilder extends JsonBuilder {
protected final String fieldName;
public FieldJsonBuilder(CMSClientConfig config, String fieldName) {
super(config);
this.fieldName = fieldName;
}
@Override
public String buildJson(Object object) {
if (object instanceof String) {
return (String) object;
}
JsonNode node = buildJsonNode(object);
if (node.has(fieldName)) {
return node.get(fieldName).toString();
}
return null;
}
}
| 732 | 0.636612 | 0.636612 | 34 | 20.529411 | 20.664312 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.323529 | false | false |
0
|
b71fbd6ea4961f0c9b3274011a130f37a72b81fe
| 30,537,217,529,503 |
c7026fec9329002e5f1db3f314c0c9a2974a3ae8
|
/app/src/main/java/com/example/kacper_light_erp/bestcalendareu/CalendarTaskList.java
|
ce19bf55d5c5c6abbff0d775a63961f6b3857614
|
[] |
no_license
|
Reason20/BestCalendarEU
|
https://github.com/Reason20/BestCalendarEU
|
5caf7d8e49cf8b9b1828d61f4898e33ddca464fd
|
4f07bade5042b5e40afdaa91783db9fff9c6d084
|
refs/heads/master
| 2020-12-25T13:23:36.070000 | 2016-06-19T16:23:59 | 2016-06-19T16:23:59 | 60,860,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.kacper_light_erp.bestcalendareu;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
public class CalendarTaskList extends ActionBarActivity {
public static final String SELECTED_DATE = "date";
public String SelectedDate;
private static final String TAG = CalendarTaskList.class.getSimpleName();
private ListView lv;
private Handler handler;
private EventsAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_task_list);
handler = new Handler();
Intent i = getIntent();
SelectedDate = new String();
SelectedDate = i.getExtras().getString(SELECTED_DATE);
//Toast.makeText(CalendarTaskList.this, SelectedDate, Toast.LENGTH_LONG).show();
initializeList();
new Thread(new Runnable() {
@Override
public void run() {
getEventsFromNetwork();
}
}).start();
}
private void getEventsFromNetwork() {
try {
fetchEvents();
} catch (IOException e) {
Log.e(TAG, "IOException while fetching recipes", e);
showToast("IOException while fetching recipes");
} catch (JSONException e) {
Log.e(TAG, "JSONException while fetching recipes", e);
showToast("JSONException while fetching recipes");
}
}
private void fetchEvents() throws IOException, JSONException {
final NetworkEventsProvider networkEventsProvider = new NetworkEventsProvider(this);
networkEventsProvider.getEvents(new NetworkEventsProvider.OnEventsDownloadedListener() {
@Override
public void onEventsDownloaded() {
handler.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Fetched " + networkEventsProvider.getEventsNumber() + " events");
adapter.setEvents(networkEventsProvider.getAllEvents());
adapter.notifyDataSetChanged();
}
});
}
}, SelectedDate);
}
private void showToast(final String tost) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(CalendarTaskList.this, tost, Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
private void initializeList() {
lv = (ListView) findViewById(R.id.listView);
adapter = new EventsAdapter(this);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Event event = adapter.getItem(position);
showEvent(event);
}
});
}
private void showEvent(Event event) {
Intent i = new Intent(this, EventsDetailsActivity.class);
i.putExtra(EventsDetailsActivity.EVENT_KEY, event);
startActivity(i);
}
}
|
UTF-8
|
Java
| 3,610 |
java
|
CalendarTaskList.java
|
Java
|
[] | null |
[] |
package com.example.kacper_light_erp.bestcalendareu;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
public class CalendarTaskList extends ActionBarActivity {
public static final String SELECTED_DATE = "date";
public String SelectedDate;
private static final String TAG = CalendarTaskList.class.getSimpleName();
private ListView lv;
private Handler handler;
private EventsAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_task_list);
handler = new Handler();
Intent i = getIntent();
SelectedDate = new String();
SelectedDate = i.getExtras().getString(SELECTED_DATE);
//Toast.makeText(CalendarTaskList.this, SelectedDate, Toast.LENGTH_LONG).show();
initializeList();
new Thread(new Runnable() {
@Override
public void run() {
getEventsFromNetwork();
}
}).start();
}
private void getEventsFromNetwork() {
try {
fetchEvents();
} catch (IOException e) {
Log.e(TAG, "IOException while fetching recipes", e);
showToast("IOException while fetching recipes");
} catch (JSONException e) {
Log.e(TAG, "JSONException while fetching recipes", e);
showToast("JSONException while fetching recipes");
}
}
private void fetchEvents() throws IOException, JSONException {
final NetworkEventsProvider networkEventsProvider = new NetworkEventsProvider(this);
networkEventsProvider.getEvents(new NetworkEventsProvider.OnEventsDownloadedListener() {
@Override
public void onEventsDownloaded() {
handler.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Fetched " + networkEventsProvider.getEventsNumber() + " events");
adapter.setEvents(networkEventsProvider.getAllEvents());
adapter.notifyDataSetChanged();
}
});
}
}, SelectedDate);
}
private void showToast(final String tost) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(CalendarTaskList.this, tost, Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
private void initializeList() {
lv = (ListView) findViewById(R.id.listView);
adapter = new EventsAdapter(this);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Event event = adapter.getItem(position);
showEvent(event);
}
});
}
private void showEvent(Event event) {
Intent i = new Intent(this, EventsDetailsActivity.class);
i.putExtra(EventsDetailsActivity.EVENT_KEY, event);
startActivity(i);
}
}
| 3,610 | 0.615512 | 0.615235 | 124 | 28.112904 | 25.766699 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false |
0
|
555932c0422d1d171fd676140f0b30f4b5aca94a
| 27,479,200,781,082 |
9b0bef6996bf50f7d525b0384d326d9422ba7b7f
|
/workspace/Estudos/src/atividade_4/Atividade_4_02.java
|
c4d0c29861817ae7fdde8a9a9f21168d5070ab38
|
[] |
no_license
|
thiagosilva92/JavaStudy
|
https://github.com/thiagosilva92/JavaStudy
|
49d5e6fe46aad754eb0c237d67c3331e2aad77d4
|
815a64423d149cd76de96a28ec468a5eacb25fe1
|
refs/heads/master
| 2016-09-06T11:14:36.945000 | 2015-03-24T14:21:37 | 2015-03-24T14:21:37 | 32,599,200 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package atividade_4;
public class Atividade_4_02 {
public static void main( String[] args) {
int x = 10;
int y = 9;
x = x / y;
y = y / x;
System.out.println( func(x,y) + func(y,x));
}
public static String func(int a, int b) {
if ((a != b) | ( a > 2 ))
return ("AB" + "X");
else return ("RR");
}
}
|
UTF-8
|
Java
| 328 |
java
|
Atividade_4_02.java
|
Java
|
[] | null |
[] |
package atividade_4;
public class Atividade_4_02 {
public static void main( String[] args) {
int x = 10;
int y = 9;
x = x / y;
y = y / x;
System.out.println( func(x,y) + func(y,x));
}
public static String func(int a, int b) {
if ((a != b) | ( a > 2 ))
return ("AB" + "X");
else return ("RR");
}
}
| 328 | 0.52439 | 0.5 | 20 | 15.4 | 14.779716 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.9 | false | false |
0
|
3bebe0476f716f863d3ca226f52d391a304bd0ff
| 15,659,450,784,682 |
7ccfb7ccdb738583e090cd427866cef8b06529ef
|
/src/main/java/com/global/kinetic/repositories/UserRepository.java
|
40cbc67797f0ff06cba1cb44917a67b86b7cd4bd
|
[] |
no_license
|
BigJ-dev/GlobalKineticApi
|
https://github.com/BigJ-dev/GlobalKineticApi
|
f26c0829ef04c1ca25ceb8c47f395cf30ef70749
|
50b731db8974c0903b7773bd9595f7862764e03f
|
refs/heads/master
| 2023-08-03T12:14:13.506000 | 2021-09-22T07:39:35 | 2021-09-22T07:39:35 | 409,104,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.global.kinetic.repositories;
import Projection.UserProjection;
import com.global.kinetic.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "select * from user", nativeQuery = true)
List<UserProjection> getAllUsers();
User findByUsername(String username);
}
|
UTF-8
|
Java
| 472 |
java
|
UserRepository.java
|
Java
|
[] | null |
[] |
package com.global.kinetic.repositories;
import Projection.UserProjection;
import com.global.kinetic.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "select * from user", nativeQuery = true)
List<UserProjection> getAllUsers();
User findByUsername(String username);
}
| 472 | 0.788136 | 0.788136 | 17 | 26.764706 | 24.568104 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false |
0
|
68813daf8eb52c2babdbca336338182396aba470
| 34,479,997,493,698 |
c5be190cae8df83e735457dd6a7314ee912cca01
|
/Q-1/Main.java
|
8bca4bc29a6bd39454310594f8d0ea1c95c590be
|
[] |
no_license
|
vatsal-uppal-1997/ASSIGNMENT-13
|
https://github.com/vatsal-uppal-1997/ASSIGNMENT-13
|
40e344b97b2eb75c7876a94a6d0f94df0760713f
|
0fe94071120fde9851f60ef81702518e36026e88
|
refs/heads/master
| 2020-03-30T06:01:25.135000 | 2018-09-29T06:40:55 | 2018-09-29T06:40:55 | 150,834,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date dt = new Date();
SimpleDateFormat frmt = new SimpleDateFormat("dd MMMM yy");
System.out.println(frmt.format(dt));
}
}
|
UTF-8
|
Java
| 256 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date dt = new Date();
SimpleDateFormat frmt = new SimpleDateFormat("dd MMMM yy");
System.out.println(frmt.format(dt));
}
}
| 256 | 0.707031 | 0.707031 | 14 | 17.285715 | 19.270365 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
0
|
8e0120e842d5631d779e5185a2ac43f029f1c7f7
| 36,825,049,614,085 |
efb59ab39d695251e4c3af708d4ae5c810594935
|
/Client/app/src/main/java/com/example/tallerdyp2/client/utils/SharedPreferencesUtils.java
|
5491ae68cdea6e8ff92480625d5caab476f6d0f6
|
[] |
no_license
|
xpitr256/7547Android
|
https://github.com/xpitr256/7547Android
|
d3b0fec0863e4687d49e9902a4b6f94d7267451a
|
08a66862545cd06d7f2c354e1aa81edcd29cf765
|
refs/heads/master
| 2021-01-18T11:24:02.264000 | 2017-05-16T12:29:12 | 2017-05-16T12:29:12 | 84,323,809 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.tallerdyp2.client.utils;
import android.content.SharedPreferences;
import com.example.tallerdyp2.client.AttractionGOApplication;
/**
* Created by Sebastian on 1/4/2017.
*/
public class SharedPreferencesUtils {
private static SharedPreferences prefs = AttractionGOApplication.getAppContext().
getSharedPreferences(Constants.PREFERENCES, AttractionGOApplication.getAppContext().MODE_PRIVATE);
public static String getTokenSplex() {
String token = prefs.getString(Constants.TOKEN_SPLEX_SESSION, Constants.EMPTY_STRING);
return token;
}
public static void setTokenSplex(String token) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.TOKEN_SPLEX_SESSION, token);
editor.commit();
}
public static String getFacebookUserId() {
String token = prefs.getString(Constants.FB_USER_ID, Constants.EMPTY_STRING);
return token;
}
public static void setFacebookUserId(String userId) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.FB_USER_ID, userId);
editor.commit();
}
public static String getSplexUserName() {
String token = prefs.getString(Constants.SPLEX_USER_NAME, Constants.EMPTY_STRING);
return token;
}
public static void setSplexUserName(String userId) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.SPLEX_USER_NAME, userId);
editor.commit();
}
public static String getLanguage() {
String token = prefs.getString(Constants.LANGUAGE, Constants.EMPTY_STRING);
return token;
}
public static void setLanguage(String language) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.LANGUAGE, language);
editor.commit();
}
}
|
UTF-8
|
Java
| 1,907 |
java
|
SharedPreferencesUtils.java
|
Java
|
[
{
"context": "client.AttractionGOApplication;\n\n/**\n * Created by Sebastian on 1/4/2017.\n */\n\npublic class SharedPreferencesU",
"end": 179,
"score": 0.9934300184249878,
"start": 170,
"tag": "NAME",
"value": "Sebastian"
}
] | null |
[] |
package com.example.tallerdyp2.client.utils;
import android.content.SharedPreferences;
import com.example.tallerdyp2.client.AttractionGOApplication;
/**
* Created by Sebastian on 1/4/2017.
*/
public class SharedPreferencesUtils {
private static SharedPreferences prefs = AttractionGOApplication.getAppContext().
getSharedPreferences(Constants.PREFERENCES, AttractionGOApplication.getAppContext().MODE_PRIVATE);
public static String getTokenSplex() {
String token = prefs.getString(Constants.TOKEN_SPLEX_SESSION, Constants.EMPTY_STRING);
return token;
}
public static void setTokenSplex(String token) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.TOKEN_SPLEX_SESSION, token);
editor.commit();
}
public static String getFacebookUserId() {
String token = prefs.getString(Constants.FB_USER_ID, Constants.EMPTY_STRING);
return token;
}
public static void setFacebookUserId(String userId) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.FB_USER_ID, userId);
editor.commit();
}
public static String getSplexUserName() {
String token = prefs.getString(Constants.SPLEX_USER_NAME, Constants.EMPTY_STRING);
return token;
}
public static void setSplexUserName(String userId) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.SPLEX_USER_NAME, userId);
editor.commit();
}
public static String getLanguage() {
String token = prefs.getString(Constants.LANGUAGE, Constants.EMPTY_STRING);
return token;
}
public static void setLanguage(String language) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.LANGUAGE, language);
editor.commit();
}
}
| 1,907 | 0.691662 | 0.687467 | 71 | 25.87324 | 29.612013 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464789 | false | false |
0
|
5d49f2c1d6fd50871a128beaeef821c34ea4ad06
| 37,031,208,040,536 |
76ca52991ca1a1e50d066e9f7c4827b6a4453414
|
/core/java/android/text/style/EasyEditSpan.java
|
bfb2873b5112e46e6ad5d5fb2f18d5b0ea4cab09
|
[
"Apache-2.0",
"LicenseRef-scancode-unicode"
] |
permissive
|
ResurrectionRemix/android_frameworks_base
|
https://github.com/ResurrectionRemix/android_frameworks_base
|
3126048967fa5f14760664bea8002e7911da206a
|
5e1db0334755ba47245d69857a17f84503f7ce6f
|
refs/heads/Q
| 2023-02-17T11:50:11.652000 | 2021-09-19T11:36:09 | 2021-09-19T11:36:09 | 17,213,932 | 169 | 1,154 |
Apache-2.0
| false | 2023-02-11T12:45:31 | 2014-02-26T14:52:44 | 2022-11-20T20:08:48 | 2023-02-11T11:57:00 | 3,325,928 | 112 | 289 | 0 |
Java
| false | false |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.text.style;
import android.annotation.NonNull;
import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
import android.os.Parcel;
import android.text.ParcelableSpan;
import android.text.TextUtils;
import android.widget.TextView;
/**
* Provides an easy way to edit a portion of text.
* <p>
* The {@link TextView} uses this span to allow the user to delete a chuck of text in one click.
* <p>
* {@link TextView} removes the span when the user deletes the whole text or modifies it.
* <p>
* This span can be also used to receive notification when the user deletes or modifies the text;
*/
public class EasyEditSpan implements ParcelableSpan {
/**
* The extra key field in the pending intent that describes how the text changed.
*
* @see #TEXT_DELETED
* @see #TEXT_MODIFIED
*/
public static final String EXTRA_TEXT_CHANGED_TYPE =
"android.text.style.EXTRA_TEXT_CHANGED_TYPE";
/**
* The value of {@link #EXTRA_TEXT_CHANGED_TYPE} when the text wrapped by this span is deleted.
*/
public static final int TEXT_DELETED = 1;
/**
* The value of {@link #EXTRA_TEXT_CHANGED_TYPE} when the text wrapped by this span is modified.
*/
public static final int TEXT_MODIFIED = 2;
private final PendingIntent mPendingIntent;
private boolean mDeleteEnabled;
/**
* Creates the span. No intent is sent when the wrapped text is modified or
* deleted.
*/
public EasyEditSpan() {
mPendingIntent = null;
mDeleteEnabled = true;
}
/**
* @param pendingIntent The intent will be sent when the wrapped text is deleted or modified.
* When the pending intent is sent, {@link #EXTRA_TEXT_CHANGED_TYPE} is
* added in the intent to describe how the text changed.
*/
public EasyEditSpan(PendingIntent pendingIntent) {
mPendingIntent = pendingIntent;
mDeleteEnabled = true;
}
/**
* Constructor called from {@link TextUtils} to restore the span.
*/
public EasyEditSpan(@NonNull Parcel source) {
mPendingIntent = source.readParcelable(null);
mDeleteEnabled = (source.readByte() == 1);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
writeToParcelInternal(dest, flags);
}
/** @hide */
public void writeToParcelInternal(@NonNull Parcel dest, int flags) {
dest.writeParcelable(mPendingIntent, 0);
dest.writeByte((byte) (mDeleteEnabled ? 1 : 0));
}
@Override
public int getSpanTypeId() {
return getSpanTypeIdInternal();
}
/** @hide */
public int getSpanTypeIdInternal() {
return TextUtils.EASY_EDIT_SPAN;
}
/**
* @return True if the {@link TextView} should offer the ability to delete the text.
*
* @hide
*/
@UnsupportedAppUsage
public boolean isDeleteEnabled() {
return mDeleteEnabled;
}
/**
* Enables or disables the deletion of the text.
*
* @hide
*/
@UnsupportedAppUsage
public void setDeleteEnabled(boolean value) {
mDeleteEnabled = value;
}
/**
* @return the pending intent to send when the wrapped text is deleted or modified.
*
* @hide
*/
@UnsupportedAppUsage
public PendingIntent getPendingIntent() {
return mPendingIntent;
}
}
|
UTF-8
|
Java
| 4,159 |
java
|
EasyEditSpan.java
|
Java
|
[] | null |
[] |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.text.style;
import android.annotation.NonNull;
import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
import android.os.Parcel;
import android.text.ParcelableSpan;
import android.text.TextUtils;
import android.widget.TextView;
/**
* Provides an easy way to edit a portion of text.
* <p>
* The {@link TextView} uses this span to allow the user to delete a chuck of text in one click.
* <p>
* {@link TextView} removes the span when the user deletes the whole text or modifies it.
* <p>
* This span can be also used to receive notification when the user deletes or modifies the text;
*/
public class EasyEditSpan implements ParcelableSpan {
/**
* The extra key field in the pending intent that describes how the text changed.
*
* @see #TEXT_DELETED
* @see #TEXT_MODIFIED
*/
public static final String EXTRA_TEXT_CHANGED_TYPE =
"android.text.style.EXTRA_TEXT_CHANGED_TYPE";
/**
* The value of {@link #EXTRA_TEXT_CHANGED_TYPE} when the text wrapped by this span is deleted.
*/
public static final int TEXT_DELETED = 1;
/**
* The value of {@link #EXTRA_TEXT_CHANGED_TYPE} when the text wrapped by this span is modified.
*/
public static final int TEXT_MODIFIED = 2;
private final PendingIntent mPendingIntent;
private boolean mDeleteEnabled;
/**
* Creates the span. No intent is sent when the wrapped text is modified or
* deleted.
*/
public EasyEditSpan() {
mPendingIntent = null;
mDeleteEnabled = true;
}
/**
* @param pendingIntent The intent will be sent when the wrapped text is deleted or modified.
* When the pending intent is sent, {@link #EXTRA_TEXT_CHANGED_TYPE} is
* added in the intent to describe how the text changed.
*/
public EasyEditSpan(PendingIntent pendingIntent) {
mPendingIntent = pendingIntent;
mDeleteEnabled = true;
}
/**
* Constructor called from {@link TextUtils} to restore the span.
*/
public EasyEditSpan(@NonNull Parcel source) {
mPendingIntent = source.readParcelable(null);
mDeleteEnabled = (source.readByte() == 1);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
writeToParcelInternal(dest, flags);
}
/** @hide */
public void writeToParcelInternal(@NonNull Parcel dest, int flags) {
dest.writeParcelable(mPendingIntent, 0);
dest.writeByte((byte) (mDeleteEnabled ? 1 : 0));
}
@Override
public int getSpanTypeId() {
return getSpanTypeIdInternal();
}
/** @hide */
public int getSpanTypeIdInternal() {
return TextUtils.EASY_EDIT_SPAN;
}
/**
* @return True if the {@link TextView} should offer the ability to delete the text.
*
* @hide
*/
@UnsupportedAppUsage
public boolean isDeleteEnabled() {
return mDeleteEnabled;
}
/**
* Enables or disables the deletion of the text.
*
* @hide
*/
@UnsupportedAppUsage
public void setDeleteEnabled(boolean value) {
mDeleteEnabled = value;
}
/**
* @return the pending intent to send when the wrapped text is deleted or modified.
*
* @hide
*/
@UnsupportedAppUsage
public PendingIntent getPendingIntent() {
return mPendingIntent;
}
}
| 4,159 | 0.656889 | 0.653282 | 143 | 28.083916 | 28.273266 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
0
|
dc81a08eb8e2b418c84e0ce86771d14b6af6637e
| 38,886,633,898,694 |
44979e8ef1ee7281420444fe38ea5cabe7686f79
|
/app/src/main/java/com/showers/main/HomeFragment.java
|
8772bc013d520e958a790d57cbe34f40fb561f6a
|
[] |
no_license
|
khaiwalVikrant/Weather-App-using-Yahoo-API
|
https://github.com/khaiwalVikrant/Weather-App-using-Yahoo-API
|
d4fa1621108bf27d09e0e4ff08421f80f3a7f893
|
444b2fc551ad00f53c4e16a946c17dc09310b852
|
refs/heads/master
| 2021-01-20T22:11:15.612000 | 2016-06-04T11:02:42 | 2016-06-04T11:02:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.showers.main;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.showers.R;
import com.showers.model.ViewModel;
import com.showers.restModel.Root;
import com.showers.restclient.RestClient;
import com.showers.utility.MyUtility;
import com.showers.utility.Progressdialog;
import com.showers.utility.UnitUtility;
import com.thbs.skycons.library.CloudHvRainView;
import com.thbs.skycons.library.CloudMoonView;
import com.thbs.skycons.library.CloudRainView;
import com.thbs.skycons.library.CloudSunView;
import com.thbs.skycons.library.CloudThunderView;
import com.thbs.skycons.library.CloudView;
import com.thbs.skycons.library.MoonView;
import com.thbs.skycons.library.SkyconView;
import com.thbs.skycons.library.SunView;
import com.thbs.skycons.library.WindView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import retrofit2.Call;
/**
* Created by vikrant on 01/6/16.
*/
// This class display Current date weather information
public class HomeFragment extends Fragment{
private SimpleDateFormat srcFormatter=new SimpleDateFormat("yyyy-MM-dd");
private static List<ViewModel> items = new ArrayList<>();
private Context context;
private View root;
private Progressdialog key_progressbar;
// Declare UI elements
private TextView cityText, dayDateText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView unitTemp;
private TextView visibility;
private TextView hum;
private TextView sunset;
private TextView sunrise;
private LinearLayout dayView;
private LinearLayout mainView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
root = (View) inflater.inflate(R.layout.content_main, null);
context = getActivity();
mainView = (LinearLayout) root.findViewById(R.id.mainView);
dayView = (LinearLayout) root.findViewById(R.id.dayView);
dayDateText = (TextView) root.findViewById(R.id.dayDate);
cityText = (TextView) root.findViewById(R.id.location);
temp = (TextView) root.findViewById(R.id.temp);
condDescr = (TextView) root.findViewById(R.id.descrWeather);
hum = (TextView) root.findViewById(R.id.humidity);
press = (TextView) root.findViewById(R.id.pressure);
windSpeed = (TextView) root.findViewById(R.id.windSpeed);
windDeg = (TextView) root.findViewById(R.id.windDeg);
unitTemp = (TextView) root.findViewById(R.id.tempUnit);
visibility = (TextView) root.findViewById(R.id.visibility);
sunrise = (TextView) root.findViewById(R.id.sunrise);
sunset = (TextView) root.findViewById(R.id.sunset);
// check internet connection
if(MyUtility.isConnected(context)) {
//initialize progress dialog
key_progressbar = (Progressdialog) Progressdialog.show(context);
// this function get all json data from yahoo api and use current information
getCurrentWeatherUpdates();
}
else
Toast.makeText(context, getString(R.string.internetconnection), Toast.LENGTH_LONG).show();
return root;
}
private void getCurrentWeatherUpdates() {
RestClient.RestInterface service = RestClient.getClient(getActivity());
Call<Root> call = service.getYahooWeather();
call.enqueue(new retrofit2.Callback<Root>() {
@Override
public void onResponse(Call<Root> call, retrofit2.Response<Root> response) {
if (response != null && response.isSuccessful() && response.errorBody() == null){
Date createdDate = null;
try {
//get created date
createdDate = srcFormatter.parse(response.body().getQuery().getCreated());
} catch (ParseException ex) {
ex.printStackTrace();
}
// create object of Skycons library
SunView sunView = new SunView(context);
MoonView moonView = new MoonView(context);
SkyconView skyconView = new SkyconView(context);
CloudThunderView thunderView = new CloudThunderView(context);
CloudRainView cloudRainView = new CloudRainView(context);
CloudHvRainView cloudHvRainView = new CloudHvRainView(context);
CloudMoonView cloudMoonView = new CloudMoonView(context);
CloudSunView cloudSunView = new CloudSunView(context);
CloudView cloudView = new CloudView(context);
WindView windView = new WindView(context);
// change background of icons
sunView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudHvRainView.setBgColor(context.getResources().getColor(android.R.color.transparent));
skyconView.setBgColor(context.getResources().getColor(android.R.color.transparent));
moonView.setBgColor(context.getResources().getColor(android.R.color.transparent));
thunderView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudRainView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudMoonView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudSunView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudView.setBgColor(context.getResources().getColor(android.R.color.transparent));
windView.setBgColor(context.getResources().getColor(android.R.color.transparent));
LinearLayout layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
int dayCode = Integer.parseInt(response.body().getQuery().getResults().getChannel().getItem().getCondition().getCode());
// get current sdk version
final int sdk = android.os.Build.VERSION.SDK_INT;
// in these statement change background image according with current weather
if(dayCode == 27 || dayCode == 29){
//mostly cloudy (night)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.rainview) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.rainview));
}
}else if(dayCode == 28 || dayCode == 30){
//mostly cloudy (day)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.sunny) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.sunny));
}
}
else if(dayCode == 31 || dayCode == 33){
//clear (night)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.clearnight) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.clearnight));
}
}
else if(dayCode == 32 || dayCode == 34){
//fair (day)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.cleanweather) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.cleanweather));
}
}
// here we can change icon of current weather using yahoo api code
if(dayCode == 4 || dayCode == 47){
dayView.addView(thunderView);
}
else if(dayCode == 11 || dayCode == 12){
dayView.addView(cloudRainView);
}
else if(dayCode == 23){
dayView.addView(windView);
}
else if(dayCode == 29){
dayView.addView(cloudMoonView);
}
else if(dayCode == 28 || dayCode == 30){
dayView.addView(cloudSunView);
}else if(dayCode == 27 || dayCode == 31 || dayCode == 33){
moonView.setStrokeColor(getResources().getColor(R.color.color_white));
dayView.addView(moonView);
}
else if(dayCode == 32 || dayCode == 34){
dayView.addView(sunView);
}
else if(dayCode == 39){
dayView.addView(cloudHvRainView);
}
else if(dayCode == 44 || dayCode == 26){
dayView.addView(cloudView);
}
SimpleDateFormat expectedDateFormat = new SimpleDateFormat("EEE, MMM d, ''yy");
// set yahoo data information
cityText.setText(response.body().getQuery().getResults().getChannel().getLocation().getCity() + "," + response.body().getQuery().getResults().getChannel().getLocation().getCountry());
condDescr.setText(response.body().getQuery().getResults().getChannel().getItem().getCondition().getText());
dayDateText.setText(expectedDateFormat.format(createdDate));
temp.setText("" + UnitUtility.toCelcius(Float.parseFloat(response.body().getQuery().getResults().getChannel().getItem().getCondition().getTemp())));
unitTemp.setText(UnitUtility.tempUnit(response.body().getQuery().getResults().getChannel().getUnits().getTemperature()));
visibility.setText(response.body().getQuery().getResults().getChannel().getAtmosphere().getVisibility() + response.body().getQuery().getResults().getChannel().getUnits().getDistance());
hum.setText(response.body().getQuery().getResults().getChannel().getAtmosphere().getHumidity() + "%");
windSpeed.setText(Float.parseFloat(response.body().getQuery().getResults().getChannel().getWind().getSpeed()) + UnitUtility.speedUnit(response.body().getQuery().getResults().getChannel().getUnits().getSpeed()));
press.setText(response.body().getQuery().getResults().getChannel().getAtmosphere().getPressure() + response.body().getQuery().getResults().getChannel().getUnits().getPressure());
sunrise.setText(response.body().getQuery().getResults().getChannel().getAstronomy().getSunrise());
sunset.setText(response.body().getQuery().getResults().getChannel().getAstronomy().getSunset());
if(key_progressbar!=null)
{
key_progressbar.cancel();
}
}else{
}
}
@Override
public void onFailure(Call<Root> call, Throwable t) {
if(key_progressbar!=null)
{
key_progressbar.cancel();
}
//in case request not failure
Toast.makeText(context, getString(R.string.serverfailure), Toast.LENGTH_LONG).show();
t.printStackTrace();
}
});
}
}
|
UTF-8
|
Java
| 12,671 |
java
|
HomeFragment.java
|
Java
|
[
{
"context": ".List;\n\nimport retrofit2.Call;\n\n\n/**\n * Created by vikrant on 01/6/16.\n */\n\n// This class display Current da",
"end": 1217,
"score": 0.9994499683380127,
"start": 1210,
"tag": "USERNAME",
"value": "vikrant"
}
] | null |
[] |
package com.showers.main;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.showers.R;
import com.showers.model.ViewModel;
import com.showers.restModel.Root;
import com.showers.restclient.RestClient;
import com.showers.utility.MyUtility;
import com.showers.utility.Progressdialog;
import com.showers.utility.UnitUtility;
import com.thbs.skycons.library.CloudHvRainView;
import com.thbs.skycons.library.CloudMoonView;
import com.thbs.skycons.library.CloudRainView;
import com.thbs.skycons.library.CloudSunView;
import com.thbs.skycons.library.CloudThunderView;
import com.thbs.skycons.library.CloudView;
import com.thbs.skycons.library.MoonView;
import com.thbs.skycons.library.SkyconView;
import com.thbs.skycons.library.SunView;
import com.thbs.skycons.library.WindView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import retrofit2.Call;
/**
* Created by vikrant on 01/6/16.
*/
// This class display Current date weather information
public class HomeFragment extends Fragment{
private SimpleDateFormat srcFormatter=new SimpleDateFormat("yyyy-MM-dd");
private static List<ViewModel> items = new ArrayList<>();
private Context context;
private View root;
private Progressdialog key_progressbar;
// Declare UI elements
private TextView cityText, dayDateText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView unitTemp;
private TextView visibility;
private TextView hum;
private TextView sunset;
private TextView sunrise;
private LinearLayout dayView;
private LinearLayout mainView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
root = (View) inflater.inflate(R.layout.content_main, null);
context = getActivity();
mainView = (LinearLayout) root.findViewById(R.id.mainView);
dayView = (LinearLayout) root.findViewById(R.id.dayView);
dayDateText = (TextView) root.findViewById(R.id.dayDate);
cityText = (TextView) root.findViewById(R.id.location);
temp = (TextView) root.findViewById(R.id.temp);
condDescr = (TextView) root.findViewById(R.id.descrWeather);
hum = (TextView) root.findViewById(R.id.humidity);
press = (TextView) root.findViewById(R.id.pressure);
windSpeed = (TextView) root.findViewById(R.id.windSpeed);
windDeg = (TextView) root.findViewById(R.id.windDeg);
unitTemp = (TextView) root.findViewById(R.id.tempUnit);
visibility = (TextView) root.findViewById(R.id.visibility);
sunrise = (TextView) root.findViewById(R.id.sunrise);
sunset = (TextView) root.findViewById(R.id.sunset);
// check internet connection
if(MyUtility.isConnected(context)) {
//initialize progress dialog
key_progressbar = (Progressdialog) Progressdialog.show(context);
// this function get all json data from yahoo api and use current information
getCurrentWeatherUpdates();
}
else
Toast.makeText(context, getString(R.string.internetconnection), Toast.LENGTH_LONG).show();
return root;
}
private void getCurrentWeatherUpdates() {
RestClient.RestInterface service = RestClient.getClient(getActivity());
Call<Root> call = service.getYahooWeather();
call.enqueue(new retrofit2.Callback<Root>() {
@Override
public void onResponse(Call<Root> call, retrofit2.Response<Root> response) {
if (response != null && response.isSuccessful() && response.errorBody() == null){
Date createdDate = null;
try {
//get created date
createdDate = srcFormatter.parse(response.body().getQuery().getCreated());
} catch (ParseException ex) {
ex.printStackTrace();
}
// create object of Skycons library
SunView sunView = new SunView(context);
MoonView moonView = new MoonView(context);
SkyconView skyconView = new SkyconView(context);
CloudThunderView thunderView = new CloudThunderView(context);
CloudRainView cloudRainView = new CloudRainView(context);
CloudHvRainView cloudHvRainView = new CloudHvRainView(context);
CloudMoonView cloudMoonView = new CloudMoonView(context);
CloudSunView cloudSunView = new CloudSunView(context);
CloudView cloudView = new CloudView(context);
WindView windView = new WindView(context);
// change background of icons
sunView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudHvRainView.setBgColor(context.getResources().getColor(android.R.color.transparent));
skyconView.setBgColor(context.getResources().getColor(android.R.color.transparent));
moonView.setBgColor(context.getResources().getColor(android.R.color.transparent));
thunderView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudRainView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudMoonView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudSunView.setBgColor(context.getResources().getColor(android.R.color.transparent));
cloudView.setBgColor(context.getResources().getColor(android.R.color.transparent));
windView.setBgColor(context.getResources().getColor(android.R.color.transparent));
LinearLayout layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
int dayCode = Integer.parseInt(response.body().getQuery().getResults().getChannel().getItem().getCondition().getCode());
// get current sdk version
final int sdk = android.os.Build.VERSION.SDK_INT;
// in these statement change background image according with current weather
if(dayCode == 27 || dayCode == 29){
//mostly cloudy (night)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.rainview) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.rainview));
}
}else if(dayCode == 28 || dayCode == 30){
//mostly cloudy (day)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.sunny) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.sunny));
}
}
else if(dayCode == 31 || dayCode == 33){
//clear (night)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.clearnight) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.clearnight));
}
}
else if(dayCode == 32 || dayCode == 34){
//fair (day)
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
mainView.setBackgroundDrawable( getResources().getDrawable(R.drawable.cleanweather) );
} else {
mainView.setBackground( getResources().getDrawable(R.drawable.cleanweather));
}
}
// here we can change icon of current weather using yahoo api code
if(dayCode == 4 || dayCode == 47){
dayView.addView(thunderView);
}
else if(dayCode == 11 || dayCode == 12){
dayView.addView(cloudRainView);
}
else if(dayCode == 23){
dayView.addView(windView);
}
else if(dayCode == 29){
dayView.addView(cloudMoonView);
}
else if(dayCode == 28 || dayCode == 30){
dayView.addView(cloudSunView);
}else if(dayCode == 27 || dayCode == 31 || dayCode == 33){
moonView.setStrokeColor(getResources().getColor(R.color.color_white));
dayView.addView(moonView);
}
else if(dayCode == 32 || dayCode == 34){
dayView.addView(sunView);
}
else if(dayCode == 39){
dayView.addView(cloudHvRainView);
}
else if(dayCode == 44 || dayCode == 26){
dayView.addView(cloudView);
}
SimpleDateFormat expectedDateFormat = new SimpleDateFormat("EEE, MMM d, ''yy");
// set yahoo data information
cityText.setText(response.body().getQuery().getResults().getChannel().getLocation().getCity() + "," + response.body().getQuery().getResults().getChannel().getLocation().getCountry());
condDescr.setText(response.body().getQuery().getResults().getChannel().getItem().getCondition().getText());
dayDateText.setText(expectedDateFormat.format(createdDate));
temp.setText("" + UnitUtility.toCelcius(Float.parseFloat(response.body().getQuery().getResults().getChannel().getItem().getCondition().getTemp())));
unitTemp.setText(UnitUtility.tempUnit(response.body().getQuery().getResults().getChannel().getUnits().getTemperature()));
visibility.setText(response.body().getQuery().getResults().getChannel().getAtmosphere().getVisibility() + response.body().getQuery().getResults().getChannel().getUnits().getDistance());
hum.setText(response.body().getQuery().getResults().getChannel().getAtmosphere().getHumidity() + "%");
windSpeed.setText(Float.parseFloat(response.body().getQuery().getResults().getChannel().getWind().getSpeed()) + UnitUtility.speedUnit(response.body().getQuery().getResults().getChannel().getUnits().getSpeed()));
press.setText(response.body().getQuery().getResults().getChannel().getAtmosphere().getPressure() + response.body().getQuery().getResults().getChannel().getUnits().getPressure());
sunrise.setText(response.body().getQuery().getResults().getChannel().getAstronomy().getSunrise());
sunset.setText(response.body().getQuery().getResults().getChannel().getAstronomy().getSunset());
if(key_progressbar!=null)
{
key_progressbar.cancel();
}
}else{
}
}
@Override
public void onFailure(Call<Root> call, Throwable t) {
if(key_progressbar!=null)
{
key_progressbar.cancel();
}
//in case request not failure
Toast.makeText(context, getString(R.string.serverfailure), Toast.LENGTH_LONG).show();
t.printStackTrace();
}
});
}
}
| 12,671 | 0.592613 | 0.588194 | 245 | 50.718369 | 38.913383 | 231 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.702041 | false | false |
0
|
a73582aaa7a04d1f8a070eaa7d0312ead8e46754
| 29,875,792,559,913 |
134efc5deecb03372b8292326939c0f1dcbd2767
|
/src/main/java/com/pis/referralportal/service/CustomEmployeeDetailsService.java
|
39f08326172c970261efb09e6f951d2282216d0c
|
[] |
no_license
|
Ankitrana1/referral-portal
|
https://github.com/Ankitrana1/referral-portal
|
e9df31965c62c62ab06d3310b3c49cdf88bc6029
|
2c5c0c1201177b8170bceba2966ad323a9253b7b
|
refs/heads/main
| 2023-02-22T00:53:16.798000 | 2021-01-22T15:10:00 | 2021-01-22T15:10:00 | 331,975,890 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pis.referralportal.service;
import com.pis.referralportal.model.Employee;
import com.pis.referralportal.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class CustomEmployeeDetailsService implements UserDetailsService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Employee employee = employeeRepository.findByEmail(email);
return new User(employee.getEmail(), employee.getPassword(), new ArrayList<>());
}
}
|
UTF-8
|
Java
| 986 |
java
|
CustomEmployeeDetailsService.java
|
Java
|
[] | null |
[] |
package com.pis.referralportal.service;
import com.pis.referralportal.model.Employee;
import com.pis.referralportal.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class CustomEmployeeDetailsService implements UserDetailsService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Employee employee = employeeRepository.findByEmail(email);
return new User(employee.getEmail(), employee.getPassword(), new ArrayList<>());
}
}
| 986 | 0.824544 | 0.824544 | 25 | 38.439999 | 31.235979 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
0
|
9fe4d30d44ddf4d089c7b6f2c912d778454a3aeb
| 32,744,830,714,809 |
9648ce494416c3b31d0d373acb7a44d5fca99b3c
|
/app/src/main/java/controller/CustomListViewAdapter.java
|
c40729cb2cf09c33a1997b3820e60926338fb9a3
|
[] |
no_license
|
MatanTespay/HW1App
|
https://github.com/MatanTespay/HW1App
|
83a7056e0d98be73489eeba870ebf1c3258e5773
|
2e039bea40d4d3fd810cd60f4057e0da6772e254
|
refs/heads/master
| 2021-01-12T02:47:42.955000 | 2017-01-07T21:47:41 | 2017-01-07T21:47:41 | 78,105,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package controller;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.matan.hw1app.R;
import java.util.ArrayList;
import java.util.List;
import model.Place;
import utils.HelperClass;
import utils.RoundedImageView;
import static android.R.attr.resource;
import static android.R.id.list;
/**
* custom list adapter to populate the list items in viewlist object
* Created by Matan on 24/11/2016.
*/
public class CustomListViewAdapter extends ArrayAdapter<Place> implements CompoundButton.OnCheckedChangeListener {
private LayoutInflater mLayoutInflater;
private List<Place> items = null;
private Activity context = null;
private SparseBooleanArray mCheckStates;
private boolean edit = false;
HelperClass h;
private static final String FRAG_TAG = "place_info_frag";
/**
* ctor of the class
* @param context
* @param items
*/
/**
*
* @param context the class context
* @param resource the layout of row
* @param objects the items to populate in the view
*/
public CustomListViewAdapter(Context context, int resource, List<Place> objects, boolean edit ) {
super(context, resource, objects);
this.items = objects;
this.context = (Activity)context;
mCheckStates = new SparseBooleanArray(items.size());
this.edit = edit;
mLayoutInflater = LayoutInflater.from(context);
}
/**
*
* @return the size of the list items
*/
public int getItemCount() {
return items.size();
}
/**
* get adapter select items count
* @return
*/
public int getSelectedCount(){
int c = 0;
for(int i=0;i<getCount();i++)
{
if(mCheckStates.get(i)==true)
{
c++;
}
}
return c;
}
public List<Place> getSelectedItems(){
List<Place> list = new ArrayList<Place>();
for(int i=0;i<getCount();i++)
{
if(mCheckStates.get(i)==true)
{
Place p = getItem(i);
list.add(p);
}
}
return list;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
private class ViewContainer {
TextView title;
TextView description;
CheckBox chkSelect;
ImageView bImg;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer holder = null;
Place placeItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.itemlayout, null);
holder = new ViewContainer();
holder.title = (TextView) convertView.findViewById(R.id.name);
holder.description = (TextView) convertView.findViewById(R.id.description);
holder.chkSelect = (CheckBox) convertView.findViewById(R.id.item_chk);
holder.bImg = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else{
holder = (ViewContainer) convertView.getTag();
}
if (edit) {
holder.chkSelect.setVisibility(View.VISIBLE);
} else {
holder.chkSelect.setVisibility(View.GONE);
}
holder.title.setText(placeItem.getName());
holder.description.setText(placeItem.getDescription());
holder.chkSelect.setTag(position);
holder.chkSelect.setChecked(mCheckStates.get(position, false));
holder.chkSelect.setOnCheckedChangeListener(this);
if(placeItem.getImgData() != null){
Bitmap rouderBitmap = RoundedImageView.getCroppedBitmap(placeItem.getImgData(),300);
holder.bImg.setImageBitmap(rouderBitmap);
}
return convertView;
/*
LayoutInflater inflater=context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.itemlayout, null,true);
TextView txtName = (TextView) rowView.findViewById(R.id.name);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView txtDesc = (TextView) rowView.findViewById(R.id.description);
Place item = items.get(position);
txtName.setText(item.getName());
if(item.getImgData() != null)
imageView.setImageBitmap(item.getImgData());
txtDesc.setText(item.getDescription());
return rowView;*/
}
public Place getPlaceById(Long id){
for (Place p: items) {
if(p.getId().equals(id))
return p;
}
return null;
}
public List<Place> getItems() {
return items;
}
}
|
UTF-8
|
Java
| 5,499 |
java
|
CustomListViewAdapter.java
|
Java
|
[
{
"context": "te the list items in viewlist object\n * Created by Matan on 24/11/2016.\n */\n\npublic class CustomListViewAd",
"end": 974,
"score": 0.9994835257530212,
"start": 969,
"tag": "NAME",
"value": "Matan"
}
] | null |
[] |
package controller;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.matan.hw1app.R;
import java.util.ArrayList;
import java.util.List;
import model.Place;
import utils.HelperClass;
import utils.RoundedImageView;
import static android.R.attr.resource;
import static android.R.id.list;
/**
* custom list adapter to populate the list items in viewlist object
* Created by Matan on 24/11/2016.
*/
public class CustomListViewAdapter extends ArrayAdapter<Place> implements CompoundButton.OnCheckedChangeListener {
private LayoutInflater mLayoutInflater;
private List<Place> items = null;
private Activity context = null;
private SparseBooleanArray mCheckStates;
private boolean edit = false;
HelperClass h;
private static final String FRAG_TAG = "place_info_frag";
/**
* ctor of the class
* @param context
* @param items
*/
/**
*
* @param context the class context
* @param resource the layout of row
* @param objects the items to populate in the view
*/
public CustomListViewAdapter(Context context, int resource, List<Place> objects, boolean edit ) {
super(context, resource, objects);
this.items = objects;
this.context = (Activity)context;
mCheckStates = new SparseBooleanArray(items.size());
this.edit = edit;
mLayoutInflater = LayoutInflater.from(context);
}
/**
*
* @return the size of the list items
*/
public int getItemCount() {
return items.size();
}
/**
* get adapter select items count
* @return
*/
public int getSelectedCount(){
int c = 0;
for(int i=0;i<getCount();i++)
{
if(mCheckStates.get(i)==true)
{
c++;
}
}
return c;
}
public List<Place> getSelectedItems(){
List<Place> list = new ArrayList<Place>();
for(int i=0;i<getCount();i++)
{
if(mCheckStates.get(i)==true)
{
Place p = getItem(i);
list.add(p);
}
}
return list;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
private class ViewContainer {
TextView title;
TextView description;
CheckBox chkSelect;
ImageView bImg;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer holder = null;
Place placeItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.itemlayout, null);
holder = new ViewContainer();
holder.title = (TextView) convertView.findViewById(R.id.name);
holder.description = (TextView) convertView.findViewById(R.id.description);
holder.chkSelect = (CheckBox) convertView.findViewById(R.id.item_chk);
holder.bImg = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else{
holder = (ViewContainer) convertView.getTag();
}
if (edit) {
holder.chkSelect.setVisibility(View.VISIBLE);
} else {
holder.chkSelect.setVisibility(View.GONE);
}
holder.title.setText(placeItem.getName());
holder.description.setText(placeItem.getDescription());
holder.chkSelect.setTag(position);
holder.chkSelect.setChecked(mCheckStates.get(position, false));
holder.chkSelect.setOnCheckedChangeListener(this);
if(placeItem.getImgData() != null){
Bitmap rouderBitmap = RoundedImageView.getCroppedBitmap(placeItem.getImgData(),300);
holder.bImg.setImageBitmap(rouderBitmap);
}
return convertView;
/*
LayoutInflater inflater=context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.itemlayout, null,true);
TextView txtName = (TextView) rowView.findViewById(R.id.name);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView txtDesc = (TextView) rowView.findViewById(R.id.description);
Place item = items.get(position);
txtName.setText(item.getName());
if(item.getImgData() != null)
imageView.setImageBitmap(item.getImgData());
txtDesc.setText(item.getDescription());
return rowView;*/
}
public Place getPlaceById(Long id){
for (Place p: items) {
if(p.getId().equals(id))
return p;
}
return null;
}
public List<Place> getItems() {
return items;
}
}
| 5,499 | 0.641753 | 0.638662 | 193 | 27.487047 | 24.751429 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544041 | false | false |
0
|
7d7c7fcd85832e8afd3ed075f235c085a67adbb9
| 10,608,569,267,399 |
2a03fc16fd10bfbde4cee277256f50d6e97b5144
|
/day14/javaContinue.java
|
c3efe70376ed859fe7343428f7086eadbb8610f5
|
[] |
no_license
|
vepailjanov/gitfile
|
https://github.com/vepailjanov/gitfile
|
cbcc7f27613e4fb3726924ad353d7779883e080b
|
28f6dec6fabb435de4d7b2b31afdba8ef96d3ce8
|
refs/heads/master
| 2022-08-24T16:26:58.328000 | 2020-05-26T17:35:41 | 2020-05-26T17:35:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package day14;
public class javaContinue {
public static void main(String[] args) {
String str = "Stay home";
for (int i = 0; i <str.length(); i++){
char letter = str.charAt(i);
if (letter == ' ' || letter == 'a'){
continue;
}
System.out.println(letter);
}
}
}
|
UTF-8
|
Java
| 358 |
java
|
javaContinue.java
|
Java
|
[] | null |
[] |
package day14;
public class javaContinue {
public static void main(String[] args) {
String str = "Stay home";
for (int i = 0; i <str.length(); i++){
char letter = str.charAt(i);
if (letter == ' ' || letter == 'a'){
continue;
}
System.out.println(letter);
}
}
}
| 358 | 0.463687 | 0.455307 | 14 | 24.571428 | 16.774616 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false |
0
|
ccf1777b0aa70634a75953fceb873c79ad5ead23
| 39,384,850,132,925 |
fa76ac8eab0baec024ae1b3abc6f0a253ab036b4
|
/src/main/contract/entity/Contract.java
|
543faef63f1437a02e0bb34d45f4675d32579181
|
[] |
no_license
|
ARc2678/ContractMaster
|
https://github.com/ARc2678/ContractMaster
|
2ebda842a1d2274e366b588a3e7bbd91ed1d17c6
|
49d431610ce84043d2619aab6bca7c40712a66e4
|
refs/heads/master
| 2021-01-21T14:32:13.056000 | 2017-06-24T11:21:29 | 2017-06-24T11:21:29 | 95,292,688 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main.contract.entity;
/**
* Created by AR c on 2017/6/24.
*/
import java.io.Serializable;
import java.util.Date;
public class Contract implements Serializable
{
private static final long serialVersionUID = 351953605173085300L;
private long cid;
private String ctype;
private long uid;
private Date date_start;
private Date date_end;
private long contract_length;
private long trail_length;
private int hand_book_exist;
public long getCid()
{
return cid;
}
public void setCid(long cid)
{
this.cid = cid;
}
public String getCtype()
{
return ctype;
}
public void setCtype(String ctype)
{
this.ctype = ctype;
}
public long getUid()
{
return uid;
}
public void setUid(long uid)
{
this.uid = uid;
}
public Date getDate_start()
{
return date_start;
}
public void setDate_start(Date date_start)
{
this.date_start = date_start;
}
public Date getDate_end()
{
return date_end;
}
public void setDate_end(Date date_end)
{
this.date_end = date_end;
}
public long getContract_length()
{
return contract_length;
}
public void setContract_length(long contract_length)
{
this.contract_length = contract_length;
}
public long getTrail_length()
{
return trail_length;
}
public void setTrail_length(long trail_length)
{
this.trail_length = trail_length;
}
public int getHand_book_exist()
{
return hand_book_exist;
}
public void setHand_book_exist(int hand_book_exist)
{
this.hand_book_exist = hand_book_exist;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
}
|
UTF-8
|
Java
| 1,868 |
java
|
Contract.java
|
Java
|
[
{
"context": "package main.contract.entity;\n\n/**\n * Created by AR c on 2017/6/24.\n */\nimport java.io.Serializable;\nim",
"end": 53,
"score": 0.6665112972259521,
"start": 49,
"tag": "NAME",
"value": "AR c"
}
] | null |
[] |
package main.contract.entity;
/**
* Created by <NAME> on 2017/6/24.
*/
import java.io.Serializable;
import java.util.Date;
public class Contract implements Serializable
{
private static final long serialVersionUID = 351953605173085300L;
private long cid;
private String ctype;
private long uid;
private Date date_start;
private Date date_end;
private long contract_length;
private long trail_length;
private int hand_book_exist;
public long getCid()
{
return cid;
}
public void setCid(long cid)
{
this.cid = cid;
}
public String getCtype()
{
return ctype;
}
public void setCtype(String ctype)
{
this.ctype = ctype;
}
public long getUid()
{
return uid;
}
public void setUid(long uid)
{
this.uid = uid;
}
public Date getDate_start()
{
return date_start;
}
public void setDate_start(Date date_start)
{
this.date_start = date_start;
}
public Date getDate_end()
{
return date_end;
}
public void setDate_end(Date date_end)
{
this.date_end = date_end;
}
public long getContract_length()
{
return contract_length;
}
public void setContract_length(long contract_length)
{
this.contract_length = contract_length;
}
public long getTrail_length()
{
return trail_length;
}
public void setTrail_length(long trail_length)
{
this.trail_length = trail_length;
}
public int getHand_book_exist()
{
return hand_book_exist;
}
public void setHand_book_exist(int hand_book_exist)
{
this.hand_book_exist = hand_book_exist;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
}
| 1,870 | 0.593683 | 0.5803 | 106 | 16.632076 | 16.612297 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.273585 | false | false |
0
|
6a0a4540012799ad92a1aadd1901002cf3f5f7ff
| 29,626,684,475,633 |
620b8f17cfc47f44ec561f1740108417533ff32d
|
/Workbench/src/main/java/me/zhang/coreJava/gui/BorderLayoutTest.java
|
e58355da1e70393cb446d123fb3f39e0f2334b4a
|
[] |
no_license
|
clsio/JavaLab
|
https://github.com/clsio/JavaLab
|
62d58323495f3fbc907102a90d4e383f2c30f009
|
40ac6a266df9fc03769ee8f2c7c8b5437b908a9d
|
refs/heads/master
| 2020-12-25T15:09:19.141000 | 2018-06-17T10:46:15 | 2018-06-17T10:46:15 | 67,870,552 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package me.zhang.coreJava.gui;
import javax.swing.*;
import java.awt.*;
/**
* Created by zhangxiangdong on 2017/10/30.
*/
public class BorderLayoutTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 200));
JPanel panel = new JPanel();
panel.add(new JButton("Alpha"));
panel.add(new JButton("Beta"));
panel.add(new JButton("Gamma"));
JTextArea area = new JTextArea("Hello, world!");
// BorderLayout is the default layout of JFrame
frame.add(panel, BorderLayout.SOUTH);
frame.add(area, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
}
|
UTF-8
|
Java
| 950 |
java
|
BorderLayoutTest.java
|
Java
|
[
{
"context": "vax.swing.*;\nimport java.awt.*;\n\n/**\n * Created by zhangxiangdong on 2017/10/30.\n */\npublic class BorderLayoutTest ",
"end": 106,
"score": 0.9664861559867859,
"start": 92,
"tag": "USERNAME",
"value": "zhangxiangdong"
}
] | null |
[] |
package me.zhang.coreJava.gui;
import javax.swing.*;
import java.awt.*;
/**
* Created by zhangxiangdong on 2017/10/30.
*/
public class BorderLayoutTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 200));
JPanel panel = new JPanel();
panel.add(new JButton("Alpha"));
panel.add(new JButton("Beta"));
panel.add(new JButton("Gamma"));
JTextArea area = new JTextArea("Hello, world!");
// BorderLayout is the default layout of JFrame
frame.add(panel, BorderLayout.SOUTH);
frame.add(area, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
}
| 950 | 0.587368 | 0.572632 | 34 | 26.941177 | 22.483904 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false |
0
|
16582360a7970bbeec4bf4ca49ed29757e573e87
| 3,118,146,320,070 |
59130660503e8ba8cf7d055d6c72afc4c6017ab9
|
/src/DBMS/queryProcessing/queryEngine/planEngine/planOperations/selectCommands/SelectionOperation.java
|
96715419c8b3afc36431d7211f7d98df697ad545
|
[] |
no_license
|
alyssonchicoh/SEAL-DB
|
https://github.com/alyssonchicoh/SEAL-DB
|
d6b0fa75d6dbd2d237ae6e3f772d6a0015c1708d
|
004d7efaad19a2df54b40dbedb7b1fbc35766a20
|
refs/heads/master
| 2020-05-04T17:42:27.946000 | 2019-04-03T16:03:42 | 2019-04-03T16:03:42 | 179,323,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package DBMS.queryProcessing.queryEngine.planEngine.planOperations.selectCommands;
import DBMS.fileManager.Column;
import DBMS.queryProcessing.ITable;
import DBMS.queryProcessing.ITuple;
import DBMS.queryProcessing.queryEngine.InteratorsAlgorithms.TableScan;
import DBMS.queryProcessing.queryEngine.planEngine.Condition;
import DBMS.queryProcessing.queryEngine.planEngine.planOperations.AbstractPlanOperation;
import DBMS.transactionManager.ITransaction;
public class SelectionOperation extends AbstractPlanOperation{
protected void executeOperation(ITable resultTable) {
ITransaction transaction = super.getPlan().getTransaction();
boolean isInsertable = false;
TableScan tableScan = new TableScan(transaction, resultLeft);
ITuple tuple = tableScan.nextTuple();
while(tuple!=null){
isInsertable = false;
for (Condition aOv : attributesOperatorsValues) {
if(super.makeComparison(tuple.getColunmData(resultLeft.getIdColumn(aOv.getAtribute())), aOv.getOperator(), aOv.getValue())){
isInsertable = true;
}else{
isInsertable = false;
break;
}
}
if(isInsertable || attributesOperatorsValues.isEmpty()){
resultTable.writeTuple(transaction,tuple.getStringData());
}
tuple = tableScan.nextTuple();
}
}
public Column[] getResultTupleStruct(){
return resultLeft.getColumns();
}
}
|
UTF-8
|
Java
| 1,388 |
java
|
SelectionOperation.java
|
Java
|
[] | null |
[] |
package DBMS.queryProcessing.queryEngine.planEngine.planOperations.selectCommands;
import DBMS.fileManager.Column;
import DBMS.queryProcessing.ITable;
import DBMS.queryProcessing.ITuple;
import DBMS.queryProcessing.queryEngine.InteratorsAlgorithms.TableScan;
import DBMS.queryProcessing.queryEngine.planEngine.Condition;
import DBMS.queryProcessing.queryEngine.planEngine.planOperations.AbstractPlanOperation;
import DBMS.transactionManager.ITransaction;
public class SelectionOperation extends AbstractPlanOperation{
protected void executeOperation(ITable resultTable) {
ITransaction transaction = super.getPlan().getTransaction();
boolean isInsertable = false;
TableScan tableScan = new TableScan(transaction, resultLeft);
ITuple tuple = tableScan.nextTuple();
while(tuple!=null){
isInsertable = false;
for (Condition aOv : attributesOperatorsValues) {
if(super.makeComparison(tuple.getColunmData(resultLeft.getIdColumn(aOv.getAtribute())), aOv.getOperator(), aOv.getValue())){
isInsertable = true;
}else{
isInsertable = false;
break;
}
}
if(isInsertable || attributesOperatorsValues.isEmpty()){
resultTable.writeTuple(transaction,tuple.getStringData());
}
tuple = tableScan.nextTuple();
}
}
public Column[] getResultTupleStruct(){
return resultLeft.getColumns();
}
}
| 1,388 | 0.756484 | 0.756484 | 53 | 25.188679 | 29.103624 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.339623 | false | false |
0
|
572efaba7c41334057737ebe61decb252c47ca70
| 12,927,851,563,472 |
8073d5d92aa88c59da4d2453c93a3c3f8ca4ea79
|
/app/src/main/java/com/jifan/actv/DevListActivity.java
|
1f78fc3ced11be6c47d1a90e1db1d706eb59760c
|
[] |
no_license
|
bingoiot/smarthome-sdk-demo-android
|
https://github.com/bingoiot/smarthome-sdk-demo-android
|
0992ed620c4b75ed6b4466353ef090fa9281212b
|
38e13f359ffe76b6e3c8e18e4408852258fe16e2
|
refs/heads/master
| 2020-04-25T03:31:17.173000 | 2019-06-03T01:45:27 | 2019-06-03T01:45:27 | 172,479,607 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jifan.actv;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import com.jifan.Config;
import com.jifan.model.aid_value;
import com.jifan.model.dev_hardware;
import com.jifan.model.dev_port;
import com.jifan.utils.Adapter_dev_GridView;
import com.jifan.utils.ControlHelper;
import com.jifan.utils.DevManage;
import com.jifan.utils.MyGridView;
import com.jifan.utils.UIHelper;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pluto.Aps;
import pluto.AttributeID;
import pluto.Clib;
import pluto.Common;
import pluto.Pluto;
public class DevListActivity extends BaseActivity {
@ViewInject(R.id.gv_dev)
MyGridView gv_dev;
private Adapter_dev_GridView adapterDevGridView;
List<dev_port> deviceportlist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_list);
init();
}
void init()
{
x.view().inject(this);
List<dev_hardware> all = app.getDevList();
if(!(all!=null&&all.size()>0))
{
ShowTost("请先添加设备");
this.finish();
return;
}
deviceportlist=new ArrayList<>();
for (dev_hardware dev :all)
{
deviceportlist.addAll(dev.getDev_portList());
}
deviceportlist = UIHelper.InitDevportIcon( deviceportlist, app.getSeedList());//端口初始化 图标等
adapterDevGridView=new Adapter_dev_GridView(currentcontext,deviceportlist);
gv_dev.setAdapter(adapterDevGridView);
gv_dev.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
dev_port item = deviceportlist.get(position);
ControlHelper.clickDevPort(currentcontext, item, deviceportlist);//点击 发送数据
}
});
gv_dev.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {//长按进入编辑页
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
dev_port item = deviceportlist.get(position);
ControlHelper.longclickDevPort(currentcontext, item);
return true;
}//设置事件监听(长按)
});
myHandler = new Handler(currentcontext.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case 1:// 更新数据
adapterDevGridView.notifyDataSetChanged();
break;
}
}
};
Setlisen();
SendReadDevStat();
}
/**
* 设备状态监听
*/
void Setlisen() {
Aps.setSectionListener(AttributeID.Gen_Key.Value,AttributeID.Unkown , new Aps.onSectionListener() {
@Override
public void RecieveCB(int keyID, byte[] src, int seq, int port, int aID, int cmd, int option, byte[] pdata, int len) {//收到设备状态
int aid_dev_type = 0;
for (dev_port item : deviceportlist) {
if (Arrays.equals(item.getDevAddr(), src) && port == item.getPort()) {
List<aid_value> list = item.getAid_valueList();
for (aid_value av : list) {
if (av.getAid() == aID) {
av.setValues(Clib.bytes2Hex(pdata, '\0'));
break;
}
}
item.setAid_valueList(list);
break;
}
}
myHandler.sendEmptyMessage(1);//刷新listview
}
@Override
public void SendStatus(byte[] src,int seq,int port, int aID, int cmd,int option, int state) {
}
});
Pluto.setOnLoginStateListener(new Pluto.onLoginStateListener() {//登录状态 监听
@Override
public void recieve(int state) {
/* dev_stopLogin,//停止=0
dev_startLogin,//开始登录 =1
dev_online,//登录成功,在线=2
dev_offline,//离线=3
dev_loginFailed,//登录失败=4
dev_logoutFailed,//退出登录失败=5
*/
if (state == 2) {
if (!Config.JifanIsLogin) {
Config.JifanIsLogin = true;
SendReadDevStat();//登录后,读取设备状态
}
}
}
});
}
//发送读取设备状态
void SendReadDevStat() {
if (deviceportlist!= null)
for (dev_port devPort : deviceportlist) {
ControlHelper.SendDataRead(devPort);//发送读的状态
}
}
}
|
UTF-8
|
Java
| 5,194 |
java
|
DevListActivity.java
|
Java
|
[] | null |
[] |
package com.jifan.actv;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import com.jifan.Config;
import com.jifan.model.aid_value;
import com.jifan.model.dev_hardware;
import com.jifan.model.dev_port;
import com.jifan.utils.Adapter_dev_GridView;
import com.jifan.utils.ControlHelper;
import com.jifan.utils.DevManage;
import com.jifan.utils.MyGridView;
import com.jifan.utils.UIHelper;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pluto.Aps;
import pluto.AttributeID;
import pluto.Clib;
import pluto.Common;
import pluto.Pluto;
public class DevListActivity extends BaseActivity {
@ViewInject(R.id.gv_dev)
MyGridView gv_dev;
private Adapter_dev_GridView adapterDevGridView;
List<dev_port> deviceportlist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_list);
init();
}
void init()
{
x.view().inject(this);
List<dev_hardware> all = app.getDevList();
if(!(all!=null&&all.size()>0))
{
ShowTost("请先添加设备");
this.finish();
return;
}
deviceportlist=new ArrayList<>();
for (dev_hardware dev :all)
{
deviceportlist.addAll(dev.getDev_portList());
}
deviceportlist = UIHelper.InitDevportIcon( deviceportlist, app.getSeedList());//端口初始化 图标等
adapterDevGridView=new Adapter_dev_GridView(currentcontext,deviceportlist);
gv_dev.setAdapter(adapterDevGridView);
gv_dev.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
dev_port item = deviceportlist.get(position);
ControlHelper.clickDevPort(currentcontext, item, deviceportlist);//点击 发送数据
}
});
gv_dev.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {//长按进入编辑页
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
dev_port item = deviceportlist.get(position);
ControlHelper.longclickDevPort(currentcontext, item);
return true;
}//设置事件监听(长按)
});
myHandler = new Handler(currentcontext.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case 1:// 更新数据
adapterDevGridView.notifyDataSetChanged();
break;
}
}
};
Setlisen();
SendReadDevStat();
}
/**
* 设备状态监听
*/
void Setlisen() {
Aps.setSectionListener(AttributeID.Gen_Key.Value,AttributeID.Unkown , new Aps.onSectionListener() {
@Override
public void RecieveCB(int keyID, byte[] src, int seq, int port, int aID, int cmd, int option, byte[] pdata, int len) {//收到设备状态
int aid_dev_type = 0;
for (dev_port item : deviceportlist) {
if (Arrays.equals(item.getDevAddr(), src) && port == item.getPort()) {
List<aid_value> list = item.getAid_valueList();
for (aid_value av : list) {
if (av.getAid() == aID) {
av.setValues(Clib.bytes2Hex(pdata, '\0'));
break;
}
}
item.setAid_valueList(list);
break;
}
}
myHandler.sendEmptyMessage(1);//刷新listview
}
@Override
public void SendStatus(byte[] src,int seq,int port, int aID, int cmd,int option, int state) {
}
});
Pluto.setOnLoginStateListener(new Pluto.onLoginStateListener() {//登录状态 监听
@Override
public void recieve(int state) {
/* dev_stopLogin,//停止=0
dev_startLogin,//开始登录 =1
dev_online,//登录成功,在线=2
dev_offline,//离线=3
dev_loginFailed,//登录失败=4
dev_logoutFailed,//退出登录失败=5
*/
if (state == 2) {
if (!Config.JifanIsLogin) {
Config.JifanIsLogin = true;
SendReadDevStat();//登录后,读取设备状态
}
}
}
});
}
//发送读取设备状态
void SendReadDevStat() {
if (deviceportlist!= null)
for (dev_port devPort : deviceportlist) {
ControlHelper.SendDataRead(devPort);//发送读的状态
}
}
}
| 5,194 | 0.574126 | 0.570711 | 162 | 29.728395 | 26.255869 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false |
0
|
b6c1e8f14b5d95feb5801c2cfb9509fc36ad2373
| 25,744,034,019,316 |
3cca1f08ac75ae60c5759c040c098ec164bdef8b
|
/src/main/java/me/mren/filepoller/filter/CompositWatchEventFilter.java
|
322dd35fedebb9d03462ba6573f74aecaffef8f0
|
[] |
no_license
|
ren78min/file-poller
|
https://github.com/ren78min/file-poller
|
470afd6eb0851cb696e163eba5c964e1a461871e
|
6056f878651e45a08433b456b2ede4cfe1e14367
|
refs/heads/master
| 2018-12-21T23:45:24.491000 | 2018-10-12T04:46:00 | 2018-10-12T04:46:00 | 149,718,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package me.mren.filepoller.filter;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class CompositWatchEventFilter implements WatchEventFilter, ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositWatchEventFilter.class);
@Value("${filepoller.watcheventfilter.names}")
private String[] filterNames;
private ApplicationContext applicationContext;
private final List<WatchEventFilter> filters;
public CompositWatchEventFilter() {
filters = new ArrayList<>();
}
@PostConstruct
void postConstruct() {
for (final String filterName : filterNames) {
final WatchEventFilter filter = applicationContext.getBean(filterName, WatchEventFilter.class);
filters.add(filter);
}
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public boolean filter(final WatchEvent<Path> watchEvent) {
for (final WatchEventFilter filter : filters) {
if (!filter.filter(watchEvent)) {
LOGGER.debug("Filter [{}] blocked [{}].", filter, watchEvent);
return false;
}
}
LOGGER.debug("Watch event [{}] passed all filters.", watchEvent);
return true;
}
}
|
UTF-8
|
Java
| 1,695 |
java
|
CompositWatchEventFilter.java
|
Java
|
[] | null |
[] |
package me.mren.filepoller.filter;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class CompositWatchEventFilter implements WatchEventFilter, ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositWatchEventFilter.class);
@Value("${filepoller.watcheventfilter.names}")
private String[] filterNames;
private ApplicationContext applicationContext;
private final List<WatchEventFilter> filters;
public CompositWatchEventFilter() {
filters = new ArrayList<>();
}
@PostConstruct
void postConstruct() {
for (final String filterName : filterNames) {
final WatchEventFilter filter = applicationContext.getBean(filterName, WatchEventFilter.class);
filters.add(filter);
}
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public boolean filter(final WatchEvent<Path> watchEvent) {
for (final WatchEventFilter filter : filters) {
if (!filter.filter(watchEvent)) {
LOGGER.debug("Filter [{}] blocked [{}].", filter, watchEvent);
return false;
}
}
LOGGER.debug("Watch event [{}] passed all filters.", watchEvent);
return true;
}
}
| 1,695 | 0.786431 | 0.785251 | 59 | 27.728813 | 27.848763 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.38983 | false | false |
0
|
f11829794b4c7853d488afa3e0b38b5650ca9d2e
| 30,666,066,558,657 |
d4e6661665b4a99977e8a1c79d4be0c171720c1d
|
/hello-java/src/main/java/hello/java/network/IpAddress.java
|
293126ed75353ed3941ec5190960780caf39c8b0
|
[] |
no_license
|
ypren/java
|
https://github.com/ypren/java
|
49cd91529d9513039e4658265cb15757ec8f2abc
|
77d7fdf50a89e2b18233759d4ccc0aaf079e6762
|
refs/heads/master
| 2021-06-26T15:28:17.480000 | 2021-01-07T03:39:29 | 2021-01-07T03:39:29 | 189,559,603 | 0 | 0 | null | false | 2020-11-24T02:55:54 | 2019-05-31T08:40:01 | 2020-11-23T07:30:53 | 2020-11-24T02:55:54 | 43 | 0 | 0 | 0 |
Java
| false | false |
package hello.java.network;
import java.net.Inet4Address;
import java.net.UnknownHostException;
public class IpAddress {
private int processors = Runtime.getRuntime().availableProcessors();
public static void main(String[] args) {
try {
System.out.println(Inet4Address.getLocalHost().getHostAddress());
System.out.println(Integer.toBinaryString(10));
System.out.println(Long.parseLong("abc", 16));
System.out.println(f("0101"));
IpAddress ipAddress = new IpAddress();
System.out.println(ipAddress.processors);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public static int f(String binary) {
return Integer.parseInt(binary, 2);
}
}
|
UTF-8
|
Java
| 788 |
java
|
IpAddress.java
|
Java
|
[] | null |
[] |
package hello.java.network;
import java.net.Inet4Address;
import java.net.UnknownHostException;
public class IpAddress {
private int processors = Runtime.getRuntime().availableProcessors();
public static void main(String[] args) {
try {
System.out.println(Inet4Address.getLocalHost().getHostAddress());
System.out.println(Integer.toBinaryString(10));
System.out.println(Long.parseLong("abc", 16));
System.out.println(f("0101"));
IpAddress ipAddress = new IpAddress();
System.out.println(ipAddress.processors);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public static int f(String binary) {
return Integer.parseInt(binary, 2);
}
}
| 788 | 0.635787 | 0.621827 | 26 | 29.307692 | 23.767736 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false |
0
|
be14a07c496179d08733ba9d23d9a41c8326c681
| 15,659,450,763,248 |
4fd9ab712d72b1a9876644cf04f0ed0a892f1aaa
|
/src/main/java/com/service/FileCopy.java
|
c5ebecab2bd1cd01ae2be8ca4e486f284f2e2efa
|
[] |
no_license
|
FT19960715/myNettyStudy
|
https://github.com/FT19960715/myNettyStudy
|
fb921253a853fb1baa052655c557a2f95a97e50a
|
fd84d59d10b947faee3bbdced87b0d11e3b21e7f
|
refs/heads/master
| 2022-12-03T18:30:47.290000 | 2020-08-19T08:00:44 | 2020-08-19T08:00:44 | 288,152,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.service;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
public class FileCopy {
// TODO: 2020-05-27 这里我想偷懒,不想引入日志系统,将日志输出到控制台,然后使用shell脚本将控制台输出日志输出到固定日志文件中去
private static String main = " root@10.1.24.72:";
private static String test = " root@10.1.24.73:";
public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final String debug = "DEBUG";
private static final String info = "INFO";
private static final String warning = "WARNING";
private static final String error = "ERROR";
private static String getNowDate(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(new Date());
}
public static String getHash(String fileName, String hashType)
throws Exception {
InputStream fis;
fis = new FileInputStream(fileName);
byte[] buffer = new byte[1024];
MessageDigest md5 = MessageDigest.getInstance(hashType);
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
}
/**
* md5转成字符串
*/
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}
private static String line = "\n";
// private static String scp = "scp ";
static String commond = "find /home/fengtao/temp -type f";
// find /home/clinic/pic -type f -mtime +20 查询最近二十天
// find /home/clinic/pic -type f -mmin +20 查询最近二十分钟
// static String commond1 = "find /home/script -type f";
public static Connection getConnection(String host,String name,String password) throws IOException {
Connection connection = new Connection(host);
ConnectionInfo info = connection.connect();
boolean auth = connection.authenticateWithPassword(name,password);
return connection;
}
/**
* 72
* @return
* @throws IOException
*/
public static Connection getConnectionMain() throws IOException {
Connection connection = new Connection("10.1.24.72");
ConnectionInfo info = connection.connect();
boolean auth = connection.authenticateWithPassword("root","bicon@123");
return connection;
}
/**
* 73
* @return
* @throws IOException
*/
public static Connection getConnectionTest() throws IOException {
Connection connection = new Connection("10.1.24.73");
ConnectionInfo info = connection.connect();
boolean auth = connection.authenticateWithPassword("root","bicon@123");
return connection;
}
public static String getExecResult(String command, Connection connection ) throws IOException {
// Connection connection = null;
Session session = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
// connection = getConnection(HOST_IP,USER_NAME,USER_PASSWORD);
session = connection.openSession();
session.execCommand(command);
inputStream = new StreamGobbler(session.getStdout());
reader = new BufferedReader(new InputStreamReader(inputStream));
String resultLine ;
while ((resultLine =reader.readLine())!=null){
buffer.append(resultLine).append(line);
}
} catch (IOException e) {
e.printStackTrace();
// if(connection != null){
// connection.close();
// }
if(session != null){
session.close();
} if(inputStream != null){
inputStream.close();
} if(reader != null){
reader.close();
}
}finally {
// if(connection != null){
// connection.close();
// }
if(session != null){
session.close();
} if(inputStream != null){
inputStream.close();
} if(reader != null){
reader.close();
}
}
return buffer.toString();
}
// protected static void dealTowFIle(String file1,String file2){
// List<String> list1 = Arrays.asList(file1.split("\n")); // 生产服务器文件集合
// List<String> list2 = Arrays.asList(file2.split("\n")); // 测试服务器文件集合
// Map<String,String> oneMap= new HashMap(); // 生产map集合
// Map <String,String> twoMap= new HashMap(); // 测试map集合
// for(String item : list1){
// String a = item.substring(item.lastIndexOf("/")+1);
// oneMap.put(a,item);
// } for(String item : list2){
// String a = item.substring(item.lastIndexOf("/")+1);
// twoMap.put(a,item);
// }
//// list1.forEach(item->{
//// String a = item.substring(item.lastIndexOf("/")+1);
//// oneMap.put(a,item);
//// });
//// list2.forEach(item->{
//// String a = item.substring(item.lastIndexOf("/")+1);
//// twoMap.put(a,item);
//// });
// dealTwoMap(oneMap,twoMap);
// }
// protected static void dealTwoMap(Map<String,String> bakmap , Map<String,String> mainmap){
// List<String> baklist1 = dealMap2List(bakmap);
// List<String> baklist1copy = new ArrayList(baklist1);
// List<String> baklist2 = dealMap2List(mainmap);
// List<String> baklist2copy = new ArrayList(baklist2);
// // 互相排重
// baklist1.removeAll(baklist2copy);
// baklist2.removeAll(baklist1copy);
// // TODO: 2020-05-19 这个baklist1中的是73服务器有但是72服务器没有文件,相反,baklist2是72服务器有但是73服务器没有的代码
// doScript(bakmap,baklist1);
// }
private static List<String> dealMap2List(Map<String,String> map){
List<String> list = new ArrayList();
Map.Entry entry = null;
Iterator it = map.entrySet().iterator();
while (it.hasNext()){
entry = (Map.Entry) it.next();
list.add(entry.getKey().toString());
}
return list;
}
// public static void doScript(Map<String,String> map ,List<String> list){
//// buffer.append(line);
// for(String a :list){
// StringBuffer buffer = new StringBuffer();
// String b = map.get(a);
// String c = b.substring(0,b.lastIndexOf("/"));
//
// buffer.append(scp).append(main).append(b).append(" ").append(c).append(" ").append(line);
// System.out.println(buffer.toString());
// File f1 = new File(c);
// if(!f1.exists()){f1.mkdir();}
// Connection conn = null;
// try {
// conn = getConnectionTest();
// Object obj = getExecResult(buffer.toString(),conn);
// System.out.println(obj);
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
// }
private static boolean isIpAdd(String str){
String regex = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}";
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(str).matches();
}
private static boolean isDictionary(String str){
return str.startsWith("/");
}
private static boolean check(Connection connectionA,String dirA,Connection connectionB ,String dirB){
// TODO: 2020-05-26 确认两个dir存在 ,且 copy.lock 存在,密钥相等
File fileA = new File(dirA);
File fileB = new File(dirB);
if(!fileA.exists()){ // 目录不存在
System.out.println(String.format("%s %s 目录 %s 不存在",getNowDate(),error,dirA));
return false;
}
if(!fileB.exists()){
System.out.println(String.format("%s %s 目录 %s 不存在",getNowDate(),error,dirB));
return false;
}
String pathA = dirA+"/copy.lock";
String pathB = dirB+"/copy.lock";
File keyA = new File(pathA);
File keyB = new File(pathB);
// if(!keyA.exists()){ // 没有密钥文件
// System.out.println(String.format("%s %s 密钥文件 %s 不存在",getNowDate(),error,pathA));
// return false;
// }
// if(!keyB.exists()){
// System.out.println(String.format("%s %s 密钥文件 %s 不存在",getNowDate(),error,pathB));
// return false;
// }
String hashPathA = null;
String hashPathB = null;
try {
hashPathA = getHash(pathA,"MD5");
hashPathB = getHash(pathB,"MD5");
}catch (Exception e){
}
// if (!hashPathA.equals(hashPathB)){
// System.out.println(String.format("%s %s 密钥文件不相同",getNowDate(),error));
// }
System.out.println(String.format("%s %s 文件目录校验通过",getNowDate(),info));
return true;
}
private static void doCopy(Connection connectionA,String dirA,String userA,String hostA,Connection connectionB,String dirB,String duration,String userB,String hostB) throws IOException {
List<String> listA = getUpdatedSubFileList(connectionA,dirA,duration); // A服务器所有的文件及目录
List<String> listB = getUpdatedSubFileList(connectionB,dirB,duration); // B服务器所有的文件及目录
System.out.println(String.format("%s %s A服务器所有的文件及目录 %s",getNowDate(),info,listA));
System.out.println(String.format("%s %s B服务器所有的文件及目录 %s",getNowDate(),info,listB));
List<String> aMoveToB = new ArrayList<String>();
List<String> bMoveToA = new ArrayList<String>();
for (String bfile :
listB) {
// TODO: 2020-05-26 这里
if(!listA.contains(bfile)){
bMoveToA.add(bfile);
System.out.println(String.format("%s %s B服务器有A服务器没有的文件 %s",getNowDate(),info,bfile));
}
}
for (String afile :
listA) {
if(!listB.contains(afile)) {
aMoveToB.add(afile);
System.out.println(String.format("%s %s A服务器有B服务器没有的文件 %s",getNowDate(),info,afile));
}
}
if(aMoveToB != null || !aMoveToB.isEmpty()){
scpFiles(connectionA,dirA,aMoveToB,dirB,userB,hostB);
}else{
System.out.println(String.format("%s %s aMoveToB的文件未null",getNowDate(),info));
}
if(bMoveToA != null || !bMoveToA.isEmpty()){
scpFiles(connectionB,dirB,bMoveToA,dirA,userA,hostA);
}else{
System.out.println(String.format("%s %s bMoveToA的文件未null",getNowDate(),info));
}
}
private static void scpFiles(Connection source,String sourceDir,List<String> sourceFileList,String aimDir,String aimUser,String aimHost) throws IOException {
for (String sourceSubFilePath :
sourceFileList ) {
String scpCommand = getScpCommand(sourceDir,sourceSubFilePath,aimUser,aimHost,aimDir);
String result = getExecResult(scpCommand,source);
// TODO: 2020-05-26 此处或许可以验证 scp 是否成功
System.out.println(String.format("%s %s copy 命令:%s",getNowDate(),info,scpCommand));
}
}
private static String getFindUpdatedCommand(String rootDir,String duration){
// TODO: 2020-05-27 我在这个地方做了一些小的判断,当传入的时间未空的时候表示不关心时间,直接复制所有文件
if(duration == null || "null".equals(duration)){
System.out.println(String.format("%s %s 复制文件 find %s -type f",getNowDate(),info,rootDir));
return String.format("find %s -type f",rootDir);
}else{
System.out.println(String.format("%s %s 复制文件 find %s -type f -mmin %s ",getNowDate(),info,rootDir,duration));
return String.format("find %s -type f -mmin +%s",rootDir,duration);
}
}
private static String getScpCommand(String sourceRoot,String sourceFileSubPath, String aimUser,String aimHost,String aimRoot){
String sourcePath = sourceRoot+sourceFileSubPath;
String aimPath = aimRoot + sourceFileSubPath;
return String.format("scp %s %s@%s:%s",sourcePath,aimUser,aimHost,aimPath);
}
private static List<String> getUpdatedSubFileList(Connection connection, String dir, String duration) throws IOException {
String command = getFindUpdatedCommand(dir,duration);
String listStirng = getExecResult(command,connection);
System.out.println(String.format("%s %s 服务器下的文件:%s",getNowDate(),info,listStirng));
List<String> files = new ArrayList<String>();
if(!"".equals(listStirng)){
// 非空字符串
files = Arrays.asList(listStirng.split("\n"));
}
List<String> subFiles = new ArrayList<String>();
int index = dir.length();
for (String file :
files ) {
subFiles.add(file.substring(index)); // 这个地方的subString可能有问题,需要确认
}
return subFiles;
}
public static class HostInfo{
public String user;
public String password;
public String host;
public String baseRoot;
}
public static void main(String[] args) {
Connection connectionA = null;
Connection connectionB = null;
try {
String help = getNowDate() + " /*** \n"
+ "* 本程序用于将指定两个服务器文件路径下的文件,双向同步"
+ "请保证两个服务器下的指定目录中,存在 copy.lock 文件,并且其中 密钥文本相等"
+ "注意:需自行保证两台服务器开启SSH服务,且互信"
+ " * 入参说明 : \n"
+ " * args[0] sync / help \n"
+ " * args[1] server1 host 服务器1 IP地址\n"
+ " * args[2] server1 user 服务器1 用户名\n"
+ " * args[3] server1 password 服务器1 密码\n"
+ " * args[4] server1 dictionary 服务器1 文件路径\n"
+ " * args[5] server2 host 服务器2 IP地址\n"
+ " * args[6] server2 user 服务器1 用户名\n"
+ " * args[7] server2 password 服务器1 密码\n"
+ " * args[8] server2 dictionary 服务器2 文件路径\n"
+ " * args[9] duration number字符串,单位分钟。最近时间段被修改过的文件\n"
+ " * */\n";
if (args.length == 10 || args.length == 1 || args.length == 9) { // 参数正确 或 help,我想吧时间做成可传可不传的那种,这样没传入时间的时候,查询的指令就应该是没有时间的那种
if (args.length == 1) {
System.out.println(args[0]);
if ("help".equals(args[0]) || "h".equals(args[0])) {
System.out.println(help);
} else System.out.println(getNowDate() + " 指令 help 查看帮助");
} else {
String B = "";
for (String a : args) {
B += a + " ";
}
System.out.println(String.format("%s %s 请求参数:%s", getNowDate(), warning, B));
if ("sync".equals(args[0])) {
String hostA = args[1];
String userA = args[2];
String passA = args[3];
String dirA = args[4];
String hostB = args[5];
String userB = args[6];
String passB = args[7];
String dirB = args[8];
String duration = null;
// String hostA = "10.1.24.72";
// String userA = "root";
// String passA = "bicon@123";
// String dirA = "/home/fengtao/temp";
//
// String hostB = "10.1.24.73";
// String userB = "root";
// String passB = "bicon@123";
// String dirB = "/home/fengtao/temp";
// String duration = null;
if (args.length == 10 && !"null".equals(args[9])) {
duration = args[9]; // 时间,分钟,我想做成可传可不传的那种
}
// TODO: 2020-05-26 使用正则验证 host 是 ip地址
if (!isIpAdd(hostA)) {
// 不是IP地址
System.out.println(String.format("%s %s %s不是可用ip地址", getNowDate(), warning, hostA));
}
if (!isIpAdd(hostB)) {
// 不是IP地址
System.out.println(String.format("%s %s %s不是可用ip地址", getNowDate(), warning, hostB));
}
if (!isDictionary(dirA)) {
// 不是文件目录
System.out.println(String.format("%s %s %s不是文件目录", getNowDate(), warning, dirA));
}
// 初始化两个服务连接
// 日志输出传入参数
System.out.println(String.format("%s %s hostA:%s userA:%s dirA:%s", getNowDate(), info, hostA, userA, dirA));
System.out.println(String.format("%s %s hostB:%s userB:%s dirB:%s", getNowDate(), info, hostB, userB, dirB));
connectionA= getConnection(hostA, userA, passA);
connectionB = getConnection(hostB, userB, passB);
// 验证两个目录存在,存在并验证 copy.lock
if (check(connectionA, dirA, connectionB, dirB)) {
// 进行文件互拷贝
doCopy(connectionA, dirA, userA, hostA, connectionB, dirB, duration, userB, hostB);
// 完成
} else {
}
// 关闭 connection
}
}
} else { // 参数错误
System.out.println(String.format("%s %s 参数长度错误 %s", getNowDate(), error, args.length));
}
// Connection conn = getConnectionMain();// 获取72 链接
// String obj = getExecResult(commond,conn);
// // 这里的obj是所有本地下的文件
// Connection conn1 = getConnectionTest();
// String obj1 = getExecResult(commond,conn1);
// // 获取到72服务器和73服务器下的所有文件名称并转换成字符串
//
//// System.out.println("obj");
//// System.out.println(obj);
//// System.out.println(obj1);
// dealTowFIle(obj,obj1);
}catch (Exception e){
e.printStackTrace();
}
finally {
if(connectionA!=null){
connectionA.close();
connectionA=null;
}
if(connectionB!=null){
connectionB.close();
connectionB=null;
}
}
}
}
|
UTF-8
|
Java
| 20,508 |
java
|
FileCopy.java
|
Java
|
[
{
"context": "到固定日志文件中去\n private static String main = \" root@10.1.24.72:\";\n private static String test = \" root@10.1.2",
"end": 452,
"score": 0.9994627237319946,
"start": 442,
"tag": "IP_ADDRESS",
"value": "10.1.24.72"
},
{
"context": ".24.72:\";\n private static String test = \" root@10.1.24.73:\";\n\n public static char[] hexChar = { '0', '1'",
"end": 506,
"score": 0.9994451403617859,
"start": 496,
"tag": "IP_ADDRESS",
"value": "10.1.24.73"
},
{
"context": "{\n Connection connection = new Connection(\"10.1.24.72\");\n ConnectionInfo info = connection.conne",
"end": 2644,
"score": 0.9993168115615845,
"start": 2634,
"tag": "IP_ADDRESS",
"value": "10.1.24.72"
},
{
"context": "uth = connection.authenticateWithPassword(\"root\",\"bicon@123\");\n return connection;\n }\n\n /**\n ",
"end": 2776,
"score": 0.9992649555206299,
"start": 2767,
"tag": "PASSWORD",
"value": "bicon@123"
},
{
"context": "{\n Connection connection = new Connection(\"10.1.24.73\");\n ConnectionInfo info = connection.conne",
"end": 3010,
"score": 0.9987262487411499,
"start": 3000,
"tag": "IP_ADDRESS",
"value": "10.1.24.73"
},
{
"context": "uth = connection.authenticateWithPassword(\"root\",\"bicon@123\");\n return connection;\n }\n\n public s",
"end": 3142,
"score": 0.9992875456809998,
"start": 3133,
"tag": "PASSWORD",
"value": "bicon@123"
},
{
"context": " + \" * args[3] server1 password 服务器1 密码\\n\"\n + \" * args[4] server1 dictio",
"end": 14191,
"score": 0.5894955396652222,
"start": 14190,
"tag": "PASSWORD",
"value": "n"
},
{
"context": " + \" * args[7] server2 password 服务器1 密码\\n\"\n + \" * args[8] server2 dictio",
"end": 14439,
"score": 0.6191183924674988,
"start": 14438,
"tag": "PASSWORD",
"value": "n"
},
{
"context": "ion = null;\n// String hostA = \"10.1.24.72\";\n// String userA = \"root\";\n//",
"end": 15837,
"score": 0.9995562434196472,
"start": 15827,
"tag": "IP_ADDRESS",
"value": "10.1.24.72"
},
{
"context": "0.1.24.72\";\n// String userA = \"root\";\n// String passA = \"bicon@123",
"end": 15882,
"score": 0.5305455923080444,
"start": 15878,
"tag": "USERNAME",
"value": "root"
},
{
"context": "A = \"root\";\n// String passA = \"bicon@123\";\n// String dirA = \"/home/feng",
"end": 15932,
"score": 0.9993455410003662,
"start": 15923,
"tag": "PASSWORD",
"value": "bicon@123"
},
{
"context": "o/temp\";\n//\n// String hostB = \"10.1.24.73\";\n// String userB = \"root\";\n//",
"end": 16044,
"score": 0.9995416402816772,
"start": 16034,
"tag": "IP_ADDRESS",
"value": "10.1.24.73"
},
{
"context": "0.1.24.73\";\n// String userB = \"root\";\n// String passB = \"bicon@123",
"end": 16089,
"score": 0.6850783824920654,
"start": 16085,
"tag": "USERNAME",
"value": "root"
},
{
"context": "B = \"root\";\n// String passB = \"bicon@123\";\n// String dirB = \"/home/feng",
"end": 16139,
"score": 0.9993131160736084,
"start": 16130,
"tag": "PASSWORD",
"value": "bicon@123"
}
] | null |
[] |
package com.service;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
public class FileCopy {
// TODO: 2020-05-27 这里我想偷懒,不想引入日志系统,将日志输出到控制台,然后使用shell脚本将控制台输出日志输出到固定日志文件中去
private static String main = " root@10.1.24.72:";
private static String test = " root@10.1.24.73:";
public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final String debug = "DEBUG";
private static final String info = "INFO";
private static final String warning = "WARNING";
private static final String error = "ERROR";
private static String getNowDate(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(new Date());
}
public static String getHash(String fileName, String hashType)
throws Exception {
InputStream fis;
fis = new FileInputStream(fileName);
byte[] buffer = new byte[1024];
MessageDigest md5 = MessageDigest.getInstance(hashType);
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
}
/**
* md5转成字符串
*/
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}
private static String line = "\n";
// private static String scp = "scp ";
static String commond = "find /home/fengtao/temp -type f";
// find /home/clinic/pic -type f -mtime +20 查询最近二十天
// find /home/clinic/pic -type f -mmin +20 查询最近二十分钟
// static String commond1 = "find /home/script -type f";
public static Connection getConnection(String host,String name,String password) throws IOException {
Connection connection = new Connection(host);
ConnectionInfo info = connection.connect();
boolean auth = connection.authenticateWithPassword(name,password);
return connection;
}
/**
* 72
* @return
* @throws IOException
*/
public static Connection getConnectionMain() throws IOException {
Connection connection = new Connection("10.1.24.72");
ConnectionInfo info = connection.connect();
boolean auth = connection.authenticateWithPassword("root","<PASSWORD>");
return connection;
}
/**
* 73
* @return
* @throws IOException
*/
public static Connection getConnectionTest() throws IOException {
Connection connection = new Connection("10.1.24.73");
ConnectionInfo info = connection.connect();
boolean auth = connection.authenticateWithPassword("root","<PASSWORD>");
return connection;
}
public static String getExecResult(String command, Connection connection ) throws IOException {
// Connection connection = null;
Session session = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
// connection = getConnection(HOST_IP,USER_NAME,USER_PASSWORD);
session = connection.openSession();
session.execCommand(command);
inputStream = new StreamGobbler(session.getStdout());
reader = new BufferedReader(new InputStreamReader(inputStream));
String resultLine ;
while ((resultLine =reader.readLine())!=null){
buffer.append(resultLine).append(line);
}
} catch (IOException e) {
e.printStackTrace();
// if(connection != null){
// connection.close();
// }
if(session != null){
session.close();
} if(inputStream != null){
inputStream.close();
} if(reader != null){
reader.close();
}
}finally {
// if(connection != null){
// connection.close();
// }
if(session != null){
session.close();
} if(inputStream != null){
inputStream.close();
} if(reader != null){
reader.close();
}
}
return buffer.toString();
}
// protected static void dealTowFIle(String file1,String file2){
// List<String> list1 = Arrays.asList(file1.split("\n")); // 生产服务器文件集合
// List<String> list2 = Arrays.asList(file2.split("\n")); // 测试服务器文件集合
// Map<String,String> oneMap= new HashMap(); // 生产map集合
// Map <String,String> twoMap= new HashMap(); // 测试map集合
// for(String item : list1){
// String a = item.substring(item.lastIndexOf("/")+1);
// oneMap.put(a,item);
// } for(String item : list2){
// String a = item.substring(item.lastIndexOf("/")+1);
// twoMap.put(a,item);
// }
//// list1.forEach(item->{
//// String a = item.substring(item.lastIndexOf("/")+1);
//// oneMap.put(a,item);
//// });
//// list2.forEach(item->{
//// String a = item.substring(item.lastIndexOf("/")+1);
//// twoMap.put(a,item);
//// });
// dealTwoMap(oneMap,twoMap);
// }
// protected static void dealTwoMap(Map<String,String> bakmap , Map<String,String> mainmap){
// List<String> baklist1 = dealMap2List(bakmap);
// List<String> baklist1copy = new ArrayList(baklist1);
// List<String> baklist2 = dealMap2List(mainmap);
// List<String> baklist2copy = new ArrayList(baklist2);
// // 互相排重
// baklist1.removeAll(baklist2copy);
// baklist2.removeAll(baklist1copy);
// // TODO: 2020-05-19 这个baklist1中的是73服务器有但是72服务器没有文件,相反,baklist2是72服务器有但是73服务器没有的代码
// doScript(bakmap,baklist1);
// }
private static List<String> dealMap2List(Map<String,String> map){
List<String> list = new ArrayList();
Map.Entry entry = null;
Iterator it = map.entrySet().iterator();
while (it.hasNext()){
entry = (Map.Entry) it.next();
list.add(entry.getKey().toString());
}
return list;
}
// public static void doScript(Map<String,String> map ,List<String> list){
//// buffer.append(line);
// for(String a :list){
// StringBuffer buffer = new StringBuffer();
// String b = map.get(a);
// String c = b.substring(0,b.lastIndexOf("/"));
//
// buffer.append(scp).append(main).append(b).append(" ").append(c).append(" ").append(line);
// System.out.println(buffer.toString());
// File f1 = new File(c);
// if(!f1.exists()){f1.mkdir();}
// Connection conn = null;
// try {
// conn = getConnectionTest();
// Object obj = getExecResult(buffer.toString(),conn);
// System.out.println(obj);
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
// }
private static boolean isIpAdd(String str){
String regex = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}";
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(str).matches();
}
private static boolean isDictionary(String str){
return str.startsWith("/");
}
private static boolean check(Connection connectionA,String dirA,Connection connectionB ,String dirB){
// TODO: 2020-05-26 确认两个dir存在 ,且 copy.lock 存在,密钥相等
File fileA = new File(dirA);
File fileB = new File(dirB);
if(!fileA.exists()){ // 目录不存在
System.out.println(String.format("%s %s 目录 %s 不存在",getNowDate(),error,dirA));
return false;
}
if(!fileB.exists()){
System.out.println(String.format("%s %s 目录 %s 不存在",getNowDate(),error,dirB));
return false;
}
String pathA = dirA+"/copy.lock";
String pathB = dirB+"/copy.lock";
File keyA = new File(pathA);
File keyB = new File(pathB);
// if(!keyA.exists()){ // 没有密钥文件
// System.out.println(String.format("%s %s 密钥文件 %s 不存在",getNowDate(),error,pathA));
// return false;
// }
// if(!keyB.exists()){
// System.out.println(String.format("%s %s 密钥文件 %s 不存在",getNowDate(),error,pathB));
// return false;
// }
String hashPathA = null;
String hashPathB = null;
try {
hashPathA = getHash(pathA,"MD5");
hashPathB = getHash(pathB,"MD5");
}catch (Exception e){
}
// if (!hashPathA.equals(hashPathB)){
// System.out.println(String.format("%s %s 密钥文件不相同",getNowDate(),error));
// }
System.out.println(String.format("%s %s 文件目录校验通过",getNowDate(),info));
return true;
}
private static void doCopy(Connection connectionA,String dirA,String userA,String hostA,Connection connectionB,String dirB,String duration,String userB,String hostB) throws IOException {
List<String> listA = getUpdatedSubFileList(connectionA,dirA,duration); // A服务器所有的文件及目录
List<String> listB = getUpdatedSubFileList(connectionB,dirB,duration); // B服务器所有的文件及目录
System.out.println(String.format("%s %s A服务器所有的文件及目录 %s",getNowDate(),info,listA));
System.out.println(String.format("%s %s B服务器所有的文件及目录 %s",getNowDate(),info,listB));
List<String> aMoveToB = new ArrayList<String>();
List<String> bMoveToA = new ArrayList<String>();
for (String bfile :
listB) {
// TODO: 2020-05-26 这里
if(!listA.contains(bfile)){
bMoveToA.add(bfile);
System.out.println(String.format("%s %s B服务器有A服务器没有的文件 %s",getNowDate(),info,bfile));
}
}
for (String afile :
listA) {
if(!listB.contains(afile)) {
aMoveToB.add(afile);
System.out.println(String.format("%s %s A服务器有B服务器没有的文件 %s",getNowDate(),info,afile));
}
}
if(aMoveToB != null || !aMoveToB.isEmpty()){
scpFiles(connectionA,dirA,aMoveToB,dirB,userB,hostB);
}else{
System.out.println(String.format("%s %s aMoveToB的文件未null",getNowDate(),info));
}
if(bMoveToA != null || !bMoveToA.isEmpty()){
scpFiles(connectionB,dirB,bMoveToA,dirA,userA,hostA);
}else{
System.out.println(String.format("%s %s bMoveToA的文件未null",getNowDate(),info));
}
}
private static void scpFiles(Connection source,String sourceDir,List<String> sourceFileList,String aimDir,String aimUser,String aimHost) throws IOException {
for (String sourceSubFilePath :
sourceFileList ) {
String scpCommand = getScpCommand(sourceDir,sourceSubFilePath,aimUser,aimHost,aimDir);
String result = getExecResult(scpCommand,source);
// TODO: 2020-05-26 此处或许可以验证 scp 是否成功
System.out.println(String.format("%s %s copy 命令:%s",getNowDate(),info,scpCommand));
}
}
private static String getFindUpdatedCommand(String rootDir,String duration){
// TODO: 2020-05-27 我在这个地方做了一些小的判断,当传入的时间未空的时候表示不关心时间,直接复制所有文件
if(duration == null || "null".equals(duration)){
System.out.println(String.format("%s %s 复制文件 find %s -type f",getNowDate(),info,rootDir));
return String.format("find %s -type f",rootDir);
}else{
System.out.println(String.format("%s %s 复制文件 find %s -type f -mmin %s ",getNowDate(),info,rootDir,duration));
return String.format("find %s -type f -mmin +%s",rootDir,duration);
}
}
private static String getScpCommand(String sourceRoot,String sourceFileSubPath, String aimUser,String aimHost,String aimRoot){
String sourcePath = sourceRoot+sourceFileSubPath;
String aimPath = aimRoot + sourceFileSubPath;
return String.format("scp %s %s@%s:%s",sourcePath,aimUser,aimHost,aimPath);
}
private static List<String> getUpdatedSubFileList(Connection connection, String dir, String duration) throws IOException {
String command = getFindUpdatedCommand(dir,duration);
String listStirng = getExecResult(command,connection);
System.out.println(String.format("%s %s 服务器下的文件:%s",getNowDate(),info,listStirng));
List<String> files = new ArrayList<String>();
if(!"".equals(listStirng)){
// 非空字符串
files = Arrays.asList(listStirng.split("\n"));
}
List<String> subFiles = new ArrayList<String>();
int index = dir.length();
for (String file :
files ) {
subFiles.add(file.substring(index)); // 这个地方的subString可能有问题,需要确认
}
return subFiles;
}
public static class HostInfo{
public String user;
public String password;
public String host;
public String baseRoot;
}
public static void main(String[] args) {
Connection connectionA = null;
Connection connectionB = null;
try {
String help = getNowDate() + " /*** \n"
+ "* 本程序用于将指定两个服务器文件路径下的文件,双向同步"
+ "请保证两个服务器下的指定目录中,存在 copy.lock 文件,并且其中 密钥文本相等"
+ "注意:需自行保证两台服务器开启SSH服务,且互信"
+ " * 入参说明 : \n"
+ " * args[0] sync / help \n"
+ " * args[1] server1 host 服务器1 IP地址\n"
+ " * args[2] server1 user 服务器1 用户名\n"
+ " * args[3] server1 password 服务器1 密码\n"
+ " * args[4] server1 dictionary 服务器1 文件路径\n"
+ " * args[5] server2 host 服务器2 IP地址\n"
+ " * args[6] server2 user 服务器1 用户名\n"
+ " * args[7] server2 password 服务器1 密码\n"
+ " * args[8] server2 dictionary 服务器2 文件路径\n"
+ " * args[9] duration number字符串,单位分钟。最近时间段被修改过的文件\n"
+ " * */\n";
if (args.length == 10 || args.length == 1 || args.length == 9) { // 参数正确 或 help,我想吧时间做成可传可不传的那种,这样没传入时间的时候,查询的指令就应该是没有时间的那种
if (args.length == 1) {
System.out.println(args[0]);
if ("help".equals(args[0]) || "h".equals(args[0])) {
System.out.println(help);
} else System.out.println(getNowDate() + " 指令 help 查看帮助");
} else {
String B = "";
for (String a : args) {
B += a + " ";
}
System.out.println(String.format("%s %s 请求参数:%s", getNowDate(), warning, B));
if ("sync".equals(args[0])) {
String hostA = args[1];
String userA = args[2];
String passA = args[3];
String dirA = args[4];
String hostB = args[5];
String userB = args[6];
String passB = args[7];
String dirB = args[8];
String duration = null;
// String hostA = "10.1.24.72";
// String userA = "root";
// String passA = "<PASSWORD>";
// String dirA = "/home/fengtao/temp";
//
// String hostB = "10.1.24.73";
// String userB = "root";
// String passB = "<PASSWORD>";
// String dirB = "/home/fengtao/temp";
// String duration = null;
if (args.length == 10 && !"null".equals(args[9])) {
duration = args[9]; // 时间,分钟,我想做成可传可不传的那种
}
// TODO: 2020-05-26 使用正则验证 host 是 ip地址
if (!isIpAdd(hostA)) {
// 不是IP地址
System.out.println(String.format("%s %s %s不是可用ip地址", getNowDate(), warning, hostA));
}
if (!isIpAdd(hostB)) {
// 不是IP地址
System.out.println(String.format("%s %s %s不是可用ip地址", getNowDate(), warning, hostB));
}
if (!isDictionary(dirA)) {
// 不是文件目录
System.out.println(String.format("%s %s %s不是文件目录", getNowDate(), warning, dirA));
}
// 初始化两个服务连接
// 日志输出传入参数
System.out.println(String.format("%s %s hostA:%s userA:%s dirA:%s", getNowDate(), info, hostA, userA, dirA));
System.out.println(String.format("%s %s hostB:%s userB:%s dirB:%s", getNowDate(), info, hostB, userB, dirB));
connectionA= getConnection(hostA, userA, passA);
connectionB = getConnection(hostB, userB, passB);
// 验证两个目录存在,存在并验证 copy.lock
if (check(connectionA, dirA, connectionB, dirB)) {
// 进行文件互拷贝
doCopy(connectionA, dirA, userA, hostA, connectionB, dirB, duration, userB, hostB);
// 完成
} else {
}
// 关闭 connection
}
}
} else { // 参数错误
System.out.println(String.format("%s %s 参数长度错误 %s", getNowDate(), error, args.length));
}
// Connection conn = getConnectionMain();// 获取72 链接
// String obj = getExecResult(commond,conn);
// // 这里的obj是所有本地下的文件
// Connection conn1 = getConnectionTest();
// String obj1 = getExecResult(commond,conn1);
// // 获取到72服务器和73服务器下的所有文件名称并转换成字符串
//
//// System.out.println("obj");
//// System.out.println(obj);
//// System.out.println(obj1);
// dealTowFIle(obj,obj1);
}catch (Exception e){
e.printStackTrace();
}
finally {
if(connectionA!=null){
connectionA.close();
connectionA=null;
}
if(connectionB!=null){
connectionB.close();
connectionB=null;
}
}
}
}
| 20,512 | 0.533557 | 0.519431 | 456 | 40.758774 | 29.370571 | 190 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.932018 | false | false |
0
|
794fd123f6be4e96ae365bf384e94101dee1e177
| 26,353,919,383,044 |
a949c1e76575ced05bdd78ba71aa136d236ce5db
|
/UserNotFoundException.java
|
a4412c10a771ee0178adc7f2847586066585b500
|
[] |
no_license
|
Kvedant7/e-wallet
|
https://github.com/Kvedant7/e-wallet
|
c6cac75af51ab6c60f46bf5f8fd55911451ceabf
|
0725f98d678058dcb1ce83e5ba153af3a8adc8a3
|
refs/heads/master
| 2020-08-09T22:04:03.285000 | 2019-10-10T13:16:42 | 2019-10-10T13:16:42 | 214,186,257 | 0 | 0 | null | false | 2019-10-10T13:16:43 | 2019-10-10T13:10:22 | 2019-10-10T13:10:25 | 2019-10-10T13:16:43 | 0 | 0 | 0 | 0 | null | false | false |
package com.capgemini.exception;
public class UserNotFoundException extends Exception{
@Override
public String toString() {
return "User Not Found";
}
}
|
UTF-8
|
Java
| 175 |
java
|
UserNotFoundException.java
|
Java
|
[] | null |
[] |
package com.capgemini.exception;
public class UserNotFoundException extends Exception{
@Override
public String toString() {
return "User Not Found";
}
}
| 175 | 0.697143 | 0.697143 | 11 | 13.909091 | 17.101061 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false |
0
|
a689d9bf0b3126e173029edaba9b6249992bc6ea
| 26,353,919,383,870 |
3cb814153ff1dd4b0d4e6705dc4c9639701e07f3
|
/stock-market/src/main/java/com/ausky/stock/bean/StockMarket.java
|
bd96e6c2368b9a77df952fd10b25dd150f16f9ca
|
[] |
no_license
|
zecheng/stock-4
|
https://github.com/zecheng/stock-4
|
18c68f89e234de1836c715a7ebdd982caf4c0746
|
c8ce3481a2cc9b3fc1d18b3aac99a39e52ad55d5
|
refs/heads/master
| 2021-06-21T11:30:27.345000 | 2017-08-14T04:38:48 | 2017-08-14T04:38:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* File Name: StockMarket.java
* <p/>
* File Desc: TODO
* <p/>
* Product AB: TODO
* <p/>
* Product Name: TODO
* <p/>
* Module Name: TODO
* <p/>
* Module AB: TODO
* <p/>
* Author: 敖海样
* <p/>
* History: 2016/2/10 created by hy.ao
*/
package com.ausky.stock.bean;
/**
* Created with IntelliJ IDEA.
* User: 敖海样
* Date: 2016/2/10
* Time: 11:38
* 文件说明:股票行情
*/
public class StockMarket
{
//hq 行情数据 时间 ,开盘,收盘,涨幅额 ,涨跌幅,最低,最高,成交手,成交金额,换手率
//时间 yyyy-mm-dd
private String tradeDate;
//开盘价 xx.xx
private String open;
//昨日收盘价 xx.xx
private String close;
//涨跌额 xx.xx
private String increaseMoney;
//涨跌幅 xx.xx%
private String increaseRatio;
//最低 xx.xx
private String low;
//最高 xx.xx
private String high;
//成交手 xx.xx
private String tradingHand;
//成交额
private String tradingVolume;
//换手率 xx.xx%
private String changeRatio;
//股票代码
private String stockCode;
//股票市场
private String stockMarket;
public String getTradeDate()
{
return tradeDate;
}
public void setTradeDate( String tradeDate )
{
this.tradeDate = tradeDate;
}
public String getOpen()
{
return open;
}
public void setOpen( String open )
{
this.open = open;
}
public String getClose()
{
return close;
}
public void setClose( String close )
{
this.close = close;
}
public String getIncreaseMoney()
{
return increaseMoney;
}
public void setIncreaseMoney( String increaseMoney )
{
this.increaseMoney = increaseMoney;
}
public String getIncreaseRatio()
{
return increaseRatio;
}
public void setIncreaseRatio( String increaseRatio )
{
this.increaseRatio = increaseRatio;
}
public String getLow()
{
return low;
}
public void setLow( String low )
{
this.low = low;
}
public String getHigh()
{
return high;
}
public void setHigh( String high )
{
this.high = high;
}
public String getTradingHand()
{
return tradingHand;
}
public void setTradingHand( String tradingHand )
{
this.tradingHand = tradingHand;
}
public String getTradingVolume()
{
return tradingVolume;
}
public void setTradingVolume( String tradingVolume )
{
this.tradingVolume = tradingVolume;
}
public String getChangeRatio()
{
return "-".equals( changeRatio ) ? "0" : changeRatio;
}
public void setChangeRatio( String changeRatio )
{
this.changeRatio = changeRatio;
}
public String getStockMarket()
{
return stockMarket;
}
public void setStockMarket( String stockMarket )
{
this.stockMarket = stockMarket;
}
public String getStockCode()
{
return stockCode;
}
public void setStockCode( String stockCode )
{
this.stockCode = stockCode;
}
}
|
UTF-8
|
Java
| 3,268 |
java
|
StockMarket.java
|
Java
|
[
{
"context": "/>\n * Module AB: TODO\n * <p/>\n * Author: 敖海样\n * <p/>\n * History: 2016/2/10 created by hy.",
"end": 216,
"score": 0.9073790907859802,
"start": 213,
"tag": "USERNAME",
"value": "敖海样"
},
{
"context": "ean;\n\n/**\n * Created with IntelliJ IDEA.\n * User: 敖海样\n * Date: 2016/2/10\n * Time: 11:38\n * 文件说明:股票行情\n *",
"end": 351,
"score": 0.9596127271652222,
"start": 348,
"tag": "USERNAME",
"value": "敖海样"
}
] | null |
[] |
/**
* File Name: StockMarket.java
* <p/>
* File Desc: TODO
* <p/>
* Product AB: TODO
* <p/>
* Product Name: TODO
* <p/>
* Module Name: TODO
* <p/>
* Module AB: TODO
* <p/>
* Author: 敖海样
* <p/>
* History: 2016/2/10 created by hy.ao
*/
package com.ausky.stock.bean;
/**
* Created with IntelliJ IDEA.
* User: 敖海样
* Date: 2016/2/10
* Time: 11:38
* 文件说明:股票行情
*/
public class StockMarket
{
//hq 行情数据 时间 ,开盘,收盘,涨幅额 ,涨跌幅,最低,最高,成交手,成交金额,换手率
//时间 yyyy-mm-dd
private String tradeDate;
//开盘价 xx.xx
private String open;
//昨日收盘价 xx.xx
private String close;
//涨跌额 xx.xx
private String increaseMoney;
//涨跌幅 xx.xx%
private String increaseRatio;
//最低 xx.xx
private String low;
//最高 xx.xx
private String high;
//成交手 xx.xx
private String tradingHand;
//成交额
private String tradingVolume;
//换手率 xx.xx%
private String changeRatio;
//股票代码
private String stockCode;
//股票市场
private String stockMarket;
public String getTradeDate()
{
return tradeDate;
}
public void setTradeDate( String tradeDate )
{
this.tradeDate = tradeDate;
}
public String getOpen()
{
return open;
}
public void setOpen( String open )
{
this.open = open;
}
public String getClose()
{
return close;
}
public void setClose( String close )
{
this.close = close;
}
public String getIncreaseMoney()
{
return increaseMoney;
}
public void setIncreaseMoney( String increaseMoney )
{
this.increaseMoney = increaseMoney;
}
public String getIncreaseRatio()
{
return increaseRatio;
}
public void setIncreaseRatio( String increaseRatio )
{
this.increaseRatio = increaseRatio;
}
public String getLow()
{
return low;
}
public void setLow( String low )
{
this.low = low;
}
public String getHigh()
{
return high;
}
public void setHigh( String high )
{
this.high = high;
}
public String getTradingHand()
{
return tradingHand;
}
public void setTradingHand( String tradingHand )
{
this.tradingHand = tradingHand;
}
public String getTradingVolume()
{
return tradingVolume;
}
public void setTradingVolume( String tradingVolume )
{
this.tradingVolume = tradingVolume;
}
public String getChangeRatio()
{
return "-".equals( changeRatio ) ? "0" : changeRatio;
}
public void setChangeRatio( String changeRatio )
{
this.changeRatio = changeRatio;
}
public String getStockMarket()
{
return stockMarket;
}
public void setStockMarket( String stockMarket )
{
this.stockMarket = stockMarket;
}
public String getStockCode()
{
return stockCode;
}
public void setStockCode( String stockCode )
{
this.stockCode = stockCode;
}
}
| 3,268 | 0.579391 | 0.573234 | 174 | 16.741379 | 15.66337 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.212644 | false | false |
0
|
abcd85f1d61ff2d0e3e62dbf3a069f92d8f5ea24
| 3,435,973,874,909 |
844c40e713ca8f2a30edf4d931eafa20803e63b2
|
/java/CardLayout2.java
|
b6d3aba2d28a3bdf8c8f697eb6df7abca67698f4
|
[] |
no_license
|
lparis/mycode
|
https://github.com/lparis/mycode
|
60a2d93e277cbfcb7c7526e846a50c5f59deb2de
|
f5bab71b4ea1f73380707578e78070f2ad4881de
|
refs/heads/master
| 2020-04-27T22:37:58.880000 | 2019-03-09T21:06:48 | 2019-03-09T21:06:48 | 174,742,993 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Java Project
* CIS163_AA_Phillips
* lparis Lesson 1.3
* CardLayout.java
*/
import javax.swing.*;
// Import the GUI library.
public class CardLayout2
// The CardLayout class produces a business card layout with name, address, city, state, zip, phone
{ // Class body open
public static void main(String[] args)
/* The CardLayout class class calls the main() method, which takes
* the String object as an argument and does not return a value.
*/
{
JOptionPane.showMessageDialog(null," Business Card\n -----------\n"
+ " - Name\n - Street Address\n - City\n - State\n"
+ " - Zip Code\n - Home Phone\n - Work Phone");
// "/n" creates a new line for each data item
// "+" Concatenates the string across line breaks
}
}
|
UTF-8
|
Java
| 753 |
java
|
CardLayout2.java
|
Java
|
[] | null |
[] |
/*
* Java Project
* CIS163_AA_Phillips
* lparis Lesson 1.3
* CardLayout.java
*/
import javax.swing.*;
// Import the GUI library.
public class CardLayout2
// The CardLayout class produces a business card layout with name, address, city, state, zip, phone
{ // Class body open
public static void main(String[] args)
/* The CardLayout class class calls the main() method, which takes
* the String object as an argument and does not return a value.
*/
{
JOptionPane.showMessageDialog(null," Business Card\n -----------\n"
+ " - Name\n - Street Address\n - City\n - State\n"
+ " - Zip Code\n - Home Phone\n - Work Phone");
// "/n" creates a new line for each data item
// "+" Concatenates the string across line breaks
}
}
| 753 | 0.667995 | 0.660027 | 27 | 26.888889 | 26.760021 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false |
0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.