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
1f51689986ea239beddfc29519b07c3aba9069ce
2,834,678,476,383
fb14d769654de55a3b7bd6ee6aa65c03084e41bc
/src/com/empmanagement/screens/WebCamFunctionalPanel.java
81168a8d6723e340bf5b2544d722162251459120
[]
no_license
mon-d/EmployeManagementSystem
https://github.com/mon-d/EmployeManagementSystem
3c43b94ccb58b524426c05881972a0f771f211af
81f19801f5a1aedf1aeb16a378e74d8992f2bfcc
refs/heads/master
2015-07-14T13:28:42
2014-07-15T14:05:25
2014-07-15T14:05:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.empmanagement.screens; import com.employeemanagement.common.Common; import com.employeemanagement.utility.CropImage; import com.empmanagement.testswing.ResizableComponent; import java.awt.BorderLayout; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.lang.Thread.UncaughtExceptionHandler; import javax.swing.JFrame; import javax.swing.SwingUtilities; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamEvent; import com.github.sarxos.webcam.WebcamListener; import com.github.sarxos.webcam.WebcamPanel; import com.github.sarxos.webcam.WebcamPicker; import com.github.sarxos.webcam.WebcamResolution; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * Proof of concept of how to handle webcam video stream from Java * * @author Bartosz Firyn (SarXos) */ public class WebCamFunctionalPanel extends JFrame implements Runnable, ActionListener, WebcamListener, WindowListener, UncaughtExceptionHandler{ private static final long serialVersionUID = 1L; private Webcam webcam = null; private WebcamPanel panel = null; private WebcamPicker picker = null; private JButton capture = null; private String imagePath = ""; Thread t; static MainFrame mainFrame; static EmployeeManipulationFrame emf; public WebCamFunctionalPanel(MainFrame mainFrame,EmployeeManipulationFrame emf){ this.mainFrame = mainFrame; this.emf = emf; } @Override public void run() { setTitle("Capture Your Picture"); setDefaultCloseOperation(WebCamFunctionalPanel.DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); addWindowListener(this); setLocation(200,50); this.setResizable(false); picker = new WebcamPicker(); picker.disable(); webcam = picker.getSelectedWebcam(); if (webcam == null) { // System.out.println("No webcams found..."); // System.exit(1); // this.dispose(); JFrame j = new JFrame(); j.setAlwaysOnTop(true); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); j.setVisible(false); JOptionPane.showMessageDialog(j, "No Camera found!!!", "", JOptionPane.INFORMATION_MESSAGE); } else { webcam.setViewSize(WebcamResolution.VGA.getSize()); webcam.addWebcamListener(WebCamFunctionalPanel.this); panel = new WebcamPanel(webcam, false); panel.setFPSDisplayed(true); ImageIcon icon = new ImageIcon(getClass().getResource("/com/empmanagement/screens/capture.png")); capture = new JButton("Capture"); capture.setIcon(icon); //capture.setSize(getContentPane().getWidth(),500); capture.addActionListener(this); add(picker, BorderLayout.NORTH); JPanel jp = new JPanel(); jp.add(capture); //add(capture,BorderLayout.SOUTH); add(jp,BorderLayout.SOUTH); add(panel, BorderLayout.CENTER); pack(); setVisible(true); Thread t = new Thread() { @Override public void run() { panel.start(); } }; t.setName("example-starter"); t.setDaemon(true); t.setUncaughtExceptionHandler(this); t.start(); } } @Override public void webcamOpen(WebcamEvent we) { System.out.println("webcam open"); } @Override public void webcamClosed(WebcamEvent we) { System.out.println("webcam closed"); } @Override public void webcamDisposed(WebcamEvent we) { System.out.println("webcam disposed"); } @Override public void webcamImageObtained(WebcamEvent we) { // do nothing } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { webcam.close(); } @Override public void windowClosing(WindowEvent e) { MainFrame.setImageURL(imagePath); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { System.out.println("webcam viewer resumed"); panel.resume(); } @Override public void windowIconified(WindowEvent e) { System.out.println("webcam viewer paused"); panel.pause(); } @Override public void uncaughtException(Thread t, Throwable e) { System.err.println(String.format("Exception in thread %s", t.getName())); e.printStackTrace(); } @Override public void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); if(e.getActionCommand().trim().equalsIgnoreCase("Capture")) { try { String path = new File("").getAbsolutePath(); System.out.println(path); File file = new File(Common.getTempPath()+Common.getSeparator()+String.format("image-%d.jpg", System.currentTimeMillis())); ImageIO.write(webcam.getImage(), "JPG", file); imagePath = file.getAbsolutePath(); System.out.println("Image saved in " + imagePath); MainFrame.setImageURL(imagePath); EmployeeManipulationFrame.imagePath = imagePath; //CropImage cropFrame = new CropImage(); // cropFrame.start(imagePath,emf); ResizableComponent rc = new ResizableComponent(imagePath,emf); rc.setAlwaysOnTop(true); rc.setVisible(true); //JFrameCamPicture imagePanel = new JFrameCamPicture(imagePath,mainFrame,emf); // imagePanel.setVisible(true); // imagePanel.pack(); this.dispose(); } catch (IOException e1) { e1.printStackTrace(); } } } }
UTF-8
Java
7,102
java
WebCamFunctionalPanel.java
Java
[ { "context": "andle webcam video stream from Java\n * \n * @author Bartosz Firyn (SarXos)\n */\npublic class WebCamFunctionalPanel e", "end": 1072, "score": 0.9998898506164551, "start": 1059, "tag": "NAME", "value": "Bartosz Firyn" }, { "context": "eo stream from Java\n * \n * @autho...
null
[]
package com.empmanagement.screens; import com.employeemanagement.common.Common; import com.employeemanagement.utility.CropImage; import com.empmanagement.testswing.ResizableComponent; import java.awt.BorderLayout; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.lang.Thread.UncaughtExceptionHandler; import javax.swing.JFrame; import javax.swing.SwingUtilities; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamEvent; import com.github.sarxos.webcam.WebcamListener; import com.github.sarxos.webcam.WebcamPanel; import com.github.sarxos.webcam.WebcamPicker; import com.github.sarxos.webcam.WebcamResolution; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * Proof of concept of how to handle webcam video stream from Java * * @author <NAME> (SarXos) */ public class WebCamFunctionalPanel extends JFrame implements Runnable, ActionListener, WebcamListener, WindowListener, UncaughtExceptionHandler{ private static final long serialVersionUID = 1L; private Webcam webcam = null; private WebcamPanel panel = null; private WebcamPicker picker = null; private JButton capture = null; private String imagePath = ""; Thread t; static MainFrame mainFrame; static EmployeeManipulationFrame emf; public WebCamFunctionalPanel(MainFrame mainFrame,EmployeeManipulationFrame emf){ this.mainFrame = mainFrame; this.emf = emf; } @Override public void run() { setTitle("Capture Your Picture"); setDefaultCloseOperation(WebCamFunctionalPanel.DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); addWindowListener(this); setLocation(200,50); this.setResizable(false); picker = new WebcamPicker(); picker.disable(); webcam = picker.getSelectedWebcam(); if (webcam == null) { // System.out.println("No webcams found..."); // System.exit(1); // this.dispose(); JFrame j = new JFrame(); j.setAlwaysOnTop(true); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); j.setVisible(false); JOptionPane.showMessageDialog(j, "No Camera found!!!", "", JOptionPane.INFORMATION_MESSAGE); } else { webcam.setViewSize(WebcamResolution.VGA.getSize()); webcam.addWebcamListener(WebCamFunctionalPanel.this); panel = new WebcamPanel(webcam, false); panel.setFPSDisplayed(true); ImageIcon icon = new ImageIcon(getClass().getResource("/com/empmanagement/screens/capture.png")); capture = new JButton("Capture"); capture.setIcon(icon); //capture.setSize(getContentPane().getWidth(),500); capture.addActionListener(this); add(picker, BorderLayout.NORTH); JPanel jp = new JPanel(); jp.add(capture); //add(capture,BorderLayout.SOUTH); add(jp,BorderLayout.SOUTH); add(panel, BorderLayout.CENTER); pack(); setVisible(true); Thread t = new Thread() { @Override public void run() { panel.start(); } }; t.setName("example-starter"); t.setDaemon(true); t.setUncaughtExceptionHandler(this); t.start(); } } @Override public void webcamOpen(WebcamEvent we) { System.out.println("webcam open"); } @Override public void webcamClosed(WebcamEvent we) { System.out.println("webcam closed"); } @Override public void webcamDisposed(WebcamEvent we) { System.out.println("webcam disposed"); } @Override public void webcamImageObtained(WebcamEvent we) { // do nothing } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { webcam.close(); } @Override public void windowClosing(WindowEvent e) { MainFrame.setImageURL(imagePath); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { System.out.println("webcam viewer resumed"); panel.resume(); } @Override public void windowIconified(WindowEvent e) { System.out.println("webcam viewer paused"); panel.pause(); } @Override public void uncaughtException(Thread t, Throwable e) { System.err.println(String.format("Exception in thread %s", t.getName())); e.printStackTrace(); } @Override public void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); if(e.getActionCommand().trim().equalsIgnoreCase("Capture")) { try { String path = new File("").getAbsolutePath(); System.out.println(path); File file = new File(Common.getTempPath()+Common.getSeparator()+String.format("image-%d.jpg", System.currentTimeMillis())); ImageIO.write(webcam.getImage(), "JPG", file); imagePath = file.getAbsolutePath(); System.out.println("Image saved in " + imagePath); MainFrame.setImageURL(imagePath); EmployeeManipulationFrame.imagePath = imagePath; //CropImage cropFrame = new CropImage(); // cropFrame.start(imagePath,emf); ResizableComponent rc = new ResizableComponent(imagePath,emf); rc.setAlwaysOnTop(true); rc.setVisible(true); //JFrameCamPicture imagePanel = new JFrameCamPicture(imagePath,mainFrame,emf); // imagePanel.setVisible(true); // imagePanel.pack(); this.dispose(); } catch (IOException e1) { e1.printStackTrace(); } } } }
7,095
0.565052
0.563362
228
30.149122
25.333818
145
false
false
0
0
0
0
0
0
0.850877
false
false
5
a11945e67c404cd6590cb21f05e3442d681b0d55
20,349,555,051,955
373f60bbae56e2471e7e23b24393d10bc024d7b1
/sigasr/app/models/DadosRH.java
958b5dda783002105c38301ad9063c2692d95f85
[]
no_license
ggamaral90/siga
https://github.com/ggamaral90/siga
e2aba1259611e1f079ad19f006c306f6679c58e1
0dcf7ebe702dc36e71fbea9b57cd2b15546cb593
refs/heads/migracao-jboss6-vraptor-db1
2020-12-14T07:24:08.159000
2015-05-20T11:57:05
2015-05-20T11:57:05
28,591,632
1
0
null
true
2015-04-09T18:56:43
2014-12-29T12:32:22
2015-04-09T18:33:51
2015-04-09T18:56:43
259,969
1
0
0
HTML
null
null
package models; import java.sql.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import play.db.jpa.GenericModel; @Entity @Table(name = "DADOS_RH", schema = "SIGARH") public class DadosRH extends GenericModel { @Id public Long pessoa_id; public String pessoa_cpf; public String pessoa_nome; public String pessoa_sexo; public Date pessoa_data_nascimento; public String pessoa_rua; public String pessoa_bairro; public String pessoa_cidade; public String pessoa_uf; public String pessoa_cep; public Long pessoa_matricula; public Date pessoa_data_inicio_exercicio; public String pessoa_ato_nomeacao; public Date pessoa_data_nomeacao; public Date pessoa_dt_publ_nomeacao; public Date pessoa_data_posse; public String pessoa_padrao_referencia; public Integer pessoa_situacao; public String pessoa_rg; public String pessoa_rg_orgao; public String pessoa_rg_uf; public Date pessoa_data_expedicao_rg; public Integer pessoa_estado_civil; private String pessoa_grau_de_instrucao; public String pessoa_sigla; public String pessoa_email; public String tipo_rh; public String pessoa_tp_sanguineo; public String pessoa_naturalidade; public String pessoa_nacionalidade; public Long cargo_id; public String cargo_nome; public String cargo_sigla; public Long funcao_id; public String funcao_nome; public String funcao_sigla; @Id public Long lotacao_id; public String lotacao_nome; public String lotacao_sigla; public Long lotacao_id_pai; public String lotacao_tipo; public String lotacao_tipo_papel; public Long papel_id; // public Long orgao_usu_id; public class Pessoa { public Long pessoa_id; public String pessoa_cpf; public String pessoa_nome; public String pessoa_sexo; public Date pessoa_data_nascimento; public String pessoa_rua; public String pessoa_bairro; public String pessoa_cidade; public String pessoa_uf; public String pessoa_cep; public Long pessoa_matricula; public Date pessoa_data_inicio_exercicio; public String pessoa_ato_nomeacao; public Date pessoa_data_nomeacao; public Date pessoa_dt_publ_nomeacao; public Date pessoa_data_posse; public String pessoa_padrao_referencia; public Integer pessoa_situacao; public String pessoa_rg; public String pessoa_rg_orgao; public String pessoa_rg_uf; public Date pessoa_data_expedicao_rg; public Integer pessoa_estado_civil; public String pessoa_grau_de_instrucao; public String pessoa_sigla; public String pessoa_email; public String tipo_rh; public String pessoa_tp_sanguineo; public String pessoa_naturalidade; public String pessoa_nacionalidade; public Long cargo_id; public Long funcao_id; public Long lotacao_id; public String lotacao_tipo_papel; } public class Cargo { public Long cargo_id; public String cargo_nome; public String cargo_sigla; } public class Funcao { public Long funcao_id; public String funcao_nome; public String funcao_sigla; } public class Lotacao { public Long lotacao_id; public String lotacao_nome; public String lotacao_sigla; public Long lotacao_id_pai; public String lotacao_tipo; public String lotacao_tipo_papel; } public class Papel { public Long papel_id; public Long papel_lotacao_id; public Long papel_cargo_id; public Long papel_funcao_id; public String papel_lotacao_tipo; public Long papel_pessoa_id; } public class Orgao { public Long orgao_usu_id; } public Pessoa getPessoa() { if (pessoa_id == null) return null; Pessoa o = new Pessoa(); o.pessoa_id = pessoa_id; o.pessoa_nome = pessoa_nome; o.pessoa_cpf = pessoa_cpf; o.pessoa_sexo = pessoa_sexo; o.pessoa_data_nascimento = pessoa_data_nascimento; o.pessoa_rua = pessoa_rua; o.pessoa_bairro = pessoa_bairro; o.pessoa_cidade = pessoa_cidade; o.pessoa_uf = pessoa_uf; o.pessoa_cep = pessoa_cep; o.pessoa_matricula = pessoa_matricula; o.pessoa_data_inicio_exercicio = pessoa_data_inicio_exercicio; o.pessoa_ato_nomeacao = pessoa_ato_nomeacao; o.pessoa_data_nomeacao = pessoa_data_nomeacao; o.pessoa_dt_publ_nomeacao = pessoa_dt_publ_nomeacao; o.pessoa_data_posse = pessoa_data_posse; o.pessoa_padrao_referencia = pessoa_padrao_referencia; o.pessoa_situacao = pessoa_situacao; o.pessoa_rg = pessoa_rg; o.pessoa_rg_orgao = pessoa_rg_orgao; o.pessoa_rg_uf = pessoa_rg_uf; o.pessoa_data_expedicao_rg = pessoa_data_expedicao_rg; o.pessoa_estado_civil = pessoa_estado_civil; o.pessoa_grau_de_instrucao = pessoa_grau_de_instrucao; o.pessoa_sigla = pessoa_sigla; o.pessoa_email = pessoa_email; o.tipo_rh = tipo_rh; o.pessoa_tp_sanguineo = pessoa_tp_sanguineo; o.pessoa_naturalidade = pessoa_naturalidade; o.pessoa_nacionalidade = pessoa_nacionalidade; o.cargo_id = cargo_id; o.funcao_id = funcao_id; o.lotacao_id = lotacao_id; o.lotacao_tipo_papel = lotacao_tipo_papel; return o; } public Cargo getCargo() { if (cargo_id == null) return null; Cargo o = new Cargo(); o.cargo_id = cargo_id; o.cargo_nome = cargo_nome; o.cargo_sigla = cargo_sigla; return o; } public Funcao getFuncao() { if (funcao_id == null) return null; Funcao o = new Funcao(); o.funcao_id = funcao_id; o.funcao_nome = funcao_nome; o.funcao_sigla = funcao_sigla; return o; } public Lotacao getLotacao() { if (lotacao_id == null) return null; Lotacao o = new Lotacao(); o.lotacao_id = lotacao_id; o.lotacao_nome = lotacao_nome; o.lotacao_sigla = lotacao_sigla; o.lotacao_id_pai = lotacao_id_pai; o.lotacao_tipo = lotacao_tipo; o.lotacao_tipo_papel = lotacao_tipo_papel; return o; } public Papel getPapel() { if (papel_id == null) return null; Papel o = new Papel(); o.papel_pessoa_id = pessoa_id; o.papel_id = papel_id; o.papel_lotacao_id = lotacao_id; o.papel_cargo_id = cargo_id; o.papel_funcao_id = funcao_id; o.papel_lotacao_tipo = lotacao_tipo_papel; return o; } public Orgao getOrgao() { Orgao org = new Orgao(); // org.orgao_usu_id = orgao_usu_id; return org; } }
UTF-8
Java
6,293
java
DadosRH.java
Java
[ { "context": "();\r\n\t\to.pessoa_id = pessoa_id;\r\n\t\to.pessoa_nome = pessoa_nome;\r\n\t\to.pessoa_cpf = pessoa_cpf;\r\n\t\to.pessoa_s", "end": 3749, "score": 0.7012475728988647, "start": 3743, "tag": "NAME", "value": "pessoa" } ]
null
[]
package models; import java.sql.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import play.db.jpa.GenericModel; @Entity @Table(name = "DADOS_RH", schema = "SIGARH") public class DadosRH extends GenericModel { @Id public Long pessoa_id; public String pessoa_cpf; public String pessoa_nome; public String pessoa_sexo; public Date pessoa_data_nascimento; public String pessoa_rua; public String pessoa_bairro; public String pessoa_cidade; public String pessoa_uf; public String pessoa_cep; public Long pessoa_matricula; public Date pessoa_data_inicio_exercicio; public String pessoa_ato_nomeacao; public Date pessoa_data_nomeacao; public Date pessoa_dt_publ_nomeacao; public Date pessoa_data_posse; public String pessoa_padrao_referencia; public Integer pessoa_situacao; public String pessoa_rg; public String pessoa_rg_orgao; public String pessoa_rg_uf; public Date pessoa_data_expedicao_rg; public Integer pessoa_estado_civil; private String pessoa_grau_de_instrucao; public String pessoa_sigla; public String pessoa_email; public String tipo_rh; public String pessoa_tp_sanguineo; public String pessoa_naturalidade; public String pessoa_nacionalidade; public Long cargo_id; public String cargo_nome; public String cargo_sigla; public Long funcao_id; public String funcao_nome; public String funcao_sigla; @Id public Long lotacao_id; public String lotacao_nome; public String lotacao_sigla; public Long lotacao_id_pai; public String lotacao_tipo; public String lotacao_tipo_papel; public Long papel_id; // public Long orgao_usu_id; public class Pessoa { public Long pessoa_id; public String pessoa_cpf; public String pessoa_nome; public String pessoa_sexo; public Date pessoa_data_nascimento; public String pessoa_rua; public String pessoa_bairro; public String pessoa_cidade; public String pessoa_uf; public String pessoa_cep; public Long pessoa_matricula; public Date pessoa_data_inicio_exercicio; public String pessoa_ato_nomeacao; public Date pessoa_data_nomeacao; public Date pessoa_dt_publ_nomeacao; public Date pessoa_data_posse; public String pessoa_padrao_referencia; public Integer pessoa_situacao; public String pessoa_rg; public String pessoa_rg_orgao; public String pessoa_rg_uf; public Date pessoa_data_expedicao_rg; public Integer pessoa_estado_civil; public String pessoa_grau_de_instrucao; public String pessoa_sigla; public String pessoa_email; public String tipo_rh; public String pessoa_tp_sanguineo; public String pessoa_naturalidade; public String pessoa_nacionalidade; public Long cargo_id; public Long funcao_id; public Long lotacao_id; public String lotacao_tipo_papel; } public class Cargo { public Long cargo_id; public String cargo_nome; public String cargo_sigla; } public class Funcao { public Long funcao_id; public String funcao_nome; public String funcao_sigla; } public class Lotacao { public Long lotacao_id; public String lotacao_nome; public String lotacao_sigla; public Long lotacao_id_pai; public String lotacao_tipo; public String lotacao_tipo_papel; } public class Papel { public Long papel_id; public Long papel_lotacao_id; public Long papel_cargo_id; public Long papel_funcao_id; public String papel_lotacao_tipo; public Long papel_pessoa_id; } public class Orgao { public Long orgao_usu_id; } public Pessoa getPessoa() { if (pessoa_id == null) return null; Pessoa o = new Pessoa(); o.pessoa_id = pessoa_id; o.pessoa_nome = pessoa_nome; o.pessoa_cpf = pessoa_cpf; o.pessoa_sexo = pessoa_sexo; o.pessoa_data_nascimento = pessoa_data_nascimento; o.pessoa_rua = pessoa_rua; o.pessoa_bairro = pessoa_bairro; o.pessoa_cidade = pessoa_cidade; o.pessoa_uf = pessoa_uf; o.pessoa_cep = pessoa_cep; o.pessoa_matricula = pessoa_matricula; o.pessoa_data_inicio_exercicio = pessoa_data_inicio_exercicio; o.pessoa_ato_nomeacao = pessoa_ato_nomeacao; o.pessoa_data_nomeacao = pessoa_data_nomeacao; o.pessoa_dt_publ_nomeacao = pessoa_dt_publ_nomeacao; o.pessoa_data_posse = pessoa_data_posse; o.pessoa_padrao_referencia = pessoa_padrao_referencia; o.pessoa_situacao = pessoa_situacao; o.pessoa_rg = pessoa_rg; o.pessoa_rg_orgao = pessoa_rg_orgao; o.pessoa_rg_uf = pessoa_rg_uf; o.pessoa_data_expedicao_rg = pessoa_data_expedicao_rg; o.pessoa_estado_civil = pessoa_estado_civil; o.pessoa_grau_de_instrucao = pessoa_grau_de_instrucao; o.pessoa_sigla = pessoa_sigla; o.pessoa_email = pessoa_email; o.tipo_rh = tipo_rh; o.pessoa_tp_sanguineo = pessoa_tp_sanguineo; o.pessoa_naturalidade = pessoa_naturalidade; o.pessoa_nacionalidade = pessoa_nacionalidade; o.cargo_id = cargo_id; o.funcao_id = funcao_id; o.lotacao_id = lotacao_id; o.lotacao_tipo_papel = lotacao_tipo_papel; return o; } public Cargo getCargo() { if (cargo_id == null) return null; Cargo o = new Cargo(); o.cargo_id = cargo_id; o.cargo_nome = cargo_nome; o.cargo_sigla = cargo_sigla; return o; } public Funcao getFuncao() { if (funcao_id == null) return null; Funcao o = new Funcao(); o.funcao_id = funcao_id; o.funcao_nome = funcao_nome; o.funcao_sigla = funcao_sigla; return o; } public Lotacao getLotacao() { if (lotacao_id == null) return null; Lotacao o = new Lotacao(); o.lotacao_id = lotacao_id; o.lotacao_nome = lotacao_nome; o.lotacao_sigla = lotacao_sigla; o.lotacao_id_pai = lotacao_id_pai; o.lotacao_tipo = lotacao_tipo; o.lotacao_tipo_papel = lotacao_tipo_papel; return o; } public Papel getPapel() { if (papel_id == null) return null; Papel o = new Papel(); o.papel_pessoa_id = pessoa_id; o.papel_id = papel_id; o.papel_lotacao_id = lotacao_id; o.papel_cargo_id = cargo_id; o.papel_funcao_id = funcao_id; o.papel_lotacao_tipo = lotacao_tipo_papel; return o; } public Orgao getOrgao() { Orgao org = new Orgao(); // org.orgao_usu_id = orgao_usu_id; return org; } }
6,293
0.702368
0.702368
225
25.968889
13.016705
64
false
false
0
0
0
0
0
0
2.262222
false
false
5
be23418f12ca7eccde1ad4d2c97e5b967a724d3a
32,014,686,245,015
9e80c2a79569e503867cf547f3b2a467ff9756e1
/Day2/TrainingRESTAPI/src/main/java/org/tektutor/TrainingService.java
e56d49246ac42e995cd48af4db9ede002469e98d
[]
no_license
tektutor/bdd-pune-april-2019
https://github.com/tektutor/bdd-pune-april-2019
98ab7c1b5175e7e51b2e7a362f1072688a7bac5a
f1161373e3ea3768dc1e6bc42c8ab2f3a6613fe1
refs/heads/master
2020-05-09T22:22:31.787000
2019-04-17T11:16:58
2019-04-17T11:16:58
181,469,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.tektutor; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; public class TrainingService { public ArrayList<Training> getAllTrainings( ) { ArrayList<Training> listOfTrainings = new ArrayList<Training>(); String sqlQuery = "select * from training"; Training training; try { Connection connection = new DatabaseConnectionManager().getConnection(); PreparedStatement statement = connection.prepareStatement(sqlQuery); ResultSet rs = statement.executeQuery(); while ( rs.next() ) { training = new Training(); training.setId( rs.getInt(1) ); training.setName ( rs.getString(2) ); training.setDuration( rs.getString(3) ); listOfTrainings.add ( training ); } } catch ( Exception e) { e.printStackTrace(); } return listOfTrainings; } }
UTF-8
Java
1,072
java
TrainingService.java
Java
[]
null
[]
package org.tektutor; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; public class TrainingService { public ArrayList<Training> getAllTrainings( ) { ArrayList<Training> listOfTrainings = new ArrayList<Training>(); String sqlQuery = "select * from training"; Training training; try { Connection connection = new DatabaseConnectionManager().getConnection(); PreparedStatement statement = connection.prepareStatement(sqlQuery); ResultSet rs = statement.executeQuery(); while ( rs.next() ) { training = new Training(); training.setId( rs.getInt(1) ); training.setName ( rs.getString(2) ); training.setDuration( rs.getString(3) ); listOfTrainings.add ( training ); } } catch ( Exception e) { e.printStackTrace(); } return listOfTrainings; } }
1,072
0.58209
0.579291
43
23.953489
22.915369
81
false
false
0
0
0
0
0
0
0.418605
false
false
5
46a77ab1915e8a174b4f1f7e8392afde3a9c6169
17,145,509,484,743
53f82260ed75101e2c8e236039c452441ffbc5c9
/src/main/java/com/travel/dao/impl/DocumentDaoImpl.java
413489de94d68c84c90a5b6b5cd0604aad52254c
[]
no_license
renderlife/travel-spring-hibernate
https://github.com/renderlife/travel-spring-hibernate
f5859d8c00e58af6b6f6c60fb57e47c54ad63e76
d326873d3ace9cac7f170105ea2003142c17ae8a
refs/heads/master
2021-12-12T09:50:33.098000
2016-12-28T19:04:54
2016-12-28T19:04:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.travel.dao.impl; import com.travel.dao.DocumentDao; import com.travel.dao.AbstractDao; import com.travel.model.DocumentClient; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class DocumentDaoImpl extends AbstractDao<Integer, DocumentClient> implements DocumentDao { @SuppressWarnings("unchecked") public List<DocumentClient> findAll() { Criteria crit = createEntityCriteria(); return (List<DocumentClient>)crit.list(); } public void save(DocumentClient document) { persist(document); } public DocumentClient findById(int id) { return getByKey(id); } @SuppressWarnings("unchecked") public List<DocumentClient> findAllByUserId(int idClient){ Criteria crit = createEntityCriteria(); Criteria userCriteria = crit.createCriteria("client"); userCriteria.add(Restrictions.eq("idClient", idClient)); return (List<DocumentClient>)crit.list(); } public void deleteById(int id) { DocumentClient document = getByKey(id); delete(document); } }
UTF-8
Java
1,204
java
DocumentDaoImpl.java
Java
[]
null
[]
package com.travel.dao.impl; import com.travel.dao.DocumentDao; import com.travel.dao.AbstractDao; import com.travel.model.DocumentClient; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class DocumentDaoImpl extends AbstractDao<Integer, DocumentClient> implements DocumentDao { @SuppressWarnings("unchecked") public List<DocumentClient> findAll() { Criteria crit = createEntityCriteria(); return (List<DocumentClient>)crit.list(); } public void save(DocumentClient document) { persist(document); } public DocumentClient findById(int id) { return getByKey(id); } @SuppressWarnings("unchecked") public List<DocumentClient> findAllByUserId(int idClient){ Criteria crit = createEntityCriteria(); Criteria userCriteria = crit.createCriteria("client"); userCriteria.add(Restrictions.eq("idClient", idClient)); return (List<DocumentClient>)crit.list(); } public void deleteById(int id) { DocumentClient document = getByKey(id); delete(document); } }
1,204
0.711794
0.711794
44
26.363636
23.646152
98
false
false
0
0
0
0
0
0
0.454545
false
false
5
ec8a787bf9a1893dfc263aaa6dda8ac2994ab02c
17,145,509,487,784
181480d9a1f6d12dddde318db376932b553f6396
/src/main/java/com/mason/game/task/manager/TaskUpdateMode.java
9cc02f0484905211273c8fe36338d2a227fb1c7e
[]
no_license
MasonEcnu/GameModule
https://github.com/MasonEcnu/GameModule
f4c217525c9bf7b14afcc18bafdc687d13466e2d
b51f4e1429c4c3b44e1f7e3678fe5333da827301
refs/heads/master
2020-11-24T18:26:05.895000
2020-08-05T07:07:24
2020-08-05T07:07:24
228,288,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mason.game.task.manager; /** * Created by mwu on 2019/12/16 * 任务更新模式 */ public enum TaskUpdateMode { ADD, // 累加 CHECK, // 检查 COVER // 覆盖 }
UTF-8
Java
193
java
TaskUpdateMode.java
Java
[ { "context": "ge com.mason.game.task.manager;\n\n/**\n * Created by mwu on 2019/12/16\n * 任务更新模式\n */\npublic enum TaskUpdat", "end": 59, "score": 0.9996317625045776, "start": 56, "tag": "USERNAME", "value": "mwu" } ]
null
[]
package com.mason.game.task.manager; /** * Created by mwu on 2019/12/16 * 任务更新模式 */ public enum TaskUpdateMode { ADD, // 累加 CHECK, // 检查 COVER // 覆盖 }
193
0.597633
0.550296
11
14.363636
12.107644
36
false
false
0
0
0
0
0
0
0.272727
false
false
5
aa577a792561721e7efa4db11fb12ce797e5c4ef
2,516,850,848,326
f7fac67835a6d6baef4a4e835eedb92d7a1db0ed
/FREIND_MANAGEMENT/friend-management-service/src/main/java/com/cg/fm/exception/EmailRegisterRepeatedApiException.java
cd591607ab0263b75a6295ddc6cf1662ce348e56
[]
no_license
pradeepkrathnayaka/Microservices_POC
https://github.com/pradeepkrathnayaka/Microservices_POC
8abadc28ac067dbd9cdf4909117fa383b55cc681
b56efe6b27f2e8687a168d7d87b5e7a78dc45885
refs/heads/master
2021-05-24T15:37:41.562000
2020-04-14T02:46:31
2020-04-14T02:46:31
253,634,806
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.fm.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.CONFLICT) public class EmailRegisterRepeatedApiException extends ApiException { private static final long serialVersionUID = 1L; public static final String CODE = "903"; public EmailRegisterRepeatedApiException() { super(CODE); } public EmailRegisterRepeatedApiException(String userOneEmail, String userTwoEmail) { super(CODE); } }
UTF-8
Java
530
java
EmailRegisterRepeatedApiException.java
Java
[]
null
[]
package com.cg.fm.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.CONFLICT) public class EmailRegisterRepeatedApiException extends ApiException { private static final long serialVersionUID = 1L; public static final String CODE = "903"; public EmailRegisterRepeatedApiException() { super(CODE); } public EmailRegisterRepeatedApiException(String userOneEmail, String userTwoEmail) { super(CODE); } }
530
0.779245
0.771698
20
24.6
26.61278
85
false
false
0
0
0
0
0
0
0.95
false
false
5
58fc3e116592dab0fcd58c118ae870e96f73c20a
33,277,406,671,097
cf548f5a69550a4fb4da3d52bf42279ff4bf9997
/src/main/java/de/exfy/tacticalisland/TacticalIsland.java
898ef7440d5276447ac3580375639b752fc595a4
[ "Apache-2.0" ]
permissive
Exfynation/ExfyTacticalIsland
https://github.com/Exfynation/ExfyTacticalIsland
3730a1a2462cad7e85c4cae14547051198ca402d
e87226bb75ebf35a988e9ae21f6d2f07a3be29ec
refs/heads/master
2020-04-08T13:00:48.954000
2018-11-27T17:09:14
2018-11-27T17:09:14
159,371,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.exfy.tacticalisland; import com.sk89q.intake.Intake; import de.exfy.core.ExfyCore; import de.exfy.core.modules.intake.IntakeModule; import de.exfy.tacticalisland.commands.ForceMapCommand; import de.exfy.tacticalisland.commands.PointsCommand; import de.exfy.tacticalisland.commands.SetSpawnCommand; import de.exfy.tacticalisland.commands.SetTowerCommand; import de.exfy.tacticalisland.helper.PointsManager; import de.exfy.tacticalisland.helper.RewardManager; import de.exfy.tacticalisland.helper.ScoreboardManager; import de.exfy.tacticalisland.helper.TowerManager; import de.exfy.tacticalisland.inventory.TeamShop; import de.exfy.tacticalisland.listener.*; import de.exfy.tacticalisland.maps.MapManager; import de.exfy.tacticalisland.teams.TeamManager; import org.bukkit.Bukkit; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashSet; import java.util.Set; public class TacticalIsland extends JavaPlugin { private static final String GAME_PREFIX = "§aTacticalIsland §8➟ §7"; private static PointsManager pointsManager; private static TeamManager teamManager; private static ScoreboardManager scoreboardManager; private static TowerManager towerManager; private static MapManager mapManager; private RewardManager rewardManager; //private static ChestManager chestManager; private Set<Listener> listeners = new HashSet<>(); private static TacticalIsland instance; @Override public void onEnable() { instance = this; System.out.println(ExfyCore.getPrefix() + "Tactical Island wurde aktiviert."); IntakeModule.getCommandGraph().commands() .registerMethods(new ForceMapCommand()) .registerMethods(new SetSpawnCommand()) .registerMethods(new PointsCommand()) .registerMethods(new SetTowerCommand()); pointsManager = new PointsManager(); rewardManager = new RewardManager(); rewardManager.setReward(100); teamManager = new TeamManager(); scoreboardManager = new ScoreboardManager(); towerManager = new TowerManager(rewardManager); mapManager = new MapManager(); listeners.add(new ChestListener()); listeners.add(new ChatListener()); listeners.add(new ConnectionListener()); listeners.add(new DeathListener()); listeners.add(new InteractListener()); listeners.add(new PlayerActions()); listeners.add(new TeamShop()); listeners.add(new ShopItems()); listeners.forEach(l -> Bukkit.getPluginManager().registerEvents(l, ExfyCore.getInstance())); if(Bukkit.getOnlinePlayers().size() > 0 && !towerManager.isIdling()) towerManager.startIdle(); //ExfyCloud.setCustomNameFormat("TacticalIsland"); } public static String getGamePrefix() { return GAME_PREFIX; } @Override public void onDisable() { System.out.println(ExfyCore.getPrefix() + "Tactical Island wurde deaktiviert."); } public static PointsManager getPointsManager() { return pointsManager; } public static TeamManager getTeamManager() { return teamManager; } public static TacticalIsland getInstance() { return instance; } public static ScoreboardManager getScoreboardManager() { return scoreboardManager; } public static TowerManager getTowerManager() { return towerManager; } public static MapManager getMapManager() { return mapManager; } }
UTF-8
Java
3,611
java
TacticalIsland.java
Java
[]
null
[]
package de.exfy.tacticalisland; import com.sk89q.intake.Intake; import de.exfy.core.ExfyCore; import de.exfy.core.modules.intake.IntakeModule; import de.exfy.tacticalisland.commands.ForceMapCommand; import de.exfy.tacticalisland.commands.PointsCommand; import de.exfy.tacticalisland.commands.SetSpawnCommand; import de.exfy.tacticalisland.commands.SetTowerCommand; import de.exfy.tacticalisland.helper.PointsManager; import de.exfy.tacticalisland.helper.RewardManager; import de.exfy.tacticalisland.helper.ScoreboardManager; import de.exfy.tacticalisland.helper.TowerManager; import de.exfy.tacticalisland.inventory.TeamShop; import de.exfy.tacticalisland.listener.*; import de.exfy.tacticalisland.maps.MapManager; import de.exfy.tacticalisland.teams.TeamManager; import org.bukkit.Bukkit; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashSet; import java.util.Set; public class TacticalIsland extends JavaPlugin { private static final String GAME_PREFIX = "§aTacticalIsland §8➟ §7"; private static PointsManager pointsManager; private static TeamManager teamManager; private static ScoreboardManager scoreboardManager; private static TowerManager towerManager; private static MapManager mapManager; private RewardManager rewardManager; //private static ChestManager chestManager; private Set<Listener> listeners = new HashSet<>(); private static TacticalIsland instance; @Override public void onEnable() { instance = this; System.out.println(ExfyCore.getPrefix() + "Tactical Island wurde aktiviert."); IntakeModule.getCommandGraph().commands() .registerMethods(new ForceMapCommand()) .registerMethods(new SetSpawnCommand()) .registerMethods(new PointsCommand()) .registerMethods(new SetTowerCommand()); pointsManager = new PointsManager(); rewardManager = new RewardManager(); rewardManager.setReward(100); teamManager = new TeamManager(); scoreboardManager = new ScoreboardManager(); towerManager = new TowerManager(rewardManager); mapManager = new MapManager(); listeners.add(new ChestListener()); listeners.add(new ChatListener()); listeners.add(new ConnectionListener()); listeners.add(new DeathListener()); listeners.add(new InteractListener()); listeners.add(new PlayerActions()); listeners.add(new TeamShop()); listeners.add(new ShopItems()); listeners.forEach(l -> Bukkit.getPluginManager().registerEvents(l, ExfyCore.getInstance())); if(Bukkit.getOnlinePlayers().size() > 0 && !towerManager.isIdling()) towerManager.startIdle(); //ExfyCloud.setCustomNameFormat("TacticalIsland"); } public static String getGamePrefix() { return GAME_PREFIX; } @Override public void onDisable() { System.out.println(ExfyCore.getPrefix() + "Tactical Island wurde deaktiviert."); } public static PointsManager getPointsManager() { return pointsManager; } public static TeamManager getTeamManager() { return teamManager; } public static TacticalIsland getInstance() { return instance; } public static ScoreboardManager getScoreboardManager() { return scoreboardManager; } public static TowerManager getTowerManager() { return towerManager; } public static MapManager getMapManager() { return mapManager; } }
3,611
0.71076
0.708541
111
31.477478
23.597544
100
false
false
0
0
0
0
0
0
0.54955
false
false
5
45b8ab7c8db7ed1dcc17ac3f89cd23dcfe6c1ea9
1,005,022,371,445
7cc68fef16e01d2b4a0447cabca541406b0f4434
/src/ch/hslu/prg2/semesterprojekt/controlling/GameController.java
30e140bef4c267bee84aa307d3488f9d7da68315
[]
no_license
eulor/ConnectFour
https://github.com/eulor/ConnectFour
5dd60f31336f7d78bc6875d26bb9229351e8a261
4cfdecf8cb243039c46a53389de8eb414dd5b1ab
refs/heads/master
2018-05-19T10:22:11.238000
2015-05-05T18:12:52
2015-05-05T18:12:52
27,219,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.hslu.prg2.semesterprojekt.controlling; import ch.hslu.prg2.semesterprojekt.model.IBoard; import ch.hslu.prg2.semesterprojekt.model.IGameModelModifier; import ch.hslu.prg2.semesterprojekt.model.PlayerColor; public class GameController implements IPlayerActionController, IOpponentActionController { private final IGameModelModifier model; public GameController(IGameModelModifier model) { this.model = model; } @Override public void setStone(int column, PlayerColor player) { if(this.isValidTurn(column) && player == this.model.getCurrentPlayer() && !this.model.isGameOver()) { int row = this.getLowestFreeSpace(column); this.getGrid()[column][row] = this.model.getCurrentPlayer(); this.model.getBoard().setCurrentPlayer(this.getNextPlayer(player)); evaluateBoard(); } this.model.update(); } private void evaluateBoard() { IBoard board = this.model.getBoard(); WinnerAnalyzer analyzer = new WinnerAnalyzer(board); if (analyzer.isGameOver()) { board.setGameOver(); } board.setWinner(analyzer.getWinner()); } private PlayerColor getNextPlayer(PlayerColor player) { PlayerColor nextPlayer; if (player == PlayerColor.Red) { nextPlayer = PlayerColor.Yellow; } else { nextPlayer = PlayerColor.Red; } return nextPlayer; } private boolean isValidTurn(int columnIndex) { PlayerColor[] column = this.getGrid()[columnIndex]; boolean isValid = column[column.length - 1] == PlayerColor.None; return isValid; } private int getLowestFreeSpace(int columnIndex) { PlayerColor[] column = this.getGrid()[columnIndex]; int rowIndex = -1; int i = 0; while(rowIndex == -1 && i < column.length) { if(column[i] == PlayerColor.None) { rowIndex = i; } i++; } if (rowIndex == -1) { throw new RuntimeException("There is no free space in this column."); } return rowIndex; } @Override public void setUpdatedBoard(IBoard board, PlayerColor player) { if (player == this.model.getCurrentPlayer() && !this.model.isGameOver()) { this.model.setBoard(board); this.model.getBoard().setCurrentPlayer(this.getNextPlayer(player)); this.evaluateBoard(); } this.model.update(); } private PlayerColor[][] getGrid() { return this.model.getBoard().getGrid(); } @Override public void setResetBoard(IBoard board, PlayerColor player) { this.model.setBoard(board); this.model.getBoard().setCurrentPlayer(player); this.model.update(); } }
UTF-8
Java
3,013
java
GameController.java
Java
[]
null
[]
package ch.hslu.prg2.semesterprojekt.controlling; import ch.hslu.prg2.semesterprojekt.model.IBoard; import ch.hslu.prg2.semesterprojekt.model.IGameModelModifier; import ch.hslu.prg2.semesterprojekt.model.PlayerColor; public class GameController implements IPlayerActionController, IOpponentActionController { private final IGameModelModifier model; public GameController(IGameModelModifier model) { this.model = model; } @Override public void setStone(int column, PlayerColor player) { if(this.isValidTurn(column) && player == this.model.getCurrentPlayer() && !this.model.isGameOver()) { int row = this.getLowestFreeSpace(column); this.getGrid()[column][row] = this.model.getCurrentPlayer(); this.model.getBoard().setCurrentPlayer(this.getNextPlayer(player)); evaluateBoard(); } this.model.update(); } private void evaluateBoard() { IBoard board = this.model.getBoard(); WinnerAnalyzer analyzer = new WinnerAnalyzer(board); if (analyzer.isGameOver()) { board.setGameOver(); } board.setWinner(analyzer.getWinner()); } private PlayerColor getNextPlayer(PlayerColor player) { PlayerColor nextPlayer; if (player == PlayerColor.Red) { nextPlayer = PlayerColor.Yellow; } else { nextPlayer = PlayerColor.Red; } return nextPlayer; } private boolean isValidTurn(int columnIndex) { PlayerColor[] column = this.getGrid()[columnIndex]; boolean isValid = column[column.length - 1] == PlayerColor.None; return isValid; } private int getLowestFreeSpace(int columnIndex) { PlayerColor[] column = this.getGrid()[columnIndex]; int rowIndex = -1; int i = 0; while(rowIndex == -1 && i < column.length) { if(column[i] == PlayerColor.None) { rowIndex = i; } i++; } if (rowIndex == -1) { throw new RuntimeException("There is no free space in this column."); } return rowIndex; } @Override public void setUpdatedBoard(IBoard board, PlayerColor player) { if (player == this.model.getCurrentPlayer() && !this.model.isGameOver()) { this.model.setBoard(board); this.model.getBoard().setCurrentPlayer(this.getNextPlayer(player)); this.evaluateBoard(); } this.model.update(); } private PlayerColor[][] getGrid() { return this.model.getBoard().getGrid(); } @Override public void setResetBoard(IBoard board, PlayerColor player) { this.model.setBoard(board); this.model.getBoard().setCurrentPlayer(player); this.model.update(); } }
3,013
0.585463
0.582476
109
26.642202
24.768106
107
false
false
0
0
0
0
0
0
0.376147
false
false
5
94b4ee70c0ae79e474e1a99a69a91804a2369478
7,069,516,195,586
e475bb142d5e4d3cb9fdd8d9927674f27a199d78
/Hello.java
3d1c3c8b1b940c20d250443b3c6dc163e124ee37
[]
no_license
msdhina/AnalysisOfSensorData
https://github.com/msdhina/AnalysisOfSensorData
5b742b96015a7cfdc5ed9cf9598a06928c1e82f2
5a82af1143ed9035ecce4f2cd6c92dae459a0b7a
refs/heads/master
2020-03-18T19:56:49.008000
2018-05-28T16:49:42
2018-05-28T16:49:42
135,186,885
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mirror.bigdata; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; //import jdk.nashorn.internal.runtime.regexp.joni.SearchAlgorithm; //Plain old Java Object it does not extend as class or implements //an interface //The class registers its methods for the HTTP GET request using the @GET annotation. //Using the @Produces annotation, it defines that it can deliver several MIME types, //text, XML and HTML. //The browser requests per default the HTML MIME type. //Sets the path to base URL + /hello @Path("/hello") public class Hello { // This method is called if TEXT_PLAIN is request @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey 1"; } // This method is called if XML is request @GET @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>"; } // This method is called if HTML is request @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { testmongo(); return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + "Hello Jersey 2" + "</body></h1>" + "</html> "; } @POST @Path("/responsedata") @Consumes("application/json") public Response getData(String data) { JSONArray js = new JSONArray(); try{ System.out.println("Test 1"); MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("local"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("iot"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("type", "temperature"); //searchQuery.put("type", "pressure"); //searchQuery.put("type", "vibration"); DBCursor cursor = table.find(searchQuery); BasicDBObject obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery = new BasicDBObject(); searchQuery.put("type", "pressure"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery = new BasicDBObject(); searchQuery.put("type", "vibration"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); System.out.println(js.toString()); }catch(Exception e){ e.printStackTrace(); } JSONObject outputjs = new JSONObject(); try { outputjs.put("output", js); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(201).entity(outputjs.toString()).build(); } @POST @Path("/response") @Consumes("application/json") public Response getSpikeData(String data) { JSONArray js = new JSONArray(); try{ System.out.println("Test 1"); MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("local"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("spike"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("type", "temperature"); DBCursor cursor = table.find(searchQuery); BasicDBObject obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery.put("type", "pressure"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery.put("type", "vibration"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); System.out.println(js.toString()); }catch(Exception e){ e.printStackTrace(); } JSONObject outputjs = new JSONObject(); try { outputjs.put("output", js); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(201).entity(outputjs.toString()).build(); } @POST @Consumes("application/json") public Response startSimulation(String data) { System.out.println("Inside method"); String result = data; System.out.println("data : " + data); try { JSONObject input = new JSONObject(data); boolean voltage = input.getBoolean("voltage"); boolean pressure = input.getBoolean("pressure"); boolean current = input.getBoolean("current"); IoT.voltage = voltage; IoT.pressure = pressure; IoT.current = current; System.out.println("Voltage:" + voltage + "Pressure :" + pressure); System.out.println("Voltage:" + IoT.voltage + "Pressure :" + IoT.pressure); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(201).entity("data1").build(); } public void testmongo(){ try{ System.out.println("Test"); MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("local"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("iot"); BasicDBObject doc = new BasicDBObject("title", "MongoDB"). append("description", "database"). append("likes", 100). append("url", "http://www.tutorialspoint.com/mongodb/"). append("by", "tutorials point"); table.insert(doc); System.out.println("Document inserted successfully"); }catch(Exception e){ e.printStackTrace(); } } }
UTF-8
Java
8,621
java
Hello.java
Java
[]
null
[]
package com.mirror.bigdata; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; //import jdk.nashorn.internal.runtime.regexp.joni.SearchAlgorithm; //Plain old Java Object it does not extend as class or implements //an interface //The class registers its methods for the HTTP GET request using the @GET annotation. //Using the @Produces annotation, it defines that it can deliver several MIME types, //text, XML and HTML. //The browser requests per default the HTML MIME type. //Sets the path to base URL + /hello @Path("/hello") public class Hello { // This method is called if TEXT_PLAIN is request @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey 1"; } // This method is called if XML is request @GET @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>"; } // This method is called if HTML is request @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { testmongo(); return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + "Hello Jersey 2" + "</body></h1>" + "</html> "; } @POST @Path("/responsedata") @Consumes("application/json") public Response getData(String data) { JSONArray js = new JSONArray(); try{ System.out.println("Test 1"); MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("local"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("iot"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("type", "temperature"); //searchQuery.put("type", "pressure"); //searchQuery.put("type", "vibration"); DBCursor cursor = table.find(searchQuery); BasicDBObject obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery = new BasicDBObject(); searchQuery.put("type", "pressure"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery = new BasicDBObject(); searchQuery.put("type", "vibration"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); System.out.println(js.toString()); }catch(Exception e){ e.printStackTrace(); } JSONObject outputjs = new JSONObject(); try { outputjs.put("output", js); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(201).entity(outputjs.toString()).build(); } @POST @Path("/response") @Consumes("application/json") public Response getSpikeData(String data) { JSONArray js = new JSONArray(); try{ System.out.println("Test 1"); MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("local"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("spike"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("type", "temperature"); DBCursor cursor = table.find(searchQuery); BasicDBObject obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery.put("type", "pressure"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); searchQuery.put("type", "vibration"); cursor = table.find(searchQuery); obj = new BasicDBObject(); while (cursor.hasNext()) { // System.out.println(cursor.next()); obj = (BasicDBObject) cursor.next(); JSONObject out = new JSONObject(); out.put("type", obj.getString("type")); out.put("value", obj.getInt("value")); out.put("ts", obj.getDate("ts")); js.put(out); System.out.println(js.toString()); } cursor.close(); System.out.println(js.toString()); }catch(Exception e){ e.printStackTrace(); } JSONObject outputjs = new JSONObject(); try { outputjs.put("output", js); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(201).entity(outputjs.toString()).build(); } @POST @Consumes("application/json") public Response startSimulation(String data) { System.out.println("Inside method"); String result = data; System.out.println("data : " + data); try { JSONObject input = new JSONObject(data); boolean voltage = input.getBoolean("voltage"); boolean pressure = input.getBoolean("pressure"); boolean current = input.getBoolean("current"); IoT.voltage = voltage; IoT.pressure = pressure; IoT.current = current; System.out.println("Voltage:" + voltage + "Pressure :" + pressure); System.out.println("Voltage:" + IoT.voltage + "Pressure :" + IoT.pressure); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.status(201).entity("data1").build(); } public void testmongo(){ try{ System.out.println("Test"); MongoClient mongo = new MongoClient("localhost", 27017); /**** Get database ****/ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("local"); /**** Get collection / table from 'testdb' ****/ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("iot"); BasicDBObject doc = new BasicDBObject("title", "MongoDB"). append("description", "database"). append("likes", 100). append("url", "http://www.tutorialspoint.com/mongodb/"). append("by", "tutorials point"); table.insert(doc); System.out.println("Document inserted successfully"); }catch(Exception e){ e.printStackTrace(); } } }
8,621
0.609674
0.605498
365
21.621918
20.508858
86
false
false
0
0
0
0
0
0
2.616438
false
false
5
1f16f4c97258aa7f2815f4abe8487f58797fb697
28,948,079,594,295
03cac9c4c6d624784ee392726ee3e76f896d3b02
/app/src/main/java/com/chittikathalu/Activity/SplashActivity.java
3fe69ebe1976c741eb0ae50d35b4c0f5acf38b0e
[]
no_license
gvsharma/ChittiKathalu
https://github.com/gvsharma/ChittiKathalu
3c21f411658c671733c388746c02c13f7d5323d1
2493e2bd169feaf1507abf398a3f36092f82ecb0
refs/heads/master
2020-02-28T18:01:35.481000
2018-10-26T18:03:46
2018-10-26T18:03:46
38,633,394
0
0
null
false
2018-10-26T18:03:47
2015-07-06T17:05:10
2018-10-26T15:01:48
2018-10-26T18:03:47
213
0
0
0
Java
false
null
package com.chittikathalu.Activity; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.chittikathalu.R; public class SplashActivity extends AbstractActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); navigateToMainActivity(); } private void navigateToMainActivity() { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); }catch (InterruptedException e) { e.printStackTrace(); } finally { startScreen(MainActivity.class); } } }).start(); } }
UTF-8
Java
891
java
SplashActivity.java
Java
[]
null
[]
package com.chittikathalu.Activity; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.chittikathalu.R; public class SplashActivity extends AbstractActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); navigateToMainActivity(); } private void navigateToMainActivity() { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); }catch (InterruptedException e) { e.printStackTrace(); } finally { startScreen(MainActivity.class); } } }).start(); } }
891
0.590348
0.584736
36
23.75
18.517822
56
false
false
0
0
0
0
0
0
0.361111
false
false
5
72d1e60bb234da22018398be35f15694dd7480ef
31,988,916,446,266
7ec492a36d50577820a8b687bfa27f5aa4858267
/app/src/main/java/com/example/airvironment/MainActivity.java
0dc4addd80fd3b8e8bb61a89878a7f6b644c6d51
[]
no_license
miseljicAleksa/AIRvironment_rbt
https://github.com/miseljicAleksa/AIRvironment_rbt
2f1fc5d5f9b8ca9d23318269ea87a26f0cac2b06
eb1da6fb446f6bb56abcf37c6055230f0941ad1f
refs/heads/master
2020-06-24T17:22:58.983000
2019-07-26T14:53:24
2019-07-26T14:53:24
199,029,404
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.airvironment; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Telephony; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private TextView temperature; private TextView humidity; private TextView pollution; private TextView timestamp; private Button showHistory; private Button share; private Button showGraph; private BroadcastReceiver br; final Handler handler = new Handler(); ArrayList<MeasurementModel> storedMeasurements; private void testSmsPermission(){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 0); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); temperature = findViewById(R.id.tempVal); humidity = findViewById(R.id.humVal); pollution = findViewById(R.id.iaqVal); timestamp = findViewById(R.id.timestamp); showHistory = findViewById(R.id.button); share = findViewById(R.id.buttonShare); showGraph = findViewById(R.id.buttonGraph); testSmsPermission(); showGraph.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, ShowGraphActivity.class); Bundle b = new Bundle(); b.putParcelableArrayList("MeasurementHistory",MainActivity.this.storedMeasurements); intent.putExtra("MeasurementHistory", b); startActivity(intent); } }); showHistory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, ShowHistoryActivity.class); Bundle b = new Bundle(); b.putParcelableArrayList("MeasurementHistory",MainActivity.this.storedMeasurements); intent.putExtra("MeasurementHistory", b); startActivity(intent); } }); share.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); String toSend = storedMeasurements.size() != 0 ? storedMeasurements.get(storedMeasurements.size()-1).toString() : getLatestMeasurementFromSharedPref(); sendIntent.putExtra(Intent.EXTRA_TEXT,toSend); sendIntent.setType("text/plain"); if (sendIntent.resolveActivity(getPackageManager()) != null) { startActivity(sendIntent); } } }); storedMeasurements = new ArrayList<>(); } @Override protected void onPostResume() { super.onPostResume(); fetchData(); final Runnable fetcher = new Runnable() { @Override public void run() { fetchData(); handler.postDelayed(this,6000); } }; handler.postDelayed(fetcher,6000); br = new SmsReceiver(); IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION); this.registerReceiver(br, filter); } @Override protected void onPause() { super.onPause(); handler.removeCallbacksAndMessages(null); unregisterReceiver(br); } private void saveLatestMeasurement(String toSave){ SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(getString(R.string.app_name)+"LATEST_MEASUREMENT",toSave); editor.commit(); } private String getLatestMeasurementFromSharedPref(){ SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); String defaultValue = "ERROR"; return sharedPref.getString(getString(R.string.app_name)+"LATEST_MEASUREMENT", defaultValue); } private void fetchData(){ ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if(!isConnected){ String regex = "^MeasurementModel\\{temperature=(.*), humidity=(.*), pollution=(.*), timestamp=(.*)\\}$"; String stored = getLatestMeasurementFromSharedPref(); if(stored.equals("ERROR")){ temperature.setText("NA"); humidity.setText("NA"); pollution.setText("NA"); timestamp.setText("NA"); return; } Pattern p1=Pattern.compile(regex); Matcher m1=p1.matcher(stored); m1.find(); temperature.setText(m1.group(1)); humidity.setText(m1.group(2)); pollution.setText(m1.group(3)); timestamp.setText("Last time updated: "+m1.group(4)); return; } MeasurementApi service = RetrofitInstance.getRetrofitInstance().create(MeasurementApi.class); /** Call the method with parameter in the interface to get the notice data*/ Call<MeasurementModel> call = service.getLatestMeasurement(); /**Log the URL called*/ Log.wtf("URL Called", call.request().url() + ""); call.enqueue(new Callback<MeasurementModel>() { @Override public void onResponse(Call<MeasurementModel> call, Response<MeasurementModel> response) { storedMeasurements.add(response.body()); temperature.setText(response.body().getTemperature().toString()); humidity.setText(response.body().getHumidity().toString()); pollution.setText(response.body().getPollution().toString()); String pattern = "^(.*)T(.*)\\..*$"; timestamp.setText("Last time updated: "+ response.body().getTimestamp().replaceAll(pattern,"$1 $2")); saveLatestMeasurement(response.body().toString()); } @Override public void onFailure(Call<MeasurementModel> call, Throwable t) { } }); } }
UTF-8
Java
7,780
java
MainActivity.java
Java
[]
null
[]
package com.example.airvironment; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Telephony; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private TextView temperature; private TextView humidity; private TextView pollution; private TextView timestamp; private Button showHistory; private Button share; private Button showGraph; private BroadcastReceiver br; final Handler handler = new Handler(); ArrayList<MeasurementModel> storedMeasurements; private void testSmsPermission(){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 0); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); temperature = findViewById(R.id.tempVal); humidity = findViewById(R.id.humVal); pollution = findViewById(R.id.iaqVal); timestamp = findViewById(R.id.timestamp); showHistory = findViewById(R.id.button); share = findViewById(R.id.buttonShare); showGraph = findViewById(R.id.buttonGraph); testSmsPermission(); showGraph.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, ShowGraphActivity.class); Bundle b = new Bundle(); b.putParcelableArrayList("MeasurementHistory",MainActivity.this.storedMeasurements); intent.putExtra("MeasurementHistory", b); startActivity(intent); } }); showHistory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, ShowHistoryActivity.class); Bundle b = new Bundle(); b.putParcelableArrayList("MeasurementHistory",MainActivity.this.storedMeasurements); intent.putExtra("MeasurementHistory", b); startActivity(intent); } }); share.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); String toSend = storedMeasurements.size() != 0 ? storedMeasurements.get(storedMeasurements.size()-1).toString() : getLatestMeasurementFromSharedPref(); sendIntent.putExtra(Intent.EXTRA_TEXT,toSend); sendIntent.setType("text/plain"); if (sendIntent.resolveActivity(getPackageManager()) != null) { startActivity(sendIntent); } } }); storedMeasurements = new ArrayList<>(); } @Override protected void onPostResume() { super.onPostResume(); fetchData(); final Runnable fetcher = new Runnable() { @Override public void run() { fetchData(); handler.postDelayed(this,6000); } }; handler.postDelayed(fetcher,6000); br = new SmsReceiver(); IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION); this.registerReceiver(br, filter); } @Override protected void onPause() { super.onPause(); handler.removeCallbacksAndMessages(null); unregisterReceiver(br); } private void saveLatestMeasurement(String toSave){ SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(getString(R.string.app_name)+"LATEST_MEASUREMENT",toSave); editor.commit(); } private String getLatestMeasurementFromSharedPref(){ SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); String defaultValue = "ERROR"; return sharedPref.getString(getString(R.string.app_name)+"LATEST_MEASUREMENT", defaultValue); } private void fetchData(){ ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if(!isConnected){ String regex = "^MeasurementModel\\{temperature=(.*), humidity=(.*), pollution=(.*), timestamp=(.*)\\}$"; String stored = getLatestMeasurementFromSharedPref(); if(stored.equals("ERROR")){ temperature.setText("NA"); humidity.setText("NA"); pollution.setText("NA"); timestamp.setText("NA"); return; } Pattern p1=Pattern.compile(regex); Matcher m1=p1.matcher(stored); m1.find(); temperature.setText(m1.group(1)); humidity.setText(m1.group(2)); pollution.setText(m1.group(3)); timestamp.setText("Last time updated: "+m1.group(4)); return; } MeasurementApi service = RetrofitInstance.getRetrofitInstance().create(MeasurementApi.class); /** Call the method with parameter in the interface to get the notice data*/ Call<MeasurementModel> call = service.getLatestMeasurement(); /**Log the URL called*/ Log.wtf("URL Called", call.request().url() + ""); call.enqueue(new Callback<MeasurementModel>() { @Override public void onResponse(Call<MeasurementModel> call, Response<MeasurementModel> response) { storedMeasurements.add(response.body()); temperature.setText(response.body().getTemperature().toString()); humidity.setText(response.body().getHumidity().toString()); pollution.setText(response.body().getPollution().toString()); String pattern = "^(.*)T(.*)\\..*$"; timestamp.setText("Last time updated: "+ response.body().getTimestamp().replaceAll(pattern,"$1 $2")); saveLatestMeasurement(response.body().toString()); } @Override public void onFailure(Call<MeasurementModel> call, Throwable t) { } }); } }
7,780
0.626864
0.623136
282
26.588652
28.614847
167
false
false
0
0
0
0
0
0
0.507092
false
false
5
0a8c7deb8bd4eced8109f0a353ad337cf508c23f
10,075,993,299,861
4131b07051f01265f655f7abaa2e7bac0d63e6ad
/src/main/java/com/wlt/xzzd/dao/SchoolTopicReplyMapper.java
14f918897dd55d5acab2ebec1d5e71c6cdd997b5
[]
no_license
liulong0209/xzzd
https://github.com/liulong0209/xzzd
0afd830606ce62afeaa799f48d0c0c0dc344e9d7
4dac13c159627ecf1480570074db437ade483483
refs/heads/master
2020-03-26T04:47:52.642000
2018-08-13T03:14:18
2018-08-13T03:14:18
144,523,020
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wlt.xzzd.dao; import java.util.List; import java.util.Map; import com.wlt.xzzd.model.SchoolTopicReply; /** * 话题回复持久层 * * @ClassName: SchoolTopicReplyMapper * @Description: TODO(这里用一句话描述这个类的作用) * @author liulong03@chinasoftinc.com * */ public interface SchoolTopicReplyMapper { /** * * SchoolToppicReplyService.countReplyNum * * @Description: 统计回头回复数量 * * @param topicId * @return int * * @exception Exception * * @author liulong03@chinasoftinc.com * * @date 2018年7月8日-下午10:15:22 * */ int countReplyNum(Integer topicId); /** * * SchoolToppicReplyService.queryReply * * @Description: 查询话题回复 * * @param param * @return List<SchoolTopicReply> * * @exception Exception * * @author liulong03@chinasoftinc.com * * @date 2018年7月9日-下午12:37:38 * */ List<SchoolTopicReply> queryReply(Map<String, Object> param); /** * 话题回复 * * SchoolToppicReplyService.reply * * @Description: TODO(这里用一句话描述这个方法的作用) * * @param schoolTopicReply * @return int * * @exception Exception * * @author liulong03@chinasoftinc.com * * @date 2018年7月9日-下午12:48:28 * */ int reply(SchoolTopicReply schoolTopicReply); /** * * SchoolToppicReplyService.queryReplyById * * @Description: 根据id查询回复信息 * * @param id * @return SchoolTopicReply * * @exception Exception * * @author liulong03@chinasoftinc.com * * @date 2018年7月12日-上午10:35:16 * */ SchoolTopicReply queryReplyById(Integer id); }
UTF-8
Java
1,966
java
SchoolTopicReplyMapper.java
Java
[ { "context": "\n * @Description: TODO(这里用一句话描述这个类的作用)\r\n * @author liulong03@chinasoftinc.com\r\n *\r\n */\r\npublic interface SchoolTopicReplyMapper", "end": 262, "score": 0.999931275844574, "start": 236, "tag": "EMAIL", "value": "liulong03@chinasoftinc.com" }, { "context": " * @...
null
[]
package com.wlt.xzzd.dao; import java.util.List; import java.util.Map; import com.wlt.xzzd.model.SchoolTopicReply; /** * 话题回复持久层 * * @ClassName: SchoolTopicReplyMapper * @Description: TODO(这里用一句话描述这个类的作用) * @author <EMAIL> * */ public interface SchoolTopicReplyMapper { /** * * SchoolToppicReplyService.countReplyNum * * @Description: 统计回头回复数量 * * @param topicId * @return int * * @exception Exception * * @author <EMAIL> * * @date 2018年7月8日-下午10:15:22 * */ int countReplyNum(Integer topicId); /** * * SchoolToppicReplyService.queryReply * * @Description: 查询话题回复 * * @param param * @return List<SchoolTopicReply> * * @exception Exception * * @author <EMAIL> * * @date 2018年7月9日-下午12:37:38 * */ List<SchoolTopicReply> queryReply(Map<String, Object> param); /** * 话题回复 * * SchoolToppicReplyService.reply * * @Description: TODO(这里用一句话描述这个方法的作用) * * @param schoolTopicReply * @return int * * @exception Exception * * @author <EMAIL> * * @date 2018年7月9日-下午12:48:28 * */ int reply(SchoolTopicReply schoolTopicReply); /** * * SchoolToppicReplyService.queryReplyById * * @Description: 根据id查询回复信息 * * @param id * @return SchoolTopicReply * * @exception Exception * * @author <EMAIL> * * @date 2018年7月12日-上午10:35:16 * */ SchoolTopicReply queryReplyById(Integer id); }
1,871
0.558824
0.526082
90
18.022223
15.836651
65
false
false
0
0
0
0
0
0
0.1
false
false
5
fa7d7aeb305d4d8076858c53ed86694d4135b1ef
10,746,008,202,860
3182dd5e2cb4c93c562293816203038d5e4c9708
/src/java/joptsimple/internal/Row.java
adfec46a4bdc2b432b7ec2f778f204a515f0efa4
[]
no_license
mrauer/TAC-Verif
https://github.com/mrauer/TAC-Verif
46f1fdc06475fef6d217f48a2ee6a6ffc8ec3e4f
5231854f94008729fb1be67992ffafd2ae8908a3
refs/heads/master
2023-07-16T22:25:33.181000
2021-08-29T16:00:37
2021-08-29T16:00:37
401,082,799
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Decompiled with CFR 0.0. * * Could not load the following classes: * java.lang.Class * java.lang.Object * java.lang.String */ package joptsimple.internal; public class Row { public final String description; public final String option; public Row(String string, String string2) { this.option = string; this.description = string2; } public boolean equals(Object object) { if (object == this) { return true; } if (object != null) { if (!Row.class.equals((Object)object.getClass())) { return false; } Row row = (Row)object; return this.option.equals((Object)row.option) && this.description.equals((Object)row.description); } return false; } public int hashCode() { return this.option.hashCode() ^ this.description.hashCode(); } }
UTF-8
Java
919
java
Row.java
Java
[]
null
[]
/* * Decompiled with CFR 0.0. * * Could not load the following classes: * java.lang.Class * java.lang.Object * java.lang.String */ package joptsimple.internal; public class Row { public final String description; public final String option; public Row(String string, String string2) { this.option = string; this.description = string2; } public boolean equals(Object object) { if (object == this) { return true; } if (object != null) { if (!Row.class.equals((Object)object.getClass())) { return false; } Row row = (Row)object; return this.option.equals((Object)row.option) && this.description.equals((Object)row.description); } return false; } public int hashCode() { return this.option.hashCode() ^ this.description.hashCode(); } }
919
0.579978
0.575626
37
23.81081
22.338717
110
false
false
0
0
0
0
0
0
0.324324
false
false
5
3edeeb3208b076c04274492a9a2cb11792c504a5
4,209,067,979,672
3469cd243e23683b03c961c9ab6cee7442cdc111
/Assaignment_2/primeunder10.java
d573dcbf6bf9f22a9d37cea6074170b460952cf9
[]
no_license
Zw3in/Assaignments
https://github.com/Zw3in/Assaignments
3f7984164fc914944e169534d076390186a3e4bd
b9ac9abdadc8a0264627b606b729387c7d14732a
refs/heads/main
2023-07-14T18:38:48.504000
2021-08-24T05:17:35
2021-08-24T05:17:35
395,187,815
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Assaignments.Assaignment_2; public class primeunder10 { public static void main(String[] args) { System.out.print("Prime numbers under 10 : "); for(int i = 1; i < 10; i++) { if(primecheck(i) == true) { System.out.print(i + ", "); } } }// main static boolean primecheck(int n) { if (n == 2) { return true; } // for 2 since it's the only even prime and therefore can't be checked by this // script. if (n % 2 == 0 || n <= 1) { return false; } // razor off negative numbers, 0 and 1 and even numbers else { // *probably* the most efficient and reliable way to check if a number is prime // (probably not the most efficient tbh) for (int y = 3; y < Math.sqrt(n); y += 2) { if (n % y == 0) { return false; } } } return true; }// primecheck }// class
UTF-8
Java
865
java
primeunder10.java
Java
[]
null
[]
package Assaignments.Assaignment_2; public class primeunder10 { public static void main(String[] args) { System.out.print("Prime numbers under 10 : "); for(int i = 1; i < 10; i++) { if(primecheck(i) == true) { System.out.print(i + ", "); } } }// main static boolean primecheck(int n) { if (n == 2) { return true; } // for 2 since it's the only even prime and therefore can't be checked by this // script. if (n % 2 == 0 || n <= 1) { return false; } // razor off negative numbers, 0 and 1 and even numbers else { // *probably* the most efficient and reliable way to check if a number is prime // (probably not the most efficient tbh) for (int y = 3; y < Math.sqrt(n); y += 2) { if (n % y == 0) { return false; } } } return true; }// primecheck }// class
865
0.563006
0.542197
35
22.714285
22.088875
88
false
false
0
0
0
0
0
0
2.457143
false
false
5
06da780435de2ca9180784e8eb18101b6a2406c7
8,701,603,765,392
4a62e4257fa5fa5d023a65b2161012f90f201ec1
/day01/src/cn/test/eclipse/Person.java
b5af46c479a3f2c1b2e4f6b035a028d05f5f84b9
[ "Apache-2.0" ]
permissive
lBetterManl/Java-Web-Study-Demo
https://github.com/lBetterManl/Java-Web-Study-Demo
5dca20bec7e37007d5b0c26f61007e8b0c216a7f
b873044034f183b3505dc04cb870dbf91a59eaff
refs/heads/master
2020-03-08T15:14:16.148000
2018-04-17T02:22:27
2018-04-17T02:22:27
128,206,312
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.test.eclipse; public class Person { public void run(){ System.out.println("run!!!"); } public void eat(){ System.out.println("eat!!!"); } }
UTF-8
Java
163
java
Person.java
Java
[]
null
[]
package cn.test.eclipse; public class Person { public void run(){ System.out.println("run!!!"); } public void eat(){ System.out.println("eat!!!"); } }
163
0.619632
0.619632
12
12.583333
12.148102
31
false
false
0
0
0
0
0
0
1
false
false
5
0dfd1de753a7470788ee1f2fb9efb102e6c705e7
2,336,462,242,690
bec1b5a0b88b32ac717fbae3275ed64fc41968c2
/static-pro/src/main/java/com/other/io/netty/tcp/MyMessageDecode.java
e2db349a57e722c3964d6825e215d15b2028ddb5
[]
no_license
tanshaojun/tsj-soa
https://github.com/tanshaojun/tsj-soa
9516c84cd53c68066ccd0acabc3c4885a6702d3f
763d4c6738edca5fed5d99ca840f94fc27cdab9d
refs/heads/master
2022-10-07T01:38:28.910000
2022-04-22T10:13:58
2022-04-22T10:13:58
131,245,135
2
1
null
false
2022-09-17T00:06:29
2018-04-27T04:23:24
2022-04-14T04:00:17
2022-09-17T00:06:27
84,383
2
1
7
Java
false
false
package com.other.io.netty.tcp; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * @author tanshaojun * @version 1.0 * @date 2020/6/22 11:13 */ public class MyMessageDecode extends ReplayingDecoder<Void> { private final static Logger logger = LoggerFactory.getLogger(MyMessageDecode.class); @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { logger.info("MyMessageDecode decode 执行了......"); int len = in.readInt(); byte[] bytes = new byte[len]; in.readBytes(bytes); Message message = new Message(); message.setLen(len); message.setBytes(bytes); out.add(message); } }
UTF-8
Java
882
java
MyMessageDecode.java
Java
[ { "context": "erFactory;\n\nimport java.util.List;\n\n/**\n * @author tanshaojun\n * @version 1.0\n * @date 2020/6/22 11:13\n */\npubl", "end": 267, "score": 0.999538242816925, "start": 257, "tag": "USERNAME", "value": "tanshaojun" } ]
null
[]
package com.other.io.netty.tcp; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * @author tanshaojun * @version 1.0 * @date 2020/6/22 11:13 */ public class MyMessageDecode extends ReplayingDecoder<Void> { private final static Logger logger = LoggerFactory.getLogger(MyMessageDecode.class); @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { logger.info("MyMessageDecode decode 执行了......"); int len = in.readInt(); byte[] bytes = new byte[len]; in.readBytes(bytes); Message message = new Message(); message.setLen(len); message.setBytes(bytes); out.add(message); } }
882
0.694064
0.676941
32
26.375
24.62944
101
false
false
0
0
0
0
0
0
0.5625
false
false
5
f6ec4cc17a6cc662d36f88ac7994bafd6029186f
2,336,462,247,026
abea2d049965ac4fee6f2dc244474060435b060f
/app/src/main/java/com/example/idealinternships/Login.java
9fa6358877147f0775e9af163ea0a6ac6857018c
[]
no_license
Ideal-Internships/IdealInternships
https://github.com/Ideal-Internships/IdealInternships
89ac1ae845b55aa1922cfc35a4567040e183b262
c6b96b9425a944d1fd578c351179d1e021849900
refs/heads/master
2021-05-18T19:49:00.955000
2020-05-17T12:11:24
2020-05-17T12:11:24
251,387,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.idealinternships; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; 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 com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class Login extends AppCompatActivity { private EditText mEmail, mPassword; private Button mLoginButton; private TextView mNewAccButton; private FirebaseAuth fAuth; private String email; private Company c; private Bundle bundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mEmail = findViewById(R.id.loginCompEmail); mPassword = findViewById(R.id.loginCompPassword); mLoginButton = findViewById(R.id.loginButton); mNewAccButton = findViewById(R.id.newHere); fAuth = FirebaseAuth.getInstance(); mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { email = mEmail.getText().toString().trim(); String password = mPassword.getText().toString().trim(); final Intent intent3 = new Intent(getApplicationContext(), CompanyMyAccActivity.class); final Intent intent2 = new Intent(getApplicationContext(), UploadInternshipFragment.class); bundle = new Bundle(); final CompanyMyAccFragment objects = new CompanyMyAccFragment(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("Companies"); myRef.addValueEventListener(new ValueEventListener() { /** * Gets companies from Firebase and checks if they are the one logging in * @param dataSnapshot */ @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. Log.d("database", "random"); for(DataSnapshot ds: dataSnapshot.getChildren()){ c = ds.getValue(Company.class); if(c.getEmail().equals(email)){ Log.d("database", c.toString()); bundle.putString("company name", "problem"); intent2.putExtra("company name", c.getName()); bundle.putString("company bio", c.getBio()); bundle.putString("company location", c.getLocation()); bundle.putString("company link", c.getLink()); } } } /** * Indicates an error in accessing Firebase * @param error error */ @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w("MainActivity", "Failed to read value.", error.toException()); } }); objects.setArguments(bundle); if(TextUtils.isEmpty(email)){ mEmail.setError("email is required"); return; } if(TextUtils.isEmpty(password)){ mPassword.setError("password is required"); return; } if(password.length() <6){ mPassword.setError("password must be at least 6 characters"); return; } fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Toast.makeText(Login.this,"Successful login",Toast.LENGTH_SHORT).show(); Log.d("database", "got 2.0"); Log.d("database", email); startActivity(intent3); } else{ Toast.makeText(Login.this,"Error!",Toast.LENGTH_SHORT).show(); } } }); } }); mNewAccButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), Register.class); startActivity(intent); } }); } }
UTF-8
Java
5,656
java
Login.java
Java
[]
null
[]
package com.example.idealinternships; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; 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 com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class Login extends AppCompatActivity { private EditText mEmail, mPassword; private Button mLoginButton; private TextView mNewAccButton; private FirebaseAuth fAuth; private String email; private Company c; private Bundle bundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mEmail = findViewById(R.id.loginCompEmail); mPassword = findViewById(R.id.loginCompPassword); mLoginButton = findViewById(R.id.loginButton); mNewAccButton = findViewById(R.id.newHere); fAuth = FirebaseAuth.getInstance(); mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { email = mEmail.getText().toString().trim(); String password = mPassword.getText().toString().trim(); final Intent intent3 = new Intent(getApplicationContext(), CompanyMyAccActivity.class); final Intent intent2 = new Intent(getApplicationContext(), UploadInternshipFragment.class); bundle = new Bundle(); final CompanyMyAccFragment objects = new CompanyMyAccFragment(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("Companies"); myRef.addValueEventListener(new ValueEventListener() { /** * Gets companies from Firebase and checks if they are the one logging in * @param dataSnapshot */ @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. Log.d("database", "random"); for(DataSnapshot ds: dataSnapshot.getChildren()){ c = ds.getValue(Company.class); if(c.getEmail().equals(email)){ Log.d("database", c.toString()); bundle.putString("company name", "problem"); intent2.putExtra("company name", c.getName()); bundle.putString("company bio", c.getBio()); bundle.putString("company location", c.getLocation()); bundle.putString("company link", c.getLink()); } } } /** * Indicates an error in accessing Firebase * @param error error */ @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w("MainActivity", "Failed to read value.", error.toException()); } }); objects.setArguments(bundle); if(TextUtils.isEmpty(email)){ mEmail.setError("email is required"); return; } if(TextUtils.isEmpty(password)){ mPassword.setError("password is required"); return; } if(password.length() <6){ mPassword.setError("password must be at least 6 characters"); return; } fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Toast.makeText(Login.this,"Successful login",Toast.LENGTH_SHORT).show(); Log.d("database", "got 2.0"); Log.d("database", email); startActivity(intent3); } else{ Toast.makeText(Login.this,"Error!",Toast.LENGTH_SHORT).show(); } } }); } }); mNewAccButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), Register.class); startActivity(intent); } }); } }
5,656
0.55145
0.550035
145
38.006897
28.362066
125
false
false
0
0
0
0
0
0
0.62069
false
false
5
7c20999cd25c006874df03abbab90c3cc1c88015
15,169,824,520,138
88e9d6186e06abcee95b0a0b983a01bbb167e8cb
/src/main/java/message/builder/JSONMessageBuilder.java
c1036219d5bf46f2e263fd18c9e2a6fc764d1109
[]
no_license
alex-zaplik/db-server
https://github.com/alex-zaplik/db-server
e1c23b82b57cf34284d1015a168c5e6068acaa26
24ea8fbdd32ca43097b3d65e0caf1d26a2511f3d
refs/heads/master
2021-05-13T23:12:52.139000
2018-01-14T18:17:46
2018-01-14T18:17:46
116,507,160
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package message.builder; import org.json.JSONObject; public class JSONMessageBuilder implements IMessageBuilder { private JSONObject data = new JSONObject(); /** * Puts a new object into the data set * * @param name Name of the object (must me unique) * @param o The object * @return this */ @Override public IMessageBuilder put(String name, Object o) { data.put(name, o); return this; } /** * Builds a JSON {@link String} based an the data passed via put * * @return The JSON String that was built */ @Override public String get() { String res = data.toString(); data = new JSONObject(); return res; } }
UTF-8
Java
767
java
JSONMessageBuilder.java
Java
[]
null
[]
package message.builder; import org.json.JSONObject; public class JSONMessageBuilder implements IMessageBuilder { private JSONObject data = new JSONObject(); /** * Puts a new object into the data set * * @param name Name of the object (must me unique) * @param o The object * @return this */ @Override public IMessageBuilder put(String name, Object o) { data.put(name, o); return this; } /** * Builds a JSON {@link String} based an the data passed via put * * @return The JSON String that was built */ @Override public String get() { String res = data.toString(); data = new JSONObject(); return res; } }
767
0.573664
0.573664
33
22.242424
20.338097
68
false
false
0
0
0
0
0
0
0.30303
false
false
5
be667a747cd88282b68de01ec801fd6e1ae68047
11,862,699,703,655
f37c093608fd690a07ce8777123299b79f441b9b
/nookBrowser/src/com/nookdevs/browser/FavsDB.java
7de86a56903cabe42fd078fea1c9c65738625991
[]
no_license
susemm/nookdevs
https://github.com/susemm/nookdevs
a16b49a121fa9865d0fb3ec5703d6eb865097ae7
09a2a6e6e264db75069c8005e35731dceea09cf0
refs/heads/master
2020-12-26T00:27:06.618000
2011-09-19T19:50:57
2011-09-19T19:50:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2010 nookDevs * 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.nookdevs.browser; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.util.Log; class FavsDB extends SQLiteOpenHelper { private SQLiteDatabase m_ReadDb; private SQLiteDatabase m_WriteDb; private static final String DATABASE_NAME = "BROWSER"; private static final String TABLE_NAME = "FAVS"; private static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME; private static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME + " ( id integer primary key autoincrement, name text not null," + " value text not null)"; private static String TAG = "FavsDB"; private boolean m_DataLoaded = false; private ArrayList<CharSequence> m_Names = new ArrayList<CharSequence>(); private ArrayList<CharSequence> m_Values = new ArrayList<CharSequence>(); private ArrayList<Integer> m_Ids = new ArrayList<Integer>(); private Context m_Context = null; public FavsDB(Context context, CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, version); m_Context = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading db from " + oldVersion + " to " + newVersion + ". All data will be lost"); db.execSQL(DROP_TABLE); onCreate(db); } private void loadData() { try { if (m_ReadDb == null) { m_ReadDb = getReadableDatabase(); } String[] columns = { "name", "value", "id" }; Cursor cursor = m_ReadDb.query(TABLE_NAME, columns, null, null, null, null, "id"); cursor.moveToFirst(); while (!cursor.isAfterLast()) { m_Names.add(cursor.getString(0)); m_Values.add(cursor.getString(1)); m_Ids.add(cursor.getInt(2)); cursor.moveToNext(); } cursor.close(); m_Names.add(0, m_Context.getString(R.string.add_fav)); m_DataLoaded = true; } catch (Exception ex) { Log.e(TAG, "Exception reading favs ... ", ex); } } public List<CharSequence> getNames() { if (!m_DataLoaded) { loadData(); } return m_Names; } public List<CharSequence> getValues() { if (!m_DataLoaded) { loadData(); } return m_Values; } public void deleteFav(int position) { try { String idStr = String.valueOf(m_Ids.get(position - 1)); if (m_WriteDb == null) { m_WriteDb = getWritableDatabase(); } String[] values = { idStr }; m_WriteDb.beginTransaction(); m_WriteDb.delete(TABLE_NAME, "id=?", values); m_WriteDb.setTransactionSuccessful(); m_Names.remove(position); m_Values.remove(position - 1); m_Ids.remove(position - 1); m_WriteDb.endTransaction(); } catch (Exception ex) { Log.e(TAG, "Exception deleting fav ... ", ex); m_WriteDb.endTransaction(); } } public void addFav(String name, String val) { try { m_Names.add(name); m_Values.add(val); if (m_WriteDb == null) { m_WriteDb = getWritableDatabase(); } m_WriteDb.beginTransaction(); ContentValues values = new ContentValues(); values.put("name", name); values.put("value", val); m_WriteDb.insert(TABLE_NAME, null, values); m_WriteDb.setTransactionSuccessful(); m_WriteDb.endTransaction(); String[] columns = { "id" }; Cursor cursor = m_ReadDb.query(TABLE_NAME, columns, null, null, null, null, "id"); cursor.moveToFirst(); m_Ids.add(cursor.getInt(0)); cursor.close(); } catch (Exception ex) { Log.e(TAG, "Exception adding favs ... ", ex); m_WriteDb.endTransaction(); } } }
UTF-8
Java
5,371
java
FavsDB.java
Java
[ { "context": "/* \r\n * Copyright 2010 nookDevs\r\n * Licensed under the Apache License, Version 2.", "end": 31, "score": 0.999678373336792, "start": 23, "tag": "USERNAME", "value": "nookDevs" } ]
null
[]
/* * Copyright 2010 nookDevs * 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.nookdevs.browser; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.util.Log; class FavsDB extends SQLiteOpenHelper { private SQLiteDatabase m_ReadDb; private SQLiteDatabase m_WriteDb; private static final String DATABASE_NAME = "BROWSER"; private static final String TABLE_NAME = "FAVS"; private static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME; private static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME + " ( id integer primary key autoincrement, name text not null," + " value text not null)"; private static String TAG = "FavsDB"; private boolean m_DataLoaded = false; private ArrayList<CharSequence> m_Names = new ArrayList<CharSequence>(); private ArrayList<CharSequence> m_Values = new ArrayList<CharSequence>(); private ArrayList<Integer> m_Ids = new ArrayList<Integer>(); private Context m_Context = null; public FavsDB(Context context, CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, version); m_Context = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading db from " + oldVersion + " to " + newVersion + ". All data will be lost"); db.execSQL(DROP_TABLE); onCreate(db); } private void loadData() { try { if (m_ReadDb == null) { m_ReadDb = getReadableDatabase(); } String[] columns = { "name", "value", "id" }; Cursor cursor = m_ReadDb.query(TABLE_NAME, columns, null, null, null, null, "id"); cursor.moveToFirst(); while (!cursor.isAfterLast()) { m_Names.add(cursor.getString(0)); m_Values.add(cursor.getString(1)); m_Ids.add(cursor.getInt(2)); cursor.moveToNext(); } cursor.close(); m_Names.add(0, m_Context.getString(R.string.add_fav)); m_DataLoaded = true; } catch (Exception ex) { Log.e(TAG, "Exception reading favs ... ", ex); } } public List<CharSequence> getNames() { if (!m_DataLoaded) { loadData(); } return m_Names; } public List<CharSequence> getValues() { if (!m_DataLoaded) { loadData(); } return m_Values; } public void deleteFav(int position) { try { String idStr = String.valueOf(m_Ids.get(position - 1)); if (m_WriteDb == null) { m_WriteDb = getWritableDatabase(); } String[] values = { idStr }; m_WriteDb.beginTransaction(); m_WriteDb.delete(TABLE_NAME, "id=?", values); m_WriteDb.setTransactionSuccessful(); m_Names.remove(position); m_Values.remove(position - 1); m_Ids.remove(position - 1); m_WriteDb.endTransaction(); } catch (Exception ex) { Log.e(TAG, "Exception deleting fav ... ", ex); m_WriteDb.endTransaction(); } } public void addFav(String name, String val) { try { m_Names.add(name); m_Values.add(val); if (m_WriteDb == null) { m_WriteDb = getWritableDatabase(); } m_WriteDb.beginTransaction(); ContentValues values = new ContentValues(); values.put("name", name); values.put("value", val); m_WriteDb.insert(TABLE_NAME, null, values); m_WriteDb.setTransactionSuccessful(); m_WriteDb.endTransaction(); String[] columns = { "id" }; Cursor cursor = m_ReadDb.query(TABLE_NAME, columns, null, null, null, null, "id"); cursor.moveToFirst(); m_Ids.add(cursor.getInt(0)); cursor.close(); } catch (Exception ex) { Log.e(TAG, "Exception adding favs ... ", ex); m_WriteDb.endTransaction(); } } }
5,371
0.562279
0.5593
150
33.82
23.040854
104
false
false
0
0
0
0
0
0
0.786667
false
false
5
782c3814ee23be9d26bdbbe1382f40bfa11e57bd
26,568,667,728,395
5d12b5780c124a3c1c7cb39d7615adcae037fceb
/app/src/main/java/com/saggy/wielearner/QuizEnd.java
076880cb2a02629ccf27e35138b77dc2137f2e96
[]
no_license
Saggy001/Study-Buddy-Application
https://github.com/Saggy001/Study-Buddy-Application
8f749187f0507e4fe78f9fd3924a80005bdaba7e
1e4b5a9a09d36f1937956b67194feb3fa7a317b6
refs/heads/master
2023-07-11T18:06:46.992000
2021-08-07T19:41:25
2021-08-07T19:41:25
393,775,261
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.saggy.wielearner; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatButton; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import java.util.Objects; public class QuizEnd extends AppCompatActivity { String subjectname,topic,score; String topics,quizlinks,subjectcode; TextView text; AppCompatButton home,retry; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quizend); subjectname = Objects.requireNonNull(getIntent().getExtras()).getString("subjectname"); subjectcode = Objects.requireNonNull(getIntent().getExtras()).getString("subjectcode"); score = Objects.requireNonNull(getIntent().getExtras()).getString("score"); topic = Objects.requireNonNull(getIntent().getExtras()).getString("topic"); topics = Objects.requireNonNull(getIntent().getExtras()).getString("topics"); quizlinks = Objects.requireNonNull(getIntent().getExtras()).getString("quizlinks"); text = findViewById(R.id.text); home = findViewById(R.id.home); retry = findViewById(R.id.retry); text.setText(String.format("You have scored %s/10 in %s from %s", score, topic, subjectname)); home.setOnClickListener(v -> { startActivity(new Intent(QuizEnd.this, Home_Activity.class)); finish(); }); retry.setOnClickListener(v -> { Intent into = new Intent(QuizEnd.this , TopicQuiz.class); into.putExtra("subjectname",subjectname); into.putExtra("subjectcode",subjectcode); into.putExtra("topic",topics); into.putExtra("quizlink",quizlinks); startActivity(into); finish(); }); } }
UTF-8
Java
1,893
java
QuizEnd.java
Java
[]
null
[]
package com.saggy.wielearner; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatButton; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import java.util.Objects; public class QuizEnd extends AppCompatActivity { String subjectname,topic,score; String topics,quizlinks,subjectcode; TextView text; AppCompatButton home,retry; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quizend); subjectname = Objects.requireNonNull(getIntent().getExtras()).getString("subjectname"); subjectcode = Objects.requireNonNull(getIntent().getExtras()).getString("subjectcode"); score = Objects.requireNonNull(getIntent().getExtras()).getString("score"); topic = Objects.requireNonNull(getIntent().getExtras()).getString("topic"); topics = Objects.requireNonNull(getIntent().getExtras()).getString("topics"); quizlinks = Objects.requireNonNull(getIntent().getExtras()).getString("quizlinks"); text = findViewById(R.id.text); home = findViewById(R.id.home); retry = findViewById(R.id.retry); text.setText(String.format("You have scored %s/10 in %s from %s", score, topic, subjectname)); home.setOnClickListener(v -> { startActivity(new Intent(QuizEnd.this, Home_Activity.class)); finish(); }); retry.setOnClickListener(v -> { Intent into = new Intent(QuizEnd.this , TopicQuiz.class); into.putExtra("subjectname",subjectname); into.putExtra("subjectcode",subjectcode); into.putExtra("topic",topics); into.putExtra("quizlink",quizlinks); startActivity(into); finish(); }); } }
1,893
0.673534
0.672478
53
34.735847
29.509289
102
false
false
0
0
0
0
0
0
0.90566
false
false
5
b061842daf612cf84918552d03c0d48ed5f717c0
26,895,085,234,345
1db19a4a9e63019ad740f57ef54592c23e656ea0
/src/mainFrm.java
f9ca44913ad54f5aa9a8a8dc6b8a5aa7416c8933
[]
no_license
Schiffer1945/kasir
https://github.com/Schiffer1945/kasir
917e387bdf5774750ce68da555c246ed663996a5
b21fd8992c9012733e0d0a0ff169efd91f4af2b1
refs/heads/master
2021-01-22T18:24:16.981000
2017-03-15T14:26:44
2017-03-15T14:26:44
85,080,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /* * 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. */ /** * * @author Fariz */ public class mainFrm extends javax.swing.JFrame { String hrgMakanan, hrgMinuman, hrgTotal; int hrgMkn, hrgMnm, totalHrg, totalHrgMkn, totalHrgMnm; /** * Creates new form mainFrm */ public mainFrm() { initComponents(); selectData(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); tHargaMakanan = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tHargaMinuman = new javax.swing.JTextField(); Tanggal = new com.toedter.calendar.JDateChooser(); jLabel6 = new javax.swing.JLabel(); tTotalHarga = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); bClear = new javax.swing.JButton(); bSave = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); tMinuman = new javax.swing.JComboBox<>(); tMakanan = new javax.swing.JComboBox<>(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); spinnerMnm = new javax.swing.JSpinner(); spinnerMkn = new javax.swing.JSpinner(); tNamaKsr = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); bDelete = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tabelData = new javax.swing.JTable(); jLabel13 = new javax.swing.JLabel(); bPrint1 = new javax.swing.JButton(); bRefresh = new javax.swing.JButton(); bBantuan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Entry"); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("ENTRY"); getContentPane().add(jLabel1); jLabel1.setBounds(20, 10, 90, 30); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel1.setLayout(null); jLabel2.setText("Nama makanan"); jPanel1.add(jLabel2); jLabel2.setBounds(11, 12, 190, 20); jLabel3.setText("Rp"); jPanel1.add(jLabel3); jLabel3.setBounds(10, 290, 30, 30); tHargaMakanan.setEditable(false); tHargaMakanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tHargaMakananActionPerformed(evt); } }); jPanel1.add(tHargaMakanan); tHargaMakanan.setBounds(30, 80, 180, 30); jLabel4.setText("Nama minuman"); jPanel1.add(jLabel4); jLabel4.setBounds(10, 110, 190, 20); jLabel5.setText("Tanggal Pembelian"); jPanel1.add(jLabel5); jLabel5.setBounds(10, 210, 190, 20); tHargaMinuman.setEditable(false); tHargaMinuman.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tHargaMinumanActionPerformed(evt); } }); jPanel1.add(tHargaMinuman); tHargaMinuman.setBounds(30, 180, 180, 30); jPanel1.add(Tanggal); Tanggal.setBounds(10, 230, 200, 30); jLabel6.setText("Harga minuman"); jPanel1.add(jLabel6); jLabel6.setBounds(10, 160, 190, 20); tTotalHarga.setEditable(false); jPanel1.add(tTotalHarga); tTotalHarga.setBounds(30, 290, 180, 30); jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel7.setText("Total Harga :"); jPanel1.add(jLabel7); jLabel7.setBounds(100, 270, 110, 20); bClear.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bClear.setText("CLEAR"); bClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bClearActionPerformed(evt); } }); jPanel1.add(bClear); bClear.setBounds(140, 330, 73, 40); bSave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bSave.setText("SAVE"); bSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bSaveActionPerformed(evt); } }); jPanel1.add(bSave); bSave.setBounds(70, 330, 73, 40); jPanel1.add(jSeparator1); jSeparator1.setBounds(10, 270, 200, 10); tMinuman.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Local greentea", "Toraja coffee", "'Mak' special coffee", "'Starbud' special coffee" })); tMinuman.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tMinumanActionPerformed(evt); } }); jPanel1.add(tMinuman); tMinuman.setBounds(10, 130, 200, 30); tMakanan.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Indonesian salad with peanut sauce", "Grilled chicken", "Grilled fish", "Meatball" })); tMakanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tMakananActionPerformed(evt); } }); jPanel1.add(tMakanan); tMakanan.setBounds(10, 30, 200, 30); jLabel10.setText("Harga makanan"); jPanel1.add(jLabel10); jLabel10.setBounds(10, 60, 190, 20); jLabel11.setText("Rp"); jPanel1.add(jLabel11); jLabel11.setBounds(10, 80, 30, 30); jLabel12.setText("Rp"); jPanel1.add(jLabel12); jLabel12.setBounds(10, 180, 30, 30); jButton3.setText("OK"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel1.add(jButton3); jButton3.setBounds(10, 330, 50, 40); jPanel1.add(spinnerMnm); spinnerMnm.setBounds(220, 130, 40, 30); jPanel1.add(spinnerMkn); spinnerMkn.setBounds(220, 30, 40, 30); getContentPane().add(jPanel1); jPanel1.setBounds(20, 40, 270, 380); getContentPane().add(tNamaKsr); tNamaKsr.setBounds(450, 50, 170, 30); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel8.setText("Nama kasir"); getContentPane().add(jLabel8); jLabel8.setBounds(450, 30, 130, 20); bDelete.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N bDelete.setText("DELETE"); bDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bDeleteActionPerformed(evt); } }); getContentPane().add(bDelete); bDelete.setBounds(300, 40, 73, 40); tabelData.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null} }, new String [] { "id", "Tanggal", "Nama kasir", "Nama makanan", "Harga makanan", "Nama minuman", "Harga minuman", "Total harga", "Diskon" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tabelData); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(300, 90, 640, 310); jLabel13.setFont(new java.awt.Font("Tahoma", 2, 10)); // NOI18N jLabel13.setText("Setiap pembelian diatas 200.000 diberikan diskon 10%"); getContentPane().add(jLabel13); jLabel13.setBounds(300, 400, 250, 20); bPrint1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bPrint1.setText("PRINT"); bPrint1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bPrint1ActionPerformed(evt); } }); getContentPane().add(bPrint1); bPrint1.setBounds(370, 40, 69, 40); bRefresh.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N bRefresh.setText("Refresh"); bRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRefreshActionPerformed(evt); } }); getContentPane().add(bRefresh); bRefresh.setBounds(860, 40, 80, 30); bBantuan.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N bBantuan.setText("Bantuan"); bBantuan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bBantuanActionPerformed(evt); } }); getContentPane().add(bBantuan); bBantuan.setBounds(860, 10, 80, 30); setSize(new java.awt.Dimension(968, 472)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void tMakananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tMakananActionPerformed if(tMakanan.getSelectedItem().equals("Indonesian salad with peanut sauce")) { tHargaMakanan.setText("45000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); } if(tMakanan.getSelectedItem().equals("Grilled chicken")) { tHargaMakanan.setText("180000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); } if(tMakanan.getSelectedItem().equals("Grilled fish")) { tHargaMakanan.setText("170000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); } if(tMakanan.getSelectedItem().equals("Meatball")) { tHargaMakanan.setText("30000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); }; }//GEN-LAST:event_tMakananActionPerformed private void tHargaMakananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tHargaMakananActionPerformed }//GEN-LAST:event_tHargaMakananActionPerformed private void tMinumanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tMinumanActionPerformed if(tMinuman.getSelectedItem().equals("Local greentea")) { tHargaMinuman.setText("10000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } if(tMinuman.getSelectedItem().equals("Toraja coffee")) { tHargaMinuman.setText("15000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } if(tMinuman.getSelectedItem().equals("'Mak' special coffee")) { tHargaMinuman.setText("22000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } if(tMinuman.getSelectedItem().equals("'Starbud' special coffee")) { tHargaMinuman.setText("25000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } }//GEN-LAST:event_tMinumanActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed int jumlahmakanan = (Integer) spinnerMkn.getValue(); int jumlahminuman = (Integer) spinnerMnm.getValue(); totalHrgMkn = hrgMkn * jumlahmakanan; totalHrgMnm = hrgMnm * jumlahminuman; totalHrg = totalHrgMkn + totalHrgMnm; if(totalHrg > 200000) { totalHrg = totalHrg - totalHrg * 10/100; tTotalHarga.setText(Integer.toString(totalHrg)); } else { tTotalHarga.setText(Integer.toString(totalHrg)); } }//GEN-LAST:event_jButton3ActionPerformed private void tHargaMinumanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tHargaMinumanActionPerformed }//GEN-LAST:event_tHargaMinumanActionPerformed private void bClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bClearActionPerformed tHargaMakanan.setText(""); tHargaMinuman.setText(""); Tanggal.setDate(null); tTotalHarga.setText(""); spinnerMkn.setValue(0); spinnerMnm.setValue(0); }//GEN-LAST:event_bClearActionPerformed private void bSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSaveActionPerformed SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String tanggal = dateFormat.format(Tanggal.getDate()); String namakasir = tNamaKsr.getText(); String makanan = (String) tMakanan.getSelectedItem(); int hargamakanan = Integer.parseInt(tHargaMakanan.getText()); String minuman = (String) tMinuman.getSelectedItem(); int hargaminuman = Integer.parseInt(tHargaMinuman.getText()); int totalharga = Integer.parseInt(tTotalHarga.getText()); String SQL = "INSERT INTO tb_pesan (tanggal,kasir,makanan,hargamakanan,minuman,hargaminuman,totalHarga)" + "VALUES('"+tanggal+"','"+namakasir+"','"+makanan+"',"+hargamakanan+",'"+ minuman+"',"+hargaminuman+","+totalharga+")"; int status = KoneksiDB.execute(SQL); if(status == 1) { JOptionPane.showMessageDialog(this, "Data berhasil ditambah", "SUKSES", JOptionPane.INFORMATION_MESSAGE); selectData(); } else { JOptionPane.showMessageDialog(this, "Data Gagal ditambah", "GAGAL", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bSaveActionPerformed private void bDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDeleteActionPerformed int baris = tabelData.getSelectedRow(); if(baris != -1) { String id = tabelData.getValueAt(baris, 0).toString(); String SQL = "DELETE FROM tb_pesan WHERE id='"+id+"'"; int status = KoneksiDB.execute(SQL); if(status == 1) { JOptionPane.showMessageDialog(this, "Data berhasil dihapus", "Sukses", JOptionPane.INFORMATION_MESSAGE); selectData(); } else { JOptionPane.showMessageDialog(this, "Data gagal dihapus", "Gagal", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Pilih baris data dulu", "Error", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bDeleteActionPerformed private void bRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRefreshActionPerformed selectData(); }//GEN-LAST:event_bRefreshActionPerformed private void bPrint1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPrint1ActionPerformed MessageFormat header = new MessageFormat("Pesanan"); MessageFormat footer = new MessageFormat("Page {0,number,integer}"); try { tabelData.print(JTable.PrintMode.FIT_WIDTH, header, footer, true, null, true, null); } catch(java.awt.print.PrinterException e) { System.err.format("Cannot print %s%n", e.getMessage()); } }//GEN-LAST:event_bPrint1ActionPerformed private void bBantuanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBantuanActionPerformed JOptionPane.showMessageDialog(this, "Setelah memasukkan data, tekan tombol OK untuk menghitung lalu klik Save\n" + "Selalu klik Clear apabila akan memasukkan data baru", "Help", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_bBantuanActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainFrm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser Tanggal; private javax.swing.JButton bBantuan; private javax.swing.JButton bClear; private javax.swing.JButton bDelete; private javax.swing.JButton bPrint1; private javax.swing.JButton bRefresh; private javax.swing.JButton bSave; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSpinner spinnerMkn; private javax.swing.JSpinner spinnerMnm; private javax.swing.JTextField tHargaMakanan; private javax.swing.JTextField tHargaMinuman; private javax.swing.JComboBox<String> tMakanan; private javax.swing.JComboBox<String> tMinuman; private javax.swing.JTextField tNamaKsr; private javax.swing.JTextField tTotalHarga; private javax.swing.JTable tabelData; // End of variables declaration//GEN-END:variables private void selectData() { String kolom[] = {"id", "Tanggal", "kasir", "makanan", "hargamakanan", "minuman", "hargaminuman", "totalHarga"}; DefaultTableModel dtm = new DefaultTableModel(null, kolom); String SQL = "SELECT * FROM tb_pesan"; ResultSet rs = KoneksiDB.executeQuery(SQL); try { while(rs.next()) { String id = rs.getString(1); String Tanggal = rs.getString(2); String kasir = rs.getString(3); String makanan = rs.getString(4); String hargamakanan = rs.getString(5); String minuman = rs.getString(6); String hargaminuman = rs.getString(7); String totalHarga = rs.getString(8); String data[] = {id, Tanggal, kasir, makanan, hargamakanan, minuman, hargaminuman, totalHarga}; dtm.addRow(data); } } catch(SQLException ex) { Logger.getLogger(mainFrm.class.getName()).log(Level.SEVERE, null, ex); } tabelData.setModel(dtm); } }
UTF-8
Java
22,014
java
mainFrm.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author Fariz\n */\npublic class mainFrm extends javax.swing.JFra", "end": 503, "score": 0.9984933137893677, "start": 498, "tag": "NAME", "value": "Fariz" }, { "context": "Panel1.setLayout(null);\n\n jLabel2.setText...
null
[]
import java.sql.ResultSet; import java.sql.SQLException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /* * 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. */ /** * * @author Fariz */ public class mainFrm extends javax.swing.JFrame { String hrgMakanan, hrgMinuman, hrgTotal; int hrgMkn, hrgMnm, totalHrg, totalHrgMkn, totalHrgMnm; /** * Creates new form mainFrm */ public mainFrm() { initComponents(); selectData(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); tHargaMakanan = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tHargaMinuman = new javax.swing.JTextField(); Tanggal = new com.toedter.calendar.JDateChooser(); jLabel6 = new javax.swing.JLabel(); tTotalHarga = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); bClear = new javax.swing.JButton(); bSave = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); tMinuman = new javax.swing.JComboBox<>(); tMakanan = new javax.swing.JComboBox<>(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); spinnerMnm = new javax.swing.JSpinner(); spinnerMkn = new javax.swing.JSpinner(); tNamaKsr = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); bDelete = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tabelData = new javax.swing.JTable(); jLabel13 = new javax.swing.JLabel(); bPrint1 = new javax.swing.JButton(); bRefresh = new javax.swing.JButton(); bBantuan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Entry"); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("ENTRY"); getContentPane().add(jLabel1); jLabel1.setBounds(20, 10, 90, 30); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel1.setLayout(null); jLabel2.setText("<NAME>"); jPanel1.add(jLabel2); jLabel2.setBounds(11, 12, 190, 20); jLabel3.setText("Rp"); jPanel1.add(jLabel3); jLabel3.setBounds(10, 290, 30, 30); tHargaMakanan.setEditable(false); tHargaMakanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tHargaMakananActionPerformed(evt); } }); jPanel1.add(tHargaMakanan); tHargaMakanan.setBounds(30, 80, 180, 30); jLabel4.setText("Nama minuman"); jPanel1.add(jLabel4); jLabel4.setBounds(10, 110, 190, 20); jLabel5.setText("Tanggal Pembelian"); jPanel1.add(jLabel5); jLabel5.setBounds(10, 210, 190, 20); tHargaMinuman.setEditable(false); tHargaMinuman.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tHargaMinumanActionPerformed(evt); } }); jPanel1.add(tHargaMinuman); tHargaMinuman.setBounds(30, 180, 180, 30); jPanel1.add(Tanggal); Tanggal.setBounds(10, 230, 200, 30); jLabel6.setText("Harga minuman"); jPanel1.add(jLabel6); jLabel6.setBounds(10, 160, 190, 20); tTotalHarga.setEditable(false); jPanel1.add(tTotalHarga); tTotalHarga.setBounds(30, 290, 180, 30); jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel7.setText("Total Harga :"); jPanel1.add(jLabel7); jLabel7.setBounds(100, 270, 110, 20); bClear.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bClear.setText("CLEAR"); bClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bClearActionPerformed(evt); } }); jPanel1.add(bClear); bClear.setBounds(140, 330, 73, 40); bSave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bSave.setText("SAVE"); bSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bSaveActionPerformed(evt); } }); jPanel1.add(bSave); bSave.setBounds(70, 330, 73, 40); jPanel1.add(jSeparator1); jSeparator1.setBounds(10, 270, 200, 10); tMinuman.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Local greentea", "Toraja coffee", "'Mak' special coffee", "'Starbud' special coffee" })); tMinuman.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tMinumanActionPerformed(evt); } }); jPanel1.add(tMinuman); tMinuman.setBounds(10, 130, 200, 30); tMakanan.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Indonesian salad with peanut sauce", "Grilled chicken", "Grilled fish", "Meatball" })); tMakanan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tMakananActionPerformed(evt); } }); jPanel1.add(tMakanan); tMakanan.setBounds(10, 30, 200, 30); jLabel10.setText("Harga makanan"); jPanel1.add(jLabel10); jLabel10.setBounds(10, 60, 190, 20); jLabel11.setText("Rp"); jPanel1.add(jLabel11); jLabel11.setBounds(10, 80, 30, 30); jLabel12.setText("Rp"); jPanel1.add(jLabel12); jLabel12.setBounds(10, 180, 30, 30); jButton3.setText("OK"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel1.add(jButton3); jButton3.setBounds(10, 330, 50, 40); jPanel1.add(spinnerMnm); spinnerMnm.setBounds(220, 130, 40, 30); jPanel1.add(spinnerMkn); spinnerMkn.setBounds(220, 30, 40, 30); getContentPane().add(jPanel1); jPanel1.setBounds(20, 40, 270, 380); getContentPane().add(tNamaKsr); tNamaKsr.setBounds(450, 50, 170, 30); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel8.setText("<NAME>"); getContentPane().add(jLabel8); jLabel8.setBounds(450, 30, 130, 20); bDelete.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N bDelete.setText("DELETE"); bDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bDeleteActionPerformed(evt); } }); getContentPane().add(bDelete); bDelete.setBounds(300, 40, 73, 40); tabelData.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null} }, new String [] { "id", "Tanggal", "Nama kasir", "Nama makanan", "Harga makanan", "Nama minuman", "Harga minuman", "Total harga", "Diskon" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tabelData); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(300, 90, 640, 310); jLabel13.setFont(new java.awt.Font("Tahoma", 2, 10)); // NOI18N jLabel13.setText("Setiap pembelian diatas 200.000 diberikan diskon 10%"); getContentPane().add(jLabel13); jLabel13.setBounds(300, 400, 250, 20); bPrint1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bPrint1.setText("PRINT"); bPrint1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bPrint1ActionPerformed(evt); } }); getContentPane().add(bPrint1); bPrint1.setBounds(370, 40, 69, 40); bRefresh.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N bRefresh.setText("Refresh"); bRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRefreshActionPerformed(evt); } }); getContentPane().add(bRefresh); bRefresh.setBounds(860, 40, 80, 30); bBantuan.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N bBantuan.setText("Bantuan"); bBantuan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bBantuanActionPerformed(evt); } }); getContentPane().add(bBantuan); bBantuan.setBounds(860, 10, 80, 30); setSize(new java.awt.Dimension(968, 472)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void tMakananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tMakananActionPerformed if(tMakanan.getSelectedItem().equals("Indonesian salad with peanut sauce")) { tHargaMakanan.setText("45000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); } if(tMakanan.getSelectedItem().equals("Grilled chicken")) { tHargaMakanan.setText("180000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); } if(tMakanan.getSelectedItem().equals("Grilled fish")) { tHargaMakanan.setText("170000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); } if(tMakanan.getSelectedItem().equals("Meatball")) { tHargaMakanan.setText("30000"); hrgMkn = Integer.parseInt(tHargaMakanan.getText()); }; }//GEN-LAST:event_tMakananActionPerformed private void tHargaMakananActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tHargaMakananActionPerformed }//GEN-LAST:event_tHargaMakananActionPerformed private void tMinumanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tMinumanActionPerformed if(tMinuman.getSelectedItem().equals("Local greentea")) { tHargaMinuman.setText("10000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } if(tMinuman.getSelectedItem().equals("Toraja coffee")) { tHargaMinuman.setText("15000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } if(tMinuman.getSelectedItem().equals("'Mak' special coffee")) { tHargaMinuman.setText("22000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } if(tMinuman.getSelectedItem().equals("'Starbud' special coffee")) { tHargaMinuman.setText("25000"); hrgMnm = Integer.parseInt(tHargaMinuman.getText()); } }//GEN-LAST:event_tMinumanActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed int jumlahmakanan = (Integer) spinnerMkn.getValue(); int jumlahminuman = (Integer) spinnerMnm.getValue(); totalHrgMkn = hrgMkn * jumlahmakanan; totalHrgMnm = hrgMnm * jumlahminuman; totalHrg = totalHrgMkn + totalHrgMnm; if(totalHrg > 200000) { totalHrg = totalHrg - totalHrg * 10/100; tTotalHarga.setText(Integer.toString(totalHrg)); } else { tTotalHarga.setText(Integer.toString(totalHrg)); } }//GEN-LAST:event_jButton3ActionPerformed private void tHargaMinumanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tHargaMinumanActionPerformed }//GEN-LAST:event_tHargaMinumanActionPerformed private void bClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bClearActionPerformed tHargaMakanan.setText(""); tHargaMinuman.setText(""); Tanggal.setDate(null); tTotalHarga.setText(""); spinnerMkn.setValue(0); spinnerMnm.setValue(0); }//GEN-LAST:event_bClearActionPerformed private void bSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSaveActionPerformed SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String tanggal = dateFormat.format(Tanggal.getDate()); String namakasir = tNamaKsr.getText(); String makanan = (String) tMakanan.getSelectedItem(); int hargamakanan = Integer.parseInt(tHargaMakanan.getText()); String minuman = (String) tMinuman.getSelectedItem(); int hargaminuman = Integer.parseInt(tHargaMinuman.getText()); int totalharga = Integer.parseInt(tTotalHarga.getText()); String SQL = "INSERT INTO tb_pesan (tanggal,kasir,makanan,hargamakanan,minuman,hargaminuman,totalHarga)" + "VALUES('"+tanggal+"','"+namakasir+"','"+makanan+"',"+hargamakanan+",'"+ minuman+"',"+hargaminuman+","+totalharga+")"; int status = KoneksiDB.execute(SQL); if(status == 1) { JOptionPane.showMessageDialog(this, "Data berhasil ditambah", "SUKSES", JOptionPane.INFORMATION_MESSAGE); selectData(); } else { JOptionPane.showMessageDialog(this, "Data Gagal ditambah", "GAGAL", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bSaveActionPerformed private void bDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDeleteActionPerformed int baris = tabelData.getSelectedRow(); if(baris != -1) { String id = tabelData.getValueAt(baris, 0).toString(); String SQL = "DELETE FROM tb_pesan WHERE id='"+id+"'"; int status = KoneksiDB.execute(SQL); if(status == 1) { JOptionPane.showMessageDialog(this, "Data berhasil dihapus", "Sukses", JOptionPane.INFORMATION_MESSAGE); selectData(); } else { JOptionPane.showMessageDialog(this, "Data gagal dihapus", "Gagal", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Pilih baris data dulu", "Error", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bDeleteActionPerformed private void bRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRefreshActionPerformed selectData(); }//GEN-LAST:event_bRefreshActionPerformed private void bPrint1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPrint1ActionPerformed MessageFormat header = new MessageFormat("Pesanan"); MessageFormat footer = new MessageFormat("Page {0,number,integer}"); try { tabelData.print(JTable.PrintMode.FIT_WIDTH, header, footer, true, null, true, null); } catch(java.awt.print.PrinterException e) { System.err.format("Cannot print %s%n", e.getMessage()); } }//GEN-LAST:event_bPrint1ActionPerformed private void bBantuanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBantuanActionPerformed JOptionPane.showMessageDialog(this, "Setelah memasukkan data, tekan tombol OK untuk menghitung lalu klik Save\n" + "Selalu klik Clear apabila akan memasukkan data baru", "Help", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_bBantuanActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainFrm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser Tanggal; private javax.swing.JButton bBantuan; private javax.swing.JButton bClear; private javax.swing.JButton bDelete; private javax.swing.JButton bPrint1; private javax.swing.JButton bRefresh; private javax.swing.JButton bSave; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSpinner spinnerMkn; private javax.swing.JSpinner spinnerMnm; private javax.swing.JTextField tHargaMakanan; private javax.swing.JTextField tHargaMinuman; private javax.swing.JComboBox<String> tMakanan; private javax.swing.JComboBox<String> tMinuman; private javax.swing.JTextField tNamaKsr; private javax.swing.JTextField tTotalHarga; private javax.swing.JTable tabelData; // End of variables declaration//GEN-END:variables private void selectData() { String kolom[] = {"id", "Tanggal", "kasir", "makanan", "hargamakanan", "minuman", "hargaminuman", "totalHarga"}; DefaultTableModel dtm = new DefaultTableModel(null, kolom); String SQL = "SELECT * FROM tb_pesan"; ResultSet rs = KoneksiDB.executeQuery(SQL); try { while(rs.next()) { String id = rs.getString(1); String Tanggal = rs.getString(2); String kasir = rs.getString(3); String makanan = rs.getString(4); String hargamakanan = rs.getString(5); String minuman = rs.getString(6); String hargaminuman = rs.getString(7); String totalHarga = rs.getString(8); String data[] = {id, Tanggal, kasir, makanan, hargamakanan, minuman, hargaminuman, totalHarga}; dtm.addRow(data); } } catch(SQLException ex) { Logger.getLogger(mainFrm.class.getName()).log(Level.SEVERE, null, ex); } tabelData.setModel(dtm); } }
22,004
0.631734
0.605887
514
41.828793
29.844635
170
false
false
0
0
0
0
0
0
1.083658
false
false
5
c1dc582767f870bed140f3f846e6433d3995037f
17,334,488,043,051
4bc8e8e082f5ae5c4fb5f52a283473a3965f4f96
/src/main/java/com/linkedin/backend/handlers/exception/UserNotFoundException.java
53669bfa6069f279f76fab70a06e3b240db3440d
[]
no_license
Navyera/mesh
https://github.com/Navyera/mesh
7aacf919ecb5ad187a7a8d00107fd27f72baf87e
dabf0b506facbb027a45c25b25e68bfcbd41601a
refs/heads/master
2020-04-02T10:47:31.250000
2018-09-30T15:05:33
2018-09-30T15:05:33
154,355,304
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.linkedin.backend.handlers.exception; public class UserNotFoundException extends Exception { private Integer id; public UserNotFoundException(Integer id) { this.id = id; } @Override public String getMessage() { return "No user with id " + id.toString() + " found."; } }
UTF-8
Java
324
java
UserNotFoundException.java
Java
[]
null
[]
package com.linkedin.backend.handlers.exception; public class UserNotFoundException extends Exception { private Integer id; public UserNotFoundException(Integer id) { this.id = id; } @Override public String getMessage() { return "No user with id " + id.toString() + " found."; } }
324
0.657407
0.657407
14
22.142857
21.596485
62
false
false
0
0
0
0
0
0
0.285714
false
false
5
8a241b077ae173dcf68483aa59755ca840ba588c
14,817,637,201,996
54f4440487c9f3aad4345af7ab1fec316b7b6751
/Java/JCalculator/src/model/ExpressionTokenFactory.java
91e97f43f2c37bee57e3dfc41aa880413467f230
[]
no_license
costinAndronache/MyProjects
https://github.com/costinAndronache/MyProjects
fb35bec3bd5b565e7b63f87fdb5c385061d3d0ac
b1834b66e09d8a4f1ee7ef6e7e5079893e9045ee
refs/heads/master
2021-01-02T23:13:23.090000
2015-05-12T22:18:50
2015-05-12T22:18:50
32,603,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import java.util.*; public class ExpressionTokenFactory { private Map<String,ExpressionToken> tokenMap; private static ExpressionTokenFactory instance=null; public static ExpressionTokenFactory getInstance() { if(instance == null) instance = new ExpressionTokenFactory(); return instance; } public ExpressionToken getToken(String tokenID) { return tokenMap.get(tokenID); } private ExpressionTokenFactory() { tokenMap = new HashMap<String,ExpressionToken>(); tokenMap.put("log", new LogarithmToken()); tokenMap.put("sqrt", new SquareRootToken()); tokenMap.put("+", new PlusToken() ); tokenMap.put("*", new MultiplyToken()); tokenMap.put("-", new MinusToken()); tokenMap.put("/", new DivideToken()); tokenMap.put("%", new ModuloToken()); tokenMap.put("sin", new SinToken()); tokenMap.put("cos", new CosToken()); tokenMap.put("tan", new TgToken()); tokenMap.put("pow", new PowToken()); tokenMap.put("ln", new LnToken()); tokenMap.put("fact", new FactorialToken()); } public static void main(String[] args) { ExpressionTokenFactory etf = ExpressionTokenFactory.getInstance(); ExpressionToken eTkn; String[] stringArray = new String[3]; stringArray[0]="log"; stringArray[1]="*"; stringArray[2]="+"; Stack<Float> resultStack = new Stack<Float>(); resultStack.push(2.f); resultStack.push(100.f); resultStack.push(2.f); resultStack.push(8.f); for(int i=0;i<stringArray.length;i++) { eTkn = etf.getToken(stringArray[i]); eTkn.apply(resultStack); } System.out.println("The result of 2 + 100 * log(2,8) is: " + resultStack.pop()); } } class LogarithmToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float exponent=resultStack.pop(); float base=resultStack.pop(); float result = (float)(Math.log10((double)exponent) / Math.log10((double)base)); resultStack.push(result); } public int precedence() { return 3; } } class LnToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float arg=resultStack.pop(); float result = (float)Math.log((double)arg); resultStack.push(result); } public int precedence() { return 3; } } class SquareRootToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float arg=resultStack.pop(); float result = (float)Math.sqrt((double)arg); resultStack.push(result); } public int precedence() { return 3; } } class PlusToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operand1 = resultStack.pop(); float operand2 = resultStack.pop(); resultStack.push(operand1 + operand2); } public int precedence() { return 1; } } class MultiplyToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operand1 = resultStack.pop(); float operand2 = resultStack.pop(); resultStack.push(operand1 * operand2); } public int precedence() { return 2; } } class MinusToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operandRight = resultStack.pop(); float operandLeft = resultStack.pop(); resultStack.push(operandLeft - operandRight); } public int precedence() { return 1; } } class DivideToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operandRight = resultStack.pop(); float operandLeft = resultStack.pop(); resultStack.push(operandLeft / operandRight); } public int precedence() { return 2; } } class ModuloToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float operandRight = resultStack.pop(); float operandLeft = resultStack.pop(); resultStack.push( (float)((int)operandLeft % (int)operandRight)); } } class PowToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float exponent = resultStack.pop(); float base = resultStack.pop(); resultStack.push( (float)( Math.pow( (double)base, (double)exponent) )); } public int precedence(){return 3;} } class SinToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); resultStack.push((float)Math.sin((double)arg)); } } class CosToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); resultStack.push((float)Math.cos((double)arg)); } } class TgToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); resultStack.push((float)Math.tan((double)arg)); } } class FactorialToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); if(arg<0) throw new IllegalArgumentException(); float result=1.f; for(int i=2;i<=(int)arg;i++) result = result * i; resultStack.push(result); } }
UTF-8
Java
5,246
java
ExpressionTokenFactory.java
Java
[]
null
[]
package model; import java.util.*; public class ExpressionTokenFactory { private Map<String,ExpressionToken> tokenMap; private static ExpressionTokenFactory instance=null; public static ExpressionTokenFactory getInstance() { if(instance == null) instance = new ExpressionTokenFactory(); return instance; } public ExpressionToken getToken(String tokenID) { return tokenMap.get(tokenID); } private ExpressionTokenFactory() { tokenMap = new HashMap<String,ExpressionToken>(); tokenMap.put("log", new LogarithmToken()); tokenMap.put("sqrt", new SquareRootToken()); tokenMap.put("+", new PlusToken() ); tokenMap.put("*", new MultiplyToken()); tokenMap.put("-", new MinusToken()); tokenMap.put("/", new DivideToken()); tokenMap.put("%", new ModuloToken()); tokenMap.put("sin", new SinToken()); tokenMap.put("cos", new CosToken()); tokenMap.put("tan", new TgToken()); tokenMap.put("pow", new PowToken()); tokenMap.put("ln", new LnToken()); tokenMap.put("fact", new FactorialToken()); } public static void main(String[] args) { ExpressionTokenFactory etf = ExpressionTokenFactory.getInstance(); ExpressionToken eTkn; String[] stringArray = new String[3]; stringArray[0]="log"; stringArray[1]="*"; stringArray[2]="+"; Stack<Float> resultStack = new Stack<Float>(); resultStack.push(2.f); resultStack.push(100.f); resultStack.push(2.f); resultStack.push(8.f); for(int i=0;i<stringArray.length;i++) { eTkn = etf.getToken(stringArray[i]); eTkn.apply(resultStack); } System.out.println("The result of 2 + 100 * log(2,8) is: " + resultStack.pop()); } } class LogarithmToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float exponent=resultStack.pop(); float base=resultStack.pop(); float result = (float)(Math.log10((double)exponent) / Math.log10((double)base)); resultStack.push(result); } public int precedence() { return 3; } } class LnToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float arg=resultStack.pop(); float result = (float)Math.log((double)arg); resultStack.push(result); } public int precedence() { return 3; } } class SquareRootToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float arg=resultStack.pop(); float result = (float)Math.sqrt((double)arg); resultStack.push(result); } public int precedence() { return 3; } } class PlusToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operand1 = resultStack.pop(); float operand2 = resultStack.pop(); resultStack.push(operand1 + operand2); } public int precedence() { return 1; } } class MultiplyToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operand1 = resultStack.pop(); float operand2 = resultStack.pop(); resultStack.push(operand1 * operand2); } public int precedence() { return 2; } } class MinusToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operandRight = resultStack.pop(); float operandLeft = resultStack.pop(); resultStack.push(operandLeft - operandRight); } public int precedence() { return 1; } } class DivideToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float operandRight = resultStack.pop(); float operandLeft = resultStack.pop(); resultStack.push(operandLeft / operandRight); } public int precedence() { return 2; } } class ModuloToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float operandRight = resultStack.pop(); float operandLeft = resultStack.pop(); resultStack.push( (float)((int)operandLeft % (int)operandRight)); } } class PowToken implements ExpressionToken { public void apply(Stack<Float> resultStack) { float exponent = resultStack.pop(); float base = resultStack.pop(); resultStack.push( (float)( Math.pow( (double)base, (double)exponent) )); } public int precedence(){return 3;} } class SinToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); resultStack.push((float)Math.sin((double)arg)); } } class CosToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); resultStack.push((float)Math.cos((double)arg)); } } class TgToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); resultStack.push((float)Math.tan((double)arg)); } } class FactorialToken implements ExpressionToken { public int precedence(){return 3;} public void apply(Stack<Float> resultStack) { float arg = resultStack.pop(); if(arg<0) throw new IllegalArgumentException(); float result=1.f; for(int i=2;i<=(int)arg;i++) result = result * i; resultStack.push(result); } }
5,246
0.689478
0.6809
279
17.749104
19.721033
84
false
false
0
0
0
0
0
0
1.541219
false
false
5
4816496a7912070212b29c1beddc099b4f1e6dab
18,932,215,879,728
3b9103d133c28ae7580bec932ae10be08e2b00bd
/src/com/soccer/web/enums/Action.java
c276fa0d3d4ff82cf578102beede763dd41c167b
[]
no_license
jdy0642/jee-soccer1
https://github.com/jdy0642/jee-soccer1
da8de068f0f421ee7143273adf6beb911e548d6b
5042ad15b47b95338f187a4bdeba2d1b29fee5dc
refs/heads/master
2020-07-31T08:16:32.651000
2019-10-02T09:46:52
2019-10-02T09:46:52
210,542,031
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.soccer.web.enums; public enum Action { MOVE, LOGIN, CREATE, SEARCH, UPDATE, DELETE }
UTF-8
Java
101
java
Action.java
Java
[]
null
[]
package com.soccer.web.enums; public enum Action { MOVE, LOGIN, CREATE, SEARCH, UPDATE, DELETE }
101
0.722772
0.722772
6
15.833333
16.707451
44
false
false
0
0
0
0
0
0
1.333333
false
false
5
899fd7f350d3da90222578b3b92f518b2e47ab8c
16,398,185,200,263
cfce9983d2c502154e189fef630c6aa13184b069
/src/main/java/com/revolut/domain/Account.java
f57121ee4270756c9fcf4f0aec371d0d5a14743a
[]
no_license
robo-pb/money-transfer-service
https://github.com/robo-pb/money-transfer-service
8fadea93318ef7d5b274757f51dfd016cf14fcf8
1f757d666dac514f45751df9435dfa7e00259404
refs/heads/master
2022-12-01T19:48:36.553000
2020-01-06T17:56:01
2020-01-06T17:56:01
232,102,843
0
0
null
false
2022-11-15T23:33:32
2020-01-06T13:07:46
2020-01-06T17:56:30
2022-11-15T23:33:30
48
0
0
2
Java
false
false
package com.revolut.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.revolut.exceptions.InsufficientFundsException; import com.revolut.exceptions.InvalidDepositException; import com.revolut.serializers.MoneyDeSerializer; import com.revolut.serializers.MoneySerializer; import org.joda.money.Money; import java.util.Objects; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @JsonIgnoreProperties(value = { "lock" }) public class Account { private final transient Lock lock; private String owner; private long accountNumber; @JsonSerialize(using = MoneySerializer.class) @JsonDeserialize(using = MoneyDeSerializer.class) private Money money; private Account() { this(builder()); } private Account(final Builder builder) { this(builder.owner, builder.accountNumber, builder.balance); } public Account(final String accountHolder, final long accountNumber, final Money money) { this.lock = new ReentrantLock(); this.owner = accountHolder; this.accountNumber = accountNumber; this.money = money; } public long getAccountNumber() { return accountNumber; } public String getOwner() { return owner; } public Money getMoney() { return money; } public static Builder builder() { return new Builder(); } public Lock getLock() { return lock; } public Account deposit(final Money amount) throws InvalidDepositException { if (amount.isNegative()) { throw new InvalidDepositException(String.format("money %s cannot be deposited", amount)); } return Account.builder() .money(this.getMoney().plus(amount)) .accountNumber(this.getAccountNumber()) .owner(this.getOwner()) .build(); } public Account withdraw(final Money amount) throws InsufficientFundsException { final Money afterWithDraw = this.getMoney().minus(amount); if (afterWithDraw.isNegative()) { throw new InsufficientFundsException(String.format("Account %s does not have sufficient funds", this.getAccountNumber())); } return Account.builder() .money(afterWithDraw) .accountNumber(this.getAccountNumber()) .owner(this.getOwner()) .build(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Account account = (Account) o; return accountNumber == account.accountNumber && Objects.equals(owner, account.owner) && Objects.equals(money, account.money); } @Override public int hashCode() { return Objects.hash(owner, accountNumber, money); } @Override public String toString() { return "Account{" + "'owner='" + owner + '\'' + ", accountNumber=" + accountNumber + ", money=" + money + '}'; } public static class Builder { private String owner; private long accountNumber; private Money balance; private Builder() { } public Builder accountNumber(final long number) { this.accountNumber = number; return this; } public Builder owner(final String owner) { this.owner = owner; return this; } public Builder money(final Money amount) { this.balance = amount; return this; } public Account build() { return new Account(this); } } public static Account copy(Account acc) { return Account.builder() .money(acc.getMoney()) .accountNumber(acc.getAccountNumber()) .owner(acc.getOwner()) .build(); } }
UTF-8
Java
4,206
java
Account.java
Java
[]
null
[]
package com.revolut.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.revolut.exceptions.InsufficientFundsException; import com.revolut.exceptions.InvalidDepositException; import com.revolut.serializers.MoneyDeSerializer; import com.revolut.serializers.MoneySerializer; import org.joda.money.Money; import java.util.Objects; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @JsonIgnoreProperties(value = { "lock" }) public class Account { private final transient Lock lock; private String owner; private long accountNumber; @JsonSerialize(using = MoneySerializer.class) @JsonDeserialize(using = MoneyDeSerializer.class) private Money money; private Account() { this(builder()); } private Account(final Builder builder) { this(builder.owner, builder.accountNumber, builder.balance); } public Account(final String accountHolder, final long accountNumber, final Money money) { this.lock = new ReentrantLock(); this.owner = accountHolder; this.accountNumber = accountNumber; this.money = money; } public long getAccountNumber() { return accountNumber; } public String getOwner() { return owner; } public Money getMoney() { return money; } public static Builder builder() { return new Builder(); } public Lock getLock() { return lock; } public Account deposit(final Money amount) throws InvalidDepositException { if (amount.isNegative()) { throw new InvalidDepositException(String.format("money %s cannot be deposited", amount)); } return Account.builder() .money(this.getMoney().plus(amount)) .accountNumber(this.getAccountNumber()) .owner(this.getOwner()) .build(); } public Account withdraw(final Money amount) throws InsufficientFundsException { final Money afterWithDraw = this.getMoney().minus(amount); if (afterWithDraw.isNegative()) { throw new InsufficientFundsException(String.format("Account %s does not have sufficient funds", this.getAccountNumber())); } return Account.builder() .money(afterWithDraw) .accountNumber(this.getAccountNumber()) .owner(this.getOwner()) .build(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Account account = (Account) o; return accountNumber == account.accountNumber && Objects.equals(owner, account.owner) && Objects.equals(money, account.money); } @Override public int hashCode() { return Objects.hash(owner, accountNumber, money); } @Override public String toString() { return "Account{" + "'owner='" + owner + '\'' + ", accountNumber=" + accountNumber + ", money=" + money + '}'; } public static class Builder { private String owner; private long accountNumber; private Money balance; private Builder() { } public Builder accountNumber(final long number) { this.accountNumber = number; return this; } public Builder owner(final String owner) { this.owner = owner; return this; } public Builder money(final Money amount) { this.balance = amount; return this; } public Account build() { return new Account(this); } } public static Account copy(Account acc) { return Account.builder() .money(acc.getMoney()) .accountNumber(acc.getAccountNumber()) .owner(acc.getOwner()) .build(); } }
4,206
0.608892
0.608892
151
26.860928
23.857203
134
false
false
0
0
0
0
0
0
0.417219
false
false
5
3d1476786306c4c31099f2eb32640992e0104639
6,176,162,978,987
afb3fccba1aa3fe69889ddf250b0b1760fdd5132
/src/main/java/org/ora/service/ICitaService.java
43f79f5920e8e5c2b87b2608ac502d69cd4a54ed
[]
no_license
PatrickSpace/Veterinaria-Web
https://github.com/PatrickSpace/Veterinaria-Web
9d77c9e27c4854295d9184e69fbbf9788eb413fe
2d0a62487d073cf8f46fd59cba0cbc5c7df3591c
refs/heads/master
2021-07-12T10:18:52.215000
2020-12-17T03:34:53
2020-12-17T03:34:53
226,204,809
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ora.service; import java.util.Date; import java.util.List; import org.ora.entity.Cita; public interface ICitaService { public void insert(Cita cita); public List<Cita> listar(); public List<Cita> listarXFecha(Date dia); public List<Cita> listarCitasNext(); public List<Cita> listarCitasHoy(); public List<Cita> listarXMes(int mes,int anio); public void eliminar(Long id); }
UTF-8
Java
410
java
ICitaService.java
Java
[]
null
[]
package org.ora.service; import java.util.Date; import java.util.List; import org.ora.entity.Cita; public interface ICitaService { public void insert(Cita cita); public List<Cita> listar(); public List<Cita> listarXFecha(Date dia); public List<Cita> listarCitasNext(); public List<Cita> listarCitasHoy(); public List<Cita> listarXMes(int mes,int anio); public void eliminar(Long id); }
410
0.731707
0.731707
23
16.826086
16.377748
48
false
false
0
0
0
0
0
0
1.130435
false
false
5
4e5eff321d4f2f2c3da763017d157ecb65ae00b8
13,340,168,441,937
9d21b4c3e0b1b53e63f01f270500626aeff6da45
/commerce/src/main/java/com/myhangars/order/dao/OrderDaoImpl.java
c82e0f9b587dd704e677adbbe9aba7e5579d8cbc
[]
no_license
kevinthicke/hangar-app-backend
https://github.com/kevinthicke/hangar-app-backend
5977e98f3961c272bb0e9cd44ba9c7d25528df5d
2dfaa05c10927b8480abf7c104acbaff1aeb0c13
refs/heads/master
2020-09-14T00:31:20.547000
2019-12-09T14:58:43
2019-12-09T14:58:43
222,953,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myhangars.order.dao; import com.myhangars.model.UserEntity; import com.myhangars.order.model.Order; import com.myhangars.order.repository.OrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; @Component public class OrderDaoImpl implements OrderDao { @Autowired private OrderRepository orderRepository; @Override public List<Order> findAll() { return this.orderRepository.findAll(); } @Override public List<Order> findByUserEntity(UserEntity userEntity) { return this.orderRepository.findByUserEntity(userEntity); } @Override public Optional<Order> findById(long id) { return this.orderRepository.findById(id); } @Override public Order save(Order order) { return this.orderRepository.save(order); } }
UTF-8
Java
934
java
OrderDaoImpl.java
Java
[]
null
[]
package com.myhangars.order.dao; import com.myhangars.model.UserEntity; import com.myhangars.order.model.Order; import com.myhangars.order.repository.OrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; @Component public class OrderDaoImpl implements OrderDao { @Autowired private OrderRepository orderRepository; @Override public List<Order> findAll() { return this.orderRepository.findAll(); } @Override public List<Order> findByUserEntity(UserEntity userEntity) { return this.orderRepository.findByUserEntity(userEntity); } @Override public Optional<Order> findById(long id) { return this.orderRepository.findById(id); } @Override public Order save(Order order) { return this.orderRepository.save(order); } }
934
0.738758
0.738758
37
24.243244
21.682482
65
false
false
0
0
0
0
0
0
0.351351
false
false
5
c72981a3e09f9c25a97b059db3e235e7ad39fcb8
7,765,300,885,537
a58608f26b52abc14a35939bdb3ce6b3b01a3a59
/Grupo3-FastRequest/src/Model/Funcionario.java
52799b7f47dd41959d9ac8d34a1121a6aa83db88
[]
no_license
Yeltsinn/Fast-Request
https://github.com/Yeltsinn/Fast-Request
3ba4eebccdd8b7e6ffe1a5427103f3e133b8e6c8
ce0f657412778c2b0e8de94f188a271409b0c91d
refs/heads/master
2021-01-16T20:35:42.526000
2013-05-31T16:59:19
2013-05-31T16:59:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Model; public class Funcionario { private int id_funcionario; private String Cpf; private String rg; private String telefone; }
UTF-8
Java
157
java
Funcionario.java
Java
[]
null
[]
package Model; public class Funcionario { private int id_funcionario; private String Cpf; private String rg; private String telefone; }
157
0.694268
0.694268
11
12.272727
11.233804
28
false
false
0
0
0
0
0
0
1
false
false
5
31f721c199ae4e20f77178a965ff433b502c58d6
7,765,300,882,814
d3b4f2de9ea159860255d3c84188b57dc7efa5e1
/BOJ(백준)/BOJ_1181_단어정렬.java
924da983333fa8f461e2edc373d1d02e5a7d4e7c
[]
no_license
lshmn951/algorithm_exercise
https://github.com/lshmn951/algorithm_exercise
091ca7608d32efd92860878de71ce459c7c1b781
efd865faf3dafd94dac77531178b7fd9a7fca4dd
refs/heads/master
2021-01-05T12:37:03.294000
2020-06-09T06:34:14
2020-06-09T06:34:14
241,025,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algo_exercise.BOJ; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class BOJ_1181_단어정렬 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String [] str = new String[n]; for(int i=0;i<n;i++) { str[i] = sc.next(); } Arrays.sort(str,new Comparator<String>() { @Override public int compare(String o1, String o2) { if(o1.length()<o2.length()) { return -1; } else if(o1.length()>o2.length()) { return 1; } else { return o1.compareTo(o2); } } }); String temp = str[0]; System.out.println(temp); for(int i=0;i<n;i++) { if(temp.compareTo(str[i])!=0) { System.out.println(str[i]); temp = str[i]; } } } }
UTF-8
Java
831
java
BOJ_1181_단어정렬.java
Java
[]
null
[]
package algo_exercise.BOJ; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class BOJ_1181_단어정렬 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String [] str = new String[n]; for(int i=0;i<n;i++) { str[i] = sc.next(); } Arrays.sort(str,new Comparator<String>() { @Override public int compare(String o1, String o2) { if(o1.length()<o2.length()) { return -1; } else if(o1.length()>o2.length()) { return 1; } else { return o1.compareTo(o2); } } }); String temp = str[0]; System.out.println(temp); for(int i=0;i<n;i++) { if(temp.compareTo(str[i])!=0) { System.out.println(str[i]); temp = str[i]; } } } }
831
0.592953
0.571081
42
18.595238
14.130445
45
false
false
0
0
0
0
0
0
2.690476
false
false
5
0c9233c8c8a4b3421bd9905d3541ab31d7117a97
22,978,075,096,107
b1472c0470bd5914132275a4a16f94575b5577d8
/algorithms_datastructures/src/test/java/com/lzq/study/lettcode/biweekly/ThirtyTwo.java
09270f48b63e3c0de2b6f579b3f49581b58ec4a4
[]
no_license
liuzhengqiu1127/learning
https://github.com/liuzhengqiu1127/learning
b86de05fc91d6b09fcb5cd2f95c29b3d27c3e8b2
2eb93ad447c617bc13b3100280659c712c9812b4
refs/heads/master
2022-02-26T03:02:07.359000
2022-02-20T05:55:21
2022-02-20T05:55:21
213,910,635
0
0
null
false
2020-10-13T16:49:26
2019-10-09T12:18:58
2020-10-11T08:17:31
2020-10-13T16:49:24
438
0
0
6
Java
false
false
package com.lzq.study.lettcode.biweekly; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class ThirtyTwo { public int findKthPositive(int[] arr, int k) { int max = arr[arr.length-1]; int less = max - arr.length; if (k <= less){ for (int num=1; num <= max; num++){ for (int cur : arr){ if (cur == num){ break; }else if (cur < num){ continue; }else { k--; break; } } if (k == 0){ return num; } } } return max + (k - less); } public boolean canConvertString(String s, String t, int k) { if (s.length() != t.length()) return false; char[] sourceArr = s.toCharArray(); char[] targetArr = t.toCharArray(); int len = s.length(); Map<Integer, Integer> record = new HashMap<>(); for (int i=0; i < len; i++){ int distant = targetArr[i] - sourceArr[i]; if (distant==0) { continue; }else if (distant > 0 && distant > k){ return false; }else if (distant > 0 && distant <= k){ if (record.containsKey(distant)){ int mul = 26 * record.get(distant); if (distant + mul > k) return false; record.put(distant, record.get(distant) + 1); }else{ record.put(distant, 1); } }else if (distant < 0 && (26+distant) > k){ return false; }else { if (record.containsKey(26+distant)){ int mul = 26 * record.get(26+distant); if (26+distant + mul > k) return false; record.put(26+distant, record.get(26+distant) + 1); }else { record.put(26+distant, 1); } } } return true; } public int minInsertions(String s) { int result = 0; int record = 0; for (char ch : s.toCharArray()){ if (ch == '(' && record%2!=0){ result++; record += -1; }else if (ch == '(' && record%2==0){ record += -2; } else if (ch == ')' && record >= 0){ result++; record += -1; } else { record += 1; } } if (record == 0) return result; return result + Math.abs(record); } public int longestAwesome(String s){ if (s.length() <= 1) return s.length(); Map<Integer,Integer> umap = new HashMap<>(); umap.put(0,-1); int state = 0; int ans = 1; for (int i = 0; i<s.length(); i++){ /** * 0: 1 * 1: 10 * 2: 100 * 3: 1000 * 统计前缀每个字符异或求值,可以分为三种情况 * 如果是回文分为如下两种情况: * 1,state == 0, 表示已经为回文 * 2,state == (1,10,100,1000,...,1000000000)任一一个,表示只有一个奇数,也是回文 * 如果不是回文: * 1和2都不满足,这个时候就把这个state和下标进行记录 */ int mask = 1 << (s.charAt(i) - '0'); state ^= mask; /** * 解决场景问题: * 123321 * 562323 */ if (umap.containsKey(state)){ ans = Math.max(i-umap.get(state), ans); } /** * 解决场景问题: * 12321 * 5612321 */ mask = 1; int cnt = 10; while (cnt-- > 0){ int key = state ^ mask; if (umap.containsKey(key)){ ans = Math.max(i-umap.get(key),ans); } mask<<=1; } if (!umap.containsKey(state)){ umap.put(state,i); } } return ans; } @Test public void test(){ System.out.println(longestAwesome("12332")); } }
UTF-8
Java
4,525
java
ThirtyTwo.java
Java
[]
null
[]
package com.lzq.study.lettcode.biweekly; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class ThirtyTwo { public int findKthPositive(int[] arr, int k) { int max = arr[arr.length-1]; int less = max - arr.length; if (k <= less){ for (int num=1; num <= max; num++){ for (int cur : arr){ if (cur == num){ break; }else if (cur < num){ continue; }else { k--; break; } } if (k == 0){ return num; } } } return max + (k - less); } public boolean canConvertString(String s, String t, int k) { if (s.length() != t.length()) return false; char[] sourceArr = s.toCharArray(); char[] targetArr = t.toCharArray(); int len = s.length(); Map<Integer, Integer> record = new HashMap<>(); for (int i=0; i < len; i++){ int distant = targetArr[i] - sourceArr[i]; if (distant==0) { continue; }else if (distant > 0 && distant > k){ return false; }else if (distant > 0 && distant <= k){ if (record.containsKey(distant)){ int mul = 26 * record.get(distant); if (distant + mul > k) return false; record.put(distant, record.get(distant) + 1); }else{ record.put(distant, 1); } }else if (distant < 0 && (26+distant) > k){ return false; }else { if (record.containsKey(26+distant)){ int mul = 26 * record.get(26+distant); if (26+distant + mul > k) return false; record.put(26+distant, record.get(26+distant) + 1); }else { record.put(26+distant, 1); } } } return true; } public int minInsertions(String s) { int result = 0; int record = 0; for (char ch : s.toCharArray()){ if (ch == '(' && record%2!=0){ result++; record += -1; }else if (ch == '(' && record%2==0){ record += -2; } else if (ch == ')' && record >= 0){ result++; record += -1; } else { record += 1; } } if (record == 0) return result; return result + Math.abs(record); } public int longestAwesome(String s){ if (s.length() <= 1) return s.length(); Map<Integer,Integer> umap = new HashMap<>(); umap.put(0,-1); int state = 0; int ans = 1; for (int i = 0; i<s.length(); i++){ /** * 0: 1 * 1: 10 * 2: 100 * 3: 1000 * 统计前缀每个字符异或求值,可以分为三种情况 * 如果是回文分为如下两种情况: * 1,state == 0, 表示已经为回文 * 2,state == (1,10,100,1000,...,1000000000)任一一个,表示只有一个奇数,也是回文 * 如果不是回文: * 1和2都不满足,这个时候就把这个state和下标进行记录 */ int mask = 1 << (s.charAt(i) - '0'); state ^= mask; /** * 解决场景问题: * 123321 * 562323 */ if (umap.containsKey(state)){ ans = Math.max(i-umap.get(state), ans); } /** * 解决场景问题: * 12321 * 5612321 */ mask = 1; int cnt = 10; while (cnt-- > 0){ int key = state ^ mask; if (umap.containsKey(key)){ ans = Math.max(i-umap.get(key),ans); } mask<<=1; } if (!umap.containsKey(state)){ umap.put(state,i); } } return ans; } @Test public void test(){ System.out.println(longestAwesome("12332")); } }
4,525
0.387793
0.359248
153
27.163399
17.359127
74
false
false
0
0
0
0
0
0
0.535948
false
false
5
48185d6d59f83a6d4e565bbf1a0980250a320d31
13,846,974,574,593
a952be207f118b96f3289709d6e7c1be080d2e88
/src/oocl/server/dao/DeleteDao.java
88ceb4f5596758d55ab50012423a823e3e8d2f1b
[]
no_license
chenhaoxian/ita_project
https://github.com/chenhaoxian/ita_project
b0209dd05cef15d164c7f96a55148c85fb29efd4
d35bee3dc27e4e3a378a24a6ad5a84a407e42c40
refs/heads/master
2021-01-17T19:20:19.741000
2016-07-18T09:55:06
2016-07-18T09:55:06
63,380,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oocl.server.dao; public interface DeleteDao { public int deleteDepart(int id); public int deletePerson(int id); }
UTF-8
Java
126
java
DeleteDao.java
Java
[]
null
[]
package oocl.server.dao; public interface DeleteDao { public int deleteDepart(int id); public int deletePerson(int id); }
126
0.761905
0.761905
7
17
14.716366
33
false
false
0
0
0
0
0
0
0.714286
false
false
5
26fba857af52ddd74ddd01fda8725563b6ccdb87
26,731,876,505,323
8a78ee778efe7f8c67125091fa7c88899d110b39
/workspace/Basic_ch06/src/test_encapsulation/MyProfile.java
1dce39f9ae2845f8569f8cb9dce78d1a92798ba3
[]
no_license
IceDice7912/Java2
https://github.com/IceDice7912/Java2
4bd9a37d63f2c9823ef195eea610bcbfea31ea7a
b1de54bda20363b17dee2d515420670164e42aae
refs/heads/master
2023-03-23T14:48:25.063000
2021-03-03T03:00:22
2021-03-03T03:00:22
337,696,683
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test_encapsulation; public class MyProfile { String name="전은수"; MyDate birthday=new MyDate(); public void setBirthday() { birthday.setYear(1996); birthday.setMonth(10); birthday.setDay(25); System.out.println(birthday.getYear()+"년\n"+birthday.getMonth()+"월\n"+birthday.getDay()+"일\n"); } }
UTF-8
Java
332
java
MyProfile.java
Java
[ { "context": "sulation;\n\npublic class MyProfile {\n\tString name=\"전은수\";\n\tMyDate birthday=new MyDate();\n\t\n\tpublic void s", "end": 71, "score": 0.9995543360710144, "start": 68, "tag": "NAME", "value": "전은수" } ]
null
[]
package test_encapsulation; public class MyProfile { String name="전은수"; MyDate birthday=new MyDate(); public void setBirthday() { birthday.setYear(1996); birthday.setMonth(10); birthday.setDay(25); System.out.println(birthday.getYear()+"년\n"+birthday.getMonth()+"월\n"+birthday.getDay()+"일\n"); } }
332
0.690625
0.665625
16
19
23.29163
97
false
false
0
0
0
0
0
0
1.5625
false
false
5
5a05e20c49f648a5d8cf9741c3e6d177b5bf81f1
32,203,664,852,173
a53641b03889d678c97afdab895568a77883514a
/KFLIX/src/main/java/com/kflix/login/KakaoLoginVO.java
aa7466c79ee765c4d1dadaf83d45486856766930
[]
no_license
byunghwi/k-flix
https://github.com/byunghwi/k-flix
e4ab0d722b03953e9e3d879afe235ab6f227f833
ae54167b0496f23c4e7bce316254ffa9f40a6ce4
refs/heads/main
2023-03-20T03:10:22.567000
2021-03-12T07:21:30
2021-03-12T07:21:30
337,791,908
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kflix.login; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HTTP; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.JsonNode; import com.google.gson.JsonObject; @Component public class KakaoLoginVO { /* [카카오] 인증 요청문을 구성하는 파라미터 */ // client_id: String / 앱 생성 시 발급받은 REST API 키 // response_type: String / code로 고정 // redirect_uri: String / 인가 코드가 리다이렉트될 URI /// oauth/authorize?client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}&response_type=code private final static String CLIENT_ID = "ab797bb7c662ff625fd22e4e520ce0d8"; private final static String REDIRECT_URI = "http://localhost:8081/kflix/kakao/callback"; private final static String KAKAOAPIURL = "https://kauth.kakao.com"; /* 카카오 아이디로 인증 URL 생성 Method */ public String getAuthorizationUrl() { // https://kauth.kakao.com/oauth/authorize // https://kauth.kakao.com/oauth/authorize?client_id=b5f85af25d1bdf961d4f2016bafe3c6e&redirect_uri=http://localhost:8000/login&response_type=code String requestUrl = KakaoLoginApi.instance().getAuthorizationBaseUrl() + "?client_id=" + CLIENT_ID + "&redirect_uri=" + REDIRECT_URI + "&response_type=code"; return requestUrl; } /* 카카오 아이디로 Callback 처리 및 AccessToken 획득 Method */ public String getAccessToken(String code) throws IOException { String accessToken = ""; RestTemplate restTemplate = new RestTemplate(); String requestUrl = "/oauth/token"; URI uri = URI.create(KAKAOAPIURL + requestUrl); HttpHeaders headers = new org.springframework.http.HttpHeaders(); MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); parameters.set("grant_type", "authorization_code"); parameters.set("client_id", CLIENT_ID); parameters.set("redirect_uri", REDIRECT_URI); parameters.set("code", code); HttpEntity<MultiValueMap<String, Object>> restRequest = new HttpEntity<MultiValueMap<String, Object>>( parameters, headers); ResponseEntity<JSONObject> apiResponse = restTemplate.postForEntity(uri, restRequest, JSONObject.class); JSONObject responseBody = apiResponse.getBody(); accessToken = (String) responseBody.get("access_token"); return accessToken; } // // 카카오 사용자 id 추출 // public Member getKakaoUniqueNo(String accessToken) throws Exception { // // String kakaoUniqueNo = ""; // // // restTemplate을 사용하여 API 호출 // RestTemplate restTemplate = new RestTemplate(); // String reqUrl = "/v2/user/me"; // URI uri = URI.create(KAKAOAPIURL + reqUrl); // // HttpHeaders headers = new HttpHeaders(); // headers.set("Authorization", "bearer " + accessToken); // headers.set("bearer", accessToken); // // MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); // parameters.add("property_keys", "[\"kakao_account\"]"); // // HttpEntity<MultiValueMap<String, Object>> restRequest = new HttpEntity<>(parameters, headers); // ResponseEntity<JSONObject> apiResponse = restTemplate.postForEntity(uri, restRequest, JSONObject.class); // JSONObject responseBody = apiResponse.getBody(); // // System.out.println("[KakaoLoginVO] responseBody 객체 > " + responseBody); // kakaoUniqueNo = responseBody.get("kakao_account").toString(); // // return null; // // } public JSONObject getKakaoUserInfo(String accessToken) throws ParseException{ final String RequestUrl = "https://kapi.kakao.com/v2/user/me"; final HttpClient client = HttpClientBuilder.create().build(); final HttpPost post = new HttpPost(RequestUrl); //post.addHeader("Content-Type", "application/json;charset=UTF-8"); // add header post.addHeader("Authorization", "Bearer " + accessToken); //JsonNode returnNode = null; JSONParser jsonParser = new JSONParser(); JSONObject myObject = null; String result = null; try { final HttpResponse response = client.execute(post); org.apache.http.HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); result = convertStreamToString(instream); Object obj = jsonParser.parse( result ); myObject = (JSONObject) obj; System.out.println("RESPONSE: " + myObject); instream.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } return myObject; } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
UTF-8
Java
5,968
java
KakaoLoginVO.java
Java
[ { "context": " static String KAKAOAPIURL = \"https://kauth.kakao.com\";\n\n\t/* 카카오 아이디로 인증 URL 생성 Method */\n\tpublic Strin", "end": 1611, "score": 0.8982433080673218, "start": 1608, "tag": "EMAIL", "value": "com" }, { "context": " Object>();\n//\t\tparameters.add(\"property_keys\",...
null
[]
package com.kflix.login; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HTTP; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.JsonNode; import com.google.gson.JsonObject; @Component public class KakaoLoginVO { /* [카카오] 인증 요청문을 구성하는 파라미터 */ // client_id: String / 앱 생성 시 발급받은 REST API 키 // response_type: String / code로 고정 // redirect_uri: String / 인가 코드가 리다이렉트될 URI /// oauth/authorize?client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}&response_type=code private final static String CLIENT_ID = "ab797bb7c662ff625fd22e4e520ce0d8"; private final static String REDIRECT_URI = "http://localhost:8081/kflix/kakao/callback"; private final static String KAKAOAPIURL = "https://kauth.kakao.com"; /* 카카오 아이디로 인증 URL 생성 Method */ public String getAuthorizationUrl() { // https://kauth.kakao.com/oauth/authorize // https://kauth.kakao.com/oauth/authorize?client_id=b5f85af25d1bdf961d4f2016bafe3c6e&redirect_uri=http://localhost:8000/login&response_type=code String requestUrl = KakaoLoginApi.instance().getAuthorizationBaseUrl() + "?client_id=" + CLIENT_ID + "&redirect_uri=" + REDIRECT_URI + "&response_type=code"; return requestUrl; } /* 카카오 아이디로 Callback 처리 및 AccessToken 획득 Method */ public String getAccessToken(String code) throws IOException { String accessToken = ""; RestTemplate restTemplate = new RestTemplate(); String requestUrl = "/oauth/token"; URI uri = URI.create(KAKAOAPIURL + requestUrl); HttpHeaders headers = new org.springframework.http.HttpHeaders(); MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); parameters.set("grant_type", "authorization_code"); parameters.set("client_id", CLIENT_ID); parameters.set("redirect_uri", REDIRECT_URI); parameters.set("code", code); HttpEntity<MultiValueMap<String, Object>> restRequest = new HttpEntity<MultiValueMap<String, Object>>( parameters, headers); ResponseEntity<JSONObject> apiResponse = restTemplate.postForEntity(uri, restRequest, JSONObject.class); JSONObject responseBody = apiResponse.getBody(); accessToken = (String) responseBody.get("access_token"); return accessToken; } // // 카카오 사용자 id 추출 // public Member getKakaoUniqueNo(String accessToken) throws Exception { // // String kakaoUniqueNo = ""; // // // restTemplate을 사용하여 API 호출 // RestTemplate restTemplate = new RestTemplate(); // String reqUrl = "/v2/user/me"; // URI uri = URI.create(KAKAOAPIURL + reqUrl); // // HttpHeaders headers = new HttpHeaders(); // headers.set("Authorization", "bearer " + accessToken); // headers.set("bearer", accessToken); // // MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); // parameters.add("property_keys", "[\"kakao_account\"]"); // // HttpEntity<MultiValueMap<String, Object>> restRequest = new HttpEntity<>(parameters, headers); // ResponseEntity<JSONObject> apiResponse = restTemplate.postForEntity(uri, restRequest, JSONObject.class); // JSONObject responseBody = apiResponse.getBody(); // // System.out.println("[KakaoLoginVO] responseBody 객체 > " + responseBody); // kakaoUniqueNo = responseBody.get("kakao_account").toString(); // // return null; // // } public JSONObject getKakaoUserInfo(String accessToken) throws ParseException{ final String RequestUrl = "https://kapi.kakao.com/v2/user/me"; final HttpClient client = HttpClientBuilder.create().build(); final HttpPost post = new HttpPost(RequestUrl); //post.addHeader("Content-Type", "application/json;charset=UTF-8"); // add header post.addHeader("Authorization", "Bearer " + accessToken); //JsonNode returnNode = null; JSONParser jsonParser = new JSONParser(); JSONObject myObject = null; String result = null; try { final HttpResponse response = client.execute(post); org.apache.http.HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); result = convertStreamToString(instream); Object obj = jsonParser.parse( result ); myObject = (JSONObject) obj; System.out.println("RESPONSE: " + myObject); instream.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } return myObject; } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
5,968
0.715909
0.708161
173
32.572254
28.257931
147
false
false
0
0
0
0
0
0
1.618497
false
false
5
d7a3dddd4c78716acbc1f404071f4a02040983a8
4,166,118,295,995
6b803b192fc42119287ea19f000b6b28f2257540
/src/com/ivyinfo/feiying/adapter/FavChannelListAdapter.java
3d8585b87aa716947d270834598ff6e8d1eb3d04
[]
no_license
eltld/feiying_android
https://github.com/eltld/feiying_android
4f8c44d5c0bd74b53d8ae93cb385dcb528c11aa4
e2c9ff597af3583e3cd173bd1e8ba9cd2eb41c0b
refs/heads/master
2020-12-27T15:00:39.026000
2012-11-30T04:19:51
2012-11-30T04:19:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ivyinfo.feiying.adapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.ivyinfo.feiying.android.R; import com.ivyinfo.feiying.listitemholder.Channel; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.TextView; public class FavChannelListAdapter extends BaseAdapter { private LayoutInflater mInflater; private JSONArray jsonChannelList; public FavChannelListAdapter(Context context) { this.mInflater = LayoutInflater.from(context); jsonChannelList = new JSONArray(); } public void setChannelData(JSONArray channelList) { this.jsonChannelList = channelList; notifyDataSetChanged(); } public void removeAll() { jsonChannelList = new JSONArray(); notifyDataSetChanged(); } @Override public int getCount() { return jsonChannelList.length(); } @Override public Object getItem(int position) { try { return jsonChannelList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Channel channel = new Channel(); if (convertView == null) { convertView = mInflater.inflate(R.layout.channellist, null); channel.img_btn = (ImageButton) convertView .findViewById(R.id.channel_img); channel.title = (TextView) convertView .findViewById(R.id.channel_name); convertView.setTag(channel); } else { channel = (Channel) convertView.getTag(); } JSONObject jsonChannel = (JSONObject) getItem(position); if (jsonChannel != null) { try { String title = jsonChannel.getString(Channel.TITLE); int count = jsonChannel.getInt(Channel.COUNT); channel.title.setText(title + "(" + count + ")"); channel.img_btn.setImageResource(jsonChannel .getInt(Channel.IMGPATH)); } catch (JSONException e) { e.printStackTrace(); } } return convertView; } }
UTF-8
Java
2,169
java
FavChannelListAdapter.java
Java
[]
null
[]
package com.ivyinfo.feiying.adapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.ivyinfo.feiying.android.R; import com.ivyinfo.feiying.listitemholder.Channel; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.TextView; public class FavChannelListAdapter extends BaseAdapter { private LayoutInflater mInflater; private JSONArray jsonChannelList; public FavChannelListAdapter(Context context) { this.mInflater = LayoutInflater.from(context); jsonChannelList = new JSONArray(); } public void setChannelData(JSONArray channelList) { this.jsonChannelList = channelList; notifyDataSetChanged(); } public void removeAll() { jsonChannelList = new JSONArray(); notifyDataSetChanged(); } @Override public int getCount() { return jsonChannelList.length(); } @Override public Object getItem(int position) { try { return jsonChannelList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Channel channel = new Channel(); if (convertView == null) { convertView = mInflater.inflate(R.layout.channellist, null); channel.img_btn = (ImageButton) convertView .findViewById(R.id.channel_img); channel.title = (TextView) convertView .findViewById(R.id.channel_name); convertView.setTag(channel); } else { channel = (Channel) convertView.getTag(); } JSONObject jsonChannel = (JSONObject) getItem(position); if (jsonChannel != null) { try { String title = jsonChannel.getString(Channel.TITLE); int count = jsonChannel.getInt(Channel.COUNT); channel.title.setText(title + "(" + count + ")"); channel.img_btn.setImageResource(jsonChannel .getInt(Channel.IMGPATH)); } catch (JSONException e) { e.printStackTrace(); } } return convertView; } }
2,169
0.736284
0.736284
89
23.370787
19.16597
72
false
false
0
0
0
0
0
0
1.898876
false
false
5
57bda07749984032c345f6d64fcbc2ab63c112a7
28,930,899,723,218
14154c28abc2ed8b897b8da7e988c921d1d512c3
/product-crawler/src/main/java/com/mode/ippool/htmlparse/URLFecter.java
af7d430cd498243ade9b001499d56f2c30227f5c
[]
no_license
yuerugou54/javaWeb
https://github.com/yuerugou54/javaWeb
2c519598dd29944d6f453410a6f65eb483b4ced3
a7554879bda61341512976d697b388c92497ca4a
refs/heads/master
2021-05-06T05:50:02.634000
2018-06-26T06:22:21
2018-06-26T06:22:21
115,171,211
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mode.ippool.htmlparse; import static java.lang.System.out; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import com.mode.ippool.httpbowser.MyHttpResponse; import com.mode.ippool.ipmodel.IPMessage; public class URLFecter { // 使用代理进行爬取 public static boolean urlParseNN(String url, String ip, String port, List<IPMessage> ipMessages1) { // 调用一个类使其返回html源码 String html = MyHttpResponse.getHtml(url, ip, port); if (html != null) { // 将html解析成DOM结构 Document document = Jsoup.parse(html); // 提取所需要的数据 Elements trs = document.select("table[id=ip_list]").select("tbody").select("tr"); for (int i = 1; i < trs.size(); i++) { IPMessage ipMessage = new IPMessage(); String ipAddress = trs.get(i).select("td").get(1).text(); String ipPort = trs.get(i).select("td").get(2).text(); String ipType = trs.get(i).select("td").get(5).text(); String ipSpeed = trs.get(i).select("td").get(6).select("div[class=bar]") .attr("title"); ipMessage.setIPAddress(ipAddress); ipMessage.setIPPort(Integer.valueOf(ipPort)); ipMessage.setIPType(ipType); ipMessage.setIPSpeed(ipSpeed); ipMessages1.add(ipMessage); } return true; } else { out.println(ip + ": " + port + " 代理不可用"); return false; } } // 使用本机IP爬取xici代理网站的第一页 public static List<IPMessage> urlParseNN(List<IPMessage> ipMessagesList, String xcUrl) { // String url = "http://www.xicidaili.com/wn/1"; String html = MyHttpResponse.getHtml(xcUrl); // 将html解析成DOM结构 Document document = Jsoup.parse(html); // 提取所需要的数据 Elements trs = document.select("table[id=ip_list]").select("tbody").select("tr"); // TODO 也可以设置判断第一个list值与爬取出来的第一个值对比,如果不一致就更新list for (int i = 1; i < trs.size(); i++) { IPMessage ipMessage = new IPMessage(); String ipAddress = trs.get(i).select("td").get(1).text(); String ipPort = trs.get(i).select("td").get(2).text(); String ipType = trs.get(i).select("td").get(5).text(); String ipSpeed = trs.get(i).select("td").get(6).select("div[class=bar]").attr("title"); ipMessage.setIPAddress(ipAddress); ipMessage.setIPPort(Integer.valueOf(ipPort)); ipMessage.setIPType(ipType); ipMessage.setIPSpeed(ipSpeed); ipMessagesList.add(ipMessage); } return ipMessagesList; } public static void main(String[] args) { List<IPMessage> ipMessages = new ArrayList<>(); URLFecter.urlParseNN(ipMessages, "http://www.xicidaili.com/nn/1"); for (IPMessage ipMessage : ipMessages) { System.out.println(ipMessage.getIPAddress()); } } }
UTF-8
Java
3,296
java
URLFecter.java
Java
[]
null
[]
package com.mode.ippool.htmlparse; import static java.lang.System.out; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import com.mode.ippool.httpbowser.MyHttpResponse; import com.mode.ippool.ipmodel.IPMessage; public class URLFecter { // 使用代理进行爬取 public static boolean urlParseNN(String url, String ip, String port, List<IPMessage> ipMessages1) { // 调用一个类使其返回html源码 String html = MyHttpResponse.getHtml(url, ip, port); if (html != null) { // 将html解析成DOM结构 Document document = Jsoup.parse(html); // 提取所需要的数据 Elements trs = document.select("table[id=ip_list]").select("tbody").select("tr"); for (int i = 1; i < trs.size(); i++) { IPMessage ipMessage = new IPMessage(); String ipAddress = trs.get(i).select("td").get(1).text(); String ipPort = trs.get(i).select("td").get(2).text(); String ipType = trs.get(i).select("td").get(5).text(); String ipSpeed = trs.get(i).select("td").get(6).select("div[class=bar]") .attr("title"); ipMessage.setIPAddress(ipAddress); ipMessage.setIPPort(Integer.valueOf(ipPort)); ipMessage.setIPType(ipType); ipMessage.setIPSpeed(ipSpeed); ipMessages1.add(ipMessage); } return true; } else { out.println(ip + ": " + port + " 代理不可用"); return false; } } // 使用本机IP爬取xici代理网站的第一页 public static List<IPMessage> urlParseNN(List<IPMessage> ipMessagesList, String xcUrl) { // String url = "http://www.xicidaili.com/wn/1"; String html = MyHttpResponse.getHtml(xcUrl); // 将html解析成DOM结构 Document document = Jsoup.parse(html); // 提取所需要的数据 Elements trs = document.select("table[id=ip_list]").select("tbody").select("tr"); // TODO 也可以设置判断第一个list值与爬取出来的第一个值对比,如果不一致就更新list for (int i = 1; i < trs.size(); i++) { IPMessage ipMessage = new IPMessage(); String ipAddress = trs.get(i).select("td").get(1).text(); String ipPort = trs.get(i).select("td").get(2).text(); String ipType = trs.get(i).select("td").get(5).text(); String ipSpeed = trs.get(i).select("td").get(6).select("div[class=bar]").attr("title"); ipMessage.setIPAddress(ipAddress); ipMessage.setIPPort(Integer.valueOf(ipPort)); ipMessage.setIPType(ipType); ipMessage.setIPSpeed(ipSpeed); ipMessagesList.add(ipMessage); } return ipMessagesList; } public static void main(String[] args) { List<IPMessage> ipMessages = new ArrayList<>(); URLFecter.urlParseNN(ipMessages, "http://www.xicidaili.com/nn/1"); for (IPMessage ipMessage : ipMessages) { System.out.println(ipMessage.getIPAddress()); } } }
3,296
0.581935
0.577419
90
33.444443
27.073608
99
false
false
0
0
0
0
0
0
0.6
false
false
5
024bd2360c8608d82cc4c6109940084b0c719d9f
28,930,899,721,572
e23bf0868388599c11b1dc335db35c2bfe077f2f
/app/src/main/java/duong/huy/huong/healthcare/db/User_Info.java
11d2cdc19302c894e722275a46f1b68e8ba811b0
[]
no_license
vukihai/AndroidHealthcareApp
https://github.com/vukihai/AndroidHealthcareApp
843077f69ac3301fe84cffcf0ef211e2923341ff
0ea1448df85eea033b0bc30b51f620240842f27f
refs/heads/master
2020-04-28T11:26:07.579000
2019-05-23T08:21:16
2019-05-23T08:21:16
175,239,191
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package duong.huy.huong.healthcare.db; import android.os.Bundle; import java.util.Date; public class User_Info { public static final String COL__ID = "_ID"; public static final String COL_NAME = "name"; public static final String COL_SEX = "sex"; public static final String COL_DATE_OF_BIRTH = "date_of_birth"; public static final String COL_WEIGHT = "weight"; public static final String COL_HEIGHT = "height"; private Integer m_ID; private String mname; private String msex; private String mdate_of_birth; private String mweight; private String mheight; public User_Info() { } public User_Info(Integer _ID, String name, String sex, String date_of_birth, String weight, String height) { this.m_ID = _ID; this.mname = name; this.msex = sex; this.mdate_of_birth = date_of_birth; this.mweight = weight; this.mheight = height; } public Integer get_ID() { return m_ID; } public void set_ID(Integer _ID) { this.m_ID = _ID; } public String getname() { return mname; } public void setname(String name) { this.mname = name; } public String getsex() { return msex; } public void setsex(String sex) { this.msex = sex; } public String getdate_of_birth() { return mdate_of_birth; } public void setdate_of_birth(String date_of_birth) { this.mdate_of_birth = date_of_birth; } public String getweight() { return mweight; } public void setweight(String weight) { this.mweight = weight; } public String getheight() { return mheight; } public void setheight(String height) { this.mheight = height; } public Bundle toBundle() { Bundle b = new Bundle(); b.putInt(COL__ID, this.m_ID); b.putString(COL_NAME, this.mname); b.putString(COL_SEX, this.msex); b.putString(COL_DATE_OF_BIRTH, this.mdate_of_birth); b.putString(COL_WEIGHT, this.mweight); b.putString(COL_HEIGHT, this.mheight); return b; } public User_Info(Bundle b) { if (b != null) { this.m_ID = b.getInt(COL__ID); this.mname = b.getString(COL_NAME); this.msex = b.getString(COL_SEX); this.mdate_of_birth = b.getString(COL_DATE_OF_BIRTH); this.mweight = b.getString(COL_WEIGHT); this.mheight = b.getString(COL_HEIGHT); } } @Override public String toString() { return "User_Info{" + " m_ID=" + m_ID + ", mname='" + mname + '\'' + ", msex='" + msex + '\'' + ", mdate_of_birth='" + mdate_of_birth + '\'' + ", mweight='" + mweight + '\'' + ", mheight='" + mheight + '\'' + '}'; } }
UTF-8
Java
2,915
java
User_Info.java
Java
[ { "context": " \" m_ID=\" + m_ID +\n \", mname='\" + mname + '\\'' +\n \", msex='\" + msex + '\\'' +\n ", "end": 2690, "score": 0.8839787244796753, "start": 2685, "tag": "NAME", "value": "mname" } ]
null
[]
package duong.huy.huong.healthcare.db; import android.os.Bundle; import java.util.Date; public class User_Info { public static final String COL__ID = "_ID"; public static final String COL_NAME = "name"; public static final String COL_SEX = "sex"; public static final String COL_DATE_OF_BIRTH = "date_of_birth"; public static final String COL_WEIGHT = "weight"; public static final String COL_HEIGHT = "height"; private Integer m_ID; private String mname; private String msex; private String mdate_of_birth; private String mweight; private String mheight; public User_Info() { } public User_Info(Integer _ID, String name, String sex, String date_of_birth, String weight, String height) { this.m_ID = _ID; this.mname = name; this.msex = sex; this.mdate_of_birth = date_of_birth; this.mweight = weight; this.mheight = height; } public Integer get_ID() { return m_ID; } public void set_ID(Integer _ID) { this.m_ID = _ID; } public String getname() { return mname; } public void setname(String name) { this.mname = name; } public String getsex() { return msex; } public void setsex(String sex) { this.msex = sex; } public String getdate_of_birth() { return mdate_of_birth; } public void setdate_of_birth(String date_of_birth) { this.mdate_of_birth = date_of_birth; } public String getweight() { return mweight; } public void setweight(String weight) { this.mweight = weight; } public String getheight() { return mheight; } public void setheight(String height) { this.mheight = height; } public Bundle toBundle() { Bundle b = new Bundle(); b.putInt(COL__ID, this.m_ID); b.putString(COL_NAME, this.mname); b.putString(COL_SEX, this.msex); b.putString(COL_DATE_OF_BIRTH, this.mdate_of_birth); b.putString(COL_WEIGHT, this.mweight); b.putString(COL_HEIGHT, this.mheight); return b; } public User_Info(Bundle b) { if (b != null) { this.m_ID = b.getInt(COL__ID); this.mname = b.getString(COL_NAME); this.msex = b.getString(COL_SEX); this.mdate_of_birth = b.getString(COL_DATE_OF_BIRTH); this.mweight = b.getString(COL_WEIGHT); this.mheight = b.getString(COL_HEIGHT); } } @Override public String toString() { return "User_Info{" + " m_ID=" + m_ID + ", mname='" + mname + '\'' + ", msex='" + msex + '\'' + ", mdate_of_birth='" + mdate_of_birth + '\'' + ", mweight='" + mweight + '\'' + ", mheight='" + mheight + '\'' + '}'; } }
2,915
0.554031
0.554031
118
23.70339
20.149151
112
false
false
0
0
0
0
0
0
0.542373
false
false
5
226ca72e206ac8c6afc35fb01165a8aa2dfdcb24
584,115,558,360
b076da2232adbeb0409a6cde54b499ae16c97f40
/src/com/ccsdt/factoryBean/CarFactoryBean.java
4114f0ae61ab3e8ddb30e7ef4b33b8840533b90e
[]
no_license
Chen-Fengling/spring
https://github.com/Chen-Fengling/spring
cbaa6a0ecf1ae5855987db23479ba4763d95bd6c
e04abb78228bbf52072c71f8e77876604cc19dd8
refs/heads/master
2021-01-21T18:21:55.116000
2017-06-17T16:08:50
2017-06-17T16:08:50
92,039,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ccsdt.factoryBean; import org.springframework.beans.factory.FactoryBean; /** * Created by HP on 2017/6/10. */ public class CarFactoryBean implements FactoryBean{ private String brand; /** * 自定义的FactoryBean需要实现FactoryBean中的三个方法 */ @Override public Object getObject() throws Exception { return new Car(brand,50000.002); } @Override public Class<?> getObjectType() { return Car.class; } @Override public boolean isSingleton() { return true; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } }
UTF-8
Java
703
java
CarFactoryBean.java
Java
[ { "context": "work.beans.factory.FactoryBean;\n\n/**\n * Created by HP on 2017/6/10.\n */\npublic class CarFactoryBean imp", "end": 107, "score": 0.8126221299171448, "start": 105, "tag": "USERNAME", "value": "HP" } ]
null
[]
package com.ccsdt.factoryBean; import org.springframework.beans.factory.FactoryBean; /** * Created by HP on 2017/6/10. */ public class CarFactoryBean implements FactoryBean{ private String brand; /** * 自定义的FactoryBean需要实现FactoryBean中的三个方法 */ @Override public Object getObject() throws Exception { return new Car(brand,50000.002); } @Override public Class<?> getObjectType() { return Car.class; } @Override public boolean isSingleton() { return true; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } }
703
0.628148
0.605926
36
17.75
16.844675
53
false
false
0
0
0
0
0
0
0.25
false
false
5
3eafa82b43f1f4c1c6ff15d8a6752c305058a0b1
25,409,026,590,860
3180c5a659d5bfdbf42ab07dfcc64667f738f9b3
/src/android/support/v4/widget/EdgeEffectCompat$BaseEdgeEffectImpl.java
5d06e4df2d350694902ec85678dab456045af7be
[]
no_license
tinyx3k/ZaloRE
https://github.com/tinyx3k/ZaloRE
4b4118c789310baebaa060fc8aa68131e4786ffb
fc8d2f7117a95aea98a68ad8d5009d74e977d107
refs/heads/master
2023-05-03T16:21:53.296000
2013-05-18T14:08:34
2013-05-18T14:08:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.support.v4.widget; import android.content.Context; import android.graphics.Canvas; class EdgeEffectCompat$BaseEdgeEffectImpl implements EdgeEffectCompat.EdgeEffectImpl { public void a(Object paramObject, int paramInt1, int paramInt2) { } public boolean a(Object paramObject, float paramFloat) { return false; } public boolean a(Object paramObject, Canvas paramCanvas) { return false; } public Object b(Context paramContext) { return null; } public void c(Object paramObject) { } public boolean e(Object paramObject) { return true; } public boolean f(Object paramObject) { return false; } } /* Location: /home/danghvu/0day/Zalo/Zalo_1.0.8_dex2jar.jar * Qualified Name: android.support.v4.widget.EdgeEffectCompat.BaseEdgeEffectImpl * JD-Core Version: 0.6.2 */
UTF-8
Java
866
java
EdgeEffectCompat$BaseEdgeEffectImpl.java
Java
[]
null
[]
package android.support.v4.widget; import android.content.Context; import android.graphics.Canvas; class EdgeEffectCompat$BaseEdgeEffectImpl implements EdgeEffectCompat.EdgeEffectImpl { public void a(Object paramObject, int paramInt1, int paramInt2) { } public boolean a(Object paramObject, float paramFloat) { return false; } public boolean a(Object paramObject, Canvas paramCanvas) { return false; } public Object b(Context paramContext) { return null; } public void c(Object paramObject) { } public boolean e(Object paramObject) { return true; } public boolean f(Object paramObject) { return false; } } /* Location: /home/danghvu/0day/Zalo/Zalo_1.0.8_dex2jar.jar * Qualified Name: android.support.v4.widget.EdgeEffectCompat.BaseEdgeEffectImpl * JD-Core Version: 0.6.2 */
866
0.706697
0.692841
46
17.847826
22.125107
84
false
false
0
0
0
0
0
0
0.26087
false
false
5
58f4724c33b83d25aebb9db10b69d86a00b5b7b8
10,960,756,594,867
18c70f2a4f73a9db9975280a545066c9e4d9898e
/mirror-cmdb/cmdb-api/src/main/java/com/aspire/ums/cmdb/v3/screen/payload/CmdbScreenProblemInfoRequest.java
b65f516d3f0ef95b784a42e951fe246a75af113d
[]
no_license
iu28igvc9o0/cmdb_aspire
https://github.com/iu28igvc9o0/cmdb_aspire
1fe5d8607fdacc436b8a733f0ea44446f431dfa8
793eb6344c4468fe4c61c230df51fc44f7d8357b
refs/heads/master
2023-08-11T03:54:45.820000
2021-09-18T01:47:25
2021-09-18T01:47:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aspire.ums.cmdb.v3.screen.payload; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @projectName: CmdbScreenProblemInfoRequest * @description: 类 * @author: luowenbo * @create: 2020-07-03 14:52 **/ @Data @AllArgsConstructor @NoArgsConstructor public class CmdbScreenProblemInfoRequest { /* * 用户登录账号 * */ private String loginName; /* * 是否是管理员 * */ private Boolean isAdmin; /* * 标题(模糊查询) * */ private String title; /* * 类型 * */ private String type; /* * 分类 * */ private String classify; /* * 日期 * */ private String createTime; private Integer pageNo; private Integer pageSize; }
UTF-8
Java
801
java
CmdbScreenProblemInfoRequest.java
Java
[ { "context": "nProblemInfoRequest\n * @description: 类\n * @author: luowenbo\n * @create: 2020-07-03 14:52\n **/\n@Data\n@AllArgsC", "end": 225, "score": 0.9997120499610901, "start": 217, "tag": "USERNAME", "value": "luowenbo" } ]
null
[]
package com.aspire.ums.cmdb.v3.screen.payload; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @projectName: CmdbScreenProblemInfoRequest * @description: 类 * @author: luowenbo * @create: 2020-07-03 14:52 **/ @Data @AllArgsConstructor @NoArgsConstructor public class CmdbScreenProblemInfoRequest { /* * 用户登录账号 * */ private String loginName; /* * 是否是管理员 * */ private Boolean isAdmin; /* * 标题(模糊查询) * */ private String title; /* * 类型 * */ private String type; /* * 分类 * */ private String classify; /* * 日期 * */ private String createTime; private Integer pageNo; private Integer pageSize; }
801
0.618474
0.601071
43
16.372093
12.409718
46
false
false
0
0
0
0
0
0
0.27907
false
false
5
0df86a1826cfb6260fadc959315a4b5e2e41da4e
27,797,028,381,923
a29bac26c3ff1e41de04c6a9b192b09b6cae5b38
/CentroMedico/src/Pantallas/jDialog/PanelUsuarios.java
e09365dcabc5ae5a661267cac7569d33cc1b9036
[]
no_license
edw-rys/centro_medico.v1
https://github.com/edw-rys/centro_medico.v1
4b59df89fbd4b67791e6a15de85764a9ee24c230
4f1334cb910a8cd9fd7b1fffe73b3764131693d8
refs/heads/master
2020-05-09T10:05:30.338000
2019-04-12T14:53:23
2019-04-12T14:53:23
181,028,666
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Pantallas.jDialog; import Modelo.ConsultaBD.GuardarBD; import javax.swing.JOptionPane; public class PanelUsuarios extends javax.swing.JDialog { public PanelUsuarios(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); this.setLocationRelativeTo(null);//Centrar Jframe } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { txtUser = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtClave = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); cmbTipo = new javax.swing.JComboBox<>(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setText("User: "); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Usuarios"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("Clave: "); jButton1.setText("Guardar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Cancelar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("Tipo: "); cmbTipo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "OPERADOR", "ADMINISTRADOR" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 86, Short.MAX_VALUE) .addComponent(jButton2) .addGap(76, 76, 76) .addComponent(jButton1) .addGap(72, 72, 72)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(jLabel2)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel1)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel3))) .addGap(78, 78, 78) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtUser) .addComponent(txtClave) .addComponent(cmbTipo, 0, 193, Short.MAX_VALUE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addGap(23, 23, 23)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if(txtClave.getText().equals("") || txtUser.getText().equals("")){ JOptionPane.showMessageDialog(null, "Campos vacios"); return; } int res=new GuardarBD().guardarUsuario(txtUser.getText(), txtClave.getText(), cmbTipo.getSelectedItem().toString()); if(res>0) JOptionPane.showMessageDialog(null, "Guardado"); else JOptionPane.showMessageDialog(null, "Error"); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { PanelUsuarios dialog = new PanelUsuarios(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> cmbTipo; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPasswordField txtClave; private javax.swing.JTextField txtUser; // End of variables declaration//GEN-END:variables }
UTF-8
Java
8,920
java
PanelUsuarios.java
Java
[]
null
[]
package Pantallas.jDialog; import Modelo.ConsultaBD.GuardarBD; import javax.swing.JOptionPane; public class PanelUsuarios extends javax.swing.JDialog { public PanelUsuarios(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); this.setLocationRelativeTo(null);//Centrar Jframe } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { txtUser = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtClave = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); cmbTipo = new javax.swing.JComboBox<>(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setText("User: "); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Usuarios"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("Clave: "); jButton1.setText("Guardar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Cancelar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("Tipo: "); cmbTipo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "OPERADOR", "ADMINISTRADOR" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 86, Short.MAX_VALUE) .addComponent(jButton2) .addGap(76, 76, 76) .addComponent(jButton1) .addGap(72, 72, 72)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(jLabel2)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel1)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel3))) .addGap(78, 78, 78) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtUser) .addComponent(txtClave) .addComponent(cmbTipo, 0, 193, Short.MAX_VALUE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addGap(23, 23, 23)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if(txtClave.getText().equals("") || txtUser.getText().equals("")){ JOptionPane.showMessageDialog(null, "Campos vacios"); return; } int res=new GuardarBD().guardarUsuario(txtUser.getText(), txtClave.getText(), cmbTipo.getSelectedItem().toString()); if(res>0) JOptionPane.showMessageDialog(null, "Guardado"); else JOptionPane.showMessageDialog(null, "Error"); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PanelUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { PanelUsuarios dialog = new PanelUsuarios(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<String> cmbTipo; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPasswordField txtClave; private javax.swing.JTextField txtUser; // End of variables declaration//GEN-END:variables }
8,920
0.617377
0.602018
184
47.47826
34.884895
161
false
false
0
0
0
0
0
0
0.701087
false
false
5
8b318b6ab11b5947f41610b853f84bc388d28a37
16,363,825,443,888
c7b911321bf9d3605a2f2b73d6926b4be9be16c4
/java-simple/src/main/resources/archetype-resources/src/main/java/__name__Configuration.java
7bb7753d09b82715964f810d3d8f904cffc2eb40
[]
no_license
hakandilek/dropwizard-archetype
https://github.com/hakandilek/dropwizard-archetype
b211bcbe7b4df5f35b9ca10b76df25bc1b9b2185
b826c827ccbec36771a93b7c2b7cc12e10cb0f73
refs/heads/master
2021-01-17T23:09:14.750000
2013-07-31T20:48:27
2013-07-31T20:48:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ${package}; import com.codahale.dropwizard.Configuration; public class ${name}Configuration extends Configuration { // TODO: implement service configuration }
UTF-8
Java
174
java
__name__Configuration.java
Java
[]
null
[]
package ${package}; import com.codahale.dropwizard.Configuration; public class ${name}Configuration extends Configuration { // TODO: implement service configuration }
174
0.775862
0.775862
9
18.333334
21.842873
57
false
false
0
0
0
0
0
0
0.555556
false
false
5
ae6642d0ee4bfe47fd9244d93a0dae0d0fae565e
32,839,319,988,340
53fe24b4dc52564aebb2316878b5f138058b5340
/app/src/main/java/com/sex8/sinchat/utils/NameInputFilter.java
130c8970444e19eee519f7fc5d816f7515ffe677
[]
no_license
oilking143/sinchat
https://github.com/oilking143/sinchat
6aaf32397ad6962ba1b794ecf532ffd4171a193b
0d0c52deecfea909a31c62ff328cc8fe5a1267f1
refs/heads/master
2021-03-25T03:48:22.393000
2020-03-16T02:11:02
2020-03-16T02:11:02
247,587,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sex8.sinchat.utils; import android.text.InputFilter; import android.text.Spanned; public class NameInputFilter implements InputFilter { private int mMaxLen = 80; public NameInputFilter() { } public NameInputFilter(int maxLen) { this.mMaxLen = maxLen; } @Override public CharSequence filter(CharSequence charSequence, int start, int end, Spanned dest, int dstart, int dend) { int dindex = 0; int count = 0; // 判斷是否到達最大長度 while (count <= mMaxLen && dindex < dest.length()) { char c = dest.charAt(dindex++); if (c < 128) {// 按ASCII碼錶0-127算 count = count + 1; } else { count = count + 2; } } if (count > mMaxLen) { return dest.subSequence(0, dindex - 1); } int sindex = 0; while (count <= mMaxLen && sindex < charSequence.length()) { char c = charSequence.charAt(sindex++); if (c < 128) { count = count + 1; } else { count = count + 2; } } if (count > mMaxLen) { sindex--; } return charSequence.subSequence(0, sindex); } }
UTF-8
Java
1,286
java
NameInputFilter.java
Java
[ { "context": "package com.sex8.sinchat.utils;\n\nimport android.text.InputFilter;\n", "end": 16, "score": 0.6491896510124207, "start": 15, "tag": "USERNAME", "value": "8" } ]
null
[]
package com.sex8.sinchat.utils; import android.text.InputFilter; import android.text.Spanned; public class NameInputFilter implements InputFilter { private int mMaxLen = 80; public NameInputFilter() { } public NameInputFilter(int maxLen) { this.mMaxLen = maxLen; } @Override public CharSequence filter(CharSequence charSequence, int start, int end, Spanned dest, int dstart, int dend) { int dindex = 0; int count = 0; // 判斷是否到達最大長度 while (count <= mMaxLen && dindex < dest.length()) { char c = dest.charAt(dindex++); if (c < 128) {// 按ASCII碼錶0-127算 count = count + 1; } else { count = count + 2; } } if (count > mMaxLen) { return dest.subSequence(0, dindex - 1); } int sindex = 0; while (count <= mMaxLen && sindex < charSequence.length()) { char c = charSequence.charAt(sindex++); if (c < 128) { count = count + 1; } else { count = count + 2; } } if (count > mMaxLen) { sindex--; } return charSequence.subSequence(0, sindex); } }
1,286
0.515103
0.49682
47
25.765957
22.20237
115
false
false
0
0
0
0
0
0
0.510638
false
false
5
d28ffaace691d478676cfb6b00bd282f2bca7578
38,551,626,453,050
803ad3adcd44992da5d5d7f25d9dd7c38b46bd3e
/carroGradel/src/main/java/kercki/juliano/carroGradel/CarroGradelApplication.java
3229262fb56820e3f3e34ecd01c57a3133929912
[ "MIT" ]
permissive
JulianoGabarrusKerecki/Springs
https://github.com/JulianoGabarrusKerecki/Springs
dcd455624f3be0f04b5e32c4eb512e29c76f0c94
44362432ba2e611b7b4ff2d3c4e10b012e18ed44
refs/heads/master
2022-10-26T19:04:18.881000
2020-06-16T12:20:00
2020-06-16T12:20:00
272,447,068
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kercki.juliano.carroGradel; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CarroGradelApplication { public static void main(String[] args) { SpringApplication.run(CarroGradelApplication.class, args); } }
UTF-8
Java
329
java
CarroGradelApplication.java
Java
[]
null
[]
package kercki.juliano.carroGradel; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CarroGradelApplication { public static void main(String[] args) { SpringApplication.run(CarroGradelApplication.class, args); } }
329
0.829787
0.829787
13
24.307692
24.505524
68
false
false
0
0
0
0
0
0
0.692308
false
false
5
ee4cf7b9454b9d9f32232b41c41da1fec532ccae
36,773,509,994,932
979fa206ed90d14a29e3d31983c8bcc004329685
/jslet/src/main/java/com/jslet/converter/DatasetMeta.java
740bc2fe06b04dd24b7037797210bf163ababe68
[ "Apache-2.0" ]
permissive
jslet/jsletserver
https://github.com/jslet/jsletserver
036e074bb74d005f3413c7fa047136c44e7783bd
601e9d7e50411576d792007b3dee4100eed874fc
refs/heads/master
2021-08-14T10:45:05.935000
2017-11-15T12:40:29
2017-11-15T12:40:29
110,782,540
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2017-2022 the original author or authors. * * 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.jslet.converter; import java.util.List; import java.util.Map; /** * The dataset meta that is sent/received the client. * * @author Tony Tong */ public class DatasetMeta { private String name; private String recordClass; private List<Map<String, Object>> fields; /** * Get the dataset name. * * @return name Dataset name. */ public final String getName() { return name; } /** * Set the dataset name. * * @param name Dataset name. */ public final void setName(String name) { this.name = name; } /** * Get the dataset record class name. * * @return recordClass Record class name. */ public final String getRecordClass() { return recordClass; } /** * Set the dataset record class name. * * @param recordClass Record class name */ public final void setRecordClass(String recordClass) { this.recordClass = recordClass; } /** * Get the field meta list of the dataset. * * @return fields Field meta list. */ public final List<Map<String, Object>> getFields() { return fields; } /** * Set the field meta list of the dataset. * * @param fields Field meta list. */ public final void setFields(List<Map<String, Object>> fields) { this.fields = fields; } }
UTF-8
Java
1,874
java
DatasetMeta.java
Java
[ { "context": "ta that is sent/received the client.\n *\n * @author Tony Tong\n */\npublic class DatasetMeta {\n\tprivate String na", "end": 779, "score": 0.9996916055679321, "start": 770, "tag": "NAME", "value": "Tony Tong" } ]
null
[]
/* * Copyright 2017-2022 the original author or authors. * * 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.jslet.converter; import java.util.List; import java.util.Map; /** * The dataset meta that is sent/received the client. * * @author <NAME> */ public class DatasetMeta { private String name; private String recordClass; private List<Map<String, Object>> fields; /** * Get the dataset name. * * @return name Dataset name. */ public final String getName() { return name; } /** * Set the dataset name. * * @param name Dataset name. */ public final void setName(String name) { this.name = name; } /** * Get the dataset record class name. * * @return recordClass Record class name. */ public final String getRecordClass() { return recordClass; } /** * Set the dataset record class name. * * @param recordClass Record class name */ public final void setRecordClass(String recordClass) { this.recordClass = recordClass; } /** * Get the field meta list of the dataset. * * @return fields Field meta list. */ public final List<Map<String, Object>> getFields() { return fields; } /** * Set the field meta list of the dataset. * * @param fields Field meta list. */ public final void setFields(List<Map<String, Object>> fields) { this.fields = fields; } }
1,871
0.686766
0.680363
88
20.295454
21.889786
75
false
false
0
0
0
0
0
0
0.875
false
false
5
44f8b6e0e3a230f80d513ebf67a7d5cbb62e94a6
16,295,105,967,526
64638ffed0add845cf8781560ba565dfce0a3ec9
/ThorPet/src/com/born/thor/pet/dao/BuddyDao.java
2078d1b909e7f1adade546e36600a39d8de79f91
[]
no_license
suhailahmed1512/petStore
https://github.com/suhailahmed1512/petStore
b289a857635e2d6dac38ef10566878d51574ff4f
5aa7c6bba1e1b36350babe4fe0ab767221d049b4
refs/heads/master
2016-08-09T04:58:34.074000
2015-11-12T07:41:17
2015-11-12T07:41:17
45,659,450
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.born.thor.pet.dao; import java.util.List; import com.born.thor.pet.model.BuddyModel; /** * @author thor * */ public interface BuddyDao { /** * Return a list of buddy models that are currently persisted. If none are found an empty list is returned. * * @return all Buddies of system */ List<BuddyModel> findBuddies(); /** * Finds all buddies with given code(sub-category). If none is found, an empty list will be returned. * * @param code * the code to search for buddies * @return All buddies with the given code. */ List<BuddyModel> findBuddiesByCode(String code); /** * @param dealerName * The dealer's Name to search for buddies * @return All buddies that belong to that dealer */ List<BuddyModel> findBuddiesByDealers(final String dealerName); }
UTF-8
Java
837
java
BuddyDao.java
Java
[ { "context": "m.born.thor.pet.model.BuddyModel;\n\n\n/**\n * @author thor\n *\n */\npublic interface BuddyDao\n{\n\t/**\n\t * Retur", "end": 131, "score": 0.9996035099029541, "start": 127, "tag": "USERNAME", "value": "thor" } ]
null
[]
/** * */ package com.born.thor.pet.dao; import java.util.List; import com.born.thor.pet.model.BuddyModel; /** * @author thor * */ public interface BuddyDao { /** * Return a list of buddy models that are currently persisted. If none are found an empty list is returned. * * @return all Buddies of system */ List<BuddyModel> findBuddies(); /** * Finds all buddies with given code(sub-category). If none is found, an empty list will be returned. * * @param code * the code to search for buddies * @return All buddies with the given code. */ List<BuddyModel> findBuddiesByCode(String code); /** * @param dealerName * The dealer's Name to search for buddies * @return All buddies that belong to that dealer */ List<BuddyModel> findBuddiesByDealers(final String dealerName); }
837
0.677419
0.677419
40
19.924999
26.834108
108
false
false
0
0
0
0
0
0
0.675
false
false
5
ba871dcd34bcba73a74a30294dc0ac3e5df912bc
36,601,711,299,754
a12d5743595f4b1d0209dd652d67a08c3d11a491
/Opgaver/Chapter 28 & 29/Graph/src/GraphMatrix/GraphMatrix.java
d56d620bfcbb5bda6b48d4fd1c4b34e3333b5d32
[]
no_license
Combii/BlackExercises
https://github.com/Combii/BlackExercises
38c120b7270bf460754c6852234968433f234633
7dd844ab8239441929526c1d56f9e6fadf4eb434
refs/heads/master
2021-03-27T10:26:49.284000
2016-11-30T20:58:16
2016-11-30T20:58:16
75,211,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GraphMatrix; import java.util.Arrays; /** * Created by David Stovlbaek on 20/10/16. */ public class GraphMatrix { public static void main(String[] args) { int[][] myGraph1 = new int[6][6]; myGraph1[0][1] = 1; myGraph1[0][2] = 1; myGraph1[0][3] = 1; myGraph1[1][0] = 1; myGraph1[1][2] = 1; myGraph1[2][0] = 1; myGraph1[2][3] = 1; myGraph1[2][4] = 1; myGraph1[2][0] = 1; myGraph1[3][1] = 1; myGraph1[3][2] = 1; myGraph1[3][4] = 1; myGraph1[3][5] = 1; myGraph1[4][2] = 1; myGraph1[4][3] = 1; myGraph1[4][5] = 1; myGraph1[5][3] = 1; myGraph1[5][4] = 1; int counter = 0; for (int[] arr : myGraph1) { System.out.println(counter + ": " + Arrays.toString(arr)); counter++; } } public static boolean checkGraphEquals(int[][] graph1, int[][] graph2){ if(graph1.length != graph2.length) return false; for (int i = 0; i < graph1.length; i++) { for (int j = 0; j < graph1.length; j++) { if(graph1[i][j] != graph2[i][j]) return false; } } return true; } }
UTF-8
Java
1,264
java
GraphMatrix.java
Java
[ { "context": "trix;\n\nimport java.util.Arrays;\n\n/**\n * Created by David Stovlbaek on 20/10/16.\n */\npublic class GraphMatrix {\n\n ", "end": 81, "score": 0.9998794794082642, "start": 66, "tag": "NAME", "value": "David Stovlbaek" } ]
null
[]
package GraphMatrix; import java.util.Arrays; /** * Created by <NAME> on 20/10/16. */ public class GraphMatrix { public static void main(String[] args) { int[][] myGraph1 = new int[6][6]; myGraph1[0][1] = 1; myGraph1[0][2] = 1; myGraph1[0][3] = 1; myGraph1[1][0] = 1; myGraph1[1][2] = 1; myGraph1[2][0] = 1; myGraph1[2][3] = 1; myGraph1[2][4] = 1; myGraph1[2][0] = 1; myGraph1[3][1] = 1; myGraph1[3][2] = 1; myGraph1[3][4] = 1; myGraph1[3][5] = 1; myGraph1[4][2] = 1; myGraph1[4][3] = 1; myGraph1[4][5] = 1; myGraph1[5][3] = 1; myGraph1[5][4] = 1; int counter = 0; for (int[] arr : myGraph1) { System.out.println(counter + ": " + Arrays.toString(arr)); counter++; } } public static boolean checkGraphEquals(int[][] graph1, int[][] graph2){ if(graph1.length != graph2.length) return false; for (int i = 0; i < graph1.length; i++) { for (int j = 0; j < graph1.length; j++) { if(graph1[i][j] != graph2[i][j]) return false; } } return true; } }
1,255
0.463608
0.390032
55
21.981817
18.440559
75
false
false
0
0
0
0
0
0
0.581818
false
false
5
53ec9188c8d22ee4b07addab540237452264fa11
18,674,517,851,896
2b3ed771f05c646c9e0c9486a804155105bc6e84
/app/src/main/java/com/s4/selfauth_iot/utils/JsonParser.java
7af883932226f87bb420214f1038486e1bd59315
[]
no_license
BlockChainS4/block_selfauth_iot
https://github.com/BlockChainS4/block_selfauth_iot
4b6859c8fe44fae8a0342e4e133f1d4d9034660d
596cb11542ba3b3d90922eedc1131d0dd4c7728a
refs/heads/master
2019-11-25T20:19:10.291000
2016-07-10T01:32:27
2016-07-10T01:32:27
62,936,829
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.s4.selfauth_iot.utils; import android.util.Log; import com.google.gson.*; import com.s4.selfauth_iot.data.Packet; /** * Created by 우철 on 2016-07-09. */ public class JsonParser { private static Gson jspGson; private static JsonParser jsp = new JsonParser(); private JsonParser(){ if(jspGson == null) jspGson = new GsonBuilder().create(); String value = "{'authinfo': [ {'key':'key1','value':'val1'} ]}"; Packet p = jspGson.fromJson(value, Packet.class); for(int i=0; i<p.getAuthinfo().size(); i++) Log.d("1", p.getAuthinfo().get(i).getKey() + " " + p.getAuthinfo().get(i).getPrimeNum()); //gson.toJson(person)); } public static JsonParser getInstance(){ return jsp; } public Gson getJspGson(){ return jspGson; } }
UTF-8
Java
850
java
JsonParser.java
Java
[ { "context": "om.s4.selfauth_iot.data.Packet;\n\n/**\n * Created by 우철 on 2016-07-09.\n */\npublic class JsonParser {\n ", "end": 149, "score": 0.796367883682251, "start": 147, "tag": "USERNAME", "value": "우철" } ]
null
[]
package com.s4.selfauth_iot.utils; import android.util.Log; import com.google.gson.*; import com.s4.selfauth_iot.data.Packet; /** * Created by 우철 on 2016-07-09. */ public class JsonParser { private static Gson jspGson; private static JsonParser jsp = new JsonParser(); private JsonParser(){ if(jspGson == null) jspGson = new GsonBuilder().create(); String value = "{'authinfo': [ {'key':'key1','value':'val1'} ]}"; Packet p = jspGson.fromJson(value, Packet.class); for(int i=0; i<p.getAuthinfo().size(); i++) Log.d("1", p.getAuthinfo().get(i).getKey() + " " + p.getAuthinfo().get(i).getPrimeNum()); //gson.toJson(person)); } public static JsonParser getInstance(){ return jsp; } public Gson getJspGson(){ return jspGson; } }
850
0.596927
0.580378
33
24.636364
24.018703
101
false
false
0
0
0
0
0
0
0.545455
false
false
5
6372b3887d300b6a19d65c3339f5715bc51b020a
18,459,769,487,388
918de16fc60016ded25bc8e6038849f295687125
/app/src/main/java/com/eexposito/restaurant/realm/ModelManager.java
0ae0765a51b789293263c3e34fd520c9f513370f
[]
no_license
eexpositode/Restaurant
https://github.com/eexpositode/Restaurant
2e7d4cb7f4579a23711a01db04c6b26b378dcced
3197fa7c17267f0646f114ccb855a56b1fbf485a
refs/heads/master
2021-08-17T02:52:50.676000
2017-11-20T18:09:11
2017-11-20T18:09:11
110,030,820
0
0
null
false
2017-11-14T09:44:53
2017-11-08T21:09:59
2017-11-08T21:18:17
2017-11-14T09:44:53
239
0
0
0
Java
false
null
package com.eexposito.restaurant.realm; import android.support.annotation.NonNull; import com.eexposito.restaurant.realm.models.Customer; import com.eexposito.restaurant.realm.models.Model; import com.eexposito.restaurant.realm.models.Reservation; import com.eexposito.restaurant.realm.models.Table; import java.util.List; import java.util.function.Predicate; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RealmResults; public class ModelManager { public <M extends RealmObject> RealmResults<M> getAllModels(@NonNull final Realm realm, @NonNull final Class<M> modelClass) { return realm.where(modelClass).findAll(); } public <M extends RealmObject> void saveModels(@NonNull final List<M> models) { Realm realm = Realm.getDefaultInstance(); realm.executeTransaction(realm1 -> realm1.copyToRealm(models)); realm.close(); } public <M extends RealmObject> RealmResults<M> getModelByID(final Realm realm, final Class<M> modelClass, final String value) { return realm.where(modelClass).equalTo(Model.ID, value).findAll(); } public void createReservation(@NonNull final String tableID, @NonNull final String customerID, @NonNull final String time) { Realm realm = Realm.getDefaultInstance(); realm.executeTransaction(realm1 -> { Table table = getModelByID(realm1, Table.class, tableID).first(); Customer customer = getModelByID(realm1, Customer.class, customerID).first(); Reservation reservation = realm1.copyToRealm(new Reservation(customer, time)); table.setReservation(reservation); realm1.insertOrUpdate(table); }); realm.close(); } public void removeReservation(final Table table) { Realm realm = Realm.getDefaultInstance(); realm.executeTransaction(realm1 -> { RealmResults<Reservation> rows = getModelByID( realm1, Reservation.class, table.getReservation().getID()); rows.deleteAllFromRealm(); table.setReservation(null); realm1.insertOrUpdate(table); }); realm.close(); } }
UTF-8
Java
2,292
java
ModelManager.java
Java
[]
null
[]
package com.eexposito.restaurant.realm; import android.support.annotation.NonNull; import com.eexposito.restaurant.realm.models.Customer; import com.eexposito.restaurant.realm.models.Model; import com.eexposito.restaurant.realm.models.Reservation; import com.eexposito.restaurant.realm.models.Table; import java.util.List; import java.util.function.Predicate; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RealmResults; public class ModelManager { public <M extends RealmObject> RealmResults<M> getAllModels(@NonNull final Realm realm, @NonNull final Class<M> modelClass) { return realm.where(modelClass).findAll(); } public <M extends RealmObject> void saveModels(@NonNull final List<M> models) { Realm realm = Realm.getDefaultInstance(); realm.executeTransaction(realm1 -> realm1.copyToRealm(models)); realm.close(); } public <M extends RealmObject> RealmResults<M> getModelByID(final Realm realm, final Class<M> modelClass, final String value) { return realm.where(modelClass).equalTo(Model.ID, value).findAll(); } public void createReservation(@NonNull final String tableID, @NonNull final String customerID, @NonNull final String time) { Realm realm = Realm.getDefaultInstance(); realm.executeTransaction(realm1 -> { Table table = getModelByID(realm1, Table.class, tableID).first(); Customer customer = getModelByID(realm1, Customer.class, customerID).first(); Reservation reservation = realm1.copyToRealm(new Reservation(customer, time)); table.setReservation(reservation); realm1.insertOrUpdate(table); }); realm.close(); } public void removeReservation(final Table table) { Realm realm = Realm.getDefaultInstance(); realm.executeTransaction(realm1 -> { RealmResults<Reservation> rows = getModelByID( realm1, Reservation.class, table.getReservation().getID()); rows.deleteAllFromRealm(); table.setReservation(null); realm1.insertOrUpdate(table); }); realm.close(); } }
2,292
0.660558
0.656195
67
33.208954
32.7038
131
false
false
0
0
0
0
0
0
0.656716
false
false
5
373a7d1253a86816b6bf2f80423e63a03d72462b
29,042,568,888,938
8a331c0947313f90056ef5d55ebe9430d083577a
/src/main/java/com/elex/gmrec/etl/PrepareInputForFPG.java
a3521fef1fad3fb6a1fb412f668f8e250ef62b69
[]
no_license
elex-bigdata/gmrec
https://github.com/elex-bigdata/gmrec
06233daf1129b1ca72f37e9fd1c7cbe14408f0a1
4948444f6bafe2bb48bd932d381f57e90d39579c
refs/heads/master
2021-01-10T20:44:29.625000
2015-03-24T09:02:16
2015-03-24T09:02:16
21,261,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.elex.gmrec.etl; import java.io.IOException; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.elex.gmrec.comm.Constants; import com.elex.gmrec.comm.HdfsUtils; import com.elex.gmrec.comm.PropertiesUtils; public class PrepareInputForFPG extends Configured implements Tool { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new PrepareInputForFPG(), args); } @Override public int run(String[] args) throws Exception { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); Job job = Job.getInstance(conf,"prepareInputForFPG"); job.setJarByClass(PrepareInputForFPG.class); job.setMapperClass(MyMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setReducerClass(MyReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(TextInputFormat.class); Path in = new Path(PropertiesUtils.getGmRecRootFolder()+Constants.CFINPUT); FileInputFormat.addInputPath(job, in); job.setOutputFormatClass(TextOutputFormat.class); Path output = new Path(PropertiesUtils.getGmRecRootFolder()+Constants.FPGINPUT); HdfsUtils.delFile(fs, output.toString()); FileOutputFormat.setOutputPath(job, output); return job.waitForCompletion(true)?0:1; } public static class MyMapper extends Mapper<LongWritable, Text, Text, Text> { Set<String> miniGame; String[] gidIntStrMap; @Override protected void setup(Context context) throws IOException, InterruptedException { miniGame = FilterUtils.getMiniGM(); gidIntStrMap = IDMapping.getGidIntStrMap(); } String[] vList; @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { vList = value.toString().split(","); if(vList.length==3){ if(miniGame.contains(gidIntStrMap[new Integer(vList[1])])){ if(!vList[2].equals("0")){ context.write(new Text(vList[0]), new Text(vList[1])); } } } } } public static class MyReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> gidList,Context context) throws IOException, InterruptedException { StringBuffer sb = new StringBuffer(200); for(Text gid:gidList){ sb.append(gid).append(" "); } context.write(null, new Text(sb.toString().trim())); } } }
UTF-8
Java
3,286
java
PrepareInputForFPG.java
Java
[]
null
[]
package com.elex.gmrec.etl; import java.io.IOException; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.elex.gmrec.comm.Constants; import com.elex.gmrec.comm.HdfsUtils; import com.elex.gmrec.comm.PropertiesUtils; public class PrepareInputForFPG extends Configured implements Tool { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new PrepareInputForFPG(), args); } @Override public int run(String[] args) throws Exception { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); Job job = Job.getInstance(conf,"prepareInputForFPG"); job.setJarByClass(PrepareInputForFPG.class); job.setMapperClass(MyMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setReducerClass(MyReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(TextInputFormat.class); Path in = new Path(PropertiesUtils.getGmRecRootFolder()+Constants.CFINPUT); FileInputFormat.addInputPath(job, in); job.setOutputFormatClass(TextOutputFormat.class); Path output = new Path(PropertiesUtils.getGmRecRootFolder()+Constants.FPGINPUT); HdfsUtils.delFile(fs, output.toString()); FileOutputFormat.setOutputPath(job, output); return job.waitForCompletion(true)?0:1; } public static class MyMapper extends Mapper<LongWritable, Text, Text, Text> { Set<String> miniGame; String[] gidIntStrMap; @Override protected void setup(Context context) throws IOException, InterruptedException { miniGame = FilterUtils.getMiniGM(); gidIntStrMap = IDMapping.getGidIntStrMap(); } String[] vList; @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { vList = value.toString().split(","); if(vList.length==3){ if(miniGame.contains(gidIntStrMap[new Integer(vList[1])])){ if(!vList[2].equals("0")){ context.write(new Text(vList[0]), new Text(vList[1])); } } } } } public static class MyReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> gidList,Context context) throws IOException, InterruptedException { StringBuffer sb = new StringBuffer(200); for(Text gid:gidList){ sb.append(gid).append(" "); } context.write(null, new Text(sb.toString().trim())); } } }
3,286
0.729458
0.726111
98
31.530613
23.09572
82
false
false
0
0
0
0
0
0
2.377551
false
false
5
ca8ef15f2bf4387c7ffaa1d24564383b8238872c
18,210,661,390,833
4bbb6f71cbdad1f17a8e4e42ce9a13bc7e7d49d1
/BaseProjectWeb/src/java/ru/cardio/web/beans/PsqlTestBean.java
a206abc622e7a7a30e16dde8f3235ba4c20b6d7f
[]
no_license
rogvold/Web
https://github.com/rogvold/Web
2d970f1653e9bd44843773b475fd29c780b453d2
5f4f0ac8fb8850115229fbf8d1ea2fc21470c15c
HEAD
2016-09-16T03:42:58.876000
2014-02-12T12:00:21
2014-02-12T12:00:21
9,602,179
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.cardio.web.beans; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import ru.cardio.core.managers.CardioSessionEvaluationManagerLocal; import ru.cardio.core.managers.SessionsHistoryManager; import ru.cardio.core.managers.SessionsHistoryManagerLocal; import ru.cardio.exceptions.CardioException; /** * * @author Shaykhlislamov Sabir (email: sha-sabir@yandex.ru) */ @ManagedBean @ViewScoped public class PsqlTestBean { @EJB SessionsHistoryManagerLocal shm; @EJB CardioSessionEvaluationManagerLocal csem; public void pull(Long userId) throws CardioException { csem.pullSessions(userId, 0L); } }
UTF-8
Java
688
java
PsqlTestBean.java
Java
[ { "context": "dio.exceptions.CardioException;\n\n/**\n *\n * @author Shaykhlislamov Sabir (email: sha-sabir@yandex.ru)\n */\n@ManagedBean\n@Vi", "end": 392, "score": 0.999891459941864, "start": 372, "tag": "NAME", "value": "Shaykhlislamov Sabir" }, { "context": "n;\n\n/**\n *\n * @au...
null
[]
package ru.cardio.web.beans; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import ru.cardio.core.managers.CardioSessionEvaluationManagerLocal; import ru.cardio.core.managers.SessionsHistoryManager; import ru.cardio.core.managers.SessionsHistoryManagerLocal; import ru.cardio.exceptions.CardioException; /** * * @author <NAME> (email: <EMAIL>) */ @ManagedBean @ViewScoped public class PsqlTestBean { @EJB SessionsHistoryManagerLocal shm; @EJB CardioSessionEvaluationManagerLocal csem; public void pull(Long userId) throws CardioException { csem.pullSessions(userId, 0L); } }
662
0.77907
0.777616
27
24.481482
22.181692
67
false
false
0
0
0
0
0
0
0.444444
false
false
5
432c4bd335a33e794507468908322caf8e40fc6c
16,243,566,362,633
674e7a7b84d7fa97333e43dce8f626dd2764f0ae
/src/main/java/sofka/carreraciclistica/entity/competencia/command/CrearCompetencia.java
ee89ae74a97a06fb951b1be2ca4bda45af7d5ff1
[]
no_license
NatalyMora21/ImplementacionDDD-CarreraCiclistica
https://github.com/NatalyMora21/ImplementacionDDD-CarreraCiclistica
5c6640c79c28d5d7871282c7c862e09aea58c66c
50a86980c317a9e70c31e17336c2c8bd8998d88f
refs/heads/main
2023-08-11T06:32:58.939000
2021-10-01T23:36:13
2021-10-01T23:36:13
411,925,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sofka.carreraciclistica.entity.competencia.command; import co.com.sofka.domain.generic.Command; import sofka.carreraciclistica.entity.competencia.Ruta; import sofka.carreraciclistica.entity.competencia.values.*; public class CrearCompetencia extends Command { private final CompetenciaId identity; private final NombreCompetencia nombre; private final TipoCompetencia tipo; private final FechaInicio fechaInicio; private final Categoria categoria; private final Ruta ruta; public CrearCompetencia(CompetenciaId identity, NombreCompetencia nombre, TipoCompetencia tipo, FechaInicio fechaInicio, Categoria categoria, Ruta ruta) { this.identity = identity; this.nombre = nombre; this.tipo = tipo; this.fechaInicio = fechaInicio; this.categoria = categoria; this.ruta = ruta; } public CompetenciaId getIdentity() { return identity; } public NombreCompetencia getNombre() { return nombre; } public TipoCompetencia getTipo() { return tipo; } public FechaInicio getFechaInicio() { return fechaInicio; } public Categoria getCategoria() { return categoria; } public Ruta getRuta() { return ruta; } }
UTF-8
Java
1,285
java
CrearCompetencia.java
Java
[]
null
[]
package sofka.carreraciclistica.entity.competencia.command; import co.com.sofka.domain.generic.Command; import sofka.carreraciclistica.entity.competencia.Ruta; import sofka.carreraciclistica.entity.competencia.values.*; public class CrearCompetencia extends Command { private final CompetenciaId identity; private final NombreCompetencia nombre; private final TipoCompetencia tipo; private final FechaInicio fechaInicio; private final Categoria categoria; private final Ruta ruta; public CrearCompetencia(CompetenciaId identity, NombreCompetencia nombre, TipoCompetencia tipo, FechaInicio fechaInicio, Categoria categoria, Ruta ruta) { this.identity = identity; this.nombre = nombre; this.tipo = tipo; this.fechaInicio = fechaInicio; this.categoria = categoria; this.ruta = ruta; } public CompetenciaId getIdentity() { return identity; } public NombreCompetencia getNombre() { return nombre; } public TipoCompetencia getTipo() { return tipo; } public FechaInicio getFechaInicio() { return fechaInicio; } public Categoria getCategoria() { return categoria; } public Ruta getRuta() { return ruta; } }
1,285
0.698054
0.698054
48
25.770834
26.644449
158
false
false
0
0
0
0
0
0
0.5625
false
false
5
4c3a56299fce191b69cfa2bce776ed56d8173489
17,721,035,107,353
a9fde0e9deee80d1b031182a1bc18cdd8bfb4ec7
/MPT5Server/src/doctorVisitClinic/IDoctorVisitClinicService.java
f3e8bbda79380260b038efc37a3c4713335d3340
[]
no_license
mingginew88/semi_project
https://github.com/mingginew88/semi_project
15b37c26169b6b064fa5801e120099839550e4e3
8e299e3abd1887dc3948e87b8b4cbba0222b2e90
refs/heads/master
2020-09-05T20:44:38.993000
2019-11-07T10:24:08
2019-11-07T10:24:08
220,209,272
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package doctorVisitClinic; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.List; import java.util.Map; import VO.AppointmentVO; import VO.DiseaseVO; import VO.ExaminationVO; import VO.MedicineVO; import VO.PatientVO; import VO.PrescriptionVO; import VO.VisitclinicVO; public interface IDoctorVisitClinicService extends Remote{ /** * 로그인한 의사의 당일 예약리스트 불러오는 메서드 * @param doctor_num * @return 예약 리스트 * @throws RemoteException */ public List<AppointmentVO> getAllAppoint(int doctor_num) throws RemoteException; /** * 환자 Id에 해당하는 환자 VO 불러오는 메서드 * @param pa_id * @return 환자 VO * @throws RemoteException */ public PatientVO getPaInfo(String pa_id) throws RemoteException; /** * 환자 Id에 해당하는 검사VO 불러오는 메서드 * @param pa_id * @return 검사VO * @throws RemoteException */ public List<ExaminationVO> getExInfo(String pa_id) throws RemoteException; /** * 의약품코드/의약품명으로 검색했을때 해당하는 의약품VO리스트 불러오는 메서드 * @param data * @return 의약품VO * @throws RemoteException */ public List<MedicineVO> getMedi(Map<String, String> data) throws RemoteException; /** * 환자 Id에 해당하는 질병 VO불러오는 메서드 * @param pa_id * @return 질병VO * @throws RemoteException */ public List<DiseaseVO> getDis(String pa_id) throws RemoteException; /** * VisitClinic insert * @param vc * @return */ public int insertVisitClinic(VisitclinicVO vc) throws RemoteException; /** * Disease insert * @param dis * @return */ public int insertDisease(DiseaseVO dis) throws RemoteException; /** * Prescription insert * @param presc * @return */ public int insertPrescription(PrescriptionVO presc) throws RemoteException; /** * Visitclinic num 제일 큰값 * @return * @throws RemoteException */ public int maxVCNum() throws RemoteException; /** * Disease num 제일 큰값 * @return * @throws RemoteException */ public int maxDisNum() throws RemoteException; /** * Examination insert * @return * @throws RemoteException */ public int insertExam(ExaminationVO exam) throws RemoteException; /** * 예약리스트의 환자가 진단을 했는지 검사하는 메서드 * @param appt_num * @return 진단기록이 있으면 1 없으면 0 * @throws RemoteException */ public boolean searchApptVC(int appt_num) throws RemoteException; /** * 예약리스트에 있지만 이미 진단 내용이 있을 경우 진단 내용을 가져오는 메서드 * @param appt_num * @return * @throws RemoteException */ public VisitclinicVO getPaVC(int appt_num) throws RemoteException; /** * 예약리스트에 있지만 이미 진단 내용이 있을 경우 해당 진단서의 처방 내용을 가져오는 메서드 * @param clinic_num * @return * @throws RemoteException */ public PrescriptionVO getPaPresc(int clinic_num) throws RemoteException; /** * 예약리스트에 있지만 이미 진단 내용이 있을 경우 해당 진단 관련 질병 내용을 가져오는 메서드 * @param clinic_num * @return * @throws RemoteException */ public DiseaseVO getPaDisease(int clinic_num) throws RemoteException; /** * 예약리스트에 있지만 진단 내용이 있을 경우 해당 진단 관련 검사 내용을 가져오는 메서드 * @param clinic_num * @return * @throws RemoteException */ public ExaminationVO getPaExam(int clinic_num) throws RemoteException; /** * 진단 후에 또 저장했을때 VisitClinic update하는 메서드.. * @param vc * @return * @throws RemoteException */ public int updateVC(VisitclinicVO vc) throws RemoteException; /** * 진단 후에 또 저장했을때 Prescription update하는 메서드 * @param presc * @return * @throws RemoteException */ public int updatePresc(PrescriptionVO presc) throws RemoteException; /** * 진단 후에 또 저장했을때 Disease update하는 메서드 * @param dis * @return * @throws RemoteException */ public int updateDisease(DiseaseVO dis) throws RemoteException; /** * 진단 후에 또 저장했을때 Examination update하는 메서드 * @param exam * @return * @throws RemoteException */ public int updateExam(ExaminationVO exam) throws RemoteException; }
UTF-8
Java
4,473
java
IDoctorVisitClinicService.java
Java
[]
null
[]
package doctorVisitClinic; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.List; import java.util.Map; import VO.AppointmentVO; import VO.DiseaseVO; import VO.ExaminationVO; import VO.MedicineVO; import VO.PatientVO; import VO.PrescriptionVO; import VO.VisitclinicVO; public interface IDoctorVisitClinicService extends Remote{ /** * 로그인한 의사의 당일 예약리스트 불러오는 메서드 * @param doctor_num * @return 예약 리스트 * @throws RemoteException */ public List<AppointmentVO> getAllAppoint(int doctor_num) throws RemoteException; /** * 환자 Id에 해당하는 환자 VO 불러오는 메서드 * @param pa_id * @return 환자 VO * @throws RemoteException */ public PatientVO getPaInfo(String pa_id) throws RemoteException; /** * 환자 Id에 해당하는 검사VO 불러오는 메서드 * @param pa_id * @return 검사VO * @throws RemoteException */ public List<ExaminationVO> getExInfo(String pa_id) throws RemoteException; /** * 의약품코드/의약품명으로 검색했을때 해당하는 의약품VO리스트 불러오는 메서드 * @param data * @return 의약품VO * @throws RemoteException */ public List<MedicineVO> getMedi(Map<String, String> data) throws RemoteException; /** * 환자 Id에 해당하는 질병 VO불러오는 메서드 * @param pa_id * @return 질병VO * @throws RemoteException */ public List<DiseaseVO> getDis(String pa_id) throws RemoteException; /** * VisitClinic insert * @param vc * @return */ public int insertVisitClinic(VisitclinicVO vc) throws RemoteException; /** * Disease insert * @param dis * @return */ public int insertDisease(DiseaseVO dis) throws RemoteException; /** * Prescription insert * @param presc * @return */ public int insertPrescription(PrescriptionVO presc) throws RemoteException; /** * Visitclinic num 제일 큰값 * @return * @throws RemoteException */ public int maxVCNum() throws RemoteException; /** * Disease num 제일 큰값 * @return * @throws RemoteException */ public int maxDisNum() throws RemoteException; /** * Examination insert * @return * @throws RemoteException */ public int insertExam(ExaminationVO exam) throws RemoteException; /** * 예약리스트의 환자가 진단을 했는지 검사하는 메서드 * @param appt_num * @return 진단기록이 있으면 1 없으면 0 * @throws RemoteException */ public boolean searchApptVC(int appt_num) throws RemoteException; /** * 예약리스트에 있지만 이미 진단 내용이 있을 경우 진단 내용을 가져오는 메서드 * @param appt_num * @return * @throws RemoteException */ public VisitclinicVO getPaVC(int appt_num) throws RemoteException; /** * 예약리스트에 있지만 이미 진단 내용이 있을 경우 해당 진단서의 처방 내용을 가져오는 메서드 * @param clinic_num * @return * @throws RemoteException */ public PrescriptionVO getPaPresc(int clinic_num) throws RemoteException; /** * 예약리스트에 있지만 이미 진단 내용이 있을 경우 해당 진단 관련 질병 내용을 가져오는 메서드 * @param clinic_num * @return * @throws RemoteException */ public DiseaseVO getPaDisease(int clinic_num) throws RemoteException; /** * 예약리스트에 있지만 진단 내용이 있을 경우 해당 진단 관련 검사 내용을 가져오는 메서드 * @param clinic_num * @return * @throws RemoteException */ public ExaminationVO getPaExam(int clinic_num) throws RemoteException; /** * 진단 후에 또 저장했을때 VisitClinic update하는 메서드.. * @param vc * @return * @throws RemoteException */ public int updateVC(VisitclinicVO vc) throws RemoteException; /** * 진단 후에 또 저장했을때 Prescription update하는 메서드 * @param presc * @return * @throws RemoteException */ public int updatePresc(PrescriptionVO presc) throws RemoteException; /** * 진단 후에 또 저장했을때 Disease update하는 메서드 * @param dis * @return * @throws RemoteException */ public int updateDisease(DiseaseVO dis) throws RemoteException; /** * 진단 후에 또 저장했을때 Examination update하는 메서드 * @param exam * @return * @throws RemoteException */ public int updateExam(ExaminationVO exam) throws RemoteException; }
4,473
0.703013
0.702479
171
20.935673
21.18483
82
false
false
0
0
0
0
0
0
1.087719
false
false
5
170546105a4ad4daa53d82d35deac94b8c87ce5f
24,670,292,200,101
c73b5806bf09045431d210797df5e45b283a0b03
/src/main/java/SmartHome/Service/RESTClient/RESTClientService.java
9475d3167edf5fe97d8b256ad4c37f41d4c860c6
[]
no_license
smarthomeservice/SmartDevice
https://github.com/smarthomeservice/SmartDevice
fd93c9d1fa0681d698481409eed6f46d8d6ea77c
59878d23c85b8814361fb89f157c0c9243a624de
refs/heads/master
2016-09-16T09:53:58.131000
2015-01-30T05:51:27
2015-01-30T05:51:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SmartHome.Service.RESTClient; /** * Created by Tony on 2015/1/29. */ public class RESTClientService { }
UTF-8
Java
115
java
RESTClientService.java
Java
[ { "context": "e SmartHome.Service.RESTClient;\n\n/**\n * Created by Tony on 2015/1/29.\n */\npublic class RESTClientService ", "end": 61, "score": 0.8822327852249146, "start": 57, "tag": "NAME", "value": "Tony" } ]
null
[]
package SmartHome.Service.RESTClient; /** * Created by Tony on 2015/1/29. */ public class RESTClientService { }
115
0.721739
0.66087
7
15.428572
15.900199
37
false
false
0
0
0
0
0
0
0.142857
false
false
5
9f9cefdab0ef226cb072f99189ac453c75e73a40
884,763,327,845
af48fbf48226ffef99181c4d27b050554af9547c
/src/Lab4.java
7860a7cbb6095cdd50f1d3450093b9c8bde37635
[]
no_license
jamesgooden/MyLab4
https://github.com/jamesgooden/MyLab4
cc980c9495e9054365df34c729094a55f19c3a07
2c9ffcb070fa976df624f3fbe7a6486f355a465e
refs/heads/master
2020-03-31T19:50:53.560000
2018-10-11T01:44:10
2018-10-11T01:44:10
152,514,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Lab4 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String userName; int userInteger; String userInput; System.out.println("Learn your squares and cubes! "); System.out.println("Hi ,whats your name? "); userName = scan.next(); System.out.println("Nice to meet you " + userName); do { System.out.println("Please enter a integer between 1 and 100"); userInteger = scan.nextInt(); if (userInteger > 0 && userInteger <= 100) { System.out.println("Number Squared Cubed "); System.out.println("======= ====== ====="); for (int i = 1; i <= userInteger; i++) { System.out.printf("%-10d%10d%20d%n", i, i * i, i * i * i); } } else { System.out.println("Pleaser enter valid number between 1 and 100"); } System.out.println("Press Y to continue press any other key to end "); userInput = scan.next(); } while (userInput.equalsIgnoreCase("Y")); scan.close(); } }
UTF-8
Java
1,028
java
Lab4.java
Java
[]
null
[]
import java.util.Scanner; public class Lab4 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String userName; int userInteger; String userInput; System.out.println("Learn your squares and cubes! "); System.out.println("Hi ,whats your name? "); userName = scan.next(); System.out.println("Nice to meet you " + userName); do { System.out.println("Please enter a integer between 1 and 100"); userInteger = scan.nextInt(); if (userInteger > 0 && userInteger <= 100) { System.out.println("Number Squared Cubed "); System.out.println("======= ====== ====="); for (int i = 1; i <= userInteger; i++) { System.out.printf("%-10d%10d%20d%n", i, i * i, i * i * i); } } else { System.out.println("Pleaser enter valid number between 1 and 100"); } System.out.println("Press Y to continue press any other key to end "); userInput = scan.next(); } while (userInput.equalsIgnoreCase("Y")); scan.close(); } }
1,028
0.614786
0.595331
37
26.783783
24.005781
73
false
false
0
0
0
0
0
0
2.648649
false
false
5
685e95499ff2c4348f0cc22b0e717e5cdd29eb20
21,809,843,959,116
52f91bcdf04b5ebf44b85af250ac3cb7acec23c0
/src/main/java/com/paddlenose/vertx/layer/sdk/LayerServerClient.java
84d81d87e2b9703e335a6ddcd4a7cfc955ea6b2d
[ "MIT" ]
permissive
HiPERnx/vertx-layer-server-sdk
https://github.com/HiPERnx/vertx-layer-server-sdk
029f96328063c6d3db5f601801bf63367d0cfafe
b49909f3781daa0c8394931a5e31695bc1b6cb3e
refs/heads/master
2021-01-12T00:48:06.461000
2017-03-07T01:23:08
2017-03-07T01:23:08
78,297,396
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.paddlenose.vertx.layer.sdk; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; //TODO add error handlers /** * Layer client class * <p> * A SDK to interface with Layer Server API. Use with caution. These methods should be protected. <br> * See <a href="https://github.com/HiPERnx/vertx-layer-server-sdk">GitHub repo</a> * <img src="https://travis-ci.org/HiPERnx/vertx-layer-server-sdk.svg?branch=master" alt="Build status"> <br> * <br> * Handler<HttpClientResponse> future Needs to handle http(s) errors. <br> * Currently there is no error handler for other errors. <br> * <br> * <a href="www.paddlenose.com">www.paddlenose.com</a> * </p> * @author Gustaf Nilstadius * Created by Gustaf Nilstadius ( hipernx ) on 2017-01-07. * @ */ @SuppressWarnings("WeakerAccess") public class LayerServerClient { /** * A HttpClient, requires default host */ private final HttpClient client; /** * Application id for Layer API */ private final String layer_app_id; /** * Application token for Layer API */ private final String layer_app_token; /** * LayerClient implements LayerInterface. * * @param client A HttpClient, requires default host * @param options Requires layer_app_id and layer_app_token */ public LayerServerClient(HttpClient client, LayerServerOptions options) { this.client = client; this.layer_app_id = options.getString("layer_app_id"); this.layer_app_token = options.getString("layer_app_token"); } /** * Gets 100 conversations for authenticated user from Layer API. Sorted by last message. * * @param future Handler, requires error handler. * @param user_ID User id for which conversations will be requested */ public void getConversationsAsUser(Handler<HttpClientResponse> future, String user_ID) { client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations?sort_by=last_message", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> {System.err.println(err.getMessage()); err.printStackTrace(); future.handle(null);}) .end(); } /** * Gets the last 100 messages in a conversation as User * * @param future Handler, requires error handler. * @param conversation_UUID UUID specifying conversation * @param user_ID User id for which conversation messages will be requested */ public void getConversationMessageAsUser(Handler<HttpClientResponse> future, String conversation_UUID, String user_ID) { client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> { err.printStackTrace(); future.handle(null); }) .end(); } /** * Sends a single message to the Layer API. * //TODO Needs further testing * @param future Handler, requires error handler. * @param conversation_UUID String for URI * @param message JsonObject Message, see Layer API documentation. * @param user_ID User ID specifying the layer user */ public void postMessageAsUser(Handler<HttpClientResponse> future, String conversation_UUID, JsonObject message, String user_ID) { client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(new JsonObject().put("parts", message.getJsonArray("parts")).encode()); } /** * Creates a single conversation via the Layer API * * @param future Handler, requires error handler. * @param conversation JsonObject Message, see Layer API documentation. */ public void postConversationAsUser(Handler<HttpClientResponse> future, JsonObject conversation, String user_ID) { client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(conversation.encode()); } /** * Gets one conversation * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID for the requested conversation */ public void getConversation(Handler<HttpClientResponse> future, String conversation_UUID){ client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID, future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(); } /** * Gets messages for specified conversation, messages is retrieved as server, NOT USER * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID for the requested conversation */ public void getConversationMessage(Handler<HttpClientResponse> future, String conversation_UUID){ client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> { err.printStackTrace(); future.handle(null); }) .end(); } /** * Creates a conversation as server * @param future Handler, requires error handler. * @param conversation Conversation, requires String[] participants, boolean distinct, Object metadata */ public void postConversation(Handler<HttpClientResponse> future, JsonObject conversation){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/conversations", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(conversation.encode()); } /** * Sends message as user specified in JsonObject message * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID of which to send the message * @param message Message requires String sender_id, MessagePart[] parts. Optional Object notification */ public void postMessage(Handler<HttpClientResponse> future, String conversation_UUID, JsonObject message){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(message.encode()); } /** * Sends message as user specified in JsonObject message * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID of which to send the message * @param message Message requires String sender_id, MessagePart[] parts. Optional Object notification */ public void postMessage(Future<HttpClientResponse> future, String conversation_UUID, JsonObject message){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID + "/messages", future::complete) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(future::fail) .end(message.encode()); } /** * Sends a announcement. * @param future Handler, requires error handler. * @param announcement Announcement requires String[] recipients, String sender_id, MessageParts[] parts, Object notification */ public void postAnnouncement(Handler<HttpClientResponse> future, JsonObject announcement){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/announcements", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(announcement.encode()); } /** * Sends a notification to specified recipients * @param future Handler, requires error handler. * @param notification Notification requires String[] recipients, JsonObject notification {String title, String text, (optional) String sound} */ public void postNotification(Handler<HttpClientResponse> future, JsonObject notification){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/notifications", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(notification.encode()); } }
UTF-8
Java
10,903
java
LayerServerClient.java
Java
[ { "context": "cted. <br>\n * See <a href=\"https://github.com/HiPERnx/vertx-layer-server-sdk\">GitHub repo</a>\n * <i", "end": 474, "score": 0.8640747666358948, "start": 467, "tag": "USERNAME", "value": "HiPERnx" }, { "context": "repo</a>\n * <img src=\"https://travis-ci....
null
[]
package com.paddlenose.vertx.layer.sdk; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; //TODO add error handlers /** * Layer client class * <p> * A SDK to interface with Layer Server API. Use with caution. These methods should be protected. <br> * See <a href="https://github.com/HiPERnx/vertx-layer-server-sdk">GitHub repo</a> * <img src="https://travis-ci.org/HiPERnx/vertx-layer-server-sdk.svg?branch=master" alt="Build status"> <br> * <br> * Handler<HttpClientResponse> future Needs to handle http(s) errors. <br> * Currently there is no error handler for other errors. <br> * <br> * <a href="www.paddlenose.com">www.paddlenose.com</a> * </p> * @author <NAME> * Created by <NAME> ( hipernx ) on 2017-01-07. * @ */ @SuppressWarnings("WeakerAccess") public class LayerServerClient { /** * A HttpClient, requires default host */ private final HttpClient client; /** * Application id for Layer API */ private final String layer_app_id; /** * Application token for Layer API */ private final String layer_app_token; /** * LayerClient implements LayerInterface. * * @param client A HttpClient, requires default host * @param options Requires layer_app_id and layer_app_token */ public LayerServerClient(HttpClient client, LayerServerOptions options) { this.client = client; this.layer_app_id = options.getString("layer_app_id"); this.layer_app_token = options.getString("layer_app_token"); } /** * Gets 100 conversations for authenticated user from Layer API. Sorted by last message. * * @param future Handler, requires error handler. * @param user_ID User id for which conversations will be requested */ public void getConversationsAsUser(Handler<HttpClientResponse> future, String user_ID) { client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations?sort_by=last_message", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> {System.err.println(err.getMessage()); err.printStackTrace(); future.handle(null);}) .end(); } /** * Gets the last 100 messages in a conversation as User * * @param future Handler, requires error handler. * @param conversation_UUID UUID specifying conversation * @param user_ID User id for which conversation messages will be requested */ public void getConversationMessageAsUser(Handler<HttpClientResponse> future, String conversation_UUID, String user_ID) { client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> { err.printStackTrace(); future.handle(null); }) .end(); } /** * Sends a single message to the Layer API. * //TODO Needs further testing * @param future Handler, requires error handler. * @param conversation_UUID String for URI * @param message JsonObject Message, see Layer API documentation. * @param user_ID User ID specifying the layer user */ public void postMessageAsUser(Handler<HttpClientResponse> future, String conversation_UUID, JsonObject message, String user_ID) { client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(new JsonObject().put("parts", message.getJsonArray("parts")).encode()); } /** * Creates a single conversation via the Layer API * * @param future Handler, requires error handler. * @param conversation JsonObject Message, see Layer API documentation. */ public void postConversationAsUser(Handler<HttpClientResponse> future, JsonObject conversation, String user_ID) { client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/users/" + user_ID + "/conversations", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(conversation.encode()); } /** * Gets one conversation * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID for the requested conversation */ public void getConversation(Handler<HttpClientResponse> future, String conversation_UUID){ client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID, future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(); } /** * Gets messages for specified conversation, messages is retrieved as server, NOT USER * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID for the requested conversation */ public void getConversationMessage(Handler<HttpClientResponse> future, String conversation_UUID){ client.request(HttpMethod.GET, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> { err.printStackTrace(); future.handle(null); }) .end(); } /** * Creates a conversation as server * @param future Handler, requires error handler. * @param conversation Conversation, requires String[] participants, boolean distinct, Object metadata */ public void postConversation(Handler<HttpClientResponse> future, JsonObject conversation){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/conversations", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(conversation.encode()); } /** * Sends message as user specified in JsonObject message * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID of which to send the message * @param message Message requires String sender_id, MessagePart[] parts. Optional Object notification */ public void postMessage(Handler<HttpClientResponse> future, String conversation_UUID, JsonObject message){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID + "/messages", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(message.encode()); } /** * Sends message as user specified in JsonObject message * @param future Handler, requires error handler. * @param conversation_UUID Conversation UUID of which to send the message * @param message Message requires String sender_id, MessagePart[] parts. Optional Object notification */ public void postMessage(Future<HttpClientResponse> future, String conversation_UUID, JsonObject message){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/conversations/" + conversation_UUID + "/messages", future::complete) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(future::fail) .end(message.encode()); } /** * Sends a announcement. * @param future Handler, requires error handler. * @param announcement Announcement requires String[] recipients, String sender_id, MessageParts[] parts, Object notification */ public void postAnnouncement(Handler<HttpClientResponse> future, JsonObject announcement){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/announcements", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(announcement.encode()); } /** * Sends a notification to specified recipients * @param future Handler, requires error handler. * @param notification Notification requires String[] recipients, JsonObject notification {String title, String text, (optional) String sound} */ public void postNotification(Handler<HttpClientResponse> future, JsonObject notification){ client.request(HttpMethod.POST, "/apps/" + layer_app_id + "/notifications", future) .putHeader("accept", "application/vnd.layer+json; version=2.0") .putHeader("Authorization", "Bearer " + layer_app_token ) .putHeader("Content-Type", "application/json") .exceptionHandler(err -> future.handle(null)) .end(notification.encode()); } }
10,881
0.638173
0.634871
222
48.112614
37.60524
148
false
false
0
0
0
0
0
0
0.648649
false
false
5
947e924292e30babc359214f73233dbef98830e1
22,900,765,679,223
e02bdf0f05d3252f4e7f866722d614b6544e8997
/src/main/java/com/example/demo/models/UniversalWeatherModel.java
2f33b6ec3bd0d975b42d4600179ac59539ebf213
[]
no_license
ollainorbert/Spring01
https://github.com/ollainorbert/Spring01
726d7a11b3d4ac7109b9c7126f82b91e82de8e0a
6f13cdffb74212a1fc6149612ff591aae590dc0f
refs/heads/master
2021-05-03T15:41:00.754000
2018-03-14T11:59:29
2018-03-14T11:59:29
120,483,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.models; public class UniversalWeatherModel { private static final String OPEN_WEATHER_MAP_ICON_PATTERN = "http://openweathermap.org/img/w/%s.png"; private float celsius; private String iconStringId; public float getCelsius() { return celsius; } public void setCelsius(float celsius) { this.celsius = celsius; } public String getIconStringId() { return iconStringId; } public void setIconStringId(String iconStringId) { this.iconStringId = String.format(OPEN_WEATHER_MAP_ICON_PATTERN, iconStringId); } }
UTF-8
Java
555
java
UniversalWeatherModel.java
Java
[]
null
[]
package com.example.demo.models; public class UniversalWeatherModel { private static final String OPEN_WEATHER_MAP_ICON_PATTERN = "http://openweathermap.org/img/w/%s.png"; private float celsius; private String iconStringId; public float getCelsius() { return celsius; } public void setCelsius(float celsius) { this.celsius = celsius; } public String getIconStringId() { return iconStringId; } public void setIconStringId(String iconStringId) { this.iconStringId = String.format(OPEN_WEATHER_MAP_ICON_PATTERN, iconStringId); } }
555
0.753153
0.753153
26
20.346153
25.905067
102
false
false
0
0
0
0
0
0
1.076923
false
false
5
006fa294af5d11f74afebeefd2b505dd5fb37b2c
8,211,977,499,325
c5a76ba84c35f4a299d920ab21080003a1c7cf06
/src/com/hh/hhdb_admin/mgr/constraint/ConstraintComp.java
941cdbb09e95c01386b1859fd1221854c9277421
[]
no_license
zsgwsjj/HHDBCS
https://github.com/zsgwsjj/HHDBCS
9b2182dd1b84a633a81412fc108fecf1c7f6130c
c264d73bbb457442f4402f71510e3f420fca426e
refs/heads/master
2023-07-17T07:16:50.490000
2021-08-30T07:09:53
2021-08-30T07:09:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hh.hhdb_admin.mgr.constraint; import com.hh.frame.common.base.AlignEnum; import com.hh.frame.common.base.DBTypeEnum; import com.hh.frame.create_dbobj.treeMr.base.TreeMrType; import com.hh.frame.lang.LangMgr; import com.hh.frame.lang.LangUtil; import com.hh.frame.swingui.view.container.HBarPanel; import com.hh.frame.swingui.view.container.HDialog; import com.hh.frame.swingui.view.container.HPanel; import com.hh.frame.swingui.view.container.LastPanel; import com.hh.frame.swingui.view.ctrl.HButton; import com.hh.frame.swingui.view.layout.bar.HBarLayout; import com.hh.frame.swingui.view.tab.HTabRowBean; import com.hh.frame.swingui.view.tab.HTable; import com.hh.frame.swingui.view.util.PopPaneUtil; import com.hh.hhdb_admin.CsMgrEnum; import com.hh.hhdb_admin.common.icon.IconBean; import com.hh.hhdb_admin.common.icon.IconFileUtil; import com.hh.hhdb_admin.common.icon.IconSizeEnum; import com.hh.hhdb_admin.common.util.StartUtil; import com.hh.hhdb_admin.common.util.logUtil; import com.hh.hhdb_admin.mgr.constraint.foreign.AbsForeTable; import com.hh.hhdb_admin.mgr.constraint.otherConst.AbsTable; import com.hh.hhdb_admin.mgr.table.TableComp; import javax.swing.*; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * @author YuSai */ public abstract class ConstraintComp { private static final String LOG_NAME = ConstraintComp.class.getSimpleName(); private static final String DOMAIN_NAME = ConstraintComp.class.getName(); static { LangMgr.merge(DOMAIN_NAME, LangUtil.loadLangRes(ConstraintComp.class)); } private final AtomicInteger atomicId = new AtomicInteger(); private final Connection conn; private final DBTypeEnum dbTypeEnum; private final TreeMrType treeMrType; private final String schema; private final String tableName; private final HDialog dialog; private boolean bool; public ConstraintComp(TreeMrType treeMrType, Connection conn, DBTypeEnum dbTypeEnum, String schema, String tableName) { this.conn = conn; this.dbTypeEnum = dbTypeEnum; this.treeMrType = treeMrType; this.schema = schema; this.tableName = tableName; this.dialog = new HDialog(StartUtil.parentFrame, 800, 600); dialog.setIconImage(IconFileUtil.getLogo()); dialog.setWindowTitle(ConstraintComp.getLang("addConstraint")); ConstraintUtil.initConst(conn, dbTypeEnum); TableComp panelCreate = new TableComp(conn, dbTypeEnum); panelCreate.genTableData(); } private HBarPanel getBarPanel(HTable table) { HButton addButton = new HButton(ConstraintComp.getLang("add")) { @Override protected void onClick() { table.add(getData().get(0)); } }; addButton.setIcon(getIcon("add")); HButton delButton = new HButton(ConstraintComp.getLang("delete")) { @Override protected void onClick() { List<HTabRowBean> rows = table.getSelectedRowBeans(); if (rows.size() > 0) { int result = JOptionPane.showConfirmDialog(null, ConstraintComp.getLang("sureDelete"), ConstraintComp.getLang("hint"), JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { table.deleteSelectRow(); } } } }; delButton.setIcon(getIcon("delete")); HButton savaBtn = new HButton(ConstraintComp.getLang("save")) { @Override protected void onClick() { save(table); } }; savaBtn.setIcon(getIcon("save")); HButton preViewBtn = new HButton(ConstraintComp.getLang("previewSql")) { @Override protected void onClick() { previewSql(table); } }; preViewBtn.setIcon(getIcon("sql_view")); HBarLayout barLayout = new HBarLayout(); barLayout.setAlign(AlignEnum.LEFT); HBarPanel barPanel = new HBarPanel(barLayout); barPanel.add(addButton); barPanel.add(delButton); barPanel.add(savaBtn); barPanel.add(preViewBtn); return barPanel; } private void save(HTable table) { try { ConstraintUtil.save(treeMrType, schema, tableName, table, bool); dialog.dispose(); refreshTree(); PopPaneUtil.info(StartUtil.parentFrame.getWindow(), ConstraintComp.getLang("saveSuccess")); } catch (SQLException e) { e.printStackTrace(); logUtil.error(LOG_NAME, e); PopPaneUtil.error(dialog.getWindow(), e.getMessage()); } } private void previewSql(HTable table) { ConstraintUtil.previewSql(treeMrType, schema, tableName, table, bool); } private List<Map<String, String>> getData() { List<Map<String, String>> data = new ArrayList<>(); Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(atomicId.incrementAndGet())); map.put("foreignName", ""); map.put("foreignOnDelete", ""); data.add(map); return data; } public HPanel getForePanel() { this.bool = true; LastPanel lastPanel = new LastPanel(); AbsForeTable foreTable = AbsForeTable.getForeTable(dbTypeEnum); if (null != foreTable) { HTable table = foreTable.getTable(conn, schema, tableName); lastPanel.setHead(getBarPanel(table).getComp()); lastPanel.setWithScroll(table.getComp()); table.load(new ArrayList<>(), 1); } HPanel panel = new HPanel(); panel.setLastPanel(lastPanel); return panel; } void showFore() { dialog.setRootPanel(getForePanel()); dialog.show(); } public HPanel getOtherPanel() { this.bool = false; LastPanel lastPanel = new LastPanel(); AbsTable absOtherTable = AbsTable.getOtherTable(treeMrType); if (null != absOtherTable) { HTable table = absOtherTable.getTable(conn, schema, tableName); lastPanel.setHead(getBarPanel(table).getComp()); lastPanel.setWithScroll(table.getComp()); table.load(new ArrayList<>(), 1); } HPanel panel = new HPanel(); panel.setLastPanel(lastPanel); return panel; } void showOtherConst() { dialog.setRootPanel(getOtherPanel()); dialog.show(); } void delConst(String constType, String schema, String table, String constName) throws Exception { ConstraintUtil.delete(constType, schema, table, constName); refreshTree(); } public static String getLang(String key) { LangMgr.setDefaultLang(StartUtil.default_language); return LangMgr.getValue(DOMAIN_NAME, key); } private ImageIcon getIcon(String name) { return IconFileUtil.getIcon(new IconBean(CsMgrEnum.CONSTRAINT.name(), name, IconSizeEnum.SIZE_16)); } public abstract void refreshTree(); }
UTF-8
Java
7,290
java
ConstraintComp.java
Java
[ { "context": "l.concurrent.atomic.AtomicInteger;\n\n/**\n * @author YuSai\n */\npublic abstract class ConstraintComp {\n\n p", "end": 1415, "score": 0.9997686147689819, "start": 1410, "tag": "NAME", "value": "YuSai" } ]
null
[]
package com.hh.hhdb_admin.mgr.constraint; import com.hh.frame.common.base.AlignEnum; import com.hh.frame.common.base.DBTypeEnum; import com.hh.frame.create_dbobj.treeMr.base.TreeMrType; import com.hh.frame.lang.LangMgr; import com.hh.frame.lang.LangUtil; import com.hh.frame.swingui.view.container.HBarPanel; import com.hh.frame.swingui.view.container.HDialog; import com.hh.frame.swingui.view.container.HPanel; import com.hh.frame.swingui.view.container.LastPanel; import com.hh.frame.swingui.view.ctrl.HButton; import com.hh.frame.swingui.view.layout.bar.HBarLayout; import com.hh.frame.swingui.view.tab.HTabRowBean; import com.hh.frame.swingui.view.tab.HTable; import com.hh.frame.swingui.view.util.PopPaneUtil; import com.hh.hhdb_admin.CsMgrEnum; import com.hh.hhdb_admin.common.icon.IconBean; import com.hh.hhdb_admin.common.icon.IconFileUtil; import com.hh.hhdb_admin.common.icon.IconSizeEnum; import com.hh.hhdb_admin.common.util.StartUtil; import com.hh.hhdb_admin.common.util.logUtil; import com.hh.hhdb_admin.mgr.constraint.foreign.AbsForeTable; import com.hh.hhdb_admin.mgr.constraint.otherConst.AbsTable; import com.hh.hhdb_admin.mgr.table.TableComp; import javax.swing.*; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * @author YuSai */ public abstract class ConstraintComp { private static final String LOG_NAME = ConstraintComp.class.getSimpleName(); private static final String DOMAIN_NAME = ConstraintComp.class.getName(); static { LangMgr.merge(DOMAIN_NAME, LangUtil.loadLangRes(ConstraintComp.class)); } private final AtomicInteger atomicId = new AtomicInteger(); private final Connection conn; private final DBTypeEnum dbTypeEnum; private final TreeMrType treeMrType; private final String schema; private final String tableName; private final HDialog dialog; private boolean bool; public ConstraintComp(TreeMrType treeMrType, Connection conn, DBTypeEnum dbTypeEnum, String schema, String tableName) { this.conn = conn; this.dbTypeEnum = dbTypeEnum; this.treeMrType = treeMrType; this.schema = schema; this.tableName = tableName; this.dialog = new HDialog(StartUtil.parentFrame, 800, 600); dialog.setIconImage(IconFileUtil.getLogo()); dialog.setWindowTitle(ConstraintComp.getLang("addConstraint")); ConstraintUtil.initConst(conn, dbTypeEnum); TableComp panelCreate = new TableComp(conn, dbTypeEnum); panelCreate.genTableData(); } private HBarPanel getBarPanel(HTable table) { HButton addButton = new HButton(ConstraintComp.getLang("add")) { @Override protected void onClick() { table.add(getData().get(0)); } }; addButton.setIcon(getIcon("add")); HButton delButton = new HButton(ConstraintComp.getLang("delete")) { @Override protected void onClick() { List<HTabRowBean> rows = table.getSelectedRowBeans(); if (rows.size() > 0) { int result = JOptionPane.showConfirmDialog(null, ConstraintComp.getLang("sureDelete"), ConstraintComp.getLang("hint"), JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { table.deleteSelectRow(); } } } }; delButton.setIcon(getIcon("delete")); HButton savaBtn = new HButton(ConstraintComp.getLang("save")) { @Override protected void onClick() { save(table); } }; savaBtn.setIcon(getIcon("save")); HButton preViewBtn = new HButton(ConstraintComp.getLang("previewSql")) { @Override protected void onClick() { previewSql(table); } }; preViewBtn.setIcon(getIcon("sql_view")); HBarLayout barLayout = new HBarLayout(); barLayout.setAlign(AlignEnum.LEFT); HBarPanel barPanel = new HBarPanel(barLayout); barPanel.add(addButton); barPanel.add(delButton); barPanel.add(savaBtn); barPanel.add(preViewBtn); return barPanel; } private void save(HTable table) { try { ConstraintUtil.save(treeMrType, schema, tableName, table, bool); dialog.dispose(); refreshTree(); PopPaneUtil.info(StartUtil.parentFrame.getWindow(), ConstraintComp.getLang("saveSuccess")); } catch (SQLException e) { e.printStackTrace(); logUtil.error(LOG_NAME, e); PopPaneUtil.error(dialog.getWindow(), e.getMessage()); } } private void previewSql(HTable table) { ConstraintUtil.previewSql(treeMrType, schema, tableName, table, bool); } private List<Map<String, String>> getData() { List<Map<String, String>> data = new ArrayList<>(); Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(atomicId.incrementAndGet())); map.put("foreignName", ""); map.put("foreignOnDelete", ""); data.add(map); return data; } public HPanel getForePanel() { this.bool = true; LastPanel lastPanel = new LastPanel(); AbsForeTable foreTable = AbsForeTable.getForeTable(dbTypeEnum); if (null != foreTable) { HTable table = foreTable.getTable(conn, schema, tableName); lastPanel.setHead(getBarPanel(table).getComp()); lastPanel.setWithScroll(table.getComp()); table.load(new ArrayList<>(), 1); } HPanel panel = new HPanel(); panel.setLastPanel(lastPanel); return panel; } void showFore() { dialog.setRootPanel(getForePanel()); dialog.show(); } public HPanel getOtherPanel() { this.bool = false; LastPanel lastPanel = new LastPanel(); AbsTable absOtherTable = AbsTable.getOtherTable(treeMrType); if (null != absOtherTable) { HTable table = absOtherTable.getTable(conn, schema, tableName); lastPanel.setHead(getBarPanel(table).getComp()); lastPanel.setWithScroll(table.getComp()); table.load(new ArrayList<>(), 1); } HPanel panel = new HPanel(); panel.setLastPanel(lastPanel); return panel; } void showOtherConst() { dialog.setRootPanel(getOtherPanel()); dialog.show(); } void delConst(String constType, String schema, String table, String constName) throws Exception { ConstraintUtil.delete(constType, schema, table, constName); refreshTree(); } public static String getLang(String key) { LangMgr.setDefaultLang(StartUtil.default_language); return LangMgr.getValue(DOMAIN_NAME, key); } private ImageIcon getIcon(String name) { return IconFileUtil.getIcon(new IconBean(CsMgrEnum.CONSTRAINT.name(), name, IconSizeEnum.SIZE_16)); } public abstract void refreshTree(); }
7,290
0.647874
0.646228
200
35.450001
24.762825
123
false
false
0
0
0
0
0
0
0.825
false
false
5
2473415a55a5616b5b169c7699653cbbc4a138f5
12,695,923,382,325
bd345fe938ed2ae8dd5d99887f956dbc27ec73d9
/.svn/pristine/24/2473415a55a5616b5b169c7699653cbbc4a138f5.svn-base
7d11091332bb0e0c5a87ac7c82080827b6d62179
[]
no_license
panming2088/gzpsh
https://github.com/panming2088/gzpsh
9a0fe25cd2bcfb2b1eb63bdd7abf829bdbcf3540
e00ac66a5ad4a2d8f9c867cf9a601bf6a6ddae37
refs/heads/master
2023-07-12T00:46:01.515000
2021-08-26T07:21:15
2021-08-26T07:21:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.augurit.agmobile.patrolcore.survey.dao; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.augurit.agmobile.patrolcore.common.table.dao.local.TableDBService; import com.augurit.agmobile.patrolcore.common.table.dao.remote.TableNetCallback; import com.augurit.agmobile.patrolcore.common.table.model.TableItem; import com.augurit.agmobile.patrolcore.survey.model.LocalServerTable; import com.augurit.agmobile.patrolcore.survey.model.LocalServerTableRecord; import com.augurit.agmobile.patrolcore.survey.model.LocalServerTableRecordConstant; import com.augurit.agmobile.patrolcore.survey.model.LocalTable2; import com.augurit.agmobile.patrolcore.survey.model.LocalTableItem2; import com.augurit.agmobile.patrolcore.survey.model.OfflineTask; import com.augurit.agmobile.patrolcore.survey.model.OfflineTaskConstant; import com.augurit.agmobile.patrolcore.survey.model.ServerTable; import com.augurit.agmobile.patrolcore.survey.model.ServerTableRecord; import com.augurit.agmobile.patrolcore.survey.model.ServerTask; import com.augurit.agmobile.patrolcore.survey.util.TableIdConstant; import com.augurit.am.cmpt.common.base.BaseInfoManager; import com.augurit.am.fw.db.AMDatabase; import com.augurit.am.fw.net.util.SharedPreferencesUtil; import com.augurit.am.fw.utils.ListUtil; import com.augurit.am.fw.utils.log.LogUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import io.realm.Realm; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; /** * 将任务进行本地保存的类,表单以及表单中的记录等通过{@link TableDBService}保存; * * @author 创建人 :xuciluan * @version 1.0 * @package 包名 :com.augurit.agmobile.patrolcore.survey.dao * @createTime 创建时间 :17/8/30 * @modifyBy 修改人 :xuciluan * @modifyTime 修改时间 :17/8/30 * @modifyMemo 修改备注: */ public class SurveyLocalDBDao { private Context mContext; private TableDBService tableDBService; public SurveyLocalDBDao(Context context) { mContext = context; tableDBService = new TableDBService(context); } /** * 获取当前用户的已签收任务 * * @return */ public List<ServerTask> getAcceptedTasks() { //返回当前用户的所有任务 return AMDatabase.getInstance().getQueryByWhere(ServerTask.class, "userId", BaseInfoManager.getUserId(mContext)); } /** * 保存已签收任务 */ public void saveAcceptedTasks(List<ServerTask> serverTasks) { for (ServerTask serverTask : serverTasks) { serverTask.setUserId(BaseInfoManager.getUserId(mContext)); } //保存该用户的所有任务 AMDatabase.getInstance().saveAll(serverTasks); } /** * 根据taskId 获取本地保存的该任务下栋表的数据 * * @param taskId 任务id = 地址id * @return */ public Observable<List<ServerTable>> getLocalDongTableObservable(final String taskId, final String taskType) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (TextUtils.isEmpty(taskId)) { tableDBService.getAllLocalServerTableRecordByTaskType(taskType,getDongCallback(subscriber)); } else { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("taskId",taskId); map.put("taskType",taskType); tableDBService.getLocalServerTableRecordByField(map,getDongCallback(subscriber)); } } }); } /** * 根据dongId 获取消防表 * * @param dongId 栋的id * @return */ public Observable<List<ServerTable>> getLocalXiaofangTable(final String dongId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (TextUtils.isEmpty(dongId)) { tableDBService.getAllLocalServerTableRecord(getXiaofangCallback(subscriber, dongId)); } else { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("dongId",dongId); tableDBService.getLocalServerTableRecordByField(map, getXiaofangCallback(subscriber, dongId)); } } }); } /** * 获取栋列表的回调 * * @param subscriber * @param dongId 栋的id * @return */ @NonNull private TableNetCallback<List<LocalServerTableRecord>> getXiaofangCallback(final Subscriber<? super List<ServerTable>> subscriber, final String dongId) { return new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.XIAO_FANG, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.XIAO_FANG); if (!ListUtil.isEmpty(serverTableRecords)){ ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.XIAO_FANG_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); }else { getServerTable(LocalServerTableRecordConstant.XIAO_FANG,subscriber); } } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }; } /** * 获取栋列表的回调 * * @param subscriber * @param taskId * @return */ @NonNull private TableNetCallback<List<LocalServerTableRecord>> getDongCallback(final Subscriber<? super List<ServerTable>> subscriber) { return new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.DONG, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.DONG); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.FANG_WU_DONG_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }; } /** * 根据tableType是栋,套还是人口从LocalServerTable 中拼凑出 ServerTable * * @param tableType * @param subscriber */ private void getServerTable(final String tableType, final Subscriber<? super List<ServerTable>> subscriber) { tableDBService.getAllLocalServerTable(new TableNetCallback<List<LocalServerTable>>() { @Override public void onSuccess(List<LocalServerTable> data) { for (LocalServerTable localServerTable : data) { if (tableType.equals(localServerTable.getTableType())) { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ServerTable serverTable = new ServerTable(); serverTable.setTableId(localServerTable.getTableId()); serverTable.setProjectName(localServerTable.getProjectName()); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } /** * 根据tableType 进行过滤 LocalServerTableRecord * * @param data * @param tableType 表格类型,参考{@link LocalServerTableRecordConstant} * @return */ private ArrayList<ServerTableRecord> getServerTableRecordList(List<LocalServerTableRecord> data, String tableType) { ArrayList<ServerTableRecord> serverTableRecords = new ArrayList<ServerTableRecord>(); for (LocalServerTableRecord localServerTableRecord : data) { if (tableType.equals(localServerTableRecord.getTableType())) { ServerTableRecord serverTableRecord = convertLocalServerTableRecordToServerTableRecord(localServerTableRecord); serverTableRecords.add(serverTableRecord); } } return serverTableRecords; } /** * 将 LocalServerTableRecord 转成 ServerTableRecord * * @param localServerTableRecord * @return */ @NonNull private ServerTableRecord convertLocalServerTableRecordToServerTableRecord(LocalServerTableRecord localServerTableRecord) { ServerTableRecord serverTableRecord = new ServerTableRecord(); serverTableRecord.setTaskId(localServerTableRecord.getTaskId()); serverTableRecord.setRecordId(localServerTableRecord.getRecordId()); serverTableRecord.setStandardaddress(localServerTableRecord.getStandardAddress()); serverTableRecord.setName(localServerTableRecord.getName()); serverTableRecord.setTableId(localServerTableRecord.getTableId()); serverTableRecord.setTaskName(localServerTableRecord.getTaskName()); serverTableRecord.setDanweiId(localServerTableRecord.getDanweiId()); serverTableRecord.setTaoId(localServerTableRecord.getTaoId()); serverTableRecord.setProjectName(localServerTableRecord.getProjectName()); serverTableRecord.setDongName(localServerTableRecord.getDongName()); serverTableRecord.setDongId(localServerTableRecord.getDongId()); serverTableRecord.setState(localServerTableRecord.getState()); /* RealmList<TableItem> items = localServerTableRecord.getItems(); ArrayList<TableItem> tableItems = new ArrayList<>(); for (TableItem tableItem : items) { tableItems.add(tableItem); } serverTableRecord.setItems(tableItems);*/ //根据tableKey 找到 LocalTable String tableKey = localServerTableRecord.getTableKey(); LocalTable2 localTable = getLocalTable2ByTableKey(tableKey); if (localTable != null) { ArrayList<TableItem> tableItems = convert(localTable); serverTableRecord.setItems(tableItems); } return serverTableRecord; } /** * 将本地保存的表记录项转换为原始表格项集合 * * @param localTable * @return */ public static ArrayList<TableItem> convert(LocalTable2 localTable) { ArrayList<TableItem> tableItems = new ArrayList<>(); for (LocalTableItem2 editedTableItem : localTable.getList()) { TableItem tableItem = new TableItem(); tableItem.setDic_code(editedTableItem.getDic_code()); tableItem.setBase_table(editedTableItem.getBase_table()); tableItem.setColum_num(editedTableItem.getColum_num()); tableItem.setControl_type(editedTableItem.getControl_type()); tableItem.setDevice_id(editedTableItem.getDevice_id()); tableItem.setField1(editedTableItem.getField1()); tableItem.setField2(editedTableItem.getField2()); tableItem.setHtml_name(editedTableItem.getHtml_name()); tableItem.setValue(editedTableItem.getValue()); tableItem.setId(editedTableItem.getId()); tableItem.setIs_edit(editedTableItem.getId_edit()); tableItem.setIf_hidden(editedTableItem.getIf_hidden()); tableItem.setIndustry_code(editedTableItem.getIndustry_code()); tableItem.setIndustry_table(editedTableItem.getIndustry_table()); tableItem.setRow_num(editedTableItem.getRow_num()); tableItem.setIs_form_field(editedTableItem.getIs_form_field()); tableItem.setRegex(editedTableItem.getRegex()); tableItem.setValidate_type(editedTableItem.getValidate_type()); tableItem.setFirst_correlation(editedTableItem.getFirst_correlation()); tableItem.setThree_correlation(editedTableItem.getThree_correlation()); tableItem.setIf_required(editedTableItem.getIf_required()); tableItems.add(tableItem); } return tableItems; } /** * 根据表格键ID获取具体的某表实体记录 * * @param tableKey * @return */ public LocalTable2 getLocalTable2ByTableKey(String tableKey) { Realm realm = Realm.getDefaultInstance(); LocalTable2 localTable = realm.where(LocalTable2.class).equalTo("key", tableKey) .findFirst(); LocalTable2 result = null; if (localTable != null) { result = realm.copyFromRealm(localTable); } realm.close(); return result; } /** * 根据dongId 获取本地保存的该任务下套表的数据 * * @param dongId 栋记录的id * @return 套记录 */ public Observable<List<ServerTable>> getLocalTaoTable(final String dongId, final String taskType) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (TextUtils.isEmpty(dongId)) { tableDBService.getAllLocalServerTableRecord(getTaoCallback(subscriber, dongId)); } else { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("dongId",dongId); map.put("taskType",taskType); tableDBService.getLocalServerTableRecordByField(map, getTaoCallback(subscriber, dongId)); } } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 套列表的回调 * * @param subscriber * @param dongId * @return */ @NonNull private TableNetCallback<List<LocalServerTableRecord>> getTaoCallback(final Subscriber<? super List<ServerTable>> subscriber, final String dongId) { return new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.TAO, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.TAO); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.FANG_WU_TAO_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }; } /** * 根据套的id 获取本地保存的该任务下单位记录 * * @param recordId 套的id * @return 单位记录 */ public Observable<List<ServerTable>> getLocalDanweiTable(final String recordId, final boolean ifDong) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (ifDong) { //recordId = 栋id Map<String,String> map = new LinkedHashMap<String, String>(); map.put("dongId",recordId); tableDBService.getLocalServerTableRecordByField(map, new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.SHI_YOU_DAN_WEI, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.SHI_YOU_DAN_WEI); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.SHI_TOU_DAN_WEI_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } else { //recordId = 套id Map<String,String> map = new LinkedHashMap<String, String>(); map.put("taoId",recordId); tableDBService.getLocalServerTableRecordByField( map,new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.SHI_YOU_DAN_WEI, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.SHI_YOU_DAN_WEI); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.SHI_TOU_DAN_WEI_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 根据taoId 获取本地保存的该任务下人口基本表、流动人口表、境外人口表的数据(共3张表) * * @param taoId 套的id * @return 人口基本表、流动人口表、境外人口表的数据 */ public Observable<List<ServerTable>> getLocalRenkouTable(final String taoId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { final TableDBService tableDBService = new TableDBService(mContext); Map<String,String> map = new LinkedHashMap<String, String>(); map.put("taoId",taoId); tableDBService.getLocalServerTableRecordByField(map, new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { //本地有这三张表的记录 Map<String, ServerTable> serverTableMap = new HashMap<String, ServerTable>(); Map<String, ArrayList<ServerTableRecord>> serverTableListMap = new HashMap<String, ArrayList<ServerTableRecord>>(); //过滤出属于这三张表的记录 for (LocalServerTableRecord localServerTableRecord : data) { if (LocalServerTableRecordConstant.REN_KOU_BASIC_INFO.equals(localServerTableRecord.getTableType()) || LocalServerTableRecordConstant.LIU_DONG_REN_KOU.equals(localServerTableRecord.getTableType()) || LocalServerTableRecordConstant.JING_WAI_REN_KOU.equals(localServerTableRecord.getTableType())) { ServerTableRecord serverTableRecord = convertLocalServerTableRecordToServerTableRecord(localServerTableRecord); ArrayList<ServerTableRecord> serverTableRecords1 = serverTableListMap.get(localServerTableRecord.getTableId()); if (serverTableRecords1 == null) { serverTableRecords1 = new ArrayList<ServerTableRecord>(); serverTableRecords1.add(serverTableRecord); serverTableListMap.put(localServerTableRecord.getTableId(), serverTableRecords1); } else { serverTableRecords1.add(serverTableRecord); serverTableListMap.put(localServerTableRecord.getTableId(), serverTableRecords1); } if (serverTableMap.get(localServerTableRecord.getTableId()) == null) { ServerTable serverTable = new ServerTable(); serverTable.setTableId(localServerTableRecord.getTableId()); serverTable.setProjectName(localServerTableRecord.getProjectName()); //因为之后是根据表的名称判断他们是否『基本人口表』还是『流动人口表』,所以这里必须要传入名称 serverTableMap.put(localServerTableRecord.getTableId(), serverTable); } } } if (serverTableListMap.size() == 0) { //如果本地并没有这三张表的记录 //查询三张表的tableId和tableName返回 tableDBService.getAllLocalServerTable(new TableNetCallback<List<LocalServerTable>>() { @Override public void onSuccess(List<LocalServerTable> data) { List<ServerTable> serverTables = new ArrayList<ServerTable>(); for (LocalServerTable localServerTable : data) { if (LocalServerTableRecordConstant.REN_KOU_BASIC_INFO.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.LIU_DONG_REN_KOU.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.JING_WAI_REN_KOU.equals(localServerTable.getTableType())) { ServerTable serverTable = new ServerTable(); serverTable.setProjectName(localServerTable.getProjectName()); serverTable.setTableId(localServerTable.getTableId()); serverTables.add(serverTable); } } subscriber.onNext(serverTables); subscriber.onCompleted(); } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); return; } //有这三张表的记录,将记录归到对应的表下 final List<ServerTable> serverTables = new ArrayList<ServerTable>(); Set<Map.Entry<String, ServerTable>> entries = serverTableMap.entrySet(); for (Map.Entry<String, ServerTable> entry : entries) { String tableId = entry.getKey(); ArrayList<ServerTableRecord> serverTableRecords = serverTableListMap.get(tableId); ServerTable serverTable = entry.getValue(); //此时的recordId还是 表id + recordId的组合,要去掉表id得到它原来真实的id for (ServerTableRecord serverTableRecord : serverTableRecords) { String replacePart = tableId + "+"; String originRecordId = serverTableRecord.getRecordId().replace(replacePart, ""); serverTableRecord.setRecordId(originRecordId); } serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); } //还需要判断是否是三张表,可能存在只有一张表,或者只有两张表的情况,这时需要补充另外几张表的基本信息 if (serverTables.size() != 3) { final Map<String, ServerTable> existedTableIds = new HashMap<String, ServerTable>(); for (ServerTable serverTable : serverTables) { existedTableIds.put(serverTable.getTableId(), serverTable); } tableDBService.getAllLocalServerTable(new TableNetCallback<List<LocalServerTable>>() { @Override public void onSuccess(List<LocalServerTable> data) { List<ServerTable> finalResult = new ArrayList<ServerTable>(); for (LocalServerTable localServerTable : data) { if (LocalServerTableRecordConstant.REN_KOU_BASIC_INFO.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.LIU_DONG_REN_KOU.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.JING_WAI_REN_KOU.equals(localServerTable.getTableType())) { if (existedTableIds.get(localServerTable.getTableId()) == null) { ServerTable newAddedTables = new ServerTable(); newAddedTables.setTableId(localServerTable.getTableId()); newAddedTables.setProjectName(localServerTable.getProjectName()); finalResult.add(newAddedTables); } else { //填充表名称,必须 existedTableIds.get(localServerTable.getTableId()).setProjectName(localServerTable.getProjectName()); } } } finalResult.addAll(serverTables); subscriber.onNext(finalResult); subscriber.onCompleted(); } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } else { subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 根据单位的id 获取本地保存的 从业人员信息 * * @param danweiId 单位的id * @return 从业人员信息 */ public Observable<List<ServerTable>> getLocalCongyeRenyuanTable(final String danweiId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("danweiId",danweiId); tableDBService.getLocalServerTableRecordByField(map, new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.CONGYE_RENYUAN_INFO, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.CONGYE_RENYUAN_INFO); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.CONGYE_INFO_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 根据单位的id 获取本地保存的 学生人员信息 * * @param danweiId 单位的id * @return 学生人员信息 */ public Observable<List<ServerTable>> getLocalXueshengInfoTable(final String danweiId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("danweiId",danweiId); tableDBService.getLocalServerTableRecordByField(map , new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.XUE_SHENG_INFO, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.XUE_SHENG_INFO); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.XUESHENG_INFO_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 保存下载离线数据的时间 */ public void saveSyncTime() { SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext); sharedPreferencesUtil.setLong("lastSyncTime", System.currentTimeMillis());//本地更新时间 } /** * 保存下载过的离线数据 */ public void saveOffLineTask(List<OfflineTask> offlineTasks) { AMDatabase.getInstance().saveAll(offlineTasks); } /** * 获取下载过的离线数据 */ public List<OfflineTask> getOfflineTask() { return AMDatabase.getInstance().getQueryAll(OfflineTask.class); } /** * 获取下载过的离线数据 */ public List<OfflineTask> getOfflineTaskById(String taskId) { return AMDatabase.getInstance().getQueryByWhere(OfflineTask.class,"taskId",taskId); } /** * 获取上次下载离线数据的时间 */ public Long getLastSyncTime() { SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext); return sharedPreferencesUtil.getLong("lastSyncTime", 0l);//最新更新时间 } }
UTF-8
Java
35,914
2473415a55a5616b5b169c7699653cbbc4a138f5.svn-base
Java
[ { "context": "记录等通过{@link TableDBService}保存;\n *\n * @author 创建人 :xuciluan\n * @version 1.0\n * @package 包名 :com.augurit.agmob", "end": 1780, "score": 0.999727725982666, "start": 1772, "tag": "USERNAME", "value": "xuciluan" }, { "context": "ao\n * @createTime 创建时间 :17/8/30\n * @modif...
null
[]
package com.augurit.agmobile.patrolcore.survey.dao; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.augurit.agmobile.patrolcore.common.table.dao.local.TableDBService; import com.augurit.agmobile.patrolcore.common.table.dao.remote.TableNetCallback; import com.augurit.agmobile.patrolcore.common.table.model.TableItem; import com.augurit.agmobile.patrolcore.survey.model.LocalServerTable; import com.augurit.agmobile.patrolcore.survey.model.LocalServerTableRecord; import com.augurit.agmobile.patrolcore.survey.model.LocalServerTableRecordConstant; import com.augurit.agmobile.patrolcore.survey.model.LocalTable2; import com.augurit.agmobile.patrolcore.survey.model.LocalTableItem2; import com.augurit.agmobile.patrolcore.survey.model.OfflineTask; import com.augurit.agmobile.patrolcore.survey.model.OfflineTaskConstant; import com.augurit.agmobile.patrolcore.survey.model.ServerTable; import com.augurit.agmobile.patrolcore.survey.model.ServerTableRecord; import com.augurit.agmobile.patrolcore.survey.model.ServerTask; import com.augurit.agmobile.patrolcore.survey.util.TableIdConstant; import com.augurit.am.cmpt.common.base.BaseInfoManager; import com.augurit.am.fw.db.AMDatabase; import com.augurit.am.fw.net.util.SharedPreferencesUtil; import com.augurit.am.fw.utils.ListUtil; import com.augurit.am.fw.utils.log.LogUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import io.realm.Realm; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; /** * 将任务进行本地保存的类,表单以及表单中的记录等通过{@link TableDBService}保存; * * @author 创建人 :xuciluan * @version 1.0 * @package 包名 :com.augurit.agmobile.patrolcore.survey.dao * @createTime 创建时间 :17/8/30 * @modifyBy 修改人 :xuciluan * @modifyTime 修改时间 :17/8/30 * @modifyMemo 修改备注: */ public class SurveyLocalDBDao { private Context mContext; private TableDBService tableDBService; public SurveyLocalDBDao(Context context) { mContext = context; tableDBService = new TableDBService(context); } /** * 获取当前用户的已签收任务 * * @return */ public List<ServerTask> getAcceptedTasks() { //返回当前用户的所有任务 return AMDatabase.getInstance().getQueryByWhere(ServerTask.class, "userId", BaseInfoManager.getUserId(mContext)); } /** * 保存已签收任务 */ public void saveAcceptedTasks(List<ServerTask> serverTasks) { for (ServerTask serverTask : serverTasks) { serverTask.setUserId(BaseInfoManager.getUserId(mContext)); } //保存该用户的所有任务 AMDatabase.getInstance().saveAll(serverTasks); } /** * 根据taskId 获取本地保存的该任务下栋表的数据 * * @param taskId 任务id = 地址id * @return */ public Observable<List<ServerTable>> getLocalDongTableObservable(final String taskId, final String taskType) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (TextUtils.isEmpty(taskId)) { tableDBService.getAllLocalServerTableRecordByTaskType(taskType,getDongCallback(subscriber)); } else { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("taskId",taskId); map.put("taskType",taskType); tableDBService.getLocalServerTableRecordByField(map,getDongCallback(subscriber)); } } }); } /** * 根据dongId 获取消防表 * * @param dongId 栋的id * @return */ public Observable<List<ServerTable>> getLocalXiaofangTable(final String dongId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (TextUtils.isEmpty(dongId)) { tableDBService.getAllLocalServerTableRecord(getXiaofangCallback(subscriber, dongId)); } else { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("dongId",dongId); tableDBService.getLocalServerTableRecordByField(map, getXiaofangCallback(subscriber, dongId)); } } }); } /** * 获取栋列表的回调 * * @param subscriber * @param dongId 栋的id * @return */ @NonNull private TableNetCallback<List<LocalServerTableRecord>> getXiaofangCallback(final Subscriber<? super List<ServerTable>> subscriber, final String dongId) { return new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.XIAO_FANG, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.XIAO_FANG); if (!ListUtil.isEmpty(serverTableRecords)){ ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.XIAO_FANG_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); }else { getServerTable(LocalServerTableRecordConstant.XIAO_FANG,subscriber); } } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }; } /** * 获取栋列表的回调 * * @param subscriber * @param taskId * @return */ @NonNull private TableNetCallback<List<LocalServerTableRecord>> getDongCallback(final Subscriber<? super List<ServerTable>> subscriber) { return new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.DONG, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.DONG); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.FANG_WU_DONG_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }; } /** * 根据tableType是栋,套还是人口从LocalServerTable 中拼凑出 ServerTable * * @param tableType * @param subscriber */ private void getServerTable(final String tableType, final Subscriber<? super List<ServerTable>> subscriber) { tableDBService.getAllLocalServerTable(new TableNetCallback<List<LocalServerTable>>() { @Override public void onSuccess(List<LocalServerTable> data) { for (LocalServerTable localServerTable : data) { if (tableType.equals(localServerTable.getTableType())) { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ServerTable serverTable = new ServerTable(); serverTable.setTableId(localServerTable.getTableId()); serverTable.setProjectName(localServerTable.getProjectName()); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } /** * 根据tableType 进行过滤 LocalServerTableRecord * * @param data * @param tableType 表格类型,参考{@link LocalServerTableRecordConstant} * @return */ private ArrayList<ServerTableRecord> getServerTableRecordList(List<LocalServerTableRecord> data, String tableType) { ArrayList<ServerTableRecord> serverTableRecords = new ArrayList<ServerTableRecord>(); for (LocalServerTableRecord localServerTableRecord : data) { if (tableType.equals(localServerTableRecord.getTableType())) { ServerTableRecord serverTableRecord = convertLocalServerTableRecordToServerTableRecord(localServerTableRecord); serverTableRecords.add(serverTableRecord); } } return serverTableRecords; } /** * 将 LocalServerTableRecord 转成 ServerTableRecord * * @param localServerTableRecord * @return */ @NonNull private ServerTableRecord convertLocalServerTableRecordToServerTableRecord(LocalServerTableRecord localServerTableRecord) { ServerTableRecord serverTableRecord = new ServerTableRecord(); serverTableRecord.setTaskId(localServerTableRecord.getTaskId()); serverTableRecord.setRecordId(localServerTableRecord.getRecordId()); serverTableRecord.setStandardaddress(localServerTableRecord.getStandardAddress()); serverTableRecord.setName(localServerTableRecord.getName()); serverTableRecord.setTableId(localServerTableRecord.getTableId()); serverTableRecord.setTaskName(localServerTableRecord.getTaskName()); serverTableRecord.setDanweiId(localServerTableRecord.getDanweiId()); serverTableRecord.setTaoId(localServerTableRecord.getTaoId()); serverTableRecord.setProjectName(localServerTableRecord.getProjectName()); serverTableRecord.setDongName(localServerTableRecord.getDongName()); serverTableRecord.setDongId(localServerTableRecord.getDongId()); serverTableRecord.setState(localServerTableRecord.getState()); /* RealmList<TableItem> items = localServerTableRecord.getItems(); ArrayList<TableItem> tableItems = new ArrayList<>(); for (TableItem tableItem : items) { tableItems.add(tableItem); } serverTableRecord.setItems(tableItems);*/ //根据tableKey 找到 LocalTable String tableKey = localServerTableRecord.getTableKey(); LocalTable2 localTable = getLocalTable2ByTableKey(tableKey); if (localTable != null) { ArrayList<TableItem> tableItems = convert(localTable); serverTableRecord.setItems(tableItems); } return serverTableRecord; } /** * 将本地保存的表记录项转换为原始表格项集合 * * @param localTable * @return */ public static ArrayList<TableItem> convert(LocalTable2 localTable) { ArrayList<TableItem> tableItems = new ArrayList<>(); for (LocalTableItem2 editedTableItem : localTable.getList()) { TableItem tableItem = new TableItem(); tableItem.setDic_code(editedTableItem.getDic_code()); tableItem.setBase_table(editedTableItem.getBase_table()); tableItem.setColum_num(editedTableItem.getColum_num()); tableItem.setControl_type(editedTableItem.getControl_type()); tableItem.setDevice_id(editedTableItem.getDevice_id()); tableItem.setField1(editedTableItem.getField1()); tableItem.setField2(editedTableItem.getField2()); tableItem.setHtml_name(editedTableItem.getHtml_name()); tableItem.setValue(editedTableItem.getValue()); tableItem.setId(editedTableItem.getId()); tableItem.setIs_edit(editedTableItem.getId_edit()); tableItem.setIf_hidden(editedTableItem.getIf_hidden()); tableItem.setIndustry_code(editedTableItem.getIndustry_code()); tableItem.setIndustry_table(editedTableItem.getIndustry_table()); tableItem.setRow_num(editedTableItem.getRow_num()); tableItem.setIs_form_field(editedTableItem.getIs_form_field()); tableItem.setRegex(editedTableItem.getRegex()); tableItem.setValidate_type(editedTableItem.getValidate_type()); tableItem.setFirst_correlation(editedTableItem.getFirst_correlation()); tableItem.setThree_correlation(editedTableItem.getThree_correlation()); tableItem.setIf_required(editedTableItem.getIf_required()); tableItems.add(tableItem); } return tableItems; } /** * 根据表格键ID获取具体的某表实体记录 * * @param tableKey * @return */ public LocalTable2 getLocalTable2ByTableKey(String tableKey) { Realm realm = Realm.getDefaultInstance(); LocalTable2 localTable = realm.where(LocalTable2.class).equalTo("key", tableKey) .findFirst(); LocalTable2 result = null; if (localTable != null) { result = realm.copyFromRealm(localTable); } realm.close(); return result; } /** * 根据dongId 获取本地保存的该任务下套表的数据 * * @param dongId 栋记录的id * @return 套记录 */ public Observable<List<ServerTable>> getLocalTaoTable(final String dongId, final String taskType) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (TextUtils.isEmpty(dongId)) { tableDBService.getAllLocalServerTableRecord(getTaoCallback(subscriber, dongId)); } else { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("dongId",dongId); map.put("taskType",taskType); tableDBService.getLocalServerTableRecordByField(map, getTaoCallback(subscriber, dongId)); } } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 套列表的回调 * * @param subscriber * @param dongId * @return */ @NonNull private TableNetCallback<List<LocalServerTableRecord>> getTaoCallback(final Subscriber<? super List<ServerTable>> subscriber, final String dongId) { return new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.TAO, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.TAO); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.FANG_WU_TAO_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }; } /** * 根据套的id 获取本地保存的该任务下单位记录 * * @param recordId 套的id * @return 单位记录 */ public Observable<List<ServerTable>> getLocalDanweiTable(final String recordId, final boolean ifDong) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { if (ifDong) { //recordId = 栋id Map<String,String> map = new LinkedHashMap<String, String>(); map.put("dongId",recordId); tableDBService.getLocalServerTableRecordByField(map, new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.SHI_YOU_DAN_WEI, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.SHI_YOU_DAN_WEI); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.SHI_TOU_DAN_WEI_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } else { //recordId = 套id Map<String,String> map = new LinkedHashMap<String, String>(); map.put("taoId",recordId); tableDBService.getLocalServerTableRecordByField( map,new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.SHI_YOU_DAN_WEI, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.SHI_YOU_DAN_WEI); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.SHI_TOU_DAN_WEI_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 根据taoId 获取本地保存的该任务下人口基本表、流动人口表、境外人口表的数据(共3张表) * * @param taoId 套的id * @return 人口基本表、流动人口表、境外人口表的数据 */ public Observable<List<ServerTable>> getLocalRenkouTable(final String taoId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { final TableDBService tableDBService = new TableDBService(mContext); Map<String,String> map = new LinkedHashMap<String, String>(); map.put("taoId",taoId); tableDBService.getLocalServerTableRecordByField(map, new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { //本地有这三张表的记录 Map<String, ServerTable> serverTableMap = new HashMap<String, ServerTable>(); Map<String, ArrayList<ServerTableRecord>> serverTableListMap = new HashMap<String, ArrayList<ServerTableRecord>>(); //过滤出属于这三张表的记录 for (LocalServerTableRecord localServerTableRecord : data) { if (LocalServerTableRecordConstant.REN_KOU_BASIC_INFO.equals(localServerTableRecord.getTableType()) || LocalServerTableRecordConstant.LIU_DONG_REN_KOU.equals(localServerTableRecord.getTableType()) || LocalServerTableRecordConstant.JING_WAI_REN_KOU.equals(localServerTableRecord.getTableType())) { ServerTableRecord serverTableRecord = convertLocalServerTableRecordToServerTableRecord(localServerTableRecord); ArrayList<ServerTableRecord> serverTableRecords1 = serverTableListMap.get(localServerTableRecord.getTableId()); if (serverTableRecords1 == null) { serverTableRecords1 = new ArrayList<ServerTableRecord>(); serverTableRecords1.add(serverTableRecord); serverTableListMap.put(localServerTableRecord.getTableId(), serverTableRecords1); } else { serverTableRecords1.add(serverTableRecord); serverTableListMap.put(localServerTableRecord.getTableId(), serverTableRecords1); } if (serverTableMap.get(localServerTableRecord.getTableId()) == null) { ServerTable serverTable = new ServerTable(); serverTable.setTableId(localServerTableRecord.getTableId()); serverTable.setProjectName(localServerTableRecord.getProjectName()); //因为之后是根据表的名称判断他们是否『基本人口表』还是『流动人口表』,所以这里必须要传入名称 serverTableMap.put(localServerTableRecord.getTableId(), serverTable); } } } if (serverTableListMap.size() == 0) { //如果本地并没有这三张表的记录 //查询三张表的tableId和tableName返回 tableDBService.getAllLocalServerTable(new TableNetCallback<List<LocalServerTable>>() { @Override public void onSuccess(List<LocalServerTable> data) { List<ServerTable> serverTables = new ArrayList<ServerTable>(); for (LocalServerTable localServerTable : data) { if (LocalServerTableRecordConstant.REN_KOU_BASIC_INFO.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.LIU_DONG_REN_KOU.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.JING_WAI_REN_KOU.equals(localServerTable.getTableType())) { ServerTable serverTable = new ServerTable(); serverTable.setProjectName(localServerTable.getProjectName()); serverTable.setTableId(localServerTable.getTableId()); serverTables.add(serverTable); } } subscriber.onNext(serverTables); subscriber.onCompleted(); } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); return; } //有这三张表的记录,将记录归到对应的表下 final List<ServerTable> serverTables = new ArrayList<ServerTable>(); Set<Map.Entry<String, ServerTable>> entries = serverTableMap.entrySet(); for (Map.Entry<String, ServerTable> entry : entries) { String tableId = entry.getKey(); ArrayList<ServerTableRecord> serverTableRecords = serverTableListMap.get(tableId); ServerTable serverTable = entry.getValue(); //此时的recordId还是 表id + recordId的组合,要去掉表id得到它原来真实的id for (ServerTableRecord serverTableRecord : serverTableRecords) { String replacePart = tableId + "+"; String originRecordId = serverTableRecord.getRecordId().replace(replacePart, ""); serverTableRecord.setRecordId(originRecordId); } serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); } //还需要判断是否是三张表,可能存在只有一张表,或者只有两张表的情况,这时需要补充另外几张表的基本信息 if (serverTables.size() != 3) { final Map<String, ServerTable> existedTableIds = new HashMap<String, ServerTable>(); for (ServerTable serverTable : serverTables) { existedTableIds.put(serverTable.getTableId(), serverTable); } tableDBService.getAllLocalServerTable(new TableNetCallback<List<LocalServerTable>>() { @Override public void onSuccess(List<LocalServerTable> data) { List<ServerTable> finalResult = new ArrayList<ServerTable>(); for (LocalServerTable localServerTable : data) { if (LocalServerTableRecordConstant.REN_KOU_BASIC_INFO.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.LIU_DONG_REN_KOU.equals(localServerTable.getTableType()) || LocalServerTableRecordConstant.JING_WAI_REN_KOU.equals(localServerTable.getTableType())) { if (existedTableIds.get(localServerTable.getTableId()) == null) { ServerTable newAddedTables = new ServerTable(); newAddedTables.setTableId(localServerTable.getTableId()); newAddedTables.setProjectName(localServerTable.getProjectName()); finalResult.add(newAddedTables); } else { //填充表名称,必须 existedTableIds.get(localServerTable.getTableId()).setProjectName(localServerTable.getProjectName()); } } } finalResult.addAll(serverTables); subscriber.onNext(finalResult); subscriber.onCompleted(); } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } else { subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 根据单位的id 获取本地保存的 从业人员信息 * * @param danweiId 单位的id * @return 从业人员信息 */ public Observable<List<ServerTable>> getLocalCongyeRenyuanTable(final String danweiId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("danweiId",danweiId); tableDBService.getLocalServerTableRecordByField(map, new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.CONGYE_RENYUAN_INFO, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.CONGYE_RENYUAN_INFO); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.CONGYE_INFO_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 根据单位的id 获取本地保存的 学生人员信息 * * @param danweiId 单位的id * @return 学生人员信息 */ public Observable<List<ServerTable>> getLocalXueshengInfoTable(final String danweiId) { return Observable.create(new Observable.OnSubscribe<List<ServerTable>>() { @Override public void call(final Subscriber<? super List<ServerTable>> subscriber) { Map<String,String> map = new LinkedHashMap<String, String>(); map.put("danweiId",danweiId); tableDBService.getLocalServerTableRecordByField(map , new TableNetCallback<List<LocalServerTableRecord>>() { @Override public void onSuccess(List<LocalServerTableRecord> data) { if (ListUtil.isEmpty(data)) { //返回只包含tableId的ServerTable getServerTable(LocalServerTableRecordConstant.XUE_SHENG_INFO, subscriber); } else { List<ServerTable> serverTables = new ArrayList<ServerTable>(); ArrayList<ServerTableRecord> serverTableRecords = getServerTableRecordList(data, LocalServerTableRecordConstant.XUE_SHENG_INFO); ServerTable serverTable = new ServerTable(); serverTable.setTableId(TableIdConstant.XUESHENG_INFO_TABLE_ID); serverTable.setRecords(serverTableRecords); serverTables.add(serverTable); subscriber.onNext(serverTables); subscriber.onCompleted(); } } @Override public void onError(String msg) { subscriber.onError(new Exception(msg)); } }); } }).subscribeOn(AndroidSchedulers.mainThread()); } /** * 保存下载离线数据的时间 */ public void saveSyncTime() { SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext); sharedPreferencesUtil.setLong("lastSyncTime", System.currentTimeMillis());//本地更新时间 } /** * 保存下载过的离线数据 */ public void saveOffLineTask(List<OfflineTask> offlineTasks) { AMDatabase.getInstance().saveAll(offlineTasks); } /** * 获取下载过的离线数据 */ public List<OfflineTask> getOfflineTask() { return AMDatabase.getInstance().getQueryAll(OfflineTask.class); } /** * 获取下载过的离线数据 */ public List<OfflineTask> getOfflineTaskById(String taskId) { return AMDatabase.getInstance().getQueryByWhere(OfflineTask.class,"taskId",taskId); } /** * 获取上次下载离线数据的时间 */ public Long getLastSyncTime() { SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext); return sharedPreferencesUtil.getLong("lastSyncTime", 0l);//最新更新时间 } }
35,914
0.568936
0.567807
792
42.628788
37.531685
161
false
false
0
0
0
0
0
0
0.463384
false
false
5
46fc1c2c7a9362c800c85cecc44c484ade9453a2
5,403,068,903,384
d31dc6c6d90b709b3e217bc62c5ef732035214df
/app/src/main/java/com/mkleo/project/base/IPermissonInterface.java
522c777c6d6bc1fd3430ba9c2c5ca81c66952378
[]
no_license
Mkleo-github/MkMvpAndroid
https://github.com/Mkleo-github/MkMvpAndroid
99641cdb90e3c5f402d54712b505379f03b3f4a9
e96d762552de3753a633f41bdf303e5dfe454b0d
refs/heads/master
2021-07-04T00:39:50.838000
2020-07-07T05:59:21
2020-07-07T05:59:21
199,369,109
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mkleo.project.base; public interface IPermissonInterface { String[] getRequestPermissions(); void onAllPermissionsGranted(); void onSomePermissionsDenied(); }
UTF-8
Java
187
java
IPermissonInterface.java
Java
[]
null
[]
package com.mkleo.project.base; public interface IPermissonInterface { String[] getRequestPermissions(); void onAllPermissionsGranted(); void onSomePermissionsDenied(); }
187
0.754011
0.754011
10
17.700001
17.584368
38
false
false
0
0
0
0
0
0
0.4
false
false
5
504de61ec479726aaf059fc1363477d43b8af119
23,244,363,059,874
b497e34a918afcc87400cf99c9d150ec8371d027
/poi/src/main/java/com/jk/dao/UserDao.java
31313d4b3d97d62c5d5448444a1e45fbf797dc96
[]
no_license
zhuyouQWER/qqqq
https://github.com/zhuyouQWER/qqqq
394ff30735b0cf6a98c91a607fe6de5d0ef5cb27
66b0cfcaac3ad2a941acb728749b8f650b5b2847
refs/heads/master
2022-07-05T10:57:32.682000
2019-08-14T07:02:54
2019-08-14T07:02:54
202,294,310
0
0
null
false
2022-06-29T17:34:40
2019-08-14T07:06:36
2019-08-14T07:09:22
2022-06-29T17:34:37
665
0
0
6
CSS
false
false
package com.jk.dao; import com.jk.model.User; import java.util.List; public interface UserDao { List<User> cha(); void xin(List<User> list); }
UTF-8
Java
155
java
UserDao.java
Java
[]
null
[]
package com.jk.dao; import com.jk.model.User; import java.util.List; public interface UserDao { List<User> cha(); void xin(List<User> list); }
155
0.677419
0.677419
11
13.090909
12.071413
30
false
false
0
0
0
0
0
0
0.454545
false
false
5
21b339775a9a05f0b3c065728aa30d3a3554041b
23,244,363,058,991
55d0085a4827496d72cb3a18c3b133ad5892d30e
/src/main/java/com/crd/carrental/facade/CarRentalFacadeImpl.java
34d1c4a2cb3134963686e4a17cb7e90eeff669d4
[]
no_license
floklaus/crd
https://github.com/floklaus/crd
4af01ae37d6f24cf0a34975982f0358d97d75d2c
53d82b063dc6a6b8dafc558ef4509fe7dd209ada
refs/heads/master
2020-04-17T18:55:39.161000
2019-01-21T16:42:46
2019-01-21T16:42:46
166,846,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crd.carrental.facade; import com.crd.carrental.dto.Booking; import com.crd.carrental.exception.BookingNotPossibleException; import com.crd.carrental.exception.ParameterInvalidException; import com.crd.carrental.model.Car; import com.crd.carrental.model.CarType; import com.crd.carrental.service.CarRentalService; import org.joda.time.DateTime; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CarRentalFacadeImpl implements CarRentalFacade { private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy"); @Autowired CarRentalService carRentalService; @Override public Booking acknowledgeBooking(String type, String startDate, int days) throws BookingNotPossibleException, ParameterInvalidException { assertDays(days); DateTime startOfRental = assertStartDate(startDate); CarType carType = assertCarType(type); Interval requestedRentalInterval = getRentalInterval(startOfRental, days); return createAcknowledgedBooking(carRentalService.acknowledgeBooking(carType, requestedRentalInterval), requestedRentalInterval); } @Override public void addCar(String carType) throws ParameterInvalidException { CarType type = CarType.getType(carType); if (null == type) { throw new ParameterInvalidException("unknown car type"); } Car car = new Car(type); carRentalService.addCar(car); } private void assertDays(int days) throws ParameterInvalidException { if (days < 1) { throw new ParameterInvalidException("number of days must be larger than 0"); } } private DateTime assertStartDate(String startDate) { DateTime startOfRental; try { startOfRental = formatter.parseDateTime(startDate); } catch (IllegalArgumentException ex) { throw new ParameterInvalidException("wrong format of start date. must be MM-dd-yyyy"); } if (startOfRental.isBeforeNow()) { throw new ParameterInvalidException("start date must be after now"); } // more validations possible return startOfRental; } private CarType assertCarType(String type) { CarType carType = CarType.getType(type); if (null != carType) { return carType; } else { throw new ParameterInvalidException("wrong parameter: car type unknown"); } } private Interval getRentalInterval(DateTime startOfRental, int days) { DateTime endOfRental = new DateTime(startOfRental); endOfRental = endOfRental.plusDays(days); return new Interval(startOfRental, endOfRental); } private Booking createAcknowledgedBooking(Car car, Interval interval) { Booking booking = new Booking(); booking.setCar(car.getCarType().getTypeValue()); booking.setStartDate(formatter.print(interval.getStart())); booking.setEndDate(formatter.print(interval.getEnd())); booking.setAcknowledged(true); return booking; } }
UTF-8
Java
3,291
java
CarRentalFacadeImpl.java
Java
[]
null
[]
package com.crd.carrental.facade; import com.crd.carrental.dto.Booking; import com.crd.carrental.exception.BookingNotPossibleException; import com.crd.carrental.exception.ParameterInvalidException; import com.crd.carrental.model.Car; import com.crd.carrental.model.CarType; import com.crd.carrental.service.CarRentalService; import org.joda.time.DateTime; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CarRentalFacadeImpl implements CarRentalFacade { private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy"); @Autowired CarRentalService carRentalService; @Override public Booking acknowledgeBooking(String type, String startDate, int days) throws BookingNotPossibleException, ParameterInvalidException { assertDays(days); DateTime startOfRental = assertStartDate(startDate); CarType carType = assertCarType(type); Interval requestedRentalInterval = getRentalInterval(startOfRental, days); return createAcknowledgedBooking(carRentalService.acknowledgeBooking(carType, requestedRentalInterval), requestedRentalInterval); } @Override public void addCar(String carType) throws ParameterInvalidException { CarType type = CarType.getType(carType); if (null == type) { throw new ParameterInvalidException("unknown car type"); } Car car = new Car(type); carRentalService.addCar(car); } private void assertDays(int days) throws ParameterInvalidException { if (days < 1) { throw new ParameterInvalidException("number of days must be larger than 0"); } } private DateTime assertStartDate(String startDate) { DateTime startOfRental; try { startOfRental = formatter.parseDateTime(startDate); } catch (IllegalArgumentException ex) { throw new ParameterInvalidException("wrong format of start date. must be MM-dd-yyyy"); } if (startOfRental.isBeforeNow()) { throw new ParameterInvalidException("start date must be after now"); } // more validations possible return startOfRental; } private CarType assertCarType(String type) { CarType carType = CarType.getType(type); if (null != carType) { return carType; } else { throw new ParameterInvalidException("wrong parameter: car type unknown"); } } private Interval getRentalInterval(DateTime startOfRental, int days) { DateTime endOfRental = new DateTime(startOfRental); endOfRental = endOfRental.plusDays(days); return new Interval(startOfRental, endOfRental); } private Booking createAcknowledgedBooking(Car car, Interval interval) { Booking booking = new Booking(); booking.setCar(car.getCarType().getTypeValue()); booking.setStartDate(formatter.print(interval.getStart())); booking.setEndDate(formatter.print(interval.getEnd())); booking.setAcknowledged(true); return booking; } }
3,291
0.708903
0.708295
90
35.566666
31.220026
142
false
false
0
0
0
0
0
0
0.566667
false
false
5
eacf1faaa20f4cb56db28358ace17b5542c40384
11,673,721,166,951
79d51299591d170795abde11c3a6c09f5317b773
/spring1705/src/main/java/spring1705/metro/service/MetroServiceImpl.java
3ada1dc65df0a4cda16067ded30f2fd74954cb36
[]
no_license
rktldhkd/spring_base4.2.4
https://github.com/rktldhkd/spring_base4.2.4
5d7175d47267b2511282875be5948c76a6523a2f
9109ba0b398489beb4f56364d6265582329d1ea0
refs/heads/master
2021-05-04T12:00:24.862000
2018-10-16T23:50:25
2018-10-16T23:50:25
120,284,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package spring1705.metro.service; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import spring1705.metro.dao.MetroDAO; @Service("metroService") public class MetroServiceImpl implements MetroService{ @Resource(name = "metroDAO") private MetroDAO metroDAO; @Override public List selectMetroLines() throws Exception { List<String> result = metroDAO.selectMetroLines(); return result; }//selectMetroLines() @Override public List<Map<String,Object>> selectStaions(Map<String, Object> map) throws Exception { return (List<Map<String,Object>>)metroDAO.selectStations(map); } }//class
UTF-8
Java
709
java
MetroServiceImpl.java
Java
[]
null
[]
package spring1705.metro.service; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import spring1705.metro.dao.MetroDAO; @Service("metroService") public class MetroServiceImpl implements MetroService{ @Resource(name = "metroDAO") private MetroDAO metroDAO; @Override public List selectMetroLines() throws Exception { List<String> result = metroDAO.selectMetroLines(); return result; }//selectMetroLines() @Override public List<Map<String,Object>> selectStaions(Map<String, Object> map) throws Exception { return (List<Map<String,Object>>)metroDAO.selectStations(map); } }//class
709
0.744711
0.733427
28
23.321428
23.096155
90
false
false
0
0
0
0
0
0
1.035714
false
false
5
88d3cfef6804a94bcadfaf4fd3efd777d72ec51c
21,723,944,651,770
abff60f066896890d9dd83e312178efbd82f64ab
/4.java
a4b10e3d630ad21d93a615bc21fb9531cf753203
[]
no_license
Md-Sabbir-Ahmed/Core_Java_And_OOP----Anisul_Islam_Tutorial
https://github.com/Md-Sabbir-Ahmed/Core_Java_And_OOP----Anisul_Islam_Tutorial
e84bcb7651a78e9e50cbc62f61b0670d38849487
656ae360b39f525ec0cb7daca143876f32308441
refs/heads/master
2022-11-15T20:07:23.998000
2020-07-13T17:52:39
2020-07-13T17:52:39
261,274,359
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package basicjava; public class BoiData { public static void main(String[] args) { System.out.println("Md.Sabbir Ahmed"); System.out.println("19101046"); } }
UTF-8
Java
196
java
4.java
Java
[ { "context": "tring[] args)\n {\n \n System.out.println(\"Md.Sabbir Ahmed\");\n System.out.println(\"19101046\"", "end": 130, "score": 0.9987711906433105, "start": 128, "tag": "NAME", "value": "Md" }, { "context": "ng[] args)\n {\n \n System.out.println(\"Md.S...
null
[]
package basicjava; public class BoiData { public static void main(String[] args) { System.out.println("Md.<NAME>"); System.out.println("19101046"); } }
190
0.596939
0.556122
13
14.153846
15.717928
43
false
false
0
0
0
0
0
0
0.230769
false
false
5
cdb6ce6989df96b3911faa809b3b398d3d8b7f54
1,073,741,869,125
a4f94f4701a59cafc7407aed2d525b2dff985c95
/languages/util/ypath/solutions/jetbrains.mps.ypath.runtime/source_gen/jetbrains/mps/ypath/runtime/dom/ChainedIterator.java
fa89cf64e4dcf8798632caa5dd22db787400924d
[]
no_license
jamice/code-orchestra-core
https://github.com/jamice/code-orchestra-core
ffda62860f5b117386aa6455f4fdf61661abbe9e
b2bbf8362be2e2173864c294c635badb2e27ecc6
refs/heads/master
2021-01-15T13:24:53.517000
2013-05-09T21:39:28
2013-05-09T21:39:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jetbrains.mps.ypath.runtime.dom; /*Generated by MPS */ import java.util.Iterator; import java.util.List; import java.util.Arrays; import java.util.NoSuchElementException; public class ChainedIterator<E> implements Iterator<E> { private final List<Iterator<E>> iterators; private int index = 0; public ChainedIterator(Iterator<E>... iterators) { this.iterators = Arrays.asList(iterators); moveToNext(); } public ChainedIterator(List<Iterator<E>> iteratorsList) { this.iterators = iteratorsList; moveToNext(); } private void moveToNext() { while (index < iterators.size() && !(iterators.get(index).hasNext())) { index++; } } public boolean hasNext() { return index < iterators.size(); } public E next() { if (hasNext()) { E tmp = iterators.get(index).next(); moveToNext(); return tmp; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }
UTF-8
Java
1,006
java
ChainedIterator.java
Java
[]
null
[]
package jetbrains.mps.ypath.runtime.dom; /*Generated by MPS */ import java.util.Iterator; import java.util.List; import java.util.Arrays; import java.util.NoSuchElementException; public class ChainedIterator<E> implements Iterator<E> { private final List<Iterator<E>> iterators; private int index = 0; public ChainedIterator(Iterator<E>... iterators) { this.iterators = Arrays.asList(iterators); moveToNext(); } public ChainedIterator(List<Iterator<E>> iteratorsList) { this.iterators = iteratorsList; moveToNext(); } private void moveToNext() { while (index < iterators.size() && !(iterators.get(index).hasNext())) { index++; } } public boolean hasNext() { return index < iterators.size(); } public E next() { if (hasNext()) { E tmp = iterators.get(index).next(); moveToNext(); return tmp; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }
1,006
0.666004
0.66501
46
20.869566
19.40933
75
false
false
0
0
0
0
0
0
0.391304
false
false
5
945c852a3d0240c7a5f45d6d8c6a99a3d192b259
30,829,275,281,229
4a6a9d22bb759dd56d44f7d592bd7bfaf696289f
/x_program_center/src/main/java/com/x/program/center/ThisApplication.java
2dd3275561e8cd03fdc9806a78e21932aef0e46d
[ "MIT" ]
permissive
hq1980/o2oa
https://github.com/hq1980/o2oa
ff665c70621f035d0cd1110b71f2cd4f92686972
12bdca9149bbe8f377622ca0a5a861362999cde5
refs/heads/master
2021-01-22T09:10:29.309000
2017-02-14T07:17:03
2017-02-14T07:17:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.x.program.center; import com.x.base.core.application.Applications; import com.x.base.core.project.AbstractThisApplication; import com.x.program.center.jaxrs.center.ActionReport; import com.x.program.center.timertask.CheckServerTimerTask; import com.x.program.center.timertask.ClearApplicationsTimerTask; public class ThisApplication extends AbstractThisApplication { public static void init() throws Exception { /* 启动报告任务 */ // scheduler.scheduleWithFixedDelay(new ReportTask(), 1, 20, // TimeUnit.SECONDS); scheduleWithFixedDelay(new ClearApplicationsTimerTask(), 10, 30); scheduleWithFixedDelay(new CheckServerTimerTask(), 5, 60 * 5); // dataMappings = new DataMappings(nodeConfigs); // storageMappings = new StorageMappings(nodeConfigs); applications = new Applications(); ActionReport.start(); } public static void destroy() { ActionReport.stop(); } }
UTF-8
Java
908
java
ThisApplication.java
Java
[]
null
[]
package com.x.program.center; import com.x.base.core.application.Applications; import com.x.base.core.project.AbstractThisApplication; import com.x.program.center.jaxrs.center.ActionReport; import com.x.program.center.timertask.CheckServerTimerTask; import com.x.program.center.timertask.ClearApplicationsTimerTask; public class ThisApplication extends AbstractThisApplication { public static void init() throws Exception { /* 启动报告任务 */ // scheduler.scheduleWithFixedDelay(new ReportTask(), 1, 20, // TimeUnit.SECONDS); scheduleWithFixedDelay(new ClearApplicationsTimerTask(), 10, 30); scheduleWithFixedDelay(new CheckServerTimerTask(), 5, 60 * 5); // dataMappings = new DataMappings(nodeConfigs); // storageMappings = new StorageMappings(nodeConfigs); applications = new Applications(); ActionReport.start(); } public static void destroy() { ActionReport.stop(); } }
908
0.777902
0.765625
27
32.222221
24.86755
67
false
false
0
0
0
0
0
0
1.666667
false
false
5
c07a015657fdd28d7505e2482adacdeb469c1126
4,063,039,079,405
06f5a30542b82ecc0b338995fe60429f59da331f
/ssalog_backend/src/main/java/com/ssalog/jwt/JwtAuthenticationEntryPoint.java
65b642f5416e759aea77fc0f39407e8637a025b6
[]
no_license
james0223/SSALOG
https://github.com/james0223/SSALOG
95a5977a49ea7b2d6c7700eedbba02260cee370b
52bcd8d80d48110004637ce3245b450b3e39fc99
refs/heads/master
2022-12-07T05:59:37.376000
2020-09-07T05:50:39
2020-09-07T05:50:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssalog.jwt; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Serializable; @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -7858869558953243875L; // 권한이 없을 경우, 예외처리 @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { if(response.getHeader("error") != null && response.getHeader("error").equals("expired")) { response.sendError(9999, "expired"); response.setHeader("error", null); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } } }
UTF-8
Java
1,055
java
JwtAuthenticationEntryPoint.java
Java
[]
null
[]
package com.ssalog.jwt; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Serializable; @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -7858869558953243875L; // 권한이 없을 경우, 예외처리 @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { if(response.getHeader("error") != null && response.getHeader("error").equals("expired")) { response.sendError(9999, "expired"); response.setHeader("error", null); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } } }
1,055
0.758955
0.736689
29
34.655174
31.53463
95
false
false
0
0
0
0
0
0
1
false
false
5
d8b8695ffc02f10076f546fef01d46ea5a33e08b
18,296,560,716,910
5e9f8ccb93a17257abeea2bbbe7bd7a7c94a86b0
/src/main/java/com/wms/controller/stock_managerment/ImportOrderStockController.java
aa332f384a5e60e66b084e8e7a1a756fadcd9433
[]
no_license
duyot/WMS
https://github.com/duyot/WMS
076f3b2ae28f02ec37a8d715e61b2260d86f379d
09c5c619cbdb20944e12fdee964d16ea089b6f41
refs/heads/master
2022-07-09T17:08:57.087000
2021-10-10T08:32:46
2021-10-10T08:32:46
71,097,803
1
0
null
false
2022-06-28T14:15:18
2016-10-17T03:44:00
2021-10-10T08:32:57
2022-06-28T14:15:17
50,161
1
0
3
HTML
false
false
package com.wms.controller.stock_managerment; import com.google.common.collect.Lists; import com.wms.base.BaseController; import com.wms.constants.Constants; import com.wms.dto.*; import com.wms.services.interfaces.BaseService; import com.wms.services.interfaces.CatUserService; import com.wms.services.interfaces.OrderExportService; import com.wms.utils.DataUtil; import com.wms.utils.DateTimeUtils; import com.wms.utils.FunctionUtils; import java.io.File; import java.util.*; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.wms.utils.SessionUtils; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.export.SimpleDocxReportConfiguration; import net.sf.jasperreports.export.SimpleExporterInput; import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/workspace/import_stock_order_ctr") @Scope("session") public class ImportOrderStockController extends BaseController { @Autowired OrderExportService mjrOrderService; private Logger log = LoggerFactory.getLogger(ImportOrderStockController.class); @Autowired public CatUserService catUserService; @Autowired BaseService catStockCellService; private List<CatUserDTO> lstUsers; private List<MjrOrderDTO> lstOrder; List<ComboSourceDTO> cells = new ArrayList<>(); public LinkedHashMap<String, String> mapUnitType; //------------------------------------------------------------------------------------------------------------------ @PostConstruct public void init() { if (!isDataLoaded) { initBaseBean(); } this.lstUsers = FunctionUtils.getCustomerUsers(catUserService, selectedCustomer); } @RequestMapping() public String home(Model model) { model.addAttribute("menuName", "menu.importStockOrder"); model.addAttribute("controller", "/workspace/import_stock_order_ctr/"); model.addAttribute("lstStock", lstStock); model.addAttribute("lstPartner", lstPartner); model.addAttribute("lstUsers", lstUsers); // cells.clear(); if (!DataUtil.isListNullOrEmpty(lstStock)) { int currentStockId = Integer.parseInt(lstStock.get(0).getId()); List<CatStockCellDTO> cellInSelectedStock = mapStockIdCells.get(currentStockId); if (!DataUtil.isStringNullOrEmpty(cellInSelectedStock)) { for (CatStockCellDTO i : cellInSelectedStock) { cells.add(new ComboSourceDTO(Integer.parseInt(i.getId()), i.getCode(), i.getId(), i.getCode())); } } } model.addAttribute("cells", cells); // initMapUnitType(); return "stock_management/import_stock_order"; } private void initMapUnitType() { // if (lstAppParams == null) { lstAppParams = FunctionUtils.getAppParams(appParamsService); } mapUnitType = FunctionUtils.buildMapAppParams(FunctionUtils.getAppParamByType(Constants.APP_PARAMS.UNIT_TYPE, lstAppParams)); } //------------------------------------------------------------------------------------------------------------------ @ModelAttribute("data-reload") public void checkReloadData(HttpServletRequest request) { if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.IMPORT_GOODS_MODIFIED)) { initGoods(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.IMPORT_GOODS_MODIFIED); } if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.IMPORT_CELL_MODIFIED)) { initCells(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.IMPORT_CELL_MODIFIED); } if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.IMPORT_STOCK_MODIFIED)) { initStocks(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.IMPORT_STOCK_MODIFIED); } if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.PARTNER_MODIFIED)) { initPartner(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.PARTNER_MODIFIED); } } @RequestMapping(value = "/findDataByCondition", method = RequestMethod.GET) public @ResponseBody List<MjrOrderDTO> findOrder(@RequestParam("stockId") String stockId, @RequestParam("createdUser") String createdUser, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate, @RequestParam("status") String status) { List<Condition> lstCon = Lists.newArrayList(); lstCon.add(new Condition("custId", Constants.SQL_PRO_TYPE.LONG, Constants.SQL_OPERATOR.EQUAL, selectedCustomer.getId())); if (!DataUtil.isStringNullOrEmpty(stockId) && !stockId.equals(Constants.STATS_ALL)) { lstCon.add(new Condition("stockId", Constants.SQL_PRO_TYPE.LONG, Constants.SQL_OPERATOR.EQUAL, stockId)); } if (!DataUtil.isStringNullOrEmpty(startDate) && !DataUtil.isStringNullOrEmpty(endDate)) { lstCon.add(new Condition("createdDate", Constants.SQL_OPERATOR.BETWEEN, startDate + "|" + endDate)); } if (!DataUtil.isStringNullOrEmpty(createdUser) && !createdUser.equals(Constants.STATS_ALL)) { lstCon.add(new Condition("createdUser", Constants.SQL_OPERATOR.EQUAL, createdUser)); } lstCon.add(new Condition("type", Constants.SQL_PRO_TYPE.LONG, Constants.SQL_OPERATOR.EQUAL, "1")); if (!DataUtil.isStringNullOrEmpty(status) && !status.equals(Constants.STATS_ALL)) { lstCon.add(new Condition("status", Constants.SQL_PRO_TYPE.BYTE, Constants.SQL_OPERATOR.EQUAL, status)); } lstCon.add(new Condition("createdDate", Constants.SQL_OPERATOR.ORDER, "desc")); // TODO: status here lstOrder = mjrOrderService.findByCondition(lstCon); if (DataUtil.isListNullOrEmpty(lstOrder)) { return Lists.newArrayList(); } lstOrder.forEach(e -> { e.setStockValue(mapStockIdStock.get(e.getStockId()) != null ? mapStockIdStock.get(e.getStockId()).getName() : ""); String value = ""; if (e.getStatus().equalsIgnoreCase("1")) { value = "Chưa thực nhập"; } else if (e.getStatus().equalsIgnoreCase("2")) { value = "Đã thực nhập"; } e.setTypeValue(value); }); return lstOrder; } @RequestMapping(value = "/getOrderDetail", method = RequestMethod.GET) public @ResponseBody List<MjrOrderDetailDTO> getOrderDetail(@RequestParam("orderid") String orderid) { List<MjrOrderDetailDTO> lstMjrOrderDTOS = mjrOrderService.getListOrderDetail(orderid); lstMjrOrderDTOS.forEach(e -> { e.setGoodsName(mapGoodsIdGoods.get(e.getGoodsId()).getName()); }); return lstMjrOrderDTOS; } @RequestMapping(value = "/orderImport", method = RequestMethod.POST) @ResponseBody public ResponseObject orderImport(@RequestBody OrderExportDTO orderExportDTO) { initImportOrder(orderExportDTO.getMjrOrderDTO()); orderExportDTO.getLstMjrOrderDetailDTOS().forEach(e -> { CatGoodsDTO goodsItem = mapGoodsCodeGoods.get(e.getGoodsCode()); if (goodsItem != null) { e.setGoodsId(goodsItem.getId()); e.setIsSerial(goodsItem.getIsSerial()); e.setUnitName(mapUnitType.get(goodsItem.getUnitType())); } if (!DataUtil.isNullOrEmpty(e.getSerial())) { e.setIsSerial("1"); } else { e.setIsSerial("0"); } if(!DataUtil.isNullOrEmpty(e.getProduceDate()) && "dd/mm/yyyy".equalsIgnoreCase(e.getProduceDate())){ e.setProduceDate(""); } if(!DataUtil.isNullOrEmpty(e.getExpireDate()) && "dd/mm/yyyy".equalsIgnoreCase(e.getExpireDate())){ e.setExpireDate(""); } e.setGoodsId(mapGoodsCodeGoods.get(e.getGoodsCode()).getId()); e.setGoodsOrder((orderExportDTO.getLstMjrOrderDetailDTOS().indexOf(e) + 1) +""); }); return mjrOrderService.orderExport(orderExportDTO); } @RequestMapping(value = "/deleteOrder", method = RequestMethod.GET) @ResponseBody public ResponseObject deleteOrder(@RequestParam("orderid") String orderid) { MjrOrderDTO mjrOrderDTO = mjrOrderService.findById(Long.parseLong(orderid)); if (mjrOrderDTO.getStatus().equalsIgnoreCase("2")) { ResponseObject responseObject = new ResponseObject(); responseObject.setStatusName("FAIL"); responseObject.setKey("IMPORTED"); return responseObject; } return mjrOrderService.deleteOrder(orderid); } //================================================================================================================== @RequestMapping(value = "/orderImportFile", method = RequestMethod.GET) public void orderExportFile(@RequestParam("orderId") String orderId, HttpServletResponse response) { String prefixFileName = "Thong_tin_chitiet_yeucau_xuatkho"; String templatePath = profileConfig.getTemplateURL() +selectedCustomer.getCode()+File.separator+ File.separator + Constants.FILE_RESOURCE.EXPORT_ORDER_BILL; File file = new File(templatePath); log.info("url " + templatePath); if (!file.exists()){ log.info("Url is not exist " + templatePath); templatePath = profileConfig.getTemplateURL() + Constants.FILE_RESOURCE.EXPORT_ORDER_BILL; } String outPutFile = profileConfig.getTempURL() + prefixFileName + "_" + DateTimeUtils.getTimeStamp() + ".docx"; List<RealExportExcelDTO> realExportExcelDTOS = mjrOrderService.orderExportExcel(orderId); realExportExcelDTOS.forEach(e -> { CatGoodsDTO goodsItem = mapGoodsCodeGoods.get(e.getGoodsCode()); e.setGoodsName(goodsItem.getName()); if (e.getGoodsState().equalsIgnoreCase("1")) { e.setGoodsState("Bình thường"); } else { e.setGoodsState("Hỏng"); } }); MjrOrderDTO mjrOrderDTO = null; for (MjrOrderDTO item : lstOrder) { if (item.getId().equalsIgnoreCase(orderId)) { mjrOrderDTO = item; } } try { JRBeanCollectionDataSource itemsJRBean = new JRBeanCollectionDataSource(realExportExcelDTOS); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("itemList", itemsJRBean); parameters.put("orderCode", mjrOrderDTO.getCode()); parameters.put("partner", mjrOrderDTO.getPartnerName()); parameters.put("custName", mjrOrderDTO.getReceiveName()); parameters.put("stockName", mjrOrderDTO.getStockValue()); parameters.put("description", mjrOrderDTO.getDescription()); parameters.put("createdUser", currentUser.getCode()); JasperPrint jasperPrint = JasperFillManager.fillReport(templatePath, parameters, new JREmptyDataSource()); JRDocxExporter export = new JRDocxExporter(); export.setExporterInput(new SimpleExporterInput(jasperPrint)); export.setExporterOutput(new SimpleOutputStreamExporterOutput(new File(outPutFile))); SimpleDocxReportConfiguration config = new SimpleDocxReportConfiguration(); export.setConfiguration(config); export.exportReport(); FunctionUtils.loadFileToClient(response, outPutFile); log.info("Done"); } catch (Exception e) { e.printStackTrace(); } } public List<ComboSourceDTO> getCells() { return cells; } public void setCells(List<ComboSourceDTO> cells) { this.cells = cells; } private void initImportOrder(MjrOrderDTO mjrOrderDTO) { mjrOrderDTO.setCustId(selectedCustomer.getId()); mjrOrderDTO.setType(Constants.IMPORT_TYPE.IMPORT); mjrOrderDTO.setStatus("1"); mjrOrderDTO.setCreatedUser(currentUser.getCode()); //Nhap hang cua doi tac if (mjrOrderDTO.getPartnerName() != null && !mjrOrderDTO.getPartnerName().trim().equals("") && mjrOrderDTO.getPartnerName().contains("|")) { String[] splitPartner = mjrOrderDTO.getPartnerName().split("\\|"); if (splitPartner.length > 0) { String partnerCode = splitPartner[0]; CatPartnerDTO catPartnerDTO = mapPartnerCodePartner.get(partnerCode); if (catPartnerDTO != null) { mjrOrderDTO.setPartnerId(catPartnerDTO.getId()); String partnerName = ""; if (!DataUtil.isStringNullOrEmpty(catPartnerDTO.getName())) { partnerName = partnerName + catPartnerDTO.getName(); } if (!DataUtil.isStringNullOrEmpty(catPartnerDTO.getTelNumber())) { partnerName = partnerName + "|" + catPartnerDTO.getTelNumber(); } mjrOrderDTO.setPartnerName(partnerName); } } } } public OrderExportService getMjrOrderService() { return mjrOrderService; } public void setMjrOrderService(OrderExportService mjrOrderService) { this.mjrOrderService = mjrOrderService; } public Logger getLog() { return log; } public void setLog(Logger log) { this.log = log; } public CatUserService getCatUserService() { return catUserService; } public void setCatUserService(CatUserService catUserService) { this.catUserService = catUserService; } public BaseService getCatStockCellService() { return catStockCellService; } public void setCatStockCellService(BaseService catStockCellService) { this.catStockCellService = catStockCellService; } public List<CatUserDTO> getLstUsers() { return lstUsers; } public void setLstUsers(List<CatUserDTO> lstUsers) { this.lstUsers = lstUsers; } public List<MjrOrderDTO> getLstOrder() { return lstOrder; } public void setLstOrder(List<MjrOrderDTO> lstOrder) { this.lstOrder = lstOrder; } public LinkedHashMap<String, String> getMapUnitType() { return mapUnitType; } public void setMapUnitType(LinkedHashMap<String, String> mapUnitType) { this.mapUnitType = mapUnitType; } }
UTF-8
Java
15,756
java
ImportOrderStockController.java
Java
[]
null
[]
package com.wms.controller.stock_managerment; import com.google.common.collect.Lists; import com.wms.base.BaseController; import com.wms.constants.Constants; import com.wms.dto.*; import com.wms.services.interfaces.BaseService; import com.wms.services.interfaces.CatUserService; import com.wms.services.interfaces.OrderExportService; import com.wms.utils.DataUtil; import com.wms.utils.DateTimeUtils; import com.wms.utils.FunctionUtils; import java.io.File; import java.util.*; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.wms.utils.SessionUtils; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.export.SimpleDocxReportConfiguration; import net.sf.jasperreports.export.SimpleExporterInput; import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/workspace/import_stock_order_ctr") @Scope("session") public class ImportOrderStockController extends BaseController { @Autowired OrderExportService mjrOrderService; private Logger log = LoggerFactory.getLogger(ImportOrderStockController.class); @Autowired public CatUserService catUserService; @Autowired BaseService catStockCellService; private List<CatUserDTO> lstUsers; private List<MjrOrderDTO> lstOrder; List<ComboSourceDTO> cells = new ArrayList<>(); public LinkedHashMap<String, String> mapUnitType; //------------------------------------------------------------------------------------------------------------------ @PostConstruct public void init() { if (!isDataLoaded) { initBaseBean(); } this.lstUsers = FunctionUtils.getCustomerUsers(catUserService, selectedCustomer); } @RequestMapping() public String home(Model model) { model.addAttribute("menuName", "menu.importStockOrder"); model.addAttribute("controller", "/workspace/import_stock_order_ctr/"); model.addAttribute("lstStock", lstStock); model.addAttribute("lstPartner", lstPartner); model.addAttribute("lstUsers", lstUsers); // cells.clear(); if (!DataUtil.isListNullOrEmpty(lstStock)) { int currentStockId = Integer.parseInt(lstStock.get(0).getId()); List<CatStockCellDTO> cellInSelectedStock = mapStockIdCells.get(currentStockId); if (!DataUtil.isStringNullOrEmpty(cellInSelectedStock)) { for (CatStockCellDTO i : cellInSelectedStock) { cells.add(new ComboSourceDTO(Integer.parseInt(i.getId()), i.getCode(), i.getId(), i.getCode())); } } } model.addAttribute("cells", cells); // initMapUnitType(); return "stock_management/import_stock_order"; } private void initMapUnitType() { // if (lstAppParams == null) { lstAppParams = FunctionUtils.getAppParams(appParamsService); } mapUnitType = FunctionUtils.buildMapAppParams(FunctionUtils.getAppParamByType(Constants.APP_PARAMS.UNIT_TYPE, lstAppParams)); } //------------------------------------------------------------------------------------------------------------------ @ModelAttribute("data-reload") public void checkReloadData(HttpServletRequest request) { if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.IMPORT_GOODS_MODIFIED)) { initGoods(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.IMPORT_GOODS_MODIFIED); } if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.IMPORT_CELL_MODIFIED)) { initCells(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.IMPORT_CELL_MODIFIED); } if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.IMPORT_STOCK_MODIFIED)) { initStocks(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.IMPORT_STOCK_MODIFIED); } if (SessionUtils.isPropertiesModified(request, Constants.DATA_MODIFIED.PARTNER_MODIFIED)) { initPartner(); SessionUtils.setReloadedModified(request, Constants.DATA_MODIFIED.PARTNER_MODIFIED); } } @RequestMapping(value = "/findDataByCondition", method = RequestMethod.GET) public @ResponseBody List<MjrOrderDTO> findOrder(@RequestParam("stockId") String stockId, @RequestParam("createdUser") String createdUser, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate, @RequestParam("status") String status) { List<Condition> lstCon = Lists.newArrayList(); lstCon.add(new Condition("custId", Constants.SQL_PRO_TYPE.LONG, Constants.SQL_OPERATOR.EQUAL, selectedCustomer.getId())); if (!DataUtil.isStringNullOrEmpty(stockId) && !stockId.equals(Constants.STATS_ALL)) { lstCon.add(new Condition("stockId", Constants.SQL_PRO_TYPE.LONG, Constants.SQL_OPERATOR.EQUAL, stockId)); } if (!DataUtil.isStringNullOrEmpty(startDate) && !DataUtil.isStringNullOrEmpty(endDate)) { lstCon.add(new Condition("createdDate", Constants.SQL_OPERATOR.BETWEEN, startDate + "|" + endDate)); } if (!DataUtil.isStringNullOrEmpty(createdUser) && !createdUser.equals(Constants.STATS_ALL)) { lstCon.add(new Condition("createdUser", Constants.SQL_OPERATOR.EQUAL, createdUser)); } lstCon.add(new Condition("type", Constants.SQL_PRO_TYPE.LONG, Constants.SQL_OPERATOR.EQUAL, "1")); if (!DataUtil.isStringNullOrEmpty(status) && !status.equals(Constants.STATS_ALL)) { lstCon.add(new Condition("status", Constants.SQL_PRO_TYPE.BYTE, Constants.SQL_OPERATOR.EQUAL, status)); } lstCon.add(new Condition("createdDate", Constants.SQL_OPERATOR.ORDER, "desc")); // TODO: status here lstOrder = mjrOrderService.findByCondition(lstCon); if (DataUtil.isListNullOrEmpty(lstOrder)) { return Lists.newArrayList(); } lstOrder.forEach(e -> { e.setStockValue(mapStockIdStock.get(e.getStockId()) != null ? mapStockIdStock.get(e.getStockId()).getName() : ""); String value = ""; if (e.getStatus().equalsIgnoreCase("1")) { value = "Chưa thực nhập"; } else if (e.getStatus().equalsIgnoreCase("2")) { value = "Đã thực nhập"; } e.setTypeValue(value); }); return lstOrder; } @RequestMapping(value = "/getOrderDetail", method = RequestMethod.GET) public @ResponseBody List<MjrOrderDetailDTO> getOrderDetail(@RequestParam("orderid") String orderid) { List<MjrOrderDetailDTO> lstMjrOrderDTOS = mjrOrderService.getListOrderDetail(orderid); lstMjrOrderDTOS.forEach(e -> { e.setGoodsName(mapGoodsIdGoods.get(e.getGoodsId()).getName()); }); return lstMjrOrderDTOS; } @RequestMapping(value = "/orderImport", method = RequestMethod.POST) @ResponseBody public ResponseObject orderImport(@RequestBody OrderExportDTO orderExportDTO) { initImportOrder(orderExportDTO.getMjrOrderDTO()); orderExportDTO.getLstMjrOrderDetailDTOS().forEach(e -> { CatGoodsDTO goodsItem = mapGoodsCodeGoods.get(e.getGoodsCode()); if (goodsItem != null) { e.setGoodsId(goodsItem.getId()); e.setIsSerial(goodsItem.getIsSerial()); e.setUnitName(mapUnitType.get(goodsItem.getUnitType())); } if (!DataUtil.isNullOrEmpty(e.getSerial())) { e.setIsSerial("1"); } else { e.setIsSerial("0"); } if(!DataUtil.isNullOrEmpty(e.getProduceDate()) && "dd/mm/yyyy".equalsIgnoreCase(e.getProduceDate())){ e.setProduceDate(""); } if(!DataUtil.isNullOrEmpty(e.getExpireDate()) && "dd/mm/yyyy".equalsIgnoreCase(e.getExpireDate())){ e.setExpireDate(""); } e.setGoodsId(mapGoodsCodeGoods.get(e.getGoodsCode()).getId()); e.setGoodsOrder((orderExportDTO.getLstMjrOrderDetailDTOS().indexOf(e) + 1) +""); }); return mjrOrderService.orderExport(orderExportDTO); } @RequestMapping(value = "/deleteOrder", method = RequestMethod.GET) @ResponseBody public ResponseObject deleteOrder(@RequestParam("orderid") String orderid) { MjrOrderDTO mjrOrderDTO = mjrOrderService.findById(Long.parseLong(orderid)); if (mjrOrderDTO.getStatus().equalsIgnoreCase("2")) { ResponseObject responseObject = new ResponseObject(); responseObject.setStatusName("FAIL"); responseObject.setKey("IMPORTED"); return responseObject; } return mjrOrderService.deleteOrder(orderid); } //================================================================================================================== @RequestMapping(value = "/orderImportFile", method = RequestMethod.GET) public void orderExportFile(@RequestParam("orderId") String orderId, HttpServletResponse response) { String prefixFileName = "Thong_tin_chitiet_yeucau_xuatkho"; String templatePath = profileConfig.getTemplateURL() +selectedCustomer.getCode()+File.separator+ File.separator + Constants.FILE_RESOURCE.EXPORT_ORDER_BILL; File file = new File(templatePath); log.info("url " + templatePath); if (!file.exists()){ log.info("Url is not exist " + templatePath); templatePath = profileConfig.getTemplateURL() + Constants.FILE_RESOURCE.EXPORT_ORDER_BILL; } String outPutFile = profileConfig.getTempURL() + prefixFileName + "_" + DateTimeUtils.getTimeStamp() + ".docx"; List<RealExportExcelDTO> realExportExcelDTOS = mjrOrderService.orderExportExcel(orderId); realExportExcelDTOS.forEach(e -> { CatGoodsDTO goodsItem = mapGoodsCodeGoods.get(e.getGoodsCode()); e.setGoodsName(goodsItem.getName()); if (e.getGoodsState().equalsIgnoreCase("1")) { e.setGoodsState("Bình thường"); } else { e.setGoodsState("Hỏng"); } }); MjrOrderDTO mjrOrderDTO = null; for (MjrOrderDTO item : lstOrder) { if (item.getId().equalsIgnoreCase(orderId)) { mjrOrderDTO = item; } } try { JRBeanCollectionDataSource itemsJRBean = new JRBeanCollectionDataSource(realExportExcelDTOS); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("itemList", itemsJRBean); parameters.put("orderCode", mjrOrderDTO.getCode()); parameters.put("partner", mjrOrderDTO.getPartnerName()); parameters.put("custName", mjrOrderDTO.getReceiveName()); parameters.put("stockName", mjrOrderDTO.getStockValue()); parameters.put("description", mjrOrderDTO.getDescription()); parameters.put("createdUser", currentUser.getCode()); JasperPrint jasperPrint = JasperFillManager.fillReport(templatePath, parameters, new JREmptyDataSource()); JRDocxExporter export = new JRDocxExporter(); export.setExporterInput(new SimpleExporterInput(jasperPrint)); export.setExporterOutput(new SimpleOutputStreamExporterOutput(new File(outPutFile))); SimpleDocxReportConfiguration config = new SimpleDocxReportConfiguration(); export.setConfiguration(config); export.exportReport(); FunctionUtils.loadFileToClient(response, outPutFile); log.info("Done"); } catch (Exception e) { e.printStackTrace(); } } public List<ComboSourceDTO> getCells() { return cells; } public void setCells(List<ComboSourceDTO> cells) { this.cells = cells; } private void initImportOrder(MjrOrderDTO mjrOrderDTO) { mjrOrderDTO.setCustId(selectedCustomer.getId()); mjrOrderDTO.setType(Constants.IMPORT_TYPE.IMPORT); mjrOrderDTO.setStatus("1"); mjrOrderDTO.setCreatedUser(currentUser.getCode()); //Nhap hang cua doi tac if (mjrOrderDTO.getPartnerName() != null && !mjrOrderDTO.getPartnerName().trim().equals("") && mjrOrderDTO.getPartnerName().contains("|")) { String[] splitPartner = mjrOrderDTO.getPartnerName().split("\\|"); if (splitPartner.length > 0) { String partnerCode = splitPartner[0]; CatPartnerDTO catPartnerDTO = mapPartnerCodePartner.get(partnerCode); if (catPartnerDTO != null) { mjrOrderDTO.setPartnerId(catPartnerDTO.getId()); String partnerName = ""; if (!DataUtil.isStringNullOrEmpty(catPartnerDTO.getName())) { partnerName = partnerName + catPartnerDTO.getName(); } if (!DataUtil.isStringNullOrEmpty(catPartnerDTO.getTelNumber())) { partnerName = partnerName + "|" + catPartnerDTO.getTelNumber(); } mjrOrderDTO.setPartnerName(partnerName); } } } } public OrderExportService getMjrOrderService() { return mjrOrderService; } public void setMjrOrderService(OrderExportService mjrOrderService) { this.mjrOrderService = mjrOrderService; } public Logger getLog() { return log; } public void setLog(Logger log) { this.log = log; } public CatUserService getCatUserService() { return catUserService; } public void setCatUserService(CatUserService catUserService) { this.catUserService = catUserService; } public BaseService getCatStockCellService() { return catStockCellService; } public void setCatStockCellService(BaseService catStockCellService) { this.catStockCellService = catStockCellService; } public List<CatUserDTO> getLstUsers() { return lstUsers; } public void setLstUsers(List<CatUserDTO> lstUsers) { this.lstUsers = lstUsers; } public List<MjrOrderDTO> getLstOrder() { return lstOrder; } public void setLstOrder(List<MjrOrderDTO> lstOrder) { this.lstOrder = lstOrder; } public LinkedHashMap<String, String> getMapUnitType() { return mapUnitType; } public void setMapUnitType(LinkedHashMap<String, String> mapUnitType) { this.mapUnitType = mapUnitType; } }
15,756
0.650613
0.649724
361
42.598339
34.565956
164
false
false
0
0
0
0
117
0.007434
0.66205
false
false
5
30bf6cab4146402494bb01e9260768198975c33c
6,992,206,780,186
10be8e5fc0124b8ff879caa5be1fe56208cced0e
/Section 3 Primitive Types/Ex24bFlour/src/Flour.java
3f0ef141103a44fab688fd3e33cefe168c130d78
[]
no_license
MoniqueChetty/JavaMasterClass
https://github.com/MoniqueChetty/JavaMasterClass
70938f419d46429e4be08f2da9f38832fd8d44de
03b6049f6319fd60c4ff3b857e920608fb695606
refs/heads/master
2022-11-13T06:43:06.635000
2020-06-25T18:54:43
2020-06-25T18:54:43
273,027,934
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. */ //import FlourPacker.canPack; /** * * @author Monique Chetty */ public class Flour { /** * @param args the command line arguments */ public static void main(String[] args) { canPack(1, 0, 4); //should return false since bigCount is 1 (big bag of 5 kilos) and goal is 4 kilos. System.out.println("canPack (1, 0, 4); //should return false = " + canPack(1, 0, 4)); canPack(1, 0, 5); //should return true since bigCount is 1 (big bag of 5 kilos) and goal is 5 kilos. System.out.println("canPack (1, 0, 5); //should return true = " + canPack(1, 0, 5)); canPack(0, 5, 4); //should return true since smallCount is 5 (small bags of 1 kilo) and goal is 4 kilos, and we have 1 bag left which is ok as mentioned above. System.out.println("canPack (0, 5, 4); //should return true = " + canPack(0, 5, 4)); canPack(2, 2, 11); //should return true since bigCount is 2 (big bags 5 kilos each) and smallCount is 2 (small bags of 1 kilo), makes in total 12 kilos and goal is 11 kilos. System.out.println("canPack (2, 2, 11); //should return true = " + canPack(2, 2, 11)); canPack(-3, 2, 12); //should return false since bigCount is negative. System.out.println("canPack (-3, 2, 12); //should return false = " + canPack(-3, 2, 12)); System.out.println("canPack (0, 5, 5); //should return true = " + canPack(0, 5, 5)); System.out.println("canPack (2, 1, 5); //should return true = " + canPack(2, 1, 5)); System.out.println("canPack (2, 2, 12); //should return true = " + canPack(2, 2, 12)); } public static boolean canPack(int bigCount, int smallCount, int goal) { int bigCountK = bigCount * 5; if ((bigCount < 0) || (smallCount < 0) || (goal < 0)) //negitive values { return false; } if (smallCount >= goal) { return true; } if ((bigCountK + smallCount) >= goal) { if ((smallCount == 0) && (goal % 5 == 0) && (bigCountK >= goal)) { return true; }else if (smallCount >= goal % 5 ){ return true; } } return false; } }
UTF-8
Java
2,396
java
Flour.java
Java
[ { "context": "*/\n//import FlourPacker.canPack;\n/**\n *\n * @author Monique Chetty\n */\npublic class Flour {\n\n /**\n * @param a", "end": 247, "score": 0.9998651742935181, "start": 233, "tag": "NAME", "value": "Monique Chetty" } ]
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. */ //import FlourPacker.canPack; /** * * @author <NAME> */ public class Flour { /** * @param args the command line arguments */ public static void main(String[] args) { canPack(1, 0, 4); //should return false since bigCount is 1 (big bag of 5 kilos) and goal is 4 kilos. System.out.println("canPack (1, 0, 4); //should return false = " + canPack(1, 0, 4)); canPack(1, 0, 5); //should return true since bigCount is 1 (big bag of 5 kilos) and goal is 5 kilos. System.out.println("canPack (1, 0, 5); //should return true = " + canPack(1, 0, 5)); canPack(0, 5, 4); //should return true since smallCount is 5 (small bags of 1 kilo) and goal is 4 kilos, and we have 1 bag left which is ok as mentioned above. System.out.println("canPack (0, 5, 4); //should return true = " + canPack(0, 5, 4)); canPack(2, 2, 11); //should return true since bigCount is 2 (big bags 5 kilos each) and smallCount is 2 (small bags of 1 kilo), makes in total 12 kilos and goal is 11 kilos. System.out.println("canPack (2, 2, 11); //should return true = " + canPack(2, 2, 11)); canPack(-3, 2, 12); //should return false since bigCount is negative. System.out.println("canPack (-3, 2, 12); //should return false = " + canPack(-3, 2, 12)); System.out.println("canPack (0, 5, 5); //should return true = " + canPack(0, 5, 5)); System.out.println("canPack (2, 1, 5); //should return true = " + canPack(2, 1, 5)); System.out.println("canPack (2, 2, 12); //should return true = " + canPack(2, 2, 12)); } public static boolean canPack(int bigCount, int smallCount, int goal) { int bigCountK = bigCount * 5; if ((bigCount < 0) || (smallCount < 0) || (goal < 0)) //negitive values { return false; } if (smallCount >= goal) { return true; } if ((bigCountK + smallCount) >= goal) { if ((smallCount == 0) && (goal % 5 == 0) && (bigCountK >= goal)) { return true; }else if (smallCount >= goal % 5 ){ return true; } } return false; } }
2,388
0.578047
0.537563
52
45.076923
43.858971
182
false
false
0
0
0
0
0
0
1.557692
false
false
5
77d5cec3f5eb06d6107b76be4d4560b88ae20c2e
12,120,397,740,163
7d8ba1b6954cd13620f675e583921827ab332c5b
/APLICATIE/app/src/main/java/com/example/infotrip/activitati/LogInActivity.java
909d264567b39182c483a9915463a0be1c35686e
[]
no_license
georgiananila/Licenta
https://github.com/georgiananila/Licenta
77434e4fe446f8233a3a664ed6a38fcfe12706fe
b80409c4eac0d3ec340d597ca04e270961b3aada
refs/heads/master
2022-11-16T04:51:23.042000
2020-07-14T17:41:12
2020-07-14T17:41:12
247,484,125
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.infotrip.activitati; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.InputType; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.example.infotrip.R; import com.example.infotrip.database.InfoTripRepository; import com.example.infotrip.utility.Email; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class LogInActivity extends AppCompatActivity { public ImageView imagineLogoLogIn; Button login; EditText mEmail,mpass; FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); imagineLogoLogIn=(ImageView)findViewById(R.id.imageViewLogInActivityLogo); imagineLogoLogIn.setImageResource(R.drawable.imaginelogologin); login=findViewById(R.id.buttonLogInActivityLogIn); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginUser(); // openPrincipalActivity(); } }); mEmail=findViewById(R.id.editTextLogInActivityEmail); mpass=findViewById(R.id.editTextLogInActivityPass); auth=FirebaseAuth.getInstance(); } private void openPrincipalActivity() { Intent intent=new Intent(this, PrincipalMeniu.class); startActivity(intent); } public void onClickRegister(View view) { Intent intentLegaturaLogInSingUp=new Intent(this, SingUpActivity.class); startActivity(intentLegaturaLogInSingUp); } private void loginUser() { final String email=mEmail.getText().toString().trim(); String pass=mpass.getText().toString().trim(); if(TextUtils.isEmpty(email)){ mEmail.setError("Email is required"); return; } if(TextUtils.isEmpty(pass)){ mpass.setError("Password is required"); return; } if(pass.length()<6){ mpass.setError("Password must be>=6 characters"); return; } //authenticate the user auth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Email.email=email; Email.idClient = InfoTripRepository.getInstance(getApplicationContext()).getClient(email).getIdClient(); Toast.makeText(LogInActivity.this,"Logged is Successfully",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),PrincipalMeniu.class)); }else{ Toast.makeText(LogInActivity.this,"Could not register, please try again",Toast.LENGTH_SHORT).show(); } } }); } public void onClickForgot(View view) { showRecoverPasswordDialog(); } private void showRecoverPasswordDialog() { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("Recover Password"); LinearLayout linearLayout=new LinearLayout(this); final EditText emailEt=new EditText(this); emailEt.setHint("Email"); emailEt.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); emailEt.setMinEms(10); linearLayout.addView(emailEt); linearLayout.setPadding(10,10,10,10); builder.setView(linearLayout); builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String email=emailEt.getText().toString().trim(); beginRecovery(email); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void beginRecovery(String email) { auth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(LogInActivity.this,"Email sent",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(LogInActivity.this,"Failed...",Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(LogInActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show(); } }); } }
UTF-8
Java
5,537
java
LogInActivity.java
Java
[]
null
[]
package com.example.infotrip.activitati; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.InputType; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.example.infotrip.R; import com.example.infotrip.database.InfoTripRepository; import com.example.infotrip.utility.Email; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class LogInActivity extends AppCompatActivity { public ImageView imagineLogoLogIn; Button login; EditText mEmail,mpass; FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); imagineLogoLogIn=(ImageView)findViewById(R.id.imageViewLogInActivityLogo); imagineLogoLogIn.setImageResource(R.drawable.imaginelogologin); login=findViewById(R.id.buttonLogInActivityLogIn); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginUser(); // openPrincipalActivity(); } }); mEmail=findViewById(R.id.editTextLogInActivityEmail); mpass=findViewById(R.id.editTextLogInActivityPass); auth=FirebaseAuth.getInstance(); } private void openPrincipalActivity() { Intent intent=new Intent(this, PrincipalMeniu.class); startActivity(intent); } public void onClickRegister(View view) { Intent intentLegaturaLogInSingUp=new Intent(this, SingUpActivity.class); startActivity(intentLegaturaLogInSingUp); } private void loginUser() { final String email=mEmail.getText().toString().trim(); String pass=mpass.getText().toString().trim(); if(TextUtils.isEmpty(email)){ mEmail.setError("Email is required"); return; } if(TextUtils.isEmpty(pass)){ mpass.setError("Password is required"); return; } if(pass.length()<6){ mpass.setError("Password must be>=6 characters"); return; } //authenticate the user auth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Email.email=email; Email.idClient = InfoTripRepository.getInstance(getApplicationContext()).getClient(email).getIdClient(); Toast.makeText(LogInActivity.this,"Logged is Successfully",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),PrincipalMeniu.class)); }else{ Toast.makeText(LogInActivity.this,"Could not register, please try again",Toast.LENGTH_SHORT).show(); } } }); } public void onClickForgot(View view) { showRecoverPasswordDialog(); } private void showRecoverPasswordDialog() { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("Recover Password"); LinearLayout linearLayout=new LinearLayout(this); final EditText emailEt=new EditText(this); emailEt.setHint("Email"); emailEt.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); emailEt.setMinEms(10); linearLayout.addView(emailEt); linearLayout.setPadding(10,10,10,10); builder.setView(linearLayout); builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String email=emailEt.getText().toString().trim(); beginRecovery(email); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void beginRecovery(String email) { auth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(LogInActivity.this,"Email sent",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(LogInActivity.this,"Failed...",Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(LogInActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show(); } }); } }
5,537
0.650352
0.648185
167
32.155689
28.235107
124
false
false
0
0
0
0
0
0
0.60479
false
false
5
3518716c446071a57979c177a0eeb592ff79cd7f
34,763,465,311,818
6a6a2d3250239b2c187964c1611f62fc7e306cb9
/rxfilechooser/src/main/java/com/armdroid/rxfilechooser/request_helper/CameraRequestHelper.java
0c001aa29d414940a54ee462f802f1ac8bea8005
[ "Apache-2.0" ]
permissive
MAmmad-eAMin/MyExcel
https://github.com/MAmmad-eAMin/MyExcel
4c0b262e374f2358f2fc778f05289cacb4e301ae
417e53ea0b9db13b21fd4044f688a37be407b047
refs/heads/master
2020-05-19T01:47:07.665000
2019-05-03T17:02:52
2019-05-03T17:02:52
184,765,898
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.armdroid.rxfilechooser.request_helper; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.provider.MediaStore; import com.armdroid.rxfilechooser.content.ImageContent; import com.yalantis.ucrop.UCrop; import io.reactivex.Observable; public class CameraRequestHelper extends RequestHelper<CameraRequestHelper> { public CameraRequestHelper(FileChooser fileChooser) { super(fileChooser); } /** * Include also {@link android.graphics.Bitmap} when returning file instance * * @return the same instance of {@link CameraRequestHelper} */ public CameraRequestHelper includeBitmap() { mReturnBitmap = true; return this; } /** * Crop image after taking photo. * * @return the same instance of {@link CameraRequestHelper} */ public CameraRequestHelper crop() { mDoCrop = true; return this; } /** * Crop image after taking photo with custom options such as UI of the crop page, crop aspect * ratio, max or min sie of cropped image etc. * * @param cropOptions The options that are going to be used for crop session * @return the same instance of {@link CameraRequestHelper} */ public CameraRequestHelper crop(UCrop.Options cropOptions) { mDoCrop = true; mCropOptions = cropOptions; return this; } /** * Take a single photo from camera * * @return an {@link Observable} containing the file instance */ public Observable<ImageContent> single() { return mFileChooser.startAction(this) .flatMap(this::trySendToGallery) .flatMap(fileContent -> Observable.just(((ImageContent) fileContent))); } @Override protected Intent getIntent() { Activity activity = mFileChooser.getActivity(); setupMediaFile(MediaStore.ACTION_IMAGE_CAPTURE); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri); String packageName = intent.resolveActivity(activity.getPackageManager()).getPackageName(); activity.grantUriPermission(packageName, mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); return intent; } @Override protected String[] getPermissions() { if (mUseInternalStorage) { return new String[]{Manifest.permission.CAMERA}; } return new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}; } @Override protected String getType() { return "image"; } }
UTF-8
Java
2,791
java
CameraRequestHelper.java
Java
[]
null
[]
package com.armdroid.rxfilechooser.request_helper; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.provider.MediaStore; import com.armdroid.rxfilechooser.content.ImageContent; import com.yalantis.ucrop.UCrop; import io.reactivex.Observable; public class CameraRequestHelper extends RequestHelper<CameraRequestHelper> { public CameraRequestHelper(FileChooser fileChooser) { super(fileChooser); } /** * Include also {@link android.graphics.Bitmap} when returning file instance * * @return the same instance of {@link CameraRequestHelper} */ public CameraRequestHelper includeBitmap() { mReturnBitmap = true; return this; } /** * Crop image after taking photo. * * @return the same instance of {@link CameraRequestHelper} */ public CameraRequestHelper crop() { mDoCrop = true; return this; } /** * Crop image after taking photo with custom options such as UI of the crop page, crop aspect * ratio, max or min sie of cropped image etc. * * @param cropOptions The options that are going to be used for crop session * @return the same instance of {@link CameraRequestHelper} */ public CameraRequestHelper crop(UCrop.Options cropOptions) { mDoCrop = true; mCropOptions = cropOptions; return this; } /** * Take a single photo from camera * * @return an {@link Observable} containing the file instance */ public Observable<ImageContent> single() { return mFileChooser.startAction(this) .flatMap(this::trySendToGallery) .flatMap(fileContent -> Observable.just(((ImageContent) fileContent))); } @Override protected Intent getIntent() { Activity activity = mFileChooser.getActivity(); setupMediaFile(MediaStore.ACTION_IMAGE_CAPTURE); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri); String packageName = intent.resolveActivity(activity.getPackageManager()).getPackageName(); activity.grantUriPermission(packageName, mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); return intent; } @Override protected String[] getPermissions() { if (mUseInternalStorage) { return new String[]{Manifest.permission.CAMERA}; } return new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}; } @Override protected String getType() { return "image"; } }
2,791
0.663561
0.663561
90
30.01111
28.306063
135
false
false
0
0
0
0
0
0
0.388889
false
false
5
9bf56d8e380b696a29ab7ba1e9e261f00afa3d59
2,430,951,526,347
46b534903e5996c16eeb428e1316bec21fc64003
/src/main/java/dalicia/rsvp/InvitationDao.java
7d0dc40692e0c52bed8d2dc3e0c79718bb587d1d
[ "Apache-2.0" ]
permissive
dalicia/rsvp
https://github.com/dalicia/rsvp
3a56fee389eb875c4063490ec9dc4f6e2fcf533c
5e6cecd1e82bb3bb1a8f59e1975963dd3f92a0dd
refs/heads/master
2021-01-22T11:51:30.993000
2015-02-28T20:54:01
2015-02-28T21:05:54
25,849,605
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dalicia.rsvp; import java.util.List; import com.google.common.base.Optional; public interface InvitationDao { List<Invitation> list(); Optional<Invitation> load(String code); void saveResponse(String code, int numAttending); }
UTF-8
Java
252
java
InvitationDao.java
Java
[]
null
[]
package dalicia.rsvp; import java.util.List; import com.google.common.base.Optional; public interface InvitationDao { List<Invitation> list(); Optional<Invitation> load(String code); void saveResponse(String code, int numAttending); }
252
0.746032
0.746032
13
18.384615
18.644606
53
false
false
0
0
0
0
0
0
0.538462
false
false
5
047d4071f4543dd8da71e77f74e9722f4ad5bdab
30,382,598,683,668
acb3f1ae5d455c78253c74a1ca247dc4cc8a8d8e
/message-service/src/main/java/com/enjoyf/platform/messageservice/service/PushMessageService.java
eee340ecbfff94b272d953d6b589f7e7b8d5cf64
[]
no_license
liu67224657/micro-service
https://github.com/liu67224657/micro-service
1e4656014786e813ec7a3fc13d48cb09d7d165b2
599fee529158d534526a3fed417aeb041ee55074
refs/heads/master
2021-09-04T11:05:22.500000
2018-01-18T03:40:16
2018-01-18T03:40:16
109,512,670
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.enjoyf.platform.messageservice.service; import com.enjoyf.platform.messageservice.domain.PushApp; import com.enjoyf.platform.messageservice.service.dto.PushMessageDTO; import com.enjoyf.platform.messageservice.service.exception.MessageException; /** * Service Interface for managing UserAccount. */ public interface PushMessageService { void pushMessage(PushApp pushApp, PushMessageDTO pushMessageDTO) throws MessageException; }
UTF-8
Java
451
java
PushMessageService.java
Java
[]
null
[]
package com.enjoyf.platform.messageservice.service; import com.enjoyf.platform.messageservice.domain.PushApp; import com.enjoyf.platform.messageservice.service.dto.PushMessageDTO; import com.enjoyf.platform.messageservice.service.exception.MessageException; /** * Service Interface for managing UserAccount. */ public interface PushMessageService { void pushMessage(PushApp pushApp, PushMessageDTO pushMessageDTO) throws MessageException; }
451
0.831486
0.831486
13
33.615383
32.82011
93
false
false
0
0
0
0
0
0
0.461538
false
false
5
4aa31863538029b09acf1dd0a9ed149cc9d679d9
867,583,421,967
9dff58850fb8e42eca1e6458d2f9df0e30656945
/CryptOfTheJavaDancer/src/cryptofthejavadancer/Model/Carte/Graphes/Graph.java
3808e9c7ca3f26c06f0f396235f906f5f5d57ef2
[]
no_license
julien-pintodafonseca/Crypt_of_the_JavaDancer
https://github.com/julien-pintodafonseca/Crypt_of_the_JavaDancer
85a7ebf00f87a5aebc599d17dffe68d0d9aa4e39
98e3af5d375ed797ec6f0fcf86a8d1730ff0c754
refs/heads/master
2020-03-23T11:12:36.727000
2019-02-05T18:29:22
2019-02-05T18:29:22
141,490,829
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 cryptofthejavadancer.Model.Carte.Graphes; import cryptofthejavadancer.Model.Carte.Cases.Case; import java.util.Collection; import java.util.HashMap; /** * * @author jp032952 */ public class Graph { private HashMap<Case, Vertex> vertices; private HashMap<VertexCouple, Integer> labels; public Graph() { vertices = new HashMap(); labels = new HashMap(); } public void addVertex(Case name) { vertices.put(name, new Vertex(this, name)); } public void addEdge(Case name1, Case name2) { vertices.get(name1).addNeighbour(vertices.get(name2)); } public Vertex getVertex(Case name) { return vertices.get(name); } public Integer getLabel(Case name1, Case name2) { return labels.get(new VertexCouple(vertices.get(name1), vertices.get(name2))); } public Integer getLabel(Vertex v1, Vertex v2) { return labels.get(new VertexCouple(v1, v2)); } public HashMap<VertexCouple, Integer> getLabels() { return labels; } public void setLabel(Case name1, Case name2, int label) { labels.put(new VertexCouple(vertices.get(name1), vertices.get(name2)), label); } public void setLabel(Vertex v1, Vertex v2, int label) { labels.put(new VertexCouple(v1, v2), label); } public Collection<Vertex> getVertexCollection() { return vertices.values(); } public int nbVertices() { return vertices.size(); } public void editVertex(Case oldCase, Case newCase) { Vertex oldVertex = getVertex(oldCase); vertices.put(newCase,oldVertex); vertices.remove(oldCase); oldVertex.setCase(newCase); for (Vertex v : getVertexCollection()) { if (getLabel(v,oldVertex) != null) { setLabel(v, oldVertex, 1); } } } }
UTF-8
Java
2,114
java
Graph.java
Java
[ { "context": "tion;\nimport java.util.HashMap;\n\n/**\n *\n * @author jp032952\n */\npublic class Graph {\n private HashMap<Case", "end": 370, "score": 0.9993985891342163, "start": 362, "tag": "USERNAME", "value": "jp032952" } ]
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 cryptofthejavadancer.Model.Carte.Graphes; import cryptofthejavadancer.Model.Carte.Cases.Case; import java.util.Collection; import java.util.HashMap; /** * * @author jp032952 */ public class Graph { private HashMap<Case, Vertex> vertices; private HashMap<VertexCouple, Integer> labels; public Graph() { vertices = new HashMap(); labels = new HashMap(); } public void addVertex(Case name) { vertices.put(name, new Vertex(this, name)); } public void addEdge(Case name1, Case name2) { vertices.get(name1).addNeighbour(vertices.get(name2)); } public Vertex getVertex(Case name) { return vertices.get(name); } public Integer getLabel(Case name1, Case name2) { return labels.get(new VertexCouple(vertices.get(name1), vertices.get(name2))); } public Integer getLabel(Vertex v1, Vertex v2) { return labels.get(new VertexCouple(v1, v2)); } public HashMap<VertexCouple, Integer> getLabels() { return labels; } public void setLabel(Case name1, Case name2, int label) { labels.put(new VertexCouple(vertices.get(name1), vertices.get(name2)), label); } public void setLabel(Vertex v1, Vertex v2, int label) { labels.put(new VertexCouple(v1, v2), label); } public Collection<Vertex> getVertexCollection() { return vertices.values(); } public int nbVertices() { return vertices.size(); } public void editVertex(Case oldCase, Case newCase) { Vertex oldVertex = getVertex(oldCase); vertices.put(newCase,oldVertex); vertices.remove(oldCase); oldVertex.setCase(newCase); for (Vertex v : getVertexCollection()) { if (getLabel(v,oldVertex) != null) { setLabel(v, oldVertex, 1); } } } }
2,114
0.626301
0.613529
77
26.454546
23.500509
86
false
false
0
0
0
0
0
0
0.636364
false
false
5
5d6ea047529cb356ffeeefccda2b1a47cdf3a3ca
27,530,740,401,422
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/java/java-tests/testData/codeInsight/completion/smartType/EnumAsDefaultAnnotationParam.java
14364f5bf55a1503afbccaf90534decfd3aac784
[ "Apache-2.0" ]
permissive
JetBrains/intellij-community
https://github.com/JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560000
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
false
2023-09-12T07:41:58
2011-09-30T13:33:05
2023-09-12T03:37:30
2023-09-12T06:46:46
4,523,919
15,754
4,972
237
null
false
false
enum MyEnum { FOO, BAR } @interface Anno { MyEnum value(); } @Anno(MyEnum.F<caret>) class Foo { }
UTF-8
Java
104
java
EnumAsDefaultAnnotationParam.java
Java
[]
null
[]
enum MyEnum { FOO, BAR } @interface Anno { MyEnum value(); } @Anno(MyEnum.F<caret>) class Foo { }
104
0.615385
0.615385
12
7.75
7.822244
22
false
false
0
0
0
0
0
0
0.166667
false
false
5
e75f5b496b96e7f6452c40e9a11ff6ec58fef20d
18,485,539,278,990
6731664c0fccbabaf96d6ea34ece029b56db0224
/server/src/main/java/com/u8/server/sdk/u8sdk/U8DebugSDK.java
874babfd3d182271d12d857eb45163740e5b890c
[]
no_license
kerwinzxc/union-server
https://github.com/kerwinzxc/union-server
5aca689d67ef98babd9ec015b87f4341116c3c20
d025956b70b15eac9fbd403f3e57f8ead358fe9f
refs/heads/master
2023-02-27T06:08:20.348000
2021-01-25T10:41:56
2021-01-25T10:41:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.u8.server.sdk.u8sdk; import com.u8.server.data.UChannel; import com.u8.server.data.UOrder; import com.u8.server.data.UUser; import com.u8.server.log.Log; import com.u8.server.sdk.ISDKOrderListener; import com.u8.server.sdk.ISDKScript; import com.u8.server.sdk.ISDKVerifyListener; import com.u8.server.sdk.SDKVerifyResult; import net.sf.json.JSONObject; /** * U8平台Debug账号,默认渠道号88888 * Created by ant on 2017/7/8. */ public class U8DebugSDK implements ISDKScript{ @Override public void verify(UChannel channel, String extension, ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); String userId = json.optString("userId"); String username = json.optString("username"); //U8默认测试模式,无需认证 callback.onSuccess(new SDKVerifyResult(true, userId, username, "")); }catch (Exception e){ callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); Log.e(e.getMessage()); } } @Override public void onGetOrderID(UUser user, UOrder order, ISDKOrderListener callback) { if(callback != null){ callback.onSuccess(""); } } }
UTF-8
Java
1,318
java
U8DebugSDK.java
Java
[ { "context": "ject;\n\n/**\n * U8平台Debug账号,默认渠道号88888\n * Created by ant on 2017/7/8.\n */\npublic class U8DebugSDK implemen", "end": 414, "score": 0.9949736595153809, "start": 411, "tag": "USERNAME", "value": "ant" }, { "context": "\");\n String username = json.optString(...
null
[]
package com.u8.server.sdk.u8sdk; import com.u8.server.data.UChannel; import com.u8.server.data.UOrder; import com.u8.server.data.UUser; import com.u8.server.log.Log; import com.u8.server.sdk.ISDKOrderListener; import com.u8.server.sdk.ISDKScript; import com.u8.server.sdk.ISDKVerifyListener; import com.u8.server.sdk.SDKVerifyResult; import net.sf.json.JSONObject; /** * U8平台Debug账号,默认渠道号88888 * Created by ant on 2017/7/8. */ public class U8DebugSDK implements ISDKScript{ @Override public void verify(UChannel channel, String extension, ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); String userId = json.optString("userId"); String username = json.optString("username"); //U8默认测试模式,无需认证 callback.onSuccess(new SDKVerifyResult(true, userId, username, "")); }catch (Exception e){ callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); Log.e(e.getMessage()); } } @Override public void onGetOrderID(UUser user, UOrder order, ISDKOrderListener callback) { if(callback != null){ callback.onSuccess(""); } } }
1,318
0.67163
0.652821
42
29.380953
27.938667
125
false
false
0
0
0
0
0
0
0.571429
false
false
5
6780c67adc886b7104f169941a8c9d94cb808ffa
36,481,452,225,235
561a341e66801221c36cd25a67ccb61d4bfa40d3
/regexdemo/src/regexdemo/RegexTest.java
4a9a48eb91e7d16190ca5460c8af1b3c8c436e7c
[]
no_license
bystc/SomeExamplesOfJava2
https://github.com/bystc/SomeExamplesOfJava2
545f98f2f3b5c73431b63166a58d71ba762f4fd6
36ca77fc89d3b49bcc6d446bccb7a1b88fa5e67d
refs/heads/master
2021-01-23T07:55:11.055000
2017-02-12T04:44:29
2017-02-12T04:44:29
80,520,210
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package regexdemo; import java.util.TreeSet; /* * 1.如果只想知道该字符是否对是错,使用匹配 * 2.想要将已有的字符串变成另一个字符串,替换 * 3.想要按照自定的方式将字符串变成多个字符串,切割。获取规则以外的子串 * 4.想要拿到符合需求的字符串字串,获取。获取符合规则的子串 */ public class RegexTest { public static void main(String[] args) { String str="我我...我我哇哦...想学...."; str=str.replaceAll("\\.+",""); System.out.println(str); str=str.replaceAll("(.)\\1", "$1"); System.out.println(str); String ip="192.68.1.254 102.15.01.445 10.110.10.10 2.2.2.2"; ip=ip.replaceAll("(\\d+)","00$1"); System.out.println(ip); ip=ip.replaceAll("0*(\\d{3})", "$1"); System.out.println(ip); String[] arr=ip.split(" "); TreeSet<String> ts=new TreeSet<String>(); for(String s:arr) { ts.add(s); } for(String s:ts) { System.out.println(s.replaceAll("0*(\\d+)", "$1")); } String mail="abc12@sina.com"; String reg="[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";//较为精确的匹配 //reg="\\w+@\\w+(\\.\\w+)"; //mail.indexOf("@")!=-1; System.out.println(mail.matches(reg)); } }
UTF-8
Java
1,290
java
RegexTest.java
Java
[ { "context": ".out.println(str);\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\tString ip=\"192.68.1.254 102.15.01.445 10.110.10.10 2.2.2.2\";\n\t\t\n\t\tip=ip.r", "end": 460, "score": 0.9997243285179138, "start": 448, "tag": "IP_ADDRESS", "value": "192.68.1.254" }, { "context": "str);\n\t...
null
[]
package regexdemo; import java.util.TreeSet; /* * 1.如果只想知道该字符是否对是错,使用匹配 * 2.想要将已有的字符串变成另一个字符串,替换 * 3.想要按照自定的方式将字符串变成多个字符串,切割。获取规则以外的子串 * 4.想要拿到符合需求的字符串字串,获取。获取符合规则的子串 */ public class RegexTest { public static void main(String[] args) { String str="我我...我我哇哦...想学...."; str=str.replaceAll("\\.+",""); System.out.println(str); str=str.replaceAll("(.)\\1", "$1"); System.out.println(str); String ip="172.16.58.3 102.15.01.445 10.110.10.10 2.2.2.2"; ip=ip.replaceAll("(\\d+)","00$1"); System.out.println(ip); ip=ip.replaceAll("0*(\\d{3})", "$1"); System.out.println(ip); String[] arr=ip.split(" "); TreeSet<String> ts=new TreeSet<String>(); for(String s:arr) { ts.add(s); } for(String s:ts) { System.out.println(s.replaceAll("0*(\\d+)", "$1")); } String mail="<EMAIL>"; String reg="[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";//较为精确的匹配 //reg="\\w+@\\w+(\\.\\w+)"; //mail.indexOf("@")!=-1; System.out.println(mail.matches(reg)); } }
1,282
0.560264
0.510358
61
16.409836
17.364347
66
false
false
0
0
0
0
0
0
2.032787
false
false
5
22efd255169eca831bcc95e281d096af7e7ae67b
31,301,721,692,054
cc15e580cbfc615b9c40bc2859ae849a86a716c6
/src/java/generator/Location.java
7f8ddb4db7f87ef3da2c2785b344a19a5cbad49a
[]
no_license
noobG/CA2
https://github.com/noobG/CA2
f02a33d6e8df15c6647ec804f1cb8bf4e8fa3db4
cc594b3909f7cfd55ba7986197b29fb5117390d8
refs/heads/master
2018-01-10T14:16:13.160000
2015-10-12T14:09:47
2015-10-12T14:09:47
43,739,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package generator; public class Location { public String street; public String city; public String state; public String zip; }
UTF-8
Java
131
java
Location.java
Java
[]
null
[]
package generator; public class Location { public String street; public String city; public String state; public String zip; }
131
0.770992
0.770992
8
15.5
8.789198
23
false
false
0
0
0
0
0
0
1.125
false
false
5
564cd5e8279a495685aaa23070cc9fc41a5418cb
33,389,075,826,600
3a9caa64427cf2c29e3511adea6d671a70c3bbe3
/com/google/p098a/C1868g.java
6dc2df9dcc8b416f8f18d62440ca6573a4bf501f
[]
no_license
DrOpossum/HAG-APP-obfuscated
https://github.com/DrOpossum/HAG-APP-obfuscated
9590d1f77ecccd63c4f5eeec1561e9e995005f48
f801ce550c03e6d8c78b7e01e2c6deaf39900ede
refs/heads/master
2020-02-25T12:10:31.442000
2017-08-15T12:48:12
2017-08-15T12:48:12
100,375,772
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.p098a; import com.google.p098a.p100b.C1809a; import com.google.p098a.p100b.C1826d; import com.google.p098a.p100b.p101a.C1808m; import com.google.p098a.p104c.C1845a; import java.lang.reflect.Type; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /* compiled from: GsonBuilder */ public final class C1868g { public C1847e f6497a = C1848d.f6462a; public String f6498b; private C1826d f6499c = C1826d.f6417a; private C1879v f6500d = C1879v.f6518a; private final Map<Type, C1869h<?>> f6501e = new HashMap(); private final List<C1766y> f6502f = new ArrayList(); private final List<C1766y> f6503g = new ArrayList(); private boolean f6504h = false; private int f6505i = 2; private int f6506j = 2; private boolean f6507k = false; private boolean f6508l = false; private boolean f6509m = true; private boolean f6510n = false; private boolean f6511o = false; private boolean f6512p = false; public final C1868g m6451a(Type type, Object obj) { C1809a.m6350a(true); if (obj instanceof C1869h) { this.f6501e.put(type, (C1869h) obj); } this.f6502f.add(C1883w.m6483b(C1845a.m6415a(type), obj)); if (obj instanceof C1769x) { this.f6502f.add(C1808m.m6345a(C1845a.m6415a(type), (C1769x) obj)); } return this; } public final C1868g m6450a(C1766y c1766y) { this.f6502f.add(c1766y); return this; } public final C1867f m6449a() { Object c1765a; List arrayList = new ArrayList(); arrayList.addAll(this.f6502f); Collections.reverse(arrayList); arrayList.addAll(this.f6503g); String str = this.f6498b; int i = this.f6505i; int i2 = this.f6506j; if (str == null || "".equals(str.trim())) { if (!(i == 2 || i2 == 2)) { c1765a = new C1765a(i, i2); } return new C1867f(this.f6499c, this.f6497a, this.f6501e, this.f6504h, this.f6507k, this.f6511o, this.f6509m, this.f6510n, this.f6512p, this.f6508l, this.f6500d, arrayList); } c1765a = new C1765a(str); arrayList.add(C1883w.m6481a(C1845a.m6414a(Date.class), c1765a)); arrayList.add(C1883w.m6481a(C1845a.m6414a(Timestamp.class), c1765a)); arrayList.add(C1883w.m6481a(C1845a.m6414a(java.sql.Date.class), c1765a)); return new C1867f(this.f6499c, this.f6497a, this.f6501e, this.f6504h, this.f6507k, this.f6511o, this.f6509m, this.f6510n, this.f6512p, this.f6508l, this.f6500d, arrayList); } }
UTF-8
Java
2,718
java
C1868g.java
Java
[]
null
[]
package com.google.p098a; import com.google.p098a.p100b.C1809a; import com.google.p098a.p100b.C1826d; import com.google.p098a.p100b.p101a.C1808m; import com.google.p098a.p104c.C1845a; import java.lang.reflect.Type; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /* compiled from: GsonBuilder */ public final class C1868g { public C1847e f6497a = C1848d.f6462a; public String f6498b; private C1826d f6499c = C1826d.f6417a; private C1879v f6500d = C1879v.f6518a; private final Map<Type, C1869h<?>> f6501e = new HashMap(); private final List<C1766y> f6502f = new ArrayList(); private final List<C1766y> f6503g = new ArrayList(); private boolean f6504h = false; private int f6505i = 2; private int f6506j = 2; private boolean f6507k = false; private boolean f6508l = false; private boolean f6509m = true; private boolean f6510n = false; private boolean f6511o = false; private boolean f6512p = false; public final C1868g m6451a(Type type, Object obj) { C1809a.m6350a(true); if (obj instanceof C1869h) { this.f6501e.put(type, (C1869h) obj); } this.f6502f.add(C1883w.m6483b(C1845a.m6415a(type), obj)); if (obj instanceof C1769x) { this.f6502f.add(C1808m.m6345a(C1845a.m6415a(type), (C1769x) obj)); } return this; } public final C1868g m6450a(C1766y c1766y) { this.f6502f.add(c1766y); return this; } public final C1867f m6449a() { Object c1765a; List arrayList = new ArrayList(); arrayList.addAll(this.f6502f); Collections.reverse(arrayList); arrayList.addAll(this.f6503g); String str = this.f6498b; int i = this.f6505i; int i2 = this.f6506j; if (str == null || "".equals(str.trim())) { if (!(i == 2 || i2 == 2)) { c1765a = new C1765a(i, i2); } return new C1867f(this.f6499c, this.f6497a, this.f6501e, this.f6504h, this.f6507k, this.f6511o, this.f6509m, this.f6510n, this.f6512p, this.f6508l, this.f6500d, arrayList); } c1765a = new C1765a(str); arrayList.add(C1883w.m6481a(C1845a.m6414a(Date.class), c1765a)); arrayList.add(C1883w.m6481a(C1845a.m6414a(Timestamp.class), c1765a)); arrayList.add(C1883w.m6481a(C1845a.m6414a(java.sql.Date.class), c1765a)); return new C1867f(this.f6499c, this.f6497a, this.f6501e, this.f6504h, this.f6507k, this.f6511o, this.f6509m, this.f6510n, this.f6512p, this.f6508l, this.f6500d, arrayList); } }
2,718
0.654157
0.480132
73
36.232876
30.646246
184
false
false
0
0
0
0
0
0
1.178082
false
false
5
1f016e061ae683516c7170f8e837519d13b6eadb
33,389,075,825,553
92f0fc04764158df1eb4aad32264a8272757d108
/src/main/java/com/jeeplus/modules/esign/util/OKHttpUtils.java
ec582ab1154fee023b80ae23599214491eba8536
[ "Apache-2.0" ]
permissive
moutainhigh/suppplychain
https://github.com/moutainhigh/suppplychain
9b11ff1b539c0af4075c9d1d32d834c1e73d5931
76da0c56dbd57cfb0d88a3affaa60b1fa4738ffe
refs/heads/master
2022-11-07T06:10:16.559000
2020-01-17T11:20:26
2020-01-17T11:20:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jeeplus.modules.esign.util; import com.alibaba.fastjson.JSONObject; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * 基于OKHttp构建的请求工具类 */ public class OKHttpUtils { private static final Logger logger = LoggerFactory.getLogger(OKHttpUtils.class); public static OkHttpClient getClient() { return new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); } public static JSONObject postJson(String url, JSONObject body) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); String bodyStr = body.toString(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送POST请求url={},body={}", requestBatchNo, url, bodyStr); try { RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), bodyStr); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body().string()); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } public static String postXML(String url, String body) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); String result = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送POST-XML请求url={},body={}", requestBatchNo, url, body); try { RequestBody requestBody = RequestBody.create(MediaType.parse("text/xml;charset=utf-8"), body); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = httpClient.newCall(request).execute(); result = Objects.requireNonNull(response.body().string()); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return result; } public static JSONObject postForm(String url, FormBody formBody) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS) .readTimeout(90L, TimeUnit.SECONDS) .build(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送POST-FORM请求url={},body={}", requestBatchNo, url, getRequestParams(formBody)); try { Request request = new Request.Builder().url(url).post(formBody).build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } public static JSONObject getRequest(String url, Map<String, Object> params) { OkHttpClient httpClient = new OkHttpClient(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送GET请求url={},params={}", requestBatchNo, url, params.toString()); try { url = attachParamsToUrl(url, params); Request request = new Request.Builder().url(url).get().build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("OKHttpUtils接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } public static JSONObject postJsonAddHeader(String url, HashMap<String, String> headers, JSONObject body) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); String bodyStr = body.toString(); logger.info("OKHttpUtils请求编号【{}】发送POST请求url={},header={},body={}", requestBatchNo, url, headers, bodyStr); try { RequestBody requestBody = RequestBody. create(MediaType.parse("application/json;charset=utf-8"), bodyStr); Request request = new Request.Builder().url(url) .headers(Headers.of(headers)) .post(requestBody).build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } /** * 参数关联到Url上 */ public static String attachParamsToUrl(String url, Map<String, Object> params) { Iterator<String> keys = params.keySet().iterator(); Iterator<Object> values = params.values().iterator(); if (params.size() > 0) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("?"); for (int i = 0; i < params.size(); i++) { stringBuffer.append(keys.next() + "=" + values.next()); if (i != params.size() - 1) { stringBuffer.append("&"); } } return url + stringBuffer.toString(); } return url; } public static JSONObject getRestfulAddHeader(String url,HashMap<String,String> header){ OkHttpClient httpClient = getClient(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("请求编号【{}】发送GET请求url={},header={},body={}", requestBatchNo, url, header); try { Request request = new Request.Builder().url(url).headers(Headers.of(header)) .build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } private static String getRequestParams(FormBody formBody) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < formBody.size(); i++) { stringBuilder.append(formBody.encodedName(i) + "=" + formBody.encodedValue(i) + ","); } stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length()); return stringBuilder.toString(); } }
UTF-8
Java
8,752
java
OKHttpUtils.java
Java
[]
null
[]
package com.jeeplus.modules.esign.util; import com.alibaba.fastjson.JSONObject; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * 基于OKHttp构建的请求工具类 */ public class OKHttpUtils { private static final Logger logger = LoggerFactory.getLogger(OKHttpUtils.class); public static OkHttpClient getClient() { return new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); } public static JSONObject postJson(String url, JSONObject body) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); String bodyStr = body.toString(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送POST请求url={},body={}", requestBatchNo, url, bodyStr); try { RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), bodyStr); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body().string()); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } public static String postXML(String url, String body) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); String result = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送POST-XML请求url={},body={}", requestBatchNo, url, body); try { RequestBody requestBody = RequestBody.create(MediaType.parse("text/xml;charset=utf-8"), body); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = httpClient.newCall(request).execute(); result = Objects.requireNonNull(response.body().string()); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return result; } public static JSONObject postForm(String url, FormBody formBody) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS) .readTimeout(90L, TimeUnit.SECONDS) .build(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送POST-FORM请求url={},body={}", requestBatchNo, url, getRequestParams(formBody)); try { Request request = new Request.Builder().url(url).post(formBody).build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } public static JSONObject getRequest(String url, Map<String, Object> params) { OkHttpClient httpClient = new OkHttpClient(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("OKHttpUtils请求编号【{}】发送GET请求url={},params={}", requestBatchNo, url, params.toString()); try { url = attachParamsToUrl(url, params); Request request = new Request.Builder().url(url).get().build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("OKHttpUtils接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("OKHttpUtils接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } public static JSONObject postJsonAddHeader(String url, HashMap<String, String> headers, JSONObject body) { OkHttpClient httpClient = new OkHttpClient().newBuilder() .connectTimeout(30L, TimeUnit.SECONDS)//连接时间 .readTimeout(90L, TimeUnit.SECONDS) //超时时间 .build(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); String bodyStr = body.toString(); logger.info("OKHttpUtils请求编号【{}】发送POST请求url={},header={},body={}", requestBatchNo, url, headers, bodyStr); try { RequestBody requestBody = RequestBody. create(MediaType.parse("application/json;charset=utf-8"), bodyStr); Request request = new Request.Builder().url(url) .headers(Headers.of(headers)) .post(requestBody).build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } /** * 参数关联到Url上 */ public static String attachParamsToUrl(String url, Map<String, Object> params) { Iterator<String> keys = params.keySet().iterator(); Iterator<Object> values = params.values().iterator(); if (params.size() > 0) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("?"); for (int i = 0; i < params.size(); i++) { stringBuffer.append(keys.next() + "=" + values.next()); if (i != params.size() - 1) { stringBuffer.append("&"); } } return url + stringBuffer.toString(); } return url; } public static JSONObject getRestfulAddHeader(String url,HashMap<String,String> header){ OkHttpClient httpClient = getClient(); JSONObject responseObj = null; String requestBatchNo = IdUtils.generateCouponBatchNo(); logger.info("请求编号【{}】发送GET请求url={},header={},body={}", requestBatchNo, url, header); try { Request request = new Request.Builder().url(url).headers(Headers.of(header)) .build(); Response response = httpClient.newCall(request).execute(); String result = Objects.requireNonNull(response.body()).string(); logger.info("接收请求编号【{}】返回内容={}", requestBatchNo, result); responseObj = JSONObject.parseObject(result); } catch (Exception e) { logger.error("接收请求编号【{}】报错,错误信息{}", requestBatchNo, e); } return responseObj; } private static String getRequestParams(FormBody formBody) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < formBody.size(); i++) { stringBuilder.append(formBody.encodedName(i) + "=" + formBody.encodedValue(i) + ","); } stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length()); return stringBuilder.toString(); } }
8,752
0.615422
0.61164
187
42.828876
30.887455
119
false
false
0
0
0
0
0
0
0.925134
false
false
5
996dc0f939f3c19cf213032783522c2b6b2ced34
32,933,809,294,772
104c643ac579a28516041b8f69c23abf55d6d792
/src/com/cloudfly/algorithm/leetcode/gaopin/Code_015_031.java
8790978803127c860e2e147a2a97be6f2b248bbd
[]
no_license
yungegege/algorithm
https://github.com/yungegege/algorithm
eafcbeaf6bc1088548442e14d78c6aa6511ab7bc
e7d409c68ea903d57059e28b48df96a27a3ffde3
refs/heads/master
2021-07-16T06:19:55.504000
2020-11-24T10:52:09
2020-11-24T10:52:09
218,457,025
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cloudfly.algorithm.leetcode.gaopin; import java.util.Arrays; public class Code_015_031 { public static void main(String[] args) { int[] arr = {2, 3, 1}; nextPermutation(arr); System.out.println(Arrays.toString(arr)); } public static void nextPermutation(int[] nums) { if (nums.length < 2) { return; } int index = 0; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { index = i; break; } } if (index == nums.length - 1) { swap(nums, index, index - 1); } else if (index == 0) { for (int i = 0; i < (nums.length + 1) / 2; i++) { swap(nums, i, nums.length - 1 - i); } } else { int num = index; for (int i = nums.length - 1; i > index; i--) { if (nums[i] > nums[index - 1]) { num = i; break; } } swap(nums, index - 1, num); for (int i = 0; i <= (nums.length-1-index) / 2; i++) { swap(nums, index+i , nums.length-1-i); } } } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
UTF-8
Java
1,393
java
Code_015_031.java
Java
[]
null
[]
package com.cloudfly.algorithm.leetcode.gaopin; import java.util.Arrays; public class Code_015_031 { public static void main(String[] args) { int[] arr = {2, 3, 1}; nextPermutation(arr); System.out.println(Arrays.toString(arr)); } public static void nextPermutation(int[] nums) { if (nums.length < 2) { return; } int index = 0; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { index = i; break; } } if (index == nums.length - 1) { swap(nums, index, index - 1); } else if (index == 0) { for (int i = 0; i < (nums.length + 1) / 2; i++) { swap(nums, i, nums.length - 1 - i); } } else { int num = index; for (int i = nums.length - 1; i > index; i--) { if (nums[i] > nums[index - 1]) { num = i; break; } } swap(nums, index - 1, num); for (int i = 0; i <= (nums.length-1-index) / 2; i++) { swap(nums, index+i , nums.length-1-i); } } } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
1,393
0.414214
0.394113
50
26.860001
18.546169
66
false
false
0
0
0
0
0
0
0.78
false
false
5
bb3721269bf81ac17f0f6b554daccc69eb49ff16
32,942,399,160,542
05b3de20d562d79665cef70ab435295338705770
/src_java/java/awt/Toolkit.java
92599797c7bb30809d5f8dd1dfdabc03fbd6696e
[]
no_license
stefanhaustein/kawt
https://github.com/stefanhaustein/kawt
614b51bbbe45bb87786cbe88c9da8e2c8d1d60ce
c6043079c863460c85fa64b72fd60fd29fe65ea6
refs/heads/master
2023-09-02T09:24:36.769000
2016-07-03T01:40:57
2016-07-03T01:40:57
62,476,150
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
// Toolkit.java // // 2000-10-06 SH Splitted into abstract and implementation classes // 2000-09-08 MK Added new Licensetext // //#include ..\..\license.txt // // kAWT version 0.95 // // Copyright (C) 1999-2000 by Michael Kroll & Stefan Haustein GbR, Essen // // Contact: kawt@kawt.de // General Information about kAWT is available at: http://www.kawt.de // // Using kAWT for private and educational and in GPLed open source // projects is free. For other purposes, a commercial license must be // obtained. There is absolutely no warranty for non-commercial use. // // // 1. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO // WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE // LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT // HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT // WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT // NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE // QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE // PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY // SERVICING, REPAIR OR CORRECTION. // // 2. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN // WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY // MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE // LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, // INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR // INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF // DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU // OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY // OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN // ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. // // END OF TERMS AND CONDITIONS // //#endinclude package java.awt; import java.io.*; import java.util.*; import java.awt.image.ColorModel; import de.kawt.impl.*; public abstract class Toolkit { // some package-internal constants / shortcuts static int pixelBits = System.getProperty ("kawt.colordepth") == null ? 1 : Integer.parseInt (System.getProperty ("kawt.colordepth")); static boolean colorKvm = System.getProperty ("kawt.colordepth") != null; // static int scrW = 160; // static int scrH = 160; static EventQueue eventQueue = new EventQueue (); static KawtThread kawtThread = new KawtThread (); static Object kawtLock = new Object (); static String platform = System.getProperty ("microedition.platform"); static String classbase = initclassbase (); static Class graphicsImpl = null; // last call, others must have been init.ed already! static KawtToolkit defaultToolkit = init (); static FontMetrics defaultFontMetrics = defaultToolkit.getFontMetrics (new Font ("plain", 8, 0)); static String initclassbase () { // don't ask me why this shortcut is necessary....! //System.out.println ("icb0:"+platform); if ("Jbed".equals(platform)) //return "de.kawt.impl.jbed"; return "de.kawt.impl.kjava"; if ("palm".equals (platform)) return "de.kawt.impl.kjava"; if (System.getProperty ("de.kawt.classbase") != null) return System.getProperty ("de.kawt.classbase"); try { Class.forName ("com.sun.kjava.Graphics"); if (platform == null) platform = "palm"; return "de.kawt.impl.kjava"; } catch (Exception e) {} try { Class.forName ("javax.microedition.lcdui.Graphics"); if (platform == null) platform = "midp"; return "de.kawt.impl.midp"; } catch (Exception e) {} try { Class.forName ("net.rim.device.api.system.Graphics"); if (platform == null) platform = "rim"; return "de.kawt.impl.rim"; } catch (Exception e) {} throw new RuntimeException ("unknown base lib and property de.kawt.classbase not set!"); } /** creates default toolkit and fills static shortcut variables */ static KawtToolkit init () { //System.out.println ("ti0"); Runtime.getRuntime ().gc (); // dont ask why this is neccessary... //System.out.println ("ti1"); String laf = classbase+".LafImpl"; try { Class.forName("com.sun.midp.palm.Info"); laf = "de.kawt.impl.kjava.LafImpl"; } catch (Throwable x) {} try { Laf.laf = (Laf) Class.forName (laf).newInstance (); } catch (Exception e) { Laf.laf = new Laf (); } //System.out.println ("*** ti2/cb: "+classbase); try { //System.out.println ("*** ti3"); graphicsImpl = Class.forName (classbase+".GraphicsImpl"); //System.out.println ("*** ti4"); return (KawtToolkit) Class.forName (classbase+".ToolkitImpl").newInstance (); } catch (Exception e) { //System.out.println ("*** ti5: "+e); throw new RuntimeException ("kawt init failure: "+e.toString ()); } } /** starts the kawtThread */ protected Toolkit () { kawtThread.start (); } /** not abstract, just does nothing by default */ public void beep () { } public ColorModel getColorModel () { return new ColorModel (pixelBits); } static public Toolkit getDefaultToolkit () { return defaultToolkit; } public EventQueue getSystemEventQueue () { return eventQueue; } public abstract Dimension getScreenSize (); static void flushRepaint () { synchronized (kawtLock) { Window top = Laf.getTopWindow (); if (top != null) { top.flushRepaint (); defaultToolkit.sync (); } } } public void sync () { } static Graphics createGraphics () { try { return (Graphics) graphicsImpl.newInstance (); } catch (Exception e) { throw new RuntimeException ("createGraphics failed: "+e.toString ()); } } public Image createImage (String ressourceName) { throw new RuntimeException ("jar ressources not yet supported"); } public abstract Image createImage (byte [] data); public abstract FontMetrics getFontMetrics (Font font); public static String getProperty (String key, String dflt) { if (key.equals ("kawt.classbase")) return classbase; else return dflt; } }
UTF-8
Java
6,566
java
Toolkit.java
Java
[ { "context": "kAWT version 0.95\n//\n// Copyright (C) 1999-2000 by Michael Kroll & Stefan Haustein GbR, Essen\n//\n// Contact: kawt@", "end": 233, "score": 0.999870777130127, "start": 220, "tag": "NAME", "value": "Michael Kroll" }, { "context": "5\n//\n// Copyright (C) 1999-2000 by M...
null
[]
// Toolkit.java // // 2000-10-06 SH Splitted into abstract and implementation classes // 2000-09-08 MK Added new Licensetext // //#include ..\..\license.txt // // kAWT version 0.95 // // Copyright (C) 1999-2000 by <NAME> & <NAME>, Essen // // Contact: <EMAIL> // General Information about kAWT is available at: http://www.kawt.de // // Using kAWT for private and educational and in GPLed open source // projects is free. For other purposes, a commercial license must be // obtained. There is absolutely no warranty for non-commercial use. // // // 1. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO // WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE // LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT // HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT // WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT // NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE // QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE // PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY // SERVICING, REPAIR OR CORRECTION. // // 2. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN // WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY // MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE // LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, // INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR // INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF // DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU // OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY // OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN // ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. // // END OF TERMS AND CONDITIONS // //#endinclude package java.awt; import java.io.*; import java.util.*; import java.awt.image.ColorModel; import de.kawt.impl.*; public abstract class Toolkit { // some package-internal constants / shortcuts static int pixelBits = System.getProperty ("kawt.colordepth") == null ? 1 : Integer.parseInt (System.getProperty ("kawt.colordepth")); static boolean colorKvm = System.getProperty ("kawt.colordepth") != null; // static int scrW = 160; // static int scrH = 160; static EventQueue eventQueue = new EventQueue (); static KawtThread kawtThread = new KawtThread (); static Object kawtLock = new Object (); static String platform = System.getProperty ("microedition.platform"); static String classbase = initclassbase (); static Class graphicsImpl = null; // last call, others must have been init.ed already! static KawtToolkit defaultToolkit = init (); static FontMetrics defaultFontMetrics = defaultToolkit.getFontMetrics (new Font ("plain", 8, 0)); static String initclassbase () { // don't ask me why this shortcut is necessary....! //System.out.println ("icb0:"+platform); if ("Jbed".equals(platform)) //return "de.kawt.impl.jbed"; return "de.kawt.impl.kjava"; if ("palm".equals (platform)) return "de.kawt.impl.kjava"; if (System.getProperty ("de.kawt.classbase") != null) return System.getProperty ("de.kawt.classbase"); try { Class.forName ("com.sun.kjava.Graphics"); if (platform == null) platform = "palm"; return "de.kawt.impl.kjava"; } catch (Exception e) {} try { Class.forName ("javax.microedition.lcdui.Graphics"); if (platform == null) platform = "midp"; return "de.kawt.impl.midp"; } catch (Exception e) {} try { Class.forName ("net.rim.device.api.system.Graphics"); if (platform == null) platform = "rim"; return "de.kawt.impl.rim"; } catch (Exception e) {} throw new RuntimeException ("unknown base lib and property de.kawt.classbase not set!"); } /** creates default toolkit and fills static shortcut variables */ static KawtToolkit init () { //System.out.println ("ti0"); Runtime.getRuntime ().gc (); // dont ask why this is neccessary... //System.out.println ("ti1"); String laf = classbase+".LafImpl"; try { Class.forName("com.sun.midp.palm.Info"); laf = "de.kawt.impl.kjava.LafImpl"; } catch (Throwable x) {} try { Laf.laf = (Laf) Class.forName (laf).newInstance (); } catch (Exception e) { Laf.laf = new Laf (); } //System.out.println ("*** ti2/cb: "+classbase); try { //System.out.println ("*** ti3"); graphicsImpl = Class.forName (classbase+".GraphicsImpl"); //System.out.println ("*** ti4"); return (KawtToolkit) Class.forName (classbase+".ToolkitImpl").newInstance (); } catch (Exception e) { //System.out.println ("*** ti5: "+e); throw new RuntimeException ("kawt init failure: "+e.toString ()); } } /** starts the kawtThread */ protected Toolkit () { kawtThread.start (); } /** not abstract, just does nothing by default */ public void beep () { } public ColorModel getColorModel () { return new ColorModel (pixelBits); } static public Toolkit getDefaultToolkit () { return defaultToolkit; } public EventQueue getSystemEventQueue () { return eventQueue; } public abstract Dimension getScreenSize (); static void flushRepaint () { synchronized (kawtLock) { Window top = Laf.getTopWindow (); if (top != null) { top.flushRepaint (); defaultToolkit.sync (); } } } public void sync () { } static Graphics createGraphics () { try { return (Graphics) graphicsImpl.newInstance (); } catch (Exception e) { throw new RuntimeException ("createGraphics failed: "+e.toString ()); } } public Image createImage (String ressourceName) { throw new RuntimeException ("jar ressources not yet supported"); } public abstract Image createImage (byte [] data); public abstract FontMetrics getFontMetrics (Font font); public static String getProperty (String key, String dflt) { if (key.equals ("kawt.classbase")) return classbase; else return dflt; } }
6,541
0.638136
0.631282
236
26.809322
25.274126
81
false
false
0
0
0
0
0
0
0.572034
false
false
5
5e4c2f4bdc8f554be32f9ab1e17e10be3d7bc32d
33,629,593,990,824
b3a694913d943bdb565fbf828d6ab8a08dd7dd12
/sources/p002es/gob/radarcovid/models/response/ResponseSettingsAppVersionItem.java
8f0846075172ad58d6d11c9d76548a833244b476
[]
no_license
v1ckxy/radar-covid
https://github.com/v1ckxy/radar-covid
feea41283bde8a0b37fbc9132c9fa5df40d76cc4
8acb96f8ccd979f03db3c6dbfdf162d66ad6ac5a
refs/heads/master
2022-12-06T11:29:19.567000
2020-08-29T08:00:19
2020-08-29T08:00:19
294,198,796
1
0
null
true
2020-09-09T18:39:43
2020-09-09T18:39:43
2020-08-29T08:03:57
2020-08-29T08:03:48
21,971
0
0
0
null
false
false
package p002es.gob.radarcovid.models.response; import p213q.p214a.p215a.p216a.C1965a; import p392u.p401r.p403c.C4636f; /* renamed from: es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem */ public final class ResponseSettingsAppVersionItem { public final Integer compilation; public final String version; public ResponseSettingsAppVersionItem() { this(null, null, 3, null); } public ResponseSettingsAppVersionItem(String str, Integer num) { this.version = str; this.compilation = num; } public /* synthetic */ ResponseSettingsAppVersionItem(String str, Integer num, int i, C4636f fVar) { if ((i & 1) != 0) { str = "1.0"; } if ((i & 2) != 0) { num = Integer.valueOf(1); } this(str, num); } public static /* synthetic */ ResponseSettingsAppVersionItem copy$default(ResponseSettingsAppVersionItem responseSettingsAppVersionItem, String str, Integer num, int i, Object obj) { if ((i & 1) != 0) { str = responseSettingsAppVersionItem.version; } if ((i & 2) != 0) { num = responseSettingsAppVersionItem.compilation; } return responseSettingsAppVersionItem.copy(str, num); } public final String component1() { return this.version; } public final Integer component2() { return this.compilation; } public final ResponseSettingsAppVersionItem copy(String str, Integer num) { return new ResponseSettingsAppVersionItem(str, num); } /* JADX WARNING: Code restructure failed: missing block: B:6:0x001a, code lost: if (p392u.p401r.p403c.C4638h.m10272a((java.lang.Object) r2.compilation, (java.lang.Object) r3.compilation) != false) goto L_0x001f; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public boolean equals(java.lang.Object r3) { /* r2 = this; if (r2 == r3) goto L_0x001f boolean r0 = r3 instanceof p002es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem if (r0 == 0) goto L_0x001d es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem r3 = (p002es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem) r3 java.lang.String r0 = r2.version java.lang.String r1 = r3.version boolean r0 = p392u.p401r.p403c.C4638h.m10272a(r0, r1) if (r0 == 0) goto L_0x001d java.lang.Integer r0 = r2.compilation java.lang.Integer r3 = r3.compilation boolean r3 = p392u.p401r.p403c.C4638h.m10272a(r0, r3) if (r3 == 0) goto L_0x001d goto L_0x001f L_0x001d: r3 = 0 return r3 L_0x001f: r3 = 1 return r3 */ throw new UnsupportedOperationException("Method not decompiled: p002es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem.equals(java.lang.Object):boolean"); } public final Integer getCompilation() { return this.compilation; } public final String getVersion() { return this.version; } public int hashCode() { String str = this.version; int i = 0; int hashCode = (str != null ? str.hashCode() : 0) * 31; Integer num = this.compilation; if (num != null) { i = num.hashCode(); } return hashCode + i; } public String toString() { StringBuilder a = C1965a.m4756a("ResponseSettingsAppVersionItem(version="); a.append(this.version); a.append(", compilation="); a.append(this.compilation); a.append(")"); return a.toString(); } }
UTF-8
Java
3,784
java
ResponseSettingsAppVersionItem.java
Java
[]
null
[]
package p002es.gob.radarcovid.models.response; import p213q.p214a.p215a.p216a.C1965a; import p392u.p401r.p403c.C4636f; /* renamed from: es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem */ public final class ResponseSettingsAppVersionItem { public final Integer compilation; public final String version; public ResponseSettingsAppVersionItem() { this(null, null, 3, null); } public ResponseSettingsAppVersionItem(String str, Integer num) { this.version = str; this.compilation = num; } public /* synthetic */ ResponseSettingsAppVersionItem(String str, Integer num, int i, C4636f fVar) { if ((i & 1) != 0) { str = "1.0"; } if ((i & 2) != 0) { num = Integer.valueOf(1); } this(str, num); } public static /* synthetic */ ResponseSettingsAppVersionItem copy$default(ResponseSettingsAppVersionItem responseSettingsAppVersionItem, String str, Integer num, int i, Object obj) { if ((i & 1) != 0) { str = responseSettingsAppVersionItem.version; } if ((i & 2) != 0) { num = responseSettingsAppVersionItem.compilation; } return responseSettingsAppVersionItem.copy(str, num); } public final String component1() { return this.version; } public final Integer component2() { return this.compilation; } public final ResponseSettingsAppVersionItem copy(String str, Integer num) { return new ResponseSettingsAppVersionItem(str, num); } /* JADX WARNING: Code restructure failed: missing block: B:6:0x001a, code lost: if (p392u.p401r.p403c.C4638h.m10272a((java.lang.Object) r2.compilation, (java.lang.Object) r3.compilation) != false) goto L_0x001f; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public boolean equals(java.lang.Object r3) { /* r2 = this; if (r2 == r3) goto L_0x001f boolean r0 = r3 instanceof p002es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem if (r0 == 0) goto L_0x001d es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem r3 = (p002es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem) r3 java.lang.String r0 = r2.version java.lang.String r1 = r3.version boolean r0 = p392u.p401r.p403c.C4638h.m10272a(r0, r1) if (r0 == 0) goto L_0x001d java.lang.Integer r0 = r2.compilation java.lang.Integer r3 = r3.compilation boolean r3 = p392u.p401r.p403c.C4638h.m10272a(r0, r3) if (r3 == 0) goto L_0x001d goto L_0x001f L_0x001d: r3 = 0 return r3 L_0x001f: r3 = 1 return r3 */ throw new UnsupportedOperationException("Method not decompiled: p002es.gob.radarcovid.models.response.ResponseSettingsAppVersionItem.equals(java.lang.Object):boolean"); } public final Integer getCompilation() { return this.compilation; } public final String getVersion() { return this.version; } public int hashCode() { String str = this.version; int i = 0; int hashCode = (str != null ? str.hashCode() : 0) * 31; Integer num = this.compilation; if (num != null) { i = num.hashCode(); } return hashCode + i; } public String toString() { StringBuilder a = C1965a.m4756a("ResponseSettingsAppVersionItem(version="); a.append(this.version); a.append(", compilation="); a.append(this.compilation); a.append(")"); return a.toString(); } }
3,784
0.617072
0.564746
109
33.715595
34.991768
186
false
false
0
0
0
0
0
0
0.504587
false
false
5
790f6b1a4636cb527e19010ddb36211ee2bf87bd
33,629,593,991,337
b1f0fa813a3a133f094f95fe15c8dfc197fee164
/share-po/src/test/java/org/alfresco/po/share/cmm/CreateNewPropertyGroupPopUpTest.java
3ebd9dc28287836b6b7af6d2bb36d29f573a8473
[]
no_license
lzdujing/afresco-webapp
https://github.com/lzdujing/afresco-webapp
b30f8c97e1cb88c2ec026950650038b03f30bff8
9e3521f3f7491c1460fe586bd1bc52e2337a153d
refs/heads/master
2020-03-27T00:35:02.874000
2018-08-23T00:58:15
2018-08-23T00:58:15
145,636,373
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * #%L * share-po * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.po.share.cmm; import org.alfresco.po.share.SharePage; import org.alfresco.po.share.cmm.admin.CreateNewPropertyGroupPopUp; import org.alfresco.po.share.cmm.admin.ManageTypesAndAspectsPage; import org.alfresco.po.share.cmm.admin.ModelManagerPage; import org.alfresco.po.share.cmm.admin.ModelPropertyGroupRow; import org.alfresco.po.share.cmm.steps.CmmActions; import org.alfresco.test.FailedTestListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * The Class CreateNewPropertyGroupPopUpTest * * @author Richard Smith * @author mbhave */ @SuppressWarnings("unused") @Listeners(FailedTestListener.class) public class CreateNewPropertyGroupPopUpTest extends AbstractTestCMM { /** The logger */ private static Log logger = LogFactory.getLog(CreateNewPropertyGroupPopUpTest.class); private SharePage page; private String name = "model1" + System.currentTimeMillis(); // SHA-1103: Amended Parent Aspect Name to private String parentModelName = "parent" + name; private String aspectName = "Aspect" + System.currentTimeMillis(); // private String parentPropertyGroup = "cm:author (Author)"; private String parentPropertyGroup = getParentTypeAspectName(parentModelName, aspectName); @Autowired CmmActions cmmActions; @BeforeClass(groups = { "Enterprise-only" }, alwaysRun = true) public void setup() throws Exception { page = loginAs(username, password); ModelManagerPage cmmPage = cmmActions.navigateToModelManagerPage(driver).render(); // SHA-1103: Create another Model, Aspect to be used as Parent Type Group later cmmActions.createNewModel(driver, parentModelName); cmmActions.setModelActive(driver, parentModelName, true); // Create another model cmmPage = cmmActions.createNewModel(driver, name).render(); cmmPage.selectCustomModelRowByName(parentModelName).render(); ManageTypesAndAspectsPage aspectsListPage = cmmActions.createAspect(driver, aspectName).render(); } /** * Logout at the end */ @AfterClass public void cleanupSession() { cleanSession(driver); } /** * Test the create property group button works * * @throws Exception the exception */ @Test(groups = { "Enterprise-only" }, priority = 1) public void testCreatePropertyGroupButton() throws Exception { String dialogueHeader = "Create Aspect"; CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); Assert.assertNotNull(createNewPropertyGroupPopUp); Assert.assertNotNull(createNewPropertyGroupPopUp.getDialogueTitle()); Assert.assertTrue(dialogueHeader.equals(createNewPropertyGroupPopUp.getDialogueTitle())); ManageTypesAndAspectsPage manageAspectsPage = createNewPropertyGroupPopUp.selectCloseButton().render(); Assert.assertNotNull(manageAspectsPage); } /** * Test setting the name on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 2) public void testSetName() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setNameField(name).render(); Assert.assertEquals(createNewPropertyGroupPopUp.getNameField(), name, "Name field text displayed correctly"); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test setting the parent property group on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 3) public void testSetParentPropertyGroup() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setParentPropertyGroupField(parentPropertyGroup).render(); Assert.assertEquals( createNewPropertyGroupPopUp.getParentPropertyGroupField(), parentPropertyGroup, "Parent property group field text displayed correctly"); Assert.assertTrue(createNewPropertyGroupPopUp.isGroupDisplayedInParentList(parentPropertyGroup)); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test setting the title on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 4) public void testSetTitle() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setTitleField(name).render(); Assert.assertEquals(createNewPropertyGroupPopUp.getTitleField(), name, "Title field text displayed correctly"); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test setting the description on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 5) public void testSetDescription() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setDescriptionField(name).render(); Assert.assertEquals(createNewPropertyGroupPopUp.getDescriptionField(), name, "Description field text displayed correctly"); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test creating a property group works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 6) public void testCreatePropertyGroup() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setNameField(name); createNewPropertyGroupPopUp.setParentPropertyGroupField(parentPropertyGroup); createNewPropertyGroupPopUp.setTitleField(name); createNewPropertyGroupPopUp.setDescriptionField(name); ManageTypesAndAspectsPage manageTypesAndAspectsPage = createNewPropertyGroupPopUp.selectCreateButton().render(); String compoundName = name + ":" + name; ModelPropertyGroupRow modelPropertyGroupRow = manageTypesAndAspectsPage.getCustomModelPropertyGroupRowByName(compoundName); Assert.assertNotNull(modelPropertyGroupRow, "The new property group was not found"); } /** * Test validations of a property group * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 7) public void testCreatePropertyGroupValidations() throws Exception { CreateNewPropertyGroupPopUp newPGPopUp = createNewPropertyGroupForModel(); // Commented out as error behaviour is changed. Messages will only be displayed on invalid input. // Discussed within CMM that tests for validations etc are in scope for Aikau team // Assert.assertFalse(createNewPropertyGroupPopUp.isNameValidationMessageDisplayed(), "There should be a name validation message shown"); // Assert.assertFalse(newPGPopUp.isParentAspectValidationMessageDisplayed(), "There should not be a parent property group validation message shown"); // Assert.assertFalse(createNewPropertyGroupPopUp.isTitleValidationMessageDisplayed(), "There should not be a title validation message shown"); // Assert.assertFalse(createNewPropertyGroupPopUp.isDescriptionValidationMessageDisplayed(), // "There should not be a description validation message shown"); Assert.assertTrue(newPGPopUp.isCancelButtonEnabled(), "The cancel button should be enabled"); Assert.assertFalse(newPGPopUp.isCreateButtonEnabled(), "The create button should not be enabled"); newPGPopUp.setNameField(name); newPGPopUp.setParentPropertyGroupField(parentPropertyGroup); newPGPopUp.setTitleField(name); newPGPopUp.setDescriptionField(name); Assert.assertFalse(newPGPopUp.isNameValidationMessageDisplayed(), "There should not be a name validation message shown"); Assert.assertFalse(newPGPopUp.isParentAspectValidationMessageDisplayed(), "There should not be a parent property group validation message shown"); Assert.assertFalse(newPGPopUp.isTitleValidationMessageDisplayed(), "There should not be a title validation message shown"); Assert.assertFalse(newPGPopUp.isDescriptionValidationMessageDisplayed(), "There should not be a description validation message shown"); Assert.assertTrue(newPGPopUp.isCancelButtonEnabled(), "The cancel button should be enabled"); Assert.assertTrue(newPGPopUp.isCreateButtonEnabled(), "The create button should be enabled"); newPGPopUp.setNameField("!£$%^&"); Assert.assertTrue(newPGPopUp.isNameValidationMessageDisplayed(), "There should be a name validation message shown - illegal chars"); Assert.assertTrue(newPGPopUp.isCancelButtonEnabled(), "The cancel button should be enabled"); Assert.assertFalse(newPGPopUp.isCreateButtonEnabled(), "The create button should not be enabled"); newPGPopUp.selectCloseButton().render(); } /** * Navigate to property group pop up. * * @return the creates the new property group pop up * @throws Exception the exception */ private CreateNewPropertyGroupPopUp createNewPropertyGroupForModel() { ModelManagerPage modelPage = cmmActions.navigateToModelManagerPage(driver).render(); ManageTypesAndAspectsPage manageTypesAndAspectsPage = modelPage.selectCustomModelRowByName(name).render(); return manageTypesAndAspectsPage.clickCreateNewPropertyGroupButton().render(); } }
UTF-8
Java
11,193
java
CreateNewPropertyGroupPopUpTest.java
Java
[ { "context": "ass CreateNewPropertyGroupPopUpTest\n * \n * @author Richard Smith\n * @author mbhave\n */\n@SuppressWarnings(\"unused\")", "end": 1858, "score": 0.9991403818130493, "start": 1845, "tag": "NAME", "value": "Richard Smith" }, { "context": "pPopUpTest\n * \n * @author Rich...
null
[]
/* * #%L * share-po * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.po.share.cmm; import org.alfresco.po.share.SharePage; import org.alfresco.po.share.cmm.admin.CreateNewPropertyGroupPopUp; import org.alfresco.po.share.cmm.admin.ManageTypesAndAspectsPage; import org.alfresco.po.share.cmm.admin.ModelManagerPage; import org.alfresco.po.share.cmm.admin.ModelPropertyGroupRow; import org.alfresco.po.share.cmm.steps.CmmActions; import org.alfresco.test.FailedTestListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * The Class CreateNewPropertyGroupPopUpTest * * @author <NAME> * @author mbhave */ @SuppressWarnings("unused") @Listeners(FailedTestListener.class) public class CreateNewPropertyGroupPopUpTest extends AbstractTestCMM { /** The logger */ private static Log logger = LogFactory.getLog(CreateNewPropertyGroupPopUpTest.class); private SharePage page; private String name = "model1" + System.currentTimeMillis(); // SHA-1103: Amended Parent Aspect Name to private String parentModelName = "parent" + name; private String aspectName = "Aspect" + System.currentTimeMillis(); // private String parentPropertyGroup = "cm:author (Author)"; private String parentPropertyGroup = getParentTypeAspectName(parentModelName, aspectName); @Autowired CmmActions cmmActions; @BeforeClass(groups = { "Enterprise-only" }, alwaysRun = true) public void setup() throws Exception { page = loginAs(username, password); ModelManagerPage cmmPage = cmmActions.navigateToModelManagerPage(driver).render(); // SHA-1103: Create another Model, Aspect to be used as Parent Type Group later cmmActions.createNewModel(driver, parentModelName); cmmActions.setModelActive(driver, parentModelName, true); // Create another model cmmPage = cmmActions.createNewModel(driver, name).render(); cmmPage.selectCustomModelRowByName(parentModelName).render(); ManageTypesAndAspectsPage aspectsListPage = cmmActions.createAspect(driver, aspectName).render(); } /** * Logout at the end */ @AfterClass public void cleanupSession() { cleanSession(driver); } /** * Test the create property group button works * * @throws Exception the exception */ @Test(groups = { "Enterprise-only" }, priority = 1) public void testCreatePropertyGroupButton() throws Exception { String dialogueHeader = "Create Aspect"; CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); Assert.assertNotNull(createNewPropertyGroupPopUp); Assert.assertNotNull(createNewPropertyGroupPopUp.getDialogueTitle()); Assert.assertTrue(dialogueHeader.equals(createNewPropertyGroupPopUp.getDialogueTitle())); ManageTypesAndAspectsPage manageAspectsPage = createNewPropertyGroupPopUp.selectCloseButton().render(); Assert.assertNotNull(manageAspectsPage); } /** * Test setting the name on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 2) public void testSetName() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setNameField(name).render(); Assert.assertEquals(createNewPropertyGroupPopUp.getNameField(), name, "Name field text displayed correctly"); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test setting the parent property group on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 3) public void testSetParentPropertyGroup() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setParentPropertyGroupField(parentPropertyGroup).render(); Assert.assertEquals( createNewPropertyGroupPopUp.getParentPropertyGroupField(), parentPropertyGroup, "Parent property group field text displayed correctly"); Assert.assertTrue(createNewPropertyGroupPopUp.isGroupDisplayedInParentList(parentPropertyGroup)); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test setting the title on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 4) public void testSetTitle() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setTitleField(name).render(); Assert.assertEquals(createNewPropertyGroupPopUp.getTitleField(), name, "Title field text displayed correctly"); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test setting the description on the form works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 5) public void testSetDescription() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setDescriptionField(name).render(); Assert.assertEquals(createNewPropertyGroupPopUp.getDescriptionField(), name, "Description field text displayed correctly"); createNewPropertyGroupPopUp.selectCloseButton().render(); } /** * Test creating a property group works * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 6) public void testCreatePropertyGroup() throws Exception { CreateNewPropertyGroupPopUp createNewPropertyGroupPopUp = createNewPropertyGroupForModel(); createNewPropertyGroupPopUp.setNameField(name); createNewPropertyGroupPopUp.setParentPropertyGroupField(parentPropertyGroup); createNewPropertyGroupPopUp.setTitleField(name); createNewPropertyGroupPopUp.setDescriptionField(name); ManageTypesAndAspectsPage manageTypesAndAspectsPage = createNewPropertyGroupPopUp.selectCreateButton().render(); String compoundName = name + ":" + name; ModelPropertyGroupRow modelPropertyGroupRow = manageTypesAndAspectsPage.getCustomModelPropertyGroupRowByName(compoundName); Assert.assertNotNull(modelPropertyGroupRow, "The new property group was not found"); } /** * Test validations of a property group * * @throws Exception if error */ @Test(groups = { "Enterprise-only" }, priority = 7) public void testCreatePropertyGroupValidations() throws Exception { CreateNewPropertyGroupPopUp newPGPopUp = createNewPropertyGroupForModel(); // Commented out as error behaviour is changed. Messages will only be displayed on invalid input. // Discussed within CMM that tests for validations etc are in scope for Aikau team // Assert.assertFalse(createNewPropertyGroupPopUp.isNameValidationMessageDisplayed(), "There should be a name validation message shown"); // Assert.assertFalse(newPGPopUp.isParentAspectValidationMessageDisplayed(), "There should not be a parent property group validation message shown"); // Assert.assertFalse(createNewPropertyGroupPopUp.isTitleValidationMessageDisplayed(), "There should not be a title validation message shown"); // Assert.assertFalse(createNewPropertyGroupPopUp.isDescriptionValidationMessageDisplayed(), // "There should not be a description validation message shown"); Assert.assertTrue(newPGPopUp.isCancelButtonEnabled(), "The cancel button should be enabled"); Assert.assertFalse(newPGPopUp.isCreateButtonEnabled(), "The create button should not be enabled"); newPGPopUp.setNameField(name); newPGPopUp.setParentPropertyGroupField(parentPropertyGroup); newPGPopUp.setTitleField(name); newPGPopUp.setDescriptionField(name); Assert.assertFalse(newPGPopUp.isNameValidationMessageDisplayed(), "There should not be a name validation message shown"); Assert.assertFalse(newPGPopUp.isParentAspectValidationMessageDisplayed(), "There should not be a parent property group validation message shown"); Assert.assertFalse(newPGPopUp.isTitleValidationMessageDisplayed(), "There should not be a title validation message shown"); Assert.assertFalse(newPGPopUp.isDescriptionValidationMessageDisplayed(), "There should not be a description validation message shown"); Assert.assertTrue(newPGPopUp.isCancelButtonEnabled(), "The cancel button should be enabled"); Assert.assertTrue(newPGPopUp.isCreateButtonEnabled(), "The create button should be enabled"); newPGPopUp.setNameField("!£$%^&"); Assert.assertTrue(newPGPopUp.isNameValidationMessageDisplayed(), "There should be a name validation message shown - illegal chars"); Assert.assertTrue(newPGPopUp.isCancelButtonEnabled(), "The cancel button should be enabled"); Assert.assertFalse(newPGPopUp.isCreateButtonEnabled(), "The create button should not be enabled"); newPGPopUp.selectCloseButton().render(); } /** * Navigate to property group pop up. * * @return the creates the new property group pop up * @throws Exception the exception */ private CreateNewPropertyGroupPopUp createNewPropertyGroupForModel() { ModelManagerPage modelPage = cmmActions.navigateToModelManagerPage(driver).render(); ManageTypesAndAspectsPage manageTypesAndAspectsPage = modelPage.selectCustomModelRowByName(name).render(); return manageTypesAndAspectsPage.clickCreateNewPropertyGroupButton().render(); } }
11,186
0.734185
0.731951
276
39.550724
39.312862
157
false
false
0
0
0
0
0
0
0.5
false
false
5
734aacd6545f09e59aec13ce428b344bd5d7f463
28,973,849,380,971
b1d35eaa750bd7696dd6ce36974e9bc86f359059
/src/test/java/jp/dressingroom/apiguard/httpresponder/TestHttpResponderMainVerticle.java
f896ad4d964f5aa4828f43f933f209dcc4a2f651
[ "Apache-2.0" ]
permissive
masatoshiitoh/http-responder
https://github.com/masatoshiitoh/http-responder
7251dfaa83bde3bea065c2a640710dc5d850d077
011927f6dcf117b4dea4bacba4e915783aa6edf0
refs/heads/master
2020-10-01T18:53:53.663000
2020-01-13T05:48:48
2020-01-13T05:48:48
227,603,190
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.dressingroom.apiguard.httpresponder; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.codec.BodyCodec; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(VertxExtension.class) public class TestHttpResponderMainVerticle { static int responderPort = 18000; @BeforeAll static void deployVerticle(Vertx vertx, VertxTestContext testContext) { System.setProperty("server.port", String.valueOf(responderPort)); vertx.deployVerticle(new HttpResponderMainVerticle(), testContext.completing()); } @Test void httpResponderGetHelloResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/hello") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().equals("Hello")); testContext.completeNow(); }))); } @Test void httpResponderPostHelloResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/hello") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().equals("some payload")); testContext.completeNow(); }))); } @Test void httpResponderPostSomePathResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/test/path") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().contains("/test/path")); testContext.completeNow(); }))); } @Test void httpResponderGetSomePathResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/test/path") .as(BodyCodec.string()) .send( testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().contains("/test/path")); testContext.completeNow(); }))); } @Test void httpResponderGet404Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/404") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 404); testContext.completeNow(); }))); } @Test void httpResponderGet500Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/500") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 500); testContext.completeNow(); }))); } @Test void httpResponderPost404Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/404") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 404); testContext.completeNow(); }))); } @Test void httpResponderPost500Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/500") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 500); testContext.completeNow(); }))); } @Test void httpResponderOptionSomePathResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.OPTIONS, responderPort, "localhost", "/test/path") .as(BodyCodec.string()) .send( testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().contains("/test/path")); testContext.completeNow(); }))); } @Test void httpResponderOption404Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.OPTIONS, responderPort, "localhost", "/404") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 404); testContext.completeNow(); }))); } @Test void httpResponderOption500Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.OPTIONS, responderPort, "localhost", "/500") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 500); testContext.completeNow(); }))); } @Test void httpResponderGetCounterResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.GET, responderPort, "localhost", "/counter") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); long counter1 = Long.parseLong(response.body()); client.request(HttpMethod.GET, responderPort, "localhost", "/counter") .as(BodyCodec.string()) .send(testContext.succeeding(secondCall -> testContext.verify(() -> { assertTrue(secondCall.statusCode() == 200); long counter2 = Long.parseLong(secondCall.body()); assertTrue(counter2 > counter1, "counter did not incrementd. counter1 is " + counter1 + " coutner2 is " + counter2); testContext.completeNow(); }))); }))); } }
UTF-8
Java
7,050
java
TestHttpResponderMainVerticle.java
Java
[]
null
[]
package jp.dressingroom.apiguard.httpresponder; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.codec.BodyCodec; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(VertxExtension.class) public class TestHttpResponderMainVerticle { static int responderPort = 18000; @BeforeAll static void deployVerticle(Vertx vertx, VertxTestContext testContext) { System.setProperty("server.port", String.valueOf(responderPort)); vertx.deployVerticle(new HttpResponderMainVerticle(), testContext.completing()); } @Test void httpResponderGetHelloResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/hello") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().equals("Hello")); testContext.completeNow(); }))); } @Test void httpResponderPostHelloResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/hello") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().equals("some payload")); testContext.completeNow(); }))); } @Test void httpResponderPostSomePathResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/test/path") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().contains("/test/path")); testContext.completeNow(); }))); } @Test void httpResponderGetSomePathResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/test/path") .as(BodyCodec.string()) .send( testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().contains("/test/path")); testContext.completeNow(); }))); } @Test void httpResponderGet404Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/404") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 404); testContext.completeNow(); }))); } @Test void httpResponderGet500Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.get(responderPort, "localhost", "/500") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 500); testContext.completeNow(); }))); } @Test void httpResponderPost404Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/404") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 404); testContext.completeNow(); }))); } @Test void httpResponderPost500Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.post(responderPort, "localhost", "/500") .as(BodyCodec.string()) .sendBuffer(Buffer.buffer("some payload"), testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 500); testContext.completeNow(); }))); } @Test void httpResponderOptionSomePathResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.OPTIONS, responderPort, "localhost", "/test/path") .as(BodyCodec.string()) .send( testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); assertTrue(response.body().contains("/test/path")); testContext.completeNow(); }))); } @Test void httpResponderOption404Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.OPTIONS, responderPort, "localhost", "/404") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 404); testContext.completeNow(); }))); } @Test void httpResponderOption500Response(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.OPTIONS, responderPort, "localhost", "/500") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 500); testContext.completeNow(); }))); } @Test void httpResponderGetCounterResponse(Vertx vertx, VertxTestContext testContext) throws Throwable { WebClient client = WebClient.create(vertx); client.request(HttpMethod.GET, responderPort, "localhost", "/counter") .as(BodyCodec.string()) .send(testContext.succeeding(response -> testContext.verify(() -> { assertTrue(response.statusCode() == 200); long counter1 = Long.parseLong(response.body()); client.request(HttpMethod.GET, responderPort, "localhost", "/counter") .as(BodyCodec.string()) .send(testContext.succeeding(secondCall -> testContext.verify(() -> { assertTrue(secondCall.statusCode() == 200); long counter2 = Long.parseLong(secondCall.body()); assertTrue(counter2 > counter1, "counter did not incrementd. counter1 is " + counter1 + " coutner2 is " + counter2); testContext.completeNow(); }))); }))); } }
7,050
0.682128
0.669362
189
36.301586
29.9076
129
false
false
0
0
0
0
0
0
0.661376
false
false
5
84da9ff3bbe0126baca3f13432eaf92a1b5b569b
8,735,963,548,251
e682fa3667adce9277ecdedb40d4d01a785b3912
/internal/fischer/mangf/A184389.java
847f516ac908f32da6ac9a000050f4bc4536a745
[ "Apache-2.0" ]
permissive
gfis/joeis-lite
https://github.com/gfis/joeis-lite
859158cb8fc3608febf39ba71ab5e72360b32cb4
7185a0b62d54735dc3d43d8fb5be677734f99101
refs/heads/master
2023-08-31T00:23:51.216000
2023-08-29T21:11:31
2023-08-29T21:11:31
179,938,034
4
1
Apache-2.0
false
2022-06-25T22:47:19
2019-04-07T08:35:01
2022-03-26T06:04:12
2022-06-25T22:47:18
8,156
3
0
1
Roff
false
false
package irvine.oeis.a184; import irvine.factor.factor.Jaguar; import irvine.math.z.Integers; import irvine.math.z.Z; import irvine.oeis.Sequence1; /** * A184389 a(n) = Sum_{k=1..tau(n)} k, where tau is the number of divisors of n (A000005). * @author Georg Fischer */ public class A184389 extends Sequence1 { private long mN = 0; @Override public Z next() { ++mN; return Integers.SINGLETON.sum(1, Jaguar.factor(mN).tau().intValue(), k -> Z.valueOf(k)); } }
UTF-8
Java
480
java
A184389.java
Java
[ { "context": " the number of divisors of n (A000005).\n * @author Georg Fischer\n */\npublic class A184389 extends Sequence1 {\n\n p", "end": 268, "score": 0.9998351335525513, "start": 255, "tag": "NAME", "value": "Georg Fischer" } ]
null
[]
package irvine.oeis.a184; import irvine.factor.factor.Jaguar; import irvine.math.z.Integers; import irvine.math.z.Z; import irvine.oeis.Sequence1; /** * A184389 a(n) = Sum_{k=1..tau(n)} k, where tau is the number of divisors of n (A000005). * @author <NAME> */ public class A184389 extends Sequence1 { private long mN = 0; @Override public Z next() { ++mN; return Integers.SINGLETON.sum(1, Jaguar.factor(mN).tau().intValue(), k -> Z.valueOf(k)); } }
473
0.679167
0.625
21
21.857143
25.729889
92
false
false
0
0
0
0
0
0
0.52381
false
false
5
44f38a51de5c275d58da62f8afec5642913d58ba
28,217,935,197,247
4c534ebe75be127fda8ded84e13d493925cd9842
/spring-mvc/src/main/java/org/spring/validate/ValidUserBean.java
78500c7c73d14d70aa5247fbcaf486073f90c510
[]
no_license
hexiang/spring-tutorials
https://github.com/hexiang/spring-tutorials
cf8500538b90d03279e0d3b0f93a8d20745a1dd5
0a62a2e937a6fe9cf3469ee690817c900c50f516
refs/heads/master
2016-09-07T18:15:09.473000
2015-04-30T13:11:38
2015-04-30T13:11:38
34,448,101
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.spring.validate; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.stereotype.Component; @Component("ValidUserBean") public class ValidUserBean { @NotEmpty @Email private String account; @NotEmpty @Length(min = 6, max = 16) private String password; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UTF-8
Java
658
java
ValidUserBean.java
Java
[ { "context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n}\n", "end": 651, "score": 0.9138113260269165, "start": 643, "tag": "PASSWORD", "value": "password" } ]
null
[]
package org.spring.validate; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.stereotype.Component; @Component("ValidUserBean") public class ValidUserBean { @NotEmpty @Email private String account; @NotEmpty @Length(min = 6, max = 16) private String password; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } }
660
0.761398
0.756839
34
18.352942
17.310116
52
false
false
0
0
0
0
0
0
1
false
false
5
5788c49e44447b49ad1a65eebefc1f180d8950ad
14,370,960,612,775
19a4f044817858ae19b83bff388a37d4251891ed
/TCProblems/TheSwap.java.bak
5a9ab134e0fcc160c63e5d86f24c1385edc0fe07
[]
no_license
aajjbb/contest_files
https://github.com/aajjbb/contest_files
f238e8860d3efa6cefcc175880d626c7489a6385
304becded4dc04c6651d62750c5f5efd58e51bc4
refs/heads/master
2015-08-04T16:30:22.500000
2013-05-18T13:53:50
2013-05-18T13:53:50
6,805,432
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// BEGIN CUT HERE // PROBLEM STATEMENT // There is nothing more beautiful than just an integer number. You are given an integer n. Write down n in decimal notation with no leading zeroes, and let M be the number of written digits. Perform the following operation exactly k times: Choose two different 1-based positions, i and j, such that 1 &lt= i &lt j &lt= M. Swap the digits at positions i and j. This swap must not cause the resulting number to have a leading zero, i.e., if the digit at position j is zero, then i must be strictly greater than 1. Return the maximal possible number you can get at the end of this procedure. If it's not possible to perform k operations, return -1 instead. DEFINITION Class:TheSwap Method:findMax Parameters:int, int Returns:int Method signature:int findMax(int n, int k) CONSTRAINTS -n will be between 1 and 1,000,000, inclusive. -k will be between 1 and 10, inclusive. EXAMPLES 0) 16375 1 Returns: 76315 The optimal way is to swap 1 and 7. 1) 432 1 Returns: 423 In this case the result is less than the given number. 2) 90 4 Returns: -1 We can't make even a single operation because it would cause the resulting number to have a leading zero. 3) 5 2 Returns: -1 Here we can't choose two different positions for an operation. 4) 436659 2 Returns: 966354 // END CUT HERE import java.util.*; public class TheSwap { public int findMax(int n, int k) { } public static void main(String[] args) { TheSwap temp = new TheSwap(); System.out.println(temp.findMax(int n, int k)); } }
UTF-8
Java
1,643
bak
TheSwap.java.bak
Java
[]
null
[]
// BEGIN CUT HERE // PROBLEM STATEMENT // There is nothing more beautiful than just an integer number. You are given an integer n. Write down n in decimal notation with no leading zeroes, and let M be the number of written digits. Perform the following operation exactly k times: Choose two different 1-based positions, i and j, such that 1 &lt= i &lt j &lt= M. Swap the digits at positions i and j. This swap must not cause the resulting number to have a leading zero, i.e., if the digit at position j is zero, then i must be strictly greater than 1. Return the maximal possible number you can get at the end of this procedure. If it's not possible to perform k operations, return -1 instead. DEFINITION Class:TheSwap Method:findMax Parameters:int, int Returns:int Method signature:int findMax(int n, int k) CONSTRAINTS -n will be between 1 and 1,000,000, inclusive. -k will be between 1 and 10, inclusive. EXAMPLES 0) 16375 1 Returns: 76315 The optimal way is to swap 1 and 7. 1) 432 1 Returns: 423 In this case the result is less than the given number. 2) 90 4 Returns: -1 We can't make even a single operation because it would cause the resulting number to have a leading zero. 3) 5 2 Returns: -1 Here we can't choose two different positions for an operation. 4) 436659 2 Returns: 966354 // END CUT HERE import java.util.*; public class TheSwap { public int findMax(int n, int k) { } public static void main(String[] args) { TheSwap temp = new TheSwap(); System.out.println(temp.findMax(int n, int k)); } }
1,643
0.695679
0.65916
84
17.559525
40.536682
272
false
false
0
0
0
0
0
0
0.333333
false
false
5
27ff5811af74c1755a978c6b6b450852b283b61b
4,724,464,059,383
0d47a804d1f928b8f4288c28d97554d2f29dc4c1
/titus-supplementary-component/tasks-publisher/src/test/java/com/netflix/titus/supplementary/taskspublisher/TitusClientImplTest.java
243ea0661686552e333f8b57a7ac39af5681abc1
[ "Apache-2.0" ]
permissive
Jason-Cooke/titus-control-plane
https://github.com/Jason-Cooke/titus-control-plane
571df2aa3645a432b7a4e19cbd7a6c3182135046
b91046be364d916573b157de668a48db67b21f3f
refs/heads/master
2020-05-29T18:20:11.031000
2019-05-28T21:52:03
2019-05-28T21:52:03
189,296,449
1
0
Apache-2.0
true
2019-05-29T20:53:52
2019-05-29T20:53:52
2019-05-28T21:52:05
2019-05-28T21:52:04
8,524
0
0
0
null
false
false
package com.netflix.titus.supplementary.taskspublisher; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.titus.api.jobmanager.model.job.BatchJobTask; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.grpc.protogen.JobChangeNotification; import com.netflix.titus.grpc.protogen.JobId; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc.JobManagementServiceFutureStub; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc.JobManagementServiceStub; import com.netflix.titus.grpc.protogen.ObserveJobsQuery; import com.netflix.titus.grpc.protogen.Task; import com.netflix.titus.grpc.protogen.TaskId; import com.netflix.titus.runtime.endpoint.common.EmptyLogStorageInfo; import com.netflix.titus.runtime.endpoint.v3.grpc.V3GrpcModelConverters; import com.netflix.titus.testkit.model.job.JobGenerator; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; import io.grpc.stub.StreamObserver; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.fail; public class TitusClientImplTest { private static TitusClient titusClient; private static Server testServer; private static BatchJobTask taskOne = JobGenerator.oneBatchTask(); private static BatchJobTask taskTwo = JobGenerator.oneBatchTask(); private static BatchJobTask taskThree = JobGenerator.oneBatchTask(); private static BatchJobTask taskFour = JobGenerator.oneBatchTask(); private static BatchJobTask taskFive = JobGenerator.oneBatchTask(); private static Job<BatchJobExt> jobOne = JobGenerator.oneBatchJob(); public static class MockJobManagerService extends JobManagementServiceGrpc.JobManagementServiceImplBase { @Override public void findTask(TaskId request, StreamObserver<Task> responseObserver) { final Task grpcTask = V3GrpcModelConverters.toGrpcTask(taskOne, new EmptyLogStorageInfo<>()); responseObserver.onNext(grpcTask); responseObserver.onCompleted(); } @Override public void findJob(JobId request, StreamObserver<com.netflix.titus.grpc.protogen.Job> responseObserver) { final com.netflix.titus.grpc.protogen.Job grpcJob = V3GrpcModelConverters.toGrpcJob(jobOne); responseObserver.onNext(grpcJob); responseObserver.onCompleted(); } @Override public void observeJobs(ObserveJobsQuery request, StreamObserver<JobChangeNotification> responseObserver) { final List<BatchJobTask> batchJobTasks = Arrays.asList(taskOne, taskTwo, taskThree, taskFour, taskFive); batchJobTasks.forEach(task -> { final Task grpcTask = V3GrpcModelConverters.toGrpcTask(task, new EmptyLogStorageInfo<>()); responseObserver.onNext(buildJobChangeNotification(grpcTask)); }); responseObserver.onCompleted(); } private JobChangeNotification buildJobChangeNotification(Task task) { return JobChangeNotification.newBuilder() .setTaskUpdate(JobChangeNotification.TaskUpdate.newBuilder().setTask(task).build()) .build(); } } @Before public void setup() throws IOException { final MockJobManagerService mockJobManagerService = new MockJobManagerService(); testServer = InProcessServerBuilder .forName("testServer") .directExecutor() .addService(mockJobManagerService) .build() .start(); final ManagedChannel channel = InProcessChannelBuilder .forName("testServer") .directExecutor() .usePlaintext(true) .build(); final JobManagementServiceStub jobManagementServiceStub = JobManagementServiceGrpc.newStub(channel); final JobManagementServiceFutureStub jobManagementServiceFutureStub = JobManagementServiceGrpc.newFutureStub(channel); titusClient = new TitusClientImpl(jobManagementServiceStub, jobManagementServiceFutureStub, new DefaultRegistry()); } @After public void cleanup() { testServer.shutdownNow(); } @Test public void getTaskById() { final CountDownLatch latch = new CountDownLatch(1); titusClient.getTask(taskOne.getId()).subscribe(task -> { assertThat(task.getId()).isEqualTo(taskOne.getId()); assertThat(task.getJobId()).isEqualTo(taskOne.getJobId()); latch.countDown(); }); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("getTaskById Timeout ", e); } } @Test public void getJobById() { final CountDownLatch latch = new CountDownLatch(1); titusClient.getJobById(jobOne.getId()).subscribe(job -> { assertThat(job.getId()).isEqualTo(jobOne.getId()); latch.countDown(); }); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("getJobById Timeout ", e); } } @Test public void getTaskUpdates() { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger tasksCount = new AtomicInteger(0); titusClient.getTaskUpdates().subscribe(task -> { if (tasksCount.incrementAndGet() == 5) { latch.countDown(); } }, e -> fail("getTaskUpdates exception {}", e)); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("getTaskUpdates Timeout ", e); } } }
UTF-8
Java
6,255
java
TitusClientImplTest.java
Java
[]
null
[]
package com.netflix.titus.supplementary.taskspublisher; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.titus.api.jobmanager.model.job.BatchJobTask; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.grpc.protogen.JobChangeNotification; import com.netflix.titus.grpc.protogen.JobId; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc.JobManagementServiceFutureStub; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc.JobManagementServiceStub; import com.netflix.titus.grpc.protogen.ObserveJobsQuery; import com.netflix.titus.grpc.protogen.Task; import com.netflix.titus.grpc.protogen.TaskId; import com.netflix.titus.runtime.endpoint.common.EmptyLogStorageInfo; import com.netflix.titus.runtime.endpoint.v3.grpc.V3GrpcModelConverters; import com.netflix.titus.testkit.model.job.JobGenerator; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; import io.grpc.stub.StreamObserver; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.fail; public class TitusClientImplTest { private static TitusClient titusClient; private static Server testServer; private static BatchJobTask taskOne = JobGenerator.oneBatchTask(); private static BatchJobTask taskTwo = JobGenerator.oneBatchTask(); private static BatchJobTask taskThree = JobGenerator.oneBatchTask(); private static BatchJobTask taskFour = JobGenerator.oneBatchTask(); private static BatchJobTask taskFive = JobGenerator.oneBatchTask(); private static Job<BatchJobExt> jobOne = JobGenerator.oneBatchJob(); public static class MockJobManagerService extends JobManagementServiceGrpc.JobManagementServiceImplBase { @Override public void findTask(TaskId request, StreamObserver<Task> responseObserver) { final Task grpcTask = V3GrpcModelConverters.toGrpcTask(taskOne, new EmptyLogStorageInfo<>()); responseObserver.onNext(grpcTask); responseObserver.onCompleted(); } @Override public void findJob(JobId request, StreamObserver<com.netflix.titus.grpc.protogen.Job> responseObserver) { final com.netflix.titus.grpc.protogen.Job grpcJob = V3GrpcModelConverters.toGrpcJob(jobOne); responseObserver.onNext(grpcJob); responseObserver.onCompleted(); } @Override public void observeJobs(ObserveJobsQuery request, StreamObserver<JobChangeNotification> responseObserver) { final List<BatchJobTask> batchJobTasks = Arrays.asList(taskOne, taskTwo, taskThree, taskFour, taskFive); batchJobTasks.forEach(task -> { final Task grpcTask = V3GrpcModelConverters.toGrpcTask(task, new EmptyLogStorageInfo<>()); responseObserver.onNext(buildJobChangeNotification(grpcTask)); }); responseObserver.onCompleted(); } private JobChangeNotification buildJobChangeNotification(Task task) { return JobChangeNotification.newBuilder() .setTaskUpdate(JobChangeNotification.TaskUpdate.newBuilder().setTask(task).build()) .build(); } } @Before public void setup() throws IOException { final MockJobManagerService mockJobManagerService = new MockJobManagerService(); testServer = InProcessServerBuilder .forName("testServer") .directExecutor() .addService(mockJobManagerService) .build() .start(); final ManagedChannel channel = InProcessChannelBuilder .forName("testServer") .directExecutor() .usePlaintext(true) .build(); final JobManagementServiceStub jobManagementServiceStub = JobManagementServiceGrpc.newStub(channel); final JobManagementServiceFutureStub jobManagementServiceFutureStub = JobManagementServiceGrpc.newFutureStub(channel); titusClient = new TitusClientImpl(jobManagementServiceStub, jobManagementServiceFutureStub, new DefaultRegistry()); } @After public void cleanup() { testServer.shutdownNow(); } @Test public void getTaskById() { final CountDownLatch latch = new CountDownLatch(1); titusClient.getTask(taskOne.getId()).subscribe(task -> { assertThat(task.getId()).isEqualTo(taskOne.getId()); assertThat(task.getJobId()).isEqualTo(taskOne.getJobId()); latch.countDown(); }); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("getTaskById Timeout ", e); } } @Test public void getJobById() { final CountDownLatch latch = new CountDownLatch(1); titusClient.getJobById(jobOne.getId()).subscribe(job -> { assertThat(job.getId()).isEqualTo(jobOne.getId()); latch.countDown(); }); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("getJobById Timeout ", e); } } @Test public void getTaskUpdates() { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger tasksCount = new AtomicInteger(0); titusClient.getTaskUpdates().subscribe(task -> { if (tasksCount.incrementAndGet() == 5) { latch.countDown(); } }, e -> fail("getTaskUpdates exception {}", e)); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("getTaskUpdates Timeout ", e); } } }
6,255
0.696563
0.694165
151
40.417217
31.102129
126
false
false
0
0
0
0
0
0
0.642384
false
false
5
2150f1bdf7a72c2d659ef2374aa32fc695ee77a9
764,504,198,184
b24818a948152b06c7d85ac442e9b37cb6becbbc
/src/main/java/com/ash/experiments/performance/whitespace/Class9202.java
a9a534e4441ba8e3fe073bd3855cc5ecabde340f
[]
no_license
ajorpheus/whitespace-perf-test
https://github.com/ajorpheus/whitespace-perf-test
d0797b6aa3eea1435eaa1032612f0874537c58b8
d2b695aa09c6066fbba0aceb230fa4e308670b32
refs/heads/master
2020-04-17T23:38:39.420000
2014-06-02T09:27:17
2014-06-02T09:27:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Class9202 {}
UTF-8
Java
41
java
Class9202.java
Java
[]
null
[]
public class Class9202 {}
41
0.487805
0.390244
1
25
0
25
false
false
0
0
0
0
0
0
0
false
false
5
b9d7ab272f46b51abe242f746b7fb056daddf00e
12,309,376,289,865
8ca057f8667bc504534a5050cd0c456e883fbd73
/ResumeBuilder/src/edu/sollers/components/Membership.java
ff2d3b1dc8708927f8f0623c696f1ed94a081c4e
[]
no_license
darkerror96/semi-resume_builder
https://github.com/darkerror96/semi-resume_builder
ad6ddcdd5f82d6c9b8e50a9583cf4eedb63b850c
769f33100669f97fc9886456fd14cd620584e81e
refs/heads/master
2020-04-13T12:29:33.656000
2019-04-07T03:41:09
2019-04-07T03:41:09
163,203,801
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package edu.sollers.components; import java.sql.SQLException; import java.sql.Statement; import edu.sollers.mvc.ResumeElement; /** * @author Karanveer * */ public class Membership extends ResumeElement { private String membership; /** * Constructor with parameter * * @param membership String */ public Membership(String membership) { this.membership = membership; } // Static methods cannot be overridden public static String getTableName() { return "membership"; } public static String getFieldOrder() { return "membership"; } public static String getSelectClause() { return "select " + getFieldOrder() + " from " + getTableName(); } @Override public String getInsertStatement() { return "insert into " + getTableName() + " (" + getFieldOrder() + ") values ('" + membership + "')"; } @Override public void save() { try { Statement stmt = getConnection().createStatement(); int row = stmt.executeUpdate(getInsertStatement()); if (row == 1) System.out.println("Inserted membership object into table"); } catch (SQLException e) { e.printStackTrace(); } } /** * @return the membership */ public String getMembership() { return membership; } @Override public String toString() { return "Membership: " + membership + "\n"; } }
UTF-8
Java
1,393
java
Membership.java
Java
[ { "context": " edu.sollers.mvc.ResumeElement;\r\n\r\n/**\r\n * @author Karanveer\r\n *\r\n */\r\npublic class Membership extends ResumeE", "end": 177, "score": 0.8146959543228149, "start": 168, "tag": "USERNAME", "value": "Karanveer" } ]
null
[]
/** * */ package edu.sollers.components; import java.sql.SQLException; import java.sql.Statement; import edu.sollers.mvc.ResumeElement; /** * @author Karanveer * */ public class Membership extends ResumeElement { private String membership; /** * Constructor with parameter * * @param membership String */ public Membership(String membership) { this.membership = membership; } // Static methods cannot be overridden public static String getTableName() { return "membership"; } public static String getFieldOrder() { return "membership"; } public static String getSelectClause() { return "select " + getFieldOrder() + " from " + getTableName(); } @Override public String getInsertStatement() { return "insert into " + getTableName() + " (" + getFieldOrder() + ") values ('" + membership + "')"; } @Override public void save() { try { Statement stmt = getConnection().createStatement(); int row = stmt.executeUpdate(getInsertStatement()); if (row == 1) System.out.println("Inserted membership object into table"); } catch (SQLException e) { e.printStackTrace(); } } /** * @return the membership */ public String getMembership() { return membership; } @Override public String toString() { return "Membership: " + membership + "\n"; } }
1,393
0.638909
0.638191
70
17.9
20.451441
102
false
false
0
0
0
0
0
0
1.157143
false
false
5
babcf8eda0db7d8cbce9a9be31da3aff844faaf3
25,898,652,813,538
dc4c59cf270422f8be798dc3f802dca426702315
/CTCI-CH10/src/SortedMerge.java
dceecc142139ae35aee190e80af1e52eaedf4b03
[]
no_license
sanjanamanoj/CTCI
https://github.com/sanjanamanoj/CTCI
5b198960b549d03d9dac6befb8cf1945253332e4
2c8ab4c5f06b7cd0d1ff17f5dd0c4622ff3e00ef
refs/heads/master
2020-05-21T03:42:06.270000
2017-06-19T22:47:33
2017-06-19T22:47:33
84,566,545
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Created by sanjanamanojkumar on 6/19/17. */ public class SortedMerge { public static void merge(int[] a, int[] b,int lastA, int lastB) { int asize = lastA-1; int bsize = lastB-1; int mergedsize = lastA+lastB -1; while(bsize>=0) { if(asize>=0 && a[asize] > b[bsize]){ a[mergedsize] = a[asize]; asize--; mergedsize--; } else { a[mergedsize] = b[bsize]; bsize--; mergedsize--; } } } public static void main(String[] args){ int[] a = new int[10]; a[0] = 2; a[1] = 5; a[2] = 7; a[3] = 8; int[] b = {1,3,4,6,9,10}; merge(a,b,4,6); for(int i :a) { System.out.println(i); } } }
UTF-8
Java
875
java
SortedMerge.java
Java
[ { "context": "/**\n * Created by sanjanamanojkumar on 6/19/17.\n */\npublic class SortedMerge {\n\n p", "end": 35, "score": 0.9939630627632141, "start": 18, "tag": "USERNAME", "value": "sanjanamanojkumar" } ]
null
[]
/** * Created by sanjanamanojkumar on 6/19/17. */ public class SortedMerge { public static void merge(int[] a, int[] b,int lastA, int lastB) { int asize = lastA-1; int bsize = lastB-1; int mergedsize = lastA+lastB -1; while(bsize>=0) { if(asize>=0 && a[asize] > b[bsize]){ a[mergedsize] = a[asize]; asize--; mergedsize--; } else { a[mergedsize] = b[bsize]; bsize--; mergedsize--; } } } public static void main(String[] args){ int[] a = new int[10]; a[0] = 2; a[1] = 5; a[2] = 7; a[3] = 8; int[] b = {1,3,4,6,9,10}; merge(a,b,4,6); for(int i :a) { System.out.println(i); } } }
875
0.4
0.366857
38
22.026316
15.825507
69
false
false
0
0
0
0
0
0
0.736842
false
false
5
0e5194801d13ea6c4b8f31b2b90ec744734015a0
17,686,675,355,110
f7bfa6fbef612a82f210f46b36a97054c476c1e8
/src/main/java/BrowserManager/FireFoxDriverManager.java
927f51f6bec5508ca4449dc71684e291ebe3177a
[]
no_license
svantu/testFramework
https://github.com/svantu/testFramework
6895a6f95190846df3577b6e0dc37b160bd90843
f83a57fb2502cd95769b024e266aa75600e68b22
refs/heads/master
2020-04-30T17:47:31.103000
2019-03-21T17:10:02
2019-03-21T17:10:02
176,990,514
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BrowserManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FireFoxDriverManager implements DriverManager{ private WebDriver driver; public WebDriver getDriver() { System.setProperty("webdriver.gecko.driver", ".\\src\\test\\resources\\Drivers\\geckodriver.exe"); driver=new FirefoxDriver(); return driver; } }
UTF-8
Java
389
java
FireFoxDriverManager.java
Java
[]
null
[]
package BrowserManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FireFoxDriverManager implements DriverManager{ private WebDriver driver; public WebDriver getDriver() { System.setProperty("webdriver.gecko.driver", ".\\src\\test\\resources\\Drivers\\geckodriver.exe"); driver=new FirefoxDriver(); return driver; } }
389
0.781491
0.781491
16
23.3125
27.183908
100
false
false
0
0
0
0
0
0
1.0625
false
false
12
bd26fff902ad3ddb6526c0787906bc1e42dd7b8f
10,952,166,669,651
16c2692a7b99e53771b9a9908848cabf4c3f4d7d
/CS5800/src/java/Model/PathFinder.java
a9cef2613ba042ff1acd6e2eacd053ad1f2dc654
[]
no_license
mynameislich/software_engr
https://github.com/mynameislich/software_engr
d55c0e22f01f3fad47fea1d85c8c5ec5630a5724
35321f564d0ff48a36bc0dcec6305f044fe1cbab
refs/heads/master
2020-12-31T06:55:40.657000
2017-05-05T23:20:36
2017-05-05T23:20:36
80,568,255
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 Model; import java.util.ArrayList; import java.util.List; import Model.PathNode; import dao.FlightDataAccess; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * * @author LICH */ public class PathFinder { // import time type then do time operation properly ArrayList<PathNode> m_allPath = new ArrayList(); ArrayList<PathNode> m_results = new ArrayList(); public PathFinder(Date time) throws ParseException { ArrayList<PathNode> allPath = new ArrayList(); FlightDataAccess da = new FlightDataAccess(); List flights = da.getAll(); for (Object each : flights) { Flight temp = (Flight) each; if (temp.getDepartingTime().after(time)) { allPath.add(new PathNode(temp.origin, temp.destination)); } else { System.out.println(temp.getDepartingTime()); } } Map<String, List<String>> formatting = new HashMap(); for (Object each : allPath) { PathNode temp = (PathNode) each; if (!formatting.containsKey(temp.m_first)) { formatting.put(temp.m_first, temp.m_second); } else { List<String> AddingList = temp.m_second; List<String> OriginalList = formatting.get(temp.m_first); for (String itr : AddingList) { if (!OriginalList.contains(itr)) { OriginalList.add(itr); } } formatting.put(temp.m_first, OriginalList); } } for (String itr : formatting.keySet()) { m_allPath.add(new PathNode(itr, formatting.get(itr))); } } public List<PathNode> getList() { return this.m_allPath; } public List Caculator2way(String from, String to, String departTime, String returnTime) throws ParseException { List result; result = Caculator1way(from, to, departTime); // List temp =Caculator1way(to, from, returnTime); result.addAll(Caculator1way(to, from, returnTime)); return result; } public List Caculator1way(String from, String to, String departTime) throws ParseException { List result = new ArrayList(); DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); //DateFormat format = null; PathFinder PF = new PathFinder(format.parse(departTime)); List<PathNode> list = PF.getList(); for (int i = 0; i < PF.m_allPath.size(); i++) { if (list.get(i).m_first.equals(from)) { HashMap input = new HashMap(); result = PF.Finding((ArrayList) list, list.get(i), to, input); } } return result; } public List<PathNode> Finding(ArrayList<PathNode> thePathes, PathNode thisOne, String target, HashMap theVisited) { List result = new ArrayList(); //System.out.println(thisOne.m_first); if (theVisited.containsKey(thisOne.m_first)) { return result; } else { theVisited.put(thisOne.m_first, 1); result.add(thisOne); for (Object each : thePathes) { PathNode temp = (PathNode) each; if (temp.m_first.equals(thisOne.m_first)) { temp.visit(); each = temp; for (Object itr : thisOne.m_second) { List<PathNode> got; for (Object itr2 : thePathes) { PathNode it = (PathNode) itr2; if (it.m_first.equals(itr)) { got = Finding(thePathes, it, target, theVisited); if (!got.isEmpty()) { for (int i = 0; i < got.size(); i++) { result.add(got.get(i)); } result.add(thisOne); } } } if (itr.equals(target)) { //theVisited.put(thisOne.m_first, 1); //result.add(thisOne); result.add(new PathNode(target, new ArrayList())); //return result; } } } } } return result; } public static void main(String[] args) throws ParseException { PathFinder PF = new PathFinder(new Date()); List<PathNode> list = PF.getList(); List<PathNode> result = new ArrayList(); HashMap input = new HashMap(); for (int i = 0; i < PF.m_allPath.size(); i++) { if (list.get(i).m_first.equals("GGWP")) { result.addAll(PF.Finding((ArrayList) list, list.get(i), "BA", input)); } } for (int i = 0; i < result.size(); i++) { System.out.println(i); System.out.println(result.get(i).m_first); } } }
UTF-8
Java
5,612
java
PathFinder.java
Java
[ { "context": "Map;\r\nimport java.util.Map;\r\n\r\n/**\r\n *\r\n * @author LICH\r\n */\r\npublic class PathFinder {\r\n// import time t", "end": 515, "score": 0.9995609521865845, "start": 511, "tag": "USERNAME", "value": "LICH" } ]
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 Model; import java.util.ArrayList; import java.util.List; import Model.PathNode; import dao.FlightDataAccess; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * * @author LICH */ public class PathFinder { // import time type then do time operation properly ArrayList<PathNode> m_allPath = new ArrayList(); ArrayList<PathNode> m_results = new ArrayList(); public PathFinder(Date time) throws ParseException { ArrayList<PathNode> allPath = new ArrayList(); FlightDataAccess da = new FlightDataAccess(); List flights = da.getAll(); for (Object each : flights) { Flight temp = (Flight) each; if (temp.getDepartingTime().after(time)) { allPath.add(new PathNode(temp.origin, temp.destination)); } else { System.out.println(temp.getDepartingTime()); } } Map<String, List<String>> formatting = new HashMap(); for (Object each : allPath) { PathNode temp = (PathNode) each; if (!formatting.containsKey(temp.m_first)) { formatting.put(temp.m_first, temp.m_second); } else { List<String> AddingList = temp.m_second; List<String> OriginalList = formatting.get(temp.m_first); for (String itr : AddingList) { if (!OriginalList.contains(itr)) { OriginalList.add(itr); } } formatting.put(temp.m_first, OriginalList); } } for (String itr : formatting.keySet()) { m_allPath.add(new PathNode(itr, formatting.get(itr))); } } public List<PathNode> getList() { return this.m_allPath; } public List Caculator2way(String from, String to, String departTime, String returnTime) throws ParseException { List result; result = Caculator1way(from, to, departTime); // List temp =Caculator1way(to, from, returnTime); result.addAll(Caculator1way(to, from, returnTime)); return result; } public List Caculator1way(String from, String to, String departTime) throws ParseException { List result = new ArrayList(); DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); //DateFormat format = null; PathFinder PF = new PathFinder(format.parse(departTime)); List<PathNode> list = PF.getList(); for (int i = 0; i < PF.m_allPath.size(); i++) { if (list.get(i).m_first.equals(from)) { HashMap input = new HashMap(); result = PF.Finding((ArrayList) list, list.get(i), to, input); } } return result; } public List<PathNode> Finding(ArrayList<PathNode> thePathes, PathNode thisOne, String target, HashMap theVisited) { List result = new ArrayList(); //System.out.println(thisOne.m_first); if (theVisited.containsKey(thisOne.m_first)) { return result; } else { theVisited.put(thisOne.m_first, 1); result.add(thisOne); for (Object each : thePathes) { PathNode temp = (PathNode) each; if (temp.m_first.equals(thisOne.m_first)) { temp.visit(); each = temp; for (Object itr : thisOne.m_second) { List<PathNode> got; for (Object itr2 : thePathes) { PathNode it = (PathNode) itr2; if (it.m_first.equals(itr)) { got = Finding(thePathes, it, target, theVisited); if (!got.isEmpty()) { for (int i = 0; i < got.size(); i++) { result.add(got.get(i)); } result.add(thisOne); } } } if (itr.equals(target)) { //theVisited.put(thisOne.m_first, 1); //result.add(thisOne); result.add(new PathNode(target, new ArrayList())); //return result; } } } } } return result; } public static void main(String[] args) throws ParseException { PathFinder PF = new PathFinder(new Date()); List<PathNode> list = PF.getList(); List<PathNode> result = new ArrayList(); HashMap input = new HashMap(); for (int i = 0; i < PF.m_allPath.size(); i++) { if (list.get(i).m_first.equals("GGWP")) { result.addAll(PF.Finding((ArrayList) list, list.get(i), "BA", input)); } } for (int i = 0; i < result.size(); i++) { System.out.println(i); System.out.println(result.get(i).m_first); } } }
5,612
0.503742
0.501426
150
35.413334
25.199785
119
false
false
0
0
0
0
0
0
0.72
false
false
12
23ca12e1dbd1d17e993a42721e59728c5ea2ad87
12,068,858,132,032
a79f58ee99f4f502973678b415d8f2e4bc995ab3
/CrackingTheCodingInterview/src/Chapter4/Question6.java
931fdfc2ec73789290082d20092db104d1a7aa53
[]
no_license
SmileEye/cc150
https://github.com/SmileEye/cc150
4b8db018783510c958f980201e1dc10407fad36b
045a32fa383eedfef0fbc21dfb39914f53c0aac3
refs/heads/master
2016-08-04T20:53:24.391000
2014-11-09T04:16:21
2014-11-09T04:16:21
26,382,628
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Chapter4; /** *找出二叉树中指定节点的中序后继节点 * */ public class Question6 { public TreeNode find(TreeNode root){ if(root==null){ return null; } if(root.right!=null){ return getLeft(root.right); } TreeNode parent = root.parent; while(parent.left!=root&&parent!=null){ root = parent; parent = root.parent; } return parent; } public TreeNode getLeft(TreeNode root){ if(root==null){ return root; } while(root.left!=null){ root = root.left; } return root; } }
UTF-8
Java
569
java
Question6.java
Java
[]
null
[]
package Chapter4; /** *找出二叉树中指定节点的中序后继节点 * */ public class Question6 { public TreeNode find(TreeNode root){ if(root==null){ return null; } if(root.right!=null){ return getLeft(root.right); } TreeNode parent = root.parent; while(parent.left!=root&&parent!=null){ root = parent; parent = root.parent; } return parent; } public TreeNode getLeft(TreeNode root){ if(root==null){ return root; } while(root.left!=null){ root = root.left; } return root; } }
569
0.601869
0.598131
31
15.258064
12.17869
41
false
false
0
0
0
0
0
0
1.903226
false
false
12
17e0005a23470290558b1c7985d9ba67d593c95b
21,560,735,846,133
a49bd905475cbc7905cf5ac1a66717339548bae2
/Shift/src/persistence/dao/impl/AssetDAO.java
e27b990d05709a4b40f6344eb8439529ce242815
[]
no_license
Lightcyan21/shift
https://github.com/Lightcyan21/shift
0eb6f0387a6f53d971cfcfbf10c7d97f7a01a604
7d9be0e96c673f4110cd183b1922b73823fecdd7
refs/heads/master
2020-06-03T16:02:52.284000
2015-04-12T22:37:42
2015-04-12T22:37:42
30,933,981
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package persistence.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.mysql.jdbc.Statement; import persistence.DBUtil; import persistence.dao.AbstractDAO; import persistence.dao.DAO; import persistence.entity.impl.Asset; public class AssetDAO extends AbstractDAO<Asset> implements DAO<Asset> { @Override public Asset create() { Asset asset = new Asset(); int key = 0; Connection con; con = DBUtil.getConnection(); try { PreparedStatement pre; pre = con .prepareStatement( "insert into asset (einzelpreis, bezeichnung) values (?, ?);", Statement.RETURN_GENERATED_KEYS); pre.setDouble(1, 0); pre.setString(2, null); pre.execute(); ResultSet rs = pre.getGeneratedKeys(); if (rs != null && rs.next()) { key = rs.getInt(1); } asset.setId((long) key); } catch (SQLException e) { e.printStackTrace(); } return asset; } @Override public void delete(Asset entity) { Connection con; con = DBUtil.getConnection(); try { PreparedStatement pre; pre = con.prepareStatement("delete from asset where assetID = ?;"); pre.setLong(1, entity.getId()); pre.execute(); } catch (SQLException e) { e.printStackTrace(); } } @Override public List<Asset> findAll() { Connection con; con = DBUtil.getConnection(); List<Asset> assetList = new ArrayList<>(); try { PreparedStatement pre; pre = con.prepareStatement("select * from asset"); ResultSet result = pre.executeQuery(); while (result.next()) { Asset asset = new Asset(); asset.setId(result.getLong("assetID")); asset.setBillID(result.getInt("billID")); asset.setEinzelpreis(result.getDouble("einzelpreis")); asset.setBezeichnung(result.getString("bezeichnung")); assetList.add(asset); } } catch (SQLException e) { e.printStackTrace(); } if (assetList.size() != 0) { return assetList; } else { return null; } } @Override public Asset getById(long id) { Connection con; con = DBUtil.getConnection(); Asset asset = new Asset(); try { PreparedStatement pre; pre = con.prepareStatement("select * from asset where assetID =?;"); pre.setDouble(1, (int) id); ResultSet result = pre.executeQuery(); while (result.next()) { asset.setId(result.getLong("assetID")); asset.setBillID(result.getInt("billID")); asset.setEinzelpreis(result.getDouble("einzelpreis")); asset.setBezeichnung(result.getString("bezeichnung")); } } catch (SQLException e) { e.printStackTrace(); } if (asset.getId() != 0) { return asset; } else { return null; } } @Override public boolean persist(Asset entity) { boolean rt = false; Connection con = DBUtil.getConnection(); try { PreparedStatement pre; pre = con .prepareStatement("update asset SET assetID = ?, billID = ?, einzelpreis = ?, bezeichnung = ? WHERE assetID = ?;"); pre.setLong(1, entity.getId()); pre.setInt(2, entity.getBillID()); pre.setDouble(3, entity.getEinzelpreis()); pre.setString(4, entity.getBezeichnung()); pre.setLong(5, entity.getId()); if (entity.getId() != 0 && entity.getBillID() != 0 && entity.getEinzelpreis() != 0 && entity.getBezeichnung() != null) { pre.executeUpdate(); rt = true; } else { rt = false; } } catch (SQLException e) { e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return rt; } @Override public void reload(Asset entity) { } @Override public void detach(Asset entity) { } @Override public void flush() { } }
UTF-8
Java
3,787
java
AssetDAO.java
Java
[]
null
[]
package persistence.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.mysql.jdbc.Statement; import persistence.DBUtil; import persistence.dao.AbstractDAO; import persistence.dao.DAO; import persistence.entity.impl.Asset; public class AssetDAO extends AbstractDAO<Asset> implements DAO<Asset> { @Override public Asset create() { Asset asset = new Asset(); int key = 0; Connection con; con = DBUtil.getConnection(); try { PreparedStatement pre; pre = con .prepareStatement( "insert into asset (einzelpreis, bezeichnung) values (?, ?);", Statement.RETURN_GENERATED_KEYS); pre.setDouble(1, 0); pre.setString(2, null); pre.execute(); ResultSet rs = pre.getGeneratedKeys(); if (rs != null && rs.next()) { key = rs.getInt(1); } asset.setId((long) key); } catch (SQLException e) { e.printStackTrace(); } return asset; } @Override public void delete(Asset entity) { Connection con; con = DBUtil.getConnection(); try { PreparedStatement pre; pre = con.prepareStatement("delete from asset where assetID = ?;"); pre.setLong(1, entity.getId()); pre.execute(); } catch (SQLException e) { e.printStackTrace(); } } @Override public List<Asset> findAll() { Connection con; con = DBUtil.getConnection(); List<Asset> assetList = new ArrayList<>(); try { PreparedStatement pre; pre = con.prepareStatement("select * from asset"); ResultSet result = pre.executeQuery(); while (result.next()) { Asset asset = new Asset(); asset.setId(result.getLong("assetID")); asset.setBillID(result.getInt("billID")); asset.setEinzelpreis(result.getDouble("einzelpreis")); asset.setBezeichnung(result.getString("bezeichnung")); assetList.add(asset); } } catch (SQLException e) { e.printStackTrace(); } if (assetList.size() != 0) { return assetList; } else { return null; } } @Override public Asset getById(long id) { Connection con; con = DBUtil.getConnection(); Asset asset = new Asset(); try { PreparedStatement pre; pre = con.prepareStatement("select * from asset where assetID =?;"); pre.setDouble(1, (int) id); ResultSet result = pre.executeQuery(); while (result.next()) { asset.setId(result.getLong("assetID")); asset.setBillID(result.getInt("billID")); asset.setEinzelpreis(result.getDouble("einzelpreis")); asset.setBezeichnung(result.getString("bezeichnung")); } } catch (SQLException e) { e.printStackTrace(); } if (asset.getId() != 0) { return asset; } else { return null; } } @Override public boolean persist(Asset entity) { boolean rt = false; Connection con = DBUtil.getConnection(); try { PreparedStatement pre; pre = con .prepareStatement("update asset SET assetID = ?, billID = ?, einzelpreis = ?, bezeichnung = ? WHERE assetID = ?;"); pre.setLong(1, entity.getId()); pre.setInt(2, entity.getBillID()); pre.setDouble(3, entity.getEinzelpreis()); pre.setString(4, entity.getBezeichnung()); pre.setLong(5, entity.getId()); if (entity.getId() != 0 && entity.getBillID() != 0 && entity.getEinzelpreis() != 0 && entity.getBezeichnung() != null) { pre.executeUpdate(); rt = true; } else { rt = false; } } catch (SQLException e) { e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return rt; } @Override public void reload(Asset entity) { } @Override public void detach(Asset entity) { } @Override public void flush() { } }
3,787
0.649855
0.645366
201
17.840796
18.835358
120
false
false
0
0
0
0
0
0
2.154229
false
false
12
01d7663100b66554ce49b7cef095a164d65e16e4
25,941,602,525,261
d9f4e4d624c3929e76e482df64656805424c9e07
/src/com/lsm/spring5_aop/jdkproxy/ProxyTest.java
d05b6b8e546dd216befe0e8b6345e280122c8f10
[]
no_license
pigjw/spring_kj_demo
https://github.com/pigjw/spring_kj_demo
a2b7e18beabb140bdfc14dc94dd6cfa03531d78f
fb530454a205555e12ceb6ad504e15d78eb78b58
refs/heads/master
2023-03-05T14:12:58.530000
2021-02-03T04:40:25
2021-02-03T04:40:25
334,051,181
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lsm.spring5_aop.jdkproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * JDK动态代理举例 */ //接口 interface Human{ String getBelief(); void eat(String food); } //aop要做的事情 class HumanUtile{ public void previousAop(){ System.out.println("切面前置事情"); } public void afterAop(){ System.out.println("切面后置事情"); } } //被代理类 class SuperMan implements Human { @Override public String getBelief() { return "I believe I can fly"; } @Override public void eat(String food) { System.out.println("我喜欢吃" + food); } } /** * 1.如何根据加载到内存中被代理类,动态的创建一个代理类及其对象 * * 2.当通过代理类调用这个方法时,如何动态去调用被代理类的同名方法 * */ class ProxyFactory{ /** * obj:加载到内存中的代理类 * 调用此方法返回一个代理类对象 */ public static Object getProxyInstance(Object obj){ return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MyInvocationHandler(obj)); } } class MyInvocationHandler implements InvocationHandler{ private Object obj; public MyInvocationHandler(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HumanUtile humanUtile = new HumanUtile(); humanUtile.previousAop(); //代理类对象调用的方法 一个会直接输出| 我喜欢吃四川麻辣烫 一个返回|I believe I can fly Object returnValue = method.invoke(obj,args); //上述方法的返回值就作为invoke方法的返回值 System.out.println("returnValue|"+returnValue); humanUtile.afterAop(); return returnValue; } } public class ProxyTest { public static void main(String[] args) { SuperMan superMan = new SuperMan(); // proxyInstance: 拿到的代理类对象 Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); // proxyInstance调用eat()方法时会取调用invoke方法 proxyInstance.eat("四川麻辣烫"); proxyInstance.getBelief(); } }
UTF-8
Java
2,377
java
ProxyTest.java
Java
[]
null
[]
package com.lsm.spring5_aop.jdkproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * JDK动态代理举例 */ //接口 interface Human{ String getBelief(); void eat(String food); } //aop要做的事情 class HumanUtile{ public void previousAop(){ System.out.println("切面前置事情"); } public void afterAop(){ System.out.println("切面后置事情"); } } //被代理类 class SuperMan implements Human { @Override public String getBelief() { return "I believe I can fly"; } @Override public void eat(String food) { System.out.println("我喜欢吃" + food); } } /** * 1.如何根据加载到内存中被代理类,动态的创建一个代理类及其对象 * * 2.当通过代理类调用这个方法时,如何动态去调用被代理类的同名方法 * */ class ProxyFactory{ /** * obj:加载到内存中的代理类 * 调用此方法返回一个代理类对象 */ public static Object getProxyInstance(Object obj){ return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MyInvocationHandler(obj)); } } class MyInvocationHandler implements InvocationHandler{ private Object obj; public MyInvocationHandler(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HumanUtile humanUtile = new HumanUtile(); humanUtile.previousAop(); //代理类对象调用的方法 一个会直接输出| 我喜欢吃四川麻辣烫 一个返回|I believe I can fly Object returnValue = method.invoke(obj,args); //上述方法的返回值就作为invoke方法的返回值 System.out.println("returnValue|"+returnValue); humanUtile.afterAop(); return returnValue; } } public class ProxyTest { public static void main(String[] args) { SuperMan superMan = new SuperMan(); // proxyInstance: 拿到的代理类对象 Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); // proxyInstance调用eat()方法时会取调用invoke方法 proxyInstance.eat("四川麻辣烫"); proxyInstance.getBelief(); } }
2,377
0.658013
0.656515
87
22.022989
23.324781
133
false
false
0
0
0
0
0
0
0.356322
false
false
12
23ca436f946815d9fe973af3214c28c240d9bfff
4,080,218,951,344
47eced13dbbe30bd13bb4008f01c8471aabd9cb3
/src/main/java/com/szucsatti/kata/gildedrose/strategy/StandardUpdateStrategy.java
82b31e5fef39a0f624845634f7f51a18cd931bf2
[]
no_license
szucsatti/kata
https://github.com/szucsatti/kata
4a10fa4462560e91cc122fa400e39f609865a95c
3b3575e5eaf03bbf92effe7a018adfe56b38e3ba
refs/heads/master
2021-01-20T04:36:22.291000
2017-05-03T17:21:19
2017-05-03T17:21:19
89,702,950
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.szucsatti.kata.gildedrose.strategy; import com.szucsatti.kata.gildedrose.Item; public class StandardUpdateStrategy implements UpdateStrategy{ @Override public void updateQuality(final Item item) { int actualQuality = item.getQuality(); int qualityDecrease = item.getSellIn() >= 0 ? 1 : 2; item.setQuality(Math.max(actualQuality - qualityDecrease, 0)); item.decreaseSellIn(); } }
UTF-8
Java
419
java
StandardUpdateStrategy.java
Java
[]
null
[]
package com.szucsatti.kata.gildedrose.strategy; import com.szucsatti.kata.gildedrose.Item; public class StandardUpdateStrategy implements UpdateStrategy{ @Override public void updateQuality(final Item item) { int actualQuality = item.getQuality(); int qualityDecrease = item.getSellIn() >= 0 ? 1 : 2; item.setQuality(Math.max(actualQuality - qualityDecrease, 0)); item.decreaseSellIn(); } }
419
0.739857
0.73031
14
27.928572
24.223555
64
false
false
0
0
0
0
0
0
1.285714
false
false
12
9de6b0a8a6685e0b944bd9ace3fbd2aff4bb9dda
4,080,218,953,624
c0d2ab8270221571d1cba6b628c97ee66efebfff
/src/de/syscy/kagecore/factory/entity/EntityFactory.java
a69b9b71749f2247629b4f98bc2bab2ce10a3dc2
[ "MIT" ]
permissive
Kage0x3B/KageCore
https://github.com/Kage0x3B/KageCore
ead33cef8004b8579143db4b249bb2424734f2a5
e7b7bb220020b6d76594bc37b3fdb7663ba3d2dc
refs/heads/master
2022-03-16T15:46:34.922000
2022-02-25T13:36:46
2022-02-25T13:36:46
69,486,173
4
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.syscy.kagecore.factory.entity; import de.syscy.kagecore.event.SpawnTemplateEntityEvent; import de.syscy.kagecore.factory.AbstractFactory; import de.syscy.kagecore.factory.IFactoryProviderPlugin; import de.syscy.kagecore.factory.IFactoryTemplate; import de.syscy.kagecore.versioncompat.VersionCompatClassLoader; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.metadata.FixedMetadataValue; import java.io.File; public class EntityFactory extends AbstractFactory<Entity> implements IEntityFactory { private final @Getter IFactoryProviderPlugin plugin; private final EntityFactoryNMS entityFactoryNMS; public EntityFactory(IFactoryProviderPlugin plugin) { this.plugin = plugin; entityFactoryNMS = VersionCompatClassLoader.loadClass(EntityFactoryNMS.class); } @Override public void loadTemplates() { loadTemplates(new File(plugin.getDataFolder(), "entityTemplates"), "aet"); } @Override public Entity create(String templateName, Location location) { if(templateName == null || templateName.isEmpty()) { return null; } IEntityTemplate template = (IEntityTemplate) templates.get(templateName.toLowerCase()); if(template == null) { EntityType entityType = EntityType.valueOf(templateName.toUpperCase()); Entity entity = location.getWorld().spawnEntity(location, entityType); entity.setMetadata("templateName", new FixedMetadataValue(plugin, templateName.toLowerCase())); Bukkit.getPluginManager().callEvent(new SpawnTemplateEntityEvent(entity, location, null, templateName)); return entity; } try { Entity entity = template.create(location); Bukkit.getPluginManager().callEvent(new SpawnTemplateEntityEvent(entity, location, null, templateName)); return entity; } catch(Exception ex) { ex.printStackTrace(); } return null; } @Override protected IFactoryTemplate<Entity> createTemplate() { return new EntityTemplate(entityFactoryNMS); } }
UTF-8
Java
2,109
java
EntityFactory.java
Java
[]
null
[]
package de.syscy.kagecore.factory.entity; import de.syscy.kagecore.event.SpawnTemplateEntityEvent; import de.syscy.kagecore.factory.AbstractFactory; import de.syscy.kagecore.factory.IFactoryProviderPlugin; import de.syscy.kagecore.factory.IFactoryTemplate; import de.syscy.kagecore.versioncompat.VersionCompatClassLoader; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.metadata.FixedMetadataValue; import java.io.File; public class EntityFactory extends AbstractFactory<Entity> implements IEntityFactory { private final @Getter IFactoryProviderPlugin plugin; private final EntityFactoryNMS entityFactoryNMS; public EntityFactory(IFactoryProviderPlugin plugin) { this.plugin = plugin; entityFactoryNMS = VersionCompatClassLoader.loadClass(EntityFactoryNMS.class); } @Override public void loadTemplates() { loadTemplates(new File(plugin.getDataFolder(), "entityTemplates"), "aet"); } @Override public Entity create(String templateName, Location location) { if(templateName == null || templateName.isEmpty()) { return null; } IEntityTemplate template = (IEntityTemplate) templates.get(templateName.toLowerCase()); if(template == null) { EntityType entityType = EntityType.valueOf(templateName.toUpperCase()); Entity entity = location.getWorld().spawnEntity(location, entityType); entity.setMetadata("templateName", new FixedMetadataValue(plugin, templateName.toLowerCase())); Bukkit.getPluginManager().callEvent(new SpawnTemplateEntityEvent(entity, location, null, templateName)); return entity; } try { Entity entity = template.create(location); Bukkit.getPluginManager().callEvent(new SpawnTemplateEntityEvent(entity, location, null, templateName)); return entity; } catch(Exception ex) { ex.printStackTrace(); } return null; } @Override protected IFactoryTemplate<Entity> createTemplate() { return new EntityTemplate(entityFactoryNMS); } }
2,109
0.761498
0.761498
68
29.044117
30.602976
107
false
false
0
0
0
0
0
0
1.676471
false
false
12
c7df4db77d785c2e0c7b39a29d4277af3e7ed4b9
36,679,020,735,178
6ede244cca659dc54c796f382677215b7f9f62da
/src/main/java/com/itcat/mix/Maina.java
4ab6f1f079c6952d7790fad8199aa2ae4674cfe7
[]
no_license
zcgicom/learning
https://github.com/zcgicom/learning
acac736dd239868ce76e011b7e50dcbe89e58ea8
9bde6e613ceb691df36429b9f1ade69802bbcd92
refs/heads/master
2023-07-12T01:39:56.400000
2021-03-31T07:46:39
2021-03-31T07:46:39
282,669,523
0
0
null
false
2021-08-13T15:39:15
2020-07-26T14:43:11
2021-03-31T08:17:41
2021-08-13T15:39:14
1,577
0
0
1
Java
false
false
package com.itcat.mix; import java.util.Scanner; import java.util.Stack; public class Maina { public static boolean isValidString(String str){ Stack<Character> stack = new Stack<Character>(); for (char ch:str.toCharArray()) { if (ch == ')'||ch == ']'||ch == '}'){ if (stack.peek() == '('&&ch == ')'||stack.peek() == '{'&&ch == '}'||stack.peek() == '['&&ch == ']'){ stack.pop(); continue; } } stack.push(ch); } return stack.isEmpty(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ System.out.println(isValidString(sc.next())); } } }
UTF-8
Java
784
java
Maina.java
Java
[]
null
[]
package com.itcat.mix; import java.util.Scanner; import java.util.Stack; public class Maina { public static boolean isValidString(String str){ Stack<Character> stack = new Stack<Character>(); for (char ch:str.toCharArray()) { if (ch == ')'||ch == ']'||ch == '}'){ if (stack.peek() == '('&&ch == ')'||stack.peek() == '{'&&ch == '}'||stack.peek() == '['&&ch == ']'){ stack.pop(); continue; } } stack.push(ch); } return stack.isEmpty(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ System.out.println(isValidString(sc.next())); } } }
784
0.469388
0.469388
28
27
24.779024
116
false
false
0
0
0
0
0
0
0.642857
false
false
12
b989e293580f5466c7a76cdd3b933669394298b1
36,361,193,154,866
ee325b79d02fdf9f5204fbb9d93bf38190856d37
/src/tools/gnzlz/database/query/model/builder/data/GWhere.java
cee21c32fa90e173c13398ff5e909e64d92fe9b9
[ "MIT" ]
permissive
enyelbos/GnzlzDBModel
https://github.com/enyelbos/GnzlzDBModel
c50143a6cf4d4acc0b47d9a642b2b72f0c4d53e5
b489d7e6564b62b75467398b565366f82740ffdf
refs/heads/main
2023-05-07T23:09:20.211000
2022-12-31T03:33:58
2022-12-31T03:33:58
368,015,311
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tools.gnzlz.database.query.model.builder.data; import java.util.ArrayList; import tools.gnzlz.database.query.model.builder.IWhere; import tools.gnzlz.database.query.model.builder.Query; public class GWhere { private boolean priority = true; private boolean isAND = priority; private boolean isNOT; private ArrayList<Object> wheres; private Object col; public GWhere(Object col) { this.col = col; } /*************************** * AND - OR - NOT ***************************/ public void priority(boolean priority) { this.priority = priority; } public void priorityOR() { priority(false); } public void priorityAND() { priority(true); } public void AND() { isAND = true; } public void OR() { isAND = false; } public void NOT() { isNOT = true; } public boolean isAND() { boolean is = isAND; isAND = priority; return is; } public boolean isNOT() { boolean is = isNOT; isNOT = false; return is; } private void addIsAND() { if(!wheres().isEmpty()) if(isAND()) wheres().add("AND"); else wheres().add("OR"); } /*************************** * cols ***************************/ public Object col(String column) { if(col != null && !column.isEmpty()) { if(col instanceof GSelect) for (DSelect dSelect : ((GSelect)col).selects()) { if(dSelect.column.equalsIgnoreCase(column)) return dSelect; } else if(col instanceof GUpdate) for (String string : ((GUpdate)col).sets()) { if(string.equalsIgnoreCase(column)) return string; } } return column; } public Object col(int column) { if(col != null && column>=0) { if(col instanceof GSelect) { if(column < ((GSelect)col).selects().size()) return ((GSelect)col).selects().get(column); }else if(col instanceof GUpdate) if(column < ((GUpdate)col).sets().size()) return ((GUpdate)col).sets().get(column); return null; } return null; } /*************************** * query ***************************/ public boolean query(Query<?,?> query){ if(query != null){ String s = ""; if(query instanceof IWhere<?>) s = ((IWhere) query).generate().toString(); else s = query.query(); if(!s.isEmpty()) { addIsAND(); wheres().add("(".concat(s).concat(")")); return true; } } return false; } public ArrayList<Object> wheres() { if(wheres == null ) wheres = new ArrayList<Object>(); return wheres; } /*************************** * where ***************************/ public void where(String column, String operator){ addIsAND(); wheres().add(new DWhere(col(column), operator, "?", isNOT())); } public void where(int column, String operator){ addIsAND(); wheres().add(new DWhere(col(column), operator, "?", isNOT())); } public void where(String column, String operator, String value){ addIsAND(); wheres().add(new DWhere(col(column), operator, value, isNOT())); } public void where(int column, String operator, String value){ addIsAND(); wheres().add(new DWhere(col(column), operator, value, isNOT())); } public void where(int column, String operator, int value){ addIsAND(); wheres().add(new DWhere(col(column), operator, col(value), isNOT())); } /*************************** * in ***************************/ public void in(String column, int size){ addIsAND(); wheres().add(new DIn(col(column), size, isNOT())); } public void in(int column, int size){ addIsAND(); wheres().add(new DIn(col(column), size, isNOT())); } /*************************** * like ***************************/ public void like(String column){ addIsAND(); wheres().add(new DLike(col(column), isNOT())); } public void like(int column){ addIsAND(); wheres().add(new DLike(col(column), isNOT())); } /*************************** * between ***************************/ public void between(String column){ addIsAND(); wheres().add(new DBetween(col(column), isNOT())); } public void between(int column){ addIsAND(); wheres().add(new DBetween(col(column), isNOT())); } }
UTF-8
Java
4,140
java
GWhere.java
Java
[]
null
[]
package tools.gnzlz.database.query.model.builder.data; import java.util.ArrayList; import tools.gnzlz.database.query.model.builder.IWhere; import tools.gnzlz.database.query.model.builder.Query; public class GWhere { private boolean priority = true; private boolean isAND = priority; private boolean isNOT; private ArrayList<Object> wheres; private Object col; public GWhere(Object col) { this.col = col; } /*************************** * AND - OR - NOT ***************************/ public void priority(boolean priority) { this.priority = priority; } public void priorityOR() { priority(false); } public void priorityAND() { priority(true); } public void AND() { isAND = true; } public void OR() { isAND = false; } public void NOT() { isNOT = true; } public boolean isAND() { boolean is = isAND; isAND = priority; return is; } public boolean isNOT() { boolean is = isNOT; isNOT = false; return is; } private void addIsAND() { if(!wheres().isEmpty()) if(isAND()) wheres().add("AND"); else wheres().add("OR"); } /*************************** * cols ***************************/ public Object col(String column) { if(col != null && !column.isEmpty()) { if(col instanceof GSelect) for (DSelect dSelect : ((GSelect)col).selects()) { if(dSelect.column.equalsIgnoreCase(column)) return dSelect; } else if(col instanceof GUpdate) for (String string : ((GUpdate)col).sets()) { if(string.equalsIgnoreCase(column)) return string; } } return column; } public Object col(int column) { if(col != null && column>=0) { if(col instanceof GSelect) { if(column < ((GSelect)col).selects().size()) return ((GSelect)col).selects().get(column); }else if(col instanceof GUpdate) if(column < ((GUpdate)col).sets().size()) return ((GUpdate)col).sets().get(column); return null; } return null; } /*************************** * query ***************************/ public boolean query(Query<?,?> query){ if(query != null){ String s = ""; if(query instanceof IWhere<?>) s = ((IWhere) query).generate().toString(); else s = query.query(); if(!s.isEmpty()) { addIsAND(); wheres().add("(".concat(s).concat(")")); return true; } } return false; } public ArrayList<Object> wheres() { if(wheres == null ) wheres = new ArrayList<Object>(); return wheres; } /*************************** * where ***************************/ public void where(String column, String operator){ addIsAND(); wheres().add(new DWhere(col(column), operator, "?", isNOT())); } public void where(int column, String operator){ addIsAND(); wheres().add(new DWhere(col(column), operator, "?", isNOT())); } public void where(String column, String operator, String value){ addIsAND(); wheres().add(new DWhere(col(column), operator, value, isNOT())); } public void where(int column, String operator, String value){ addIsAND(); wheres().add(new DWhere(col(column), operator, value, isNOT())); } public void where(int column, String operator, int value){ addIsAND(); wheres().add(new DWhere(col(column), operator, col(value), isNOT())); } /*************************** * in ***************************/ public void in(String column, int size){ addIsAND(); wheres().add(new DIn(col(column), size, isNOT())); } public void in(int column, int size){ addIsAND(); wheres().add(new DIn(col(column), size, isNOT())); } /*************************** * like ***************************/ public void like(String column){ addIsAND(); wheres().add(new DLike(col(column), isNOT())); } public void like(int column){ addIsAND(); wheres().add(new DLike(col(column), isNOT())); } /*************************** * between ***************************/ public void between(String column){ addIsAND(); wheres().add(new DBetween(col(column), isNOT())); } public void between(int column){ addIsAND(); wheres().add(new DBetween(col(column), isNOT())); } }
4,140
0.566184
0.565942
200
19.700001
18.521069
71
false
false
0
0
0
0
0
0
2.135
false
false
12