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
dcada424dc62b784df5a616f26f082c952bc1705
6,081,673,752,118
860794735fe561dee62eb91ad239e6346ad9bb4e
/components/forks/mdbtools/src/mdbtools/libmdb/Constants.java
b49d602f320c211da7489d30c10db52c41f4cdcd
[]
no_license
mhl/libbio-formats-java
https://github.com/mhl/libbio-formats-java
30de58c312480420169926742c88f19483f362f0
2dfc50e24babd86fac30d503472d0a86e62abc60
refs/heads/master
2021-01-10T19:09:35.621000
2012-01-07T11:13:19
2012-01-07T11:13:19
3,123,938
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package mdbtools.libmdb; /** * copied from mdbtools.h */ public class Constants { public static final int MDB_FORM = 0; public static final int MDB_TABLE = 1; public static final int MDB_MACRO = 2; public static final int MDB_SYSTEM_TABLE = 3; public static final int MDB_REPORT = 4; public static final int MDB_QUERY = 5; public static final int MDB_LINKED_TABLE = 6; public static final int MDB_MODULE = 7; public static final int MDB_RELATIONSHIP = 8; public static final int MDB_UNKNOWN_09 = 9; public static final int MDB_UNKNOWN_0A = 10; public static final int MDB_DATABASE_PROPERTY = 11; public static final int MDB_ANY = -1; public static final int MDB_BOOL = 0x01; public static final int MDB_BYTE = 0x02; public static final int MDB_INT = 0x03; public static final int MDB_LONGINT = 0x04; public static final int MDB_MONEY = 0x05; public static final int MDB_FLOAT = 0x06; public static final int MDB_DOUBLE = 0x07; public static final int MDB_SDATETIME = 0x08; public static final int MDB_TEXT = 0x0a; public static final int MDB_OLE = 0x0b; public static final int MDB_MEMO = 0x0c; public static final int MDB_REPID = 0x0f; public static final int MDB_NUMERIC = 0x10; public static final int MDB_EQUAL = 1; public static final int MDB_GT = 2; public static final int MDB_LT = 3; public static final int MDB_GTEQ = 4; public static final int MDB_LTEQ = 5; public static final int MDB_LIKE = 6; public static final int MDB_ISNULL = 7; public static final int MDB_NOTNULL = 8; public static final int MDB_PGSIZE = 4096; public static final int MDB_MAX_OBJ_NAME = 30; public static final int MDB_MAX_COLS = 256; public static final int MDB_MAX_IDX_COLS = 10; public static final int MDB_CATALOG_PG = 18; public static final int MDB_MEMO_OVERHEAD = 12; public static final int MDB_BIND_SIZE = 16384; }
UTF-8
Java
1,898
java
Constants.java
Java
[]
null
[]
package mdbtools.libmdb; /** * copied from mdbtools.h */ public class Constants { public static final int MDB_FORM = 0; public static final int MDB_TABLE = 1; public static final int MDB_MACRO = 2; public static final int MDB_SYSTEM_TABLE = 3; public static final int MDB_REPORT = 4; public static final int MDB_QUERY = 5; public static final int MDB_LINKED_TABLE = 6; public static final int MDB_MODULE = 7; public static final int MDB_RELATIONSHIP = 8; public static final int MDB_UNKNOWN_09 = 9; public static final int MDB_UNKNOWN_0A = 10; public static final int MDB_DATABASE_PROPERTY = 11; public static final int MDB_ANY = -1; public static final int MDB_BOOL = 0x01; public static final int MDB_BYTE = 0x02; public static final int MDB_INT = 0x03; public static final int MDB_LONGINT = 0x04; public static final int MDB_MONEY = 0x05; public static final int MDB_FLOAT = 0x06; public static final int MDB_DOUBLE = 0x07; public static final int MDB_SDATETIME = 0x08; public static final int MDB_TEXT = 0x0a; public static final int MDB_OLE = 0x0b; public static final int MDB_MEMO = 0x0c; public static final int MDB_REPID = 0x0f; public static final int MDB_NUMERIC = 0x10; public static final int MDB_EQUAL = 1; public static final int MDB_GT = 2; public static final int MDB_LT = 3; public static final int MDB_GTEQ = 4; public static final int MDB_LTEQ = 5; public static final int MDB_LIKE = 6; public static final int MDB_ISNULL = 7; public static final int MDB_NOTNULL = 8; public static final int MDB_PGSIZE = 4096; public static final int MDB_MAX_OBJ_NAME = 30; public static final int MDB_MAX_COLS = 256; public static final int MDB_MAX_IDX_COLS = 10; public static final int MDB_CATALOG_PG = 18; public static final int MDB_MEMO_OVERHEAD = 12; public static final int MDB_BIND_SIZE = 16384; }
1,898
0.717597
0.674921
52
35.5
15.719293
53
false
false
0
0
0
0
0
0
0.807692
false
false
0
fd7d2893b1f44be530d0a2b1d41527573eed4fbc
6,081,673,752,741
569e96644365b2109ee776049bdf1cd2eda213a7
/Life_Saver/app/src/main/java/com/example/sayantan/life_saver/Slip.java
8648c3cc1ffc3029b43fce9830615fe4411302ab
[]
no_license
werfree/Android
https://github.com/werfree/Android
117e1e7db151b0bc76e293f7b96467875ff3daa7
7fa016368515e1c076aea945832a40ed2494cca5
refs/heads/master
2020-03-26T14:20:55.770000
2019-08-16T19:27:10
2019-08-16T19:27:10
144,983,467
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sayantan.life_saver; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; 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.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.ServerValue; import com.google.firebase.database.ValueEventListener; import org.w3c.dom.Text; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class Slip extends AppCompatActivity { private static final String[] bloodgroup = {"Blood Group", "A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"}; Spinner bloodSpinner; String naem, loc, phno; Button submit; private EditText name,location,ph; String selectedbloodGroup, unit; String n; private FirebaseAuth mAuth; private DatabaseReference storeUserDefaultDataReference, getUserData, mdatabase, db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slip); mAuth = FirebaseAuth.getInstance(); name = findViewById(R.id.name); location=findViewById(R.id.location); bloodSpinner = (Spinner) findViewById(R.id.bloodgroup); ArrayAdapter<String> adapterBlood = new ArrayAdapter<String>(Slip.this, android.R.layout.simple_spinner_dropdown_item, bloodgroup); bloodSpinner.setAdapter(adapterBlood); mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getUid()); db = FirebaseDatabase.getInstance().getReference().child("Slip").child(mAuth.getUid()); mdatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { naem = dataSnapshot.child("userName").getValue().toString(); loc = dataSnapshot.child("userCity").getValue().toString(); phno = dataSnapshot.child("userPh").getValue().toString(); name.setText(naem); location.setText(loc); } Toast.makeText(getApplicationContext(),"Name :- " + naem,Toast.LENGTH_LONG).show(); } @Override public void onCancelled(DatabaseError databaseError) { } }); submit = (Button) findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedbloodGroup = bloodSpinner.getSelectedItem().toString(); unit = name.getText().toString(); check(selectedbloodGroup, unit,(location.getText().toString()).trim(),phno); } }); } public void check(String type, String unit,String loc, String pn) { if (TextUtils.isEmpty(unit)) { Toast.makeText(Slip.this, "Unit Field is Empty", Toast.LENGTH_LONG).show(); } else if (type.equals("Blood Group")) { Toast.makeText(Slip.this, "Blood Group Field is Empty", Toast.LENGTH_LONG).show(); } else { upload(type, unit,loc, pn); } } private void upload(String type, String unit, String loc, String pn) { String g=type; String u=unit; String l=loc; String ph = pn; String time=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()); Map slipmap = new HashMap(); slipmap.put("type",g); slipmap.put("unit",u); slipmap.put("loc",l); slipmap.put("phno",ph); slipmap.put("timesapp", time); DatabaseReference slipdb = db.push(); slipdb.setValue(slipmap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Intent startPage = new Intent(Slip.this, MainPage.class); startPage.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(startPage); finish(); } else { Toast.makeText(getApplicationContext(), "Error while updating your data", Toast.LENGTH_SHORT).show(); } } }); } }
UTF-8
Java
5,074
java
Slip.java
Java
[ { "context": " {\n naem = dataSnapshot.child(\"userName\").getValue().toString();\n loc ", "end": 2502, "score": 0.6640093922615051, "start": 2494, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.example.sayantan.life_saver; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; 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.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.ServerValue; import com.google.firebase.database.ValueEventListener; import org.w3c.dom.Text; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class Slip extends AppCompatActivity { private static final String[] bloodgroup = {"Blood Group", "A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"}; Spinner bloodSpinner; String naem, loc, phno; Button submit; private EditText name,location,ph; String selectedbloodGroup, unit; String n; private FirebaseAuth mAuth; private DatabaseReference storeUserDefaultDataReference, getUserData, mdatabase, db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slip); mAuth = FirebaseAuth.getInstance(); name = findViewById(R.id.name); location=findViewById(R.id.location); bloodSpinner = (Spinner) findViewById(R.id.bloodgroup); ArrayAdapter<String> adapterBlood = new ArrayAdapter<String>(Slip.this, android.R.layout.simple_spinner_dropdown_item, bloodgroup); bloodSpinner.setAdapter(adapterBlood); mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getUid()); db = FirebaseDatabase.getInstance().getReference().child("Slip").child(mAuth.getUid()); mdatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { naem = dataSnapshot.child("userName").getValue().toString(); loc = dataSnapshot.child("userCity").getValue().toString(); phno = dataSnapshot.child("userPh").getValue().toString(); name.setText(naem); location.setText(loc); } Toast.makeText(getApplicationContext(),"Name :- " + naem,Toast.LENGTH_LONG).show(); } @Override public void onCancelled(DatabaseError databaseError) { } }); submit = (Button) findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedbloodGroup = bloodSpinner.getSelectedItem().toString(); unit = name.getText().toString(); check(selectedbloodGroup, unit,(location.getText().toString()).trim(),phno); } }); } public void check(String type, String unit,String loc, String pn) { if (TextUtils.isEmpty(unit)) { Toast.makeText(Slip.this, "Unit Field is Empty", Toast.LENGTH_LONG).show(); } else if (type.equals("Blood Group")) { Toast.makeText(Slip.this, "Blood Group Field is Empty", Toast.LENGTH_LONG).show(); } else { upload(type, unit,loc, pn); } } private void upload(String type, String unit, String loc, String pn) { String g=type; String u=unit; String l=loc; String ph = pn; String time=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()); Map slipmap = new HashMap(); slipmap.put("type",g); slipmap.put("unit",u); slipmap.put("loc",l); slipmap.put("phno",ph); slipmap.put("timesapp", time); DatabaseReference slipdb = db.push(); slipdb.setValue(slipmap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Intent startPage = new Intent(Slip.this, MainPage.class); startPage.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(startPage); finish(); } else { Toast.makeText(getApplicationContext(), "Error while updating your data", Toast.LENGTH_SHORT).show(); } } }); } }
5,074
0.63579
0.635396
160
30.706249
30.528593
139
false
false
0
0
0
0
0
0
0.775
false
false
0
43c9bdf6205744e8dbb34f67e8d27a16b4f0f345
7,121,055,814,955
40f6aed9ee5aaff051f1c2eb955c7f16cf2ae3a9
/src/main/kotlin/day3/lecture3/solutions/JvmClass.java
53cde7ec5f56250262bf718b4332a800f96989d4
[]
no_license
ShiraRotman/kotlin-workshop
https://github.com/ShiraRotman/kotlin-workshop
fb965f8b72d8de236f949fda037a5547a76de054
d7b778901621ec5dd8b7a33efdebe18f3d8a87b1
refs/heads/master
2020-08-17T00:05:56.529000
2019-10-17T17:29:03
2019-10-17T17:29:03
215,575,581
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day3.lecture3.solutions; public class JvmClass { public static void main(String[] args) { // Bear bear = new Bear(); Colors.INSTANCE.getRandomColor(); Bear.Companion.getDefaultColor(); // Bear.Companion.getBearColor(); Colors.getRandomColor(); Bear.getDefaultColor(); // Bear.getBearColor(); new Bear("Yellow", "Salmon", 8); new Bear( "Salmon", 8); } }
UTF-8
Java
449
java
JvmClass.java
Java
[]
null
[]
package day3.lecture3.solutions; public class JvmClass { public static void main(String[] args) { // Bear bear = new Bear(); Colors.INSTANCE.getRandomColor(); Bear.Companion.getDefaultColor(); // Bear.Companion.getBearColor(); Colors.getRandomColor(); Bear.getDefaultColor(); // Bear.getBearColor(); new Bear("Yellow", "Salmon", 8); new Bear( "Salmon", 8); } }
449
0.583519
0.57461
23
18.52174
17.773624
44
false
false
0
0
0
0
0
0
0.565217
false
false
0
ca74420a2e15c4a88dfc40bb8b21c87d14fc8e92
4,861,903,043,937
80d30516768423898a173d9d427041fb813493c7
/src/main/java/ElectronicaWebDAW/Entidades/Carrito.java
ac664c3f59a02abd3441277fd71a59d89bbb61ff
[]
no_license
GonzaloMartinezRomero/Web-Application
https://github.com/GonzaloMartinezRomero/Web-Application
d443913241fe2556725d6f6d3467b37b4b7808ef
a4613112776a7d8e09cb33234fcb122710ce3f88
refs/heads/master
2021-01-22T15:10:54.284000
2017-09-04T15:58:04
2017-09-04T15:58:04
null
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 ElectronicaWebDAW.Entidades; /** * * @author Drebin */ public class Carrito { private int id; private int id_articulo; private String nombre_usuario; private String fecha; public Carrito(){ this.id=-1; this.id_articulo=-1; this.nombre_usuario="Vacio"; this.fecha="Vacio"; } public Carrito(int _id,int _id_articulo,String _nombre_usuario,String _fecha){ this.id=_id; this.id_articulo=_id_articulo; this.nombre_usuario=_nombre_usuario; this.fecha=_fecha; } public Carrito(Carrito c){ this.id=c.id; this.id_articulo=c.id_articulo; this.nombre_usuario=c.nombre_usuario; this.fecha=c.fecha; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the id_articulo */ public int getId_articulo() { return id_articulo; } /** * @param id_articulo the id_articulo to set */ public void setId_articulo(int id_articulo) { this.id_articulo = id_articulo; } /** * @return the nombre_usuario */ public String getNombre_usuario() { return nombre_usuario; } /** * @param nombre_usuario the nombre_usuario to set */ public void setNombre_usuario(String nombre_usuario) { this.nombre_usuario = nombre_usuario; } /** * @return the fecha */ public String getFecha() { return fecha; } /** * @param fecha the fecha to set */ public void setFecha(String fecha) { this.fecha = fecha; } }
UTF-8
Java
2,132
java
Carrito.java
Java
[ { "context": "lectronicaWebDAW.Entidades;\r\n\r\n/**\r\n *\r\n * @author Drebin\r\n */\r\npublic class Carrito {\r\n \r\n private i", "end": 256, "score": 0.965693473815918, "start": 250, "tag": "NAME", "value": "Drebin" }, { "context": "his.id_articulo=-1;\r\n this.nomb...
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 ElectronicaWebDAW.Entidades; /** * * @author Drebin */ public class Carrito { private int id; private int id_articulo; private String nombre_usuario; private String fecha; public Carrito(){ this.id=-1; this.id_articulo=-1; this.nombre_usuario="Vacio"; this.fecha="Vacio"; } public Carrito(int _id,int _id_articulo,String _nombre_usuario,String _fecha){ this.id=_id; this.id_articulo=_id_articulo; this.nombre_usuario=_nombre_usuario; this.fecha=_fecha; } public Carrito(Carrito c){ this.id=c.id; this.id_articulo=c.id_articulo; this.nombre_usuario=c.nombre_usuario; this.fecha=c.fecha; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the id_articulo */ public int getId_articulo() { return id_articulo; } /** * @param id_articulo the id_articulo to set */ public void setId_articulo(int id_articulo) { this.id_articulo = id_articulo; } /** * @return the nombre_usuario */ public String getNombre_usuario() { return nombre_usuario; } /** * @param nombre_usuario the nombre_usuario to set */ public void setNombre_usuario(String nombre_usuario) { this.nombre_usuario = nombre_usuario; } /** * @return the fecha */ public String getFecha() { return fecha; } /** * @param fecha the fecha to set */ public void setFecha(String fecha) { this.fecha = fecha; } }
2,132
0.519231
0.518293
102
18.90196
18.115376
82
false
false
0
0
0
0
0
0
0.303922
false
false
0
70227c49b6090e882e5ab59a0d4d6156da6c1738
4,861,903,042,291
f40ca64db94c8eed98e3b76a43f7632235bba61c
/src/main/java/com/infy/exceptions/ExceptionControllerAdvice.java
700bc038f41d361ccdaf25ec9105c1bf6c3e58ea
[]
no_license
agarwalsaumya1992/demo
https://github.com/agarwalsaumya1992/demo
2fa525f95c41795018aa66c9b6674ebbab900841
4b28381be82f76b41b7c495f87e6293a371888dc
refs/heads/master
2023-08-15T10:01:55.787000
2021-10-13T12:21:50
2021-10-13T12:21:50
415,104,179
0
0
null
false
2021-10-13T12:21:51
2021-10-08T19:25:40
2021-10-12T16:34:35
2021-10-13T12:21:50
113
0
0
0
Java
false
false
package com.infy.exceptions; import java.util.stream.Collectors; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.infy.dto.ResponseBuilder; import com.infy.service.ProductServiceImpl; @RestControllerAdvice public class ExceptionControllerAdvice { //this helps receiving the message/value related to the general exception from the ValidationMessages.properties // @Autowired // private Environment environment; private static Logger log = LoggerFactory.getLogger(ProductServiceImpl.class); @ExceptionHandler(Exception.class) public ResponseEntity<ResponseBuilder> handleGeneralExceptions(Exception ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); // error.setMessage(environment.getProperty(InfyConstants.GENERAL_EXCEPTION_MESSAGE.toString())); error.setMessage(ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } //Handler for NoSuchCustomerException @ExceptionHandler(NoSuchRecordException.class) public ResponseEntity<ResponseBuilder> handleCustomerExceptions(NoSuchRecordException ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } //Handler that handles the exception raised because of invalid data that is received as method argument (DTO) @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ResponseBuilder> handleValidationExceptions(MethodArgumentNotValidException ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(ex.getBindingResult().getAllErrors() .stream().map(ObjectError::getDefaultMessage)//lambda equivalent -> x->x.getDefaultMessage() .collect(Collectors.joining(", "))); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } //Handler that handles the exception raised because of invalid data that is received as //URI parameter (path variables, request parameters) @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<ResponseBuilder> handleConstraintValidationExceptions(ConstraintViolationException ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(ex.getConstraintViolations() .stream().map(ConstraintViolation::getMessage)//lambda equivalent -> x->x.getMessage() .collect(Collectors.joining(", "))); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } }
UTF-8
Java
3,440
java
ExceptionControllerAdvice.java
Java
[]
null
[]
package com.infy.exceptions; import java.util.stream.Collectors; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.infy.dto.ResponseBuilder; import com.infy.service.ProductServiceImpl; @RestControllerAdvice public class ExceptionControllerAdvice { //this helps receiving the message/value related to the general exception from the ValidationMessages.properties // @Autowired // private Environment environment; private static Logger log = LoggerFactory.getLogger(ProductServiceImpl.class); @ExceptionHandler(Exception.class) public ResponseEntity<ResponseBuilder> handleGeneralExceptions(Exception ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); // error.setMessage(environment.getProperty(InfyConstants.GENERAL_EXCEPTION_MESSAGE.toString())); error.setMessage(ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } //Handler for NoSuchCustomerException @ExceptionHandler(NoSuchRecordException.class) public ResponseEntity<ResponseBuilder> handleCustomerExceptions(NoSuchRecordException ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } //Handler that handles the exception raised because of invalid data that is received as method argument (DTO) @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ResponseBuilder> handleValidationExceptions(MethodArgumentNotValidException ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(ex.getBindingResult().getAllErrors() .stream().map(ObjectError::getDefaultMessage)//lambda equivalent -> x->x.getDefaultMessage() .collect(Collectors.joining(", "))); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } //Handler that handles the exception raised because of invalid data that is received as //URI parameter (path variables, request parameters) @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<ResponseBuilder> handleConstraintValidationExceptions(ConstraintViolationException ex) { log.error(ex.getMessage()); ResponseBuilder error = new ResponseBuilder(); error.setResponseCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(ex.getConstraintViolations() .stream().map(ConstraintViolation::getMessage)//lambda equivalent -> x->x.getMessage() .collect(Collectors.joining(", "))); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } }
3,440
0.785174
0.784593
75
44.853333
31.22123
116
false
false
0
0
0
0
0
0
1.693333
false
false
0
81488b19be0c93898420989642b9dfb18e6be8a5
11,235,634,467,696
92cbd572d8239de627a4ff89558a2c5d6a84c240
/clonepedia/src/clonepedia/java/visitor/FindInvokingMethodsVistor.java
5522ed134681fe1f4426e32daa731e0fbd3b32b9
[]
no_license
llmhyy/clonepedia
https://github.com/llmhyy/clonepedia
95491e0948561b170ca770e1b6d4c01a50f8cb7c
04fc913af7e9884b53904ac4f96225bc29c8552c
refs/heads/master
2020-12-11T04:00:26.152000
2019-11-08T12:58:38
2019-11-08T12:58:38
68,502,477
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package clonepedia.java.visitor; import java.util.HashMap; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.MethodInvocation; public class FindInvokingMethodsVistor extends ASTVisitor { private HashMap<IMethodBinding, CompilationUnit> invokedMethodBindingMap = new HashMap<IMethodBinding, CompilationUnit>(); public boolean visit(MethodInvocation invoke){ IMethodBinding methodBinding = invoke.resolveMethodBinding(); CompilationUnit cu = getCompilationUnit(invoke); if(null != cu){ invokedMethodBindingMap.put(methodBinding, cu); } return true; } public boolean visit(ClassInstanceCreation invoke){ IMethodBinding methodBinding = invoke.resolveConstructorBinding(); CompilationUnit cu = getCompilationUnit(invoke); if(null != cu){ invokedMethodBindingMap.put(methodBinding, cu); //methodBinding.getDeclaringClass(). } return true; } private CompilationUnit getCompilationUnit(ASTNode node){ while((node != null) && !(node instanceof CompilationUnit)){ node = node.getParent(); } return (node == null)? null : (CompilationUnit)node; } public HashMap<IMethodBinding, CompilationUnit> getInvokedMethodBindingMap() { return invokedMethodBindingMap; } }
UTF-8
Java
1,508
java
FindInvokingMethodsVistor.java
Java
[]
null
[]
package clonepedia.java.visitor; import java.util.HashMap; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.MethodInvocation; public class FindInvokingMethodsVistor extends ASTVisitor { private HashMap<IMethodBinding, CompilationUnit> invokedMethodBindingMap = new HashMap<IMethodBinding, CompilationUnit>(); public boolean visit(MethodInvocation invoke){ IMethodBinding methodBinding = invoke.resolveMethodBinding(); CompilationUnit cu = getCompilationUnit(invoke); if(null != cu){ invokedMethodBindingMap.put(methodBinding, cu); } return true; } public boolean visit(ClassInstanceCreation invoke){ IMethodBinding methodBinding = invoke.resolveConstructorBinding(); CompilationUnit cu = getCompilationUnit(invoke); if(null != cu){ invokedMethodBindingMap.put(methodBinding, cu); //methodBinding.getDeclaringClass(). } return true; } private CompilationUnit getCompilationUnit(ASTNode node){ while((node != null) && !(node instanceof CompilationUnit)){ node = node.getParent(); } return (node == null)? null : (CompilationUnit)node; } public HashMap<IMethodBinding, CompilationUnit> getInvokedMethodBindingMap() { return invokedMethodBindingMap; } }
1,508
0.740053
0.740053
52
27
27.83744
123
false
false
0
0
0
0
0
0
1.846154
false
false
0
0dc530dba8112c0bfd87880138f7c82384152e69
15,882,789,062,945
72e2c38fe480ca1af8029c037c2ded68686d8275
/tripoin-pos-shared-data/src/main/java/com/tripoin/pos/shared/data/dto/response/master/ProductTypeResponseDTO.java
458cae26f4a8e407b8ac0dd9c66ad51b6325d9fc
[]
no_license
KNIGHTMASTER/tripoin-pos
https://github.com/KNIGHTMASTER/tripoin-pos
b23ee566f6c92785e07551769d03512d90b4ee81
5a9edec9cfad2fd5ed90ffc952ac3d96ca61499b
refs/heads/master
2019-07-18T08:53:13.372000
2018-01-18T09:21:04
2018-01-18T09:21:04
67,919,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tripoin.pos.shared.data.dto.response.master; import com.tripoin.scaffolding.data.dto.response.BaseResponseDTO; /** * Created on 11/20/17. * * @author <a href="mailto:fauzi.knightmaster.achmad@gmail.com">Achmad Fauzi</a> */ public class ProductTypeResponseDTO extends BaseResponseDTO { /** * * */ private static final long serialVersionUID = -4458327710851194936L; private String imageUrl; private ProductCategoryResponseDTO productCategory; public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public ProductCategoryResponseDTO getProductCategory() { return productCategory; } public void setProductCategory(ProductCategoryResponseDTO productCategory) { this.productCategory = productCategory; } }
UTF-8
Java
883
java
ProductTypeResponseDTO.java
Java
[ { "context": "reated on 11/20/17.\n *\n * @author <a href=\"mailto:fauzi.knightmaster.achmad@gmail.com\">Achmad Fauzi</a>\n */\npublic class ProductTypeRes", "end": 218, "score": 0.9995707273483276, "start": 183, "tag": "EMAIL", "value": "fauzi.knightmaster.achmad@gmail.com" }, { "co...
null
[]
package com.tripoin.pos.shared.data.dto.response.master; import com.tripoin.scaffolding.data.dto.response.BaseResponseDTO; /** * Created on 11/20/17. * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class ProductTypeResponseDTO extends BaseResponseDTO { /** * * */ private static final long serialVersionUID = -4458327710851194936L; private String imageUrl; private ProductCategoryResponseDTO productCategory; public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public ProductCategoryResponseDTO getProductCategory() { return productCategory; } public void setProductCategory(ProductCategoryResponseDTO productCategory) { this.productCategory = productCategory; } }
849
0.710079
0.681767
35
24.228571
26.537397
80
false
false
0
0
0
0
0
0
0.257143
false
false
0
9eb0b6f3ba2a407f0e1bb54b6a080a37eab55b59
5,317,169,525,329
e9f3f0d21ccc65c2ef7bc5ea20e293b6186e4b12
/src/main/java/com/example/application/views/dashboard/DashboardView.java
12e6c485c35613698a24e7177de29d9a90286b2a
[ "Unlicense" ]
permissive
OlliTietavainenVaadin/v14-chart-test
https://github.com/OlliTietavainenVaadin/v14-chart-test
9206447c2179059678d7865cae0c695445508385
dd5e60a3f3a57271d5ef1a4c49d04efd78c87be6
refs/heads/main
2023-08-25T20:18:19.228000
2021-10-14T10:03:05
2021-10-14T10:03:05
417,075,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.application.views.dashboard; import com.example.application.views.MainLayout; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.charts.Chart; import com.vaadin.flow.component.charts.model.ChartType; import com.vaadin.flow.component.charts.model.Configuration; import com.vaadin.flow.component.charts.model.ListSeries; import com.vaadin.flow.component.charts.model.PlotOptionsArea; import com.vaadin.flow.component.charts.model.PointPlacement; import com.vaadin.flow.component.charts.model.Tooltip; import com.vaadin.flow.component.charts.model.XAxis; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.select.Select; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; @PageTitle("Dashboard") @Route(value = "dashboard", layout = MainLayout.class) @RouteAlias(value = "", layout = MainLayout.class) @CssImport(value = "./chart-gridline.css", themeFor = "vaadin-chart", include = "vaadin-chart-default-theme") public class DashboardView extends Main { public DashboardView() { addClassName("dashboard-view"); Chart chart = createViewEvents(); add(chart); Button initialDrawChartButton = new Button("drawChart with reset", e -> { chart.drawChart(true); }); add(initialDrawChartButton); Button toggleTooltipAndRedrawButton = new Button("Toggle tooltip and redraw"); toggleTooltipAndRedrawButton.addClickListener(e -> { Boolean enabled = chart.getConfiguration().getTooltip().getEnabled(); chart.getConfiguration().getTooltip().setEnabled(!enabled); chart.drawChart(); }); add(toggleTooltipAndRedrawButton); } private Chart createViewEvents() { // Header Select year = new Select(); year.setItems("2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021"); year.setValue("2021"); year.setWidth("100px"); HorizontalLayout header = createHeader("View events", "Cumulative (city/month)"); header.add(year); // Chart Chart chart = new Chart(ChartType.LINE); Configuration conf = chart.getConfiguration(); Tooltip tooltip = conf.getTooltip(); tooltip.setEnabled(true); XAxis xAxis = new XAxis(); xAxis.setCategories("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); conf.addxAxis(xAxis); conf.getyAxis().setTitle("Values"); PlotOptionsArea plotOptions = new PlotOptionsArea(); plotOptions.setPointPlacement(PointPlacement.ON); conf.addPlotOptions(plotOptions); conf.addSeries(new ListSeries("Berlin", 189, 191, 191, 196, 201, 203, 209, 212, 229, 242, 244, 247)); conf.addSeries(new ListSeries("London", 138, 146, 148, 148, 152, 153, 163, 173, 178, 179, 185, 187)); conf.addSeries(new ListSeries("New York", 65, 65, 66, 71, 93, 102, 108, 117, 127, 129, 135, 136)); conf.addSeries(new ListSeries("Tokyo", 0, 11, 17, 23, 30, 42, 48, 49, 52, 54, 58, 62)); return chart; } private HorizontalLayout createHeader(String title, String subtitle) { H2 h2 = new H2(title); h2.addClassNames("text-xl", "m-0"); Span span = new Span(subtitle); span.addClassNames("text-secondary", "text-xs"); VerticalLayout column = new VerticalLayout(h2, span); column.setPadding(false); column.setSpacing(false); HorizontalLayout header = new HorizontalLayout(column); header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN); header.setSpacing(false); header.setWidthFull(); return header; } }
UTF-8
Java
4,216
java
DashboardView.java
Java
[]
null
[]
package com.example.application.views.dashboard; import com.example.application.views.MainLayout; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.charts.Chart; import com.vaadin.flow.component.charts.model.ChartType; import com.vaadin.flow.component.charts.model.Configuration; import com.vaadin.flow.component.charts.model.ListSeries; import com.vaadin.flow.component.charts.model.PlotOptionsArea; import com.vaadin.flow.component.charts.model.PointPlacement; import com.vaadin.flow.component.charts.model.Tooltip; import com.vaadin.flow.component.charts.model.XAxis; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Main; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.select.Select; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; @PageTitle("Dashboard") @Route(value = "dashboard", layout = MainLayout.class) @RouteAlias(value = "", layout = MainLayout.class) @CssImport(value = "./chart-gridline.css", themeFor = "vaadin-chart", include = "vaadin-chart-default-theme") public class DashboardView extends Main { public DashboardView() { addClassName("dashboard-view"); Chart chart = createViewEvents(); add(chart); Button initialDrawChartButton = new Button("drawChart with reset", e -> { chart.drawChart(true); }); add(initialDrawChartButton); Button toggleTooltipAndRedrawButton = new Button("Toggle tooltip and redraw"); toggleTooltipAndRedrawButton.addClickListener(e -> { Boolean enabled = chart.getConfiguration().getTooltip().getEnabled(); chart.getConfiguration().getTooltip().setEnabled(!enabled); chart.drawChart(); }); add(toggleTooltipAndRedrawButton); } private Chart createViewEvents() { // Header Select year = new Select(); year.setItems("2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021"); year.setValue("2021"); year.setWidth("100px"); HorizontalLayout header = createHeader("View events", "Cumulative (city/month)"); header.add(year); // Chart Chart chart = new Chart(ChartType.LINE); Configuration conf = chart.getConfiguration(); Tooltip tooltip = conf.getTooltip(); tooltip.setEnabled(true); XAxis xAxis = new XAxis(); xAxis.setCategories("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); conf.addxAxis(xAxis); conf.getyAxis().setTitle("Values"); PlotOptionsArea plotOptions = new PlotOptionsArea(); plotOptions.setPointPlacement(PointPlacement.ON); conf.addPlotOptions(plotOptions); conf.addSeries(new ListSeries("Berlin", 189, 191, 191, 196, 201, 203, 209, 212, 229, 242, 244, 247)); conf.addSeries(new ListSeries("London", 138, 146, 148, 148, 152, 153, 163, 173, 178, 179, 185, 187)); conf.addSeries(new ListSeries("New York", 65, 65, 66, 71, 93, 102, 108, 117, 127, 129, 135, 136)); conf.addSeries(new ListSeries("Tokyo", 0, 11, 17, 23, 30, 42, 48, 49, 52, 54, 58, 62)); return chart; } private HorizontalLayout createHeader(String title, String subtitle) { H2 h2 = new H2(title); h2.addClassNames("text-xl", "m-0"); Span span = new Span(subtitle); span.addClassNames("text-secondary", "text-xs"); VerticalLayout column = new VerticalLayout(h2, span); column.setPadding(false); column.setSpacing(false); HorizontalLayout header = new HorizontalLayout(column); header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN); header.setSpacing(false); header.setWidthFull(); return header; } }
4,216
0.685247
0.641603
105
39.152382
29.760881
112
false
false
0
0
0
0
0
0
1.409524
false
false
0
0d45f01a7bb0352d36e4c452911566b9909791ae
5,317,169,522,626
52de28e068258879fd7ba89949ea232762ebd9c6
/src/main/java/soltiaapp/se/StartPage.java
cfa3db72024ddc4e67ac6fbd5facaf7d0c7ec0d1
[]
no_license
etxmsl/soltiaapp
https://github.com/etxmsl/soltiaapp
1747cfdda6004632fb87ca92871c965d9f0b7a86
2051cff4db503b46679eea542d32b78bf6de4ea3
refs/heads/master
2020-04-15T17:01:10.716000
2019-03-04T16:24:58
2019-03-04T16:24:58
164,857,643
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package soltiaapp.se; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class StartPage extends IPageChrome { public StartPage(int defaultwait) { super(defaultwait); // TODO Auto-generated constructor stub driver.get("http://teltecstaging.nu/soltiaapp.se"); } public void loadpage(){ driver.get("http://teltecstaging.nu/soltiaapp.se"); } public boolean findInputByIdandsendkeys(String id,String keys){ boolean success=true; WebElement idelement=driver.findElement(By.tagName("html")); try{ idelement=driver.findElement(By.id(id)); } catch(Exception e){ success=false; } if(success){idelement.sendKeys(keys);} return success; } public boolean findElementBycssandclick(String css){ boolean success=true; WebElement csselement=driver.findElement(By.tagName("html")); try{ csselement=driver.findElement(By.cssSelector(css)); } catch(Exception e){ success=false; } if(success){csselement.click();} return success; } public boolean findElementByidandclick(String id){ boolean success=true; WebElement idelement=driver.findElement(By.tagName("html")); try{ idelement=driver.findElement(By.id(id)); } catch(Exception e){ success=false; } if(success){idelement.click();} return success; } public boolean findElementBynameandclick(String name){ boolean success=true; WebElement namelement=driver.findElement(By.tagName("html")); try{ namelement=driver.findElement(By.name(name)); } catch(Exception e){ success=false; } if(success){namelement.click();} return success; } public boolean findElementByxpathandclick(String xpath){ boolean success=true; WebElement csselement=driver.findElement(By.tagName("html")); try{ csselement=driver.findElement(By.xpath(xpath)); } catch(Exception e){ success=false; } if(success){csselement.click();} return success; } public boolean findandClicCheckboxbyid(String id){ boolean success=true; WebElement idelement=driver.findElement(By.tagName("html")); try{ idelement=driver.findElement(By.id(id)); } catch(Exception e){ success=false; } if(success){idelement.click();} return success; } public String getTextByWebElement (WebElement element){ return element.getText(); } public List<WebElement> getWebElementsByCss(String css){ List<WebElement> ret = driver.findElements(By.cssSelector(css)); return ret; } public List<WebElement> getWebElementsByXpath(String xpath){ List<WebElement> ret = driver.findElements(By.xpath(xpath)); return ret; } }
UTF-8
Java
2,942
java
StartPage.java
Java
[]
null
[]
package soltiaapp.se; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class StartPage extends IPageChrome { public StartPage(int defaultwait) { super(defaultwait); // TODO Auto-generated constructor stub driver.get("http://teltecstaging.nu/soltiaapp.se"); } public void loadpage(){ driver.get("http://teltecstaging.nu/soltiaapp.se"); } public boolean findInputByIdandsendkeys(String id,String keys){ boolean success=true; WebElement idelement=driver.findElement(By.tagName("html")); try{ idelement=driver.findElement(By.id(id)); } catch(Exception e){ success=false; } if(success){idelement.sendKeys(keys);} return success; } public boolean findElementBycssandclick(String css){ boolean success=true; WebElement csselement=driver.findElement(By.tagName("html")); try{ csselement=driver.findElement(By.cssSelector(css)); } catch(Exception e){ success=false; } if(success){csselement.click();} return success; } public boolean findElementByidandclick(String id){ boolean success=true; WebElement idelement=driver.findElement(By.tagName("html")); try{ idelement=driver.findElement(By.id(id)); } catch(Exception e){ success=false; } if(success){idelement.click();} return success; } public boolean findElementBynameandclick(String name){ boolean success=true; WebElement namelement=driver.findElement(By.tagName("html")); try{ namelement=driver.findElement(By.name(name)); } catch(Exception e){ success=false; } if(success){namelement.click();} return success; } public boolean findElementByxpathandclick(String xpath){ boolean success=true; WebElement csselement=driver.findElement(By.tagName("html")); try{ csselement=driver.findElement(By.xpath(xpath)); } catch(Exception e){ success=false; } if(success){csselement.click();} return success; } public boolean findandClicCheckboxbyid(String id){ boolean success=true; WebElement idelement=driver.findElement(By.tagName("html")); try{ idelement=driver.findElement(By.id(id)); } catch(Exception e){ success=false; } if(success){idelement.click();} return success; } public String getTextByWebElement (WebElement element){ return element.getText(); } public List<WebElement> getWebElementsByCss(String css){ List<WebElement> ret = driver.findElements(By.cssSelector(css)); return ret; } public List<WebElement> getWebElementsByXpath(String xpath){ List<WebElement> ret = driver.findElements(By.xpath(xpath)); return ret; } }
2,942
0.646499
0.646499
114
23.807018
21.31628
69
false
false
0
0
0
0
0
0
1.27193
false
false
0
3d3e3d816326c51d336f4f26bce08d89af37a848
33,294,586,519,088
d57fc3d03a9fba5c45507f0d30e00fca7a09d55f
/app/src/main/java/com/lsjr/zizisteward/activity/TaoCanDetailActivity.java
3570b39d95db95ebb178d837cecba14701d2564b
[]
no_license
gyymz1993/V6.1
https://github.com/gyymz1993/V6.1
8bc1cd4d9c10890331a4366b06c9384c7ba9068c
ecb13d853b4adc69f915ec24ff3cd501f99ee80e
refs/heads/master
2020-03-28T21:41:16.584000
2017-06-20T11:58:41
2017-06-20T11:58:41
94,621,793
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lsjr.zizisteward.activity; import android.annotation.SuppressLint; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.RelativeLayout; import android.widget.Toast; import com.lsjr.zizisteward.R; import com.lsjr.zizisteward.basic.App; import com.lsjr.zizisteward.basic.BaseActivity; import com.lsjr.zizisteward.http.HttpClientGet; import com.lsjr.zizisteward.http.HttpConfig; import com.lsjr.zizisteward.http.MyError; import com.lsjr.zizisteward.utils.EncryptUtils; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; @SuppressLint("SetJavaScriptEnabled") public class TaoCanDetailActivity extends BaseActivity { private WebView mWebview; private String sid; private RelativeLayout mIv_back; @Override public int getContainerView() { return R.layout.activity_travel_webview; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setmTitle("出行"); mWebview = (WebView) findViewById(R.id.webview); mIv_back = (RelativeLayout) findViewById(R.id.iv_back); sid = getIntent().getStringExtra("sid"); WebSettings settings = mWebview.getSettings(); mWebview.setVerticalScrollBarEnabled(false); settings.setJavaScriptEnabled(true); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); mWebview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); getData(); mIv_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mWebview.canGoBack()) { mWebview.goBack(); } else { finish(); } } }); } private void getData() { HashMap<String, String> map = new HashMap<>(); map.put("OPT", "273"); map.put("spid", sid); map.put("user_id", EncryptUtils.addSign(Integer.parseInt(App.getUserInfo().getId()), "u")); new HttpClientGet(getApplicationContext(), null, map, false, new HttpClientGet.CallBacks<String>() { @Override public void onSuccess(String result) { try { JSONObject jsonObject = new JSONObject(result); String comboDetailUrl = jsonObject.getString("comboDetailUrl"); mWebview.loadUrl(HttpConfig.IMAGEHOST + comboDetailUrl); mWebview.addJavascriptInterface(new DemoJavaInterface(), "control"); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(MyError myError) { super.onFailure(myError); } }); } public class DemoJavaInterface { @JavascriptInterface public void serviceprogrammedemand(int code, String msg) {// 提交定制 System.out.println("得到的数据" + code + msg); if (code == 1) { Intent intent = new Intent(getApplicationContext(), BasicWebViewActivity.class); startActivity(intent); finish(); } else { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } @JavascriptInterface public void Callthehousekeeper() { Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + "88300006")); startActivity(phoneIntent); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) { mWebview.goBack();// 返回前一个页面 return true; } return super.onKeyDown(keyCode, event); } }
UTF-8
Java
3,720
java
TaoCanDetailActivity.java
Java
[]
null
[]
package com.lsjr.zizisteward.activity; import android.annotation.SuppressLint; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.RelativeLayout; import android.widget.Toast; import com.lsjr.zizisteward.R; import com.lsjr.zizisteward.basic.App; import com.lsjr.zizisteward.basic.BaseActivity; import com.lsjr.zizisteward.http.HttpClientGet; import com.lsjr.zizisteward.http.HttpConfig; import com.lsjr.zizisteward.http.MyError; import com.lsjr.zizisteward.utils.EncryptUtils; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; @SuppressLint("SetJavaScriptEnabled") public class TaoCanDetailActivity extends BaseActivity { private WebView mWebview; private String sid; private RelativeLayout mIv_back; @Override public int getContainerView() { return R.layout.activity_travel_webview; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setmTitle("出行"); mWebview = (WebView) findViewById(R.id.webview); mIv_back = (RelativeLayout) findViewById(R.id.iv_back); sid = getIntent().getStringExtra("sid"); WebSettings settings = mWebview.getSettings(); mWebview.setVerticalScrollBarEnabled(false); settings.setJavaScriptEnabled(true); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); mWebview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); getData(); mIv_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mWebview.canGoBack()) { mWebview.goBack(); } else { finish(); } } }); } private void getData() { HashMap<String, String> map = new HashMap<>(); map.put("OPT", "273"); map.put("spid", sid); map.put("user_id", EncryptUtils.addSign(Integer.parseInt(App.getUserInfo().getId()), "u")); new HttpClientGet(getApplicationContext(), null, map, false, new HttpClientGet.CallBacks<String>() { @Override public void onSuccess(String result) { try { JSONObject jsonObject = new JSONObject(result); String comboDetailUrl = jsonObject.getString("comboDetailUrl"); mWebview.loadUrl(HttpConfig.IMAGEHOST + comboDetailUrl); mWebview.addJavascriptInterface(new DemoJavaInterface(), "control"); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(MyError myError) { super.onFailure(myError); } }); } public class DemoJavaInterface { @JavascriptInterface public void serviceprogrammedemand(int code, String msg) {// 提交定制 System.out.println("得到的数据" + code + msg); if (code == 1) { Intent intent = new Intent(getApplicationContext(), BasicWebViewActivity.class); startActivity(intent); finish(); } else { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } @JavascriptInterface public void Callthehousekeeper() { Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + "88300006")); startActivity(phoneIntent); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) { mWebview.goBack();// 返回前一个页面 return true; } return super.onKeyDown(keyCode, event); } }
3,720
0.734528
0.73127
132
26.90909
22.96422
102
false
false
0
0
0
0
0
0
2.340909
false
false
0
91a27a593df93ceb5875f47a3c31496d10490aa7
8,624,294,389,737
f7a24adb65885eef58b5beb00220ed8866081f78
/LaunchServer/source/auth/provider/DigestAuthProvider.java
0113f12ef12544305989fdb8ef00ff5159219d15
[]
no_license
tetratec/Launcher
https://github.com/tetratec/Launcher
7f599daf99593c266c134df1d171a17bf10efaa2
6c7304f91074e7baaff3e74ea851354728af9847
refs/heads/master
2018-02-09T21:54:48.878000
2015-11-01T14:12:32
2015-11-01T14:12:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package launchserver.auth.provider; import launcher.LauncherAPI; import launcher.helper.SecurityHelper; import launcher.serialize.config.entry.BlockConfigEntry; import launcher.serialize.config.entry.StringConfigEntry; import launchserver.auth.AuthException; public abstract class DigestAuthProvider extends AuthProvider { private final String digest; @LauncherAPI protected DigestAuthProvider(BlockConfigEntry block) { super(block); digest = block.getEntryValue("digest", StringConfigEntry.class); getDigest(); // Verify that this digest exists } @LauncherAPI public final SecurityHelper.DigestAlgorithm getDigest() { return SecurityHelper.DigestAlgorithm.byName(digest); } @LauncherAPI protected final void verifyDigest(String validDigest, String password) throws AuthException { boolean valid; SecurityHelper.DigestAlgorithm algorithm = getDigest(); if (algorithm == SecurityHelper.DigestAlgorithm.PLAIN) { valid = password.equals(validDigest); } else if (validDigest == null) { valid = false; } else { byte[] actualDigest = SecurityHelper.digest(getDigest(), password); valid = SecurityHelper.toHex(actualDigest).equals(validDigest); } // Verify is valid if (!valid) { authError("Incorrect username or password"); } } }
UTF-8
Java
1,281
java
DigestAuthProvider.java
Java
[]
null
[]
package launchserver.auth.provider; import launcher.LauncherAPI; import launcher.helper.SecurityHelper; import launcher.serialize.config.entry.BlockConfigEntry; import launcher.serialize.config.entry.StringConfigEntry; import launchserver.auth.AuthException; public abstract class DigestAuthProvider extends AuthProvider { private final String digest; @LauncherAPI protected DigestAuthProvider(BlockConfigEntry block) { super(block); digest = block.getEntryValue("digest", StringConfigEntry.class); getDigest(); // Verify that this digest exists } @LauncherAPI public final SecurityHelper.DigestAlgorithm getDigest() { return SecurityHelper.DigestAlgorithm.byName(digest); } @LauncherAPI protected final void verifyDigest(String validDigest, String password) throws AuthException { boolean valid; SecurityHelper.DigestAlgorithm algorithm = getDigest(); if (algorithm == SecurityHelper.DigestAlgorithm.PLAIN) { valid = password.equals(validDigest); } else if (validDigest == null) { valid = false; } else { byte[] actualDigest = SecurityHelper.digest(getDigest(), password); valid = SecurityHelper.toHex(actualDigest).equals(validDigest); } // Verify is valid if (!valid) { authError("Incorrect username or password"); } } }
1,281
0.773614
0.773614
42
29.5
25.571795
94
false
false
0
0
0
0
0
0
1.714286
false
false
0
bc2778b5f4372dfb5dba0f1c5c040ac8d8cf3c25
28,630,252,055,905
52f134bbb4d3eae9496ea6e8d7a74272d489b821
/app/src/main/java/com/tendinsights/tenddemo/util/Constants.java
5f106398a784f0305e8536a555b8080a3be9d706
[]
no_license
bayaSalvatory/tendRetrofit
https://github.com/bayaSalvatory/tendRetrofit
6c21bdb480ee986b274f1488d8876b43ebe094c5
e02bd9dc8c69553e9f067244d68b819543b69eb5
refs/heads/master
2020-11-29T15:25:33.113000
2017-08-02T23:10:41
2017-08-02T23:10:41
87,481,967
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tendinsights.tenddemo.util; /** * Created by Rob on 4/5/17. */ public class Constants { public static final String NAME_KEY = "name"; public static final String DESCR_KEY = "descr"; }
UTF-8
Java
208
java
Constants.java
Java
[ { "context": "com.tendinsights.tenddemo.util;\n\n/**\n * Created by Rob on 4/5/17.\n */\n\npublic class Constants {\n publ", "end": 62, "score": 0.941024899482727, "start": 59, "tag": "NAME", "value": "Rob" }, { "context": "ants {\n public static final String NAME_KEY = \"name\...
null
[]
package com.tendinsights.tenddemo.util; /** * Created by Rob on 4/5/17. */ public class Constants { public static final String NAME_KEY = "name"; public static final String DESCR_KEY = "descr"; }
208
0.682692
0.663462
10
19.799999
19.953947
51
false
false
0
0
0
0
0
0
0.3
false
false
0
06c25c97d46b899a4555dcff7e3bc49029095f04
19,207,093,800,499
2af1f77604e855aa21d07f54c81a1ec5be142c35
/src/classes/javax/sound/sampled/FloatControl.java
a56a60e823dfc64b0c17f744de8f9d83b5af3629
[ "Apache-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
EvilKhaosKat/tritonus
https://github.com/EvilKhaosKat/tritonus
160da46c602889a03e03867fcc232e67b2dbe3e0
08f78f2a1d24a292a8939711a04de1f5c971c6b7
refs/heads/master
2020-04-08T23:33:28.141000
2018-11-26T21:32:40
2018-11-26T21:32:40
159,829,664
0
0
Apache-2.0
true
2018-11-30T13:46:28
2018-11-30T13:46:28
2018-11-30T13:00:09
2018-11-26T21:33:01
3,004
0
0
0
null
false
null
/* * FloatControl.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 1999 by Matthias Pfisterer * * * 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. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package javax.sound.sampled; import org.tritonus.share.TDebug; public abstract class FloatControl extends Control { private float m_fValue; private float m_fMinimum; private float m_fMaximum; private float m_fPrecision; private int m_nUpdatePeriod; private String m_strUnits; private String m_strMinLabel; private String m_strMidLabel; private String m_strMaxLabel; protected FloatControl(Type type, float fMinimum, float fMaximum, float fPrecision, int nUpdatePeriod, float fInitialValue, String strUnits, String strMinLabel, String strMidLabel, String strMaxLabel) { super(type); if (TDebug.TraceControl) { TDebug.out("FloatControl.<init>: begin"); } m_fMinimum = fMinimum; m_fMaximum = fMaximum; m_fPrecision = fPrecision; m_nUpdatePeriod = nUpdatePeriod; //$$fb 2000-12-02: incompatible with Sun implementation... //setValue(fInitialValue); m_fValue = fInitialValue; m_nUpdatePeriod = nUpdatePeriod; m_strMinLabel = strMinLabel; m_strMidLabel = strMidLabel; m_strMaxLabel = strMaxLabel; if (TDebug.TraceControl) { TDebug.out("FloatControl.<init>: end"); } } protected FloatControl(Type type, float fMinimum, float fMaximum, float fPrecision, int nUpdatePeriod, float fInitialValue, String strUnits) { this(type, fMinimum, fMaximum, fPrecision, nUpdatePeriod, fInitialValue, strUnits, "Left", "Center", "Right"); } /** Set the value of the control. If subclasses need to override this method, super.setValue() should be called at the beginning of the overriding implementation. */ public void setValue(float fValue) { m_fValue = fValue; } public float getValue() { return m_fValue; } public float getMaximum() { return m_fMaximum; } public float getMinimum() { return m_fMinimum; } public String getUnits() { return m_strUnits; } public String getMinLabel() { return m_strMinLabel; } public String getMidLabel() { return m_strMidLabel; } public String getMaxLabel() { return m_strMaxLabel; } public float getPrecision() { return m_fPrecision; } public int getUpdatePeriod() { return m_nUpdatePeriod; } public void shift(float fFrom, float fTo, int nMicroseconds) { /* This default implementation is required by the specification. */ setValue(fTo); } public String toString() { return super.toString() + " [value = " + getValue() + "]"; } public static class Type extends Control.Type { public static final Type MASTER_GAIN = new Type("MASTER_GAIN"); public static final Type AUX_SEND = new Type("AUX_SEND"); public static final Type AUX_RETURN = new Type("AUX_RETURN"); public static final Type REVERB_SEND = new Type("REVERB_SEND"); public static final Type REVERB_RETURN = new Type("REVERB_RETURN"); public static final Type VOLUME = new Type("VOLUME"); public static final Type PAN = new Type("PAN"); public static final Type BALANCE = new Type("BALANCE"); //$$fb 2000-12-02: SAMPLE_RATE had been missing public static final Type SAMPLE_RATE = new Type("SAMPLE RATE"); protected Type(String strName) { super(strName); } } } /*** FloatControl.java ***/
UTF-8
Java
4,248
java
FloatControl.java
Java
[ { "context": "ww.tritonus.org/\n */\n\n/*\n * Copyright (c) 1999 by Matthias Pfisterer\n *\n *\n * Licensed under the Apache License, Ver", "end": 138, "score": 0.999871551990509, "start": 120, "tag": "NAME", "value": "Matthias Pfisterer" } ]
null
[]
/* * FloatControl.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 1999 by <NAME> * * * 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. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package javax.sound.sampled; import org.tritonus.share.TDebug; public abstract class FloatControl extends Control { private float m_fValue; private float m_fMinimum; private float m_fMaximum; private float m_fPrecision; private int m_nUpdatePeriod; private String m_strUnits; private String m_strMinLabel; private String m_strMidLabel; private String m_strMaxLabel; protected FloatControl(Type type, float fMinimum, float fMaximum, float fPrecision, int nUpdatePeriod, float fInitialValue, String strUnits, String strMinLabel, String strMidLabel, String strMaxLabel) { super(type); if (TDebug.TraceControl) { TDebug.out("FloatControl.<init>: begin"); } m_fMinimum = fMinimum; m_fMaximum = fMaximum; m_fPrecision = fPrecision; m_nUpdatePeriod = nUpdatePeriod; //$$fb 2000-12-02: incompatible with Sun implementation... //setValue(fInitialValue); m_fValue = fInitialValue; m_nUpdatePeriod = nUpdatePeriod; m_strMinLabel = strMinLabel; m_strMidLabel = strMidLabel; m_strMaxLabel = strMaxLabel; if (TDebug.TraceControl) { TDebug.out("FloatControl.<init>: end"); } } protected FloatControl(Type type, float fMinimum, float fMaximum, float fPrecision, int nUpdatePeriod, float fInitialValue, String strUnits) { this(type, fMinimum, fMaximum, fPrecision, nUpdatePeriod, fInitialValue, strUnits, "Left", "Center", "Right"); } /** Set the value of the control. If subclasses need to override this method, super.setValue() should be called at the beginning of the overriding implementation. */ public void setValue(float fValue) { m_fValue = fValue; } public float getValue() { return m_fValue; } public float getMaximum() { return m_fMaximum; } public float getMinimum() { return m_fMinimum; } public String getUnits() { return m_strUnits; } public String getMinLabel() { return m_strMinLabel; } public String getMidLabel() { return m_strMidLabel; } public String getMaxLabel() { return m_strMaxLabel; } public float getPrecision() { return m_fPrecision; } public int getUpdatePeriod() { return m_nUpdatePeriod; } public void shift(float fFrom, float fTo, int nMicroseconds) { /* This default implementation is required by the specification. */ setValue(fTo); } public String toString() { return super.toString() + " [value = " + getValue() + "]"; } public static class Type extends Control.Type { public static final Type MASTER_GAIN = new Type("MASTER_GAIN"); public static final Type AUX_SEND = new Type("AUX_SEND"); public static final Type AUX_RETURN = new Type("AUX_RETURN"); public static final Type REVERB_SEND = new Type("REVERB_SEND"); public static final Type REVERB_RETURN = new Type("REVERB_RETURN"); public static final Type VOLUME = new Type("VOLUME"); public static final Type PAN = new Type("PAN"); public static final Type BALANCE = new Type("BALANCE"); //$$fb 2000-12-02: SAMPLE_RATE had been missing public static final Type SAMPLE_RATE = new Type("SAMPLE RATE"); protected Type(String strName) { super(strName); } } } /*** FloatControl.java ***/
4,236
0.657721
0.651601
229
17.545851
20.191525
80
false
false
0
0
0
0
0
0
1.480349
false
false
0
42ad8e261199b29bdf907d978eb591b813b63c67
30,305,289,279,688
9bde77d47d9e70ce35a8b0d65e26c0ce08e1ca3e
/AIGame/src/GameForWhite/AlphaBetaOpening.java
585d1ffe399823ea4e5744581f7b24f99c4858e5
[]
no_license
jovizhu/courseDemo
https://github.com/jovizhu/courseDemo
cbf4ab5d3509301f3028c27bc3459bb5241a0f12
e1a8f358462a67d2c4c832214d67433a73d1e762
refs/heads/master
2021-01-23T17:19:11.117000
2015-10-07T15:41:27
2015-10-07T15:41:27
15,168,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GameForWhite; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; public class AlphaBetaOpening { public static String result = null; public static int estimate_count = 0; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String input = new String(); try { input = in.readLine(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(input.split(" ")[0]); String inputfilename = input.split(" ")[0]; System.out.println(input.split(" ")[1]); String outputfilename = input.split(" ")[1]; String deep = input.split(" ")[2]; System.out.println(input.split(" ")[2]); RandomAccessFile inputfile = null; RandomAccessFile outputfile = null; // inputfile = new String("board1.txt"); String line = null; try { FileInputStream fin = new FileInputStream(inputfilename); BufferedReader reader = new BufferedReader(new InputStreamReader( fin)); line = reader.readLine(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } StringBuffer board = new StringBuffer(line); int turns = new Integer(deep); System.out.println(turns); AlphaBetaOpening alphabetaopening = new AlphaBetaOpening(); int alpha = -1000; int beta = 1000; System.out.println("Final MinMax is "+alphabetaopening.AlphaBetaMaxMin(board, turns, alpha, beta)); System.out.println("Board Position: "+ result); System.out.println("Positon Estimated: "+estimate_count); try { FileOutputStream fos = new FileOutputStream(outputfilename); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); writer.write(alphabetaopening.result); writer.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int AlphaBetaMaxMin(StringBuffer board, int turns, int alpha, int beta) { //System.out.println("Enter into MaxMin "+ board+"turns is " + turns); StringBuffer info = new StringBuffer("Enter into AlphaBetaMaxMin "+ board+" turns is " + turns); String result = null; if(turns == 0) { int maxmin = StaticEstimation.StaticEstimationForOpeining(board); //System.out.println("the leaf for the opeining in maxmin " + maxmin); return maxmin; } ArrayList<StringBuffer> boardlist= MoveGenerator.GenerateMoveOpening(board, 'W'); Iterator<StringBuffer> itr = boardlist.iterator(); turns --; int v = -10000; while(itr.hasNext()) { estimate_count++; StringBuffer child_board = itr.next(); //System.out.println("Calcualte for the "+ child_board + " length is " + boardlist.size()); int minmax= AlphaBetaMinMax(child_board, turns, alpha, beta); if(minmax > v) { v = minmax; result = new String(child_board); } else { if(v > alpha) { alpha = v; } } } info.append("result is " +result); System.out.println(info); AlphaBetaOpening.result = new String(result); return v; } public int AlphaBetaMinMax(StringBuffer board, int turns, int alpha, int beta) { // TODO Auto-generated method stub //System.out.println("Enter into MinMax "+ board+"turns is " + turns); StringBuffer info = new StringBuffer("Enter into AlphaBetaminMax "+ board+" turns is " + turns); String result = null; if(turns == 0) { int minmax = StaticEstimation.StaticEstimationForOpeining(board); //System.out.println("the leaf for the opeining in minmax " + minmax); return minmax; } ArrayList<StringBuffer> boardlist= MoveGenerator.GenerateMoveOpening(board, 'B'); Iterator<StringBuffer> itr = boardlist.iterator(); turns--; int v = 10000; while(itr.hasNext()) { estimate_count++; StringBuffer child_board = itr.next(); //System.out.println(child_board.toString()+" is the child "); int minmax= AlphaBetaMaxMin(child_board, turns, alpha, beta); if(minmax < v) { v = minmax; result = new String(child_board); } else { if(v< beta) { beta = v; } } } info.append("result is " +result); System.out.println(info); return v; } }
UTF-8
Java
4,727
java
AlphaBetaOpening.java
Java
[]
null
[]
package GameForWhite; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; public class AlphaBetaOpening { public static String result = null; public static int estimate_count = 0; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String input = new String(); try { input = in.readLine(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(input.split(" ")[0]); String inputfilename = input.split(" ")[0]; System.out.println(input.split(" ")[1]); String outputfilename = input.split(" ")[1]; String deep = input.split(" ")[2]; System.out.println(input.split(" ")[2]); RandomAccessFile inputfile = null; RandomAccessFile outputfile = null; // inputfile = new String("board1.txt"); String line = null; try { FileInputStream fin = new FileInputStream(inputfilename); BufferedReader reader = new BufferedReader(new InputStreamReader( fin)); line = reader.readLine(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } StringBuffer board = new StringBuffer(line); int turns = new Integer(deep); System.out.println(turns); AlphaBetaOpening alphabetaopening = new AlphaBetaOpening(); int alpha = -1000; int beta = 1000; System.out.println("Final MinMax is "+alphabetaopening.AlphaBetaMaxMin(board, turns, alpha, beta)); System.out.println("Board Position: "+ result); System.out.println("Positon Estimated: "+estimate_count); try { FileOutputStream fos = new FileOutputStream(outputfilename); Writer writer = new BufferedWriter(new OutputStreamWriter(fos)); writer.write(alphabetaopening.result); writer.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int AlphaBetaMaxMin(StringBuffer board, int turns, int alpha, int beta) { //System.out.println("Enter into MaxMin "+ board+"turns is " + turns); StringBuffer info = new StringBuffer("Enter into AlphaBetaMaxMin "+ board+" turns is " + turns); String result = null; if(turns == 0) { int maxmin = StaticEstimation.StaticEstimationForOpeining(board); //System.out.println("the leaf for the opeining in maxmin " + maxmin); return maxmin; } ArrayList<StringBuffer> boardlist= MoveGenerator.GenerateMoveOpening(board, 'W'); Iterator<StringBuffer> itr = boardlist.iterator(); turns --; int v = -10000; while(itr.hasNext()) { estimate_count++; StringBuffer child_board = itr.next(); //System.out.println("Calcualte for the "+ child_board + " length is " + boardlist.size()); int minmax= AlphaBetaMinMax(child_board, turns, alpha, beta); if(minmax > v) { v = minmax; result = new String(child_board); } else { if(v > alpha) { alpha = v; } } } info.append("result is " +result); System.out.println(info); AlphaBetaOpening.result = new String(result); return v; } public int AlphaBetaMinMax(StringBuffer board, int turns, int alpha, int beta) { // TODO Auto-generated method stub //System.out.println("Enter into MinMax "+ board+"turns is " + turns); StringBuffer info = new StringBuffer("Enter into AlphaBetaminMax "+ board+" turns is " + turns); String result = null; if(turns == 0) { int minmax = StaticEstimation.StaticEstimationForOpeining(board); //System.out.println("the leaf for the opeining in minmax " + minmax); return minmax; } ArrayList<StringBuffer> boardlist= MoveGenerator.GenerateMoveOpening(board, 'B'); Iterator<StringBuffer> itr = boardlist.iterator(); turns--; int v = 10000; while(itr.hasNext()) { estimate_count++; StringBuffer child_board = itr.next(); //System.out.println(child_board.toString()+" is the child "); int minmax= AlphaBetaMaxMin(child_board, turns, alpha, beta); if(minmax < v) { v = minmax; result = new String(child_board); } else { if(v< beta) { beta = v; } } } info.append("result is " +result); System.out.println(info); return v; } }
4,727
0.651788
0.645441
177
24.706215
24.737118
103
false
false
0
0
0
0
0
0
2.59887
false
false
0
0f928a66c6c74e252379261751a93f5d90e61f66
3,496,103,445,981
ba41dd8445eeef5eed6032a90ae91178f0860948
/examen_21/Matriz_Cuadrada.java
b37a7434e16a0fa9da6c72907195e6ea4b1453ca
[]
no_license
luis-code-666/lu
https://github.com/luis-code-666/lu
9b1ff37ccaecbab7721aacf1321686ba8438d695
ff6289d9d7e19342d9f4eb93f3ab2d9a3f40c830
refs/heads/main
2023-03-25T11:11:01.204000
2021-03-27T13:31:19
2021-03-27T13:31:19
352,086,096
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package examen_21; public class Matriz_Cuadrada { public static void main (String[] args) { int matriz[][] = new int [6][6]; for(int i=1; i<5; i++) { System.out.println(); for(int j=1;j<5;j++){ matriz[i][j] = j*2; System.out.println(matriz[i][j]+ " "); } } } }
UTF-8
Java
292
java
Matriz_Cuadrada.java
Java
[]
null
[]
package examen_21; public class Matriz_Cuadrada { public static void main (String[] args) { int matriz[][] = new int [6][6]; for(int i=1; i<5; i++) { System.out.println(); for(int j=1;j<5;j++){ matriz[i][j] = j*2; System.out.println(matriz[i][j]+ " "); } } } }
292
0.544521
0.513699
16
17.25
14.880776
42
false
false
0
0
0
0
0
0
2.3125
false
false
0
aed4f6ef76a7c92240e4ed8abd8241a099d256b1
3,496,103,448,933
61c1f7bf267fd1a6ae9cb050c3a27ec9dead5035
/src/ua/nure/bogdanov/SummaryTask4/web/command/ListTestsCommand.java
1f91869393a76bd835830a0c32b9a6767d3d1f1f
[]
no_license
bbengamin/finalTask4
https://github.com/bbengamin/finalTask4
0342b63bb1d3200daa1d7708c995b831ff1a8a2f
bc50cc32c83b3d0e33fbd0ac4d8bc1f1449673b2
refs/heads/master
2021-01-10T14:06:43.731000
2016-03-05T10:14:52
2016-03-05T10:14:52
53,195,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.nure.bogdanov.SummaryTask4.web.command; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import ua.nure.bogdanov.SummaryTask4.Path; import ua.nure.bogdanov.SummaryTask4.db.DBManager; import ua.nure.bogdanov.SummaryTask4.db.bean.TestBean; import ua.nure.bogdanov.SummaryTask4.db.entity.Subject; import ua.nure.bogdanov.SummaryTask4.exception.AppException; import ua.nure.bogdanov.SummaryTask4.web.command.Command; /** * List test command * * @author I.Bogdanov * */ public class ListTestsCommand extends Command { private static final long serialVersionUID = -5498433181969451372L; private static final Logger LOG = Logger.getLogger(ListTestsCommand.class); @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, AppException { LOG.debug("Command starts"); DBManager manager = DBManager.getInstance(); // get test items list List<TestBean> listTestsBeans = manager.findAllTestsBean(); LOG.trace("Found in DB: listTestsBeans --> " + listTestsBeans); List<Subject> subjects = manager.findAllSubjects(); LOG.trace("Set the request attribute: subjects --> " + subjects); request.setAttribute("subjects", subjects); long idTestMinResult = 0; double minResult = 100; for (TestBean test : listTestsBeans) { double result = manager.getTestResult(test.getId()); if (result < minResult) { idTestMinResult = test.getId(); minResult = result; } } // sort test by name Collections.sort(listTestsBeans, new Comparator<TestBean>() { public int compare(TestBean o1, TestBean o2) { return o1.getName().compareTo(o2.getName()); } }); request.setAttribute("minResult", idTestMinResult); LOG.trace("Set the request attribute: minResult --> " + idTestMinResult); // put test items list to the request request.setAttribute("listTestsBeans", listTestsBeans); LOG.trace("Set the request attribute: listTestsBeans --> " + listTestsBeans); LOG.debug("Command finished"); return Path.PAGE_INDEX; } }
UTF-8
Java
2,291
java
ListTestsCommand.java
Java
[ { "context": ".Command;\n\n/**\n * List test command\n * \n * @author I.Bogdanov\n * \n */\npublic class ListTestsCommand extends Com", "end": 704, "score": 0.9997873902320862, "start": 694, "tag": "NAME", "value": "I.Bogdanov" } ]
null
[]
package ua.nure.bogdanov.SummaryTask4.web.command; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import ua.nure.bogdanov.SummaryTask4.Path; import ua.nure.bogdanov.SummaryTask4.db.DBManager; import ua.nure.bogdanov.SummaryTask4.db.bean.TestBean; import ua.nure.bogdanov.SummaryTask4.db.entity.Subject; import ua.nure.bogdanov.SummaryTask4.exception.AppException; import ua.nure.bogdanov.SummaryTask4.web.command.Command; /** * List test command * * @author I.Bogdanov * */ public class ListTestsCommand extends Command { private static final long serialVersionUID = -5498433181969451372L; private static final Logger LOG = Logger.getLogger(ListTestsCommand.class); @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, AppException { LOG.debug("Command starts"); DBManager manager = DBManager.getInstance(); // get test items list List<TestBean> listTestsBeans = manager.findAllTestsBean(); LOG.trace("Found in DB: listTestsBeans --> " + listTestsBeans); List<Subject> subjects = manager.findAllSubjects(); LOG.trace("Set the request attribute: subjects --> " + subjects); request.setAttribute("subjects", subjects); long idTestMinResult = 0; double minResult = 100; for (TestBean test : listTestsBeans) { double result = manager.getTestResult(test.getId()); if (result < minResult) { idTestMinResult = test.getId(); minResult = result; } } // sort test by name Collections.sort(listTestsBeans, new Comparator<TestBean>() { public int compare(TestBean o1, TestBean o2) { return o1.getName().compareTo(o2.getName()); } }); request.setAttribute("minResult", idTestMinResult); LOG.trace("Set the request attribute: minResult --> " + idTestMinResult); // put test items list to the request request.setAttribute("listTestsBeans", listTestsBeans); LOG.trace("Set the request attribute: listTestsBeans --> " + listTestsBeans); LOG.debug("Command finished"); return Path.PAGE_INDEX; } }
2,291
0.751637
0.73636
78
28.371796
24.011274
76
false
false
0
0
0
0
0
0
1.679487
false
false
0
c09cb19c655040c670f88baf82dcff628a2b72ce
2,877,628,133,558
834da2aea4110bd1fb54ea8f542dd3ac1d980e90
/chippai/src/test/java/com/chippai/design/proxy/IDBQuery.java
9922ebea4882c872c117083e98e2787bd6333fd3
[]
no_license
yggcyi/shinobu
https://github.com/yggcyi/shinobu
acedfc44b2ee67b0c8c2519e2f36bec5fcc8e406
9d9566142fef429f896db992454ba2ed0acf37ab
refs/heads/master
2019-03-31T07:59:29.655000
2018-02-14T08:37:11
2018-02-14T08:37:11
83,307,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chippai.design.proxy; /** * Created by ygcyi on 2017/9/24. */ public interface IDBQuery { String request(); }
UTF-8
Java
130
java
IDBQuery.java
Java
[ { "context": "ckage com.chippai.design.proxy;\n\n/**\n * Created by ygcyi on 2017/9/24.\n */\npublic interface IDBQuery {\n\n ", "end": 58, "score": 0.9994704723358154, "start": 53, "tag": "USERNAME", "value": "ygcyi" } ]
null
[]
package com.chippai.design.proxy; /** * Created by ygcyi on 2017/9/24. */ public interface IDBQuery { String request(); }
130
0.669231
0.615385
9
13.444445
13.905324
33
false
false
0
0
0
0
0
0
0.222222
false
false
0
bdf7ede12741f0ad6a268cab845d561fafa65a2a
1,133,871,436,532
8f5bd100ce38515f1e3870e846c04d628575f10f
/javascript/src/ajax/Test05.java
9a21ef008809257ac2f6bc8b91310aa33d351a48
[]
no_license
jonginout/JAVA_STUDY_BASIC
https://github.com/jonginout/JAVA_STUDY_BASIC
742f2215e0b6f454bc5688e787997f5be5a8f990
ba4f1993c9c2559cd86a13596c86257707307893
refs/heads/master
2022-10-30T17:06:50.860000
2018-01-21T19:31:10
2018-01-21T19:31:10
109,293,198
0
1
null
false
2022-10-19T13:51:40
2017-11-02T16:47:38
2019-10-03T14:54:01
2022-10-19T13:51:40
49,200
0
1
1
JavaScript
false
false
package ajax; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet("/08_ajax/test05") public class Test05 extends HttpServlet{ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); List<AjaxVO> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { AjaxVO vo = new AjaxVO(); vo.setName("길수"+i); vo.setEmail("ajdskj"+i+"@naber.com"); vo.setAge(20+i); vo.toString(); list.add(vo); } response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.println(new Gson().toJson(list)); out.close(); } }
UTF-8
Java
1,021
java
Test05.java
Java
[ { "context": " AjaxVO();\n\t\t\tvo.setName(\"길수\"+i);\n\t\t\tvo.setEmail(\"ajdskj\"+i+\"@naber.com\");\n\t\t\tvo.setAge(20+i);\n\t\t\tvo.toString();\n\t\t\tlist.", "end": 791, "score": 0.9540104269981384, "start": 770, "tag": "EMAIL", "value": "ajdskj\"+i+\"@naber.com" } ]
null
[]
package ajax; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet("/08_ajax/test05") public class Test05 extends HttpServlet{ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); List<AjaxVO> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { AjaxVO vo = new AjaxVO(); vo.setName("길수"+i); vo.setEmail("<EMAIL>"); vo.setAge(20+i); vo.toString(); list.add(vo); } response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.println(new Gson().toJson(list)); out.close(); } }
1,007
0.723697
0.711898
42
23.214285
18.999418
82
false
false
0
0
0
0
0
0
1.880952
false
false
0
e4403ef0484bfc79498280f7861569164da0c5ad
7,962,869,373,044
0bcb4e3e8a4043775bf93f7216e113ca076fcae4
/New Resolutions/Fichas/Ficha 3/PROPOSTA DE RESOLUCAO/Exerc2.java
0231f6efad46f8ce8f3a834fd7f43bb725bce024
[]
no_license
ZePedroFernandes/SO
https://github.com/ZePedroFernandes/SO
0ef65bf34f6da965b3e30f18c61497ddcdc375ab
c84ed35991ac4146a0aeba4037c548ca486bb9cf
refs/heads/master
2023-03-28T21:28:15.135000
2021-04-02T14:23:11
2021-04-02T14:23:11
314,023,183
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Exerc2 implements Runnable { private final int id; Exerc2(int id) { this.id = id; } public void run() { System.out.println("[Th" + id + "] Eu sou uma thread, dude..."); //System.out.println("[Th" + Thread.currentThread().getName() + "] Eu sou uma thread, dude..."); } public static void main(String[] args) { if (args.length != 1) { System.err.println("Modo de uso: java Exerc2 <número de threads a criar>"); System.exit(0); } final int count = Integer.parseInt(args[0]); Thread[] th = new Thread[count]; for (int i = 0; i < count; i++) { Exerc2 ex2 = new Exerc2(i); th[i] = new Thread(ex2); //th[i].setName( Integer.toString( i ) ); th[i].start(); // numa linha só // ( new Thread( new Exerc1() ) ).start(); } } }
UTF-8
Java
936
java
Exerc2.java
Java
[]
null
[]
public class Exerc2 implements Runnable { private final int id; Exerc2(int id) { this.id = id; } public void run() { System.out.println("[Th" + id + "] Eu sou uma thread, dude..."); //System.out.println("[Th" + Thread.currentThread().getName() + "] Eu sou uma thread, dude..."); } public static void main(String[] args) { if (args.length != 1) { System.err.println("Modo de uso: java Exerc2 <número de threads a criar>"); System.exit(0); } final int count = Integer.parseInt(args[0]); Thread[] th = new Thread[count]; for (int i = 0; i < count; i++) { Exerc2 ex2 = new Exerc2(i); th[i] = new Thread(ex2); //th[i].setName( Integer.toString( i ) ); th[i].start(); // numa linha só // ( new Thread( new Exerc1() ) ).start(); } } }
936
0.498929
0.486081
35
25.657143
26.216618
104
false
false
0
0
0
0
0
0
0.485714
false
false
0
9473c453f96b2e58c4df903dc880004221481c3d
23,854,248,374,197
144d2f70e94d3c54bc2c0ac18818d0151ef21f21
/app/src/main/java/com/punchcard/app/dao/DBHelper.java
ca02df390b3d604aa781a590fd9010447fb0224b
[]
no_license
stylocool/punchcard-android
https://github.com/stylocool/punchcard-android
671b1ca6730c303c52dfed2f19b48b4d2a085678
89125baae06cdbd020c3e804b8f111cfae05b46f
refs/heads/master
2021-01-23T09:33:59.141000
2015-05-06T16:12:11
2015-05-06T16:12:11
33,872,850
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.punchcard.app.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBHelper extends SQLiteOpenHelper { private static final String TAG = DBHelper.class.getName(); private static final String DATABASE_NAME = "punchcard.db"; private static final int DATABASE_VERSION = 1; private CompanyDataSource companyDS = null; private ProjectDataSource projectDS = null; private PunchcardDataSource punchcardDS = null; private UserDataSource userDS = null; private WorkerDataSource workerDS = null; private SQLiteDatabase database = null; //private static DBHelper instance = null; private Context context; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; database = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase database) { Log.i(TAG, "Creating company table"); database.execSQL(CompanyDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating project table"); database.execSQL(ProjectDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating punchcard table"); database.execSQL(PunchcardDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating user table"); database.execSQL(UserDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating worker table"); database.execSQL(WorkerDBHelper.DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + CompanyDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + ProjectDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + PunchcardDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + UserDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + WorkerDBHelper.TABLE); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } public SQLiteDatabase getDatabase() { return database; } public synchronized CompanyDataSource getCompanyDS() { if (companyDS == null) { companyDS = new CompanyDataSource(this); } return companyDS; } public synchronized ProjectDataSource getProjectDS() { if (projectDS == null) { projectDS = new ProjectDataSource(this); } return projectDS; } public synchronized PunchcardDataSource getPunchcardDS() { if (punchcardDS == null) { punchcardDS = new PunchcardDataSource(this); } return punchcardDS; } public synchronized UserDataSource getUserDS() { if (userDS == null) { userDS = new UserDataSource(this); } return userDS; } public synchronized WorkerDataSource getWorkerDS() { if (workerDS == null) { workerDS = new WorkerDataSource(this); } return workerDS; } }
UTF-8
Java
3,195
java
DBHelper.java
Java
[]
null
[]
package com.punchcard.app.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBHelper extends SQLiteOpenHelper { private static final String TAG = DBHelper.class.getName(); private static final String DATABASE_NAME = "punchcard.db"; private static final int DATABASE_VERSION = 1; private CompanyDataSource companyDS = null; private ProjectDataSource projectDS = null; private PunchcardDataSource punchcardDS = null; private UserDataSource userDS = null; private WorkerDataSource workerDS = null; private SQLiteDatabase database = null; //private static DBHelper instance = null; private Context context; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; database = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase database) { Log.i(TAG, "Creating company table"); database.execSQL(CompanyDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating project table"); database.execSQL(ProjectDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating punchcard table"); database.execSQL(PunchcardDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating user table"); database.execSQL(UserDBHelper.DATABASE_CREATE); Log.i(TAG, "Creating worker table"); database.execSQL(WorkerDBHelper.DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + CompanyDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + ProjectDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + PunchcardDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + UserDBHelper.TABLE); db.execSQL("DROP TABLE IF EXISTS " + WorkerDBHelper.TABLE); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } public SQLiteDatabase getDatabase() { return database; } public synchronized CompanyDataSource getCompanyDS() { if (companyDS == null) { companyDS = new CompanyDataSource(this); } return companyDS; } public synchronized ProjectDataSource getProjectDS() { if (projectDS == null) { projectDS = new ProjectDataSource(this); } return projectDS; } public synchronized PunchcardDataSource getPunchcardDS() { if (punchcardDS == null) { punchcardDS = new PunchcardDataSource(this); } return punchcardDS; } public synchronized UserDataSource getUserDS() { if (userDS == null) { userDS = new UserDataSource(this); } return userDS; } public synchronized WorkerDataSource getWorkerDS() { if (workerDS == null) { workerDS = new WorkerDataSource(this); } return workerDS; } }
3,195
0.683255
0.682942
103
30.019417
25.560884
122
false
false
0
0
0
0
0
0
1.019418
false
false
0
2fd05c86d80b62ba1aa08ade87de3df2276c865c
32,796,370,292,296
bcd2705164ecd4d4585ccd06aa11eafc4d3c3ee2
/MOAPRec/src/arida/ufc/br/moap/rec/database/RecommendationDB.java
c3708884c1a81900bba364ead3477ae3c5069a10
[]
no_license
jmacedoj/moap
https://github.com/jmacedoj/moap
ed844979a5e3142901874af80630277c1558a8df
75230152ba866acdcab0bc8a57bd7d71d6e0a871
refs/heads/master
2021-01-20T23:38:04.280000
2012-11-13T00:23:48
2012-11-13T00:23:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package arida.ufc.br.moap.rec.database; import arida.ufc.br.moap.core.beans.Poi; import arida.ufc.br.moap.db.postgres.imp.PostgresqlProvider; import arida.ufc.br.moap.rec.algorithms.TopK; import arida.ufc.br.moap.rec.location.beans.RecommendationSet; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import org.apache.log4j.Logger; //import arida.ufc.br.moap. /** * * @author igobrilhante */ public class RecommendationDB { private static Logger logger = Logger.getLogger(RecommendationDB.class); /** * * @param <U> * @param <I> * @param dataset * @param table_name * @throws SQLException * @throws Exception */ public static synchronized <U, I> void storeRecommendation(RecommendationSet<U, I> dataset,String table_name) throws SQLException, Exception{ PostgresqlProvider db = new PostgresqlProvider(); db.createTable(table_name, "userid text, itemid text, rating numeric "); PreparedStatement ps = PostgresqlProvider.getConnection().prepareStatement( "INSERT INTO "+table_name+" VALUES (?,?,?)"); for(U user : dataset.getUsers()){ Set<I> items = dataset.getItems(user); for(I item : items){ double rating = dataset.getRating(user, item); ps.setString(1, user.toString()); ps.setString(2, item.toString()); ps.setDouble(3, rating); ps.addBatch(); } int[] r = ps.executeBatch(); logger.info("Commiting "+r.length); } ps.close(); } public static synchronized <I extends Comparable> void storeRecommendation(RecommendationSet dataset,int k,String table_name) throws SQLException, Exception{ PostgresqlProvider db = new PostgresqlProvider(); db.createTable(table_name, "userid text, itemid text, rating numeric "); PreparedStatement ps = PostgresqlProvider.getConnection().prepareStatement( "INSERT INTO "+table_name+" VALUES (?,?,?)"); for(Object user : dataset.getUsers()){ Map<I,Double> items = dataset.getItemRatings(user); SortedMap<I,Double> sorted_items = TopK.getTopK(dataset.getItemRatings(user), k); for(Object item : sorted_items.keySet()){ double rating = dataset.getRating(user, item); ps.setString(1, user.toString()); ps.setString(2, item.toString()); ps.setDouble(3, rating); ps.addBatch(); } int[] r = ps.executeBatch(); logger.info("Commiting "+r.length); } ps.close(); } public static synchronized RecommendationSet loadRecommendation(String table_name) throws SQLException{ logger.info("Load Recommendation"); PostgresqlProvider db = new PostgresqlProvider(); ResultSet rs = db.getResultSet(table_name); RecommendationSet rec = new RecommendationSet(); String previous_user = "-1"; while(rs.next()){ String userid = rs.getString("userid"); String itemid = rs.getString("itemid"); Double rating = rs.getDouble("rating"); if(!userid.equals(previous_user)){ rec.addUser(userid); } rec.addUserItem(userid, itemid, rating); previous_user = userid; } return rec; } public static synchronized RecommendationSet loadRecommendation(int top_k,String table_name) throws SQLException{ logger.info("Load Recommendation"); PostgresqlProvider db = new PostgresqlProvider(); ResultSet rs = db.getResultSet(table_name); RecommendationSet rec = new RecommendationSet(); Map<String,Double> items = null; String previous_user = "-1"; while(rs.next()){ String userid = rs.getString("userid"); String itemid = rs.getString("itemid"); Double rating = rs.getDouble("rating"); if(!userid.equals(previous_user)){ if(!previous_user.equals("-1")){ SortedMap<String,Double> sorted_items = TopK.getTopK(items, top_k); rec.addUser(previous_user, sorted_items); } items = new HashMap<String, Double>(); } items.put(itemid, rating); previous_user = userid; } if(!items.isEmpty()){ SortedMap<String,Double> sorted_items = TopK.getTopK(items, top_k); rec.addUser(previous_user, sorted_items); } return rec; } public static synchronized Set<Poi> loadPoiSet(String poi_table) throws SQLException{ logger.info("Load Poi Set"); Map<String,Poi> map = new HashMap<String, Poi>(); Set<Poi> pois = new HashSet<Poi>(); PostgresqlProvider db = new PostgresqlProvider(); ResultSet rs = db.getResultSet(poi_table); Poi poi = null; while(rs.next()){ String poi_id = rs.getString("poi_id"); String category = rs.getString("poi_category"); if(!map.containsKey(poi_id)){ poi = new Poi(poi_id); poi.getAnnotations().addAnnotation("categories", "set", new HashSet<Object>()); ((Set)poi.getAnnotations().getAnnotation("categories").getValue()).add(category); map.put(poi_id, poi); } else{ ((Set)map.get(poi_id).getAnnotations().getAnnotation("categories").getValue()).add(category); } // if(poi_id.equals(previous_poi)){ // ((Set)poi.getAnnotations().getAnnotation("category").getValue()).add(category); // } // else{ // if(!previous_poi.equals("-1")){ // pois.add(poi); // poi=null; // } // poi = new Poi(poi_id); // poi.getAnnotations().addAnnotation("category", "set", new HashSet<Object>()); // ((Set)poi.getAnnotations().getAnnotation("category").getValue()).add(category); // } // previous_poi = poi_id; } // if(poi!=null){ // pois.add(poi); // } for(Poi p : map.values()){ pois.add(p); } return pois; } }
UTF-8
Java
7,026
java
RecommendationDB.java
Java
[ { "context": "\n//import arida.ufc.br.moap.\n\n\n/**\n * \n * @author igobrilhante\n */\npublic class RecommendationDB {\n\tprivate stat", "end": 457, "score": 0.998855471611023, "start": 445, "tag": "USERNAME", "value": "igobrilhante" } ]
null
[]
package arida.ufc.br.moap.rec.database; import arida.ufc.br.moap.core.beans.Poi; import arida.ufc.br.moap.db.postgres.imp.PostgresqlProvider; import arida.ufc.br.moap.rec.algorithms.TopK; import arida.ufc.br.moap.rec.location.beans.RecommendationSet; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import org.apache.log4j.Logger; //import arida.ufc.br.moap. /** * * @author igobrilhante */ public class RecommendationDB { private static Logger logger = Logger.getLogger(RecommendationDB.class); /** * * @param <U> * @param <I> * @param dataset * @param table_name * @throws SQLException * @throws Exception */ public static synchronized <U, I> void storeRecommendation(RecommendationSet<U, I> dataset,String table_name) throws SQLException, Exception{ PostgresqlProvider db = new PostgresqlProvider(); db.createTable(table_name, "userid text, itemid text, rating numeric "); PreparedStatement ps = PostgresqlProvider.getConnection().prepareStatement( "INSERT INTO "+table_name+" VALUES (?,?,?)"); for(U user : dataset.getUsers()){ Set<I> items = dataset.getItems(user); for(I item : items){ double rating = dataset.getRating(user, item); ps.setString(1, user.toString()); ps.setString(2, item.toString()); ps.setDouble(3, rating); ps.addBatch(); } int[] r = ps.executeBatch(); logger.info("Commiting "+r.length); } ps.close(); } public static synchronized <I extends Comparable> void storeRecommendation(RecommendationSet dataset,int k,String table_name) throws SQLException, Exception{ PostgresqlProvider db = new PostgresqlProvider(); db.createTable(table_name, "userid text, itemid text, rating numeric "); PreparedStatement ps = PostgresqlProvider.getConnection().prepareStatement( "INSERT INTO "+table_name+" VALUES (?,?,?)"); for(Object user : dataset.getUsers()){ Map<I,Double> items = dataset.getItemRatings(user); SortedMap<I,Double> sorted_items = TopK.getTopK(dataset.getItemRatings(user), k); for(Object item : sorted_items.keySet()){ double rating = dataset.getRating(user, item); ps.setString(1, user.toString()); ps.setString(2, item.toString()); ps.setDouble(3, rating); ps.addBatch(); } int[] r = ps.executeBatch(); logger.info("Commiting "+r.length); } ps.close(); } public static synchronized RecommendationSet loadRecommendation(String table_name) throws SQLException{ logger.info("Load Recommendation"); PostgresqlProvider db = new PostgresqlProvider(); ResultSet rs = db.getResultSet(table_name); RecommendationSet rec = new RecommendationSet(); String previous_user = "-1"; while(rs.next()){ String userid = rs.getString("userid"); String itemid = rs.getString("itemid"); Double rating = rs.getDouble("rating"); if(!userid.equals(previous_user)){ rec.addUser(userid); } rec.addUserItem(userid, itemid, rating); previous_user = userid; } return rec; } public static synchronized RecommendationSet loadRecommendation(int top_k,String table_name) throws SQLException{ logger.info("Load Recommendation"); PostgresqlProvider db = new PostgresqlProvider(); ResultSet rs = db.getResultSet(table_name); RecommendationSet rec = new RecommendationSet(); Map<String,Double> items = null; String previous_user = "-1"; while(rs.next()){ String userid = rs.getString("userid"); String itemid = rs.getString("itemid"); Double rating = rs.getDouble("rating"); if(!userid.equals(previous_user)){ if(!previous_user.equals("-1")){ SortedMap<String,Double> sorted_items = TopK.getTopK(items, top_k); rec.addUser(previous_user, sorted_items); } items = new HashMap<String, Double>(); } items.put(itemid, rating); previous_user = userid; } if(!items.isEmpty()){ SortedMap<String,Double> sorted_items = TopK.getTopK(items, top_k); rec.addUser(previous_user, sorted_items); } return rec; } public static synchronized Set<Poi> loadPoiSet(String poi_table) throws SQLException{ logger.info("Load Poi Set"); Map<String,Poi> map = new HashMap<String, Poi>(); Set<Poi> pois = new HashSet<Poi>(); PostgresqlProvider db = new PostgresqlProvider(); ResultSet rs = db.getResultSet(poi_table); Poi poi = null; while(rs.next()){ String poi_id = rs.getString("poi_id"); String category = rs.getString("poi_category"); if(!map.containsKey(poi_id)){ poi = new Poi(poi_id); poi.getAnnotations().addAnnotation("categories", "set", new HashSet<Object>()); ((Set)poi.getAnnotations().getAnnotation("categories").getValue()).add(category); map.put(poi_id, poi); } else{ ((Set)map.get(poi_id).getAnnotations().getAnnotation("categories").getValue()).add(category); } // if(poi_id.equals(previous_poi)){ // ((Set)poi.getAnnotations().getAnnotation("category").getValue()).add(category); // } // else{ // if(!previous_poi.equals("-1")){ // pois.add(poi); // poi=null; // } // poi = new Poi(poi_id); // poi.getAnnotations().addAnnotation("category", "set", new HashSet<Object>()); // ((Set)poi.getAnnotations().getAnnotation("category").getValue()).add(category); // } // previous_poi = poi_id; } // if(poi!=null){ // pois.add(poi); // } for(Poi p : map.values()){ pois.add(p); } return pois; } }
7,026
0.528608
0.527042
188
36.372341
28.497101
165
false
false
0
0
0
0
0
0
1.351064
false
false
0
327f353f510b2d08f516c2f776cca0614e8aeba9
17,317,308,153,703
acf2570df42cb7df347930afa543911b70a0ebe4
/springmvc-websocket/src/main/java/com/listener/WebSocketListener.java
6928d42401329b775b211f43e22c32a6697ae537
[]
no_license
AIFEINIK/SpringMVC
https://github.com/AIFEINIK/SpringMVC
6159ef94f0b7eb2ac198bd9710801dd10156478c
2894d24e9d087f5f6a00916002e3c855a82d6b20
refs/heads/master
2020-04-13T22:32:13.625000
2018-12-29T06:11:20
2018-12-29T06:11:20
163,481,450
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.listener; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import org.springframework.web.socket.messaging.SessionDisconnectEvent; /** * @author Feinik * @Discription 监听客户端是否断开连接 * @Data 2018/12/28 * @Version 1.0.0 */ @Component public class WebSocketListener { @EventListener public void onApplicationEvent(SessionDisconnectEvent event) { System.out.println("客户端断开连接了:" + event.getUser().getName()); } }
UTF-8
Java
541
java
WebSocketListener.java
Java
[ { "context": ".messaging.SessionDisconnectEvent;\n\n/**\n * @author Feinik\n * @Discription 监听客户端是否断开连接\n * @Data 2018/12/28\n ", "end": 222, "score": 0.9833073616027832, "start": 216, "tag": "USERNAME", "value": "Feinik" } ]
null
[]
package com.listener; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import org.springframework.web.socket.messaging.SessionDisconnectEvent; /** * @author Feinik * @Discription 监听客户端是否断开连接 * @Data 2018/12/28 * @Version 1.0.0 */ @Component public class WebSocketListener { @EventListener public void onApplicationEvent(SessionDisconnectEvent event) { System.out.println("客户端断开连接了:" + event.getUser().getName()); } }
541
0.754491
0.732535
20
24.049999
23.856812
71
false
false
0
0
0
0
0
0
0.25
false
false
0
c80f84937704f77095f043a80090dfdb63e98c7c
3,049,426,800,118
b6b5ef77602b4f2bf4885666dc065699a45d2e9c
/src/Stack/MaximumFrequencyStack.java
1ca32ca72921189dac35faa062e5067e45ddf5ad
[]
no_license
bhumika-satpathy/verbose-dsa-interview-prep-guide
https://github.com/bhumika-satpathy/verbose-dsa-interview-prep-guide
23bbfd269a95b3828984b69800b2389823fdbc9a
424ad3fcdac91726258b561abe5ce6d4b5fb6a2d
refs/heads/master
2023-07-21T19:22:25.072000
2021-08-23T14:10:23
2021-08-23T14:10:23
359,200,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Stack; import java.util.HashMap; import java.util.Map; import java.util.Stack; // Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. // //Implement the FreqStack class: // //FreqStack() constructs an empty frequency stack. //void push(int val) pushes an integer val onto the top of the stack. //int pop() removes and returns the most frequent element in the stack. //If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. // public class MaximumFrequencyStack { HashMap<Integer, Integer> freq; Map<Integer, Stack<Integer>> frequenciesHavingElements; int maxFreq; public MaximumFrequencyStack() { freq = new HashMap<>(); frequenciesHavingElements = new HashMap<>(); maxFreq = 0; } public void push(int val) { int f = freq.getOrDefault(val, 0) + 1; freq.put(val, f); if(maxFreq < f){ maxFreq = f; } frequenciesHavingElements.computeIfAbsent(f, z-> new Stack()).push(val); } public int pop() { int x = frequenciesHavingElements.get(maxFreq).pop(); freq.put(x, freq.get(x) - 1); if(frequenciesHavingElements.get(maxFreq).size() == 0){ maxFreq--; } return x; } }
UTF-8
Java
1,358
java
MaximumFrequencyStack.java
Java
[]
null
[]
package Stack; import java.util.HashMap; import java.util.Map; import java.util.Stack; // Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. // //Implement the FreqStack class: // //FreqStack() constructs an empty frequency stack. //void push(int val) pushes an integer val onto the top of the stack. //int pop() removes and returns the most frequent element in the stack. //If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. // public class MaximumFrequencyStack { HashMap<Integer, Integer> freq; Map<Integer, Stack<Integer>> frequenciesHavingElements; int maxFreq; public MaximumFrequencyStack() { freq = new HashMap<>(); frequenciesHavingElements = new HashMap<>(); maxFreq = 0; } public void push(int val) { int f = freq.getOrDefault(val, 0) + 1; freq.put(val, f); if(maxFreq < f){ maxFreq = f; } frequenciesHavingElements.computeIfAbsent(f, z-> new Stack()).push(val); } public int pop() { int x = frequenciesHavingElements.get(maxFreq).pop(); freq.put(x, freq.get(x) - 1); if(frequenciesHavingElements.get(maxFreq).size() == 0){ maxFreq--; } return x; } }
1,358
0.648012
0.64433
45
29.177778
28.647505
117
false
false
0
0
0
0
0
0
0.555556
false
false
0
564a7fe9d1bcfb03b0538befe0bff465d9d0874b
3,075,196,647,045
8021aac5c61bd196df1a7c3c5ae771afa3a45433
/forms-drawer/src/main/java/com/labouardy/app/MyCanvas.java
7df096e5c67b2b2e725ed832056b89a9e97b0876
[]
no_license
mlabouardy/Form-drawers
https://github.com/mlabouardy/Form-drawers
aef47a3641a3495c92a8555de277c2b6e703e4c9
0f1a5f83fd0363bce974f707e8c8d4117b64b1d9
refs/heads/master
2021-01-10T06:07:19.546000
2015-10-06T13:23:02
2015-10-06T13:23:02
43,751,761
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.labouardy.app; import java.awt.Color; import java.awt.Graphics; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import com.labouardy.model.Form; public class MyCanvas extends JPanel { private List<Form> forms; public MyCanvas(List<Form> forms, int width, int height){ this.forms=forms; setBackground(Color.WHITE); setSize(width, height); setBackground(Color.WHITE); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { super.paintComponent(g); for(Form f:forms){ f.draw(g); } } }
UTF-8
Java
676
java
MyCanvas.java
Java
[]
null
[]
package com.labouardy.app; import java.awt.Color; import java.awt.Graphics; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import com.labouardy.model.Form; public class MyCanvas extends JPanel { private List<Form> forms; public MyCanvas(List<Form> forms, int width, int height){ this.forms=forms; setBackground(Color.WHITE); setSize(width, height); setBackground(Color.WHITE); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { super.paintComponent(g); for(Form f:forms){ f.draw(g); } } }
676
0.705621
0.705621
32
20.125
16.560024
58
false
false
0
0
0
0
0
0
1.15625
false
false
0
26a8d1b2f3069e18874436b8950a60aad76bc118
5,351,529,260,832
cb68a1d0dcd499662c91cebb3b4bc62499e75db7
/bundles/core/src/main/java/com/adobe/aem/mobile/commons/core/impl/rewriter/AssetsPathRewriterTransformerFactory.java
ba884a396edf63b3baa06f541158c021faeba37a
[ "Apache-2.0" ]
permissive
Adobe-Marketing-Cloud-Apps/aem-mobile-commons
https://github.com/Adobe-Marketing-Cloud-Apps/aem-mobile-commons
b5a9f037f49cee40b5e5d9de7a7dc25b31957afd
8d4666f0211f5f4042cbb5e5ea9172e837525e01
refs/heads/master
2021-01-13T10:30:49.750000
2016-09-26T14:10:11
2016-09-26T14:10:11
68,726,828
1
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adobe.aem.mobile.commons.core.impl.rewriter; import com.adobe.acs.commons.rewriter.AbstractTransformer; import com.adobe.acs.commons.util.ParameterUtil; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.*; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.commons.osgi.PropertiesUtil; import org.apache.sling.rewriter.ProcessingComponentConfiguration; import org.apache.sling.rewriter.ProcessingContext; import org.apache.sling.rewriter.Transformer; import org.apache.sling.rewriter.TransformerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import java.io.IOException; import java.util.Map; /** * TODO: Convert to use AbstractSlingResourceUpdateHandler. But this would require a dependency on the unobfuscated jar. */ @Component( label = "AEM Mobile Commons - Assets Path Rewriter Factory", description = "Rewriter pipeline component which rewrites paths of assets to be relative", metatype = true) @Properties({ @Property( label = "Rewriter Pipeline Type", description = "Type identifier to be referenced in rewriter pipeline configuration.", name = "pipeline.type", value = "aem-mobile-commons-asset-path", propertyPrivate = true) }) @Service @SuppressWarnings("unused") public class AssetsPathRewriterTransformerFactory implements TransformerFactory { @Property(value = {"source:src", "video:poster"} ) private static final String PROPERTY_ASSETS_MAPPING = "mapping.assets"; private static final Logger log = LoggerFactory.getLogger(AssetsPathRewriterTransformerFactory.class); private static final String[] DEFAULT_ATTRIBUTES = new String[]{"source:src", "video:poster"}; private static final String DAM_PATH_PREFIX = "/content/dam"; private Map<String, String[]> attributes; @Activate protected void activate(final Map<String, Object> config) { final String[] attrProp = PropertiesUtil.toStringArray(config.get(PROPERTY_ASSETS_MAPPING), DEFAULT_ATTRIBUTES); this.attributes = ParameterUtil.toMap( attrProp, ":", "," ); } protected Attributes rebuildAttributes(final SlingHttpServletRequest slingRequest, final String elementName, final Attributes attrs) { boolean rewriteLinks = false; if( slingRequest != null ){ Object object = slingRequest.getAttribute( "publishPathRewritingOptions" ); log.info( "publishPathRewritingOptions {}", object ); if( object != null ){ rewriteLinks = true; } } if (slingRequest == null || !attributes.containsKey(elementName) ) { // element is not defined as a candidate to rewrite return attrs; } final String[] modifiableAttributes = attributes.get(elementName); // clone the attributes final AttributesImpl newAttrs = new AttributesImpl(attrs); final int len = newAttrs.getLength(); for (int i = 0; i < len; i++) { final String attrName = newAttrs.getLocalName(i); if (ArrayUtils.contains(modifiableAttributes, attrName)) { final String attrValue = newAttrs.getValue(i); if (StringUtils.startsWith(attrValue, DAM_PATH_PREFIX)) { if( rewriteLinks ){ String relativePath = "." + attrValue; log.info( "rewriting {} to {}", attrValue, relativePath ); newAttrs.setValue(i, relativePath); } } } } return newAttrs; } /** * {@inheritDoc} */ public Transformer createTransformer() { return new AssetPathRewriterTransformer(); } public final class AssetPathRewriterTransformer extends AbstractTransformer { private SlingHttpServletRequest slingRequest; @Override public void init(ProcessingContext context, ProcessingComponentConfiguration config) throws IOException { super.init(context, config); this.slingRequest = context.getRequest(); } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { getContentHandler().startElement(namespaceURI, localName, qName, rebuildAttributes(this.slingRequest, localName, atts)); } } }
UTF-8
Java
4,754
java
AssetsPathRewriterTransformerFactory.java
Java
[]
null
[]
package com.adobe.aem.mobile.commons.core.impl.rewriter; import com.adobe.acs.commons.rewriter.AbstractTransformer; import com.adobe.acs.commons.util.ParameterUtil; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.*; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.commons.osgi.PropertiesUtil; import org.apache.sling.rewriter.ProcessingComponentConfiguration; import org.apache.sling.rewriter.ProcessingContext; import org.apache.sling.rewriter.Transformer; import org.apache.sling.rewriter.TransformerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import java.io.IOException; import java.util.Map; /** * TODO: Convert to use AbstractSlingResourceUpdateHandler. But this would require a dependency on the unobfuscated jar. */ @Component( label = "AEM Mobile Commons - Assets Path Rewriter Factory", description = "Rewriter pipeline component which rewrites paths of assets to be relative", metatype = true) @Properties({ @Property( label = "Rewriter Pipeline Type", description = "Type identifier to be referenced in rewriter pipeline configuration.", name = "pipeline.type", value = "aem-mobile-commons-asset-path", propertyPrivate = true) }) @Service @SuppressWarnings("unused") public class AssetsPathRewriterTransformerFactory implements TransformerFactory { @Property(value = {"source:src", "video:poster"} ) private static final String PROPERTY_ASSETS_MAPPING = "mapping.assets"; private static final Logger log = LoggerFactory.getLogger(AssetsPathRewriterTransformerFactory.class); private static final String[] DEFAULT_ATTRIBUTES = new String[]{"source:src", "video:poster"}; private static final String DAM_PATH_PREFIX = "/content/dam"; private Map<String, String[]> attributes; @Activate protected void activate(final Map<String, Object> config) { final String[] attrProp = PropertiesUtil.toStringArray(config.get(PROPERTY_ASSETS_MAPPING), DEFAULT_ATTRIBUTES); this.attributes = ParameterUtil.toMap( attrProp, ":", "," ); } protected Attributes rebuildAttributes(final SlingHttpServletRequest slingRequest, final String elementName, final Attributes attrs) { boolean rewriteLinks = false; if( slingRequest != null ){ Object object = slingRequest.getAttribute( "publishPathRewritingOptions" ); log.info( "publishPathRewritingOptions {}", object ); if( object != null ){ rewriteLinks = true; } } if (slingRequest == null || !attributes.containsKey(elementName) ) { // element is not defined as a candidate to rewrite return attrs; } final String[] modifiableAttributes = attributes.get(elementName); // clone the attributes final AttributesImpl newAttrs = new AttributesImpl(attrs); final int len = newAttrs.getLength(); for (int i = 0; i < len; i++) { final String attrName = newAttrs.getLocalName(i); if (ArrayUtils.contains(modifiableAttributes, attrName)) { final String attrValue = newAttrs.getValue(i); if (StringUtils.startsWith(attrValue, DAM_PATH_PREFIX)) { if( rewriteLinks ){ String relativePath = "." + attrValue; log.info( "rewriting {} to {}", attrValue, relativePath ); newAttrs.setValue(i, relativePath); } } } } return newAttrs; } /** * {@inheritDoc} */ public Transformer createTransformer() { return new AssetPathRewriterTransformer(); } public final class AssetPathRewriterTransformer extends AbstractTransformer { private SlingHttpServletRequest slingRequest; @Override public void init(ProcessingContext context, ProcessingComponentConfiguration config) throws IOException { super.init(context, config); this.slingRequest = context.getRequest(); } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { getContentHandler().startElement(namespaceURI, localName, qName, rebuildAttributes(this.slingRequest, localName, atts)); } } }
4,754
0.661969
0.661338
127
36.433071
32.278706
120
false
false
0
0
0
0
0
0
0.637795
false
false
0
4adbc774b1058d8a470c4ffd18a1a3371641c0a9
2,319,282,375,193
50779b1289aa5b534cc858e3ef422f928df6f33a
/app/src/main/java/com/jagr/android/popularmovies/data/model/Review.java
33969882defd24e4ffe9103703fe5e40b4bd2861
[]
no_license
AntonioGonzalezR/PopularMoviesApp
https://github.com/AntonioGonzalezR/PopularMoviesApp
8081c523662f2318c869a6c309c8cb9ecbd0fb52
9ddb2709779db44ccede395ea0a7820d31095efc
refs/heads/master
2020-06-02T21:22:45.353000
2015-09-19T23:47:04
2015-09-19T23:47:04
41,969,218
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jagr.android.popularmovies.data.model; import android.os.Parcel; import android.os.Parcelable; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; /** * Created by Antonio on 15-09-09. * Object representation of the Json format returned by the movies API */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class Review implements Parcelable { @JsonProperty("id") private String reviewId; @JsonProperty("author") private String reviewAuthor = null; @JsonProperty("content") private String reviewContent = null; @JsonProperty("url") private String reviewUrl = null; public Review() { } public Review(String reviewId, String reviewAuthor, String reviewContent, String reviewUrl) { this.reviewId = reviewId; this.reviewAuthor = reviewAuthor; this.reviewContent = reviewContent; this.reviewUrl = reviewUrl; } public String getReviewId() { return reviewId; } public String getReviewAuthor() { return reviewAuthor; } public String getReviewContent() { return reviewContent; } public String getReviewUrl() { return reviewUrl; } /** Static field used to regenerate object, individually or as arrays */ public static final Parcelable.Creator<Review> CREATOR = new Parcelable.Creator<Review>() { public Review createFromParcel(Parcel pc) { return new Review(pc); } public Review[] newArray(int size) { return new Review[size]; } }; /**Ctor from Parcel, reads back fields IN THE ORDER they were written */ public Review(Parcel pc){ reviewId = pc.readString(); reviewAuthor = pc.readString(); reviewContent = pc.readString(); reviewUrl = pc.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(reviewId); dest.writeString(reviewAuthor); dest.writeString(reviewContent); dest.writeString(reviewUrl); } @Override public String toString() { return "Review: [ id: " + reviewId + ", " + "author: " + reviewAuthor + ", " + "content: " + reviewContent + ", " + "url: " + reviewUrl + "]"; } }
UTF-8
Java
2,592
java
Review.java
Java
[ { "context": ".jackson.annotate.JsonProperty;\n\n/**\n * Created by Antonio on 15-09-09.\n * Object representation of the Json", "end": 298, "score": 0.9982559084892273, "start": 291, "tag": "NAME", "value": "Antonio" } ]
null
[]
package com.jagr.android.popularmovies.data.model; import android.os.Parcel; import android.os.Parcelable; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; /** * Created by Antonio on 15-09-09. * Object representation of the Json format returned by the movies API */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class Review implements Parcelable { @JsonProperty("id") private String reviewId; @JsonProperty("author") private String reviewAuthor = null; @JsonProperty("content") private String reviewContent = null; @JsonProperty("url") private String reviewUrl = null; public Review() { } public Review(String reviewId, String reviewAuthor, String reviewContent, String reviewUrl) { this.reviewId = reviewId; this.reviewAuthor = reviewAuthor; this.reviewContent = reviewContent; this.reviewUrl = reviewUrl; } public String getReviewId() { return reviewId; } public String getReviewAuthor() { return reviewAuthor; } public String getReviewContent() { return reviewContent; } public String getReviewUrl() { return reviewUrl; } /** Static field used to regenerate object, individually or as arrays */ public static final Parcelable.Creator<Review> CREATOR = new Parcelable.Creator<Review>() { public Review createFromParcel(Parcel pc) { return new Review(pc); } public Review[] newArray(int size) { return new Review[size]; } }; /**Ctor from Parcel, reads back fields IN THE ORDER they were written */ public Review(Parcel pc){ reviewId = pc.readString(); reviewAuthor = pc.readString(); reviewContent = pc.readString(); reviewUrl = pc.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(reviewId); dest.writeString(reviewAuthor); dest.writeString(reviewContent); dest.writeString(reviewUrl); } @Override public String toString() { return "Review: [ id: " + reviewId + ", " + "author: " + reviewAuthor + ", " + "content: " + reviewContent + ", " + "url: " + reviewUrl + "]"; } }
2,592
0.638117
0.635417
93
26.870968
22.800785
97
false
false
0
0
0
0
0
0
0.430108
false
false
0
a40ae57fcd6baa45af07bd1e24a92b233f9bb6e5
2,319,282,376,807
bfb55fc92a47a94310c6a9a41bf8e43cd8767441
/app/src/main/java/com/androidapp/androidproject/FindPlace.java
57e0a97e571de7a300a6a94bd82f87efd67bcefa
[]
no_license
rooohit/preplanner
https://github.com/rooohit/preplanner
eceb9a055d73efec489bd08d0c175c18c3aa8283
2493f485611ad38b6133b4897220461e4798be75
refs/heads/master
2020-12-04T11:34:15.269000
2020-01-04T11:56:34
2020-01-04T11:56:34
231,748,064
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.androidapp.androidproject; import androidx.appcompat.app.AppCompatActivity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; public class FindPlace extends AppCompatActivity implements AdapterView.OnItemSelectedListener { String[] places={"Select Places","Hot Places","Cold Places","Deserts","Indian Safari","Devotional Places","Ancient Places"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_find_place); Spinner spinner=findViewById(R.id.spinner); spinner.setOnItemSelectedListener(this); ArrayAdapter aa= new ArrayAdapter(this,android.R.layout.simple_spinner_item,places); aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(aa); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { switch (i){ case 0:{ break; } case 1:{ String link="https://www.indianholiday.com/blog/warm-weather-destinations-india/"; try{ Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 2:{ String link="https://www.treebo.com/blog/places-to-visit-in-india-in-june/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 3:{ String link="https://www.indianholiday.com/blog/warm-weather-destinations-india/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 4:{ String link="https://www.tourmyindia.com/blog/india-top-places-for-wildlife-safari-holidays/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 5:{ String link="https://www.tourmyindia.com/blog/top-25-religious-tourism-places-in-india/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 6:{ String link="https://www.holidify.com/collections/historical-places-in-india"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } } Toast.makeText(getApplicationContext(),places[i],Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }
UTF-8
Java
6,129
java
FindPlace.java
Java
[]
null
[]
package com.androidapp.androidproject; import androidx.appcompat.app.AppCompatActivity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; public class FindPlace extends AppCompatActivity implements AdapterView.OnItemSelectedListener { String[] places={"Select Places","Hot Places","Cold Places","Deserts","Indian Safari","Devotional Places","Ancient Places"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_find_place); Spinner spinner=findViewById(R.id.spinner); spinner.setOnItemSelectedListener(this); ArrayAdapter aa= new ArrayAdapter(this,android.R.layout.simple_spinner_item,places); aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(aa); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { switch (i){ case 0:{ break; } case 1:{ String link="https://www.indianholiday.com/blog/warm-weather-destinations-india/"; try{ Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 2:{ String link="https://www.treebo.com/blog/places-to-visit-in-india-in-june/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 3:{ String link="https://www.indianholiday.com/blog/warm-weather-destinations-india/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 4:{ String link="https://www.tourmyindia.com/blog/india-top-places-for-wildlife-safari-holidays/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 5:{ String link="https://www.tourmyindia.com/blog/top-25-religious-tourism-places-in-india/"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } case 6:{ String link="https://www.holidify.com/collections/historical-places-in-india"; try { Intent in = new Intent(Intent.ACTION_MAIN); in.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main")); in.addCategory("android.intent.category.LAUNCHER"); in.setData(Uri.parse(link)); startActivity(in); } catch (ActivityNotFoundException e){ //app is not installed Intent in= new Intent(Intent.ACTION_VIEW,Uri.parse(link)); startActivity(in); } break; } } Toast.makeText(getApplicationContext(),places[i],Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }
6,129
0.548866
0.547398
139
43.093525
31.001715
128
false
false
0
0
0
0
0
0
0.683453
false
false
0
d91b570c3198103e25efe6c321c53be2c88f1ec8
24,541,443,176,017
ff8382c10d95036e4c31b9a866d88499ecd56c9d
/src/test/java/com/dsg/cucumber/step_definitions/athlete/Regression_ATHLETE_005_my_account_page_and_name_in_header.java
2ada7a18481028d5487ab292b35e77652cfb0bf7
[]
no_license
nashua1985/testrepo
https://github.com/nashua1985/testrepo
c27284ac60d4412355938a84d026c75fc4c46b86
5996bc62f20e5d86946ca45adc2d1eb56434585c
refs/heads/master
2023-08-29T21:35:31.999000
2021-11-09T14:40:39
2021-11-09T14:40:39
421,069,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dsg.cucumber.step_definitions.athlete; import com.dsg.cucumber.framework.CommonElementMethods; import io.cucumber.java.en.When; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.testng.Assert; import java.util.List; public class Regression_ATHLETE_005_my_account_page_and_name_in_header { private static final Logger logger = Logger.getLogger(Regression_ATHLETE_005_my_account_page_and_name_in_header.class); private static final Integer timeout = 10; CommonElementMethods commonMethods = new CommonElementMethods(); @When("we should land on Sign In page by validating headers") public void we_should_land_on_sign_in_page_by_validating_headers(List<String> headerList) throws Exception { for(int i = 0; i < headerList.size();i++){ boolean isTextVisible = commonMethods.isElementVisible(By.xpath("//h1[contains(text(), \"" + headerList.get(i) + "\")]"), timeout); if (!isTextVisible) { Assert.fail(headerList + " is not VISIBLE"); } } } }
UTF-8
Java
1,070
java
Regression_ATHLETE_005_my_account_page_and_name_in_header.java
Java
[]
null
[]
package com.dsg.cucumber.step_definitions.athlete; import com.dsg.cucumber.framework.CommonElementMethods; import io.cucumber.java.en.When; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.testng.Assert; import java.util.List; public class Regression_ATHLETE_005_my_account_page_and_name_in_header { private static final Logger logger = Logger.getLogger(Regression_ATHLETE_005_my_account_page_and_name_in_header.class); private static final Integer timeout = 10; CommonElementMethods commonMethods = new CommonElementMethods(); @When("we should land on Sign In page by validating headers") public void we_should_land_on_sign_in_page_by_validating_headers(List<String> headerList) throws Exception { for(int i = 0; i < headerList.size();i++){ boolean isTextVisible = commonMethods.isElementVisible(By.xpath("//h1[contains(text(), \"" + headerList.get(i) + "\")]"), timeout); if (!isTextVisible) { Assert.fail(headerList + " is not VISIBLE"); } } } }
1,070
0.702804
0.692523
26
40.192307
38.855766
143
false
false
0
0
0
0
0
0
0.615385
false
false
0
a6c057f9f5c79d41ea56f2d55c6a67cbe9e51401
24,945,170,074,343
7d18bce36c7b0d990985a979ecd1f6f4469a0132
/src/main/java/com/insigma/mvc/controller/login/LoginController.java
310a1123187f4989cfa3ee174da27bb635a5d253
[]
no_license
wengweng85/myapi
https://github.com/wengweng85/myapi
f76fbecdac9f3a5db2d9bc4101faeb2f5b4f7fe9
59d7661b7167d7a7df2462e95828cc6b1ea10844
refs/heads/master
2021-01-21T22:19:15.849000
2017-09-13T07:00:32
2017-09-13T07:00:32
102,149,343
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.insigma.mvc.controller.login; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.insigma.dto.AjaxReturnMsg; import com.insigma.mvc.MvcHelper; import com.insigma.mvc.model.SPermission; import com.insigma.mvc.model.SRole; import com.insigma.mvc.model.SUser; import com.insigma.mvc.service.login.LoginService; /** * 登录controller * @author Administrator * */ @RestController public class LoginController extends MvcHelper { Log log=LogFactory.getLog(LoginController.class); @Autowired private LoginService loginservice; /** * getUserAndGroupInfo * @param request * @param username * @return * @throws Exception */ @RequestMapping(value = "/getUserAndGroupInfo/{loginname}",method=RequestMethod.GET,produces="application/json;charset=UTF-8") public AjaxReturnMsg<SUser> getUserAndGroupInfo(HttpServletRequest request,@PathVariable String loginname) throws Exception { //转换成json对象并调用远程接口 return loginservice.getUserAndGroupInfo(loginname); } /** * findPermissionStr * @param request * @param username * @return * @throws Exception */ @RequestMapping(value = "/findPermissionStr/{username}",method=RequestMethod.GET,produces="application/json;charset=UTF-8") public AjaxReturnMsg<List<SPermission>> findPermissionStr(HttpServletRequest request,@PathVariable String username) throws Exception { return loginservice.findPermissionStr(username); } /** * * @param request * @param username * @return * @throws Exception */ @RequestMapping(value = "/findRolesStr/{username}",method=RequestMethod.GET,produces="application/json;charset=UTF-8") public AjaxReturnMsg<List<SRole>> findRolesStr(HttpServletRequest request,@PathVariable String username) throws Exception { return loginservice.findRolesStr(username); } }
GB18030
Java
2,252
java
LoginController.java
Java
[ { "context": "gin.LoginService;\n\n\n/**\n * 登录controller\n * @author Administrator\n *\n */\n@RestController\npublic class LoginControll", "end": 795, "score": 0.9587672352790833, "start": 782, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.insigma.mvc.controller.login; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.insigma.dto.AjaxReturnMsg; import com.insigma.mvc.MvcHelper; import com.insigma.mvc.model.SPermission; import com.insigma.mvc.model.SRole; import com.insigma.mvc.model.SUser; import com.insigma.mvc.service.login.LoginService; /** * 登录controller * @author Administrator * */ @RestController public class LoginController extends MvcHelper { Log log=LogFactory.getLog(LoginController.class); @Autowired private LoginService loginservice; /** * getUserAndGroupInfo * @param request * @param username * @return * @throws Exception */ @RequestMapping(value = "/getUserAndGroupInfo/{loginname}",method=RequestMethod.GET,produces="application/json;charset=UTF-8") public AjaxReturnMsg<SUser> getUserAndGroupInfo(HttpServletRequest request,@PathVariable String loginname) throws Exception { //转换成json对象并调用远程接口 return loginservice.getUserAndGroupInfo(loginname); } /** * findPermissionStr * @param request * @param username * @return * @throws Exception */ @RequestMapping(value = "/findPermissionStr/{username}",method=RequestMethod.GET,produces="application/json;charset=UTF-8") public AjaxReturnMsg<List<SPermission>> findPermissionStr(HttpServletRequest request,@PathVariable String username) throws Exception { return loginservice.findPermissionStr(username); } /** * * @param request * @param username * @return * @throws Exception */ @RequestMapping(value = "/findRolesStr/{username}",method=RequestMethod.GET,produces="application/json;charset=UTF-8") public AjaxReturnMsg<List<SRole>> findRolesStr(HttpServletRequest request,@PathVariable String username) throws Exception { return loginservice.findRolesStr(username); } }
2,252
0.786421
0.785072
74
29.054054
34.494766
135
false
false
0
0
0
0
0
0
1.081081
false
false
0
508856dc151ff4f20e12d21d16cc2d24f3fbce08
16,174,846,857,041
6b102ab7fec59a757af76d17ea81e998525424e6
/CMUPayMobileShopFront/src/main/java/com/huateng/core/common/SgwThreadPoolUtil.java
740271cd22519c952372934488965f91f2a5773a
[]
no_license
justfordream/my-2
https://github.com/justfordream/my-2
a52516b87de9321916c0f111328fe1ced17e3549
e7b2d1003afbd5df8351342692e94a11b7ec15c5
refs/heads/master
2016-08-10T13:48:44.772000
2015-06-01T15:40:45
2015-06-01T15:40:45
36,330,084
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/*package com.huateng.core.common; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import com.huateng.tmall.bean.TMallRequestMessage; //import com.huateng.haobai.ppcore.model.BillProvinceSwitch; //import com.huateng.haobai.ppcore.service.db.IBusiDBService; *//** * * @author JGQ * 2013-05-08 *//* public class SgwThreadPoolUtil { private static Logger logger = Logger.getLogger("FILE"); //private IBusiDBService busiDbService; private static Map<String, ThreadPoolExecutor> excutorMap = new ConcurrentHashMap<String, ThreadPoolExecutor>(); private static ThreadPoolExecutor executor = null; *//** * 各省线程池初始化方法 *//* public void init() { //取各省参数 // List<BillProvinceSwitch> list = busiDbService.selectBillProvinceSwitch(); // for (int i = 0; i < list.size(); i++) { // BillProvinceSwitch provinceSwitch = list.get(i); // ThreadPoolExecutor executor = new ThreadPoolExecutor(provinceSwitch.getMinSize(), // provinceSwitch.getMaxSize(), // 500, // TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<Runnable>(provinceSwitch.getQueueSize()), // new ThreadPoolExecutor.AbortPolicy()); // excutorMap.put(provinceSwitch.getTeleCode(), executor); // logger.info("省线程池初始化teleCode="+provinceSwitch.getTeleCode()+",min="+provinceSwitch.getMinSize() // + ",max="+provinceSwitch.getMaxSize()+",queueSize="+provinceSwitch.getQueueSize()); // } executor = new ThreadPoolExecutor(80,1000,500,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(1000),new ThreadPoolExecutor.AbortPolicy()); } *//** * 各省线程池参数更新方法 *//* public void updateProvinceSwitch() { //取各省参数 // List<BillProvinceSwitch> list = busiDbService.selectBillProvinceSwitch(); // for (int i = 0; i < list.size(); i++) { // BillProvinceSwitch provinceSwitch = list.get(i); // ThreadPoolExecutor executor = excutorMap.get(provinceSwitch.getTeleCode()); // if (executor == null) { //省线程池不存在,创建新的 // logger.info("省线程池更新重建!teleCode="+provinceSwitch.getTeleCode()+",min="+provinceSwitch.getMinSize() // + ",max="+provinceSwitch.getMaxSize()+",queueSize="+provinceSwitch.getQueueSize()); // executor = new ThreadPoolExecutor(provinceSwitch.getMinSize(), // provinceSwitch.getMaxSize(), // 500, // TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<Runnable>(provinceSwitch.getQueueSize()), // new ThreadPoolExecutor.AbortPolicy()); // excutorMap.put(provinceSwitch.getTeleCode(), executor); // }else {// 更新省线程池 // executor.setCorePoolSize(provinceSwitch.getMinSize()); // executor.setMaximumPoolSize(provinceSwitch.getMaxSize()); // logger.info("省线程池更新!teleCode="+provinceSwitch.getTeleCode()+",min="+provinceSwitch.getMinSize() // + ",max="+provinceSwitch.getMaxSize()+",queueSize="+provinceSwitch.getQueueSize()); // } // } } *//** * 任务加入省线程池 * @author JGQ * @param teleCode 省代码 * @param runnable 请求集团SGW充值任务 * @param reqlog 订单参数信息 *//* public static String putReqestQueue(String teleCode, Runnable runnable, String reqlog){ // ThreadPoolExecutor executor = excutorMap.get(teleCode); // if (executor == null) { // logger.error("没有找到省线程队列!teleCode = "+teleCode + reqlog); // return "未找到省线程队列!"; // } // try { // executor.execute(runnable); // logger.debug("teleCode="+teleCode +"加入省线程池成功!活动线程数--->" // + executor.getActiveCount() + "|| 队列实际数---->" // + executor.getQueue().size() + "|| 最小线程数---->" // + executor.getCorePoolSize() +"||最大线程数---->" // + executor.getMaximumPoolSize()+ "||最大线程峰值---->" // + executor.getLargestPoolSize()+"||"+reqlog); // logger.info("teleCode="+teleCode +"加入省线程池成功!活动线程数--->" // + executor.getActiveCount() + "|| 队列实际数---->" // + executor.getQueue().size() + "||最大线程峰值---->" // + executor.getLargestPoolSize()+"||"+reqlog); // } catch (RejectedExecutionException e) { // logger.error("teleCode="+teleCode +"省资源忙!活动线程数--->" // + executor.getActiveCount() + "|| 队列实际数---->" // + executor.getQueue().size() + "|| 最小线程数---->" // + executor.getCorePoolSize() +"||最大线程数---->" // + executor.getMaximumPoolSize()+ "||最大线程峰值---->" // + executor.getLargestPoolSize()+"||"+reqlog); // return "省资源忙!"; // } // return null; return null; } public static String getRequestQueue(TMallRequestMessage tmallMsg){ executor = new ThreadPoolExecutor(80,1000,500,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(1000),new ThreadPoolExecutor.AbortPolicy()); executor.execute(tmallMsg); System.out.println("省线程池成功!活动线程数--->" + executor.getActiveCount() + "|| 队列实际数---->" + executor.getQueue().size() + "|| 最小线程数---->" + executor.getCorePoolSize() +"||最大线程数---->" + executor.getMaximumPoolSize()+ "||最大线程峰值---->" + executor.getLargestPoolSize()+"||"); return null; } // public IBusiDBService getBusiDbService() { // return busiDbService; // } // // public void setBusiDbService(IBusiDBService busiDbService) { // this.busiDbService = busiDbService; // } // public static void main(String[] args){ } }*/
UTF-8
Java
5,829
java
SgwThreadPoolUtil.java
Java
[ { "context": "re.service.db.IBusiDBService;\n*//**\n * \n * @author JGQ\n * 2013-05-08\n *//*\npublic class SgwThreadPoolUti", "end": 551, "score": 0.9995682835578918, "start": 548, "tag": "USERNAME", "value": "JGQ" }, { "context": "\n//\t\t\t}\n//\t\t}\n\t}\n\t\n\t*//**\n\t * 任务加入省线...
null
[]
/*package com.huateng.core.common; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import com.huateng.tmall.bean.TMallRequestMessage; //import com.huateng.haobai.ppcore.model.BillProvinceSwitch; //import com.huateng.haobai.ppcore.service.db.IBusiDBService; *//** * * @author JGQ * 2013-05-08 *//* public class SgwThreadPoolUtil { private static Logger logger = Logger.getLogger("FILE"); //private IBusiDBService busiDbService; private static Map<String, ThreadPoolExecutor> excutorMap = new ConcurrentHashMap<String, ThreadPoolExecutor>(); private static ThreadPoolExecutor executor = null; *//** * 各省线程池初始化方法 *//* public void init() { //取各省参数 // List<BillProvinceSwitch> list = busiDbService.selectBillProvinceSwitch(); // for (int i = 0; i < list.size(); i++) { // BillProvinceSwitch provinceSwitch = list.get(i); // ThreadPoolExecutor executor = new ThreadPoolExecutor(provinceSwitch.getMinSize(), // provinceSwitch.getMaxSize(), // 500, // TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<Runnable>(provinceSwitch.getQueueSize()), // new ThreadPoolExecutor.AbortPolicy()); // excutorMap.put(provinceSwitch.getTeleCode(), executor); // logger.info("省线程池初始化teleCode="+provinceSwitch.getTeleCode()+",min="+provinceSwitch.getMinSize() // + ",max="+provinceSwitch.getMaxSize()+",queueSize="+provinceSwitch.getQueueSize()); // } executor = new ThreadPoolExecutor(80,1000,500,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(1000),new ThreadPoolExecutor.AbortPolicy()); } *//** * 各省线程池参数更新方法 *//* public void updateProvinceSwitch() { //取各省参数 // List<BillProvinceSwitch> list = busiDbService.selectBillProvinceSwitch(); // for (int i = 0; i < list.size(); i++) { // BillProvinceSwitch provinceSwitch = list.get(i); // ThreadPoolExecutor executor = excutorMap.get(provinceSwitch.getTeleCode()); // if (executor == null) { //省线程池不存在,创建新的 // logger.info("省线程池更新重建!teleCode="+provinceSwitch.getTeleCode()+",min="+provinceSwitch.getMinSize() // + ",max="+provinceSwitch.getMaxSize()+",queueSize="+provinceSwitch.getQueueSize()); // executor = new ThreadPoolExecutor(provinceSwitch.getMinSize(), // provinceSwitch.getMaxSize(), // 500, // TimeUnit.MILLISECONDS, // new ArrayBlockingQueue<Runnable>(provinceSwitch.getQueueSize()), // new ThreadPoolExecutor.AbortPolicy()); // excutorMap.put(provinceSwitch.getTeleCode(), executor); // }else {// 更新省线程池 // executor.setCorePoolSize(provinceSwitch.getMinSize()); // executor.setMaximumPoolSize(provinceSwitch.getMaxSize()); // logger.info("省线程池更新!teleCode="+provinceSwitch.getTeleCode()+",min="+provinceSwitch.getMinSize() // + ",max="+provinceSwitch.getMaxSize()+",queueSize="+provinceSwitch.getQueueSize()); // } // } } *//** * 任务加入省线程池 * @author JGQ * @param teleCode 省代码 * @param runnable 请求集团SGW充值任务 * @param reqlog 订单参数信息 *//* public static String putReqestQueue(String teleCode, Runnable runnable, String reqlog){ // ThreadPoolExecutor executor = excutorMap.get(teleCode); // if (executor == null) { // logger.error("没有找到省线程队列!teleCode = "+teleCode + reqlog); // return "未找到省线程队列!"; // } // try { // executor.execute(runnable); // logger.debug("teleCode="+teleCode +"加入省线程池成功!活动线程数--->" // + executor.getActiveCount() + "|| 队列实际数---->" // + executor.getQueue().size() + "|| 最小线程数---->" // + executor.getCorePoolSize() +"||最大线程数---->" // + executor.getMaximumPoolSize()+ "||最大线程峰值---->" // + executor.getLargestPoolSize()+"||"+reqlog); // logger.info("teleCode="+teleCode +"加入省线程池成功!活动线程数--->" // + executor.getActiveCount() + "|| 队列实际数---->" // + executor.getQueue().size() + "||最大线程峰值---->" // + executor.getLargestPoolSize()+"||"+reqlog); // } catch (RejectedExecutionException e) { // logger.error("teleCode="+teleCode +"省资源忙!活动线程数--->" // + executor.getActiveCount() + "|| 队列实际数---->" // + executor.getQueue().size() + "|| 最小线程数---->" // + executor.getCorePoolSize() +"||最大线程数---->" // + executor.getMaximumPoolSize()+ "||最大线程峰值---->" // + executor.getLargestPoolSize()+"||"+reqlog); // return "省资源忙!"; // } // return null; return null; } public static String getRequestQueue(TMallRequestMessage tmallMsg){ executor = new ThreadPoolExecutor(80,1000,500,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(1000),new ThreadPoolExecutor.AbortPolicy()); executor.execute(tmallMsg); System.out.println("省线程池成功!活动线程数--->" + executor.getActiveCount() + "|| 队列实际数---->" + executor.getQueue().size() + "|| 最小线程数---->" + executor.getCorePoolSize() +"||最大线程数---->" + executor.getMaximumPoolSize()+ "||最大线程峰值---->" + executor.getLargestPoolSize()+"||"); return null; } // public IBusiDBService getBusiDbService() { // return busiDbService; // } // // public void setBusiDbService(IBusiDBService busiDbService) { // this.busiDbService = busiDbService; // } // public static void main(String[] args){ } }*/
5,829
0.680293
0.67223
150
34.560001
30.754616
147
false
false
0
0
0
0
0
0
3.033333
false
false
0
d9793d09186dce8b9b9c80ce6834e47fbf860975
18,837,726,630,793
c5eea5149d62a0cef76130c8d70984ce6a6fd872
/Algo/Common/Palindrome/Palindrome.java
9a09f08aaa8a4d9a8e1bd13dabd556519c778047
[]
no_license
nir099/KnowledgeBase
https://github.com/nir099/KnowledgeBase
c12f5c2114d87ffe6b3a2cff648513910d0c69ab
7fd56f175ed5d35f17fbaa48b4a7f63dd3d540a8
refs/heads/main
2023-02-16T23:43:58.563000
2021-01-07T08:34:33
2021-01-07T08:34:33
324,538,039
16
6
null
false
2021-01-05T18:36:55
2020-12-26T11:12:26
2021-01-05T17:18:36
2021-01-05T18:36:54
13,658
9
2
0
Python
false
false
class Palindrome{ public static void main(String args[]){ String word = "abcba"; if (isPalindrome(word)) { System.out.println("Palindrom"); } else { System.out.println("Not Palindrom"); } } public static boolean isPalindrome(String word) { int wordLength = word.length(); char[] letters = word.toCharArray(); for (int i = 0; i < wordLength/2; i++) { if (letters[i] != letters[wordLength-1-i]) { return false; } } return true; } }
UTF-8
Java
604
java
Palindrome.java
Java
[]
null
[]
class Palindrome{ public static void main(String args[]){ String word = "abcba"; if (isPalindrome(word)) { System.out.println("Palindrom"); } else { System.out.println("Not Palindrom"); } } public static boolean isPalindrome(String word) { int wordLength = word.length(); char[] letters = word.toCharArray(); for (int i = 0; i < wordLength/2; i++) { if (letters[i] != letters[wordLength-1-i]) { return false; } } return true; } }
604
0.490066
0.485099
24
24.125
18.536703
56
false
false
0
0
0
0
0
0
0.375
false
false
0
ddb4614b302b37cdb5571e6c3663b95195d3d360
3,186,865,761,568
fac08447a665cc0cec83b58716c002ffa930f49c
/app/src/main/java/com/example/a13703/my_app/util/BmobUtil.java
f51df187f22797f3e7043ffb3e398a6af3ca197a
[]
no_license
SYOICQ/SMusic
https://github.com/SYOICQ/SMusic
a4571c4099a6d56fabbfaace2bb07fa2ea07bb7f
8c2ccbf737bd9445a0bbe72c05fcffb461db14bd
refs/heads/master
2023-03-20T22:24:01.216000
2019-07-21T14:14:23
2019-07-21T14:14:23
197,938,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.a13703.my_app.util; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.support.design.widget.Snackbar; import android.util.Log; import android.widget.Toast; import com.example.a13703.my_app.Inter_kou.OnQueryUserListener; import com.example.a13703.my_app.Inter_kou.OnSucessLoginListener; import com.example.a13703.my_app.Inter_kou.OnaddGe_danListener; import com.example.a13703.my_app.Inter_kou.OnquerListener; import com.example.a13703.my_app.Inter_kou.OnqueryGe_dan_Listener; import com.example.a13703.my_app.Inter_kou.OnqueryGe_dan_list_Listener; import com.example.a13703.my_app.Inter_kou.OnqueryUserGenDanListener; import com.example.a13703.my_app.Inter_kou.query_Online_Song_ByObjectIdListener; import com.example.a13703.my_app.LoginActivity; import com.example.a13703.my_app.MainActivity; import com.example.a13703.my_app.MyApplication; import com.example.a13703.my_app.bean.Ge_dan; import com.example.a13703.my_app.bean.Ge_dan_Online_Song; import com.example.a13703.my_app.bean.Local_music; import com.example.a13703.my_app.bean.Online_Song; import com.example.a13703.my_app.bean.Person; import com.example.a13703.my_app.bean.User_Ge_dan; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobSMS; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; import cn.bmob.v3.listener.LogInListener; import cn.bmob.v3.listener.QueryListener; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener; import cn.bmob.v3.listener.UploadFileListener; /** * Created by 13703 on 2019/7/15. */ public class BmobUtil { public static final String songRootPath = Environment.getExternalStorageDirectory().toString() + "/SMusicPlayer/pic/"; //弹出信息 public static void showToast(String message){ Toast.makeText(MyApplication.getContext(),message,Toast.LENGTH_SHORT).show(); } /** * 账号密码登陆 */ public static void loginByUsername(String username,String password,final OnSucessLoginListener listener){ Person userlogin = new Person(); userlogin.setUsername(username); userlogin.setPassword(password); userlogin.login(new SaveListener<Person>() { @Override public void done(Person bmobUser, BmobException e) { if (e == null) { listener.onSucessLogin(bmobUser,e); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("账号或密码错误"); Log.e("error",e.getMessage().toString()); } } }); } /** * 邮箱登陆 */ public static void loginByEmail(String email,String password,final OnSucessLoginListener listener){ Person.loginByAccount(email,password, new LogInListener<Person>() { @Override public void done(Person user, BmobException e) { if (user != null) { listener.onSucessLogin(user,e); }else{ if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("邮箱或密码错误!"); } } }); } /** * 发送验证邮件 */ public static void emailVerify(final String email) { Person.requestEmailVerify(email, new UpdateListener() { @Override public void done(BmobException e) { if (e == null) { showToast("请求验证邮件成功,请到" + email + "邮箱中进行激活账户。"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("请求失败!"); } } }); } /** * 邮箱重置密码 */ public static void resetPasswordByEmail(final String email) { Person.resetPasswordByEmail(email, new UpdateListener() { @Override public void done(BmobException e) { if (e == null) { showToast("重置密码请求成功,请到 "+ email + "邮箱进行密码重置操作"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("请求失败!"); } } }); } /** * 用户注册(手机号) */ public static void signUp(String phone_number, String password,String security_code,Bitmap head_photo) { //不能修改邮箱,邮箱必须为正确格式,否侧注册失败 //由于bmob功能受限 头像功能无法实现 Person user = new Person(); user.setRegion(""); user.setSex(""); user.setBirth(""); user.setHobby(""); user.setPersonal_signature(""); user.setUsername(phone_number); user.setPassword(password); user.setMobilePhoneNumber(phone_number); user.setNickname(phone_number); user.setMobilePhoneNumberVerified(true); user.signOrLogin(security_code, new SaveListener<Person>() { @Override public void done(Person person, BmobException e) { if (e == null) { showToast("注册成功!"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else if(e.getErrorCode()==202) showToast("注册失败,用户名已存在,请重试!"); else{ showToast("注册失败!" ); } Log.e("注册失败", "原因: ", e); } } }); } /** * 发送手机验证码 */ public static void requestBmobSMs(String phone){ BmobSMS.requestSMSCode(phone,"S乐官方客服", new QueryListener<Integer>() { @Override public void done(Integer smsId, BmobException e) { if (e == null) { showToast("发送验证码成功!"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("发送验证码失败!"); } } }); } /** * 手机重置密码 */ public static void resetPasswordByPhone(String code,String newPassword) { Person.resetPasswordBySMSCode(code, newPassword, new UpdateListener() { @Override public void done(BmobException e) { if (e == null) { showToast("重置成功"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("重置失败"); } } }); } /** * 检验邮箱合法性 */ public static Boolean checkEmail(String email) { if (email.matches("^[a-z0-9A-Z]+[- |a-z0-9A-Z._]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$")) { return true; } else { return false; } } /** * 获取当前时间 */ public static String getNowTime(){ SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间 sdf.applyPattern("yyyy-MM-dd");// a为am/pm的标记 Date date = new Date();// 获取当前时间 return sdf.format(date); } /** * 判断乐龄 */ public static String judgeMusicAge(Person person){ long daysBetween = 0; String[] t = person.getCreatedAt().trim().split(" "); String dateStr1 = t[0]; String dateStr2 = getNowTime(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date date2 = format.parse(dateStr2); Date date1 = format.parse(dateStr1); daysBetween=(date2.getTime()-date1.getTime()+1000000)/(60*60*24*1000); } catch (ParseException e) { e.printStackTrace(); } return Long.toString(daysBetween) +" 天"; } /** * 判断星座 */ public static String judgeConstellation(Person person){ String t = person.getBirth(); String month1 = t.substring(5,7); String day1 = t.substring(8); int month = Integer.parseInt(month1); int day = Integer.parseInt(day1); String[] starArr = {"魔羯座","水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座" }; int[] DayArr = {22, 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22}; // 两个星座分割日 int index = month; // 所查询日期在分割日之前,索引-1,否则不变 if (day < DayArr[month - 1]) { index = index - 1; } // 返回索引指向的星座string return starArr[index]; } /** * 根据用户名查询 */ public static void queryUserByUserName(String username,final OnQueryUserListener listener){ BmobQuery<Person> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("username", username); categoryBmobQuery.findObjects(new FindListener<Person>() { @Override public void done(List<Person> object, BmobException e) { if (e == null) { listener.OnQueryUserSucess(object,e); } else { listener.OnQueryUserFailed(); Log.e("BMOB", e.toString()); } } }); } /** * 更新昵称 */ public static void updateNickName(String objectId, String nickname) { final Person p2 = new Person(); p2.setNickname(nickname); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("昵称更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } /** * 查询用户信息 */ public static void queryInformation(String objectId,final OnquerListener listener){ BmobQuery<Person> bmobQuery = new BmobQuery<>(); bmobQuery.getObject(objectId, new QueryListener<Person>() { @Override public void done(Person object,BmobException e) { if(e==null){ listener.OnqueryListenerSucess(object,e); }else{ } } }); } public static void updateSex(String objectId, String sex) { final Person p2 = new Person(); p2.setSex(sex); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("性别更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateRegion(String objectId, String city) { final Person p2 = new Person(); p2.setRegion(city); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("地区更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateBirth(String objectId, String birth) { final Person p2 = new Person(); p2.setBirth(birth); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("生日更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateSignature(String objectId, String newsignature) { final Person p2 = new Person(); p2.setPersonal_signature(newsignature); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("个性签名更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateHobby(String objectId, String newhobby) { final Person p2 = new Person(); p2.setHobby(newhobby); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("兴趣更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateEmail(String objectId, String newemail) { final Person p2 = new Person(); p2.setEmail(newemail); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("邮箱更新成功,请及时验证!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void query_Ge_dan_ById(Integer id,final OnqueryGe_dan_list_Listener listener){ BmobQuery<Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("Id", id); categoryBmobQuery.findObjects(new FindListener<Ge_dan>() { @Override public void done(List<Ge_dan> object, BmobException e) { if (e == null) { listener.Onsucess(object,e); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); } public static void query_Ge_dan_ByObjectId(String objecId, final OnqueryGe_dan_Listener listener){ BmobQuery<Ge_dan> bmobQuery = new BmobQuery<>(); bmobQuery.getObject(objecId, new QueryListener<Ge_dan>() { @Override public void done(Ge_dan ge_dan, BmobException e) { if(e==null){ listener.Onsucess(ge_dan,e); }else{ showToast("在查询歌单的时候出现错误"); } } }); } public static void add_Ge_dan(final String username, String name, final OnaddGe_danListener listener){ Ge_dan p2 = new Ge_dan(); p2.setName(name); p2.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ query_Ge_dan_ByObjectId(objectId, new OnqueryGe_dan_Listener() { @Override public void Onsucess(Ge_dan ge_dan, BmobException e) { Integer ge_dan_id = ge_dan.getId(); Add_User_Ge_dan(username,ge_dan_id,listener); } }); }else{ showToast("创建数据失败!"); } } }); } public static void Add_User_Ge_dan(String username,int id,final OnaddGe_danListener listener){ User_Ge_dan p2 = new User_Ge_dan(); p2.setUsername(username); p2.setGe_dan_Id(id); p2.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ showToast("添加歌单成功"); listener.Onsucess(); }else{ showToast("创建歌单失败!"); } } }); } public static void queryUser_Ge_dan(String username, final OnqueryUserGenDanListener listener){ BmobQuery<User_Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("username", username); categoryBmobQuery.findObjects(new FindListener<User_Ge_dan>() { @Override public void done(List<User_Ge_dan> object, BmobException e) { if (e == null) { listener.onSucess(object,e); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); } //往歌单里添加歌曲 public static void add_Online_Song(Online_Song song, final Integer ge_dan_id) { song.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ query_Online_Song_ByObjectId(objectId, new query_Online_Song_ByObjectIdListener() { @Override public void onSucess(Online_Song song, BmobException e) { Integer id = song.getsId(); Add_Ge_dan_Online_Song(ge_dan_id,id); } }); }else{ showToast("添加失败:" + e.getMessage()); } } }); } public static void query_Online_Song_ByObjectId(String objectId, final query_Online_Song_ByObjectIdListener listener){ BmobQuery<Online_Song> bmobQuery = new BmobQuery<>(); bmobQuery.getObject(objectId, new QueryListener<Online_Song>() { @Override public void done(Online_Song song, BmobException e) { if(e==null){ listener.onSucess(song,e); }else{ showToast("在查询的时候出现错误"); } } }); } public static void Add_Ge_dan_Online_Song(Integer ge_dan_id,Integer song_id){ Ge_dan_Online_Song p2 = new Ge_dan_Online_Song(); p2.setGe_dan_Id(ge_dan_id); p2.setSongId(song_id); p2.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ showToast("添加成功"); }else{ showToast("创建失败!"); } } }); } public static void del_Ge_dan(final Integer id, final OnaddGe_danListener listener) { BmobQuery<Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("Id", id); categoryBmobQuery.findObjects(new FindListener<Ge_dan>() { @Override public void done(List<Ge_dan> object, BmobException e) { if (e == null) { String num = object.get(0).getObjectId(); Ge_dan p2 = new Ge_dan(); p2.setObjectId(num); p2.delete(new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ BmobQuery<User_Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("Ge_dan_Id", id); categoryBmobQuery.findObjects(new FindListener<User_Ge_dan>() { @Override public void done(List<User_Ge_dan> object, BmobException e) { if (e == null) { final String num1 = object.get(0).getObjectId(); User_Ge_dan p2 = new User_Ge_dan(); p2.setObjectId(num1); p2.delete(new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("删除成功"); listener.Onsucess(); }else{ showToast("删除失败!"); } } }); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); }else{ showToast("删除失败!"); } } }); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); } public static Local_music copy(Online_Song music) { Local_music song = new Local_music(); song.setCreatedAt(music.getCreatedAt()); song.setsId(music.getsId()); song.setSongId(music.getSongId()); song.setSinger(music.getSinger()); song.setSong(music.getSong()); song.setImageId(music.getImageId()); song.setAlbumId(music.getAlbumId()); song.setPath(music.getPath()); song.setUrl(music.getUrl()); song.setDuration(music.getDuration()); song.setSize(music.getSize()); song.setSongmid(music.getSongmid()); song.setToken(music.getToken()); song.setLrc_url(music.getLrc_url()); song.setMv_url(music.getMv_url()); song.setBitm(""); return song; } }
UTF-8
Java
23,983
java
BmobUtil.java
Java
[ { "context": "istener.UploadFileListener;\r\n\r\n/**\r\n * Created by 13703 on 2019/7/15.\r\n */\r\n\r\npublic class BmobUtil {\r\n ", "end": 1951, "score": 0.9824963808059692, "start": 1946, "tag": "USERNAME", "value": "13703" }, { "context": "in = new Person();\r\n userlogi...
null
[]
package com.example.a13703.my_app.util; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.support.design.widget.Snackbar; import android.util.Log; import android.widget.Toast; import com.example.a13703.my_app.Inter_kou.OnQueryUserListener; import com.example.a13703.my_app.Inter_kou.OnSucessLoginListener; import com.example.a13703.my_app.Inter_kou.OnaddGe_danListener; import com.example.a13703.my_app.Inter_kou.OnquerListener; import com.example.a13703.my_app.Inter_kou.OnqueryGe_dan_Listener; import com.example.a13703.my_app.Inter_kou.OnqueryGe_dan_list_Listener; import com.example.a13703.my_app.Inter_kou.OnqueryUserGenDanListener; import com.example.a13703.my_app.Inter_kou.query_Online_Song_ByObjectIdListener; import com.example.a13703.my_app.LoginActivity; import com.example.a13703.my_app.MainActivity; import com.example.a13703.my_app.MyApplication; import com.example.a13703.my_app.bean.Ge_dan; import com.example.a13703.my_app.bean.Ge_dan_Online_Song; import com.example.a13703.my_app.bean.Local_music; import com.example.a13703.my_app.bean.Online_Song; import com.example.a13703.my_app.bean.Person; import com.example.a13703.my_app.bean.User_Ge_dan; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobSMS; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; import cn.bmob.v3.listener.LogInListener; import cn.bmob.v3.listener.QueryListener; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener; import cn.bmob.v3.listener.UploadFileListener; /** * Created by 13703 on 2019/7/15. */ public class BmobUtil { public static final String songRootPath = Environment.getExternalStorageDirectory().toString() + "/SMusicPlayer/pic/"; //弹出信息 public static void showToast(String message){ Toast.makeText(MyApplication.getContext(),message,Toast.LENGTH_SHORT).show(); } /** * 账号密码登陆 */ public static void loginByUsername(String username,String password,final OnSucessLoginListener listener){ Person userlogin = new Person(); userlogin.setUsername(username); userlogin.setPassword(<PASSWORD>); userlogin.login(new SaveListener<Person>() { @Override public void done(Person bmobUser, BmobException e) { if (e == null) { listener.onSucessLogin(bmobUser,e); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("账号或密码错误"); Log.e("error",e.getMessage().toString()); } } }); } /** * 邮箱登陆 */ public static void loginByEmail(String email,String password,final OnSucessLoginListener listener){ Person.loginByAccount(email,password, new LogInListener<Person>() { @Override public void done(Person user, BmobException e) { if (user != null) { listener.onSucessLogin(user,e); }else{ if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("邮箱或密码错误!"); } } }); } /** * 发送验证邮件 */ public static void emailVerify(final String email) { Person.requestEmailVerify(email, new UpdateListener() { @Override public void done(BmobException e) { if (e == null) { showToast("请求验证邮件成功,请到" + email + "邮箱中进行激活账户。"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("请求失败!"); } } }); } /** * 邮箱重置密码 */ public static void resetPasswordByEmail(final String email) { Person.resetPasswordByEmail(email, new UpdateListener() { @Override public void done(BmobException e) { if (e == null) { showToast("重置密码请求成功,请到 "+ email + "邮箱进行密码重置操作"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("请求失败!"); } } }); } /** * 用户注册(手机号) */ public static void signUp(String phone_number, String password,String security_code,Bitmap head_photo) { //不能修改邮箱,邮箱必须为正确格式,否侧注册失败 //由于bmob功能受限 头像功能无法实现 Person user = new Person(); user.setRegion(""); user.setSex(""); user.setBirth(""); user.setHobby(""); user.setPersonal_signature(""); user.setUsername(phone_number); user.setPassword(<PASSWORD>); user.setMobilePhoneNumber(phone_number); user.setNickname(phone_number); user.setMobilePhoneNumberVerified(true); user.signOrLogin(security_code, new SaveListener<Person>() { @Override public void done(Person person, BmobException e) { if (e == null) { showToast("注册成功!"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else if(e.getErrorCode()==202) showToast("注册失败,用户名已存在,请重试!"); else{ showToast("注册失败!" ); } Log.e("注册失败", "原因: ", e); } } }); } /** * 发送手机验证码 */ public static void requestBmobSMs(String phone){ BmobSMS.requestSMSCode(phone,"S乐官方客服", new QueryListener<Integer>() { @Override public void done(Integer smsId, BmobException e) { if (e == null) { showToast("发送验证码成功!"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("发送验证码失败!"); } } }); } /** * 手机重置密码 */ public static void resetPasswordByPhone(String code,String newPassword) { Person.resetPasswordBySMSCode(code, newPassword, new UpdateListener() { @Override public void done(BmobException e) { if (e == null) { showToast("重置成功"); } else { if (e.getErrorCode() == 9016) showToast("网络连接超时!"); else showToast("重置失败"); } } }); } /** * 检验邮箱合法性 */ public static Boolean checkEmail(String email) { if (email.matches("^[a-z0-9A-Z]+[- |a-z0-9A-Z._]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$")) { return true; } else { return false; } } /** * 获取当前时间 */ public static String getNowTime(){ SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间 sdf.applyPattern("yyyy-MM-dd");// a为am/pm的标记 Date date = new Date();// 获取当前时间 return sdf.format(date); } /** * 判断乐龄 */ public static String judgeMusicAge(Person person){ long daysBetween = 0; String[] t = person.getCreatedAt().trim().split(" "); String dateStr1 = t[0]; String dateStr2 = getNowTime(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date date2 = format.parse(dateStr2); Date date1 = format.parse(dateStr1); daysBetween=(date2.getTime()-date1.getTime()+1000000)/(60*60*24*1000); } catch (ParseException e) { e.printStackTrace(); } return Long.toString(daysBetween) +" 天"; } /** * 判断星座 */ public static String judgeConstellation(Person person){ String t = person.getBirth(); String month1 = t.substring(5,7); String day1 = t.substring(8); int month = Integer.parseInt(month1); int day = Integer.parseInt(day1); String[] starArr = {"魔羯座","水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座" }; int[] DayArr = {22, 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22}; // 两个星座分割日 int index = month; // 所查询日期在分割日之前,索引-1,否则不变 if (day < DayArr[month - 1]) { index = index - 1; } // 返回索引指向的星座string return starArr[index]; } /** * 根据用户名查询 */ public static void queryUserByUserName(String username,final OnQueryUserListener listener){ BmobQuery<Person> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("username", username); categoryBmobQuery.findObjects(new FindListener<Person>() { @Override public void done(List<Person> object, BmobException e) { if (e == null) { listener.OnQueryUserSucess(object,e); } else { listener.OnQueryUserFailed(); Log.e("BMOB", e.toString()); } } }); } /** * 更新昵称 */ public static void updateNickName(String objectId, String nickname) { final Person p2 = new Person(); p2.setNickname(nickname); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("昵称更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } /** * 查询用户信息 */ public static void queryInformation(String objectId,final OnquerListener listener){ BmobQuery<Person> bmobQuery = new BmobQuery<>(); bmobQuery.getObject(objectId, new QueryListener<Person>() { @Override public void done(Person object,BmobException e) { if(e==null){ listener.OnqueryListenerSucess(object,e); }else{ } } }); } public static void updateSex(String objectId, String sex) { final Person p2 = new Person(); p2.setSex(sex); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("性别更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateRegion(String objectId, String city) { final Person p2 = new Person(); p2.setRegion(city); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("地区更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateBirth(String objectId, String birth) { final Person p2 = new Person(); p2.setBirth(birth); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("生日更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateSignature(String objectId, String newsignature) { final Person p2 = new Person(); p2.setPersonal_signature(newsignature); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("个性签名更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateHobby(String objectId, String newhobby) { final Person p2 = new Person(); p2.setHobby(newhobby); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("兴趣更新成功!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void updateEmail(String objectId, String newemail) { final Person p2 = new Person(); p2.setEmail(newemail); p2.update(objectId, new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("邮箱更新成功,请及时验证!"); }else{ showToast("更新失败:" + e.getMessage()); } } }); } public static void query_Ge_dan_ById(Integer id,final OnqueryGe_dan_list_Listener listener){ BmobQuery<Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("Id", id); categoryBmobQuery.findObjects(new FindListener<Ge_dan>() { @Override public void done(List<Ge_dan> object, BmobException e) { if (e == null) { listener.Onsucess(object,e); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); } public static void query_Ge_dan_ByObjectId(String objecId, final OnqueryGe_dan_Listener listener){ BmobQuery<Ge_dan> bmobQuery = new BmobQuery<>(); bmobQuery.getObject(objecId, new QueryListener<Ge_dan>() { @Override public void done(Ge_dan ge_dan, BmobException e) { if(e==null){ listener.Onsucess(ge_dan,e); }else{ showToast("在查询歌单的时候出现错误"); } } }); } public static void add_Ge_dan(final String username, String name, final OnaddGe_danListener listener){ Ge_dan p2 = new Ge_dan(); p2.setName(name); p2.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ query_Ge_dan_ByObjectId(objectId, new OnqueryGe_dan_Listener() { @Override public void Onsucess(Ge_dan ge_dan, BmobException e) { Integer ge_dan_id = ge_dan.getId(); Add_User_Ge_dan(username,ge_dan_id,listener); } }); }else{ showToast("创建数据失败!"); } } }); } public static void Add_User_Ge_dan(String username,int id,final OnaddGe_danListener listener){ User_Ge_dan p2 = new User_Ge_dan(); p2.setUsername(username); p2.setGe_dan_Id(id); p2.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ showToast("添加歌单成功"); listener.Onsucess(); }else{ showToast("创建歌单失败!"); } } }); } public static void queryUser_Ge_dan(String username, final OnqueryUserGenDanListener listener){ BmobQuery<User_Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("username", username); categoryBmobQuery.findObjects(new FindListener<User_Ge_dan>() { @Override public void done(List<User_Ge_dan> object, BmobException e) { if (e == null) { listener.onSucess(object,e); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); } //往歌单里添加歌曲 public static void add_Online_Song(Online_Song song, final Integer ge_dan_id) { song.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ query_Online_Song_ByObjectId(objectId, new query_Online_Song_ByObjectIdListener() { @Override public void onSucess(Online_Song song, BmobException e) { Integer id = song.getsId(); Add_Ge_dan_Online_Song(ge_dan_id,id); } }); }else{ showToast("添加失败:" + e.getMessage()); } } }); } public static void query_Online_Song_ByObjectId(String objectId, final query_Online_Song_ByObjectIdListener listener){ BmobQuery<Online_Song> bmobQuery = new BmobQuery<>(); bmobQuery.getObject(objectId, new QueryListener<Online_Song>() { @Override public void done(Online_Song song, BmobException e) { if(e==null){ listener.onSucess(song,e); }else{ showToast("在查询的时候出现错误"); } } }); } public static void Add_Ge_dan_Online_Song(Integer ge_dan_id,Integer song_id){ Ge_dan_Online_Song p2 = new Ge_dan_Online_Song(); p2.setGe_dan_Id(ge_dan_id); p2.setSongId(song_id); p2.save(new SaveListener<String>() { @Override public void done(String objectId,BmobException e) { if(e==null){ showToast("添加成功"); }else{ showToast("创建失败!"); } } }); } public static void del_Ge_dan(final Integer id, final OnaddGe_danListener listener) { BmobQuery<Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("Id", id); categoryBmobQuery.findObjects(new FindListener<Ge_dan>() { @Override public void done(List<Ge_dan> object, BmobException e) { if (e == null) { String num = object.get(0).getObjectId(); Ge_dan p2 = new Ge_dan(); p2.setObjectId(num); p2.delete(new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ BmobQuery<User_Ge_dan> categoryBmobQuery = new BmobQuery<>(); categoryBmobQuery.addWhereEqualTo("Ge_dan_Id", id); categoryBmobQuery.findObjects(new FindListener<User_Ge_dan>() { @Override public void done(List<User_Ge_dan> object, BmobException e) { if (e == null) { final String num1 = object.get(0).getObjectId(); User_Ge_dan p2 = new User_Ge_dan(); p2.setObjectId(num1); p2.delete(new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ showToast("删除成功"); listener.Onsucess(); }else{ showToast("删除失败!"); } } }); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); }else{ showToast("删除失败!"); } } }); } else { Log.e("BMOB", e.toString()); showToast("获取不到歌单!"); } } }); } public static Local_music copy(Online_Song music) { Local_music song = new Local_music(); song.setCreatedAt(music.getCreatedAt()); song.setsId(music.getsId()); song.setSongId(music.getSongId()); song.setSinger(music.getSinger()); song.setSong(music.getSong()); song.setImageId(music.getImageId()); song.setAlbumId(music.getAlbumId()); song.setPath(music.getPath()); song.setUrl(music.getUrl()); song.setDuration(music.getDuration()); song.setSize(music.getSize()); song.setSongmid(music.getSongmid()); song.setToken(music.getToken()); song.setLrc_url(music.getLrc_url()); song.setMv_url(music.getMv_url()); song.setBitm(""); return song; } }
23,987
0.478387
0.467175
612
35.308823
23.955999
122
false
false
0
0
0
0
0
0
0.594771
false
false
0
ee0ba96eb414ba8bac9710a1ff4fad4805c10a27
25,254,407,771,193
6e90f29cd0e08b38a2c0182e4fb89b3f8ea2bb1e
/app/src/main/java/ace/cse/finalyrproject/spotter/CurrenLocationMap.java
338982084c8b6826072999dc7d02b37e6e50b34d
[]
no_license
sathish-cse/PacketFriend
https://github.com/sathish-cse/PacketFriend
e676aa5c543aaf9c078a1a365961700f3ce20223
76ccaf792d3473add3ccd3c253f98a4f70a815e5
refs/heads/master
2021-01-22T02:58:47.901000
2017-02-06T13:09:45
2017-02-06T13:09:45
81,088,189
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ace.cse.finalyrproject.spotter; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.List; import java.util.Locale; public class CurrenLocationMap extends AppCompatActivity implements OnMapReadyCallback { private Geocoder geocoder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_curren_location_map); initMap(); } private void initMap() { MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { Bundle bundle = getIntent().getExtras(); LatLng latLng = new LatLng(Double.parseDouble(bundle.getString("Latitude")), Double.parseDouble(bundle.getString("Longitude"))); map.animateCamera(CameraUpdateFactory.newLatLng(latLng)); try { geocoder = new Geocoder(CurrenLocationMap.this, Locale.ENGLISH); List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(bundle.getString("Latitude")), Double.parseDouble(bundle.getString("Longitude")), 1); if (addresses != null) { Address returnedAddress = addresses.get(0); StringBuilder strReturnedAddress = new StringBuilder("\n"); for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); } //Toast.makeText(getApplicationContext(),strReturnedAddress.toString(),Toast.LENGTH_LONG).show(); map.addMarker(new MarkerOptions().position(latLng).title(strReturnedAddress.toString())); map.setMapType(GoogleMap.MAP_TYPE_TERRAIN); map.moveCamera(CameraUpdateFactory.newLatLng(latLng)); map.animateCamera(CameraUpdateFactory.zoomTo(13)); } } catch (Exception e) { Toast.makeText(getApplicationContext(),"can't get Address!",Toast.LENGTH_LONG).show(); } } }
UTF-8
Java
2,749
java
CurrenLocationMap.java
Java
[]
null
[]
package ace.cse.finalyrproject.spotter; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.List; import java.util.Locale; public class CurrenLocationMap extends AppCompatActivity implements OnMapReadyCallback { private Geocoder geocoder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_curren_location_map); initMap(); } private void initMap() { MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { Bundle bundle = getIntent().getExtras(); LatLng latLng = new LatLng(Double.parseDouble(bundle.getString("Latitude")), Double.parseDouble(bundle.getString("Longitude"))); map.animateCamera(CameraUpdateFactory.newLatLng(latLng)); try { geocoder = new Geocoder(CurrenLocationMap.this, Locale.ENGLISH); List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(bundle.getString("Latitude")), Double.parseDouble(bundle.getString("Longitude")), 1); if (addresses != null) { Address returnedAddress = addresses.get(0); StringBuilder strReturnedAddress = new StringBuilder("\n"); for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); } //Toast.makeText(getApplicationContext(),strReturnedAddress.toString(),Toast.LENGTH_LONG).show(); map.addMarker(new MarkerOptions().position(latLng).title(strReturnedAddress.toString())); map.setMapType(GoogleMap.MAP_TYPE_TERRAIN); map.moveCamera(CameraUpdateFactory.newLatLng(latLng)); map.animateCamera(CameraUpdateFactory.zoomTo(13)); } } catch (Exception e) { Toast.makeText(getApplicationContext(),"can't get Address!",Toast.LENGTH_LONG).show(); } } }
2,749
0.696617
0.694434
70
38.285713
36.205029
167
false
false
0
0
0
0
0
0
0.671429
false
false
0
a02422cd694e501b9ea9e4acd390b7b33fc08ecc
1,846,835,946,841
250eee6da9b66de50459b162d8a37f94b166504c
/app/src/main/java/com/example/mathieu/pacman/GhostSmart.java
aceefc321ccd91e84f70ac72a4470df85117e0d8
[]
no_license
Mathieu33260/pacmanAndroid
https://github.com/Mathieu33260/pacmanAndroid
7a19ba9767287a7c47d712886c6f67c15f3cdd0f
6fd55ebe570ede456e8fc133d732e1b6cf4696a6
refs/heads/master
2021-03-28T23:14:27.654000
2018-02-01T07:51:04
2018-02-01T07:51:04
117,231,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mathieu.pacman; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Created by Mathieu on 22/01/2018. */ public class GhostSmart extends Ghost{ private List<int[]> intersections; GhostSmart(String previousDirection, String nextDirection, String[][] matrice) { super(previousDirection,nextDirection); intersections = intersections(matrice); tempBlock = ""; } @Override String[][] nextDirection(String[][] matrice, int posXpacman, int posYpacman) { List<int[]> list = intersectionsOrdo(posXpacman,posYpacman); if(posXpacman - list.get(0)[0] >= 0) //bas { if(posYpacman - list.get(0)[1] >= 0) //droite { if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le bas { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { } } } else { //plus de chemin vers la droite if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { } } } } else { //gauche if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le bas { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { } } } else { //plus de chemin vers la gauche if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { } } } } } else { //haut if(list.get(0)[1] - list.get(0)[1] > 0) //droite { if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le haut { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { } } } else { //plus de chemin vers la droite if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { } } } } else { //gauche if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le haut { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { } } } else { //plus de chemin vers la gauche if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { } } } } } return matrice; } public List<int[]> intersections(String[][] matrice) { List<int[]> list = new ArrayList<>(); int cpt; for(int i=1; i<matrice.length-1; i++) { for(int j=1; j<matrice[i].length-1; j++) { cpt = 0; if(!Objects.equals(matrice[i][j], WALL_BLOCK)) { if(!Objects.equals(matrice[i - 1][j], WALL_BLOCK)) { cpt++; } if(!Objects.equals(matrice[i + 1][j], WALL_BLOCK)) { cpt++; } if(!Objects.equals(matrice[i][j - 1], WALL_BLOCK)) { cpt++; } if(!Objects.equals(matrice[i][j + 1], WALL_BLOCK)) { cpt++; } } if(cpt >= 3) { int tab[] = {i,j}; list.add(tab); } } } return list; } public List<int[]> intersectionsOrdo(int posXpacman, int posYpacman) { List<int[]> list = new ArrayList<>(); Map<int[],Double> map = new HashMap<>(); for(int[] coord:intersections) { double dist = Math.sqrt(((coord[1] - coord[0]) * (coord[1] - coord[0])) + ((posYpacman - posXpacman) * (posYpacman - posXpacman))); map.put(coord,dist); } Map<int[],Double> map2 = sortMapByValues(map); for(Map.Entry<int[],Double> entry: map2.entrySet()) { System.out.println(entry.getKey()[0] + " " + entry.getKey()[1] + " " + entry.getValue()); list.add(entry.getKey()); } return list; } private Map<int[], Double> sortMapByValues(Map<int[],Double> aMap) { Set<Entry<int[],Double>> mapEntries = aMap.entrySet(); // used linked list to sort, because insertion of elements in linked list is faster than an array list. List<Entry<int[],Double>> aList = new LinkedList<Entry<int[],Double>>(mapEntries); // sorting the List Collections.sort(aList, new Comparator<Entry<int[],Double>>() { @Override public int compare(Entry<int[],Double> ele1, Entry<int[],Double> ele2) { return ele1.getValue().compareTo(ele2.getValue()); } }); // Storing the list into Linked HashMap to preserve the order of insertion. Map<int[],Double> aMap2 = new LinkedHashMap<int[],Double>(); for(Entry<int[],Double> entry: aList) { aMap2.put(entry.getKey(), entry.getValue()); } return aMap2; } @Override int getPosX() { return posX; } @Override void setPosX(int posX) { this.posX = posX; } @Override int getPosY() { return posY; } @Override void setPosY(int posY) { this.posY = posY; } @Override String getPreviousDirection() { return previousDirection; } @Override void setTempBlock(String[][] matrice, String direction) { if (tempBlock.equals("")) { matrice[posX][posY] = MIAM_BLOCK; } else { matrice[posX][posY] = tempBlock; } if (direction.equals("top")) { if (matrice[posX - 1][posY].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } else if (direction.equals("bottom")) { if (matrice[posX + 1][posY].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } else if (direction.equals("left")) { if (matrice[posX][posY - 1].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } else if (direction.equals("right")) { if (matrice[posX][posY + 1].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } } @Override void setPreviousDirection(String previousDirection) { this.previousDirection = previousDirection; } @Override String getNextDirection() { return nextDirection; } @Override void setNextDirection(String nextDirection) { this.nextDirection = nextDirection; } public List<int[]> getIntersections() { return intersections; } public void setIntersections(List<int[]> intersections) { this.intersections = intersections; } }
UTF-8
Java
11,879
java
GhostSmart.java
Java
[ { "context": "ap.Entry;\nimport java.util.Set;\n\n/**\n * Created by Mathieu on 22/01/2018.\n */\n\npublic class GhostSmart exten", "end": 432, "score": 0.9653900861740112, "start": 425, "tag": "NAME", "value": "Mathieu" } ]
null
[]
package com.example.mathieu.pacman; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Created by Mathieu on 22/01/2018. */ public class GhostSmart extends Ghost{ private List<int[]> intersections; GhostSmart(String previousDirection, String nextDirection, String[][] matrice) { super(previousDirection,nextDirection); intersections = intersections(matrice); tempBlock = ""; } @Override String[][] nextDirection(String[][] matrice, int posXpacman, int posYpacman) { List<int[]> list = intersectionsOrdo(posXpacman,posYpacman); if(posXpacman - list.get(0)[0] >= 0) //bas { if(posYpacman - list.get(0)[1] >= 0) //droite { if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le bas { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { } } } else { //plus de chemin vers la droite if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { } } } } else { //gauche if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le bas { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { } } } else { //plus de chemin vers la gauche if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { if(!matrice[posX + 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "bottom"); matrice[posX + 1][posY] = GHOST_3; posX++; } else { } } } } } else { //haut if(list.get(0)[1] - list.get(0)[1] > 0) //droite { if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le haut { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { } } } else { //plus de chemin vers la droite if(!matrice[posX][posY + 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "right"); matrice[posX][posY + 1] = GHOST_3; posY++; } else { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { } } } } else { //gauche if(Math.abs(posXpacman - list.get(0)[0]) > Math.abs(posYpacman - list.get(0)[1])) //plus de chemin vers le haut { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { } } } else { //plus de chemin vers la gauche if(!matrice[posX][posY - 1].equals(WALL_BLOCK)) { setTempBlock(matrice, "left"); matrice[posX][posY - 1] = GHOST_3; posY--; } else { if(!matrice[posX - 1][posY].equals(WALL_BLOCK)) { setTempBlock(matrice, "top"); matrice[posX - 1][posY] = GHOST_3; posX--; } else { } } } } } return matrice; } public List<int[]> intersections(String[][] matrice) { List<int[]> list = new ArrayList<>(); int cpt; for(int i=1; i<matrice.length-1; i++) { for(int j=1; j<matrice[i].length-1; j++) { cpt = 0; if(!Objects.equals(matrice[i][j], WALL_BLOCK)) { if(!Objects.equals(matrice[i - 1][j], WALL_BLOCK)) { cpt++; } if(!Objects.equals(matrice[i + 1][j], WALL_BLOCK)) { cpt++; } if(!Objects.equals(matrice[i][j - 1], WALL_BLOCK)) { cpt++; } if(!Objects.equals(matrice[i][j + 1], WALL_BLOCK)) { cpt++; } } if(cpt >= 3) { int tab[] = {i,j}; list.add(tab); } } } return list; } public List<int[]> intersectionsOrdo(int posXpacman, int posYpacman) { List<int[]> list = new ArrayList<>(); Map<int[],Double> map = new HashMap<>(); for(int[] coord:intersections) { double dist = Math.sqrt(((coord[1] - coord[0]) * (coord[1] - coord[0])) + ((posYpacman - posXpacman) * (posYpacman - posXpacman))); map.put(coord,dist); } Map<int[],Double> map2 = sortMapByValues(map); for(Map.Entry<int[],Double> entry: map2.entrySet()) { System.out.println(entry.getKey()[0] + " " + entry.getKey()[1] + " " + entry.getValue()); list.add(entry.getKey()); } return list; } private Map<int[], Double> sortMapByValues(Map<int[],Double> aMap) { Set<Entry<int[],Double>> mapEntries = aMap.entrySet(); // used linked list to sort, because insertion of elements in linked list is faster than an array list. List<Entry<int[],Double>> aList = new LinkedList<Entry<int[],Double>>(mapEntries); // sorting the List Collections.sort(aList, new Comparator<Entry<int[],Double>>() { @Override public int compare(Entry<int[],Double> ele1, Entry<int[],Double> ele2) { return ele1.getValue().compareTo(ele2.getValue()); } }); // Storing the list into Linked HashMap to preserve the order of insertion. Map<int[],Double> aMap2 = new LinkedHashMap<int[],Double>(); for(Entry<int[],Double> entry: aList) { aMap2.put(entry.getKey(), entry.getValue()); } return aMap2; } @Override int getPosX() { return posX; } @Override void setPosX(int posX) { this.posX = posX; } @Override int getPosY() { return posY; } @Override void setPosY(int posY) { this.posY = posY; } @Override String getPreviousDirection() { return previousDirection; } @Override void setTempBlock(String[][] matrice, String direction) { if (tempBlock.equals("")) { matrice[posX][posY] = MIAM_BLOCK; } else { matrice[posX][posY] = tempBlock; } if (direction.equals("top")) { if (matrice[posX - 1][posY].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } else if (direction.equals("bottom")) { if (matrice[posX + 1][posY].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } else if (direction.equals("left")) { if (matrice[posX][posY - 1].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } else if (direction.equals("right")) { if (matrice[posX][posY + 1].equals(WHITE_BLOCK)) { tempBlock = WHITE_BLOCK; } else { tempBlock = MIAM_BLOCK; } } } @Override void setPreviousDirection(String previousDirection) { this.previousDirection = previousDirection; } @Override String getNextDirection() { return nextDirection; } @Override void setNextDirection(String nextDirection) { this.nextDirection = nextDirection; } public List<int[]> getIntersections() { return intersections; } public void setIntersections(List<int[]> intersections) { this.intersections = intersections; } }
11,879
0.413755
0.404327
353
32.651558
24.863375
127
false
false
0
0
0
0
0
0
0.473088
false
false
0
149aea60e62c0778694304f939f7c1398350fb04
20,014,547,603,821
70d67a9745603f20a720b8ff8cc105ff773230b0
/src/test/java/com/kodilla/ecommercee/group/repository/GroupRepositoryTest.java
772a623069258216a1aa8f505c2c39c948014261
[]
no_license
niokle/JDP-1903-01
https://github.com/niokle/JDP-1903-01
be3c3bf92fb90f31e2170cf36a9adc23f646f84c
df015aef899ab4d8a93e8c0d3a45472553539453
refs/heads/master
2020-06-15T18:22:58.762000
2019-04-20T19:37:33
2019-04-20T19:37:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kodilla.ecommercee.group.repository; import com.kodilla.ecommercee.group.domain.Group; import com.kodilla.ecommercee.group.repository.GroupRepository; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional @RunWith(SpringRunner.class) @SpringBootTest public class GroupRepositoryTest { @Autowired private GroupRepository groupRepository; @Test public void saveGroupRepository() { //given Group group = new Group("test", "test"); //when groupRepository.save(group); //then Assert.assertNotNull(group.getGroupId()); //cleanup groupRepository.delete(group); } @Test public void testFindAll() { //given Group group = new Group("test", "test"); Group group1 = new Group("test1", "test1"); Group group2 = new Group("test2", "test2"); groupRepository.save(group); groupRepository.save(group1); groupRepository.save(group2); //when List<Group> showGroups = groupRepository.findAll(); //then Assert.assertEquals(3, showGroups.size()); //cleanUp groupRepository.deleteAll(showGroups); } }
UTF-8
Java
1,516
java
GroupRepositoryTest.java
Java
[]
null
[]
package com.kodilla.ecommercee.group.repository; import com.kodilla.ecommercee.group.domain.Group; import com.kodilla.ecommercee.group.repository.GroupRepository; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional @RunWith(SpringRunner.class) @SpringBootTest public class GroupRepositoryTest { @Autowired private GroupRepository groupRepository; @Test public void saveGroupRepository() { //given Group group = new Group("test", "test"); //when groupRepository.save(group); //then Assert.assertNotNull(group.getGroupId()); //cleanup groupRepository.delete(group); } @Test public void testFindAll() { //given Group group = new Group("test", "test"); Group group1 = new Group("test1", "test1"); Group group2 = new Group("test2", "test2"); groupRepository.save(group); groupRepository.save(group1); groupRepository.save(group2); //when List<Group> showGroups = groupRepository.findAll(); //then Assert.assertEquals(3, showGroups.size()); //cleanUp groupRepository.deleteAll(showGroups); } }
1,516
0.687995
0.681398
57
25.614035
20.970953
64
false
false
0
0
0
0
0
0
0.526316
false
false
0
d74b3bd3d8ad610d96ff82fa01ccd253e3d46b43
4,320,737,133,995
6cc06958c6dff97a56e77544a489003d261c861e
/src/mobi/whichclub/android/data/Course.java
c3be11b5e39ed6ca63b498be3f1bd73488e9b8ae
[]
no_license
camrdale/whichclub
https://github.com/camrdale/whichclub
abf0ccbc517f19dd088952fdb201c79b2242d6b7
1e7a8c3c8aa8e8486e1ebb39140964098b9580a9
refs/heads/master
2021-01-02T22:19:04.693000
2011-09-15T20:52:50
2011-09-15T20:52:50
640,351
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package mobi.whichclub.android.data; import java.util.HashMap; import java.util.Map; import mobi.whichclub.android.provider.WhichClubProvider; import android.net.Uri; import android.provider.BaseColumns; /** * A single golf course. * @author camrdale */ public class Course implements BaseColumns { /** The name of the table. */ public static final String TABLE_NAME = "course"; /** The name of the course column (String). */ public static final String NAME = "name"; /** The name of the city column (String). */ public static final String CITY = "city"; /** The name of the state or province column (String). */ public static final String STATE_PROV = "state_prov"; /** The name of the country column (String). */ public static final String COUNTRY = "country"; /** The latitude of the course column (Double). */ public static final String LATITUDE = "latitude"; /** The longitude of the course column (Double). */ public static final String LONGITUDE = "longitude"; /** The par of the course column (Integer). */ public static final String PAR = "par"; /** The content:// style URL for this table. */ public static final Uri CONTENT_URI = Uri.parse( "content://" + WhichClubProvider.AUTHORITY + "/" + TABLE_NAME); /** The content type for multiple records from this table. */ public static final String CONTENT_MULTI_TYPE = "vnd.android.cursor.dir/vnd.whichclub." + TABLE_NAME; /** The content type for a single record from this table. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.whichclub." + TABLE_NAME; /** The default sort order for records returned from this table. */ public static final String DEFAULT_SORT_ORDER = NAME + " ASC"; /** A default column projection map to get all the columns. */ public static final Map<String, String> PROJECTION_MAP = new HashMap<String, String>(); static { PROJECTION_MAP.put(Course._ID, Course._ID); PROJECTION_MAP.put(Course.NAME, Course.NAME); PROJECTION_MAP.put(Course.PAR, Course.PAR); PROJECTION_MAP.put(Course.CITY, Course.CITY); PROJECTION_MAP.put(Course.STATE_PROV, Course.STATE_PROV); PROJECTION_MAP.put(Course.COUNTRY, Course.COUNTRY); PROJECTION_MAP.put(Course.LATITUDE, Course.LATITUDE); PROJECTION_MAP.put(Course.LONGITUDE, Course.LONGITUDE); } /** Protected default constructor for utility class. */ protected Course() { } }
UTF-8
Java
2,562
java
Course.java
Java
[ { "context": "eColumns;\n\n/**\n * A single golf course.\n * @author camrdale\n */\npublic class Course implements BaseColumns {\n", "end": 256, "score": 0.9994612336158752, "start": 248, "tag": "USERNAME", "value": "camrdale" } ]
null
[]
package mobi.whichclub.android.data; import java.util.HashMap; import java.util.Map; import mobi.whichclub.android.provider.WhichClubProvider; import android.net.Uri; import android.provider.BaseColumns; /** * A single golf course. * @author camrdale */ public class Course implements BaseColumns { /** The name of the table. */ public static final String TABLE_NAME = "course"; /** The name of the course column (String). */ public static final String NAME = "name"; /** The name of the city column (String). */ public static final String CITY = "city"; /** The name of the state or province column (String). */ public static final String STATE_PROV = "state_prov"; /** The name of the country column (String). */ public static final String COUNTRY = "country"; /** The latitude of the course column (Double). */ public static final String LATITUDE = "latitude"; /** The longitude of the course column (Double). */ public static final String LONGITUDE = "longitude"; /** The par of the course column (Integer). */ public static final String PAR = "par"; /** The content:// style URL for this table. */ public static final Uri CONTENT_URI = Uri.parse( "content://" + WhichClubProvider.AUTHORITY + "/" + TABLE_NAME); /** The content type for multiple records from this table. */ public static final String CONTENT_MULTI_TYPE = "vnd.android.cursor.dir/vnd.whichclub." + TABLE_NAME; /** The content type for a single record from this table. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.whichclub." + TABLE_NAME; /** The default sort order for records returned from this table. */ public static final String DEFAULT_SORT_ORDER = NAME + " ASC"; /** A default column projection map to get all the columns. */ public static final Map<String, String> PROJECTION_MAP = new HashMap<String, String>(); static { PROJECTION_MAP.put(Course._ID, Course._ID); PROJECTION_MAP.put(Course.NAME, Course.NAME); PROJECTION_MAP.put(Course.PAR, Course.PAR); PROJECTION_MAP.put(Course.CITY, Course.CITY); PROJECTION_MAP.put(Course.STATE_PROV, Course.STATE_PROV); PROJECTION_MAP.put(Course.COUNTRY, Course.COUNTRY); PROJECTION_MAP.put(Course.LATITUDE, Course.LATITUDE); PROJECTION_MAP.put(Course.LONGITUDE, Course.LONGITUDE); } /** Protected default constructor for utility class. */ protected Course() { } }
2,562
0.669009
0.669009
68
36.676472
24.612551
75
false
false
0
0
0
0
0
0
0.544118
false
false
0
cbf00f439287b54ccf80e5ec45249de40434b3d5
14,602,888,806,666
987584392274b970532e1aaa278c0598fb51a85f
/Discord_Challage/Aim_Lab_I.java
2a8fb08228b77453c55ed2de67226966b4514c26
[]
no_license
Kimitozuki/HackerRank
https://github.com/Kimitozuki/HackerRank
be08341bc73113d78d169511e8b691c1b9af9802
b8f17fa5aeaeaf124e4ecbd259a690cfbd09d22c
refs/heads/main
2023-02-27T16:16:23.172000
2021-01-29T12:16:31
2021-01-29T12:16:31
325,715,270
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Discord_Challage; import java.util.Scanner; public class Aim_Lab_I { public static void main(String[] args) { Scanner input = new Scanner(System.in); //https://www.hackerrank.com/contests/utp-discord-filkom-ub/challenges int match = input.nextInt(); int indexHuda = 0, indexForga = match; int hudaScore, forgaScore, huda = 0, forga = 0; int[] arrayAllScore = new int[match*2]; for(int loop = 0; loop < match*2; loop++){ arrayAllScore[loop] = input.nextInt(); } for(int loop = 0; loop < match; loop++){ hudaScore = arrayAllScore[indexHuda]; indexHuda++; forgaScore = arrayAllScore[indexForga]; indexForga++; if (hudaScore > forgaScore){ huda++; }else if (hudaScore < forgaScore){ forga++; }else if (hudaScore == forgaScore){ continue; } } System.out.printf("Huda : %d - %d : Forga",huda,forga); } }
UTF-8
Java
1,058
java
Aim_Lab_I.java
Java
[]
null
[]
package Discord_Challage; import java.util.Scanner; public class Aim_Lab_I { public static void main(String[] args) { Scanner input = new Scanner(System.in); //https://www.hackerrank.com/contests/utp-discord-filkom-ub/challenges int match = input.nextInt(); int indexHuda = 0, indexForga = match; int hudaScore, forgaScore, huda = 0, forga = 0; int[] arrayAllScore = new int[match*2]; for(int loop = 0; loop < match*2; loop++){ arrayAllScore[loop] = input.nextInt(); } for(int loop = 0; loop < match; loop++){ hudaScore = arrayAllScore[indexHuda]; indexHuda++; forgaScore = arrayAllScore[indexForga]; indexForga++; if (hudaScore > forgaScore){ huda++; }else if (hudaScore < forgaScore){ forga++; }else if (hudaScore == forgaScore){ continue; } } System.out.printf("Huda : %d - %d : Forga",huda,forga); } }
1,058
0.539698
0.533081
29
35.482758
18.267403
78
false
false
0
0
0
0
0
0
0.896552
false
false
0
a9d1010feaf3aa4f2e55e86a7fb680a87a704d61
15,307,263,447,064
d491aa7a03c1d31ef0c1f16d63964f8915bedfc9
/uikit/src/com/netease/nim/uikit/business/session/viewholder/MsgViewHolderPicture.java
d31b5a80ffac512f8d530cda9fb1d63bc8295bb1
[ "MIT" ]
permissive
liuxiong1115/cb_net_imlibrary
https://github.com/liuxiong1115/cb_net_imlibrary
ea96a0b3a93e7832b619ba8ddbc128977969dad0
1302566c8bd942045e22e9f37de35becdd5f8b1b
refs/heads/master
2021-06-18T10:46:59.679000
2021-01-18T09:29:09
2021-01-18T09:29:09
156,326,789
1
1
null
false
2021-01-18T09:29:10
2018-11-06T04:39:59
2021-01-18T09:14:57
2021-01-18T09:29:10
74,449
1
1
0
Java
false
false
package com.netease.nim.uikit.business.session.viewholder; import android.text.TextUtils; import android.util.Log; import com.netease.nim.uikit.R; import com.netease.nim.uikit.business.session.activity.WatchMessagePictureActivity; import com.netease.nim.uikit.common.CommonUtil; import com.netease.nim.uikit.common.ToastHelper; import com.netease.nim.uikit.common.ui.recyclerview.adapter.BaseMultiItemFetchLoadAdapter; import com.netease.nim.uikit.common.util.log.sdk.util.FileUtils; import com.netease.nimlib.sdk.msg.attachment.FileAttachment; import com.netease.nimlib.sdk.msg.attachment.ImageAttachment; import com.netease.nimlib.sdk.msg.model.IMMessage; import java.util.Map; /** * Created by zhoujianghua on 2015/8/4. */ public class MsgViewHolderPicture extends MsgViewHolderThumbBase { public MsgViewHolderPicture(BaseMultiItemFetchLoadAdapter adapter) { super(adapter); } @Override protected int getContentResId() { CommonUtil.setonDealImageMediaUrlListener(new CommonUtil.onDealImageMediaUrlListener() { @Override public void onDealImageMediaUrl(IMMessage messageNwe) { message = messageNwe; WatchMessagePictureActivity.start(context, message); } }); return R.layout.nim_message_item_picture; } @Override protected void onItemClick() { if (CommonUtil.role == CommonUtil.SELLER) { Map<String, Object> map = message.getRemoteExtension(); if (map != null) { String wxMsgId = (String) map.get("wxMsgId"); if (!TextUtils.isEmpty(wxMsgId)) { CommonUtil.onGetMediaUrlListener onGetMediaUrlListener = CommonUtil.getMediaUrlListener; if (onGetMediaUrlListener != null) { onGetMediaUrlListener.onMediaUrl(message,context,wxMsgId); return; } } } WatchMessagePictureActivity.start(context, message); } else { WatchMessagePictureActivity.start(context, message); } } @Override protected String thumbFromSourceFile(String path) { return path; } }
UTF-8
Java
2,250
java
MsgViewHolderPicture.java
Java
[ { "context": "Message;\n\nimport java.util.Map;\n\n/**\n * Created by zhoujianghua on 2015/8/4.\n */\npublic class MsgViewHolderPictur", "end": 714, "score": 0.9822869300842285, "start": 702, "tag": "USERNAME", "value": "zhoujianghua" } ]
null
[]
package com.netease.nim.uikit.business.session.viewholder; import android.text.TextUtils; import android.util.Log; import com.netease.nim.uikit.R; import com.netease.nim.uikit.business.session.activity.WatchMessagePictureActivity; import com.netease.nim.uikit.common.CommonUtil; import com.netease.nim.uikit.common.ToastHelper; import com.netease.nim.uikit.common.ui.recyclerview.adapter.BaseMultiItemFetchLoadAdapter; import com.netease.nim.uikit.common.util.log.sdk.util.FileUtils; import com.netease.nimlib.sdk.msg.attachment.FileAttachment; import com.netease.nimlib.sdk.msg.attachment.ImageAttachment; import com.netease.nimlib.sdk.msg.model.IMMessage; import java.util.Map; /** * Created by zhoujianghua on 2015/8/4. */ public class MsgViewHolderPicture extends MsgViewHolderThumbBase { public MsgViewHolderPicture(BaseMultiItemFetchLoadAdapter adapter) { super(adapter); } @Override protected int getContentResId() { CommonUtil.setonDealImageMediaUrlListener(new CommonUtil.onDealImageMediaUrlListener() { @Override public void onDealImageMediaUrl(IMMessage messageNwe) { message = messageNwe; WatchMessagePictureActivity.start(context, message); } }); return R.layout.nim_message_item_picture; } @Override protected void onItemClick() { if (CommonUtil.role == CommonUtil.SELLER) { Map<String, Object> map = message.getRemoteExtension(); if (map != null) { String wxMsgId = (String) map.get("wxMsgId"); if (!TextUtils.isEmpty(wxMsgId)) { CommonUtil.onGetMediaUrlListener onGetMediaUrlListener = CommonUtil.getMediaUrlListener; if (onGetMediaUrlListener != null) { onGetMediaUrlListener.onMediaUrl(message,context,wxMsgId); return; } } } WatchMessagePictureActivity.start(context, message); } else { WatchMessagePictureActivity.start(context, message); } } @Override protected String thumbFromSourceFile(String path) { return path; } }
2,250
0.667111
0.664444
65
33.615383
28.900728
111
false
false
0
0
0
0
0
0
0.492308
false
false
0
d624ec72049227c834d5fab54051657a3a8851d9
5,703,716,578,208
93cc5652867ceb64cdb018b4395385c0cd766f25
/icqserver/src/ClientConnected.java
f48ac15c3e4417347ea59b5b33fdad4a7313c9fc
[]
no_license
proton5000/icq
https://github.com/proton5000/icq
c2fa7b5b5daac08f66ef2507e122031536ece577
36900338317762f082dab1b058f12747391c1bd2
refs/heads/master
2021-01-10T04:42:00.607000
2015-10-20T13:54:17
2015-10-20T13:54:17
44,609,481
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * Created by marina on 01.04.2015. */ public class ClientConnected extends Thread { Socket s; ClientConnected(Socket s) { this.s = s; this.start(); } @Override public void run() { System.out.println("client connected... " + s.getLocalPort() + " Local port --- Inet port " + s.getPort()); while (true) { BufferedReader read = null; PrintWriter out = null; BufferedReader write = null; try { read = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true); write = new BufferedReader(new InputStreamReader(System.in)); } catch (IOException e) { e.printStackTrace(); } String readIn = null; try { readIn = read.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println(readIn + " " + Thread.currentThread()); out.println("s ::::" + readIn); out.println("s ::: " + write); // try { // read.close(); // } catch (IOException e) { // e.printStackTrace(); // } } } } //ArrayList<Connection> ar=...; // ServerSocket ss=...; // while (true){ // ar.add(new Connection(ss.accept())); // } // //class Connection implements Runnable{ // Connection(Socket s){ // // } //}
UTF-8
Java
1,730
java
ClientConnected.java
Java
[ { "context": "Socket;\nimport java.net.Socket;\n\n/**\n * Created by marina on 01.04.2015.\n */\npublic class ClientConnected e", "end": 200, "score": 0.7781400680541992, "start": 194, "tag": "USERNAME", "value": "marina" } ]
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * Created by marina on 01.04.2015. */ public class ClientConnected extends Thread { Socket s; ClientConnected(Socket s) { this.s = s; this.start(); } @Override public void run() { System.out.println("client connected... " + s.getLocalPort() + " Local port --- Inet port " + s.getPort()); while (true) { BufferedReader read = null; PrintWriter out = null; BufferedReader write = null; try { read = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true); write = new BufferedReader(new InputStreamReader(System.in)); } catch (IOException e) { e.printStackTrace(); } String readIn = null; try { readIn = read.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println(readIn + " " + Thread.currentThread()); out.println("s ::::" + readIn); out.println("s ::: " + write); // try { // read.close(); // } catch (IOException e) { // e.printStackTrace(); // } } } } //ArrayList<Connection> ar=...; // ServerSocket ss=...; // while (true){ // ar.add(new Connection(ss.accept())); // } // //class Connection implements Runnable{ // Connection(Socket s){ // // } //}
1,730
0.521965
0.517341
72
23.041666
22.555141
115
false
false
0
0
0
0
0
0
0.402778
false
false
0
5697cd140a5bca7bd3e6e5769d927bedf62301fb
5,205,500,368,608
d9d3c9a88a2fd50942f574a429cb8a9081e18f08
/src/math/binary/Q1018BinaryPrefixDivisibleBy5.java
64808a81fbb6ea0d464ed72fef528bdbb0e2d637
[ "MIT" ]
permissive
StevenUpForever/LeetCodeInJava
https://github.com/StevenUpForever/LeetCodeInJava
e9a34465b582584efed79193f4ab25395f0699ab
2c181d9108e56986ce587c94926938660323f1cf
refs/heads/master
2021-01-18T18:43:19.732000
2020-09-04T06:19:50
2020-09-04T06:19:50
45,562,856
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package math.binary; import java.util.ArrayList; import java.util.List; public class Q1018BinaryPrefixDivisibleBy5 { /** * 1018. Binary Prefix Divisible By 5 * Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) * * Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. * * Example 1: * * Input: [0,1,1] * Output: [true,false,false] * Explanation: * The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. * Example 2: * * Input: [1,1,1] * Output: [false,false,false] * Example 3: * * Input: [0,1,1,1,1,1] * Output: [true,false,false,false,true,false] * Example 4: * * Input: [1,1,1,0,1] * Output: [false,false,false,false,false] * * * Note: * * 1 <= A.length <= 30000 * A[i] is 0 or 1 */ /* Solution: n % 5 == n << 1 % 5 so n << 1 + digit = (n%5)<<1 + digit every time when n = n << 1 + digit then n %= 5, check if n == 0 Time: O(n) Space: O(n) */ public List<Boolean> prefixesDivBy5(int[] A) { List<Boolean> list = new ArrayList<>(); int num = 0; for (int cur: A) { num = (num << 1) + cur; num %= 5; list.add(num == 0); } return list; } }
UTF-8
Java
1,563
java
Q1018BinaryPrefixDivisibleBy5.java
Java
[]
null
[]
package math.binary; import java.util.ArrayList; import java.util.List; public class Q1018BinaryPrefixDivisibleBy5 { /** * 1018. Binary Prefix Divisible By 5 * Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) * * Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. * * Example 1: * * Input: [0,1,1] * Output: [true,false,false] * Explanation: * The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. * Example 2: * * Input: [1,1,1] * Output: [false,false,false] * Example 3: * * Input: [0,1,1,1,1,1] * Output: [true,false,false,false,true,false] * Example 4: * * Input: [1,1,1,0,1] * Output: [false,false,false,false,false] * * * Note: * * 1 <= A.length <= 30000 * A[i] is 0 or 1 */ /* Solution: n % 5 == n << 1 % 5 so n << 1 + digit = (n%5)<<1 + digit every time when n = n << 1 + digit then n %= 5, check if n == 0 Time: O(n) Space: O(n) */ public List<Boolean> prefixesDivBy5(int[] A) { List<Boolean> list = new ArrayList<>(); int num = 0; for (int cur: A) { num = (num << 1) + cur; num %= 5; list.add(num == 0); } return list; } }
1,563
0.52975
0.484965
63
23.809525
30.881678
172
false
false
0
0
0
0
0
0
0.698413
false
false
0
2f141d48688d35fbefc3cdb31921153d7b974f1c
6,940,667,184,220
145e2834746b8a95c1f32ea4f984407068bc6d74
/app/src/main/java/com/tbeh/ninjaclicker/model/sprite/components/IComponent.java
c119f9a0c3109d89809c38719671da4369926f3e
[]
no_license
thilo-behnke/android-ninja-clicker-game
https://github.com/thilo-behnke/android-ninja-clicker-game
daaa6058c25cbb13271520ba17ace3c7ddbfa6f1
e891894f0f8528d3abbf0a2cac59f8fb122f55fa
refs/heads/master
2021-06-22T10:11:36.252000
2017-08-11T13:13:35
2017-08-11T13:13:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tbeh.ninjaclicker.model.sprite.components; import com.tbeh.ninjaclicker.model.sprite.Sprite; public interface IComponent { void initialize(Sprite sprite); void update(Sprite sprite); String toString(); }
UTF-8
Java
232
java
IComponent.java
Java
[]
null
[]
package com.tbeh.ninjaclicker.model.sprite.components; import com.tbeh.ninjaclicker.model.sprite.Sprite; public interface IComponent { void initialize(Sprite sprite); void update(Sprite sprite); String toString(); }
232
0.758621
0.758621
11
20.09091
19.974777
54
false
false
0
0
0
0
0
0
0.454545
false
false
0
71ef9bf0251d27955876a72731586fd5b1249ad6
21,646,635,211,721
ee160c4a0906d020270caf6b85c974e299c81ccd
/src/sium/app/ATIS.java
c126808c27187dfda56ec5f19e67906a257336bb
[ "MIT" ]
permissive
bsu-slim/sium
https://github.com/bsu-slim/sium
560ef644d867c2dc2dc8ecf42f6067e9c8f85d39
8a23244e7d83b8cea33566601bacb828fc1acdf3
refs/heads/master
2020-04-04T11:29:53.986000
2018-11-21T19:51:37
2018-11-21T19:51:37
155,893,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sium.app; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Scanner; import java.util.TreeSet; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.varia.NullAppender; import sium.nlu.context.Context; import sium.nlu.grounding.Grounder; import sium.nlu.language.LingEvidence; import sium.nlu.language.mapping.Mapping; import sium.nlu.language.mapping.MaxEntMapping; import sium.nlu.language.mapping.NaiveBayesMapping; import sium.nlu.stat.Distribution; public class ATIS { ArrayList<Instance> data; TreeSet<String> attributes; Instance current; String currentType; String path = "/home/casey/corpora/ATIS/atoms/"; // Mapping<String> goalMapping = new MaxEntMapping("goal.txt"); Mapping<String> slotMapping = new MaxEntMapping("slot.txt"); Mapping<String> goalMapping = new NaiveBayesMapping(); // Mapping<String> slotMapping = new NaiveBayesMapping(); Context<String,String> slots = new Context<String, String>(); // keeps track of all slots Context<String,String> goals = new Context<String, String>(); // keeps track of all the goals private void train() throws IOException { BasicConfigurator.configure(new NullAppender()); // turn logging off for the demo attributes = new TreeSet<String>(); data = new ArrayList<Instance>(); gatherData(path+"trainAtis.atoms"); gatherData(path+"devAtis.train.atoms"); cleanup(); // run this for the final eval System.out.println("num instances for training: " + data.size()); trainModel(); // evaluate(path+"atis_2_3_dev.atoms", path+"atis.guess"); evaluate(path+"testAtis.atoms", path+"atis.guess"); } private void cleanup() { if (current != null) { current.clearEnds(); data.add(current); } current = null; } private void trainModel() { for (Instance instance : data) { String pWord = "<s1>"; String ppWord = "<s2>"; String pppWord = "<s3>"; String pPos = "<t1>"; String ppPos = "<t2>"; String pSlot = "<p1>"; String ppSlot = "<p2>"; // step through each instance incrementally, word by word for (Integer i : instance.getIndeces()) { // the main goal is to map the word to the tag String goldTag = instance.getSlotsMap().get(i); String word = instance.getWordsMap().get(i); Context<String,String> context = new Context<String,String>(); addProperties(context, goldTag); String pos = instance.getPOSMap().get(i); addProperties(goals, instance.goal); addProperties(slots, goldTag); LingEvidence ling = new LingEvidence(); ling.addEvidence("w1", word); ling.addEvidence("w2", pWord); ling.addEvidence("w3", ppWord); // ling.addEvidence("tag1", pSlot); // ling.addEvidence("pos1", pos + "_" + word); slotMapping.addEvidenceToTrain(ling, context.getPropertiesForEntity(goldTag)); // ling.addEvidence("tag2", ppSlot); // ling.addEvidence("pos2", pPos + "_" + pWord); // ling.addEvidence("pos3", ppPos + "_" + ppWord); ling.addEvidence("w4", pppWord); goalMapping.addEvidenceToTrain(ling, goals.getPropertiesForEntity(instance.goal)); pppWord = ppWord; ppWord = pWord; pWord = word; ppPos = pPos; pPos = pos; ppSlot = pSlot; pSlot = goldTag; } } goalMapping.train(); slotMapping.train(); } private void addProperties(Context<String, String> goals, String goal) { goals.addPropertyToEntity(goal, goal); } private void evaluate(String evalpath, String outpath) throws IOException { data.clear(); gatherData(evalpath); cleanup(); FileWriter writer = new FileWriter(new File(outpath)); HashMap<String,Double> confusionMatrix = new HashMap<String,Double>(); double correct = 0.0, total = 0.0, flights = 0.0; for (Instance instance : data) { writer.write("=== " + instance.getSentence() +"\n"); String pWord = "<s1>"; String ppWord = "<s2>"; String pppWord = "<s3>"; String pPos = "<t1>"; String ppPos = "<t2>"; String pSlot = "<p1>"; String ppSlot = "<p2>"; Grounder<String, String> goal = new Grounder<String, String>(); ArrayList<String> guesses = new ArrayList<String> (); ArrayList<String> words = new ArrayList<String>(); String prevGuess = new String(); for (Integer i : instance.getIndeces()) { Grounder<String, String> slot = new Grounder<String, String>(); String word = instance.getWordsMap().get(i); String pos = instance.getPOSMap().get(i); String goldTag = instance.getSlotsMap().get(i); LingEvidence ling = new LingEvidence(); ling.addEvidence("w1", word); ling.addEvidence("w2", pWord); ling.addEvidence("w3", ppWord); ling.addEvidence("tag1", pSlot); ling.addEvidence("pos1", pos + "_" + word); Distribution<String> slotDist = slotMapping.applyEvidenceToContext(ling); slot.groundIncrement(slots, slotDist); String guess = slot.getPosterior().getArgMax().getEntity(); ppSlot = pSlot; pSlot = guess; ling.addEvidence("tag2", ppSlot); ling.addEvidence("pos2", pPos + "_" + pWord); ling.addEvidence("pos3", ppPos + "_" + ppWord); ling.addEvidence("w4", pppWord); Distribution<String> goalDist = goalMapping.applyEvidenceToContext(ling); goal.groundIncrement(goals, goalDist); guesses.add(guess); words.add(word); pppWord = ppWord; ppWord = pWord; pWord = word; ppPos = pPos; pPos = pos; if (!goldTag.equals(guess) && !guess.equals("OSLOT")) { String con = goldTag+":"+guess; if (!confusionMatrix.containsKey(con)) { confusionMatrix.put(con, 0.0); } double temp = confusionMatrix.get(con); temp++; confusionMatrix.put(con, temp); } } // Now, we have to write the guesses to a file String guess = goal.getPosterior().getArgMax().getEntity(); if (instance.goal.equals("FLIGHT")) flights++; if (guess.equals(instance.goal)) correct++; total++; writer.write("GOAL:" + guess + "\n"); // collect all guesses throughout the sentence, combining ones that have the same guessed tag prevGuess = new String(); String prevWord = new String(); String slotWords = new String(); ArrayList<String> foundSlots = new ArrayList<String>(); for (int j=0; j<words.size(); j++) { String g = guesses.get(j); String w = words.get(j); if (prevGuess.equals(g)) { slotWords += " " + w; } else { if (!"".equals(prevWord)) { foundSlots.add(prevGuess.toUpperCase() + "=" +slotWords); slotWords = new String(); } slotWords += w; } prevGuess = g; prevWord = w; } if (!"".equals(prevWord)) { foundSlots.add(prevGuess.toUpperCase() + "=" + slotWords); } // now write them filter out OSLOT for (String f : foundSlots) { if (f.startsWith("OSLOT")) continue; writer.write(f.trim()+"\n"); } writer.write("*\n"); } System.out.println(correct + " " + total + " %correct:" + correct/total + " %flights:" + flights/total); // for (String key : confusionMatrix.keySet()) { // System.out.println(key + " " + confusionMatrix.get(key)); // } writer.close(); goalMapping.clear(); slotMapping.clear(); } private void gatherData(String string) throws FileNotFoundException { Scanner scan = new Scanner(new File(string)); String line = ""; while (scan.hasNext()){ line = scan.nextLine(); process(line); } scan.close(); } private void process(String line) { if (line.isEmpty()) return; if (line.equals(">>")) { if (current != null) { current.clearEnds(); data.add(current); } current = new Instance(); } else if (line.contains(">slot")) { currentType = "slot"; return; } else if (line.contains(">pos")) { currentType = "pos"; return; } else if (line.contains(">cass")) { currentType = "cass"; return; } else if (line.contains(">word")) { currentType = "word"; return; } else if (line.contains(">goal")) { currentType = "goal"; return; } else if (line.startsWith(">")) { currentType = null; return; } if (currentType != null) current.add(currentType, line); } public static void main(String[] args) { try { new ATIS().train(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public class Instance { HashMap<String, HashMap<Integer,String>> maps = new HashMap<String, HashMap<Integer,String>>(); String goal; public Instance() { maps.put("word", new HashMap<Integer,String>()); } public void add(String type, String line) { if (type.equals("goal")) { this.goal = clean(line); return; } String[] split = line.split("\\s+"); Integer i = Integer.parseInt(clean(split[0])); if (!maps.containsKey(type)) { maps.put(type, new HashMap<Integer,String>()); } HashMap<Integer,String> temp = maps.get(type); temp.put(i, clean(split[1])); maps.put(type, temp); } public void clearEnds() { int start = 0; int end = 0; for (Integer i : getWordsMap().keySet()) { String word = getWordsMap().get(i); if (word.equals("END")) end = i; } for (String type : maps.keySet()) { maps.get(type).remove(start); maps.get(type).remove(end); } } private String clean(String line) { String newLine = line.trim(); newLine = newLine.replace("\"", ""); return newLine; } public String toString() { return goal + " " + maps; } public HashMap<Integer, String> getWordsMap() { return maps.get("word"); } public HashMap<Integer, String> getSlotsMap() { return maps.get("slot"); } public HashMap<Integer, String> getPOSMap() { return maps.get("pos"); } public HashMap<Integer, String> getCassMap() { return maps.get("cass"); } public TreeSet<Integer> getIndeces() { TreeSet<Integer> orderedWords = new TreeSet<Integer>(); orderedWords.addAll(getWordsMap().keySet()); return orderedWords; } public String getSentence() { String temp = ""; for (Integer i : getIndeces()) { temp += getWordsMap().get(i) + " "; } return temp.trim(); } } }
UTF-8
Java
10,496
java
ATIS.java
Java
[]
null
[]
package sium.app; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Scanner; import java.util.TreeSet; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.varia.NullAppender; import sium.nlu.context.Context; import sium.nlu.grounding.Grounder; import sium.nlu.language.LingEvidence; import sium.nlu.language.mapping.Mapping; import sium.nlu.language.mapping.MaxEntMapping; import sium.nlu.language.mapping.NaiveBayesMapping; import sium.nlu.stat.Distribution; public class ATIS { ArrayList<Instance> data; TreeSet<String> attributes; Instance current; String currentType; String path = "/home/casey/corpora/ATIS/atoms/"; // Mapping<String> goalMapping = new MaxEntMapping("goal.txt"); Mapping<String> slotMapping = new MaxEntMapping("slot.txt"); Mapping<String> goalMapping = new NaiveBayesMapping(); // Mapping<String> slotMapping = new NaiveBayesMapping(); Context<String,String> slots = new Context<String, String>(); // keeps track of all slots Context<String,String> goals = new Context<String, String>(); // keeps track of all the goals private void train() throws IOException { BasicConfigurator.configure(new NullAppender()); // turn logging off for the demo attributes = new TreeSet<String>(); data = new ArrayList<Instance>(); gatherData(path+"trainAtis.atoms"); gatherData(path+"devAtis.train.atoms"); cleanup(); // run this for the final eval System.out.println("num instances for training: " + data.size()); trainModel(); // evaluate(path+"atis_2_3_dev.atoms", path+"atis.guess"); evaluate(path+"testAtis.atoms", path+"atis.guess"); } private void cleanup() { if (current != null) { current.clearEnds(); data.add(current); } current = null; } private void trainModel() { for (Instance instance : data) { String pWord = "<s1>"; String ppWord = "<s2>"; String pppWord = "<s3>"; String pPos = "<t1>"; String ppPos = "<t2>"; String pSlot = "<p1>"; String ppSlot = "<p2>"; // step through each instance incrementally, word by word for (Integer i : instance.getIndeces()) { // the main goal is to map the word to the tag String goldTag = instance.getSlotsMap().get(i); String word = instance.getWordsMap().get(i); Context<String,String> context = new Context<String,String>(); addProperties(context, goldTag); String pos = instance.getPOSMap().get(i); addProperties(goals, instance.goal); addProperties(slots, goldTag); LingEvidence ling = new LingEvidence(); ling.addEvidence("w1", word); ling.addEvidence("w2", pWord); ling.addEvidence("w3", ppWord); // ling.addEvidence("tag1", pSlot); // ling.addEvidence("pos1", pos + "_" + word); slotMapping.addEvidenceToTrain(ling, context.getPropertiesForEntity(goldTag)); // ling.addEvidence("tag2", ppSlot); // ling.addEvidence("pos2", pPos + "_" + pWord); // ling.addEvidence("pos3", ppPos + "_" + ppWord); ling.addEvidence("w4", pppWord); goalMapping.addEvidenceToTrain(ling, goals.getPropertiesForEntity(instance.goal)); pppWord = ppWord; ppWord = pWord; pWord = word; ppPos = pPos; pPos = pos; ppSlot = pSlot; pSlot = goldTag; } } goalMapping.train(); slotMapping.train(); } private void addProperties(Context<String, String> goals, String goal) { goals.addPropertyToEntity(goal, goal); } private void evaluate(String evalpath, String outpath) throws IOException { data.clear(); gatherData(evalpath); cleanup(); FileWriter writer = new FileWriter(new File(outpath)); HashMap<String,Double> confusionMatrix = new HashMap<String,Double>(); double correct = 0.0, total = 0.0, flights = 0.0; for (Instance instance : data) { writer.write("=== " + instance.getSentence() +"\n"); String pWord = "<s1>"; String ppWord = "<s2>"; String pppWord = "<s3>"; String pPos = "<t1>"; String ppPos = "<t2>"; String pSlot = "<p1>"; String ppSlot = "<p2>"; Grounder<String, String> goal = new Grounder<String, String>(); ArrayList<String> guesses = new ArrayList<String> (); ArrayList<String> words = new ArrayList<String>(); String prevGuess = new String(); for (Integer i : instance.getIndeces()) { Grounder<String, String> slot = new Grounder<String, String>(); String word = instance.getWordsMap().get(i); String pos = instance.getPOSMap().get(i); String goldTag = instance.getSlotsMap().get(i); LingEvidence ling = new LingEvidence(); ling.addEvidence("w1", word); ling.addEvidence("w2", pWord); ling.addEvidence("w3", ppWord); ling.addEvidence("tag1", pSlot); ling.addEvidence("pos1", pos + "_" + word); Distribution<String> slotDist = slotMapping.applyEvidenceToContext(ling); slot.groundIncrement(slots, slotDist); String guess = slot.getPosterior().getArgMax().getEntity(); ppSlot = pSlot; pSlot = guess; ling.addEvidence("tag2", ppSlot); ling.addEvidence("pos2", pPos + "_" + pWord); ling.addEvidence("pos3", ppPos + "_" + ppWord); ling.addEvidence("w4", pppWord); Distribution<String> goalDist = goalMapping.applyEvidenceToContext(ling); goal.groundIncrement(goals, goalDist); guesses.add(guess); words.add(word); pppWord = ppWord; ppWord = pWord; pWord = word; ppPos = pPos; pPos = pos; if (!goldTag.equals(guess) && !guess.equals("OSLOT")) { String con = goldTag+":"+guess; if (!confusionMatrix.containsKey(con)) { confusionMatrix.put(con, 0.0); } double temp = confusionMatrix.get(con); temp++; confusionMatrix.put(con, temp); } } // Now, we have to write the guesses to a file String guess = goal.getPosterior().getArgMax().getEntity(); if (instance.goal.equals("FLIGHT")) flights++; if (guess.equals(instance.goal)) correct++; total++; writer.write("GOAL:" + guess + "\n"); // collect all guesses throughout the sentence, combining ones that have the same guessed tag prevGuess = new String(); String prevWord = new String(); String slotWords = new String(); ArrayList<String> foundSlots = new ArrayList<String>(); for (int j=0; j<words.size(); j++) { String g = guesses.get(j); String w = words.get(j); if (prevGuess.equals(g)) { slotWords += " " + w; } else { if (!"".equals(prevWord)) { foundSlots.add(prevGuess.toUpperCase() + "=" +slotWords); slotWords = new String(); } slotWords += w; } prevGuess = g; prevWord = w; } if (!"".equals(prevWord)) { foundSlots.add(prevGuess.toUpperCase() + "=" + slotWords); } // now write them filter out OSLOT for (String f : foundSlots) { if (f.startsWith("OSLOT")) continue; writer.write(f.trim()+"\n"); } writer.write("*\n"); } System.out.println(correct + " " + total + " %correct:" + correct/total + " %flights:" + flights/total); // for (String key : confusionMatrix.keySet()) { // System.out.println(key + " " + confusionMatrix.get(key)); // } writer.close(); goalMapping.clear(); slotMapping.clear(); } private void gatherData(String string) throws FileNotFoundException { Scanner scan = new Scanner(new File(string)); String line = ""; while (scan.hasNext()){ line = scan.nextLine(); process(line); } scan.close(); } private void process(String line) { if (line.isEmpty()) return; if (line.equals(">>")) { if (current != null) { current.clearEnds(); data.add(current); } current = new Instance(); } else if (line.contains(">slot")) { currentType = "slot"; return; } else if (line.contains(">pos")) { currentType = "pos"; return; } else if (line.contains(">cass")) { currentType = "cass"; return; } else if (line.contains(">word")) { currentType = "word"; return; } else if (line.contains(">goal")) { currentType = "goal"; return; } else if (line.startsWith(">")) { currentType = null; return; } if (currentType != null) current.add(currentType, line); } public static void main(String[] args) { try { new ATIS().train(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public class Instance { HashMap<String, HashMap<Integer,String>> maps = new HashMap<String, HashMap<Integer,String>>(); String goal; public Instance() { maps.put("word", new HashMap<Integer,String>()); } public void add(String type, String line) { if (type.equals("goal")) { this.goal = clean(line); return; } String[] split = line.split("\\s+"); Integer i = Integer.parseInt(clean(split[0])); if (!maps.containsKey(type)) { maps.put(type, new HashMap<Integer,String>()); } HashMap<Integer,String> temp = maps.get(type); temp.put(i, clean(split[1])); maps.put(type, temp); } public void clearEnds() { int start = 0; int end = 0; for (Integer i : getWordsMap().keySet()) { String word = getWordsMap().get(i); if (word.equals("END")) end = i; } for (String type : maps.keySet()) { maps.get(type).remove(start); maps.get(type).remove(end); } } private String clean(String line) { String newLine = line.trim(); newLine = newLine.replace("\"", ""); return newLine; } public String toString() { return goal + " " + maps; } public HashMap<Integer, String> getWordsMap() { return maps.get("word"); } public HashMap<Integer, String> getSlotsMap() { return maps.get("slot"); } public HashMap<Integer, String> getPOSMap() { return maps.get("pos"); } public HashMap<Integer, String> getCassMap() { return maps.get("cass"); } public TreeSet<Integer> getIndeces() { TreeSet<Integer> orderedWords = new TreeSet<Integer>(); orderedWords.addAll(getWordsMap().keySet()); return orderedWords; } public String getSentence() { String temp = ""; for (Integer i : getIndeces()) { temp += getWordsMap().get(i) + " "; } return temp.trim(); } } }
10,496
0.631193
0.626524
410
24.6
21.142166
106
false
false
0
0
0
0
0
0
3.360976
false
false
0
218f0afdd660651c2667e000dbf2a5ea3ed546d7
12,498,354,874,500
6cb26c4d9e69c9cde033b90a8e4150ff6196015b
/amazon-echo-ha-bridge/src/main/java/com/armzilla/ha/rest/RestConstants.java
f2fa08658e7c3d364f1cb1434a830721606a9cdb
[ "Apache-2.0" ]
permissive
TheTinkerDad/amazon-echo-ha-bridge
https://github.com/TheTinkerDad/amazon-echo-ha-bridge
df227ba210c1841784b314de0a3bdb3823b056fd
e7367efa5703dc916d4fc8bdfdec52f2664c054b
refs/heads/master
2020-04-15T02:31:06.349000
2019-02-13T11:32:54
2019-02-13T11:32:54
164,317,379
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.armzilla.ha.rest; public class RestConstants { public static final String APPLICATION_JSON = "application/json"; }
UTF-8
Java
135
java
RestConstants.java
Java
[]
null
[]
package com.armzilla.ha.rest; public class RestConstants { public static final String APPLICATION_JSON = "application/json"; }
135
0.748148
0.748148
7
18.285715
24.045874
69
false
false
0
0
0
0
0
0
0.428571
false
false
0
bb6f2164cba7bd842dfe52161fd59e0c7e6d5d06
20,186,346,337,284
84bce56a5557e6230b3f221c0fb5eb420084871b
/utils/restclient/handler/FileHandler.java
7205ddeb33b59022c05d2ef404c7cb76d1a171db
[]
no_license
zafor99/serviceatlas
https://github.com/zafor99/serviceatlas
8e42c9e5a161e34e188cd09af9ab39103f79318d
922ffdd223d1d8b206efb63e0a1a42083fe1bd9c
refs/heads/master
2022-11-29T17:23:47.411000
2019-07-28T19:57:47
2019-07-28T19:57:47
94,845,828
0
0
null
false
2022-11-24T07:02:22
2017-06-20T03:28:52
2019-07-28T19:57:49
2022-11-24T07:02:18
69,909
0
0
4
Java
false
false
package com.bn.qa.webservice.restclient.handler; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import com.bn.qa.webservice.exceptions.ResponseException; import com.bn.qa.webservice.restclient.httpclient.BNHttpClient; import com.bn.qa.webservice.restclient.specification.IHandler; public class FileHandler implements IHandler<File> { public File handleResponse(HttpResponse response) throws ResponseException { HttpEntity entity = response.getEntity(); InputStream stream = null; String body = null; File file = new File(String.format(BNHttpClient.BN_ANDROID_SYNC_FILE_PATH, System.currentTimeMillis())); FileWriter fw = null; try { file.createNewFile(); fw = new FileWriter(file); stream = entity.getContent(); boolean gzip = false; if (response.containsHeader("Content-Encoding")) { Header encodingHeader = response.getFirstHeader("Content-Encoding"); if (encodingHeader.getValue().contains("gzip")) { gzip = true; } } // Input reader BufferedReader input = null; if (gzip) { input = new BufferedReader(new InputStreamReader(new GZIPInputStream(stream))); } else { input = new BufferedReader(new InputStreamReader(stream)); } //StringBuilder buffer = new StringBuilder(); String line = null; while ((line = input.readLine()) != null) { //buffer.append(line + "\n"); fw.write(line + "\n"); } //body = buffer.toString(); } catch (IOException e) { throw new ResponseException(e); } finally { try { if (entity != null) entity.consumeContent(); if (stream != null) stream.close(); if (fw != null) fw.close(); } catch (Exception e) { // TODO we should never get here, but log in case? } } // TODO remove logging //LoggerFactory.getDefaultInstance().information(TAG, "RESPONSE: " + body); return file; //return body; } @Override public File handleResponse(Object response) throws ResponseException { // TODO Auto-generated method stub return null; } }
UTF-8
Java
2,347
java
FileHandler.java
Java
[]
null
[]
package com.bn.qa.webservice.restclient.handler; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import com.bn.qa.webservice.exceptions.ResponseException; import com.bn.qa.webservice.restclient.httpclient.BNHttpClient; import com.bn.qa.webservice.restclient.specification.IHandler; public class FileHandler implements IHandler<File> { public File handleResponse(HttpResponse response) throws ResponseException { HttpEntity entity = response.getEntity(); InputStream stream = null; String body = null; File file = new File(String.format(BNHttpClient.BN_ANDROID_SYNC_FILE_PATH, System.currentTimeMillis())); FileWriter fw = null; try { file.createNewFile(); fw = new FileWriter(file); stream = entity.getContent(); boolean gzip = false; if (response.containsHeader("Content-Encoding")) { Header encodingHeader = response.getFirstHeader("Content-Encoding"); if (encodingHeader.getValue().contains("gzip")) { gzip = true; } } // Input reader BufferedReader input = null; if (gzip) { input = new BufferedReader(new InputStreamReader(new GZIPInputStream(stream))); } else { input = new BufferedReader(new InputStreamReader(stream)); } //StringBuilder buffer = new StringBuilder(); String line = null; while ((line = input.readLine()) != null) { //buffer.append(line + "\n"); fw.write(line + "\n"); } //body = buffer.toString(); } catch (IOException e) { throw new ResponseException(e); } finally { try { if (entity != null) entity.consumeContent(); if (stream != null) stream.close(); if (fw != null) fw.close(); } catch (Exception e) { // TODO we should never get here, but log in case? } } // TODO remove logging //LoggerFactory.getDefaultInstance().information(TAG, "RESPONSE: " + body); return file; //return body; } @Override public File handleResponse(Object response) throws ResponseException { // TODO Auto-generated method stub return null; } }
2,347
0.683852
0.683852
77
28.506493
23.296856
106
false
false
0
0
0
0
0
0
2.558442
false
false
0
a33a1dfe6325a8aac8decabae5f3c7a235798aa4
31,860,067,442,588
3d2ecf16ecae15789a89fcd5c4ea336983ecb1c9
/tecolotl-web/src/main/java/tecolotl/web/profesor/CalificaMapaMentalControlador.java
5c1f3aaa54b0ff7f99870b1084e3ea629696990a
[]
no_license
GuillermoCuahueyE/tecolotl_16_02
https://github.com/GuillermoCuahueyE/tecolotl_16_02
8b7a13176376d22b4a370bbca2e1a72db7268ba4
39fad16019ef8153c8cb5393a8480fe1e4def80f
refs/heads/main
2023-04-13T02:32:49.792000
2021-04-30T00:00:30
2021-04-30T00:00:30
362,972,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tecolotl.web.profesor; import tecolotl.alumno.modelo.mapamental.TareaMapaMentalModelo; import tecolotl.alumno.sesion.MapaMentalSessionBean; import tecolotl.profesor.modelo.CalificaTareaMapaMentalModelo; import tecolotl.profesor.sesion.CalificaTareaMapaMentalSesionBean; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.UUID; import java.util.logging.Logger; @RequestScoped @Named public class CalificaMapaMentalControlador { @Inject private MapaMentalSessionBean mapaMentalSessionBean; @Inject private CalificaTareaMapaMentalSesionBean calificaTareaMapaMentalSesionBean; @Inject private Logger logger; private String idTarea; private Short cardinalidad; private Short intento; private List<TareaMapaMentalModelo> tareaMapaMentalModeloLista; private CalificaTareaMapaMentalModelo calificaTareaMapaMentalModelo; @PostConstruct public void inicio() { calificaTareaMapaMentalModelo = new CalificaTareaMapaMentalModelo(); } public void busca() { tareaMapaMentalModeloLista = mapaMentalSessionBean.busca(UUID.fromString(idTarea), cardinalidad); calificaTareaMapaMentalModelo = calificaTareaMapaMentalSesionBean.busca(UUID.fromString(idTarea), cardinalidad, intento); } public String califica() { logger.info(calificaTareaMapaMentalModelo.toString()); calificaTareaMapaMentalSesionBean.respuesta(calificaTareaMapaMentalModelo); return "tareas"; } public List<TareaMapaMentalModelo> getTareaMapaMentalModeloLista() { return tareaMapaMentalModeloLista; } public void setTareaMapaMentalModeloLista(List<TareaMapaMentalModelo> tareaMapaMentalModeloLista) { this.tareaMapaMentalModeloLista = tareaMapaMentalModeloLista; } public String getIdTarea() { return idTarea; } public void setIdTarea(String idTarea) { this.idTarea = idTarea; } public Short getCardinalidad() { return cardinalidad; } public void setCardinalidad(Short cardinalidad) { this.cardinalidad = cardinalidad; } public Short getIntento() { return intento; } public void setIntento(Short intento) { this.intento = intento; } public CalificaTareaMapaMentalModelo getCalificaTareaMapaMentalModelo() { return calificaTareaMapaMentalModelo; } public void setCalificaTareaMapaMentalModelo(CalificaTareaMapaMentalModelo calificaTareaMapaMentalModelo) { this.calificaTareaMapaMentalModelo = calificaTareaMapaMentalModelo; } }
UTF-8
Java
2,712
java
CalificaMapaMentalControlador.java
Java
[]
null
[]
package tecolotl.web.profesor; import tecolotl.alumno.modelo.mapamental.TareaMapaMentalModelo; import tecolotl.alumno.sesion.MapaMentalSessionBean; import tecolotl.profesor.modelo.CalificaTareaMapaMentalModelo; import tecolotl.profesor.sesion.CalificaTareaMapaMentalSesionBean; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.UUID; import java.util.logging.Logger; @RequestScoped @Named public class CalificaMapaMentalControlador { @Inject private MapaMentalSessionBean mapaMentalSessionBean; @Inject private CalificaTareaMapaMentalSesionBean calificaTareaMapaMentalSesionBean; @Inject private Logger logger; private String idTarea; private Short cardinalidad; private Short intento; private List<TareaMapaMentalModelo> tareaMapaMentalModeloLista; private CalificaTareaMapaMentalModelo calificaTareaMapaMentalModelo; @PostConstruct public void inicio() { calificaTareaMapaMentalModelo = new CalificaTareaMapaMentalModelo(); } public void busca() { tareaMapaMentalModeloLista = mapaMentalSessionBean.busca(UUID.fromString(idTarea), cardinalidad); calificaTareaMapaMentalModelo = calificaTareaMapaMentalSesionBean.busca(UUID.fromString(idTarea), cardinalidad, intento); } public String califica() { logger.info(calificaTareaMapaMentalModelo.toString()); calificaTareaMapaMentalSesionBean.respuesta(calificaTareaMapaMentalModelo); return "tareas"; } public List<TareaMapaMentalModelo> getTareaMapaMentalModeloLista() { return tareaMapaMentalModeloLista; } public void setTareaMapaMentalModeloLista(List<TareaMapaMentalModelo> tareaMapaMentalModeloLista) { this.tareaMapaMentalModeloLista = tareaMapaMentalModeloLista; } public String getIdTarea() { return idTarea; } public void setIdTarea(String idTarea) { this.idTarea = idTarea; } public Short getCardinalidad() { return cardinalidad; } public void setCardinalidad(Short cardinalidad) { this.cardinalidad = cardinalidad; } public Short getIntento() { return intento; } public void setIntento(Short intento) { this.intento = intento; } public CalificaTareaMapaMentalModelo getCalificaTareaMapaMentalModelo() { return calificaTareaMapaMentalModelo; } public void setCalificaTareaMapaMentalModelo(CalificaTareaMapaMentalModelo calificaTareaMapaMentalModelo) { this.calificaTareaMapaMentalModelo = calificaTareaMapaMentalModelo; } }
2,712
0.762168
0.762168
90
29.133333
30.233242
129
false
false
0
0
0
0
0
0
0.433333
false
false
0
c2fed93af8ab5e3703744d0f86c2f096d2cefc83
33,560,874,497,135
b558b92f0e55b6807d63f6b9507c758d7e2f49bc
/MilleniumShopping/app/src/main/java/com/milleniumshopping/app/milleniumshopping/activity/employee/ViewEmployee.java
13fc619e858a93355906f2f43c4aabd5293876e0
[]
no_license
chadfebruary/Assignment-5
https://github.com/chadfebruary/Assignment-5
eaa8096fd48635e6872d2bce41fb2e888cc233ec
a27932085e002eddc66a5f090a475ef77ad8465a
refs/heads/master
2021-01-12T17:35:21.514000
2016-10-31T02:46:07
2016-10-31T02:46:07
71,608,545
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.milleniumshopping.app.milleniumshopping.activity.employee; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.milleniumshopping.app.milleniumshopping.R; import com.milleniumshopping.app.milleniumshopping.activity.MainActivity; import com.milleniumshopping.app.milleniumshopping.domain.employee.Employee; import com.milleniumshopping.app.milleniumshopping.repository.employee.EmployeeRepository; import com.milleniumshopping.app.milleniumshopping.repository.employee.Impl.EmployeeRepositoryImpl; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class ViewEmployee extends AppCompatActivity { ArrayAdapter adapter; ListView listView; String[] names; Set<Employee> employeeSet = new HashSet<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_employee); EmployeeRepository employeeRepository = new EmployeeRepositoryImpl(this.getApplicationContext()); employeeSet = new HashSet<>(); employeeSet = employeeRepository.findAll(); Iterator<Employee> employeeIterator = employeeSet.iterator(); if(employeeSet.size()>0) { names = new String[employeeSet.size()]; int i = 0; while(employeeIterator.hasNext()) { names[i] = employeeIterator.next().toString(); i++; } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,names); listView = (ListView)findViewById(R.id.listView); listView.setAdapter(adapter); } else { Toast.makeText(ViewEmployee.this, "No data", Toast.LENGTH_SHORT).show(); } } public void returnHome(View v) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } /*public class AccountRegisterTask extends AsyncTask<Void, Void, Employee> { private final Account account; AccountRegisterTask(Account account) { this.account = account; } @Override protected Employee doInBackground(Void... params) { final String uri = "http://148.100.5.84:8080/employee/"; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json"))); HttpEntity<Account> requestEntity = new HttpEntity<>(account, requestHeaders); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); ResponseEntity<Account> result = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, Account.class); return result.getBody(); } @Override protected void onPostExecute(final Account success) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(getBaseContext(), "Account successfully added!", Toast.LENGTH_SHORT).show(); } }); } } public static boolean isInternetConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); }*/ }
UTF-8
Java
3,736
java
ViewEmployee.java
Java
[ { "context": "params) {\n\n final String uri = \"http://148.100.5.84:8080/employee/\";\n\n HttpHeaders request", "end": 2494, "score": 0.9996547698974609, "start": 2482, "tag": "IP_ADDRESS", "value": "148.100.5.84" } ]
null
[]
package com.milleniumshopping.app.milleniumshopping.activity.employee; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.milleniumshopping.app.milleniumshopping.R; import com.milleniumshopping.app.milleniumshopping.activity.MainActivity; import com.milleniumshopping.app.milleniumshopping.domain.employee.Employee; import com.milleniumshopping.app.milleniumshopping.repository.employee.EmployeeRepository; import com.milleniumshopping.app.milleniumshopping.repository.employee.Impl.EmployeeRepositoryImpl; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class ViewEmployee extends AppCompatActivity { ArrayAdapter adapter; ListView listView; String[] names; Set<Employee> employeeSet = new HashSet<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_employee); EmployeeRepository employeeRepository = new EmployeeRepositoryImpl(this.getApplicationContext()); employeeSet = new HashSet<>(); employeeSet = employeeRepository.findAll(); Iterator<Employee> employeeIterator = employeeSet.iterator(); if(employeeSet.size()>0) { names = new String[employeeSet.size()]; int i = 0; while(employeeIterator.hasNext()) { names[i] = employeeIterator.next().toString(); i++; } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,names); listView = (ListView)findViewById(R.id.listView); listView.setAdapter(adapter); } else { Toast.makeText(ViewEmployee.this, "No data", Toast.LENGTH_SHORT).show(); } } public void returnHome(View v) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } /*public class AccountRegisterTask extends AsyncTask<Void, Void, Employee> { private final Account account; AccountRegisterTask(Account account) { this.account = account; } @Override protected Employee doInBackground(Void... params) { final String uri = "http://172.16.58.3:8080/employee/"; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json"))); HttpEntity<Account> requestEntity = new HttpEntity<>(account, requestHeaders); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); ResponseEntity<Account> result = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, Account.class); return result.getBody(); } @Override protected void onPostExecute(final Account success) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(getBaseContext(), "Account successfully added!", Toast.LENGTH_SHORT).show(); } }); } } public static boolean isInternetConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); }*/ }
3,735
0.675054
0.670503
109
33.27523
32.162964
119
false
false
0
0
0
0
0
0
0.59633
false
false
0
e116a38def02200dadefb3cd1838125875cf9d6e
20,469,814,164,840
37ee9c3db1b8b3a0269ee395f111d592142d70a9
/service/com.gy.acs/src/main/java/com/gy/domain/vo/req/ArticleReq.java
3aa3c653ae4a7686c33916b2da1d227baa873731
[]
no_license
donggua131432/gy
https://github.com/donggua131432/gy
27ec2434094a05fb78d2afab28fd4a02296f84b5
72c8dd12bff43a4de8b5030fee327e21141b4e00
refs/heads/master
2020-04-13T22:36:51.403000
2019-01-16T16:36:56
2019-01-16T16:36:56
163,483,587
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gy.domain.vo.req; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @描述: 文章实体 * @作者: FangLin * @创建时间: 2018/12/25 15:14 * @版本号: V1.0 */ @ApiModel(value = "Article",description = "文章实体") @Data public class ArticleReq implements Serializable { private static final long serialVersionUID = 8866245710507352903L; @ApiModelProperty("文章ID") private String articleId; @ApiModelProperty("整装ID") private String wholeMakeupId; @ApiModelProperty("外链文字") private String linkText; @ApiModelProperty("链接地址") private String linkUrl; @ApiModelProperty("文章标题") private String articleTitle; @JsonIgnore @ApiModelProperty("创建时间") @JSONField(format = "yy-MM-dd HH:mm:ss") private Date createTime; }
UTF-8
Java
1,054
java
ArticleReq.java
Java
[ { "context": ";\nimport java.util.Date;\n\n/**\n * @描述: 文章实体\n * @作者: FangLin\n * @创建时间: 2018/12/25 15:14\n * @版本号: V1.0\n *", "end": 321, "score": 0.711013913154602, "start": 320, "tag": "NAME", "value": "F" }, { "context": "import java.util.Date;\n\n/**\n * @描述: 文章实体\n * @作者: FangL...
null
[]
package com.gy.domain.vo.req; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @描述: 文章实体 * @作者: FangLin * @创建时间: 2018/12/25 15:14 * @版本号: V1.0 */ @ApiModel(value = "Article",description = "文章实体") @Data public class ArticleReq implements Serializable { private static final long serialVersionUID = 8866245710507352903L; @ApiModelProperty("文章ID") private String articleId; @ApiModelProperty("整装ID") private String wholeMakeupId; @ApiModelProperty("外链文字") private String linkText; @ApiModelProperty("链接地址") private String linkUrl; @ApiModelProperty("文章标题") private String articleTitle; @JsonIgnore @ApiModelProperty("创建时间") @JSONField(format = "yy-MM-dd HH:mm:ss") private Date createTime; }
1,054
0.731557
0.697746
36
26.111111
16.729511
70
false
false
0
0
0
0
0
0
0.444444
false
false
0
4c2a87f65564bf32521cbd96e41cda5d53caa871
17,085,379,939,540
8edb7b997c9d341c85f6b5193ce553e01876f14f
/expedia.java
1b10c67ad93865aeeab0c4f7981f68c7cae0e5d6
[]
no_license
QA101/week-10-homework-Ishwarya24
https://github.com/QA101/week-10-homework-Ishwarya24
288f3dfc1595ff4cf7f344c32afaa5993eb1dfe1
40df0f700361660411f069a22c13c11fad32fadd
refs/heads/master
2021-09-02T08:48:21.170000
2018-01-01T05:45:36
2018-01-01T05:45:36
115,894,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package expe; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.swing.JOptionPane; import org.apache.http.client.utils.DateUtils; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; //import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.support.ui.Select; import com.google.common.io.Files; public class expedia { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.edge.driver","C:\\Users\\Ishwarya\\Documents\\MicrosoftWebDriver.exe"); WebDriver driver = new EdgeDriver(); driver.get("http://expedia.com"); WebElement origin = driver.findElement(By.id("package-origin-hp-package")); origin.sendKeys("SEA"); origin.sendKeys(Keys.TAB); WebElement destination = driver.findElement(By.id("package-destination-hp-package")); destination.sendKeys("Mexico"); destination.sendKeys(Keys.TAB); WebElement dateWidget = driver.findElement(By.id("package-departing-hp-package")); DateFormat d= new SimpleDateFormat("mm/dd/yyyy"); Date date = new Date(); dateWidget.sendKeys(d.format(date)); dateWidget.sendKeys(Keys.TAB); List<WebElement> columns=dateWidget.findElements(By.tagName("td")); for (WebElement cell: columns){ if (cell.getText().equals("11")){ cell.findElement(By.linkText("11")).click(); break; } } WebElement dateWidget1 = driver.findElement(By.id("package-returning-hp-package")); List<WebElement> columns1=dateWidget.findElements(By.tagName("td")); for (WebElement cell: columns1){ if (cell.getText().equals("23")){ cell.findElement(By.linkText("23")).click(); break; } } WebElement search = driver.findElement(By.id("search-button-hp-package")); search.click(); Thread.sleep(5000); driver.quit(); } }
UTF-8
Java
2,155
java
expedia.java
Java
[]
null
[]
package expe; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.swing.JOptionPane; import org.apache.http.client.utils.DateUtils; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; //import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.support.ui.Select; import com.google.common.io.Files; public class expedia { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.edge.driver","C:\\Users\\Ishwarya\\Documents\\MicrosoftWebDriver.exe"); WebDriver driver = new EdgeDriver(); driver.get("http://expedia.com"); WebElement origin = driver.findElement(By.id("package-origin-hp-package")); origin.sendKeys("SEA"); origin.sendKeys(Keys.TAB); WebElement destination = driver.findElement(By.id("package-destination-hp-package")); destination.sendKeys("Mexico"); destination.sendKeys(Keys.TAB); WebElement dateWidget = driver.findElement(By.id("package-departing-hp-package")); DateFormat d= new SimpleDateFormat("mm/dd/yyyy"); Date date = new Date(); dateWidget.sendKeys(d.format(date)); dateWidget.sendKeys(Keys.TAB); List<WebElement> columns=dateWidget.findElements(By.tagName("td")); for (WebElement cell: columns){ if (cell.getText().equals("11")){ cell.findElement(By.linkText("11")).click(); break; } } WebElement dateWidget1 = driver.findElement(By.id("package-returning-hp-package")); List<WebElement> columns1=dateWidget.findElements(By.tagName("td")); for (WebElement cell: columns1){ if (cell.getText().equals("23")){ cell.findElement(By.linkText("23")).click(); break; } } WebElement search = driver.findElement(By.id("search-button-hp-package")); search.click(); Thread.sleep(5000); driver.quit(); } }
2,155
0.72761
0.72065
82
25.231707
25.636435
103
false
false
0
0
0
0
0
0
1.439024
false
false
0
46a09630ad83826acbc447f238241cf41271ce6e
7,876,970,091,561
ee0388d1d712a8b2a151d3ffa2e834ab963e6139
/U7_T7_Collections/MapT2/Main.java
47eed77e6272fb0352d3b9cc240059785aeee716
[]
no_license
DavidRG4/Programacion
https://github.com/DavidRG4/Programacion
2d1136c637cd3f44295944536fd96490f82bc15c
694fd78eb4c0211040e423e77ec999a054253d89
refs/heads/master
2023-04-27T22:07:18.838000
2021-04-27T11:45:47
2021-04-27T11:45:47
297,617,553
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.MapT2; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String opcion2=" ",nfb,nombre,dni; int opcion,edad; double altura,saldo; System.out.println("1-Desea cargar datos de un fichero binario"); System.out.println("2-Desea cargar datos de forma manual "); opcion= sc.nextInt(); if (opcion==1){ nfb=sc.nextLine(); Empleado e=new Empleado(nfb); }else if(opcion==2){ do { System.out.println("Dime un dni"); dni=sc.nextLine(); System.out.println("Dime un nombre"); nombre=sc.nextLine(); System.out.println("Dime la edad"); edad=sc.nextInt(); System.out.println("Dime la altura"); altura=sc.nextDouble(); System.out.println("Dime el saldo"); saldo=sc.nextDouble(); System.out.println("Quires seguir introduciendo datos[Y/N]"); opcion2= sc.nextLine(); }while (opcion2.equalsIgnoreCase("n")); }else { System.out.println("Ninguna opcion es valida"); } } }
UTF-8
Java
1,291
java
Main.java
Java
[]
null
[]
package com.company.MapT2; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String opcion2=" ",nfb,nombre,dni; int opcion,edad; double altura,saldo; System.out.println("1-Desea cargar datos de un fichero binario"); System.out.println("2-Desea cargar datos de forma manual "); opcion= sc.nextInt(); if (opcion==1){ nfb=sc.nextLine(); Empleado e=new Empleado(nfb); }else if(opcion==2){ do { System.out.println("Dime un dni"); dni=sc.nextLine(); System.out.println("Dime un nombre"); nombre=sc.nextLine(); System.out.println("Dime la edad"); edad=sc.nextInt(); System.out.println("Dime la altura"); altura=sc.nextDouble(); System.out.println("Dime el saldo"); saldo=sc.nextDouble(); System.out.println("Quires seguir introduciendo datos[Y/N]"); opcion2= sc.nextLine(); }while (opcion2.equalsIgnoreCase("n")); }else { System.out.println("Ninguna opcion es valida"); } } }
1,291
0.53292
0.526723
36
34.861111
19.445297
77
false
false
0
0
0
0
0
0
0.833333
false
false
0
aa47643f0b3e5cd785d2f0c2adaac761de6d12ca
4,329,327,040,231
bf44677a3d1806134653acb6a3548e585028c535
/src/main/java/com/glacialrush/api/dispatch/notification/NotificationHandler.java
86623a32470b6cb7ea38be5ab52ac5436758a171
[]
no_license
cyberpwnn/GlacialAPI
https://github.com/cyberpwnn/GlacialAPI
2dd90d1d20aac7ccae157b8578b256992f1c7188
8202bb166be0b705cb117ddcde0dec96818381f9
refs/heads/master
2021-01-19T09:49:45.162000
2016-11-27T22:15:11
2016-11-27T22:15:11
74,915,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.glacialrush.api.dispatch.notification; import java.util.UUID; import org.bukkit.entity.Player; import com.glacialrush.api.game.Game; import com.glacialrush.api.game.GameState; import com.glacialrush.api.game.GlacialHandler; import com.glacialrush.api.object.GList; import com.glacialrush.api.object.GMap; public class NotificationHandler extends GlacialHandler { private GMap<Player, GList<Notification>> queue; private GMap<Player, Notification> ongoing; private GMap<Player, Integer> cooldown; public NotificationHandler(Game game) { super(game); } @Override public void start(GameState state) { super.start(state); queue = new GMap<Player, GList<Notification>>(); ongoing = new GMap<Player, Notification>(); cooldown = new GMap<Player, Integer>(); } @Override public void tick(GameState state) { super.tick(state); for(Player i : queue.keySet()) { process(i); } } @Override public void stop(GameState state) { super.stop(state); queue = new GMap<Player, GList<Notification>>(); ongoing = new GMap<Player, Notification>(); cooldown = new GMap<Player, Integer>(); } public void addPlayer(Player p) { queue.put(p, new GList<Notification>()); cooldown.put(p, 0); } public void queue(Player p, Notification n) { if(n == null) { return; } if(!queue.containsKey(p)) { addPlayer(p); } if(n.isOngoing() != null && n.isOngoing()) { ongoing.put(p, n); } else { if(n.getNoDupe()) { UUID tag = n.getDupeTag(); for(Notification i : queue.get(p)) { if(i.getNoDupe()) { if(i.getDupeTag().equals(tag)) { return; } } } } queue.get(p).add(n); } } public void resetOngoing(Player p) { ongoing.remove(p); } public void removePlayer(Player p) { queue.remove(p); cooldown.remove(p); ongoing.remove(p); } public void process(Player p) { Notification o = ongoing.get(p); if(cooldown.get(p) > 0) { cooldown.put(p, cooldown.get(p) - 1); if(o != null) { o.show(p); } return; } Notification n = nextNotification(p); if(n != null) { if(o != null) { if(canMerge(n, o)) { if(legitimateLine(o.getTitlea())) { n.setTitlea(o.getTitlea()); } if(legitimateLine(o.getTitleb())) { n.setTitleb(o.getTitleb()); } if(legitimateLine(o.getTitlec())) { n.setTitlec(o.getTitlec()); } cooldown.put(p, n.getDelay() + n.getDisplay()); n.show(p); queue.get(p).remove(nextNotification(p)); } else { o.show(p); } } else { cooldown.put(p, n.getDelay() + n.getDisplay()); n.show(p); queue.get(p).remove(nextNotification(p)); } } else if(o != null) { o.show(p); } } public Notification nextNotification(Player p) { for(NotificationPriority i : NotificationPriority.topDown()) { for(Notification j : queue.get(p)) { if(j.getPriority().equals(i)) { return j; } } } return null; } public boolean canMerge(Notification a, Notification b) { return canMerge(a.getTitlea(), b.getTitlea()) && canMerge(a.getTitleb(), b.getTitleb()) && canMerge(a.getTitlec(), b.getTitlec()); } public boolean canMerge(String a, String b) { return (legitimateLine(a) != legitimateLine(b)) || (!legitimateLine(a) && !legitimateLine(b)); } public boolean legitimateLine(String s) { return s != null && !s.equals("") && !s.equals(" "); } }
UTF-8
Java
3,582
java
NotificationHandler.java
Java
[]
null
[]
package com.glacialrush.api.dispatch.notification; import java.util.UUID; import org.bukkit.entity.Player; import com.glacialrush.api.game.Game; import com.glacialrush.api.game.GameState; import com.glacialrush.api.game.GlacialHandler; import com.glacialrush.api.object.GList; import com.glacialrush.api.object.GMap; public class NotificationHandler extends GlacialHandler { private GMap<Player, GList<Notification>> queue; private GMap<Player, Notification> ongoing; private GMap<Player, Integer> cooldown; public NotificationHandler(Game game) { super(game); } @Override public void start(GameState state) { super.start(state); queue = new GMap<Player, GList<Notification>>(); ongoing = new GMap<Player, Notification>(); cooldown = new GMap<Player, Integer>(); } @Override public void tick(GameState state) { super.tick(state); for(Player i : queue.keySet()) { process(i); } } @Override public void stop(GameState state) { super.stop(state); queue = new GMap<Player, GList<Notification>>(); ongoing = new GMap<Player, Notification>(); cooldown = new GMap<Player, Integer>(); } public void addPlayer(Player p) { queue.put(p, new GList<Notification>()); cooldown.put(p, 0); } public void queue(Player p, Notification n) { if(n == null) { return; } if(!queue.containsKey(p)) { addPlayer(p); } if(n.isOngoing() != null && n.isOngoing()) { ongoing.put(p, n); } else { if(n.getNoDupe()) { UUID tag = n.getDupeTag(); for(Notification i : queue.get(p)) { if(i.getNoDupe()) { if(i.getDupeTag().equals(tag)) { return; } } } } queue.get(p).add(n); } } public void resetOngoing(Player p) { ongoing.remove(p); } public void removePlayer(Player p) { queue.remove(p); cooldown.remove(p); ongoing.remove(p); } public void process(Player p) { Notification o = ongoing.get(p); if(cooldown.get(p) > 0) { cooldown.put(p, cooldown.get(p) - 1); if(o != null) { o.show(p); } return; } Notification n = nextNotification(p); if(n != null) { if(o != null) { if(canMerge(n, o)) { if(legitimateLine(o.getTitlea())) { n.setTitlea(o.getTitlea()); } if(legitimateLine(o.getTitleb())) { n.setTitleb(o.getTitleb()); } if(legitimateLine(o.getTitlec())) { n.setTitlec(o.getTitlec()); } cooldown.put(p, n.getDelay() + n.getDisplay()); n.show(p); queue.get(p).remove(nextNotification(p)); } else { o.show(p); } } else { cooldown.put(p, n.getDelay() + n.getDisplay()); n.show(p); queue.get(p).remove(nextNotification(p)); } } else if(o != null) { o.show(p); } } public Notification nextNotification(Player p) { for(NotificationPriority i : NotificationPriority.topDown()) { for(Notification j : queue.get(p)) { if(j.getPriority().equals(i)) { return j; } } } return null; } public boolean canMerge(Notification a, Notification b) { return canMerge(a.getTitlea(), b.getTitlea()) && canMerge(a.getTitleb(), b.getTitleb()) && canMerge(a.getTitlec(), b.getTitlec()); } public boolean canMerge(String a, String b) { return (legitimateLine(a) != legitimateLine(b)) || (!legitimateLine(a) && !legitimateLine(b)); } public boolean legitimateLine(String s) { return s != null && !s.equals("") && !s.equals(" "); } }
3,582
0.604969
0.604132
204
16.558823
19.30563
132
false
false
0
0
0
0
0
0
2.720588
false
false
0
b52c75798e3119f8ee85082fb478f155338ee889
2,499,670,999,339
14755b80b5860af4d46c16b851e84ccf9d12506e
/java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/impl/IVoiceMailsManagerImpl.java
5fea026398b05413ef55137ef328d21e725c5148
[ "MIT" ]
permissive
wolfgangimig/joa
https://github.com/wolfgangimig/joa
cdabaf1386dcc40c53a0279659666e7a83af3d89
a74bbab92eab2e3a7e525728ed318537c2b6a42a
refs/heads/master
2022-04-30T09:24:25.177000
2022-04-24T09:03:42
2022-04-24T09:03:42
26,138,099
12
14
null
null
null
null
null
null
null
null
null
null
null
null
null
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib.impl; import com.wilutions.com.*; @SuppressWarnings("all") @CoClass(guid="{22DBBDEF-636E-9FEA-17E0-98BFFFE05F1B}") public class IVoiceMailsManagerImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib.IVoiceMailsManager { @DeclDISPID(1610743808) public com.wilutions.mslib.uccollaborationlib.PreviousConversationsConnectionState getConnectionState() throws ComException { final Object obj = this._dispatchCall(1610743808,"ConnectionState", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return com.wilutions.mslib.uccollaborationlib.PreviousConversationsConnectionState.valueOf((Integer)obj); } @DeclDISPID(1610743809) public void Connect() throws ComException { this._dispatchCall(1610743809,"Connect", DISPATCH_METHOD,null); } @DeclDISPID(1610743810) public void Reset() throws ComException { this._dispatchCall(1610743810,"Reset", DISPATCH_METHOD,null); } @DeclDISPID(1610743811) public Integer getNewVoiceMailCountSinceLastReset() throws ComException { final Object obj = this._dispatchCall(1610743811,"NewVoiceMailCountSinceLastReset", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return (Integer)obj; } @DeclDISPID(1610743812) public Integer getMaxItems() throws ComException { final Object obj = this._dispatchCall(1610743812,"MaxItems", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return (Integer)obj; } @DeclDISPID(1610743812) public void setMaxItems(final Integer value) throws ComException { assert(value != null); this._dispatchCall(1610743812,"MaxItems", DISPATCH_PROPERTYPUT,value); } @DeclDISPID(1610743814) public com.wilutions.mslib.uccollaborationlib.IAsynchronousOperation GetUnreadVoiceMails(final Object _voiceMailsManagerCallback, final Object _state) throws ComException { assert(_voiceMailsManagerCallback != null); assert(_state != null); final Object obj = this._dispatchCall(1610743814,"GetUnreadVoiceMails", DISPATCH_METHOD,null,_voiceMailsManagerCallback,_state); if (obj == null) return null; return Dispatch.as(obj, com.wilutions.mslib.uccollaborationlib.impl.IAsynchronousOperationImpl.class); } @DeclDISPID(1610743815) public com.wilutions.mslib.uccollaborationlib.IAsynchronousOperation GetAllVoiceMails(final Object _voiceMailsManagerCallback, final Object _state) throws ComException { assert(_voiceMailsManagerCallback != null); assert(_state != null); final Object obj = this._dispatchCall(1610743815,"GetAllVoiceMails", DISPATCH_METHOD,null,_voiceMailsManagerCallback,_state); if (obj == null) return null; return Dispatch.as(obj, com.wilutions.mslib.uccollaborationlib.impl.IAsynchronousOperationImpl.class); } public IVoiceMailsManagerImpl(String progId) throws ComException { super(progId, "{E24C2484-C70D-44AB-8A4E-F1585A17A3E1}"); } protected IVoiceMailsManagerImpl(long ndisp) { super(ndisp); } public String toString() { return "[IVoiceMailsManagerImpl" + super.toString() + "]"; } }
UTF-8
Java
3,189
java
IVoiceMailsManagerImpl.java
Java
[]
null
[]
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib.impl; import com.wilutions.com.*; @SuppressWarnings("all") @CoClass(guid="{22DBBDEF-636E-9FEA-17E0-98BFFFE05F1B}") public class IVoiceMailsManagerImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib.IVoiceMailsManager { @DeclDISPID(1610743808) public com.wilutions.mslib.uccollaborationlib.PreviousConversationsConnectionState getConnectionState() throws ComException { final Object obj = this._dispatchCall(1610743808,"ConnectionState", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return com.wilutions.mslib.uccollaborationlib.PreviousConversationsConnectionState.valueOf((Integer)obj); } @DeclDISPID(1610743809) public void Connect() throws ComException { this._dispatchCall(1610743809,"Connect", DISPATCH_METHOD,null); } @DeclDISPID(1610743810) public void Reset() throws ComException { this._dispatchCall(1610743810,"Reset", DISPATCH_METHOD,null); } @DeclDISPID(1610743811) public Integer getNewVoiceMailCountSinceLastReset() throws ComException { final Object obj = this._dispatchCall(1610743811,"NewVoiceMailCountSinceLastReset", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return (Integer)obj; } @DeclDISPID(1610743812) public Integer getMaxItems() throws ComException { final Object obj = this._dispatchCall(1610743812,"MaxItems", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return (Integer)obj; } @DeclDISPID(1610743812) public void setMaxItems(final Integer value) throws ComException { assert(value != null); this._dispatchCall(1610743812,"MaxItems", DISPATCH_PROPERTYPUT,value); } @DeclDISPID(1610743814) public com.wilutions.mslib.uccollaborationlib.IAsynchronousOperation GetUnreadVoiceMails(final Object _voiceMailsManagerCallback, final Object _state) throws ComException { assert(_voiceMailsManagerCallback != null); assert(_state != null); final Object obj = this._dispatchCall(1610743814,"GetUnreadVoiceMails", DISPATCH_METHOD,null,_voiceMailsManagerCallback,_state); if (obj == null) return null; return Dispatch.as(obj, com.wilutions.mslib.uccollaborationlib.impl.IAsynchronousOperationImpl.class); } @DeclDISPID(1610743815) public com.wilutions.mslib.uccollaborationlib.IAsynchronousOperation GetAllVoiceMails(final Object _voiceMailsManagerCallback, final Object _state) throws ComException { assert(_voiceMailsManagerCallback != null); assert(_state != null); final Object obj = this._dispatchCall(1610743815,"GetAllVoiceMails", DISPATCH_METHOD,null,_voiceMailsManagerCallback,_state); if (obj == null) return null; return Dispatch.as(obj, com.wilutions.mslib.uccollaborationlib.impl.IAsynchronousOperationImpl.class); } public IVoiceMailsManagerImpl(String progId) throws ComException { super(progId, "{E24C2484-C70D-44AB-8A4E-F1585A17A3E1}"); } protected IVoiceMailsManagerImpl(long ndisp) { super(ndisp); } public String toString() { return "[IVoiceMailsManagerImpl" + super.toString() + "]"; } }
3,189
0.755096
0.694262
56
54.94643
48.726063
199
false
false
0
0
0
0
0
0
1.089286
false
false
0
ed25082b8a2249f79a4803711ef9fe7b45fac112
4,011,499,488,395
2966ced7f30434881627130ede93fc25af78b001
/app/src/main/java/com/example/yellowlilyp/buttonex/ButtonEx.java
2129268db8e0be314cb396dc4ca16ed190e1d7f9
[]
no_license
YellowLilyP/ButtonEx_Android
https://github.com/YellowLilyP/ButtonEx_Android
1ada7a7edc3215a9c62228526783ede1d88efd01
592dbaef57b1d1ee64c94939fed2e58c5bb3323c
refs/heads/master
2016-06-15T14:28:47.277000
2016-04-09T15:51:25
2016-04-09T15:51:25
55,820,892
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.yellowlilyp.buttonex; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; /** * Created by YellowLilyP on 2016/04/09. */ public class ButtonEx extends Activity implements View.OnClickListener { private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT; private final static String TAG_MESSAGE = "0"; private final static String TAG_YESNO = "1"; private final static String TAG_TEXT = "2"; private final static String TAG_IMAGE = "3"; // Called when activities start public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); // Generate layouts LinearLayout layout = new LinearLayout(this); layout.setBackgroundColor(Color.WHITE); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); // Generate buttons layout.addView(makeButton("Show message dialog", TAG_MESSAGE)); layout.addView(makeButton("Show Yes/No dialog", TAG_YESNO)); layout.addView(makeButton("Show input text dialog", TAG_TEXT)); layout.addView(makeImageButton(res2bmp(this,R.drawable.sample), TAG_IMAGE)); } // Generate buttons private Button makeButton(String text, String tag) { Button button = new Button(this); button.setText(text); button.setTag(tag); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return button; } // Generate image buttons private ImageButton makeImageButton(Bitmap bmp, String tag) { ImageButton imageButton = new ImageButton(this); imageButton.setTag(tag); imageButton.setOnClickListener(this); imageButton.setImageBitmap(bmp); imageButton.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return imageButton; } // Convert resources to bitmaps public Bitmap res2bmp(Context context, int resID) { return BitmapFactory.decodeResource(context.getResources(), resID); } // Called if buttons pressed public void onClick(View view) { String tag = (String)view.getTag(); if (TAG_MESSAGE.equals(tag)) { MessageDialog.show(this, "Message dialog", "Pressed button"); } else if (TAG_YESNO.equals(tag)) { YesNoDialog.show(this, "Yes/No dialog", "Selected Yes/No"); } else if (TAG_TEXT.equals(tag)) { TextDialog.show(this, "Text dialog", "Input text"); } else if (TAG_IMAGE.equals(tag)) { MessageDialog.show(this, "", "Pressed image button"); } } // Define message dialogs public static class MessageDialog extends DialogFragment { // Show message dialogs public static void show(Activity activity, String title, String text) { MessageDialog f = new MessageDialog(); Bundle args = new Bundle(); args.putString("Title", title); args.putString("Text", text); f.setArguments(args); f.show(activity.getFragmentManager(), "MessageDialog"); } // Generate message dialogs @Override public Dialog onCreateDialog(Bundle bundle) { AlertDialog.Builder ad = new AlertDialog.Builder(getActivity()); ad.setTitle(getArguments().getString("Title")); ad.setMessage(getArguments().getString("Text")); ad.setPositiveButton("OK", null); return ad.create(); } } // Define yes/no dialogs public static class YesNoDialog extends DialogFragment { // Show yes/no dialogs public static void show(Activity activity, String title, String text) { YesNoDialog f = new YesNoDialog(); Bundle args = new Bundle(); args.putString("Title", title); args.putString("Text", text); f.setArguments(args); f.show(activity.getFragmentManager(), "YesNoDialog"); } // Generate yes/no dialogs @Override public Dialog onCreateDialog(Bundle bundle) { // Generate listener DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { // Called if dialog button pressed public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { MessageDialog.show(getActivity(), "", "YES"); } else if (which == DialogInterface.BUTTON_NEGATIVE) { MessageDialog.show(getActivity(), "", "NO"); } } }; // Generate yes/no dialogs AlertDialog.Builder ad = new AlertDialog.Builder(getActivity()); ad.setTitle(getArguments().getString("Title")); ad.setMessage(getArguments().getString("Text")); ad.setPositiveButton("Yes", listener); ad.setNegativeButton("No", listener); return ad.create(); } } // Define input text dialogs public static class TextDialog extends DialogFragment { private EditText editText; // Show input text dialogs public static void show(Activity activity, String title, String text) { TextDialog f = new TextDialog(); Bundle args = new Bundle(); args.putString("Title", title); args.putString("Text", text); f.setArguments(args); f.show(activity.getFragmentManager(), "TextDialog"); } // Generate input text dialogs @Override public Dialog onCreateDialog(Bundle bundle) { // Generate listener DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { // Called if dialog button pressed public void onClick(DialogInterface dialog, int which) { MessageDialog.show(getActivity(), "", editText.getText().toString()); } }; // Generate edit text editText = new EditText(getActivity()); // Generate input text dialogs AlertDialog.Builder ad = new AlertDialog.Builder(getActivity()); ad.setTitle(getArguments().getString("Title")); ad.setMessage(getArguments().getString("Text")); ad.setView(editText); ad.setPositiveButton("OK", listener); // Return states of fragment if (bundle != null) { editText.setText(bundle.getString("EditText", "")); } return ad.create(); } // Save states of fragment @Override public void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putString("EditText", editText.getText().toString()); } } }
UTF-8
Java
7,467
java
ButtonEx.java
Java
[ { "context": "rt android.widget.LinearLayout;\n\n/**\n * Created by YellowLilyP on 2016/04/09.\n */\npublic class ButtonEx extends ", "end": 582, "score": 0.999186635017395, "start": 571, "tag": "USERNAME", "value": "YellowLilyP" } ]
null
[]
package com.example.yellowlilyp.buttonex; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; /** * Created by YellowLilyP on 2016/04/09. */ public class ButtonEx extends Activity implements View.OnClickListener { private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT; private final static String TAG_MESSAGE = "0"; private final static String TAG_YESNO = "1"; private final static String TAG_TEXT = "2"; private final static String TAG_IMAGE = "3"; // Called when activities start public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); // Generate layouts LinearLayout layout = new LinearLayout(this); layout.setBackgroundColor(Color.WHITE); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); // Generate buttons layout.addView(makeButton("Show message dialog", TAG_MESSAGE)); layout.addView(makeButton("Show Yes/No dialog", TAG_YESNO)); layout.addView(makeButton("Show input text dialog", TAG_TEXT)); layout.addView(makeImageButton(res2bmp(this,R.drawable.sample), TAG_IMAGE)); } // Generate buttons private Button makeButton(String text, String tag) { Button button = new Button(this); button.setText(text); button.setTag(tag); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return button; } // Generate image buttons private ImageButton makeImageButton(Bitmap bmp, String tag) { ImageButton imageButton = new ImageButton(this); imageButton.setTag(tag); imageButton.setOnClickListener(this); imageButton.setImageBitmap(bmp); imageButton.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return imageButton; } // Convert resources to bitmaps public Bitmap res2bmp(Context context, int resID) { return BitmapFactory.decodeResource(context.getResources(), resID); } // Called if buttons pressed public void onClick(View view) { String tag = (String)view.getTag(); if (TAG_MESSAGE.equals(tag)) { MessageDialog.show(this, "Message dialog", "Pressed button"); } else if (TAG_YESNO.equals(tag)) { YesNoDialog.show(this, "Yes/No dialog", "Selected Yes/No"); } else if (TAG_TEXT.equals(tag)) { TextDialog.show(this, "Text dialog", "Input text"); } else if (TAG_IMAGE.equals(tag)) { MessageDialog.show(this, "", "Pressed image button"); } } // Define message dialogs public static class MessageDialog extends DialogFragment { // Show message dialogs public static void show(Activity activity, String title, String text) { MessageDialog f = new MessageDialog(); Bundle args = new Bundle(); args.putString("Title", title); args.putString("Text", text); f.setArguments(args); f.show(activity.getFragmentManager(), "MessageDialog"); } // Generate message dialogs @Override public Dialog onCreateDialog(Bundle bundle) { AlertDialog.Builder ad = new AlertDialog.Builder(getActivity()); ad.setTitle(getArguments().getString("Title")); ad.setMessage(getArguments().getString("Text")); ad.setPositiveButton("OK", null); return ad.create(); } } // Define yes/no dialogs public static class YesNoDialog extends DialogFragment { // Show yes/no dialogs public static void show(Activity activity, String title, String text) { YesNoDialog f = new YesNoDialog(); Bundle args = new Bundle(); args.putString("Title", title); args.putString("Text", text); f.setArguments(args); f.show(activity.getFragmentManager(), "YesNoDialog"); } // Generate yes/no dialogs @Override public Dialog onCreateDialog(Bundle bundle) { // Generate listener DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { // Called if dialog button pressed public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { MessageDialog.show(getActivity(), "", "YES"); } else if (which == DialogInterface.BUTTON_NEGATIVE) { MessageDialog.show(getActivity(), "", "NO"); } } }; // Generate yes/no dialogs AlertDialog.Builder ad = new AlertDialog.Builder(getActivity()); ad.setTitle(getArguments().getString("Title")); ad.setMessage(getArguments().getString("Text")); ad.setPositiveButton("Yes", listener); ad.setNegativeButton("No", listener); return ad.create(); } } // Define input text dialogs public static class TextDialog extends DialogFragment { private EditText editText; // Show input text dialogs public static void show(Activity activity, String title, String text) { TextDialog f = new TextDialog(); Bundle args = new Bundle(); args.putString("Title", title); args.putString("Text", text); f.setArguments(args); f.show(activity.getFragmentManager(), "TextDialog"); } // Generate input text dialogs @Override public Dialog onCreateDialog(Bundle bundle) { // Generate listener DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { // Called if dialog button pressed public void onClick(DialogInterface dialog, int which) { MessageDialog.show(getActivity(), "", editText.getText().toString()); } }; // Generate edit text editText = new EditText(getActivity()); // Generate input text dialogs AlertDialog.Builder ad = new AlertDialog.Builder(getActivity()); ad.setTitle(getArguments().getString("Title")); ad.setMessage(getArguments().getString("Text")); ad.setView(editText); ad.setPositiveButton("OK", listener); // Return states of fragment if (bundle != null) { editText.setText(bundle.getString("EditText", "")); } return ad.create(); } // Save states of fragment @Override public void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putString("EditText", editText.getText().toString()); } } }
7,467
0.619124
0.617249
197
36.903553
23.860548
94
false
false
0
0
0
0
0
0
0.725888
false
false
0
f1068d2ceea3345247d95f6d659cdc6e70e0f261
17,188,459,160,730
1b7e754e4ce5c9b3a40e3d71941b1843f017fcc4
/src/backend/model/Drawable.java
a354b497199095684877516364b95c23c3cf569f
[]
no_license
JuanOriana/Final-POO
https://github.com/JuanOriana/Final-POO
f8b5c97a4905f5580a75a36560afbe5bb3690e29
6bad05fd36ae41bc96844299a176240de68ed92a
refs/heads/master
2022-11-16T14:08:12.288000
2020-07-11T22:09:18
2020-07-11T22:09:18
276,684,076
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package backend.model; import javafx.scene.canvas.GraphicsContext; /** * Interfaz que representa todos los elementos que saben representarse en un * GraphicContent */ public interface Drawable { void draw(GraphicsContext gc); }
UTF-8
Java
240
java
Drawable.java
Java
[]
null
[]
package backend.model; import javafx.scene.canvas.GraphicsContext; /** * Interfaz que representa todos los elementos que saben representarse en un * GraphicContent */ public interface Drawable { void draw(GraphicsContext gc); }
240
0.758333
0.758333
12
19
22.653183
77
false
false
0
0
0
0
0
0
0.25
false
false
0
eade6ba504ca64643b9cdbc60e2ecff447d61692
17,188,459,160,615
249ade123e85518ee31fba1e42ad18f28614ecfd
/src/main/java/ru/litkovets/service/impl/EventServiceImpl.java
bb006bb726f9d5bb126b4454ea2f3b80830352ad
[]
no_license
AlekseyLitkovets/art
https://github.com/AlekseyLitkovets/art
9c9e5bbc80b0466d6daf3029a7e7d99665a11ae2
f96dd38b4de9bbfd64f067b6fbb137f800ff6cbf
refs/heads/master
2021-01-11T22:55:31.392000
2017-01-23T18:54:17
2017-01-23T18:54:17
78,514,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.litkovets.service.impl; import ru.litkovets.db.dao.intr.EventDao; import ru.litkovets.db.exception.DaoException; import ru.litkovets.model.event.JoinEvent; import ru.litkovets.service.exception.ServiceException; import ru.litkovets.service.intr.EventService; import javax.inject.Inject; import java.util.ArrayList; public class EventServiceImpl implements EventService { private final EventDao eventDao; @Inject public EventServiceImpl(EventDao eventDao) { this.eventDao = eventDao; } @Override public ArrayList<JoinEvent> getEventsByMuseumId(long userId, long museumId) throws ServiceException { try { return eventDao.getEventsByMuseumId(userId, museumId); } catch (DaoException e) { throw new ServiceException("Problem with database " + "in EventServiceImpl class, getEventsByMuseumId method", e); } } @Override public ArrayList<JoinEvent> getEventsByUserId(long userId) throws ServiceException { try { return eventDao.getEventsByUserId(userId); } catch (DaoException e) { throw new ServiceException("Problem with database " + "in EventServiceImpl class, getEventsByMuseumId method", e); } } }
UTF-8
Java
1,289
java
EventServiceImpl.java
Java
[]
null
[]
package ru.litkovets.service.impl; import ru.litkovets.db.dao.intr.EventDao; import ru.litkovets.db.exception.DaoException; import ru.litkovets.model.event.JoinEvent; import ru.litkovets.service.exception.ServiceException; import ru.litkovets.service.intr.EventService; import javax.inject.Inject; import java.util.ArrayList; public class EventServiceImpl implements EventService { private final EventDao eventDao; @Inject public EventServiceImpl(EventDao eventDao) { this.eventDao = eventDao; } @Override public ArrayList<JoinEvent> getEventsByMuseumId(long userId, long museumId) throws ServiceException { try { return eventDao.getEventsByMuseumId(userId, museumId); } catch (DaoException e) { throw new ServiceException("Problem with database " + "in EventServiceImpl class, getEventsByMuseumId method", e); } } @Override public ArrayList<JoinEvent> getEventsByUserId(long userId) throws ServiceException { try { return eventDao.getEventsByUserId(userId); } catch (DaoException e) { throw new ServiceException("Problem with database " + "in EventServiceImpl class, getEventsByMuseumId method", e); } } }
1,289
0.698991
0.698991
39
32.051281
27.961466
105
false
false
0
0
0
0
0
0
0.512821
false
false
0
31a02c75dac5bea6eca05262717768dcdd2f7ff8
12,412,455,519,445
950e2c86a56803351de3395b964a1be3e8b1064f
/guli_parent/service/service_edu/src/main/java/com/atguigu/eduservice/mapper/EduCommentMapper.java
011a45d4e850c902436d2d30ed60cc3afb2903e4
[ "MIT" ]
permissive
loong-son/GrainCollege
https://github.com/loong-son/GrainCollege
4ffca4bf727467f81846d9958231ddbc4346e517
d27dd27e5b98c5dcba2daa8eee75d38992214eea
refs/heads/main
2023-08-19T00:05:14.307000
2021-10-09T03:54:34
2021-10-09T03:54:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.eduservice.mapper; import com.atguigu.eduservice.entity.EduComment; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @author chenglongsheng * @create 2021-09-29 13:29 */ public interface EduCommentMapper extends BaseMapper<EduComment> { }
UTF-8
Java
277
java
EduCommentMapper.java
Java
[ { "context": "ybatisplus.core.mapper.BaseMapper;\n\n/**\n * @author chenglongsheng\n * @create 2021-09-29 13:29\n */\npublic interface ", "end": 175, "score": 0.9893083572387695, "start": 161, "tag": "USERNAME", "value": "chenglongsheng" } ]
null
[]
package com.atguigu.eduservice.mapper; import com.atguigu.eduservice.entity.EduComment; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @author chenglongsheng * @create 2021-09-29 13:29 */ public interface EduCommentMapper extends BaseMapper<EduComment> { }
277
0.790614
0.747292
11
24.181818
23.490107
66
false
false
0
0
0
0
0
0
0.272727
false
false
0
b4e5e379d6df024ad7d4c6832ebaff46fa59d02d
12,412,455,521,780
4b496dfb36b00c21ecab25d1c4db020c8785709e
/src/com/grupo5/Interfaces/Menu/intUsuario/CRUD_user.java
eb5d7dd644e61b1c7b3fe8d444a4fecd456fdd20
[]
no_license
Grupo5IPC/IPC1_PROYECTO1_G5
https://github.com/Grupo5IPC/IPC1_PROYECTO1_G5
759ad0993cef070b67c583295ab3007785752164
e9ea4e8732080b0d8ea350c1c88948b7d5917f3c
refs/heads/master
2023-06-10T22:54:37.559000
2021-07-05T22:04:24
2021-07-05T22:04:24
376,975,691
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.grupo5.Interfaces.Menu.intUsuario; import com.grupo5.Clientes.Gestor_cliente; import com.grupo5.Facturas.Gestor_Factura; import com.grupo5.Fuentes.Fuentes; import com.grupo5.Gestor_restaurante; import com.grupo5.Interfaces.Menu.intUsuario.Dialogs.*; import com.grupo5.Interfaces.Menu.intUsuario.Dialogs.updateUser; import com.grupo5.Interfaces.Menu.intUsuario.Renders.HeaderRenderer; import com.grupo5.Interfaces.Menu.intUsuario.Renders.Render; import com.grupo5.Log; import com.grupo5.Logdeacciones; import com.grupo5.Productos.Gestor_Producto; import com.grupo5.Serializacion; import com.grupo5.Usuarios.Gestor_usuario; import com.grupo5.Usuarios.Usuario; import com.sun.istack.internal.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; public class CRUD_user extends JPanel { public Color fondo = new Color(24, 30, 54); public Color azul = new Color(42, 52, 67); public Color texto = new Color(0, 126, 249); public JTable table; JButton eliminar; public JButton nuevo; JButton modificar; DefaultTableModel model; public static Log log; public static Logdeacciones logdeacciones; public static Gestor_restaurante Nuevo; public static Gestor_usuario usuario; public static Gestor_Producto producto; public static Gestor_Factura factura; public static Gestor_cliente cliente; public Color textoSecundario = new Color(158, 161, 176); public CRUD_user(Gestor_usuario usuarios, Gestor_Producto productos, Gestor_Factura facturas, Gestor_cliente clientes, Gestor_restaurante nuev, Log log, Logdeacciones logdeacciones) { this.log = log; this.logdeacciones = logdeacciones; Nuevo = nuev; usuario = usuarios; producto = productos; factura = facturas; cliente = clientes; JPanel aux = new JPanel(); Fuentes fuente = new Fuentes(); setSize(898, 300); setBounds(0, 0, getWidth(), getHeight()); setBackground(azul); setLayout(null); setForeground(textoSecundario); usuario.print_usu(); ArrayList<Usuario> data = usuario.getArray(); Object[] header = new Object[]{" Usuario", " Password", "", ""}; Object matriz[][] = new Object[data.size()][4]; modificar = new JButton("Modificar"); modificar.setName("m"); modificar.setForeground(textoSecundario); modificar.setBorder(null); modificar.setBackground(azul); modificar.setBounds(0, 0, 30, 30); modificar.setIcon(getIcon2("iconos\\update.png", modificar)); modificar.setCursor(new Cursor(Cursor.HAND_CURSOR)); modificar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); eliminar = new JButton("Eliminar"); eliminar.setName("e"); eliminar.setForeground(textoSecundario); eliminar.setBorder(null); eliminar.setBackground(azul); eliminar.setBounds(0, 0, 30, 30); eliminar.setForeground(textoSecundario); eliminar.setIcon(getIcon2("iconos\\delete2.png", modificar)); eliminar.setCursor(new Cursor(Cursor.HAND_CURSOR)); eliminar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); for (int i = 0; i < data.size(); i++) { matriz[i][0] = data.get(i).getUsername(); matriz[i][1] = data.get(i).getPassword(); matriz[i][2] = modificar; matriz[i][3] = eliminar; } model = new DefaultTableModel(matriz, header) { public boolean isCellEditable(int row, int column) { return false; } }; table = new JTable(model); table.setForeground(textoSecundario); table.getTableHeader().setForeground(textoSecundario); table.getTableHeader().setDefaultRenderer(new HeaderRenderer(table)); table.setDefaultRenderer(Object.class, new Render()); table.setFocusable(false); table.setBackground(azul); table.setIntercellSpacing(new Dimension(0, 1)); table.setRowHeight(50); table.setSelectionBackground(texto); table.setShowVerticalLines(false); table.setBorder(BorderFactory.createEmptyBorder()); table.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); table.getTableHeader().setFont(fuente.fuente(fuente.OpensansBold, 0, 17)); table.getTableHeader().setOpaque(true); table.getTableHeader().setBorder(BorderFactory.createEmptyBorder()); table.getTableHeader().setBackground(azul); table.getTableHeader().setResizingAllowed(false); table.setShowHorizontalLines(true); table.setGridColor(texto); UIManager.getDefaults().put("TableHeader.cellBorder", BorderFactory.createEmptyBorder(0, 0, 0, 0)); //table.getColumnModel().getColumn(2).setCellRenderer(new ButtonRenderer()); table.setCursor(new Cursor(Cursor.HAND_CURSOR)); table.setBounds(80, 100, 400, 400); table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int col = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY() / table.getRowHeight(); if (row < table.getRowCount() && row >= 0 && col < table.getColumnCount() && col > 0) { Object valor = table.getValueAt(row, col); if (valor instanceof JButton) { ((JButton) valor).doClick(); JButton btn = (JButton) valor; if (btn.getName().equals("m")) { System.out.println(row); //System.out.println("Modificar"); String usuarios2 = (String) table.getValueAt(row, 0); System.out.println(usuarios2); openDialog(usuarios2); Serializacion serializacion = new Serializacion(); serializacion.serializar(Nuevo,usuarios,productos,clientes,facturas); Refresh(); } if (btn.getName().equals("e")) { String usuarios2 = (String) table.getValueAt(row, 0); System.out.println(usuarios2); int opcion = JOptionPane.showConfirmDialog(table, "¿Esta seguro de elimnar el usuario: "+ usuarios+"?","Confirmar", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE ); if (opcion == JOptionPane.YES_OPTION){ usuario.eliminarUsuario((String) table.getValueAt(row, 0)); model.removeRow(row); usuario.print_usu(); logdeacciones.addlog(usuario.getSesion()+": Elimino el usuario +"+usuarios2); Serializacion serializacion = new Serializacion(); serializacion.serializar(Nuevo,usuarios,productos,clientes,facturas); Refresh(); } if (opcion == JOptionPane.NO_OPTION){ } } } } } }); JScrollPane pane = new JScrollPane(); pane.setViewportView(table); pane.setBackground(azul); pane.setOpaque(true); pane.setBorder(BorderFactory.createEmptyBorder()); pane.getViewport().setBackground(azul); pane.setBounds(150, 100, 600, 400); add(pane); nuevo = new JButton("Nuevo usuario"); nuevo.setForeground(textoSecundario); nuevo.setBackground(azul); nuevo.setBounds(600, 520, 140, 45); nuevo.setFont(fuente.fuente(fuente.RobotoBold,0,16)); nuevo.setBorder(BorderFactory.createLineBorder(textoSecundario)); nuevo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println("si"); addUser a = new addUser(usuarios,productos,facturas,clientes,Nuevo,true,log,logdeacciones); a.setVisible(true); Serializacion serializacion = new Serializacion(); serializacion.serializar(Nuevo,usuarios,productos,clientes,facturas); //a.setBounds((int)table.getBounds().getX()-20, table.getY(), 600,400 ); //System.out.println(a.getSize().getWidth()); Refresh(); } @Override public void mouseEntered(MouseEvent e) { nuevo.setBackground(fondo); nuevo.setForeground(texto); nuevo.setBorder(BorderFactory.createLineBorder(texto)); nuevo.setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { nuevo.setBackground(azul); nuevo.setForeground(textoSecundario); nuevo.setBorder(BorderFactory.createLineBorder(textoSecundario)); nuevo.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); add(nuevo); } ImageIcon getIcon2(String ruta, @NotNull JButton label) { ImageIcon icon = new ImageIcon(ruta); Image img = icon.getImage(); Image imgs = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH); ImageIcon scale = new ImageIcon(imgs); return scale; } void openDialog(String username) { updateUser c = new updateUser(usuario,producto,factura,cliente,Nuevo,true,username,log,logdeacciones); c.setVisible(true); } void Refresh(){ Fuentes fuente = new Fuentes(); ArrayList<Usuario> data = usuario.getArray(); Object[] header = new Object[]{" Usuario", " Password", "", ""}; Object matriz[][] = new Object[data.size()][4]; modificar = new JButton("Modificar"); modificar.setName("m"); modificar.setForeground(textoSecundario); modificar.setBorder(null); modificar.setBackground(azul); modificar.setBounds(0, 0, 30, 30); modificar.setIcon(getIcon2("iconos\\update.png", modificar)); modificar.setCursor(new Cursor(Cursor.HAND_CURSOR)); modificar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); eliminar = new JButton("Eliminar"); eliminar.setName("e"); eliminar.setForeground(textoSecundario); eliminar.setBorder(null); eliminar.setBackground(azul); eliminar.setBounds(0, 0, 30, 30); eliminar.setForeground(textoSecundario); eliminar.setIcon(getIcon2("iconos\\delete2.png", modificar)); eliminar.setCursor(new Cursor(Cursor.HAND_CURSOR)); eliminar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); for (int i = 0; i < data.size(); i++) { matriz[i][0] = data.get(i).getUsername(); matriz[i][1] = data.get(i).getPassword(); matriz[i][2] = modificar; matriz[i][3] = eliminar; } model = new DefaultTableModel(matriz, header) { public boolean isCellEditable(int row, int column) { return false; } }; table.setModel(model); } }
UTF-8
Java
11,668
java
CRUD_user.java
Java
[]
null
[]
package com.grupo5.Interfaces.Menu.intUsuario; import com.grupo5.Clientes.Gestor_cliente; import com.grupo5.Facturas.Gestor_Factura; import com.grupo5.Fuentes.Fuentes; import com.grupo5.Gestor_restaurante; import com.grupo5.Interfaces.Menu.intUsuario.Dialogs.*; import com.grupo5.Interfaces.Menu.intUsuario.Dialogs.updateUser; import com.grupo5.Interfaces.Menu.intUsuario.Renders.HeaderRenderer; import com.grupo5.Interfaces.Menu.intUsuario.Renders.Render; import com.grupo5.Log; import com.grupo5.Logdeacciones; import com.grupo5.Productos.Gestor_Producto; import com.grupo5.Serializacion; import com.grupo5.Usuarios.Gestor_usuario; import com.grupo5.Usuarios.Usuario; import com.sun.istack.internal.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; public class CRUD_user extends JPanel { public Color fondo = new Color(24, 30, 54); public Color azul = new Color(42, 52, 67); public Color texto = new Color(0, 126, 249); public JTable table; JButton eliminar; public JButton nuevo; JButton modificar; DefaultTableModel model; public static Log log; public static Logdeacciones logdeacciones; public static Gestor_restaurante Nuevo; public static Gestor_usuario usuario; public static Gestor_Producto producto; public static Gestor_Factura factura; public static Gestor_cliente cliente; public Color textoSecundario = new Color(158, 161, 176); public CRUD_user(Gestor_usuario usuarios, Gestor_Producto productos, Gestor_Factura facturas, Gestor_cliente clientes, Gestor_restaurante nuev, Log log, Logdeacciones logdeacciones) { this.log = log; this.logdeacciones = logdeacciones; Nuevo = nuev; usuario = usuarios; producto = productos; factura = facturas; cliente = clientes; JPanel aux = new JPanel(); Fuentes fuente = new Fuentes(); setSize(898, 300); setBounds(0, 0, getWidth(), getHeight()); setBackground(azul); setLayout(null); setForeground(textoSecundario); usuario.print_usu(); ArrayList<Usuario> data = usuario.getArray(); Object[] header = new Object[]{" Usuario", " Password", "", ""}; Object matriz[][] = new Object[data.size()][4]; modificar = new JButton("Modificar"); modificar.setName("m"); modificar.setForeground(textoSecundario); modificar.setBorder(null); modificar.setBackground(azul); modificar.setBounds(0, 0, 30, 30); modificar.setIcon(getIcon2("iconos\\update.png", modificar)); modificar.setCursor(new Cursor(Cursor.HAND_CURSOR)); modificar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); eliminar = new JButton("Eliminar"); eliminar.setName("e"); eliminar.setForeground(textoSecundario); eliminar.setBorder(null); eliminar.setBackground(azul); eliminar.setBounds(0, 0, 30, 30); eliminar.setForeground(textoSecundario); eliminar.setIcon(getIcon2("iconos\\delete2.png", modificar)); eliminar.setCursor(new Cursor(Cursor.HAND_CURSOR)); eliminar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); for (int i = 0; i < data.size(); i++) { matriz[i][0] = data.get(i).getUsername(); matriz[i][1] = data.get(i).getPassword(); matriz[i][2] = modificar; matriz[i][3] = eliminar; } model = new DefaultTableModel(matriz, header) { public boolean isCellEditable(int row, int column) { return false; } }; table = new JTable(model); table.setForeground(textoSecundario); table.getTableHeader().setForeground(textoSecundario); table.getTableHeader().setDefaultRenderer(new HeaderRenderer(table)); table.setDefaultRenderer(Object.class, new Render()); table.setFocusable(false); table.setBackground(azul); table.setIntercellSpacing(new Dimension(0, 1)); table.setRowHeight(50); table.setSelectionBackground(texto); table.setShowVerticalLines(false); table.setBorder(BorderFactory.createEmptyBorder()); table.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); table.getTableHeader().setFont(fuente.fuente(fuente.OpensansBold, 0, 17)); table.getTableHeader().setOpaque(true); table.getTableHeader().setBorder(BorderFactory.createEmptyBorder()); table.getTableHeader().setBackground(azul); table.getTableHeader().setResizingAllowed(false); table.setShowHorizontalLines(true); table.setGridColor(texto); UIManager.getDefaults().put("TableHeader.cellBorder", BorderFactory.createEmptyBorder(0, 0, 0, 0)); //table.getColumnModel().getColumn(2).setCellRenderer(new ButtonRenderer()); table.setCursor(new Cursor(Cursor.HAND_CURSOR)); table.setBounds(80, 100, 400, 400); table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int col = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY() / table.getRowHeight(); if (row < table.getRowCount() && row >= 0 && col < table.getColumnCount() && col > 0) { Object valor = table.getValueAt(row, col); if (valor instanceof JButton) { ((JButton) valor).doClick(); JButton btn = (JButton) valor; if (btn.getName().equals("m")) { System.out.println(row); //System.out.println("Modificar"); String usuarios2 = (String) table.getValueAt(row, 0); System.out.println(usuarios2); openDialog(usuarios2); Serializacion serializacion = new Serializacion(); serializacion.serializar(Nuevo,usuarios,productos,clientes,facturas); Refresh(); } if (btn.getName().equals("e")) { String usuarios2 = (String) table.getValueAt(row, 0); System.out.println(usuarios2); int opcion = JOptionPane.showConfirmDialog(table, "¿Esta seguro de elimnar el usuario: "+ usuarios+"?","Confirmar", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE ); if (opcion == JOptionPane.YES_OPTION){ usuario.eliminarUsuario((String) table.getValueAt(row, 0)); model.removeRow(row); usuario.print_usu(); logdeacciones.addlog(usuario.getSesion()+": Elimino el usuario +"+usuarios2); Serializacion serializacion = new Serializacion(); serializacion.serializar(Nuevo,usuarios,productos,clientes,facturas); Refresh(); } if (opcion == JOptionPane.NO_OPTION){ } } } } } }); JScrollPane pane = new JScrollPane(); pane.setViewportView(table); pane.setBackground(azul); pane.setOpaque(true); pane.setBorder(BorderFactory.createEmptyBorder()); pane.getViewport().setBackground(azul); pane.setBounds(150, 100, 600, 400); add(pane); nuevo = new JButton("Nuevo usuario"); nuevo.setForeground(textoSecundario); nuevo.setBackground(azul); nuevo.setBounds(600, 520, 140, 45); nuevo.setFont(fuente.fuente(fuente.RobotoBold,0,16)); nuevo.setBorder(BorderFactory.createLineBorder(textoSecundario)); nuevo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println("si"); addUser a = new addUser(usuarios,productos,facturas,clientes,Nuevo,true,log,logdeacciones); a.setVisible(true); Serializacion serializacion = new Serializacion(); serializacion.serializar(Nuevo,usuarios,productos,clientes,facturas); //a.setBounds((int)table.getBounds().getX()-20, table.getY(), 600,400 ); //System.out.println(a.getSize().getWidth()); Refresh(); } @Override public void mouseEntered(MouseEvent e) { nuevo.setBackground(fondo); nuevo.setForeground(texto); nuevo.setBorder(BorderFactory.createLineBorder(texto)); nuevo.setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { nuevo.setBackground(azul); nuevo.setForeground(textoSecundario); nuevo.setBorder(BorderFactory.createLineBorder(textoSecundario)); nuevo.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); add(nuevo); } ImageIcon getIcon2(String ruta, @NotNull JButton label) { ImageIcon icon = new ImageIcon(ruta); Image img = icon.getImage(); Image imgs = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH); ImageIcon scale = new ImageIcon(imgs); return scale; } void openDialog(String username) { updateUser c = new updateUser(usuario,producto,factura,cliente,Nuevo,true,username,log,logdeacciones); c.setVisible(true); } void Refresh(){ Fuentes fuente = new Fuentes(); ArrayList<Usuario> data = usuario.getArray(); Object[] header = new Object[]{" Usuario", " Password", "", ""}; Object matriz[][] = new Object[data.size()][4]; modificar = new JButton("Modificar"); modificar.setName("m"); modificar.setForeground(textoSecundario); modificar.setBorder(null); modificar.setBackground(azul); modificar.setBounds(0, 0, 30, 30); modificar.setIcon(getIcon2("iconos\\update.png", modificar)); modificar.setCursor(new Cursor(Cursor.HAND_CURSOR)); modificar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); eliminar = new JButton("Eliminar"); eliminar.setName("e"); eliminar.setForeground(textoSecundario); eliminar.setBorder(null); eliminar.setBackground(azul); eliminar.setBounds(0, 0, 30, 30); eliminar.setForeground(textoSecundario); eliminar.setIcon(getIcon2("iconos\\delete2.png", modificar)); eliminar.setCursor(new Cursor(Cursor.HAND_CURSOR)); eliminar.setFont(fuente.fuente(fuente.OpensansBold, 0, 13)); for (int i = 0; i < data.size(); i++) { matriz[i][0] = data.get(i).getUsername(); matriz[i][1] = data.get(i).getPassword(); matriz[i][2] = modificar; matriz[i][3] = eliminar; } model = new DefaultTableModel(matriz, header) { public boolean isCellEditable(int row, int column) { return false; } }; table.setModel(model); } }
11,668
0.601869
0.586698
293
38.819111
28.930151
209
false
false
0
0
0
0
0
0
1.078498
false
false
0
b28e447e1d7865f4e039ab789baef3e1425c410a
13,288,628,849,792
f0cd7060b9c85405ca4807d6aa626e47d9882f65
/src/main/java/jp/tldemo/constants/Constants.java
35ba37b2ee7dd5b870a9ed55883c1b9fe92f1cea
[]
no_license
TiraTom/TLdemo
https://github.com/TiraTom/TLdemo
cded75aaa76a79f71cae172e762c7e0432e9492c
e6e07dbc7ea96aa14bc00b4ec2000d31c65cdc21
refs/heads/master
2021-06-21T11:38:12.927000
2019-11-22T13:20:26
2019-11-22T13:20:26
209,930,225
0
0
null
false
2021-04-26T19:33:32
2019-09-21T05:29:19
2019-11-22T13:20:37
2021-04-26T19:33:32
66
0
0
9
Java
false
false
package jp.tldemo.constants; public class Constants { // インスタンス作成抑止用 private Constants() {} public static final double COST_OVER_BORDER = 0.3; public static final int ROULETTE_CANDIDATE_NUMBER = 8; public static final String DB_ERROR_MESSAGE = "ごめんなさい。DBエラーが発生しました。"; public static final String SAVE_SUCCESS_MESSAGE = "保存しました。"; public static final String SERACH_ACTIVITY_FAILED_MESSAGE = "ごめんなさい。良さそうな暇つぶしが見つかりませんでした。"; public static final String DELETE_SUCCESS_MESSAGE = "削除しました。"; public static final String ACTIVITY_NOT_FOUND_MESSAGE = "該当する暇つぶしが見つかりませんでした。"; public static final String ACTIVITY_SEARCH_CONDITION_INVALID = "整数値を入力してくれたら、おすすめ暇つぶしを提案します"; public static final String VALIDATION_ERROR = "入力値が適切ではありません"; public static final String VALIDATION_ERROR_TITLE_LENGTH = "タイトルは1~30文字の長さで入力して下さい"; public static final String VALIDATION_ERROR_COST = "費用は0~999,999,999の範囲で入力して下さい"; }
UTF-8
Java
1,242
java
Constants.java
Java
[]
null
[]
package jp.tldemo.constants; public class Constants { // インスタンス作成抑止用 private Constants() {} public static final double COST_OVER_BORDER = 0.3; public static final int ROULETTE_CANDIDATE_NUMBER = 8; public static final String DB_ERROR_MESSAGE = "ごめんなさい。DBエラーが発生しました。"; public static final String SAVE_SUCCESS_MESSAGE = "保存しました。"; public static final String SERACH_ACTIVITY_FAILED_MESSAGE = "ごめんなさい。良さそうな暇つぶしが見つかりませんでした。"; public static final String DELETE_SUCCESS_MESSAGE = "削除しました。"; public static final String ACTIVITY_NOT_FOUND_MESSAGE = "該当する暇つぶしが見つかりませんでした。"; public static final String ACTIVITY_SEARCH_CONDITION_INVALID = "整数値を入力してくれたら、おすすめ暇つぶしを提案します"; public static final String VALIDATION_ERROR = "入力値が適切ではありません"; public static final String VALIDATION_ERROR_TITLE_LENGTH = "タイトルは1~30文字の長さで入力して下さい"; public static final String VALIDATION_ERROR_COST = "費用は0~999,999,999の範囲で入力して下さい"; }
1,242
0.777293
0.759825
29
30.586206
34.65049
94
false
false
0
0
0
0
0
0
0.931035
false
false
0
cffbc000809d6f19227870663fa83c3c4b646f71
21,371,757,301,972
66f198f27dd22348dce50a6e032f79631aa4105b
/prj/2/Code/ReadPrice.java
40e62281765ef684ee358debe532c1170e60b18c
[]
no_license
Grace-Kelly1/cmpt220Kelly
https://github.com/Grace-Kelly1/cmpt220Kelly
0d287c36ea02715c681954e8f3d5512b5e2bef1d
f35ee249b177da9983d73d96c71e9d57411d417a
refs/heads/master
2021-01-11T20:09:29.276000
2019-01-28T01:38:12
2019-01-28T01:38:12
79,052,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.io.File; import java.util.Scanner; public class ReadPrice { //Data Fields private String Ticker; private int NumberShares; public ReadPrice(String Ticker){ this.Ticker = Ticker; } //Get price for individual ticker public double getPrice(String Ticker) throws IOException{ double priceMaybe = 0; // Create a Scanner for the file Scanner input = new Scanner(new File("C:\\data\\Price.txt")); // Read data from a file while (input.hasNext()) { String Stock = input.next(); priceMaybe = input.nextDouble(); //Check for match if (Stock.equals(Ticker)){ break; } } // Close the file input.close(); //Return Price Value return priceMaybe; } }
UTF-8
Java
821
java
ReadPrice.java
Java
[]
null
[]
import java.io.*; import java.io.File; import java.util.Scanner; public class ReadPrice { //Data Fields private String Ticker; private int NumberShares; public ReadPrice(String Ticker){ this.Ticker = Ticker; } //Get price for individual ticker public double getPrice(String Ticker) throws IOException{ double priceMaybe = 0; // Create a Scanner for the file Scanner input = new Scanner(new File("C:\\data\\Price.txt")); // Read data from a file while (input.hasNext()) { String Stock = input.next(); priceMaybe = input.nextDouble(); //Check for match if (Stock.equals(Ticker)){ break; } } // Close the file input.close(); //Return Price Value return priceMaybe; } }
821
0.599269
0.598051
38
20.631578
15.638046
67
false
false
0
0
0
0
0
0
2.394737
false
false
0
9c7373616a7dd422c57493f3ecba77b8a723b11d
27,212,912,827,999
41cfcd4b91b7d23599b5adf6e7ea91d8d83c523a
/src/ms/platform/system/groupUser/model/TMgtGroupUser.java
d51ad87beb723b83fe3f9d5c9a779b79da2fb78a
[]
no_license
happy6eve/huangyanjun
https://github.com/happy6eve/huangyanjun
209d27ff4b99af929afacb222af5ede09f19df58
b39f4eb9b494bed18d3ff9f578044dc69cfa52e9
refs/heads/master
2018-04-21T20:57:54.096000
2017-05-10T09:53:39
2017-05-10T09:53:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ms.platform.system.groupUser.model; public class TMgtGroupUser implements java.io.Serializable { /** * TMgtGroupUser entity. @author MyEclipse Persistence Tools */ private static final long serialVersionUID = 520400997779971768L; private String groupUserID; //主键 private String userId; //用户id private String groupCode; //部门编号 private String instCode; //机构编号 private String orgCode; //运营机构 private String creator; //创建人 private String createTime; //创建时间 private String mender; //修改人 private String mendTime; //修改时间 private String remark; //备注 /** default constructor */ public TMgtGroupUser ( ) { } /** minimal constructor */ public TMgtGroupUser ( String groupUserID ) { this.groupUserID = groupUserID; } /** * @return the groupUserID */ public String getGroupUserID ( ) { return groupUserID; } /** * @return the userId */ public String getUserId ( ) { return userId; } /** * @param userId the userId to set */ public void setUserId ( String userId ) { this.userId = userId; } /** full constructor */ public TMgtGroupUser (String instCode, String groupUserID,String userId, String groupCode, String orgCode, String creator, String createTime, String mender, String mendTime, String remark ) { this.setInstCode( instCode ); this.groupUserID = groupUserID; this.userId = userId; this.groupCode = groupCode; this.orgCode = orgCode; this.creator = creator; this.createTime = createTime; this.mender = mender; this.mendTime = mendTime; this.remark = remark; } /** * @param groupUserID * the groupUserID to set */ public void setGroupUserID ( String groupUserID ) { this.groupUserID = groupUserID; } /** * @return the groupCode */ public String getGroupCode ( ) { return groupCode; } /** * @return the mendTime */ public String getMendTime ( ) { return mendTime; } /** * @param mendTime the mendTime to set */ public void setMendTime ( String mendTime ) { this.mendTime = mendTime; } /** * @param groupCode * the groupCode to set */ public void setGroupCode ( String groupCode ) { this.groupCode = groupCode; } /** * @return the instCode */ public String getInstCode ( ) { return instCode; } /** * @param instCode * the instCode to set */ public void setInstCode ( String instCode ) { this.instCode = instCode; } /** * @return the orgCode */ public String getOrgCode ( ) { return orgCode; } /** * @param orgCode * the orgCode to set */ public void setOrgCode ( String orgCode ) { this.orgCode = orgCode; } /** * @return the creator */ public String getCreator ( ) { return creator; } /** * @param creator * the creator to set */ public void setCreator ( String creator ) { this.creator = creator; } /** * @return the creatorTime */ public String getCreateTime ( ) { return createTime; } /** * @param creatorTime * the creatorTime to set */ public void setCreateTime ( String createTime ) { this.createTime = createTime; } /** * @return the mender */ public String getMender ( ) { return mender; } /** * @param mender * the mender to set */ public void setMender ( String mender ) { this.mender = mender; } /** * @return the menderTime */ public String getMenderTime ( ) { return mendTime; } /** * @param menderTime * the menderTime to set */ public void setMenderTime ( String mendTime ) { this.mendTime = mendTime; } /** * @return the remark */ public String getRemark ( ) { return remark; } /** * @param remark * the remark to set */ public void setRemark ( String remark ) { this.remark = remark; } }
UTF-8
Java
4,379
java
TMgtGroupUser.java
Java
[]
null
[]
package ms.platform.system.groupUser.model; public class TMgtGroupUser implements java.io.Serializable { /** * TMgtGroupUser entity. @author MyEclipse Persistence Tools */ private static final long serialVersionUID = 520400997779971768L; private String groupUserID; //主键 private String userId; //用户id private String groupCode; //部门编号 private String instCode; //机构编号 private String orgCode; //运营机构 private String creator; //创建人 private String createTime; //创建时间 private String mender; //修改人 private String mendTime; //修改时间 private String remark; //备注 /** default constructor */ public TMgtGroupUser ( ) { } /** minimal constructor */ public TMgtGroupUser ( String groupUserID ) { this.groupUserID = groupUserID; } /** * @return the groupUserID */ public String getGroupUserID ( ) { return groupUserID; } /** * @return the userId */ public String getUserId ( ) { return userId; } /** * @param userId the userId to set */ public void setUserId ( String userId ) { this.userId = userId; } /** full constructor */ public TMgtGroupUser (String instCode, String groupUserID,String userId, String groupCode, String orgCode, String creator, String createTime, String mender, String mendTime, String remark ) { this.setInstCode( instCode ); this.groupUserID = groupUserID; this.userId = userId; this.groupCode = groupCode; this.orgCode = orgCode; this.creator = creator; this.createTime = createTime; this.mender = mender; this.mendTime = mendTime; this.remark = remark; } /** * @param groupUserID * the groupUserID to set */ public void setGroupUserID ( String groupUserID ) { this.groupUserID = groupUserID; } /** * @return the groupCode */ public String getGroupCode ( ) { return groupCode; } /** * @return the mendTime */ public String getMendTime ( ) { return mendTime; } /** * @param mendTime the mendTime to set */ public void setMendTime ( String mendTime ) { this.mendTime = mendTime; } /** * @param groupCode * the groupCode to set */ public void setGroupCode ( String groupCode ) { this.groupCode = groupCode; } /** * @return the instCode */ public String getInstCode ( ) { return instCode; } /** * @param instCode * the instCode to set */ public void setInstCode ( String instCode ) { this.instCode = instCode; } /** * @return the orgCode */ public String getOrgCode ( ) { return orgCode; } /** * @param orgCode * the orgCode to set */ public void setOrgCode ( String orgCode ) { this.orgCode = orgCode; } /** * @return the creator */ public String getCreator ( ) { return creator; } /** * @param creator * the creator to set */ public void setCreator ( String creator ) { this.creator = creator; } /** * @return the creatorTime */ public String getCreateTime ( ) { return createTime; } /** * @param creatorTime * the creatorTime to set */ public void setCreateTime ( String createTime ) { this.createTime = createTime; } /** * @return the mender */ public String getMender ( ) { return mender; } /** * @param mender * the mender to set */ public void setMender ( String mender ) { this.mender = mender; } /** * @return the menderTime */ public String getMenderTime ( ) { return mendTime; } /** * @param menderTime * the menderTime to set */ public void setMenderTime ( String mendTime ) { this.mendTime = mendTime; } /** * @return the remark */ public String getRemark ( ) { return remark; } /** * @param remark * the remark to set */ public void setRemark ( String remark ) { this.remark = remark; } }
4,379
0.565238
0.561066
236
17.279661
18.213837
109
false
false
0
0
0
0
0
0
0.228814
false
false
0
d04e7411ec9ea4539cfd3d5979e0f9ff8aec9640
28,819,230,588,167
bf1cffa1a912aec1dcd3972e8587e29b924036fb
/src/w1/app/easymoney/data/TN_RelationDBH.java
6d3c9c86504f782a131fbed60336ae4e1fdedd71
[]
no_license
liumanman/EasyMoney
https://github.com/liumanman/EasyMoney
1860d370b3593481c5fc8aaa79b4fb05b590fa9a
3f154de7a5d13f71289f5489f80f90becd603f66
refs/heads/master
2020-04-21T16:12:37.491000
2014-04-17T21:25:07
2014-04-17T21:25:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package w1.app.easymoney.data; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import w1.app.easymoney.common.Utility; import w1.app.easymoney.entity.TN_Relation; import java.text.ParseException; import java.util.ArrayList; import java.util.List; public class TN_RelationDBH { public static int insert(TN_Relation tn) throws SQLException, java.sql.SQLException{ ContentValues cv = new ContentValues(6); cv.put(TN_Relation.COLUMN_FLAG, tn.getFlag()); //cv.put(TN_Relation.COLUMN_ID, tn.getID()); cv.put(TN_Relation.COLUMN_INDATE, Utility.DateToString(tn.getInDate())); cv.put(TN_Relation.COLUMN_INUSERID, tn.getInUserID()); cv.put(TN_Relation.COLUMN_NODEID, tn.getNodeID()); cv.put(TN_Relation.COLUMN_TRANID, tn.getTranID()); return (int) DatabaseOperator.getOperator().getWritableDatabase().insertOrThrow(TN_Relation.TABLE_NAME, null, cv); } public static void update(TN_Relation tn){ } public static void delete(int id) throws java.sql.SQLException { DatabaseOperator.getOperator().getWritableDatabase().delete(TN_Relation.TABLE_NAME, "id=?", new String[] {String.valueOf(id)}); } public static void deleteBYTranID(int tranID) throws java.sql.SQLException { DatabaseOperator.getOperator().getWritableDatabase().delete(TN_Relation.TABLE_NAME, "TranID=?", new String[] {String.valueOf(tranID)}); } public static List<TN_Relation> getByTranID(int tranID) throws ParseException { Cursor cursor = DatabaseOperator.getOperator().getReadableDatabase().query(TN_Relation.TABLE_NAME, null, "TranID=?", new String[]{String.valueOf(tranID)}, null, null, null); ArrayList<TN_Relation> list = new ArrayList<TN_Relation>(cursor.getCount()); while(cursor.moveToNext()){ list.add(createTNRelationFromCursor(cursor)); } return list; } private static TN_Relation createTNRelationFromCursor(Cursor cursor) throws ParseException { TN_Relation r = new TN_Relation(); r.setFlag(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_FLAG))); r.setID(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_ID))); r.setInDate(Utility.StringToDate(cursor.getString(cursor.getColumnIndex(TN_Relation.COLUMN_INDATE)))); r.setInUserID(cursor.getString(cursor.getColumnIndex(TN_Relation.COLUMN_INUSERID))); r.setNodeID(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_NODEID))); r.setTranID(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_TRANID))); return r; } }
UTF-8
Java
2,605
java
TN_RelationDBH.java
Java
[]
null
[]
package w1.app.easymoney.data; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import w1.app.easymoney.common.Utility; import w1.app.easymoney.entity.TN_Relation; import java.text.ParseException; import java.util.ArrayList; import java.util.List; public class TN_RelationDBH { public static int insert(TN_Relation tn) throws SQLException, java.sql.SQLException{ ContentValues cv = new ContentValues(6); cv.put(TN_Relation.COLUMN_FLAG, tn.getFlag()); //cv.put(TN_Relation.COLUMN_ID, tn.getID()); cv.put(TN_Relation.COLUMN_INDATE, Utility.DateToString(tn.getInDate())); cv.put(TN_Relation.COLUMN_INUSERID, tn.getInUserID()); cv.put(TN_Relation.COLUMN_NODEID, tn.getNodeID()); cv.put(TN_Relation.COLUMN_TRANID, tn.getTranID()); return (int) DatabaseOperator.getOperator().getWritableDatabase().insertOrThrow(TN_Relation.TABLE_NAME, null, cv); } public static void update(TN_Relation tn){ } public static void delete(int id) throws java.sql.SQLException { DatabaseOperator.getOperator().getWritableDatabase().delete(TN_Relation.TABLE_NAME, "id=?", new String[] {String.valueOf(id)}); } public static void deleteBYTranID(int tranID) throws java.sql.SQLException { DatabaseOperator.getOperator().getWritableDatabase().delete(TN_Relation.TABLE_NAME, "TranID=?", new String[] {String.valueOf(tranID)}); } public static List<TN_Relation> getByTranID(int tranID) throws ParseException { Cursor cursor = DatabaseOperator.getOperator().getReadableDatabase().query(TN_Relation.TABLE_NAME, null, "TranID=?", new String[]{String.valueOf(tranID)}, null, null, null); ArrayList<TN_Relation> list = new ArrayList<TN_Relation>(cursor.getCount()); while(cursor.moveToNext()){ list.add(createTNRelationFromCursor(cursor)); } return list; } private static TN_Relation createTNRelationFromCursor(Cursor cursor) throws ParseException { TN_Relation r = new TN_Relation(); r.setFlag(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_FLAG))); r.setID(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_ID))); r.setInDate(Utility.StringToDate(cursor.getString(cursor.getColumnIndex(TN_Relation.COLUMN_INDATE)))); r.setInUserID(cursor.getString(cursor.getColumnIndex(TN_Relation.COLUMN_INUSERID))); r.setNodeID(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_NODEID))); r.setTranID(cursor.getInt(cursor.getColumnIndex(TN_Relation.COLUMN_TRANID))); return r; } }
2,605
0.73167
0.730134
62
41.016129
41.894833
181
false
false
0
0
0
0
0
0
1.33871
false
false
0
cf9ba4e73a6fc3458bf7963528c9a2aba5163f70
4,312,147,216,594
bf05bbfeee447e124fe854cb084ea4ed3463cbc4
/src/main/java/vn/edu/imic/tung/EX3.java
74537c0b705d7c924fe088901d94c95e917820d5
[]
no_license
doannv1409/app
https://github.com/doannv1409/app
20b86d943de74c040bea5b07e49ee09fb16c9698
211eeffaec45b5b86e0287c20b205e66a9dbb1e9
refs/heads/master
2021-06-01T02:56:16.184000
2016-05-23T14:33:16
2016-05-23T14:33:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vn.edu.imic.tung; import java.util.Scanner; public class EX3 { public static void main(String agrv[]) { System.out.println("nhap mot so nguyen bat ki"); Scanner keyboard =new Scanner(System.in); int n = keyboard.nextInt(); int count=0; int i=0; while (i<=n) { if (i%2==0) count++; i++; } System.out.println("so chan trong day la "+count); System.exit(0); } }
UTF-8
Java
438
java
EX3.java
Java
[]
null
[]
package vn.edu.imic.tung; import java.util.Scanner; public class EX3 { public static void main(String agrv[]) { System.out.println("nhap mot so nguyen bat ki"); Scanner keyboard =new Scanner(System.in); int n = keyboard.nextInt(); int count=0; int i=0; while (i<=n) { if (i%2==0) count++; i++; } System.out.println("so chan trong day la "+count); System.exit(0); } }
438
0.577626
0.563927
24
16.25
15.732795
52
false
false
0
0
0
0
0
0
2.25
false
false
0
a9fa0aa969101095e66358a6abc00adfb6398eac
10,316,511,490,945
fa3c41529cf3590a50c09d11260c02c7a9fba277
/src/main/java/cn/edu/hfut/backend/dto/friend/SendMessageReqBean.java
100621c0a75afcd6db79f2b558c54d9041c2f336
[]
no_license
xuewenG/online-chat-backend
https://github.com/xuewenG/online-chat-backend
d6f33b1a1bdf5028abc1aa546254977f27eed145
a883884b559dc7ab6c3124da88f6514e348e21c4
refs/heads/master
2022-11-12T08:37:59.076000
2020-07-06T17:53:20
2020-07-06T17:53:20
274,790,204
0
0
null
false
2020-07-05T13:02:27
2020-06-24T23:35:16
2020-07-05T12:48:37
2020-07-05T13:02:26
506
0
0
0
Java
false
false
package cn.edu.hfut.backend.dto.friend; import lombok.Data; import javax.validation.constraints.NotNull; import java.sql.Timestamp; @Data public class SendMessageReqBean { private Integer userId; private Integer friendId; private Integer groupId; @NotNull private Integer type; @NotNull private String content; private Timestamp time; }
UTF-8
Java
373
java
SendMessageReqBean.java
Java
[]
null
[]
package cn.edu.hfut.backend.dto.friend; import lombok.Data; import javax.validation.constraints.NotNull; import java.sql.Timestamp; @Data public class SendMessageReqBean { private Integer userId; private Integer friendId; private Integer groupId; @NotNull private Integer type; @NotNull private String content; private Timestamp time; }
373
0.742627
0.742627
19
18.631578
14.027081
44
false
false
0
0
0
0
0
0
0.526316
false
false
0
9d1359559e3d35844ac1218815ae3055ae5042e2
12,833,362,291,800
c60ca24dbb2ce8be7d42d70c12fadf40f4f1dc1a
/Game/TanduriMemCleaner/src/main/java/net/miginfocom/layout/ResizeConstraint.java
3651c85deffa035596fb9103aa9f59080e4576c5
[]
no_license
Niharkanta1/JavaRepo
https://github.com/Niharkanta1/JavaRepo
8e57a3e6c2ed113029bbff71f7fba23f8dc2b6cd
daa4f7f5c67bf8e38c1282ab340e084e1d1c0726
refs/heads/master
2021-07-07T20:47:21.224000
2019-06-30T11:47:27
2019-06-30T11:47:27
194,510,056
0
0
null
false
2020-10-13T14:17:34
2019-06-30T11:50:19
2019-06-30T11:51:01
2020-10-13T14:17:33
18,517
0
0
2
Java
false
false
package net.miginfocom.layout; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; final class ResizeConstraint implements Externalizable { static final Float WEIGHT_100 = new Float(100.0F); Float grow = null; int growPrio = 100; Float shrink = WEIGHT_100; int shrinkPrio = 100; public ResizeConstraint() {} ResizeConstraint(int paramInt1, Float paramFloat1, int paramInt2, Float paramFloat2) { this.shrinkPrio = paramInt1; this.shrink = paramFloat1; this.growPrio = paramInt2; this.grow = paramFloat2; } private Object readResolve() throws ObjectStreamException { return LayoutUtil.getSerializedObject(this); } public void readExternal(ObjectInput paramObjectInput) throws IOException, ClassNotFoundException { LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(paramObjectInput)); } public void writeExternal(ObjectOutput paramObjectOutput) throws IOException { if (getClass() == ResizeConstraint.class) LayoutUtil.writeAsXML(paramObjectOutput, this); } } /* Location: D:\CODING\JAVA\Game\lemons tf2 cheat xd.jar!\net\miginfocom\layout\ResizeConstraint.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.0.4 */
UTF-8
Java
1,335
java
ResizeConstraint.java
Java
[]
null
[]
package net.miginfocom.layout; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; final class ResizeConstraint implements Externalizable { static final Float WEIGHT_100 = new Float(100.0F); Float grow = null; int growPrio = 100; Float shrink = WEIGHT_100; int shrinkPrio = 100; public ResizeConstraint() {} ResizeConstraint(int paramInt1, Float paramFloat1, int paramInt2, Float paramFloat2) { this.shrinkPrio = paramInt1; this.shrink = paramFloat1; this.growPrio = paramInt2; this.grow = paramFloat2; } private Object readResolve() throws ObjectStreamException { return LayoutUtil.getSerializedObject(this); } public void readExternal(ObjectInput paramObjectInput) throws IOException, ClassNotFoundException { LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(paramObjectInput)); } public void writeExternal(ObjectOutput paramObjectOutput) throws IOException { if (getClass() == ResizeConstraint.class) LayoutUtil.writeAsXML(paramObjectOutput, this); } } /* Location: D:\CODING\JAVA\Game\lemons tf2 cheat xd.jar!\net\miginfocom\layout\ResizeConstraint.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.0.4 */
1,335
0.743071
0.719101
43
30.069767
36.7103
181
false
false
0
0
0
0
0
0
0.55814
false
false
0
947c3c4576cd7b9fe190fff7312e548b07a1dc11
24,970,939,891,647
0b77ac58768b1cb33144b96d270064b2b8790675
/vidada-server/src/main/java/com/elderbyte/messages/exceptions/PublishException.java
dc497b82afe1bc1ff7dd75eb12d16929ba0ae725
[ "Apache-2.0" ]
permissive
Vidada-Project/Vidada-Server
https://github.com/Vidada-Project/Vidada-Server
2d7cc5e36720c2fa99d0613c90b13f7627d26684
b79d8493207568aecf3c6981d41eca406d32a1db
refs/heads/master
2017-05-31T01:21:16.591000
2017-05-29T20:08:37
2017-05-29T20:08:37
34,208,224
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.elderbyte.messages.exceptions; import com.elderbyte.messages.exceptions.MessageClientException; public class PublishException extends MessageClientException { public PublishException(String message) { super(message, null); } public PublishException(String message, Throwable e) { super(message, e); } }
UTF-8
Java
352
java
PublishException.java
Java
[]
null
[]
package com.elderbyte.messages.exceptions; import com.elderbyte.messages.exceptions.MessageClientException; public class PublishException extends MessageClientException { public PublishException(String message) { super(message, null); } public PublishException(String message, Throwable e) { super(message, e); } }
352
0.738636
0.738636
15
22.466667
24.616707
64
false
false
0
0
0
0
0
0
0.466667
false
false
0
d508a05162951c3e2657fa75c3a2d27019cdaabb
8,658,654,091,010
bc674ebe01198556d9426ec519301a6f8c8d09da
/src/test/java/com/capacitar/pontoapi/repository/LancamentoRepositoryTest.java
b754fb26f82634e0cbec70b7d7f901624ac1e123
[]
no_license
jakkison/api-ponto-capacitar
https://github.com/jakkison/api-ponto-capacitar
8c84e922ca1dab6a80a2dd8ece719d2a3e4db8de
136dc6301c2b211fdda51788b31c337eed23885b
refs/heads/master
2023-08-13T23:00:36.112000
2021-10-04T20:31:25
2021-10-04T20:31:25
390,391,462
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.capacitar.pontoapi.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.capacitar.pontoapi.enums.PerfilEnum; import com.capacitar.pontoapi.enums.TipoEnum; import com.capacitar.pontoapi.model.Empresa; import com.capacitar.pontoapi.model.Funcionario; import com.capacitar.pontoapi.model.Lancamento; import com.capacitar.pontoapi.utils.PasswordUtils; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class LancamentoRepositoryTest { @Autowired private LancamentoRepository lancRepository; @Autowired private FuncionarioRepository funcRepository; @Autowired private EmpresaRepository empRepository; private Long idFuncionario; @Before public void setUp() throws NoSuchAlgorithmException { Empresa empresa = this.empRepository.save(obterDadosEmpresa()); Funcionario funcionario = this.funcRepository.save(obterDadosFuncionario(empresa)); this.idFuncionario = funcionario.getId(); this.lancRepository.save(obterDadosLancamentos(funcionario)); this.lancRepository.save(obterDadosLancamentos(funcionario)); } @After public void tearDown() throws Exception{ this.empRepository.deleteAll(); } @Test public void testBuscarLancamentoPorFuncionarioID() { List<Lancamento> lancamentos = this.lancRepository.findByFuncionarioId(idFuncionario); assertEquals(2, lancamentos.size()); } @Test public void testBuscarLancamentosPorFuncionarioIdPaginado() { Page<Lancamento> lancamentos = this.lancRepository.findByFuncionarioId(idFuncionario, PageRequest.of(0, 10)); assertEquals(2, lancamentos.getTotalElements()); } private Lancamento obterDadosLancamentos(Funcionario funcionario) { Lancamento lancameto = new Lancamento(); lancameto.setData(new Date()); lancameto.setTipo(TipoEnum.INICIO_ALMOCO); lancameto.setFuncionario(funcionario); return lancameto; } private Funcionario obterDadosFuncionario(Empresa empresa) throws NoSuchAlgorithmException { Funcionario funcionario = new Funcionario(); funcionario.setNome("Fulano de Tal"); funcionario.setPerfil(PerfilEnum.ROLE_USUARIO); funcionario.setSenha(PasswordUtils.gerarBCrypt("123456")); funcionario.setCpf("24291173474"); funcionario.setEmail("email@email.com"); funcionario.setEmpresa(empresa); return funcionario; } private Empresa obterDadosEmpresa() { Empresa empresa = new Empresa(); empresa.setRazaoSocial("Empresa de exemplo"); empresa.setCnpj("51463645000100"); return empresa; } }
UTF-8
Java
3,082
java
LancamentoRepositoryTest.java
Java
[ { "context": "io = new Funcionario();\n\t\t\n\t\tfuncionario.setNome(\"Fulano de Tal\");\n\t\tfuncionario.setPerfil(PerfilEnum.ROLE_USUARI", "end": 2630, "score": 0.9998923540115356, "start": 2617, "tag": "NAME", "value": "Fulano de Tal" }, { "context": "\t\tfuncionario.setSenha(Pass...
null
[]
package com.capacitar.pontoapi.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.capacitar.pontoapi.enums.PerfilEnum; import com.capacitar.pontoapi.enums.TipoEnum; import com.capacitar.pontoapi.model.Empresa; import com.capacitar.pontoapi.model.Funcionario; import com.capacitar.pontoapi.model.Lancamento; import com.capacitar.pontoapi.utils.PasswordUtils; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class LancamentoRepositoryTest { @Autowired private LancamentoRepository lancRepository; @Autowired private FuncionarioRepository funcRepository; @Autowired private EmpresaRepository empRepository; private Long idFuncionario; @Before public void setUp() throws NoSuchAlgorithmException { Empresa empresa = this.empRepository.save(obterDadosEmpresa()); Funcionario funcionario = this.funcRepository.save(obterDadosFuncionario(empresa)); this.idFuncionario = funcionario.getId(); this.lancRepository.save(obterDadosLancamentos(funcionario)); this.lancRepository.save(obterDadosLancamentos(funcionario)); } @After public void tearDown() throws Exception{ this.empRepository.deleteAll(); } @Test public void testBuscarLancamentoPorFuncionarioID() { List<Lancamento> lancamentos = this.lancRepository.findByFuncionarioId(idFuncionario); assertEquals(2, lancamentos.size()); } @Test public void testBuscarLancamentosPorFuncionarioIdPaginado() { Page<Lancamento> lancamentos = this.lancRepository.findByFuncionarioId(idFuncionario, PageRequest.of(0, 10)); assertEquals(2, lancamentos.getTotalElements()); } private Lancamento obterDadosLancamentos(Funcionario funcionario) { Lancamento lancameto = new Lancamento(); lancameto.setData(new Date()); lancameto.setTipo(TipoEnum.INICIO_ALMOCO); lancameto.setFuncionario(funcionario); return lancameto; } private Funcionario obterDadosFuncionario(Empresa empresa) throws NoSuchAlgorithmException { Funcionario funcionario = new Funcionario(); funcionario.setNome("<NAME>"); funcionario.setPerfil(PerfilEnum.ROLE_USUARIO); funcionario.setSenha(PasswordUtils.gerarBCrypt("<PASSWORD>")); funcionario.setCpf("24291173474"); funcionario.setEmail("<EMAIL>"); funcionario.setEmpresa(empresa); return funcionario; } private Empresa obterDadosEmpresa() { Empresa empresa = new Empresa(); empresa.setRazaoSocial("Empresa de exemplo"); empresa.setCnpj("51463645000100"); return empresa; } }
3,071
0.794938
0.782933
112
26.517857
25.487385
111
false
false
0
0
0
0
0
0
1.535714
false
false
0
c8f0b48d7583fd16412580829f0c44f4b25d42ad
11,922,829,217,426
1f9b85675bdef6430ecccf94416dd8b957b7f854
/singlePlayer/advanced/tkomisarczyk/MonteCarlo/GameKnowledge.java
be358393e0918a06771138801df485fc7cb48fd0
[]
no_license
RegyN/magisterka
https://github.com/RegyN/magisterka
413a3785720859f3f37447ffeb372696f510d667
57dec2a03c00662d301afe58810365a6ede77eb6
refs/heads/master
2020-05-04T23:50:57.668000
2019-10-23T17:32:53
2019-10-23T17:32:53
179,557,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tracks.singlePlayer.advanced.tkomisarczyk.MonteCarlo; import core.game.Observation; import core.game.StateObservation; import ontology.Types; import tools.ElapsedCpuTimer; import tools.Vector2d; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; enum GameType{ Planar2D, Other } enum SpriteType{ Wall, Floor, Player, Enemy, Point, Other, Unknown } public class GameKnowledge{ final static int SPRITE_MAX = 50; final int NPC_CATEGORY = 3; GameType type; SpriteType[] sprites; int gameWidth; int gameHeight; double avatarSpeed; boolean isAvatarOriented; private static GameKnowledge instance; private GameKnowledge(){ sprites = new SpriteType[SPRITE_MAX]; for(int i = 0; i<SPRITE_MAX; i++){ sprites[i] = SpriteType.Unknown; } } public static GameKnowledge getInstance() { if(instance == null) instance = new GameKnowledge(); return instance; } public static GameKnowledge GetNew(){ instance = new GameKnowledge(); return instance; } public static void Reset(){ instance = new GameKnowledge(); } public boolean CheckForWalls(ArrayList<Observation> objects){ for(Observation o : objects){ if(this.sprites[o.itype] == SpriteType.Wall){ return true; } } return false; } public void GatherStaticInfo(StateObservation stateObs){ gameHeight = stateObs.getWorldDimension().height / stateObs.getBlockSize(); gameWidth = stateObs.getWorldDimension().width / stateObs.getBlockSize(); avatarSpeed = stateObs.getAvatarSpeed(); ArrayList<Types.ACTIONS> actions = stateObs.getAvailableActions(); if (actions.contains(Types.ACTIONS.ACTION_UP) && actions.contains(Types.ACTIONS.ACTION_DOWN) && actions.contains(Types.ACTIONS.ACTION_LEFT) && actions.contains(Types.ACTIONS.ACTION_RIGHT)) { type = GameType.Planar2D; } else { type = GameType.Other; } // Statycznie zbieram info o spritach w grze sprites[stateObs.getAvatarType()] = SpriteType.Player; Position2D avatarPos = Position2D.GetAvatarPosition(stateObs); ArrayList<Observation> obs = Position2D.GetObservations(stateObs, avatarPos.x, avatarPos.y); for (Observation o : obs) { if (o.itype != stateObs.getAvatarType()) { sprites[o.itype] = SpriteType.Floor; // Jeśli na początku gry coś jest bezpośrednio pod graczem, to pewnie jest to podłoga. } } isAvatarOriented = checkIsAvatarOriented(stateObs); } private boolean checkIsAvatarOriented(StateObservation stateObs) { Vector2d originalOrientation = stateObs.getAvatarOrientation(); Vector2d originalPosition = stateObs.getAvatarPosition(); List<Types.ACTIONS> actions = Arrays.asList(Types.ACTIONS.ACTION_LEFT, Types.ACTIONS.ACTION_UP, Types.ACTIONS.ACTION_RIGHT, Types.ACTIONS.ACTION_DOWN); for(Types.ACTIONS testAction : actions){ StateObservation stateCopy = stateObs.copy(); stateCopy.advance(testAction); Vector2d walkDirection; switch (testAction) { case ACTION_DOWN: walkDirection = Types.DOWN; case ACTION_UP: walkDirection = Types.UP; case ACTION_RIGHT: walkDirection = Types.RIGHT; case ACTION_LEFT: walkDirection = Types.LEFT; default: walkDirection = Types.NONE; } Vector2d newPosition = stateCopy.getAvatarPosition(); // Can we can walk to an field without having the right orientation? if (!walkDirection.equals(originalOrientation)) { if (!originalPosition.equals(newPosition)) { return false; } } } return true; } public void GatherSpriteInfoRandomly(StateObservation stateObs, ElapsedCpuTimer elapsedTimer) { //Dynamiczne zbieranie informacji o grze StateObservation stCopy = stateObs.copy(); Random generator = new Random(); Position2D avatarPos = Position2D.GetAvatarPosition(stCopy); int testInRow = 0; while(elapsedTimer.remainingTimeMillis() > 10){ if(stCopy.isGameOver() || CheckForNearbyNpc(stCopy, avatarPos)){ stCopy = stateObs.copy(); continue; } if(trySnapToGrid(stCopy, avatarPos)){ continue; } avatarPos = Position2D.GetAvatarPosition(stCopy); if(!tryGetInfoFromSurrounding(stCopy, avatarPos)){ int choice = generator.nextInt(4); switch(choice){ case 0: stCopy.advance(Types.ACTIONS.ACTION_UP); break; case 1: stCopy.advance(Types.ACTIONS.ACTION_DOWN); break; case 2: stCopy.advance(Types.ACTIONS.ACTION_LEFT); break; case 3: stCopy.advance(Types.ACTIONS.ACTION_RIGHT); break; } } testInRow++; } } // Zwraca Obserwację, która nie jest znana, jeśli jest jedyną nieznaną obserwacją w tablicy. private Observation FindSingleUnknown(ArrayList<Observation> objects){ Observation unknown = null; for(Observation o : objects){ if(this.sprites[o.itype] == SpriteType.Unknown){ if(unknown == null){ unknown = o; } else{ unknown = null; break; } } } return unknown; } // Zakładam, że avatar jest centralnie na polu i sprawdzam sąsiednie pola na obecność NPC private boolean CheckForNearbyNpc(StateObservation stateObs, Position2D avatarPos) { if(avatarPos.x < 0 || avatarPos.y < 0 || avatarPos.x >= gameWidth || avatarPos.y >= gameHeight) return false; if(avatarPos.x >= 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x - 1][(int)avatarPos.y]){ if(o.category == NPC_CATEGORY) return true; } } if(avatarPos.x < gameWidth - 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x + 1][(int)avatarPos.y]){ if(o.category == NPC_CATEGORY) return true; } } if(avatarPos.y >= 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x][(int)avatarPos.y - 1]){ if(o.category == NPC_CATEGORY) return true; } } if(avatarPos.y < gameHeight - 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x][(int)avatarPos.y + 1]){ if(o.category == NPC_CATEGORY) return true; } } return false; } // Avatar centralnie na polu, sprawdzam czy w okolicy da się czegoś dowiedzieć i jeśli tak, to się dowiaduję 1 ruchem private boolean tryGetInfoFromSurrounding(StateObservation stateObs, Position2D avatarPos) { boolean gotInfo = false; if(tryLearnSingleUnknown(stateObs, avatarPos.x+1, avatarPos.y, Types.ACTIONS.ACTION_RIGHT)){ gotInfo = true; } else if(tryLearnSingleUnknown(stateObs, avatarPos.x-1, avatarPos.y, Types.ACTIONS.ACTION_LEFT)){ gotInfo = true; } else if(tryLearnSingleUnknown(stateObs, avatarPos.x, avatarPos.y-1, Types.ACTIONS.ACTION_UP)){ gotInfo = true; } else if(tryLearnSingleUnknown(stateObs, avatarPos.x, avatarPos.y+1, Types.ACTIONS.ACTION_DOWN)){ gotInfo = true; } return gotInfo; } private boolean tryLearnSingleUnknown(StateObservation stateObs, double x, double y, Types.ACTIONS action){ if(x < 0 || y < 0 || x >= GameKnowledge.getInstance().gameWidth || y >= GameKnowledge.getInstance().gameHeight){ return false; } Observation unknown = FindSingleUnknown(Position2D.GetObservationsFast(stateObs, x, y)); boolean canLearn = (unknown != null); if(canLearn){ double numberOfPoints = stateObs.getGameScore(); Position2D avatarPosBefore = Position2D.GetAvatarPosition(stateObs); Vector2d avatarOrientationBefore = stateObs.getAvatarOrientation(); stateObs.advance(action); Position2D avatarPosAfter = Position2D.GetAvatarPosition(stateObs); Vector2d avatarOrientationAfter = stateObs.getAvatarOrientation(); if(!stateObs.isAvatarAlive()){ sprites[unknown.itype] = SpriteType.Enemy; } else if(stateObs.getGameScore() > numberOfPoints){ sprites[unknown.itype] = SpriteType.Point; } else if(avatarPosAfter.x == avatarPosBefore.x && avatarPosAfter.y == avatarPosBefore.y){ // Obiekt zablokował przejście, ale się nie przesunął if(isAvatarOriented && (avatarOrientationBefore.x != avatarOrientationAfter.x || avatarOrientationBefore.y != avatarOrientationAfter.y)){ stateObs.advance(action); avatarPosAfter = Position2D.GetAvatarPosition(stateObs); } if(FindSingleUnknown(Position2D.GetObservationsFast(stateObs, x, y)) == unknown && avatarPosAfter.x == avatarPosBefore.x && avatarPosAfter.y == avatarPosBefore.y && unknown.category == 4){ sprites[unknown.itype] = SpriteType.Wall; } else{ sprites[unknown.itype] = SpriteType.Other; } } else{ sprites[unknown.itype] = SpriteType.Other; } } return canLearn; } private boolean trySnapToGrid(StateObservation stateObs, Position2D avatarPos) { PositionGridType grid = Position2D.GetAvatarPosition(stateObs).IsOnGrid(); boolean positionChanged = false; Random generator = new Random(); if(grid == PositionGridType.OffX){ int choice = generator.nextInt(2); if(choice == 1){ stateObs.advance(Types.ACTIONS.ACTION_RIGHT); } else{ stateObs.advance(Types.ACTIONS.ACTION_LEFT); } positionChanged = true; } else if(grid == PositionGridType.OffY){ int choice = generator.nextInt(2); if(choice == 1){ stateObs.advance(Types.ACTIONS.ACTION_UP); } else{ stateObs.advance(Types.ACTIONS.ACTION_DOWN); } positionChanged = true; } else if(grid == PositionGridType.OffGrid){ int choice = generator.nextInt(4); switch(choice){ case 0: stateObs.advance(Types.ACTIONS.ACTION_UP); break; case 1: stateObs.advance(Types.ACTIONS.ACTION_DOWN); break; case 2: stateObs.advance(Types.ACTIONS.ACTION_LEFT); break; case 3: stateObs.advance(Types.ACTIONS.ACTION_RIGHT); break; } positionChanged = true; } return positionChanged; } }
UTF-8
Java
12,130
java
GameKnowledge.java
Java
[]
null
[]
package tracks.singlePlayer.advanced.tkomisarczyk.MonteCarlo; import core.game.Observation; import core.game.StateObservation; import ontology.Types; import tools.ElapsedCpuTimer; import tools.Vector2d; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; enum GameType{ Planar2D, Other } enum SpriteType{ Wall, Floor, Player, Enemy, Point, Other, Unknown } public class GameKnowledge{ final static int SPRITE_MAX = 50; final int NPC_CATEGORY = 3; GameType type; SpriteType[] sprites; int gameWidth; int gameHeight; double avatarSpeed; boolean isAvatarOriented; private static GameKnowledge instance; private GameKnowledge(){ sprites = new SpriteType[SPRITE_MAX]; for(int i = 0; i<SPRITE_MAX; i++){ sprites[i] = SpriteType.Unknown; } } public static GameKnowledge getInstance() { if(instance == null) instance = new GameKnowledge(); return instance; } public static GameKnowledge GetNew(){ instance = new GameKnowledge(); return instance; } public static void Reset(){ instance = new GameKnowledge(); } public boolean CheckForWalls(ArrayList<Observation> objects){ for(Observation o : objects){ if(this.sprites[o.itype] == SpriteType.Wall){ return true; } } return false; } public void GatherStaticInfo(StateObservation stateObs){ gameHeight = stateObs.getWorldDimension().height / stateObs.getBlockSize(); gameWidth = stateObs.getWorldDimension().width / stateObs.getBlockSize(); avatarSpeed = stateObs.getAvatarSpeed(); ArrayList<Types.ACTIONS> actions = stateObs.getAvailableActions(); if (actions.contains(Types.ACTIONS.ACTION_UP) && actions.contains(Types.ACTIONS.ACTION_DOWN) && actions.contains(Types.ACTIONS.ACTION_LEFT) && actions.contains(Types.ACTIONS.ACTION_RIGHT)) { type = GameType.Planar2D; } else { type = GameType.Other; } // Statycznie zbieram info o spritach w grze sprites[stateObs.getAvatarType()] = SpriteType.Player; Position2D avatarPos = Position2D.GetAvatarPosition(stateObs); ArrayList<Observation> obs = Position2D.GetObservations(stateObs, avatarPos.x, avatarPos.y); for (Observation o : obs) { if (o.itype != stateObs.getAvatarType()) { sprites[o.itype] = SpriteType.Floor; // Jeśli na początku gry coś jest bezpośrednio pod graczem, to pewnie jest to podłoga. } } isAvatarOriented = checkIsAvatarOriented(stateObs); } private boolean checkIsAvatarOriented(StateObservation stateObs) { Vector2d originalOrientation = stateObs.getAvatarOrientation(); Vector2d originalPosition = stateObs.getAvatarPosition(); List<Types.ACTIONS> actions = Arrays.asList(Types.ACTIONS.ACTION_LEFT, Types.ACTIONS.ACTION_UP, Types.ACTIONS.ACTION_RIGHT, Types.ACTIONS.ACTION_DOWN); for(Types.ACTIONS testAction : actions){ StateObservation stateCopy = stateObs.copy(); stateCopy.advance(testAction); Vector2d walkDirection; switch (testAction) { case ACTION_DOWN: walkDirection = Types.DOWN; case ACTION_UP: walkDirection = Types.UP; case ACTION_RIGHT: walkDirection = Types.RIGHT; case ACTION_LEFT: walkDirection = Types.LEFT; default: walkDirection = Types.NONE; } Vector2d newPosition = stateCopy.getAvatarPosition(); // Can we can walk to an field without having the right orientation? if (!walkDirection.equals(originalOrientation)) { if (!originalPosition.equals(newPosition)) { return false; } } } return true; } public void GatherSpriteInfoRandomly(StateObservation stateObs, ElapsedCpuTimer elapsedTimer) { //Dynamiczne zbieranie informacji o grze StateObservation stCopy = stateObs.copy(); Random generator = new Random(); Position2D avatarPos = Position2D.GetAvatarPosition(stCopy); int testInRow = 0; while(elapsedTimer.remainingTimeMillis() > 10){ if(stCopy.isGameOver() || CheckForNearbyNpc(stCopy, avatarPos)){ stCopy = stateObs.copy(); continue; } if(trySnapToGrid(stCopy, avatarPos)){ continue; } avatarPos = Position2D.GetAvatarPosition(stCopy); if(!tryGetInfoFromSurrounding(stCopy, avatarPos)){ int choice = generator.nextInt(4); switch(choice){ case 0: stCopy.advance(Types.ACTIONS.ACTION_UP); break; case 1: stCopy.advance(Types.ACTIONS.ACTION_DOWN); break; case 2: stCopy.advance(Types.ACTIONS.ACTION_LEFT); break; case 3: stCopy.advance(Types.ACTIONS.ACTION_RIGHT); break; } } testInRow++; } } // Zwraca Obserwację, która nie jest znana, jeśli jest jedyną nieznaną obserwacją w tablicy. private Observation FindSingleUnknown(ArrayList<Observation> objects){ Observation unknown = null; for(Observation o : objects){ if(this.sprites[o.itype] == SpriteType.Unknown){ if(unknown == null){ unknown = o; } else{ unknown = null; break; } } } return unknown; } // Zakładam, że avatar jest centralnie na polu i sprawdzam sąsiednie pola na obecność NPC private boolean CheckForNearbyNpc(StateObservation stateObs, Position2D avatarPos) { if(avatarPos.x < 0 || avatarPos.y < 0 || avatarPos.x >= gameWidth || avatarPos.y >= gameHeight) return false; if(avatarPos.x >= 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x - 1][(int)avatarPos.y]){ if(o.category == NPC_CATEGORY) return true; } } if(avatarPos.x < gameWidth - 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x + 1][(int)avatarPos.y]){ if(o.category == NPC_CATEGORY) return true; } } if(avatarPos.y >= 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x][(int)avatarPos.y - 1]){ if(o.category == NPC_CATEGORY) return true; } } if(avatarPos.y < gameHeight - 1){ for(Observation o : stateObs.getObservationGrid()[(int)avatarPos.x][(int)avatarPos.y + 1]){ if(o.category == NPC_CATEGORY) return true; } } return false; } // Avatar centralnie na polu, sprawdzam czy w okolicy da się czegoś dowiedzieć i jeśli tak, to się dowiaduję 1 ruchem private boolean tryGetInfoFromSurrounding(StateObservation stateObs, Position2D avatarPos) { boolean gotInfo = false; if(tryLearnSingleUnknown(stateObs, avatarPos.x+1, avatarPos.y, Types.ACTIONS.ACTION_RIGHT)){ gotInfo = true; } else if(tryLearnSingleUnknown(stateObs, avatarPos.x-1, avatarPos.y, Types.ACTIONS.ACTION_LEFT)){ gotInfo = true; } else if(tryLearnSingleUnknown(stateObs, avatarPos.x, avatarPos.y-1, Types.ACTIONS.ACTION_UP)){ gotInfo = true; } else if(tryLearnSingleUnknown(stateObs, avatarPos.x, avatarPos.y+1, Types.ACTIONS.ACTION_DOWN)){ gotInfo = true; } return gotInfo; } private boolean tryLearnSingleUnknown(StateObservation stateObs, double x, double y, Types.ACTIONS action){ if(x < 0 || y < 0 || x >= GameKnowledge.getInstance().gameWidth || y >= GameKnowledge.getInstance().gameHeight){ return false; } Observation unknown = FindSingleUnknown(Position2D.GetObservationsFast(stateObs, x, y)); boolean canLearn = (unknown != null); if(canLearn){ double numberOfPoints = stateObs.getGameScore(); Position2D avatarPosBefore = Position2D.GetAvatarPosition(stateObs); Vector2d avatarOrientationBefore = stateObs.getAvatarOrientation(); stateObs.advance(action); Position2D avatarPosAfter = Position2D.GetAvatarPosition(stateObs); Vector2d avatarOrientationAfter = stateObs.getAvatarOrientation(); if(!stateObs.isAvatarAlive()){ sprites[unknown.itype] = SpriteType.Enemy; } else if(stateObs.getGameScore() > numberOfPoints){ sprites[unknown.itype] = SpriteType.Point; } else if(avatarPosAfter.x == avatarPosBefore.x && avatarPosAfter.y == avatarPosBefore.y){ // Obiekt zablokował przejście, ale się nie przesunął if(isAvatarOriented && (avatarOrientationBefore.x != avatarOrientationAfter.x || avatarOrientationBefore.y != avatarOrientationAfter.y)){ stateObs.advance(action); avatarPosAfter = Position2D.GetAvatarPosition(stateObs); } if(FindSingleUnknown(Position2D.GetObservationsFast(stateObs, x, y)) == unknown && avatarPosAfter.x == avatarPosBefore.x && avatarPosAfter.y == avatarPosBefore.y && unknown.category == 4){ sprites[unknown.itype] = SpriteType.Wall; } else{ sprites[unknown.itype] = SpriteType.Other; } } else{ sprites[unknown.itype] = SpriteType.Other; } } return canLearn; } private boolean trySnapToGrid(StateObservation stateObs, Position2D avatarPos) { PositionGridType grid = Position2D.GetAvatarPosition(stateObs).IsOnGrid(); boolean positionChanged = false; Random generator = new Random(); if(grid == PositionGridType.OffX){ int choice = generator.nextInt(2); if(choice == 1){ stateObs.advance(Types.ACTIONS.ACTION_RIGHT); } else{ stateObs.advance(Types.ACTIONS.ACTION_LEFT); } positionChanged = true; } else if(grid == PositionGridType.OffY){ int choice = generator.nextInt(2); if(choice == 1){ stateObs.advance(Types.ACTIONS.ACTION_UP); } else{ stateObs.advance(Types.ACTIONS.ACTION_DOWN); } positionChanged = true; } else if(grid == PositionGridType.OffGrid){ int choice = generator.nextInt(4); switch(choice){ case 0: stateObs.advance(Types.ACTIONS.ACTION_UP); break; case 1: stateObs.advance(Types.ACTIONS.ACTION_DOWN); break; case 2: stateObs.advance(Types.ACTIONS.ACTION_LEFT); break; case 3: stateObs.advance(Types.ACTIONS.ACTION_RIGHT); break; } positionChanged = true; } return positionChanged; } }
12,130
0.569115
0.563745
314
37.544586
29.694618
159
false
false
0
0
0
0
0
0
0.605096
false
false
0
29beb2027a297e19060590121f5f83ea664c64b9
17,154,099,385,811
f99f6ccd65f344d4c8651f4e4b058ec7f440f60c
/main5/project_shaver/gRpcClient/src/main/java/com/yhglobal/gongxiao/grpc/client/foundation/FoundationDataServiceClient.java
abf7b984a4e9cc66cd01d6829188f533c55c627a
[]
no_license
wilnd/gongxiao
https://github.com/wilnd/gongxiao
fa60c9d5d57c3cbbb69d39e3848b42850bf22e12
f18bc2f48b4041ab09ee46876fd9f7a0dcb57a52
refs/heads/master
2020-03-28T05:50:50.258000
2018-09-07T09:32:00
2018-09-07T09:32:00
147,799,238
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yhglobal.gongxiao.grpc.client.foundation; import com.yhglobal.gongxiao.accountmanage.microservice.SupplierCouponPostingServiceGrpc; import com.yhglobal.gongxiao.accountmanage.microservice.SupplierCouponPostingServiceStructure; import com.yhglobal.gongxiao.foundation.product.microservice.ProductServiceGrpc; import com.yhglobal.gongxiao.foundation.product.microservice.ProductStructure; import com.yhglobal.gongxiao.foundation.project.microservice.ProjectServiceGrpc; import com.yhglobal.gongxiao.foundation.project.microservice.ProjectStructure; import com.yhglobal.gongxiao.foundation.supplier.microservice.SupplierServiceGrpc; import com.yhglobal.gongxiao.foundation.supplier.microservice.SupplierStructure; import com.yhglobal.gongxiao.foundation.warehouse.microservice.WarehouseServiceGrpc; import com.yhglobal.gongxiao.foundation.warehouse.microservice.WarehouseStructure; import com.yhglobal.gongxiao.grpc.client.RpcStubStore; import com.yhglobal.gongxiao.microservice.GongxiaoRpc; /** * 调试时调用FoundationData服务 */ public class FoundationDataServiceClient { public static void main(String[] args) { getProjectById("1"); // selectAllDistributorAddress(); // getProjectById(146798161); // GongxiaoRpc.RpcHeader rpcHeader = RpcHeaderUtil.createRpcHeader(traceId, portalUserInfo.getUserId(), portalUserInfo.getUserName()); // generateFrontFlowSubtotal(306,"CNY",1L,146798161L,0L,9999999999999L); // generateFrontFlowSubtotal(-1, "CNY", 1L, 146798161L, 0L, 9999999999999L); // getProductInfo(); // getdistributorCoupon(); // getDistributorByDistributorId(); // getByProductCode(); // getSupplierByCode(); } static void getWarehouseById(){ GongxiaoRpc.RpcHeader rpcHeader = GongxiaoRpc.RpcHeader.newBuilder().setUid("1").setTraceId("11111").build(); WarehouseStructure.GetWarehouseByIdReq getWarehouseByIdReq = WarehouseStructure.GetWarehouseByIdReq.newBuilder() .setRpcHeader(rpcHeader) .setWarehouseId("1") .build(); WarehouseStructure.GetWarehouseByIdResp getWarehouseByIdResp=null; try { WarehouseServiceGrpc.WarehouseServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(WarehouseServiceGrpc.WarehouseServiceBlockingStub.class); getWarehouseByIdResp = rpcStub.getWarehouseById(getWarehouseByIdReq); }catch (Exception e){ e.printStackTrace(); } System.out.println(getWarehouseByIdResp.toString()); } static void getSupplierByCode(){ GongxiaoRpc.RpcHeader rpcHeader = GongxiaoRpc.RpcHeader.newBuilder().setUid("1").setTraceId("11111").build(); SupplierStructure.GetSupplierByCodeReq getSupplierByCodeReq = SupplierStructure.GetSupplierByCodeReq.newBuilder() .setRpcHeader(rpcHeader) .setSupplierCode("123456") .build(); SupplierStructure.GetSupplierByCodeResp getSupplierByCodeResp=null; try { SupplierServiceGrpc.SupplierServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(SupplierServiceGrpc.SupplierServiceBlockingStub.class); getSupplierByCodeResp = rpcStub.getSupplierByCode(getSupplierByCodeReq); }catch (Exception e){ e.printStackTrace(); } System.out.println(getSupplierByCodeResp.toString()); } static void getByProductCode(){ GongxiaoRpc.RpcHeader rpcHeader = GongxiaoRpc.RpcHeader.newBuilder().setUid("1").setTraceId("11111").build(); ProductStructure.GetByProductModelReq getByProductModelReq = ProductStructure.GetByProductModelReq.newBuilder() .setRpcHeader(rpcHeader) .setProductModel("111") .build(); ProductStructure.GetByProductModelResp getByProductCodeResp=null; try { ProductServiceGrpc.ProductServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(ProductServiceGrpc.ProductServiceBlockingStub.class); getByProductCodeResp = rpcStub.getByProductModel(getByProductModelReq); }catch (Exception e){ e.printStackTrace(); } System.out.println(getByProductCodeResp.toString()); } //ProjectService static void getProjectById(String projectId) { //1. 构建GetProjectByIdReq ProjectStructure.GetByProjectIdReq req = ProjectStructure.GetByProjectIdReq.newBuilder() .setProjectId(projectId) .build(); //2. 获取该gRpc对应的stub ProjectServiceGrpc.ProjectServiceBlockingStub blockingStub = RpcStubStore.getRpcStub(ProjectServiceGrpc.ProjectServiceBlockingStub.class); ProjectStructure.GetByProjectIdResp resp; try { //3. 进行gRpc调用 resp = blockingStub.getByProjectId(req); System.out.println("[RPC][response]: " + resp.toString()); } catch (Exception e) { e.printStackTrace(); } } static void generateFrontFlowSubtotal( Integer moneyFlow, String currencyCode, Long supplierId, Long projectId, Long beginDateLong, Long endDateLong) { SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalReq.Builder reqBuilder = SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalReq.newBuilder(); reqBuilder.setMoneyFlow(moneyFlow); reqBuilder.setCurrencyCode(currencyCode); reqBuilder.setSupplierId(supplierId); reqBuilder.setProjectId(projectId); reqBuilder.setBeginDate(beginDateLong); reqBuilder.setEndDate(endDateLong); SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalReq req = reqBuilder.build(); //2. 获取该gRpc对应的stub // ProjectServiceGrpc.ProjectServiceBlockingStub blockingStub = RpcStubStore.getRpcStub(ProjectServiceGrpc.ProjectServiceBlockingStub.class); SupplierCouponPostingServiceGrpc.SupplierCouponPostingServiceBlockingStub blockingStub = RpcStubStore.getRpcStub(SupplierCouponPostingServiceGrpc.SupplierCouponPostingServiceBlockingStub.class); // ProjectServiceStructure.GetProjectByIdResp resp; SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalResp resp; try { //3. 进行gRpc调用 resp = blockingStub.generateFrontFlowSubtotal(req); System.out.println("[RPC][response]: " + resp.toString()); System.out.println("调用成功了"); } catch (Exception e) { e.printStackTrace(); } } static void getProductInfo(){ ProductStructure.GetByProductIdReq productIdReq = ProductStructure.GetByProductIdReq.newBuilder() .setProductId(108) .setRpcHeader(GongxiaoRpc.RpcHeader.newBuilder() .setTraceId("1111") .setUid("123") .setUsername("ch")).build(); ProductServiceGrpc.ProductServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(ProductServiceGrpc.ProductServiceBlockingStub.class); ProductStructure.GetByProductIdResp productIdResp = rpcStub.getByProductId(productIdReq); String productCode = productIdResp.getProductBusiness().getCustomerProductCode(); System.out.println(productCode); } }
UTF-8
Java
7,485
java
FoundationDataServiceClient.java
Java
[ { "context": "tUid(\"123\")\n .setUsername(\"ch\")).build();\n\n ProductServiceGrpc.ProductSe", "end": 7006, "score": 0.9960979223251343, "start": 7004, "tag": "USERNAME", "value": "ch" } ]
null
[]
package com.yhglobal.gongxiao.grpc.client.foundation; import com.yhglobal.gongxiao.accountmanage.microservice.SupplierCouponPostingServiceGrpc; import com.yhglobal.gongxiao.accountmanage.microservice.SupplierCouponPostingServiceStructure; import com.yhglobal.gongxiao.foundation.product.microservice.ProductServiceGrpc; import com.yhglobal.gongxiao.foundation.product.microservice.ProductStructure; import com.yhglobal.gongxiao.foundation.project.microservice.ProjectServiceGrpc; import com.yhglobal.gongxiao.foundation.project.microservice.ProjectStructure; import com.yhglobal.gongxiao.foundation.supplier.microservice.SupplierServiceGrpc; import com.yhglobal.gongxiao.foundation.supplier.microservice.SupplierStructure; import com.yhglobal.gongxiao.foundation.warehouse.microservice.WarehouseServiceGrpc; import com.yhglobal.gongxiao.foundation.warehouse.microservice.WarehouseStructure; import com.yhglobal.gongxiao.grpc.client.RpcStubStore; import com.yhglobal.gongxiao.microservice.GongxiaoRpc; /** * 调试时调用FoundationData服务 */ public class FoundationDataServiceClient { public static void main(String[] args) { getProjectById("1"); // selectAllDistributorAddress(); // getProjectById(146798161); // GongxiaoRpc.RpcHeader rpcHeader = RpcHeaderUtil.createRpcHeader(traceId, portalUserInfo.getUserId(), portalUserInfo.getUserName()); // generateFrontFlowSubtotal(306,"CNY",1L,146798161L,0L,9999999999999L); // generateFrontFlowSubtotal(-1, "CNY", 1L, 146798161L, 0L, 9999999999999L); // getProductInfo(); // getdistributorCoupon(); // getDistributorByDistributorId(); // getByProductCode(); // getSupplierByCode(); } static void getWarehouseById(){ GongxiaoRpc.RpcHeader rpcHeader = GongxiaoRpc.RpcHeader.newBuilder().setUid("1").setTraceId("11111").build(); WarehouseStructure.GetWarehouseByIdReq getWarehouseByIdReq = WarehouseStructure.GetWarehouseByIdReq.newBuilder() .setRpcHeader(rpcHeader) .setWarehouseId("1") .build(); WarehouseStructure.GetWarehouseByIdResp getWarehouseByIdResp=null; try { WarehouseServiceGrpc.WarehouseServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(WarehouseServiceGrpc.WarehouseServiceBlockingStub.class); getWarehouseByIdResp = rpcStub.getWarehouseById(getWarehouseByIdReq); }catch (Exception e){ e.printStackTrace(); } System.out.println(getWarehouseByIdResp.toString()); } static void getSupplierByCode(){ GongxiaoRpc.RpcHeader rpcHeader = GongxiaoRpc.RpcHeader.newBuilder().setUid("1").setTraceId("11111").build(); SupplierStructure.GetSupplierByCodeReq getSupplierByCodeReq = SupplierStructure.GetSupplierByCodeReq.newBuilder() .setRpcHeader(rpcHeader) .setSupplierCode("123456") .build(); SupplierStructure.GetSupplierByCodeResp getSupplierByCodeResp=null; try { SupplierServiceGrpc.SupplierServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(SupplierServiceGrpc.SupplierServiceBlockingStub.class); getSupplierByCodeResp = rpcStub.getSupplierByCode(getSupplierByCodeReq); }catch (Exception e){ e.printStackTrace(); } System.out.println(getSupplierByCodeResp.toString()); } static void getByProductCode(){ GongxiaoRpc.RpcHeader rpcHeader = GongxiaoRpc.RpcHeader.newBuilder().setUid("1").setTraceId("11111").build(); ProductStructure.GetByProductModelReq getByProductModelReq = ProductStructure.GetByProductModelReq.newBuilder() .setRpcHeader(rpcHeader) .setProductModel("111") .build(); ProductStructure.GetByProductModelResp getByProductCodeResp=null; try { ProductServiceGrpc.ProductServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(ProductServiceGrpc.ProductServiceBlockingStub.class); getByProductCodeResp = rpcStub.getByProductModel(getByProductModelReq); }catch (Exception e){ e.printStackTrace(); } System.out.println(getByProductCodeResp.toString()); } //ProjectService static void getProjectById(String projectId) { //1. 构建GetProjectByIdReq ProjectStructure.GetByProjectIdReq req = ProjectStructure.GetByProjectIdReq.newBuilder() .setProjectId(projectId) .build(); //2. 获取该gRpc对应的stub ProjectServiceGrpc.ProjectServiceBlockingStub blockingStub = RpcStubStore.getRpcStub(ProjectServiceGrpc.ProjectServiceBlockingStub.class); ProjectStructure.GetByProjectIdResp resp; try { //3. 进行gRpc调用 resp = blockingStub.getByProjectId(req); System.out.println("[RPC][response]: " + resp.toString()); } catch (Exception e) { e.printStackTrace(); } } static void generateFrontFlowSubtotal( Integer moneyFlow, String currencyCode, Long supplierId, Long projectId, Long beginDateLong, Long endDateLong) { SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalReq.Builder reqBuilder = SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalReq.newBuilder(); reqBuilder.setMoneyFlow(moneyFlow); reqBuilder.setCurrencyCode(currencyCode); reqBuilder.setSupplierId(supplierId); reqBuilder.setProjectId(projectId); reqBuilder.setBeginDate(beginDateLong); reqBuilder.setEndDate(endDateLong); SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalReq req = reqBuilder.build(); //2. 获取该gRpc对应的stub // ProjectServiceGrpc.ProjectServiceBlockingStub blockingStub = RpcStubStore.getRpcStub(ProjectServiceGrpc.ProjectServiceBlockingStub.class); SupplierCouponPostingServiceGrpc.SupplierCouponPostingServiceBlockingStub blockingStub = RpcStubStore.getRpcStub(SupplierCouponPostingServiceGrpc.SupplierCouponPostingServiceBlockingStub.class); // ProjectServiceStructure.GetProjectByIdResp resp; SupplierCouponPostingServiceStructure.GenerateFrontFlowSubtotalResp resp; try { //3. 进行gRpc调用 resp = blockingStub.generateFrontFlowSubtotal(req); System.out.println("[RPC][response]: " + resp.toString()); System.out.println("调用成功了"); } catch (Exception e) { e.printStackTrace(); } } static void getProductInfo(){ ProductStructure.GetByProductIdReq productIdReq = ProductStructure.GetByProductIdReq.newBuilder() .setProductId(108) .setRpcHeader(GongxiaoRpc.RpcHeader.newBuilder() .setTraceId("1111") .setUid("123") .setUsername("ch")).build(); ProductServiceGrpc.ProductServiceBlockingStub rpcStub = RpcStubStore.getRpcStub(ProductServiceGrpc.ProductServiceBlockingStub.class); ProductStructure.GetByProductIdResp productIdResp = rpcStub.getByProductId(productIdReq); String productCode = productIdResp.getProductBusiness().getCustomerProductCode(); System.out.println(productCode); } }
7,485
0.710665
0.696508
164
44.225609
38.788567
153
false
false
0
0
0
0
0
0
0.542683
false
false
0
4d67f6fcda69234ba6e4db684aafaece1855cc79
36,532,991,829,212
a4fd2039d9eee037c941920882a2a9011b0a4755
/app/src/main/java/com/arife/adnbikerider/mvp/m/interfaz/Route/RouteView.java
be793000a3de58d0baeb2d412a6811e4bc7c20dc
[]
no_license
lien0226/AdnBike_Rider
https://github.com/lien0226/AdnBike_Rider
e035cbd441df3d82c5e484e81bb0957eab36d047
fc1ef1f0fbf266473c75327e32f8d826bf7d562a
refs/heads/master
2023-05-21T07:49:57.046000
2021-05-29T20:01:54
2021-05-29T20:01:54
345,108,445
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.arife.adnbikerider.mvp.m.interfaz.Route; import com.arife.adnbikerider.mvc.m.RouteModel; import java.util.List; public interface RouteView { void OnSuccesRoute(String msg); void OnError(String error); }
UTF-8
Java
228
java
RouteView.java
Java
[]
null
[]
package com.arife.adnbikerider.mvp.m.interfaz.Route; import com.arife.adnbikerider.mvc.m.RouteModel; import java.util.List; public interface RouteView { void OnSuccesRoute(String msg); void OnError(String error); }
228
0.763158
0.763158
12
18
19.321836
52
false
false
0
0
0
0
0
0
0.416667
false
false
0
69dab0901413fc40665711024c0c9723da4f6623
34,471,407,541,018
974b11f60f8e17415da04349d1eba17e18f75b15
/src/Java/Chap4/StackApp.java
e66f10c4fbabc633485e3a3152fffda27174e826
[]
no_license
veteran97/PP2-1
https://github.com/veteran97/PP2-1
0ecd03becab3d18c5f7e9a72315243cd9afc98ef
63f13db892ab6f0a314d04575350203370a59341
refs/heads/master
2020-03-27T17:45:26.658000
2018-08-31T09:39:51
2018-08-31T09:39:51
146,872,289
1
0
null
true
2018-08-31T09:40:20
2018-08-31T09:40:20
2018-08-31T09:39:53
2018-08-31T09:39:52
35
0
0
0
null
false
null
class StackApp { private DeQueue deQueue; StackApp(int s) // constructor { deQueue = new DeQueue(s); } void push(char j) // put item on top of stack { deQueue.insertLeft(j); } char pop() { return deQueue.removeLeft(); } char peek() { return deQueue.peekLeft(); } boolean isEmpty() { return deQueue.isEmpty(); } void display(){ deQueue.display(); } boolean isFull() { return deQueue.isFull(); } public static void main(String[] args) { StackApp s = new StackApp(10); System.out.println(s.isEmpty()); s.push('a'); s.push('b'); s.push('c'); s.push('d'); char c = s.pop(); System.out.println(c); s.pop(); System.out.println(s.peek()); s.pop(); s.pop(); s.display(); System.out.println(s.isFull()); } }
UTF-8
Java
998
java
StackApp.java
Java
[]
null
[]
class StackApp { private DeQueue deQueue; StackApp(int s) // constructor { deQueue = new DeQueue(s); } void push(char j) // put item on top of stack { deQueue.insertLeft(j); } char pop() { return deQueue.removeLeft(); } char peek() { return deQueue.peekLeft(); } boolean isEmpty() { return deQueue.isEmpty(); } void display(){ deQueue.display(); } boolean isFull() { return deQueue.isFull(); } public static void main(String[] args) { StackApp s = new StackApp(10); System.out.println(s.isEmpty()); s.push('a'); s.push('b'); s.push('c'); s.push('d'); char c = s.pop(); System.out.println(c); s.pop(); System.out.println(s.peek()); s.pop(); s.pop(); s.display(); System.out.println(s.isFull()); } }
998
0.465932
0.463928
49
18.367348
14.018492
49
false
false
0
0
0
0
0
0
0.44898
false
false
0
1e3c8a4bf658b0afdfe1698839b68d407bbd9181
29,703,993,866,151
69616d6e4832724a258b7330f9000eb4c4dce1da
/src/main/java/com/qa/api/gorest/restclient/RestClient.java
7eadff0e0fa49a7d927dc0ffc96adc4692bd8774
[]
no_license
test-q/RestAssuredFrameWork
https://github.com/test-q/RestAssuredFrameWork
bffb291d18b86418513ba75453e2eed0f0ed214a
be72fc48a3b817f007570ec3dd4adb57ad1fdc37
refs/heads/master
2023-01-01T10:15:41.912000
2020-10-20T14:45:19
2020-10-20T14:45:19
304,356,758
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qa.api.gorest.restclient; import java.io.File; import java.util.List; import java.util.Map; import com.qa.api.gorest.util.TestUtil; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.http.Header; import io.restassured.http.Headers; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import junit.framework.Assert; /** * This class is having all HTTP methods which will call the APIs and having generic methods * for getting the response and fetch the value from response. * 4 HTTP METHODS >> GET POST PUT DELETE * @author rupal * */ public class RestClient { //HTTP METHODS -- GET, POST, PUT, DELETE /** * This is HTTP GET Method * @param domainUrl * @param serviceUrl * @param token * @param contentType * @param paramMap * @param log * @return Response from GET Call */ public static Response doGet(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token,contentType,queryParamMap, log); return getResponse("GET",request, serviceUrl); } return null; } /** * This is HTTP POST Method * @param domainUrl * @param serviceUrl * @param token * @param contentType * @param paramMap * @param pojoObj * @param log * @return Response from POST Call */ public static Response doPost(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, Object pojoObj, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token, contentType, queryParamMap, log); addPayload(request, pojoObj); return getResponse("POST", request, serviceUrl); } return null; } private static void addPayload(RequestSpecification request, Object pojoObj) { if (pojoObj instanceof Map) { //The java instanceof operator is used to test whether the object is an instance of the specified type //The instanceof in java is also known as type comparison operator because it compares the instance with type. //It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false. request.formParams((Map<String, String>) pojoObj); // here we type cast Object to Map } else { String jsonPayload = TestUtil.getSerializedJSON(pojoObj); request.body(jsonPayload); } } public static Response doPut(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, Object pojoObj, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token, contentType, queryParamMap, log); addPayload(request, pojoObj); return getResponse("PUT", request, serviceUrl); } return null; } public static Response doDelete(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token, contentType, queryParamMap, log); return getResponse("DELETE", request, serviceUrl); } return null; } private static boolean setDomainUrl(String domainUrl) { if(domainUrl == null || domainUrl.isEmpty()) { System.out.println("Please pass the correct Domain/Base URL. It is either null or blank"); return false; } try { RestAssured.baseURI = domainUrl; return true; }catch(Exception e){ System.out.println("Problem Occuured While Assigning Domain Url to Rest Assured..."); return false; } } private static RequestSpecification createRequest(Map<String, String> tokenMap, String contentType, Map<String, String> queryParamMap, boolean log) { RequestSpecification request = null; if(log) { request = RestAssured.given().log().all(); }else { request = RestAssured.given(); } if(tokenMap.size() > 0) { //tokenMap is map hence check size if size is not zero/null that time only execute this if statement. request.headers(tokenMap); } if(queryParamMap != null) { request.queryParams(queryParamMap); } if(contentType != null) { if(contentType.equalsIgnoreCase("JSON")) { request.contentType(ContentType.JSON); }else if(contentType.equalsIgnoreCase("XML")) { request.contentType(ContentType.XML); }else if(contentType.equalsIgnoreCase("TEXT")){ request.contentType(ContentType.TEXT); }else if(contentType.equalsIgnoreCase("MULTIPART")){ //There is no ContentType as "multipart" so how to add "multipart" content type. request.multiPart("image", new File("C:/Users/rupal/OneDrive/Pictures/Saved Pictures/1.jpg")); } } return request; } private static Response getResponse(String httpMethod, RequestSpecification request, String serviceUrl) { Response response = null; switch(httpMethod) { case "GET": response = request.get(serviceUrl); break; case "POST": response = request.post(serviceUrl); break; case "PUT": response = request.put(serviceUrl); break; case "DELETE": response = request.delete(serviceUrl); break; default: System.out.println("Please Pass Correct HTTP Method...."); break; } return response; } /** * This method Validate response status code * @param response */ public static void getStatusCode(Response response) { if(response != null) { int code = response.getStatusCode(); System.out.println("Response Status Code Is: " +code); Assert.assertEquals(200, code); }else { System.out.println("Something wrong in Response."); } } /** * This method return json path * @param response * @return JsonPath */ public static JsonPath getJsonPath(Response response) { if(response != null) { JsonPath jPath = response.jsonPath(); return jPath; }else { System.out.println("Something wrong in Response"); return null; } } /** * This method return Header Name * @param response * @param headerName * @return Header Name in string format */ public static String getHeaderValue(Response response, String headerName) { if(response != null) { return response.getHeader(headerName); }else { System.out.println("Something wrong in Response"); return null; } } /** * * @param response * @return Header size */ public static int getResponseHeaderCount(Response response) { Headers headers = response.getHeaders(); System.out.println("Response Header Count Is : " +headers.size()); return headers.size(); } /** * * @param response * @return */ public static List<Header> getResponseHeaders(Response response) { Headers headers = response.getHeaders(); List<Header> headerList = headers.asList(); System.out.println("==============Response Header List=============="); System.out.println(headerList); System.out.println("==============================================="); return headerList; } /** * This method display Response in Pretty Print format * @param response */ public static void getPrettyResponsePrint(Response response) { System.out.println("==============Response In Pretty Format============"); response.prettyPrint(); } }
UTF-8
Java
7,440
java
RestClient.java
Java
[ { "context": "* 4 HTTP METHODS >> GET POST PUT DELETE\n * @author rupal\n *\n */\npublic class RestClient {\n\t//HTTP METHODS ", "end": 683, "score": 0.9994450807571411, "start": 678, "tag": "USERNAME", "value": "rupal" } ]
null
[]
package com.qa.api.gorest.restclient; import java.io.File; import java.util.List; import java.util.Map; import com.qa.api.gorest.util.TestUtil; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.http.Header; import io.restassured.http.Headers; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import junit.framework.Assert; /** * This class is having all HTTP methods which will call the APIs and having generic methods * for getting the response and fetch the value from response. * 4 HTTP METHODS >> GET POST PUT DELETE * @author rupal * */ public class RestClient { //HTTP METHODS -- GET, POST, PUT, DELETE /** * This is HTTP GET Method * @param domainUrl * @param serviceUrl * @param token * @param contentType * @param paramMap * @param log * @return Response from GET Call */ public static Response doGet(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token,contentType,queryParamMap, log); return getResponse("GET",request, serviceUrl); } return null; } /** * This is HTTP POST Method * @param domainUrl * @param serviceUrl * @param token * @param contentType * @param paramMap * @param pojoObj * @param log * @return Response from POST Call */ public static Response doPost(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, Object pojoObj, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token, contentType, queryParamMap, log); addPayload(request, pojoObj); return getResponse("POST", request, serviceUrl); } return null; } private static void addPayload(RequestSpecification request, Object pojoObj) { if (pojoObj instanceof Map) { //The java instanceof operator is used to test whether the object is an instance of the specified type //The instanceof in java is also known as type comparison operator because it compares the instance with type. //It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false. request.formParams((Map<String, String>) pojoObj); // here we type cast Object to Map } else { String jsonPayload = TestUtil.getSerializedJSON(pojoObj); request.body(jsonPayload); } } public static Response doPut(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, Object pojoObj, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token, contentType, queryParamMap, log); addPayload(request, pojoObj); return getResponse("PUT", request, serviceUrl); } return null; } public static Response doDelete(String domainUrl, String serviceUrl, Map<String, String> token, String contentType, Map<String, String> queryParamMap, boolean log) { if(setDomainUrl(domainUrl)) { RequestSpecification request = createRequest(token, contentType, queryParamMap, log); return getResponse("DELETE", request, serviceUrl); } return null; } private static boolean setDomainUrl(String domainUrl) { if(domainUrl == null || domainUrl.isEmpty()) { System.out.println("Please pass the correct Domain/Base URL. It is either null or blank"); return false; } try { RestAssured.baseURI = domainUrl; return true; }catch(Exception e){ System.out.println("Problem Occuured While Assigning Domain Url to Rest Assured..."); return false; } } private static RequestSpecification createRequest(Map<String, String> tokenMap, String contentType, Map<String, String> queryParamMap, boolean log) { RequestSpecification request = null; if(log) { request = RestAssured.given().log().all(); }else { request = RestAssured.given(); } if(tokenMap.size() > 0) { //tokenMap is map hence check size if size is not zero/null that time only execute this if statement. request.headers(tokenMap); } if(queryParamMap != null) { request.queryParams(queryParamMap); } if(contentType != null) { if(contentType.equalsIgnoreCase("JSON")) { request.contentType(ContentType.JSON); }else if(contentType.equalsIgnoreCase("XML")) { request.contentType(ContentType.XML); }else if(contentType.equalsIgnoreCase("TEXT")){ request.contentType(ContentType.TEXT); }else if(contentType.equalsIgnoreCase("MULTIPART")){ //There is no ContentType as "multipart" so how to add "multipart" content type. request.multiPart("image", new File("C:/Users/rupal/OneDrive/Pictures/Saved Pictures/1.jpg")); } } return request; } private static Response getResponse(String httpMethod, RequestSpecification request, String serviceUrl) { Response response = null; switch(httpMethod) { case "GET": response = request.get(serviceUrl); break; case "POST": response = request.post(serviceUrl); break; case "PUT": response = request.put(serviceUrl); break; case "DELETE": response = request.delete(serviceUrl); break; default: System.out.println("Please Pass Correct HTTP Method...."); break; } return response; } /** * This method Validate response status code * @param response */ public static void getStatusCode(Response response) { if(response != null) { int code = response.getStatusCode(); System.out.println("Response Status Code Is: " +code); Assert.assertEquals(200, code); }else { System.out.println("Something wrong in Response."); } } /** * This method return json path * @param response * @return JsonPath */ public static JsonPath getJsonPath(Response response) { if(response != null) { JsonPath jPath = response.jsonPath(); return jPath; }else { System.out.println("Something wrong in Response"); return null; } } /** * This method return Header Name * @param response * @param headerName * @return Header Name in string format */ public static String getHeaderValue(Response response, String headerName) { if(response != null) { return response.getHeader(headerName); }else { System.out.println("Something wrong in Response"); return null; } } /** * * @param response * @return Header size */ public static int getResponseHeaderCount(Response response) { Headers headers = response.getHeaders(); System.out.println("Response Header Count Is : " +headers.size()); return headers.size(); } /** * * @param response * @return */ public static List<Header> getResponseHeaders(Response response) { Headers headers = response.getHeaders(); List<Header> headerList = headers.asList(); System.out.println("==============Response Header List=============="); System.out.println(headerList); System.out.println("==============================================="); return headerList; } /** * This method display Response in Pretty Print format * @param response */ public static void getPrettyResponsePrint(Response response) { System.out.println("==============Response In Pretty Format============"); response.prettyPrint(); } }
7,440
0.705914
0.705108
250
28.76
32.977543
180
false
false
0
0
0
0
0
0
2.26
false
false
0
a62f6296225dc686a2f183414e14a4b7ffff7381
30,477,087,978,622
aa4b15834e1c23d6a1dfdf41720ac4b78e7126e8
/ondex-opt/modules-opt/decypher/src/main/java/net/sourceforge/ondex/mapping/paralogprediction/SequenceAlignmentProgramArgumentDefinition.java
cc8bd5d1931f824ccacaa8026300d720ec6ede26
[ "MIT" ]
permissive
Rothamsted/ondex-knet-builder
https://github.com/Rothamsted/ondex-knet-builder
2f013af2acca6df283d4aa1e43b8790574581c5f
1abc57442c7aa467f002c650b5cb990445474fa3
refs/heads/master
2021-05-23T02:37:52.301000
2021-05-21T21:21:31
2021-05-21T21:21:31
82,045,610
3
7
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.sourceforge.ondex.mapping.paralogprediction; import net.sourceforge.ondex.InvalidPluginArgumentException; import net.sourceforge.ondex.args.NonContinuousArgumentDefinition; import net.sourceforge.ondex.args.StringArgumentDefinition; /** * Defines the Sequence Alignment Programs valid for this mapping method * * @author hindlem */ public class SequenceAlignmentProgramArgumentDefinition extends StringArgumentDefinition implements NonContinuousArgumentDefinition<String> { // public static final String BLAST = "blast"; // public static final String PATTERN_HUNTER = "patternhunter"; // public static final String FSA_BLAST = "fsablast"; public static final String DECYPHER = "decypher"; public SequenceAlignmentProgramArgumentDefinition(String name, boolean required, String defaultValue) { super(name, "The Aligment program to use e.g. blast/patternhunter/fsablast", required, defaultValue, false); } public String[] getValidValues() { return new String[]{DECYPHER}; } @Override public void isValidArgument(Object obj) throws InvalidPluginArgumentException { if (obj instanceof String) { String sequence = ((String) obj); if (sequence.length() > 0) { for (Object value : getValidValues()) { if (sequence.equalsIgnoreCase((String) value)) { return; } } throw new InvalidPluginArgumentException(sequence + " is not a valid argument for " + getName()); } throw new InvalidPluginArgumentException("Value is empty for " + getName()); } throw new InvalidPluginArgumentException("A " + this.getName() + " argument is required to be specified as a String for " + getName()); } }
UTF-8
Java
1,873
java
SequenceAlignmentProgramArgumentDefinition.java
Java
[ { "context": "rams valid for this mapping method\r\n *\r\n * @author hindlem\r\n */\r\npublic class SequenceAlignmentProgramArgume", "end": 354, "score": 0.9991817474365234, "start": 347, "tag": "USERNAME", "value": "hindlem" } ]
null
[]
package net.sourceforge.ondex.mapping.paralogprediction; import net.sourceforge.ondex.InvalidPluginArgumentException; import net.sourceforge.ondex.args.NonContinuousArgumentDefinition; import net.sourceforge.ondex.args.StringArgumentDefinition; /** * Defines the Sequence Alignment Programs valid for this mapping method * * @author hindlem */ public class SequenceAlignmentProgramArgumentDefinition extends StringArgumentDefinition implements NonContinuousArgumentDefinition<String> { // public static final String BLAST = "blast"; // public static final String PATTERN_HUNTER = "patternhunter"; // public static final String FSA_BLAST = "fsablast"; public static final String DECYPHER = "decypher"; public SequenceAlignmentProgramArgumentDefinition(String name, boolean required, String defaultValue) { super(name, "The Aligment program to use e.g. blast/patternhunter/fsablast", required, defaultValue, false); } public String[] getValidValues() { return new String[]{DECYPHER}; } @Override public void isValidArgument(Object obj) throws InvalidPluginArgumentException { if (obj instanceof String) { String sequence = ((String) obj); if (sequence.length() > 0) { for (Object value : getValidValues()) { if (sequence.equalsIgnoreCase((String) value)) { return; } } throw new InvalidPluginArgumentException(sequence + " is not a valid argument for " + getName()); } throw new InvalidPluginArgumentException("Value is empty for " + getName()); } throw new InvalidPluginArgumentException("A " + this.getName() + " argument is required to be specified as a String for " + getName()); } }
1,873
0.668446
0.667912
44
40.56818
39.792873
143
false
false
0
0
0
0
0
0
0.545455
false
false
0
7329bbbe46ee03cc31efbbd37252abbf3d426cc1
33,002,528,756,764
965aee1f99936a905b9a30ad228a25575b3e0c0f
/src/main/java/com/example/tolist/TODO/service/UserService.java
d5d6854333bb23d6e012e806905ba7517d80569c
[]
no_license
lionfiren/todo
https://github.com/lionfiren/todo
68c11667d433e304fbd4c762128372286f80aa01
469bd0c778a8f6c385633a018453d15d0d1685f8
refs/heads/master
2022-02-09T22:58:41.224000
2020-03-10T09:31:26
2020-03-10T09:31:26
245,570,940
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.tolist.TODO.service; import com.example.tolist.TODO.entity.User; public interface UserService { void save(User user); User findByUsername(String username); }
UTF-8
Java
192
java
UserService.java
Java
[]
null
[]
package com.example.tolist.TODO.service; import com.example.tolist.TODO.entity.User; public interface UserService { void save(User user); User findByUsername(String username); }
192
0.75
0.75
12
15
18.156725
43
false
false
0
0
0
0
0
0
0.333333
false
false
0
e18c548a94e59b4be20f42b8afcb31d1d8ae5992
34,067,680,629,238
acf300477760cee9b8338a38a8c718433dd0b06f
/cxc/src/main/java/com/luxsoft/siipap/cxc/swing/notas/ImpresionPorDescuento.java
d71a019cde10134fd0647de8ca3d8b2d78d7fd17
[]
no_license
ArtChl/siipapwin
https://github.com/ArtChl/siipapwin
507ead6438c29345bd76026160f5498e99b945e6
a8d2834f7de1c904d5ba58e6b45e4f8c9936bfa9
refs/heads/master
2016-09-01T10:56:04.312000
2009-06-08T23:27:41
2009-06-08T23:27:41
49,718,479
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.luxsoft.siipap.cxc.swing.notas; import java.util.Date; import com.jgoodies.binding.beans.Model; import com.luxsoft.siipap.cxc.domain.TiposDeNotas; /** * Bean para controlar la impresion de notas de credito * por descuento tipo U y V * * @author Ruben Cancino * */ public class ImpresionPorDescuento extends Model{ private Date fecha=new Date(); private TiposDeNotas tipo=TiposDeNotas.U; private int consecutivo=0; public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public TiposDeNotas getTipo() { return tipo; } public void setTipo(TiposDeNotas tipo) { this.tipo = tipo; } public int getConsecutivo() { return consecutivo; } public void setConsecutivo(int consecutivo) { this.consecutivo = consecutivo; } }
UTF-8
Java
855
java
ImpresionPorDescuento.java
Java
[ { "context": "ito\r\n * por descuento tipo U y V \r\n * \r\n * @author Ruben Cancino\r\n *\r\n */\r\npublic class ImpresionPorDescuento exte", "end": 290, "score": 0.9998703002929688, "start": 277, "tag": "NAME", "value": "Ruben Cancino" } ]
null
[]
package com.luxsoft.siipap.cxc.swing.notas; import java.util.Date; import com.jgoodies.binding.beans.Model; import com.luxsoft.siipap.cxc.domain.TiposDeNotas; /** * Bean para controlar la impresion de notas de credito * por descuento tipo U y V * * @author <NAME> * */ public class ImpresionPorDescuento extends Model{ private Date fecha=new Date(); private TiposDeNotas tipo=TiposDeNotas.U; private int consecutivo=0; public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public TiposDeNotas getTipo() { return tipo; } public void setTipo(TiposDeNotas tipo) { this.tipo = tipo; } public int getConsecutivo() { return consecutivo; } public void setConsecutivo(int consecutivo) { this.consecutivo = consecutivo; } }
848
0.691228
0.690058
42
18.357143
17.527966
55
false
false
0
0
0
0
0
0
1.047619
false
false
0
6c19600f1d83cdc73a429d652b3d176bbd2e0095
36,275,293,802,590
d586387c6b159a1a8bbffc12d67c2643481cda4c
/src/test/java/com/xmlangel/selenium/tests/TableDemoIT.java
b650a5ed68346be86d7aadebbfa8ac16d6eb086c
[]
no_license
xmlangel/Selenium
https://github.com/xmlangel/Selenium
3eec44e284edb1848fd73298ed837a985132f27f
9f299b7baabe1c6306c768a6a0b3ae380eca8924
refs/heads/master
2021-07-03T08:51:25.592000
2019-08-09T15:08:58
2019-08-09T15:08:58
35,152,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xmlangel.selenium.tests; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.xmlangel.selenium.DriverBase; import com.xmlangel.selenium.utils.Log; import com.xmlangel.selenium.utils.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xmlangel.selenium.page_objects.AwsHomePage; import com.xmlangel.selenium.utils.Table; import com.xmlangel.selenium.utils.Wait; import com.xmlangel.selenium.utils.Utils; public class TableDemoIT extends DriverBase { private static final Logger logger = LoggerFactory.getLogger(Log.class); private static final String awsID = ""; private static final String awsPassword = ""; private static final String awsLoginURL = ""; private static final String awsBucketUrl = ""; @Test(enabled = false) public void tableTest_01() throws Exception { WebDriver driver = getDriver(); Table getTable = new Table(); System.out.println("TEST01"); driver.get("http://elvery.net/demo/responsive-tables/"); driver.manage().window().maximize(); int tableNumber; tableNumber = getTable.table(driver, By.xpath("//table[contains(@class,'table-bordered')]"), "AAC"); logger.debug("Table Number: " + String.valueOf(tableNumber)); } @Test(enabled = false) public void tableTestÏ_table3() throws Exception { WebDriver driver = getDriver(); System.out.println("TEST03"); driver.get("http://toolsqa.wpengine.com/automation-practice-table"); driver.manage().window().maximize(); // Here we are storing the value from the cell in to the string variable String sCellValue = driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[1]/td[2]")).getText(); System.out.println(sCellValue); // Here we are clicking on the link of first row and the last column driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[1]/td[6]/a")).click(); System.out.println("Link has been clicked otherwise an exception would have thrown"); } @Test(enabled = false) public void tableTest_awsTable() throws Exception { WebDriver driver = getDriver(); Table getTable = new Table(); Wait wait = new Wait(); System.out.println("awstest"); driver.get(awsLoginURL); AwsHomePage awsHomePage = new AwsHomePage(); // AWS console 에접속하여 // 아이디와 패스워드를 입력하고 로그인한다. awsHomePage.enterUserID(awsID); awsHomePage.enterUserPassword(awsPassword); awsHomePage.submitSigninForm(); awsHomePage.selectLanguage("en"); // AWS 테이블의 마지막라인의 Viewing 을 기다리기위한엘리먼트 By paginationNumbering = By.id("paginationNumbering");// PabinationNumbering By prePage = By.xpath("//button[@type='submit'])[6]");// < 버튼. By nextPage = By.xpath("//button[@type='submit'])[7]");// > 버튼. By endofviewing = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/div[2]/div/span");// 맨하단의 driver.get(awsBucketUrl); wait.waitElementbyXpath(driver, paginationNumbering); // AWS Table Name By awsTable = By.xpath("//div[@id='c']"); // 전체 Table 의 갯수를 얻어온다. int totalTable = getTable.getTotalcountOfTable(driver, awsTable); // aws의 경우 3번째까지가기본, 4번째 라인이 Title 이다. 실제 데이터는 4번째 이후부터이므로 4를 빼준다. totalTable = totalTable - 4; logger.info(String.valueOf(totalTable)); // div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[290]/td[5] awsHomePage.clickStorageClass(); awsHomePage.clickStorageClass(); String sColValue = "Glacier"; // First loop will find the 'ClOCK TWER HOTEL' in the first column for (int i = 1; i <= totalTable; i++) { String sValue = null; By StorageClass = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[" + i + "]/td[5]"); sValue = driver.findElement(StorageClass).getText(); By S3FileName = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[" + i + "]/td[2]"); logger.info(driver.findElement(S3FileName).getText()); logger.info(String.valueOf(sValue)); if (sValue.equalsIgnoreCase(sColValue)) { logger.info(String.valueOf(i)); // div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[3]/td/awsui-checkbox/label/div By firstCheckBox = By.xpath( "// div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr/td/awsui-checkbox/label/div"); By NthCheckBox = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[" + i + "]/td/awsui-checkbox/label/div"); driver.findElement(NthCheckBox).click(); } } /* * Glacie 로 선택된 아이템들을 설정한다. archived Date : 30일 Retrieval option 리스토어 옵션 : "Bulk retrieval * (expected time: 5 - 12 hours) */ By S3Morebtn = By.xpath("//button[@type='button']"); driver.findElement(S3Morebtn).click(); By S3MoreMenuInitiateRestore = By.linkText("Initiate restore"); wait.waitElementbyXpath(driver, S3MoreMenuInitiateRestore); driver.findElement(S3MoreMenuInitiateRestore).click(); By InitiateRestoreTitle = By.xpath("//div[@id='confirmation-modal']/div/div/div"); wait.waitElementbyXpath(driver, InitiateRestoreTitle); By periodTextBox = By.id("awsui-textfield-0"); driver.findElement(periodTextBox).clear(); driver.findElement(periodTextBox).sendKeys("30"); driver .findElement( By.xpath("//div[@id='confirmation-modal']/div/div[3]/dialog-modal-content/div[2]")) .click(); // Retrieval Option ComboBox By RetrievalOption = By.xpath("//div[@id='dropdown']/div/div/div"); driver.findElement(RetrievalOption).click(); // "Bulk retrieval (expected time: 5 - 12 hours)"); By RetrievalOptionText = By.xpath("//table[@id='current-displayed-table']/tbody/tr/td/div"); logger.info(driver.findElement(RetrievalOptionText).getText()); // 리스토어Summit버튼 By RestoreSummitBtn = By.xpath("(//button[@type='submit'])[13]"); driver.findElement(RestoreSummitBtn).click(); } }
UTF-8
Java
6,791
java
TableDemoIT.java
Java
[ { "context": "rUserID(awsID);\n awsHomePage.enterUserPassword(awsPassword);\n awsHomePage.submitSigninForm();\n ", "end": 2703, "score": 0.8718399405479431, "start": 2700, "tag": "PASSWORD", "value": "aws" } ]
null
[]
package com.xmlangel.selenium.tests; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.xmlangel.selenium.DriverBase; import com.xmlangel.selenium.utils.Log; import com.xmlangel.selenium.utils.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xmlangel.selenium.page_objects.AwsHomePage; import com.xmlangel.selenium.utils.Table; import com.xmlangel.selenium.utils.Wait; import com.xmlangel.selenium.utils.Utils; public class TableDemoIT extends DriverBase { private static final Logger logger = LoggerFactory.getLogger(Log.class); private static final String awsID = ""; private static final String awsPassword = ""; private static final String awsLoginURL = ""; private static final String awsBucketUrl = ""; @Test(enabled = false) public void tableTest_01() throws Exception { WebDriver driver = getDriver(); Table getTable = new Table(); System.out.println("TEST01"); driver.get("http://elvery.net/demo/responsive-tables/"); driver.manage().window().maximize(); int tableNumber; tableNumber = getTable.table(driver, By.xpath("//table[contains(@class,'table-bordered')]"), "AAC"); logger.debug("Table Number: " + String.valueOf(tableNumber)); } @Test(enabled = false) public void tableTestÏ_table3() throws Exception { WebDriver driver = getDriver(); System.out.println("TEST03"); driver.get("http://toolsqa.wpengine.com/automation-practice-table"); driver.manage().window().maximize(); // Here we are storing the value from the cell in to the string variable String sCellValue = driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[1]/td[2]")).getText(); System.out.println(sCellValue); // Here we are clicking on the link of first row and the last column driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[1]/td[6]/a")).click(); System.out.println("Link has been clicked otherwise an exception would have thrown"); } @Test(enabled = false) public void tableTest_awsTable() throws Exception { WebDriver driver = getDriver(); Table getTable = new Table(); Wait wait = new Wait(); System.out.println("awstest"); driver.get(awsLoginURL); AwsHomePage awsHomePage = new AwsHomePage(); // AWS console 에접속하여 // 아이디와 패스워드를 입력하고 로그인한다. awsHomePage.enterUserID(awsID); awsHomePage.enterUserPassword(awsPassword); awsHomePage.submitSigninForm(); awsHomePage.selectLanguage("en"); // AWS 테이블의 마지막라인의 Viewing 을 기다리기위한엘리먼트 By paginationNumbering = By.id("paginationNumbering");// PabinationNumbering By prePage = By.xpath("//button[@type='submit'])[6]");// < 버튼. By nextPage = By.xpath("//button[@type='submit'])[7]");// > 버튼. By endofviewing = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/div[2]/div/span");// 맨하단의 driver.get(awsBucketUrl); wait.waitElementbyXpath(driver, paginationNumbering); // AWS Table Name By awsTable = By.xpath("//div[@id='c']"); // 전체 Table 의 갯수를 얻어온다. int totalTable = getTable.getTotalcountOfTable(driver, awsTable); // aws의 경우 3번째까지가기본, 4번째 라인이 Title 이다. 실제 데이터는 4번째 이후부터이므로 4를 빼준다. totalTable = totalTable - 4; logger.info(String.valueOf(totalTable)); // div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[290]/td[5] awsHomePage.clickStorageClass(); awsHomePage.clickStorageClass(); String sColValue = "Glacier"; // First loop will find the 'ClOCK TWER HOTEL' in the first column for (int i = 1; i <= totalTable; i++) { String sValue = null; By StorageClass = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[" + i + "]/td[5]"); sValue = driver.findElement(StorageClass).getText(); By S3FileName = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[" + i + "]/td[2]"); logger.info(driver.findElement(S3FileName).getText()); logger.info(String.valueOf(sValue)); if (sValue.equalsIgnoreCase(sColValue)) { logger.info(String.valueOf(i)); // div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[3]/td/awsui-checkbox/label/div By firstCheckBox = By.xpath( "// div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr/td/awsui-checkbox/label/div"); By NthCheckBox = By.xpath( "//div[@id='c']/div/div/awsui-tabs/div/div/div/span/div/ng-include/div/div[2]/table/tbody/tr[" + i + "]/td/awsui-checkbox/label/div"); driver.findElement(NthCheckBox).click(); } } /* * Glacie 로 선택된 아이템들을 설정한다. archived Date : 30일 Retrieval option 리스토어 옵션 : "Bulk retrieval * (expected time: 5 - 12 hours) */ By S3Morebtn = By.xpath("//button[@type='button']"); driver.findElement(S3Morebtn).click(); By S3MoreMenuInitiateRestore = By.linkText("Initiate restore"); wait.waitElementbyXpath(driver, S3MoreMenuInitiateRestore); driver.findElement(S3MoreMenuInitiateRestore).click(); By InitiateRestoreTitle = By.xpath("//div[@id='confirmation-modal']/div/div/div"); wait.waitElementbyXpath(driver, InitiateRestoreTitle); By periodTextBox = By.id("awsui-textfield-0"); driver.findElement(periodTextBox).clear(); driver.findElement(periodTextBox).sendKeys("30"); driver .findElement( By.xpath("//div[@id='confirmation-modal']/div/div[3]/dialog-modal-content/div[2]")) .click(); // Retrieval Option ComboBox By RetrievalOption = By.xpath("//div[@id='dropdown']/div/div/div"); driver.findElement(RetrievalOption).click(); // "Bulk retrieval (expected time: 5 - 12 hours)"); By RetrievalOptionText = By.xpath("//table[@id='current-displayed-table']/tbody/tr/td/div"); logger.info(driver.findElement(RetrievalOptionText).getText()); // 리스토어Summit버튼 By RestoreSummitBtn = By.xpath("(//button[@type='submit'])[13]"); driver.findElement(RestoreSummitBtn).click(); } }
6,791
0.676857
0.667991
180
35.344444
30.398159
136
false
false
0
0
0
0
0
0
0.555556
false
false
0
acf177bd21a4a3e066fcefe7822f63b08076b1f4
1,898,375,604,425
d90f934ba7b25aa611b6b46bd72f1581a4d97bea
/hobbit-projects/hobbit-storm-projects/hobbit-storm-cache-state/src/main/java/com/voole/hobbit/cachestate/RefreshCmdSender.java
10788df8718fbcb2ca28c85946eda85f692147f2
[]
no_license
dangxia/voole
https://github.com/dangxia/voole
498cba5f6869f7a039aedbccf718f08238ad8684
e32320e768f71c020af6854c19262727c743d92e
refs/heads/master
2021-01-10T21:19:34.731000
2015-01-20T08:00:15
2015-01-20T08:00:15
21,857,750
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2014 BEIJING UNION VOOLE TECHNOLOGY CO., LTD */ package com.voole.hobbit.cachestate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import org.springframework.context.support.ClassPathXmlApplicationContext; import storm.trident.operation.TridentCollector; import storm.trident.spout.IBatchSpout; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; /** * @author XuehuiHe * @date 2014年6月9日 */ public class RefreshCmdSender implements IBatchSpout { public static final Fields OUTPUT_FIELDS = new Fields("cmds"); private ArrayBlockingQueue<String> blockingQueue; private ClassPathXmlApplicationContext cxt; @Override public void open(@SuppressWarnings("rawtypes") Map conf, TopologyContext context) { cxt = new ClassPathXmlApplicationContext("refresh-cache-spring.xml"); RefreshCmdAdder adder = cxt.getBean(RefreshCmdAdder.class); blockingQueue = adder.getBlockingQueue(); } @Override public void emitBatch(long batchId, TridentCollector collector) { try { List<String> cmds = new ArrayList<String>(); String cmd = blockingQueue.poll(200, TimeUnit.MILLISECONDS); while (cmd != null) { cmds.add(cmd); cmd = blockingQueue.poll(200, TimeUnit.MILLISECONDS); } if (cmds.size() > 0) { collector.emit(new Values(cmds)); } } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void ack(long batchId) { } @Override public void close() { if (cxt != null) { cxt.close(); } } @SuppressWarnings("rawtypes") @Override public Map getComponentConfiguration() { return null; } @Override public Fields getOutputFields() { return OUTPUT_FIELDS; } }
UTF-8
Java
1,849
java
RefreshCmdSender.java
Java
[ { "context": "mport backtype.storm.tuple.Values;\n\n/**\n * @author XuehuiHe\n * @date 2014年6月9日\n */\npublic class RefreshCmdSen", "end": 572, "score": 0.8375476598739624, "start": 564, "tag": "NAME", "value": "XuehuiHe" } ]
null
[]
/* * Copyright (C) 2014 BEIJING UNION VOOLE TECHNOLOGY CO., LTD */ package com.voole.hobbit.cachestate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import org.springframework.context.support.ClassPathXmlApplicationContext; import storm.trident.operation.TridentCollector; import storm.trident.spout.IBatchSpout; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; /** * @author XuehuiHe * @date 2014年6月9日 */ public class RefreshCmdSender implements IBatchSpout { public static final Fields OUTPUT_FIELDS = new Fields("cmds"); private ArrayBlockingQueue<String> blockingQueue; private ClassPathXmlApplicationContext cxt; @Override public void open(@SuppressWarnings("rawtypes") Map conf, TopologyContext context) { cxt = new ClassPathXmlApplicationContext("refresh-cache-spring.xml"); RefreshCmdAdder adder = cxt.getBean(RefreshCmdAdder.class); blockingQueue = adder.getBlockingQueue(); } @Override public void emitBatch(long batchId, TridentCollector collector) { try { List<String> cmds = new ArrayList<String>(); String cmd = blockingQueue.poll(200, TimeUnit.MILLISECONDS); while (cmd != null) { cmds.add(cmd); cmd = blockingQueue.poll(200, TimeUnit.MILLISECONDS); } if (cmds.size() > 0) { collector.emit(new Values(cmds)); } } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void ack(long batchId) { } @Override public void close() { if (cxt != null) { cxt.close(); } } @SuppressWarnings("rawtypes") @Override public Map getComponentConfiguration() { return null; } @Override public Fields getOutputFields() { return OUTPUT_FIELDS; } }
1,849
0.741725
0.732501
77
22.935064
21.593853
74
false
false
0
0
0
0
0
0
1.467533
false
false
0
04db7510b9209a79e5d47cea1aaf445ac78743b9
33,689,723,516,401
f4da33c4edfe0762703de80f0f44c84c69008fce
/src/main/java/com/bielu/gpw/domain/AbstractStatistics.java
0755e781cbf41e267e0a30d3293397b0905b85f7
[]
no_license
doibay/openshift-playground
https://github.com/doibay/openshift-playground
9368265927d3cc4cfe7775c13ad3bdf2cb923cc7
8a10d2c4f95343ef3a485fd3d48235cde98c47f9
refs/heads/master
2020-12-24T06:17:52.162000
2015-09-24T18:29:25
2015-09-24T18:29:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bielu.gpw.domain; import java.math.BigDecimal; import java.math.RoundingMode; import javax.xml.bind.annotation.XmlAttribute; import com.bielu.gpw.Util; public abstract class AbstractStatistics { @XmlAttribute(name = "iv") String initValue; @XmlAttribute(name = "vnet") String valueNet; @XmlAttribute(name = "pnet") String profitNet; @XmlAttribute(name = "ptaxed") String profitNetTaxed; @XmlAttribute(name = "r") String rate; public AbstractStatistics() { } protected AbstractStatistics(Investment initial, Investment current) { if (initial == null || current == null) { return; } initValue = format(initial.value()); valueNet = format(current.netValue()); BigDecimal profitNet = current.netValue().subtract(initial.value()); this.profitNet = format(profitNet); if (profitNet.intValue() > 0) { profitNetTaxed = format(profitNet.multiply(Util.NET_PROFIT_RATE)); } else { profitNetTaxed = format(profitNet); } rate = format(profitNet.divide(current.netValue(), RoundingMode.FLOOR).multiply(BigDecimal.valueOf(100))) + "%"; } protected String format(BigDecimal value) { return String.format(Util.FORMAT_MONEY, value); } }
UTF-8
Java
1,225
java
AbstractStatistics.java
Java
[]
null
[]
package com.bielu.gpw.domain; import java.math.BigDecimal; import java.math.RoundingMode; import javax.xml.bind.annotation.XmlAttribute; import com.bielu.gpw.Util; public abstract class AbstractStatistics { @XmlAttribute(name = "iv") String initValue; @XmlAttribute(name = "vnet") String valueNet; @XmlAttribute(name = "pnet") String profitNet; @XmlAttribute(name = "ptaxed") String profitNetTaxed; @XmlAttribute(name = "r") String rate; public AbstractStatistics() { } protected AbstractStatistics(Investment initial, Investment current) { if (initial == null || current == null) { return; } initValue = format(initial.value()); valueNet = format(current.netValue()); BigDecimal profitNet = current.netValue().subtract(initial.value()); this.profitNet = format(profitNet); if (profitNet.intValue() > 0) { profitNetTaxed = format(profitNet.multiply(Util.NET_PROFIT_RATE)); } else { profitNetTaxed = format(profitNet); } rate = format(profitNet.divide(current.netValue(), RoundingMode.FLOOR).multiply(BigDecimal.valueOf(100))) + "%"; } protected String format(BigDecimal value) { return String.format(Util.FORMAT_MONEY, value); } }
1,225
0.703673
0.700408
42
28.166666
26.643963
116
false
false
0
0
0
0
0
0
0.571429
false
false
0
c975895e33d564aa5baffc27e34416cb1fd4afda
35,545,149,374,517
b7a7561b1c599350dbaa5ccc7d5053207037a03a
/src/main/java/com/sky/strategy/Test.java
bc8630e87e48a5d8c614b2de7bd7162475d427c6
[]
no_license
dhzy0425/strategy
https://github.com/dhzy0425/strategy
dc5e0186c8f2114c1207b421f623a63ae0858b07
1d129fe9c33718e5f6653828944a28d80bd11e7c
refs/heads/master
2021-01-19T21:48:09.059000
2017-08-23T13:07:34
2017-08-23T13:07:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sky.strategy; import com.sky.strategy.behavior.impl.CacheNoImpl; import com.sky.strategy.behavior.impl.CacheRedisImpl; import com.sky.strategy.behavior.impl.MRenderImpl; import com.sky.strategy.service.impl.MActServiceImpl; /** * Created by gantianxing on 2017/8/23. */ public class Test { private MySpringFactory mySpringFactory; public void commonRender(String type,String pageId){ mySpringFactory.doRender(type,pageId); } public static void main(String[] args) { MActServiceImpl mact = new MActServiceImpl(new MRenderImpl(),new CacheRedisImpl()); mact.setCacheBehavior(new CacheNoImpl()); String pageId="sdfsdfsfd"; mact.render(pageId); } }
UTF-8
Java
724
java
Test.java
Java
[ { "context": "y.service.impl.MActServiceImpl;\n\n/**\n * Created by gantianxing on 2017/8/23.\n */\npublic class Test {\n\n privat", "end": 267, "score": 0.9995572566986084, "start": 256, "tag": "USERNAME", "value": "gantianxing" } ]
null
[]
package com.sky.strategy; import com.sky.strategy.behavior.impl.CacheNoImpl; import com.sky.strategy.behavior.impl.CacheRedisImpl; import com.sky.strategy.behavior.impl.MRenderImpl; import com.sky.strategy.service.impl.MActServiceImpl; /** * Created by gantianxing on 2017/8/23. */ public class Test { private MySpringFactory mySpringFactory; public void commonRender(String type,String pageId){ mySpringFactory.doRender(type,pageId); } public static void main(String[] args) { MActServiceImpl mact = new MActServiceImpl(new MRenderImpl(),new CacheRedisImpl()); mact.setCacheBehavior(new CacheNoImpl()); String pageId="sdfsdfsfd"; mact.render(pageId); } }
724
0.726519
0.716851
26
26.846153
24.962576
91
false
false
0
0
0
0
0
0
0.538462
false
false
0
2413ba8f8d258048ac7bcb694eeec6acce95e1c3
35,313,221,146,505
9cbfd63e69d792e9b5354d40bff2cd2646c99af7
/pages-api/src/main/java/com/leoyon/pages/user/AccountDetailStatus.java
3c242ce8b5692ca9e663050700d2f8609396eb13
[]
no_license
sillyemperor/pages
https://github.com/sillyemperor/pages
8faf4e6a4671136aa8130829144356d999552c40
94ed7a9da47bd7d4e79f2f391f599288e4355c94
refs/heads/master
2018-10-15T05:01:02.103000
2018-10-15T03:46:13
2018-10-15T03:46:13
129,489,223
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leoyon.pages.user; import java.util.Arrays; import java.util.Optional; public enum AccountDetailStatus { BALANCE(1, "Balance"), Pending(2, "Pending"), LOCK(3, "Lock") ; private int value; private String label; public int getValue() { return value; } public String getLabel() { return label; } AccountDetailStatus(int value,String label){ this.value = value; this.label = label; } public static AccountDetailStatus getByVal(int value){ Optional<AccountDetailStatus> optional = Arrays.stream(AccountDetailStatus.values()).filter(st -> st.value == value) .findFirst(); return optional.isPresent()?optional.get():null; } }
UTF-8
Java
717
java
AccountDetailStatus.java
Java
[]
null
[]
package com.leoyon.pages.user; import java.util.Arrays; import java.util.Optional; public enum AccountDetailStatus { BALANCE(1, "Balance"), Pending(2, "Pending"), LOCK(3, "Lock") ; private int value; private String label; public int getValue() { return value; } public String getLabel() { return label; } AccountDetailStatus(int value,String label){ this.value = value; this.label = label; } public static AccountDetailStatus getByVal(int value){ Optional<AccountDetailStatus> optional = Arrays.stream(AccountDetailStatus.values()).filter(st -> st.value == value) .findFirst(); return optional.isPresent()?optional.get():null; } }
717
0.668061
0.663877
33
20.727272
24.373697
125
false
false
0
0
0
0
0
0
1.060606
false
false
0
c9b8581ea1803cb4eb42cfc823b262f07ebcd962
37,409,165,155,710
a436d6762c43e8ba5f586fef95fdaa22e8f5868f
/chapter8/chapter8_rensyu2/Book.java
c282d637d81e113c9a6fcf9dcb1dbb32546dcb3d
[]
no_license
rin-mso/Java_practice
https://github.com/rin-mso/Java_practice
5d31b1ae6f06ab2f43d802e0429307ddc76a6a69
87a734a8a0a0d39263e1447f94ca6e15bf59f64d
refs/heads/master
2022-12-19T03:04:58.966000
2020-09-30T04:48:48
2020-09-30T04:48:48
299,812,140
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter8_rensyu2; import java.util.Date; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class Book implements Comparable<Book>, Cloneable { private String title; private Date publishDate; private String comment; public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } // 書名と発行日が等価か判定 public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } // 古い順に並びかえ public int compareTo(Book o) { return CompareToBuilder.reflectionCompare(this, o); } // colone()を呼び出すと深いコピーによる複製 public Book clone() { Book b = new Book(); b.title = this.title; b.publishDate = this.publishDate; b.comment = this.comment; b.publishDate = (Date) this.publishDate.clone(); return b; } }
UTF-8
Java
1,045
java
Book.java
Java
[]
null
[]
package chapter8_rensyu2; import java.util.Date; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class Book implements Comparable<Book>, Cloneable { private String title; private Date publishDate; private String comment; public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } // 書名と発行日が等価か判定 public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } // 古い順に並びかえ public int compareTo(Book o) { return CompareToBuilder.reflectionCompare(this, o); } // colone()を呼び出すと深いコピーによる複製 public Book clone() { Book b = new Book(); b.title = this.title; b.publishDate = this.publishDate; b.comment = this.comment; b.publishDate = (Date) this.publishDate.clone(); return b; } }
1,045
0.678315
0.673176
37
25.297297
20.321556
59
false
false
0
0
0
0
0
0
0.540541
false
false
0
bbfc9c9921afaedabf13f668ff474483bba7cb37
36,326,833,415,177
d43b1cb3c37a7aed947e7d99d97fdea5f25a24f4
/org.ualerts.fixed/org.ualerts.fixed.service/src/main/java/org/ualerts/fixed/service/api/BuildingService.java
53d5aa29833fb58a529485fac261f2535c51d652
[ "Apache-2.0" ]
permissive
mukpal/ualerts-server
https://github.com/mukpal/ualerts-server
088dbb6ae6f3faaff69e04dedb6f6bc0b682393c
58e921d9251e548e86e84b8041df17f64e746bc2
refs/heads/master
2020-12-31T06:32:28.561000
2013-10-21T14:42:16
2013-10-21T14:42:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * File created on May 15, 2013 * * Copyright 2008-2013 Virginia Polytechnic Institute and State University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.ualerts.fixed.service.api; import org.ualerts.fixed.service.api.model.BuildingsModel; /** * A service to provide interaction with Building data. * * @author Michael Irwin */ public interface BuildingService { /** * Get all known active buildings. * @return All of the active buildings * @throws Exception Any exception that occurs during retrieval of buildings */ BuildingsModel getAllActiveBuildings() throws Exception; }
UTF-8
Java
1,140
java
BuildingService.java
Java
[ { "context": "vide interaction with Building data.\n *\n * @author Michael Irwin\n */\npublic interface BuildingService {\n\n /**\n ", "end": 866, "score": 0.9997966289520264, "start": 853, "tag": "NAME", "value": "Michael Irwin" } ]
null
[]
/* * File created on May 15, 2013 * * Copyright 2008-2013 Virginia Polytechnic Institute and State University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.ualerts.fixed.service.api; import org.ualerts.fixed.service.api.model.BuildingsModel; /** * A service to provide interaction with Building data. * * @author <NAME> */ public interface BuildingService { /** * Get all known active buildings. * @return All of the active buildings * @throws Exception Any exception that occurs during retrieval of buildings */ BuildingsModel getAllActiveBuildings() throws Exception; }
1,133
0.739474
0.723684
38
29
28.398479
78
false
false
0
0
0
0
0
0
0.236842
false
false
0
6f92dd642cbb3871b34045f360bf2b0d6f95897f
36,326,833,413,710
638a3916682dedf037ef464370d9095dcc8fe0ca
/src/main/java/hudson/plugins/scm_sync_configuration/strategies/model/PageMatcher.java
fa95a365582d66e339474ca9409c97aacb3bae94
[ "MIT" ]
permissive
malept/scm-sync-configuration-plugin
https://github.com/malept/scm-sync-configuration-plugin
d9383266f7a7bc867959bc18579498633270ff7b
984c56a553620ac60825808a3dcd0089ac6ffc81
refs/heads/master
2023-09-02T00:02:31.935000
2011-08-31T23:17:09
2011-08-31T23:17:09
2,303,474
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hudson.plugins.scm_sync_configuration.strategies.model; import java.util.regex.Pattern; public class PageMatcher { private Pattern urlRegex; private String targetFormName; public PageMatcher(String _urlRegexStr, String _targetFormName){ this.urlRegex = Pattern.compile(_urlRegexStr); this.targetFormName = _targetFormName; } public Pattern getUrlRegex() { return urlRegex; } public String getTargetFormName() { return targetFormName; } }
UTF-8
Java
491
java
PageMatcher.java
Java
[]
null
[]
package hudson.plugins.scm_sync_configuration.strategies.model; import java.util.regex.Pattern; public class PageMatcher { private Pattern urlRegex; private String targetFormName; public PageMatcher(String _urlRegexStr, String _targetFormName){ this.urlRegex = Pattern.compile(_urlRegexStr); this.targetFormName = _targetFormName; } public Pattern getUrlRegex() { return urlRegex; } public String getTargetFormName() { return targetFormName; } }
491
0.737271
0.737271
22
20.318182
20.737288
65
false
false
0
0
0
0
0
0
1.181818
false
false
0
13bd9806c27ed5b2a73740a9eb2e064016a8a667
26,371,099,250,355
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Shopping/target_source/src/com/target/mothership/model/guest/a/j.java
bab5ab3a488088a1ca682057c38326c271b061f2
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.target.mothership.model.guest.a; import com.target.mothership.model.common.a.g; import com.target.mothership.model.common.a.h; import com.target.mothership.services.x; // Referenced classes of package com.target.mothership.model.guest.a: // m public class j implements g { h mErrorSetTransformer; m mJsonTransformer; public j() { mJsonTransformer = new m(); } public com.target.mothership.model.guest.interfaces.a.j a(x x1) { com.target.mothership.model.guest.interfaces.a.j j1 = new com.target.mothership.model.guest.interfaces.a.j(); mErrorSetTransformer = new h(mJsonTransformer, j1); return (com.target.mothership.model.guest.interfaces.a.j)mErrorSetTransformer.a(x1); } public volatile Object a(Object obj) { return a((x)obj); } }
UTF-8
Java
1,029
java
j.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996098279953003, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.target.mothership.model.guest.a; import com.target.mothership.model.common.a.g; import com.target.mothership.model.common.a.h; import com.target.mothership.services.x; // Referenced classes of package com.target.mothership.model.guest.a: // m public class j implements g { h mErrorSetTransformer; m mJsonTransformer; public j() { mJsonTransformer = new m(); } public com.target.mothership.model.guest.interfaces.a.j a(x x1) { com.target.mothership.model.guest.interfaces.a.j j1 = new com.target.mothership.model.guest.interfaces.a.j(); mErrorSetTransformer = new h(mJsonTransformer, j1); return (com.target.mothership.model.guest.interfaces.a.j)mErrorSetTransformer.a(x1); } public volatile Object a(Object obj) { return a((x)obj); } }
1,019
0.694849
0.684159
37
26.81081
29.217579
117
false
false
0
0
0
0
0
0
0.324324
false
false
0
fa0cb179c2d3870e33baef480dda6d973c88741f
35,107,062,716,323
ff94cba0c7c74d07447a6d8fc752733964f1748b
/jpsave/src/main/java/org/jps/jpsave/controller/ViewController.java
be8129787d25e1bd34113041a95bc98e4f47b081
[]
no_license
J-Phiz/ExercicesSpring2021
https://github.com/J-Phiz/ExercicesSpring2021
79c637f88970b1186404c53a1b5b199dba228184
6092d19f37a6250cf51c1c9b381b800460bbc77f
refs/heads/main
2023-06-19T00:17:32.081000
2021-07-20T13:23:33
2021-07-20T13:23:33
361,693,222
0
0
null
true
2021-04-26T09:32:58
2021-04-26T09:32:57
2021-02-21T14:50:24
2021-02-21T14:50:22
0
0
0
0
null
false
false
package org.jps.jpsave.controller; import org.jps.jpsave.dto.OrderRequest; import org.jps.jpsave.exception.NotFoundException; import org.jps.jpsave.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/view") public class ViewController { @Autowired private OrderService orderService; @GetMapping() public String viewGet(Model model) { model.addAttribute("orderRequest", new OrderRequest()); model.addAttribute("orders", orderService.getOrders()); return "view"; } @GetMapping("{id}") public String viewDescription(Model model, @PathVariable("id") int id) throws NotFoundException { model.addAttribute("order", orderService.getOrderById(id)); return "view-by-id"; } @PostMapping(params="create") public String viewPostAdd(Model model, @ModelAttribute("orderRequest") OrderRequest orderRequest) { orderService.addOrderWithCity(orderRequest); return "redirect:/view"; } @PostMapping("/delete/{id}") public String viewPostSuppress(Model model, @PathVariable("id") int id) throws NotFoundException { orderService.deleteOrderById(id); return "redirect:/view"; } }
UTF-8
Java
1,392
java
ViewController.java
Java
[]
null
[]
package org.jps.jpsave.controller; import org.jps.jpsave.dto.OrderRequest; import org.jps.jpsave.exception.NotFoundException; import org.jps.jpsave.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/view") public class ViewController { @Autowired private OrderService orderService; @GetMapping() public String viewGet(Model model) { model.addAttribute("orderRequest", new OrderRequest()); model.addAttribute("orders", orderService.getOrders()); return "view"; } @GetMapping("{id}") public String viewDescription(Model model, @PathVariable("id") int id) throws NotFoundException { model.addAttribute("order", orderService.getOrderById(id)); return "view-by-id"; } @PostMapping(params="create") public String viewPostAdd(Model model, @ModelAttribute("orderRequest") OrderRequest orderRequest) { orderService.addOrderWithCity(orderRequest); return "redirect:/view"; } @PostMapping("/delete/{id}") public String viewPostSuppress(Model model, @PathVariable("id") int id) throws NotFoundException { orderService.deleteOrderById(id); return "redirect:/view"; } }
1,392
0.72342
0.72342
42
32.142857
27.914471
103
false
false
0
0
0
0
0
0
0.571429
false
false
0
8d1e79a153e7144c29ad1924e8730acd41d79aee
38,732,015,118,240
0ac0abaeb2548426b9c57062455ac6e5d4cd3250
/src/main/java/top/young/tools/util/EnDeCryptUtil.java
cd5f0e51ce0e70957a098024002f9b43c8d66ff5
[]
no_license
yangweixin/young-tools
https://github.com/yangweixin/young-tools
756a53a9db262e12ac55a906290d648672f564f4
f5577a75f4ad9f72886d10f6ed3b9f3c96084d1d
refs/heads/master
2021-09-03T21:49:37.635000
2018-01-12T08:48:42
2018-01-12T08:48:42
113,809,215
0
0
null
false
2018-01-12T08:48:34
2017-12-11T03:47:15
2017-12-11T03:50:59
2018-01-12T08:47:58
3,534
0
0
1
Java
false
null
package top.young.tools.util; import org.apache.commons.lang3.ArrayUtils; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class EnDeCryptUtil { /** * 加密 * @param content 需要加密的内容 * @param keyWord 加密密钥 * @return byte[] 加密后的字节数组 * @throws Exception */ private static byte[] encrypt(String content, String keyWord) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(keyWord.getBytes()); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 return cipher.doFinal(byteContent); // 加密 } /** * @param content 需要加密的内容 * @param password 加密密钥 * @return String 加密后的字符串 * @throws Exception */ private static String encrypttoStr(String content, String password) throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException { return parseByte2HexStr(encrypt(content, password)); } /**解密 * @param content 待解密内容 * @param keyWord 解密密钥 * @return byte[] * @throws Exception */ private static byte[] decrypt(byte[] content, String keyWord) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(keyWord.getBytes()); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 return cipher.doFinal(content); // 加密 } /** * @param content 待解密内容(字符串) * @param keyWord 解密密钥 * @return byte[] * @throws Exception */ private static byte[] decrypt(String content, String keyWord) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { return decrypt(parseHexStr2Byte(content), keyWord); } /**将二进制转换成16进制 * @param buf * @return String */ private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /**将16进制转换为二进制 * @param hexStr * @return byte[] */ private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return ArrayUtils.EMPTY_BYTE_ARRAY; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } private static String Key = "eJiAyOu^2014"; /**字符串解密**/ public static String decString(String inputString) { String outputString = ""; if (inputString == null || "".equals(inputString)) { return outputString; } try { outputString = new String(decrypt(inputString, Key)); } catch (Exception e) { System.out.println(e.getMessage()); outputString = inputString; } return outputString; } /**字符串加密**/ public static String encString(String inputString) { String outputString = ""; if (inputString == null || "".equals(inputString)) { return outputString; } try { outputString = encrypttoStr(inputString, Key); } catch (Exception e) { System.out.println( e.getMessage()); outputString = inputString; } return outputString; } }
UTF-8
Java
5,205
java
EnDeCryptUtil.java
Java
[ { "context": "rn result;\n }\n private static String Key = \"eJiAyOu^2014\";\n /**字符串解密**/\n public static String decStr", "end": 4072, "score": 0.9995397925376892, "start": 4060, "tag": "KEY", "value": "eJiAyOu^2014" } ]
null
[]
package top.young.tools.util; import org.apache.commons.lang3.ArrayUtils; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class EnDeCryptUtil { /** * 加密 * @param content 需要加密的内容 * @param keyWord 加密密钥 * @return byte[] 加密后的字节数组 * @throws Exception */ private static byte[] encrypt(String content, String keyWord) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(keyWord.getBytes()); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 return cipher.doFinal(byteContent); // 加密 } /** * @param content 需要加密的内容 * @param password 加密密钥 * @return String 加密后的字符串 * @throws Exception */ private static String encrypttoStr(String content, String password) throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException { return parseByte2HexStr(encrypt(content, password)); } /**解密 * @param content 待解密内容 * @param keyWord 解密密钥 * @return byte[] * @throws Exception */ private static byte[] decrypt(byte[] content, String keyWord) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(keyWord.getBytes()); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 return cipher.doFinal(content); // 加密 } /** * @param content 待解密内容(字符串) * @param keyWord 解密密钥 * @return byte[] * @throws Exception */ private static byte[] decrypt(String content, String keyWord) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { return decrypt(parseHexStr2Byte(content), keyWord); } /**将二进制转换成16进制 * @param buf * @return String */ private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /**将16进制转换为二进制 * @param hexStr * @return byte[] */ private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return ArrayUtils.EMPTY_BYTE_ARRAY; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } private static String Key = "eJiAyOu^2014"; /**字符串解密**/ public static String decString(String inputString) { String outputString = ""; if (inputString == null || "".equals(inputString)) { return outputString; } try { outputString = new String(decrypt(inputString, Key)); } catch (Exception e) { System.out.println(e.getMessage()); outputString = inputString; } return outputString; } /**字符串加密**/ public static String encString(String inputString) { String outputString = ""; if (inputString == null || "".equals(inputString)) { return outputString; } try { outputString = encrypttoStr(inputString, Key); } catch (Exception e) { System.out.println( e.getMessage()); outputString = inputString; } return outputString; } }
5,205
0.633902
0.625276
130
37.338463
36.841145
228
false
false
0
0
0
0
0
0
0.761538
false
false
0
423b426a04876c0cd649b34c019517f12edf528d
36,584,531,445,809
f6c19c77c3e73cefb46439464de8023ae6003d2f
/jsf/registration/registration/src/main/java/com/registration/ejb/SearchEJB.java
6bb8b7b98a46c7c2b7c963d380e5d84fb6ef9f24
[]
no_license
kenny999/javaee
https://github.com/kenny999/javaee
61ca196bc3d93ec5944f12b1bfa0e8e6c9fa7773
acee1b0067d8cc7f68440c5f3af10d8fa44409a3
refs/heads/master
2020-03-18T01:28:08.757000
2019-01-22T14:22:05
2019-01-22T14:22:05
134,143,295
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.registration.ejb; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.registration.persistence.RegisteredUser; @Stateless public class SearchEJB { @PersistenceContext private EntityManager em; @SuppressWarnings("unchecked") public List<RegisteredUser> searchUserWithPrefix(String userName) { Query q = em.createNamedQuery(RegisteredUser.FIND_USER_BY_USERNAMEPREFIX); q.setParameter(RegisteredUser.PARAMETER_USER_FIND_USER_BY_USERNAMEPREFIX, userName + "%"); return (List<RegisteredUser>) q.getResultList(); } @SuppressWarnings("unchecked") public boolean doesUserExist(String userName) { Query q = em.createNamedQuery(RegisteredUser.FIND_USER_BY_USERNAME_EXACT); q.setParameter(RegisteredUser.PARAMETER_USER_FIND_USER_BY_USERNAME_EXACT, userName); Object r = null; try { r = q.getSingleResult(); } catch (NoResultException e) { return false; } return r != null; } }
UTF-8
Java
1,089
java
SearchEJB.java
Java
[]
null
[]
package com.registration.ejb; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.registration.persistence.RegisteredUser; @Stateless public class SearchEJB { @PersistenceContext private EntityManager em; @SuppressWarnings("unchecked") public List<RegisteredUser> searchUserWithPrefix(String userName) { Query q = em.createNamedQuery(RegisteredUser.FIND_USER_BY_USERNAMEPREFIX); q.setParameter(RegisteredUser.PARAMETER_USER_FIND_USER_BY_USERNAMEPREFIX, userName + "%"); return (List<RegisteredUser>) q.getResultList(); } @SuppressWarnings("unchecked") public boolean doesUserExist(String userName) { Query q = em.createNamedQuery(RegisteredUser.FIND_USER_BY_USERNAME_EXACT); q.setParameter(RegisteredUser.PARAMETER_USER_FIND_USER_BY_USERNAME_EXACT, userName); Object r = null; try { r = q.getSingleResult(); } catch (NoResultException e) { return false; } return r != null; } }
1,089
0.780533
0.780533
37
28.432432
25.654188
92
false
false
0
0
0
0
0
0
1.459459
false
false
0
82a1e3e3a6982de11560bf0bfa7f60ef93e203e2
36,584,531,447,008
7aab974aa553edf91a82ceb7fe82d33a0f1c9f1d
/src/main/java/at/ac/tuwien/big/we16/ue3/DateUtil.java
7370269d49a0b319bdc1ff1b41662b20ef5c3efb
[]
no_license
Chrisi63/WebUE3
https://github.com/Chrisi63/WebUE3
283b873d4cffbcd740c135617d4b8edc99602413
9e3711cb69151a5e2cf379de540f8aac70bb77a9
refs/heads/master
2016-09-14T07:10:39.001000
2016-05-22T11:21:18
2016-05-22T11:21:18
58,160,241
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.ac.tuwien.big.we16.ue3; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Michael on 15.05.2016. */ public class DateUtil { public static Date parseDate(String inputdate) { if (!inputdate.equals("")) { Date date = null; try { if (date == null) { date = new SimpleDateFormat("dd.mm.yyyy").parse(inputdate); } } catch (ParseException pe) { date = null; } try { if (date == null) { date = new SimpleDateFormat("dd/mm/yyyy").parse(inputdate); } } catch (ParseException pe) { date = null; } try { if (date == null) { date = new SimpleDateFormat("dd-mm-yyyy").parse(inputdate); } } catch (ParseException pe) { date = null; } try { if (date == null) { date = new SimpleDateFormat("yyyy-mm-dd").parse(inputdate); } } catch (ParseException pe) { date = null; } return date; } return null; } }
UTF-8
Java
985
java
DateUtil.java
Java
[ { "context": "eFormat;\nimport java.util.Date;\n\n/**\n * Created by Michael on 15.05.2016.\n */\npublic class DateUtil {\n\t\n\tpub", "end": 153, "score": 0.9665952324867249, "start": 146, "tag": "NAME", "value": "Michael" } ]
null
[]
package at.ac.tuwien.big.we16.ue3; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Michael on 15.05.2016. */ public class DateUtil { public static Date parseDate(String inputdate) { if (!inputdate.equals("")) { Date date = null; try { if (date == null) { date = new SimpleDateFormat("dd.mm.yyyy").parse(inputdate); } } catch (ParseException pe) { date = null; } try { if (date == null) { date = new SimpleDateFormat("dd/mm/yyyy").parse(inputdate); } } catch (ParseException pe) { date = null; } try { if (date == null) { date = new SimpleDateFormat("dd-mm-yyyy").parse(inputdate); } } catch (ParseException pe) { date = null; } try { if (date == null) { date = new SimpleDateFormat("yyyy-mm-dd").parse(inputdate); } } catch (ParseException pe) { date = null; } return date; } return null; } }
985
0.593909
0.582741
55
16.90909
18.148151
64
false
false
0
0
0
0
0
0
2.436364
false
false
0
b31990dbe5266a4d5b47d0b2d31cd50b925ce878
37,495,064,515,955
aacb137c54e38e4b43e114959cae846a81143271
/springbookCh5/src/springbook/user/dao/UserDaoTest.java
9ac59e2902669c73e39ae18539efa437a923a365
[]
no_license
Han-Git/sts_project
https://github.com/Han-Git/sts_project
c6bda636fab466c0a727d40d30f8146ab3f43678
e94e1ae29d81ee615d87e2632ccafdf8eef1de62
refs/heads/master
2020-04-06T07:00:00.196000
2017-05-09T11:48:04
2017-05-09T11:48:04
50,900,633
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package springbook.user.dao; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import springbook.user.domain.Level; import springbook.user.domain.User; @RunWith(SpringJUnit4ClassRunner.class) // #p185 @ContextConfiguration(locations="/test-applicationContext.xml") // #p194 public class UserDaoTest { @Autowired private UserDao dao; //#p188 @Autowired private DataSource dataSource; private User user1; //#p183 private User user2; //#p183 private User user3; //#p183 @Before public void setUp(){ this.user1 = new User("jkonoury", "장지홍","springno1", Level.BASIC , 1,0,"test1@naver.com"); this.user2 = new User("jmh", "정명한","springno2", Level.SILVER , 55,10,"test2@naver.com"); this.user3 = new User("lyg", "이용규","springno3", Level.GOLD , 100,40,"test3@naver.com"); } @Test public void update(){ dao.deleteAll(); dao.add(user1); dao.add(user2); user1.setName("오민규"); user1.setPassword("spring06"); user1.setLevel(Level.GOLD); user1.setLogin(1000); user1.setRecommend(999); dao.update(user1); User user1update = dao.get(user1.getId()); checkSameUser(user1, user1update); User user2same = dao.get(user2.getId()); checkSameUser(user2, user2same); } @Test public void addAndGet() throws SQLException, ClassNotFoundException{ dao.deleteAll(); dao.add(user1); dao.add(user2); User userget1 = dao.get(user1.getId()); checkSameUser(userget1, user1); User userget2 = dao.get(user2.getId()); checkSameUser(userget2, user2); } private void checkSameUser(User user1, User user2){ assertThat(user1.getId(),is(user2.getId())); assertThat(user1.getName(),is(user2.getName())); assertThat(user1.getPassword(),is(user2.getPassword())); assertThat(user1.getLevel(),is(user2.getLevel())); assertThat(user1.getLogin(),is(user2.getLogin())); assertThat(user1.getRecommend(),is(user2.getRecommend())); } public static void main(String[] args)throws ClassNotFoundException, SQLException { JUnitCore.main("springbook.user.dao.UserDaoTest"); } }
UHC
Java
2,474
java
UserDaoTest.java
Java
[ { "context": "re\n\tpublic void setUp(){\n\t\tthis.user1 = new User(\"jkonoury\", \"장지홍\",\"springno1\", Level.BASIC , 1,0,\"test1@nav", "end": 960, "score": 0.9996601939201355, "start": 952, "tag": "USERNAME", "value": "jkonoury" }, { "context": "id setUp(){\n\t\tthis.user1 = new Us...
null
[]
package springbook.user.dao; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import springbook.user.domain.Level; import springbook.user.domain.User; @RunWith(SpringJUnit4ClassRunner.class) // #p185 @ContextConfiguration(locations="/test-applicationContext.xml") // #p194 public class UserDaoTest { @Autowired private UserDao dao; //#p188 @Autowired private DataSource dataSource; private User user1; //#p183 private User user2; //#p183 private User user3; //#p183 @Before public void setUp(){ this.user1 = new User("jkonoury", "장지홍","springno1", Level.BASIC , 1,0,"<EMAIL>"); this.user2 = new User("jmh", "정명한","springno2", Level.SILVER , 55,10,"<EMAIL>"); this.user3 = new User("lyg", "이용규","springno3", Level.GOLD , 100,40,"<EMAIL>"); } @Test public void update(){ dao.deleteAll(); dao.add(user1); dao.add(user2); user1.setName("오민규"); user1.setPassword("<PASSWORD>"); user1.setLevel(Level.GOLD); user1.setLogin(1000); user1.setRecommend(999); dao.update(user1); User user1update = dao.get(user1.getId()); checkSameUser(user1, user1update); User user2same = dao.get(user2.getId()); checkSameUser(user2, user2same); } @Test public void addAndGet() throws SQLException, ClassNotFoundException{ dao.deleteAll(); dao.add(user1); dao.add(user2); User userget1 = dao.get(user1.getId()); checkSameUser(userget1, user1); User userget2 = dao.get(user2.getId()); checkSameUser(userget2, user2); } private void checkSameUser(User user1, User user2){ assertThat(user1.getId(),is(user2.getId())); assertThat(user1.getName(),is(user2.getName())); assertThat(user1.getPassword(),is(user2.getPassword())); assertThat(user1.getLevel(),is(user2.getLevel())); assertThat(user1.getLogin(),is(user2.getLogin())); assertThat(user1.getRecommend(),is(user2.getRecommend())); } public static void main(String[] args)throws ClassNotFoundException, SQLException { JUnitCore.main("springbook.user.dao.UserDaoTest"); } }
2,452
0.731837
0.693878
89
26.52809
24.084631
92
false
false
0
0
0
0
0
0
2.101124
false
false
0
60f4a53fd2fdc5a2bca40ae40a4f9d9bbc0e4b8b
34,952,443,882,642
675a119ee3e1be1408e2a45a695688653592fe4f
/be/api/po-app/src/main/java/cz/covid/po/api/converter/HealthCheckConverter.java
0b5ae8a850de8b76b403283c019f7c3735716a07
[]
no_license
opus-x/po-app
https://github.com/opus-x/po-app
5683c2df9503658170424c9894d0dde1a8496a8e
5e34d560d4a03249b7de4f398291e5ea1e3dc316
refs/heads/master
2022-04-13T10:23:24.599000
2020-03-20T07:14:15
2020-03-20T07:16:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.covid.po.api.converter; import cz.covid.po.api.domain.model.HealthCheck; import cz.covid.po.api.generated.dto.HealthCheckDto; import cz.covid.po.api.generated.dto.SymptomEnum; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class HealthCheckConverter extends OneWayConverterBase<HealthCheck, HealthCheckDto> { private final HealthCheckResultConverter healthCheckResultConverter; private final CodebookConvertor codebookConvertor; @Override protected HealthCheckDto convertInternal(HealthCheck healthCheck) { HealthCheckDto result = new HealthCheckDto(); result.setAbleToDrive(healthCheck.getAbleToDrive()); if (healthCheck.getDryCoughDuration() != null) { result.setDryCoughDuration(SymptomEnum.fromValue(healthCheck.getDryCoughDuration().name())); } result.setFinalHealthCheckLocation(codebookConvertor.convert(healthCheck.getFinalHealthCheckLocation())); result.setHeadache(healthCheck.getHeadache()); result.setHealthCheckCode(healthCheck.getHealthCheckCode()); result.setHealthCheckType(codebookConvertor.convert(healthCheck.getHealthCheckType())); if (healthCheck.getHighTemperatureDuration() != null) { result.setHighTemperatureDuration(SymptomEnum.fromValue(healthCheck.getHighTemperatureDuration().name())); } result.setInfectedInContact(healthCheck.getInfectedInContact()); result.setInfectedInContactDate(healthCheck.getInfectedInContactDate()); result.setInfectedPhoneNumbers(healthCheck.getInfectedPhoneNumbers()); result.setPreferredHealthCheckLocation(codebookConvertor.convert(healthCheck.getPreferredHealthCheckLocation())); result.setSymtompsSince(healthCheck.getSymtompsSince()); result.setVisitedRiskArea(codebookConvertor.convert(healthCheck.getVisitedRiskArea())); result.setHealthCheckResults(healthCheckResultConverter.convert(healthCheck.getHealthCheckResults())); return result; } }
UTF-8
Java
2,095
java
HealthCheckConverter.java
Java
[]
null
[]
package cz.covid.po.api.converter; import cz.covid.po.api.domain.model.HealthCheck; import cz.covid.po.api.generated.dto.HealthCheckDto; import cz.covid.po.api.generated.dto.SymptomEnum; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class HealthCheckConverter extends OneWayConverterBase<HealthCheck, HealthCheckDto> { private final HealthCheckResultConverter healthCheckResultConverter; private final CodebookConvertor codebookConvertor; @Override protected HealthCheckDto convertInternal(HealthCheck healthCheck) { HealthCheckDto result = new HealthCheckDto(); result.setAbleToDrive(healthCheck.getAbleToDrive()); if (healthCheck.getDryCoughDuration() != null) { result.setDryCoughDuration(SymptomEnum.fromValue(healthCheck.getDryCoughDuration().name())); } result.setFinalHealthCheckLocation(codebookConvertor.convert(healthCheck.getFinalHealthCheckLocation())); result.setHeadache(healthCheck.getHeadache()); result.setHealthCheckCode(healthCheck.getHealthCheckCode()); result.setHealthCheckType(codebookConvertor.convert(healthCheck.getHealthCheckType())); if (healthCheck.getHighTemperatureDuration() != null) { result.setHighTemperatureDuration(SymptomEnum.fromValue(healthCheck.getHighTemperatureDuration().name())); } result.setInfectedInContact(healthCheck.getInfectedInContact()); result.setInfectedInContactDate(healthCheck.getInfectedInContactDate()); result.setInfectedPhoneNumbers(healthCheck.getInfectedPhoneNumbers()); result.setPreferredHealthCheckLocation(codebookConvertor.convert(healthCheck.getPreferredHealthCheckLocation())); result.setSymtompsSince(healthCheck.getSymtompsSince()); result.setVisitedRiskArea(codebookConvertor.convert(healthCheck.getVisitedRiskArea())); result.setHealthCheckResults(healthCheckResultConverter.convert(healthCheck.getHealthCheckResults())); return result; } }
2,095
0.781862
0.781862
40
51.375
37.073364
121
false
false
0
0
0
0
0
0
0.625
false
false
0
86e83f5a68ea14a85e9a79092ffe5bca5a1b8ed2
38,182,259,274,499
97c002bf660442346586f1353fbb1724efd25c5c
/bank.eltropy/src/main/java/bank/eltropy/domain/card/CardFacade.java
9db6b19b7e0125bfdbb4e5748c5b75fffc678649
[]
no_license
dahmed12/eltropyBankApp
https://github.com/dahmed12/eltropyBankApp
4e4a2ddb6b88accdd3a8a47dc7bee10bc88dc1c9
ffbc87c8c9d2323072b57bfb5f0bb576f738309d
refs/heads/master
2023-02-19T16:40:01.101000
2021-01-18T05:01:58
2021-01-18T05:01:58
330,400,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bank.eltropy.domain.card; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import pl.bank.app.domain.card.CreateCardClient; @Service @RequiredArgsConstructor public class CardFacade { private final CreateCardClient createCardClient; public void create(long accountId) { createCardClient.create(accountId); } }
UTF-8
Java
380
java
CardFacade.java
Java
[]
null
[]
package bank.eltropy.domain.card; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import pl.bank.app.domain.card.CreateCardClient; @Service @RequiredArgsConstructor public class CardFacade { private final CreateCardClient createCardClient; public void create(long accountId) { createCardClient.create(accountId); } }
380
0.789474
0.789474
17
21.352942
19.772057
52
false
false
0
0
0
0
0
0
0.352941
false
false
0
1f88634995094631a867e0bf2b092cb4efbfa5a5
36,206,574,336,411
3ff1f32f0333b014bdc5aa0dd6fe1e245878e3d1
/src/com/papersales/servlets/storage/NewProductstoragedetailServlet.java
20db23764f6c813ea3ac0ed8d2a443c3363199c4
[]
no_license
qcmoke/PaperSales
https://github.com/qcmoke/PaperSales
6cfa711b852c2eccd1fc21cf62bef7b345d4bece
33b4271ee589159a38af5da963e3e3b8c453cc68
refs/heads/master
2020-04-09T22:35:00.999000
2018-12-20T08:29:35
2018-12-20T08:29:35
160,632,349
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.papersales.servlets.storage; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.papersales.beans.Productstoragedetail; import com.papersales.services.StorageService; import com.papersales.services.impl.StorageServiceImpl; /** * Servlet implementation class NewProductstoragedetailServlet */ @WebServlet("/NewProductstoragedetailServlet") public class NewProductstoragedetailServlet extends HttpServlet { private static final long serialVersionUID = 1L; StorageService service; /** * @see HttpServlet#HttpServlet() */ public NewProductstoragedetailServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { service = new StorageServiceImpl(); String productStoId = request.getParameter("ProductStoId"); String productId = request.getParameter("ProductId"); double amount = Double.valueOf(request.getParameter("Amount")); String date = request.getParameter("Date"); double min = Double.valueOf(request.getParameter("Min")); Productstoragedetail new_psd = new Productstoragedetail(productStoId,productId,amount,date,min); boolean status = service.insertProductstoragedetail(new_psd); if (status == false) { request.getSession().setAttribute("msg", "添加失败"); response.sendRedirect(request.getContextPath() + "/view/storage/new_productStoragedetail.jsp"); return; } else { request.getSession().setAttribute("msg", "添加成功"); response.sendRedirect(request.getContextPath() + "/PagingForProductstoragedetailServlet"); return; } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
UTF-8
Java
2,318
java
NewProductstoragedetailServlet.java
Java
[]
null
[]
package com.papersales.servlets.storage; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.papersales.beans.Productstoragedetail; import com.papersales.services.StorageService; import com.papersales.services.impl.StorageServiceImpl; /** * Servlet implementation class NewProductstoragedetailServlet */ @WebServlet("/NewProductstoragedetailServlet") public class NewProductstoragedetailServlet extends HttpServlet { private static final long serialVersionUID = 1L; StorageService service; /** * @see HttpServlet#HttpServlet() */ public NewProductstoragedetailServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { service = new StorageServiceImpl(); String productStoId = request.getParameter("ProductStoId"); String productId = request.getParameter("ProductId"); double amount = Double.valueOf(request.getParameter("Amount")); String date = request.getParameter("Date"); double min = Double.valueOf(request.getParameter("Min")); Productstoragedetail new_psd = new Productstoragedetail(productStoId,productId,amount,date,min); boolean status = service.insertProductstoragedetail(new_psd); if (status == false) { request.getSession().setAttribute("msg", "添加失败"); response.sendRedirect(request.getContextPath() + "/view/storage/new_productStoragedetail.jsp"); return; } else { request.getSession().setAttribute("msg", "添加成功"); response.sendRedirect(request.getContextPath() + "/PagingForProductstoragedetailServlet"); return; } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
2,318
0.750217
0.749783
64
33.96875
31.74654
119
false
false
0
0
0
0
0
0
1.609375
false
false
0
99dc6dd54c11dc942dac5b2d39a6d953085ac213
34,961,033,828,243
6dc818eac00d33bb873402b40f2828090800b0c4
/DDIT_High_Java/high_java_class/javaNetwork/src/H_java_210120/URLTest2.java
a1e5debd9f377a2d2070a5e2ad38a7344d960cf8
[]
no_license
JeonghoonWon/ddit
https://github.com/JeonghoonWon/ddit
0df0d29db4a2a1e15a7754adddb6fb5ef87935be
478812565f3c2ed297e80bc69a5699c58c1dfdb8
refs/heads/master
2023-06-01T18:42:04.310000
2021-06-29T07:48:42
2021-06-29T07:48:42
342,758,724
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package H_java_210120; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class URLTest2 { public static void main(String[] args) throws IOException { // URL Connection 클래스 ==> 어플리케이션과 URL간의 통신 연결을 위한 클래스 // 특정 서버의 정보와 파일 내용을 가져와 출력하는 예제 URL url = new URL("https://www.naver.com/"); // 주어진 URL주소에 접속하기 위해 URLConnection 객체를 구한다. URLConnection urlCon = url.openConnection(); // Header정보 가져오기 Map<String,List<String>> headerMap = urlCon.getHeaderFields(); // headerMap의 key값과 value 값 출력하기 for(String headerKey : headerMap.keySet()) { System.out.println(headerKey +" : " + headerMap.get(headerKey)); } System.out.println("--------------------------------------------"); //URL 주소에 지정한 해당 문서의 내용 가져오기 // (index.html문서의 내용을 가져온다.) // 방법 1) ==> URL Connection 객체를 이용하는 방법 // byte 기반으로 처리 해야 함. // 파일 내용을 읽어오기 위한 스트림 객체 생성 /* InputStream is = urlCon.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); // 자료를 읽어와 화면에 출력하기 while(true) { String str = br.readLine(); // 한 줄씩 읽기 if(str==null) break; System.out.println(str); } br.close(); */ // 방법 2) ==> URL 객체의 openStream()메서드 이용하기 InputStream is2 = url.openStream(); InputStreamReader isr2 = new InputStreamReader(is2, "utf-8"); BufferedReader br2 = new BufferedReader(isr2); // 자료를 읽어와 화면에 출력하기 while(true) { String str = br2.readLine(); // 한 줄씩 읽기 if(str==null) break; System.out.println(str); } br2.close(); } } //
UTF-8
Java
2,127
java
URLTest2.java
Java
[]
null
[]
package H_java_210120; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class URLTest2 { public static void main(String[] args) throws IOException { // URL Connection 클래스 ==> 어플리케이션과 URL간의 통신 연결을 위한 클래스 // 특정 서버의 정보와 파일 내용을 가져와 출력하는 예제 URL url = new URL("https://www.naver.com/"); // 주어진 URL주소에 접속하기 위해 URLConnection 객체를 구한다. URLConnection urlCon = url.openConnection(); // Header정보 가져오기 Map<String,List<String>> headerMap = urlCon.getHeaderFields(); // headerMap의 key값과 value 값 출력하기 for(String headerKey : headerMap.keySet()) { System.out.println(headerKey +" : " + headerMap.get(headerKey)); } System.out.println("--------------------------------------------"); //URL 주소에 지정한 해당 문서의 내용 가져오기 // (index.html문서의 내용을 가져온다.) // 방법 1) ==> URL Connection 객체를 이용하는 방법 // byte 기반으로 처리 해야 함. // 파일 내용을 읽어오기 위한 스트림 객체 생성 /* InputStream is = urlCon.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); // 자료를 읽어와 화면에 출력하기 while(true) { String str = br.readLine(); // 한 줄씩 읽기 if(str==null) break; System.out.println(str); } br.close(); */ // 방법 2) ==> URL 객체의 openStream()메서드 이용하기 InputStream is2 = url.openStream(); InputStreamReader isr2 = new InputStreamReader(is2, "utf-8"); BufferedReader br2 = new BufferedReader(isr2); // 자료를 읽어와 화면에 출력하기 while(true) { String str = br2.readLine(); // 한 줄씩 읽기 if(str==null) break; System.out.println(str); } br2.close(); } } //
2,127
0.642653
0.632361
78
21.435898
20.222855
69
false
false
0
0
0
0
0
0
2
false
false
0
42188a41f1cd1538d1f4d09d28e31acf0b23ec26
11,690,901,044,822
1865e907a51471fcaa22508108b6b09e69f88e03
/Exam280216/Pr4Events.java
a3ed1d5bcf1c1ed846c684e17a42ac97daae1598
[]
no_license
gabbriela/Java
https://github.com/gabbriela/Java
768018d86071354f7aed576dcf48a7a6e5c850eb
ae5c64db2e528298397eaf3a4f25ac28344b5db7
refs/heads/master
2016-09-14T06:33:35.477000
2016-05-17T17:34:20
2016-05-17T17:34:20
56,510,507
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Exam280216; import sun.reflect.generics.tree.Tree; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Pr4Events { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); TreeMap<String, TreeMap<String, TreeSet<String>>> eventLog = new TreeMap<>(); // name #([A-Za-z]+): // place @([A-Za-z]+) // time (\d+:\d+) Pattern pattern = Pattern.compile("#([A-Za-z]+): @([A-Za-z]+)\\s*(\\d+:\\d+)"); int eventCount = scanner.nextInt(); scanner.nextLine(); String inputLine = ""; for (int i = 0; i < eventCount; i++) { inputLine = scanner.nextLine(); Matcher matcher = pattern.matcher(inputLine); boolean validData = matcher.find(); if (validData){ String personName = matcher.group(1); String eventPlace = matcher.group(2); String eventTime = matcher.group(3); //add place if(!(eventLog.containsKey(eventPlace))){ eventLog.put(eventPlace, new TreeMap<>()); eventLog.get(eventPlace).put(personName, new TreeSet<>()); eventLog.get(eventPlace).get(personName).add(eventTime); } else{ //add person if(!(eventLog.get(eventPlace).containsKey(personName))){ eventLog.get(eventPlace).put(personName, new TreeSet<>()); eventLog.get(eventPlace).get(personName).add(eventTime); } else{ eventLog.get(eventPlace).get(personName).add(eventTime); //eventLog.get(eventPlace).put(personName, eventLog.get(eventPlace).get(personName) + eventTime); } } } } System.out.println(); int counter = 1; eventLog.entrySet().stream().forEach(es -> { System.out.println(es.getKey() + ":"); es.getValue().entrySet().stream().forEach(set -> { System.out.printf("%d. %s -> ", counter, set.getKey()); System.out.print(String.join(", ", set.getValue())); System.out.println(""); }); }); } }
UTF-8
Java
2,635
java
Pr4Events.java
Java
[]
null
[]
package Exam280216; import sun.reflect.generics.tree.Tree; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Pr4Events { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); TreeMap<String, TreeMap<String, TreeSet<String>>> eventLog = new TreeMap<>(); // name #([A-Za-z]+): // place @([A-Za-z]+) // time (\d+:\d+) Pattern pattern = Pattern.compile("#([A-Za-z]+): @([A-Za-z]+)\\s*(\\d+:\\d+)"); int eventCount = scanner.nextInt(); scanner.nextLine(); String inputLine = ""; for (int i = 0; i < eventCount; i++) { inputLine = scanner.nextLine(); Matcher matcher = pattern.matcher(inputLine); boolean validData = matcher.find(); if (validData){ String personName = matcher.group(1); String eventPlace = matcher.group(2); String eventTime = matcher.group(3); //add place if(!(eventLog.containsKey(eventPlace))){ eventLog.put(eventPlace, new TreeMap<>()); eventLog.get(eventPlace).put(personName, new TreeSet<>()); eventLog.get(eventPlace).get(personName).add(eventTime); } else{ //add person if(!(eventLog.get(eventPlace).containsKey(personName))){ eventLog.get(eventPlace).put(personName, new TreeSet<>()); eventLog.get(eventPlace).get(personName).add(eventTime); } else{ eventLog.get(eventPlace).get(personName).add(eventTime); //eventLog.get(eventPlace).put(personName, eventLog.get(eventPlace).get(personName) + eventTime); } } } } System.out.println(); int counter = 1; eventLog.entrySet().stream().forEach(es -> { System.out.println(es.getKey() + ":"); es.getValue().entrySet().stream().forEach(set -> { System.out.printf("%d. %s -> ", counter, set.getKey()); System.out.print(String.join(", ", set.getValue())); System.out.println(""); }); }); } }
2,635
0.478558
0.474004
71
35.112675
28.153778
121
false
false
0
0
0
0
0
0
0.647887
false
false
0
fbb75b8f1967515e2fdb58ddef33623446013a69
38,835,094,302,813
d77a9e877a2ab84a75e4ed8f161b5d49c5e65ec6
/com.jaspersoft.studio/src/com/jaspersoft/studio/editor/outline/part/NotDragableContainerTreeEditPart.java
2ef03e5a3702c3e91fb6dc7ca37878f1817b341a
[]
no_license
jasonbrianhall/Jaspersoft-Studio
https://github.com/jasonbrianhall/Jaspersoft-Studio
3b0faa08e4da17c24f2f60531e3a5c2e8d7b6478
33f85aee98402cb9da4ac305eab7f071e2ff1b61
refs/heads/master
2021-01-21T20:28:59.761000
2017-05-24T13:10:37
2017-05-24T13:10:37
92,215,885
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (C) 2010 - 2016. TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. ******************************************************************************/ package com.jaspersoft.studio.editor.outline.part; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.RequestConstants; import org.eclipse.gef.RootEditPart; import org.eclipse.gef.editpolicies.RootComponentEditPolicy; import com.jaspersoft.studio.editor.outline.editpolicy.JDContainerEditPolicy; import com.jaspersoft.studio.editor.outline.editpolicy.JDTreeContainerEditPolicy; import com.jaspersoft.studio.model.MGraphicElement; public class NotDragableContainerTreeEditPart extends NotDragableTreeEditPart { /** * Creates and installs pertinent EditPolicies. */ @Override protected void createEditPolicies() { super.createEditPolicies(); installEditPolicy(EditPolicy.CONTAINER_ROLE, new JDContainerEditPolicy()); installEditPolicy(EditPolicy.TREE_CONTAINER_ROLE, new JDTreeContainerEditPolicy()); // If this editpart is the contents of the viewer, then it is not deletable! if (getParent() instanceof RootEditPart) installEditPolicy(EditPolicy.COMPONENT_ROLE, new RootComponentEditPolicy()); } @Override public boolean understandsRequest(Request req) { if (getModel() instanceof MGraphicElement && req.getType() == RequestConstants.REQ_ALIGN) return true; return super.understandsRequest(req); } //These two methods allow to show a visual feedback on the main editor, if available @Override public void showTargetFeedback(Request request) { super.showTargetFeedback(request); showTargetFeedbackOnEditor(request); } @Override public void eraseTargetFeedback(Request request) { super.eraseTargetFeedback(request); eraseTargetFeedbackOnEditor(request); } }
UTF-8
Java
1,918
java
NotDragableContainerTreeEditPart.java
Java
[]
null
[]
/******************************************************************************* * Copyright (C) 2010 - 2016. TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. ******************************************************************************/ package com.jaspersoft.studio.editor.outline.part; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.RequestConstants; import org.eclipse.gef.RootEditPart; import org.eclipse.gef.editpolicies.RootComponentEditPolicy; import com.jaspersoft.studio.editor.outline.editpolicy.JDContainerEditPolicy; import com.jaspersoft.studio.editor.outline.editpolicy.JDTreeContainerEditPolicy; import com.jaspersoft.studio.model.MGraphicElement; public class NotDragableContainerTreeEditPart extends NotDragableTreeEditPart { /** * Creates and installs pertinent EditPolicies. */ @Override protected void createEditPolicies() { super.createEditPolicies(); installEditPolicy(EditPolicy.CONTAINER_ROLE, new JDContainerEditPolicy()); installEditPolicy(EditPolicy.TREE_CONTAINER_ROLE, new JDTreeContainerEditPolicy()); // If this editpart is the contents of the viewer, then it is not deletable! if (getParent() instanceof RootEditPart) installEditPolicy(EditPolicy.COMPONENT_ROLE, new RootComponentEditPolicy()); } @Override public boolean understandsRequest(Request req) { if (getModel() instanceof MGraphicElement && req.getType() == RequestConstants.REQ_ALIGN) return true; return super.understandsRequest(req); } //These two methods allow to show a visual feedback on the main editor, if available @Override public void showTargetFeedback(Request request) { super.showTargetFeedback(request); showTargetFeedbackOnEditor(request); } @Override public void eraseTargetFeedback(Request request) { super.eraseTargetFeedback(request); eraseTargetFeedbackOnEditor(request); } }
1,918
0.73097
0.726799
52
35.884617
29.710562
91
false
false
0
0
0
0
0
0
1.384615
false
false
0
d810fc661467a08fcac5d1fa9e387bf6525e4973
38,603,166,076,526
592ccc0f3b81079c4a359689b9310d0ac908d8dc
/app/src/main/java/ash/aiqinhaigou/com/ashcny/Welcome.java
9f3d5a09e3a38073e12da0d71768e6ce817de24e
[]
no_license
aspros-luo/AshCNY
https://github.com/aspros-luo/AshCNY
f7f822ecaac916916e587643388e9c1fd98b7d6f
83d6faafe7803145f746972d172004a2d907dad1
refs/heads/master
2021-01-20T19:14:01.214000
2016-06-15T10:16:53
2016-06-15T10:16:53
60,316,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ash.aiqinhaigou.com.ashcny; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import ash.aiqinhaigou.com.ashcny.index.widget.MainActivity; import ash.aiqinhaigou.com.ashcny.login.widget.LoginSystem; public class Welcome extends AppCompatActivity { private static final int GUIDE_LOGIN = 0; private static final int GUIDE_MAIN = 1; private static final int DISPLAY_TIME = 3000; private Boolean isLogin = false; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case GUIDE_LOGIN: go_Login(); break; case GUIDE_MAIN: go_Main(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); initView(); } private void initView() { SharedPreferences s = getSharedPreferences("loginInfo", MODE_MULTI_PROCESS); isLogin = s.getBoolean("isLogin", false); if (isLogin) { handler.sendEmptyMessageDelayed(GUIDE_MAIN, DISPLAY_TIME); } else { handler.sendEmptyMessageDelayed(GUIDE_LOGIN, DISPLAY_TIME); } } private void go_Main() { Intent i = new Intent(Welcome.this, MainActivity.class); // Intent i = new Intent(Welcome.this, LoginSystem.class); startActivity(i); finish(); } private void go_Login() { Intent i = new Intent(Welcome.this, LoginSystem.class); startActivity(i); finish(); } }
UTF-8
Java
1,921
java
Welcome.java
Java
[]
null
[]
package ash.aiqinhaigou.com.ashcny; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import ash.aiqinhaigou.com.ashcny.index.widget.MainActivity; import ash.aiqinhaigou.com.ashcny.login.widget.LoginSystem; public class Welcome extends AppCompatActivity { private static final int GUIDE_LOGIN = 0; private static final int GUIDE_MAIN = 1; private static final int DISPLAY_TIME = 3000; private Boolean isLogin = false; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case GUIDE_LOGIN: go_Login(); break; case GUIDE_MAIN: go_Main(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); initView(); } private void initView() { SharedPreferences s = getSharedPreferences("loginInfo", MODE_MULTI_PROCESS); isLogin = s.getBoolean("isLogin", false); if (isLogin) { handler.sendEmptyMessageDelayed(GUIDE_MAIN, DISPLAY_TIME); } else { handler.sendEmptyMessageDelayed(GUIDE_LOGIN, DISPLAY_TIME); } } private void go_Main() { Intent i = new Intent(Welcome.this, MainActivity.class); // Intent i = new Intent(Welcome.this, LoginSystem.class); startActivity(i); finish(); } private void go_Login() { Intent i = new Intent(Welcome.this, LoginSystem.class); startActivity(i); finish(); } }
1,921
0.612181
0.608537
67
27.671642
21.575544
84
false
false
0
0
0
0
0
0
0.597015
false
false
0
ff3b57e4ec982c92102e4c1b7e8fe15cfe876822
39,316,130,643,343
3c139ea06ae2b7769824d607960c56587e720126
/src/main/java/com/demo/jdk8/SupplierTest.java
d86b37fc6625e2d33fc61216cf556e7a3bf3ebcc
[]
no_license
hishanks/java-demo
https://github.com/hishanks/java-demo
fdbae6b7b70cc88287f0b91144d9490b7dcb01ab
5c9f2340f9ec1a5a26a40fd9e5a9755bb0b208af
refs/heads/master
2021-06-22T09:59:22.038000
2019-08-29T15:17:36
2019-08-29T15:17:36
145,686,657
0
0
null
false
2019-08-29T14:58:53
2018-08-22T09:27:32
2019-04-28T05:33:11
2019-08-29T14:53:34
533
0
0
0
Java
false
false
package com.demo.jdk8; import org.junit.jupiter.api.Test; import java.util.function.Supplier; /** * 抽象方法也是唯一的方法:T get(); * * @author zhoukai * @date 2018/6/27 */ public class SupplierTest { @Test public void testSupplier() { // 无参数,有返回值 Supplier<Double> supplier = Math::random; System.out.println(supplier.get()); Supplier<String> stringSupplier = String::new; System.out.println(stringSupplier.get().getClass()); } }
UTF-8
Java
522
java
SupplierTest.java
Java
[ { "context": "pplier;\n\n/**\n * 抽象方法也是唯一的方法:T get();\n *\n * @author zhoukai\n * @date 2018/6/27\n */\npublic class SupplierTest ", "end": 146, "score": 0.9994370341300964, "start": 139, "tag": "USERNAME", "value": "zhoukai" } ]
null
[]
package com.demo.jdk8; import org.junit.jupiter.api.Test; import java.util.function.Supplier; /** * 抽象方法也是唯一的方法:T get(); * * @author zhoukai * @date 2018/6/27 */ public class SupplierTest { @Test public void testSupplier() { // 无参数,有返回值 Supplier<Double> supplier = Math::random; System.out.println(supplier.get()); Supplier<String> stringSupplier = String::new; System.out.println(stringSupplier.get().getClass()); } }
522
0.639004
0.622407
24
19.041666
18.651361
60
false
false
0
0
0
0
0
0
0.333333
false
false
0
8758f80b5ce3ea5b01f663f63c8291f64a4d51d4
35,399,120,495,772
0653f733f8de5ecb76336aa77d9ab4e565fb6a9c
/auth-center/src/main/java/com/again/cloud/auth/config/SecurityConfig.java
ffe2bc2dee6e841422707a6463f830e3c355e4d0
[]
no_license
bellmit/again-cloud
https://github.com/bellmit/again-cloud
a1560f44d84e0be07b52347fa62470e1df4fee38
bca0a8401b1522e90220d4f65eaf0cb476924809
refs/heads/master
2023-07-13T05:57:35.155000
2021-08-25T10:55:23
2021-08-25T10:55:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.again.cloud.auth.config; import com.again.cloud.auth.model.MyUserDetails; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 密码模式才需要配置,认证管理器 @Bean @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().permitAll() .and().formLogin() .and().logout(); } @Bean public UserDetailsService userDetailsService() { return s -> { if ("admin".equals(s) || "user".equals(s)) { return new MyUserDetails(s, passwordEncoder().encode(s), s); } return null; }; } }
UTF-8
Java
1,623
java
SecurityConfig.java
Java
[]
null
[]
package com.again.cloud.auth.config; import com.again.cloud.auth.model.MyUserDetails; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 密码模式才需要配置,认证管理器 @Bean @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().permitAll() .and().formLogin() .and().logout(); } @Bean public UserDetailsService userDetailsService() { return s -> { if ("admin".equals(s) || "user".equals(s)) { return new MyUserDetails(s, passwordEncoder().encode(s), s); } return null; }; } }
1,623
0.802508
0.802508
49
31.571428
31.259937
102
false
false
0
0
0
0
0
0
1.387755
false
false
0
8996a6942da238502164036ed359eea07674d11c
36,653,250,931,437
6be39fc2c882d0b9269f1530e0650fd3717df493
/weixin反编译/sources/com/tencent/mm/sandbox/monitor/a.java
9ab1fb7ad9c04d7b246158bf777321fcee97be75
[]
no_license
sir-deng/res
https://github.com/sir-deng/res
f1819af90b366e8326bf23d1b2f1074dfe33848f
3cf9b044e1f4744350e5e89648d27247c9dc9877
refs/heads/master
2022-06-11T21:54:36.725000
2020-05-07T06:03:23
2020-05-07T06:03:23
155,177,067
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.mm.sandbox.monitor; import android.content.Intent; import android.os.Build; import com.tencent.mm.a.c; import com.tencent.mm.a.e; import com.tencent.mm.a.g; import com.tencent.mm.a.o; import com.tencent.mm.a.q; import com.tencent.mm.loader.stub.b; import com.tencent.mm.pointers.PByteArray; import com.tencent.mm.protocal.d; import com.tencent.mm.sandbox.updater.AppUpdaterUI; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.bj; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.w; import com.tencent.wcdb.database.SQLiteDatabase; import java.io.File; import java.io.FilenameFilter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; public final class a { static final HashMap<String, Integer> gKR; static /* synthetic */ void v(String str, byte[] bArr) { x.e("MicroMsg.CrashUpload", "doPost : url = " + str + ", data.length = " + bArr.length); HttpClient defaultHttpClient = new DefaultHttpClient(); HttpUriRequest httpPost = new HttpPost(str); try { HttpEntity byteArrayEntity = new ByteArrayEntity(bArr); byteArrayEntity.setContentType("binary/octet-stream"); httpPost.setEntity(byteArrayEntity); String convertStreamToString = bi.convertStreamToString(defaultHttpClient.execute(httpPost).getEntity().getContent()); if (convertStreamToString != null && convertStreamToString.length() > 0) { final Map y = bj.y(convertStreamToString, "Response"); if (!(y == null || !"-1000".equalsIgnoreCase((String) y.get(".Response.retCode")) || y.get(".Response.url") == null)) { new Timer().schedule(new TimerTask() { public final void run() { Intent intent = new Intent(ad.getContext(), AppUpdaterUI.class); intent.addFlags(SQLiteDatabase.CREATE_IF_NECESSARY); intent.putExtra("intent_extra_desc", (String) y.get(".Response.desc")); intent.putExtra("intent_update_type", 999); intent.putExtra("intent_extra_download_url", new String[]{(String) y.get(".Response.url")}); ad.getContext().startActivity(intent); } }, 500); } } x.d("MicroMsg.CrashUpload", convertStreamToString); x.e("MicroMsg.CrashUpload", "doPost: returnConnection = %s", convertStreamToString); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.CrashUpload", e, "", new Object[0]); x.e("MicroMsg.CrashUpload", "doPost e type: %s, msg: %s", e.getClass().getSimpleName(), e.getMessage()); } } static { HashMap hashMap = new HashMap(16); gKR = hashMap; hashMap.put("exception", Integer.valueOf(10001)); gKR.put("anr", Integer.valueOf(10002)); gKR.put("handler", Integer.valueOf(10003)); gKR.put("sql", Integer.valueOf(10004)); gKR.put("permission", Integer.valueOf(10005)); gKR.put("main_thread_watch", Integer.valueOf(10006)); } public static int ceS() { File file = new File(w.hbv + "crash/"); if (!file.exists()) { x.w("MicroMsg.CrashUpload", "dkcrash checkUpload dir never create ?"); return -1; } else if (file.isFile()) { file.delete(); x.w("MicroMsg.CrashUpload", "dkcrash is the fucking file ??"); return -1; } else { String[] list = file.list(new FilenameFilter() { public final boolean accept(File file, String str) { return str.endsWith(".crashlog"); } }); if (list == null || list.length == 0) { return -1; } Pattern compile = Pattern.compile("."); for (CharSequence split : list) { String[] split2 = compile.split(split); if (split2 != null && split2.length > 0) { fs(split2[0], split2.length >= 2 ? split2[1] : ""); } } return 1; } } private static int fs(String str, String str2) { String str3 = w.hbv + "crash/" + str + "." + str2 + ".crashini"; long c = bi.c(com.tencent.mm.sdk.e.a.fC(str3, "count")); long Wy = bi.Wy() - bi.c(com.tencent.mm.sdk.e.a.fC(str3, "lasttime")); String str4 = w.hbv + "crash/" + str + "." + str2 + ".crashlog"; int bN = e.bN(str4); x.d("MicroMsg.CrashUpload", "dkcrash count:" + c + " t:" + Wy + " len:" + bN); if (bN < 5242880) { byte[] e = e.e(str4, 0, -1); if (!bi.by(e)) { final int length = e.length; final String toLowerCase = g.s(String.format("weixin#$()%d%d", new Object[]{Integer.valueOf(d.vHl), Integer.valueOf(length)}).getBytes()).toLowerCase(); e = q.q(e); final PByteArray pByteArray = new PByteArray(); c.a(pByteArray, e, toLowerCase.getBytes()); final String str5 = str2; final String str6 = str; com.tencent.mm.sdk.f.e.post(new Runnable() { public final void run() { StringBuilder append = new StringBuilder().append("http://" + ad.getContext().getSharedPreferences("system_config_prefs", 0).getString("support.weixin.qq.com", "support.weixin.qq.com")).append("/cgi-bin/mmsupport-bin/stackreport?version=").append(Integer.toHexString(d.vHl)).append("&devicetype=").append(d.DEVICE_TYPE).append("&filelength=").append(length).append("&sum=").append(toLowerCase).append("&reporttype=1&NewReportType=").append(bi.e((Integer) a.gKR.get(str5))); if (!(str6 == null || str6.equals(""))) { append.append("&username=").append(str6); } x.d("MicroMsg.CrashUpload", "dkcrash sb:" + append.toString()); a.v(append.toString(), pByteArray.value); } }, "CrashUpload_upload"); } } b.deleteFile(str4); new com.tencent.mm.sdk.e.a(str3).da("count", 0); com.tencent.mm.sdk.e.a.h(str3, "lasttime", bi.Wy()); return 1; } public static int a(String str, String str2, a aVar) { if (bi.oN(aVar.toString())) { return -1; } File file = new File(w.hbv + "crash/"); if (!file.exists()) { file.mkdir(); } String str3 = w.hbv + "crash/" + str + "." + str2 + ".crashini"; com.tencent.mm.sdk.e.a.h(str3, "count", bi.c(com.tencent.mm.sdk.e.a.fC(str3, "count")) + 1); if (bi.c(com.tencent.mm.sdk.e.a.fC(str3, "lasttime")) == 0) { com.tencent.mm.sdk.e.a.h(str3, "lasttime", bi.Wy()); } x.d("MicroMsg.CrashUpload", "crash:[%s] len:[%d]", w.hbv + "crash/" + str + "." + str2 + ".crashlog", Integer.valueOf(aVar.toString().length())); a(aVar); a(str3, aVar); return fs(str, str2); } private static void a(a aVar) { if (aVar.xkl) { File file = new File(com.tencent.mm.compatible.util.e.hbx); if (!file.exists()) { file.mkdirs(); } File[] listFiles = file.listFiles(); if (listFiles != null) { for (File file2 : listFiles) { if (bi.bA(file2.lastModified()) > 604800000) { x.i("MicroMsg.CrashUpload", "dealWithSdcardCrash del old file: %s", file2.getPath()); file2.delete(); } } } x.i("MicroMsg.CrashUpload", "dealWithSdcardCrash %s", com.tencent.mm.compatible.util.e.hbx + "crash_" + new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new Date()) + ".txt"); a(r0, aVar); } } private static void a(String str, a aVar) { if (!new File(str).exists()) { int i = ad.getContext().getSharedPreferences("system_config_prefs", 0).getInt("default_uin", 0); StringBuilder stringBuilder = new StringBuilder(); if (i == 0) { String eY = bi.eY(ad.getContext()); if (bi.oN(eY)) { stringBuilder.append("uin[" + Integer.toString((Build.DEVICE + Build.FINGERPRINT + Build.MANUFACTURER + Build.MODEL).hashCode()) + "] "); } else { stringBuilder.append("uin[" + eY + "] "); } } else { stringBuilder.append("uin[" + o.getString(i) + "] "); } stringBuilder.append(x.cfZ()); stringBuilder.append(" BRAND:[" + Build.BRAND + "] "); String[] yR = com.tencent.mm.compatible.e.q.yR(); stringBuilder.append("c1[" + yR[0] + "] "); stringBuilder.append("c2[" + yR[1] + "] "); stringBuilder.append("\n"); e.d(str, stringBuilder.toString().getBytes()); } if (e.bN(str) > 10485760) { b.deleteFile(str); } e.d(str, (aVar.toString() + "\n").getBytes()); } }
UTF-8
Java
9,885
java
a.java
Java
[]
null
[]
package com.tencent.mm.sandbox.monitor; import android.content.Intent; import android.os.Build; import com.tencent.mm.a.c; import com.tencent.mm.a.e; import com.tencent.mm.a.g; import com.tencent.mm.a.o; import com.tencent.mm.a.q; import com.tencent.mm.loader.stub.b; import com.tencent.mm.pointers.PByteArray; import com.tencent.mm.protocal.d; import com.tencent.mm.sandbox.updater.AppUpdaterUI; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.bj; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.w; import com.tencent.wcdb.database.SQLiteDatabase; import java.io.File; import java.io.FilenameFilter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; public final class a { static final HashMap<String, Integer> gKR; static /* synthetic */ void v(String str, byte[] bArr) { x.e("MicroMsg.CrashUpload", "doPost : url = " + str + ", data.length = " + bArr.length); HttpClient defaultHttpClient = new DefaultHttpClient(); HttpUriRequest httpPost = new HttpPost(str); try { HttpEntity byteArrayEntity = new ByteArrayEntity(bArr); byteArrayEntity.setContentType("binary/octet-stream"); httpPost.setEntity(byteArrayEntity); String convertStreamToString = bi.convertStreamToString(defaultHttpClient.execute(httpPost).getEntity().getContent()); if (convertStreamToString != null && convertStreamToString.length() > 0) { final Map y = bj.y(convertStreamToString, "Response"); if (!(y == null || !"-1000".equalsIgnoreCase((String) y.get(".Response.retCode")) || y.get(".Response.url") == null)) { new Timer().schedule(new TimerTask() { public final void run() { Intent intent = new Intent(ad.getContext(), AppUpdaterUI.class); intent.addFlags(SQLiteDatabase.CREATE_IF_NECESSARY); intent.putExtra("intent_extra_desc", (String) y.get(".Response.desc")); intent.putExtra("intent_update_type", 999); intent.putExtra("intent_extra_download_url", new String[]{(String) y.get(".Response.url")}); ad.getContext().startActivity(intent); } }, 500); } } x.d("MicroMsg.CrashUpload", convertStreamToString); x.e("MicroMsg.CrashUpload", "doPost: returnConnection = %s", convertStreamToString); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.CrashUpload", e, "", new Object[0]); x.e("MicroMsg.CrashUpload", "doPost e type: %s, msg: %s", e.getClass().getSimpleName(), e.getMessage()); } } static { HashMap hashMap = new HashMap(16); gKR = hashMap; hashMap.put("exception", Integer.valueOf(10001)); gKR.put("anr", Integer.valueOf(10002)); gKR.put("handler", Integer.valueOf(10003)); gKR.put("sql", Integer.valueOf(10004)); gKR.put("permission", Integer.valueOf(10005)); gKR.put("main_thread_watch", Integer.valueOf(10006)); } public static int ceS() { File file = new File(w.hbv + "crash/"); if (!file.exists()) { x.w("MicroMsg.CrashUpload", "dkcrash checkUpload dir never create ?"); return -1; } else if (file.isFile()) { file.delete(); x.w("MicroMsg.CrashUpload", "dkcrash is the fucking file ??"); return -1; } else { String[] list = file.list(new FilenameFilter() { public final boolean accept(File file, String str) { return str.endsWith(".crashlog"); } }); if (list == null || list.length == 0) { return -1; } Pattern compile = Pattern.compile("."); for (CharSequence split : list) { String[] split2 = compile.split(split); if (split2 != null && split2.length > 0) { fs(split2[0], split2.length >= 2 ? split2[1] : ""); } } return 1; } } private static int fs(String str, String str2) { String str3 = w.hbv + "crash/" + str + "." + str2 + ".crashini"; long c = bi.c(com.tencent.mm.sdk.e.a.fC(str3, "count")); long Wy = bi.Wy() - bi.c(com.tencent.mm.sdk.e.a.fC(str3, "lasttime")); String str4 = w.hbv + "crash/" + str + "." + str2 + ".crashlog"; int bN = e.bN(str4); x.d("MicroMsg.CrashUpload", "dkcrash count:" + c + " t:" + Wy + " len:" + bN); if (bN < 5242880) { byte[] e = e.e(str4, 0, -1); if (!bi.by(e)) { final int length = e.length; final String toLowerCase = g.s(String.format("weixin#$()%d%d", new Object[]{Integer.valueOf(d.vHl), Integer.valueOf(length)}).getBytes()).toLowerCase(); e = q.q(e); final PByteArray pByteArray = new PByteArray(); c.a(pByteArray, e, toLowerCase.getBytes()); final String str5 = str2; final String str6 = str; com.tencent.mm.sdk.f.e.post(new Runnable() { public final void run() { StringBuilder append = new StringBuilder().append("http://" + ad.getContext().getSharedPreferences("system_config_prefs", 0).getString("support.weixin.qq.com", "support.weixin.qq.com")).append("/cgi-bin/mmsupport-bin/stackreport?version=").append(Integer.toHexString(d.vHl)).append("&devicetype=").append(d.DEVICE_TYPE).append("&filelength=").append(length).append("&sum=").append(toLowerCase).append("&reporttype=1&NewReportType=").append(bi.e((Integer) a.gKR.get(str5))); if (!(str6 == null || str6.equals(""))) { append.append("&username=").append(str6); } x.d("MicroMsg.CrashUpload", "dkcrash sb:" + append.toString()); a.v(append.toString(), pByteArray.value); } }, "CrashUpload_upload"); } } b.deleteFile(str4); new com.tencent.mm.sdk.e.a(str3).da("count", 0); com.tencent.mm.sdk.e.a.h(str3, "lasttime", bi.Wy()); return 1; } public static int a(String str, String str2, a aVar) { if (bi.oN(aVar.toString())) { return -1; } File file = new File(w.hbv + "crash/"); if (!file.exists()) { file.mkdir(); } String str3 = w.hbv + "crash/" + str + "." + str2 + ".crashini"; com.tencent.mm.sdk.e.a.h(str3, "count", bi.c(com.tencent.mm.sdk.e.a.fC(str3, "count")) + 1); if (bi.c(com.tencent.mm.sdk.e.a.fC(str3, "lasttime")) == 0) { com.tencent.mm.sdk.e.a.h(str3, "lasttime", bi.Wy()); } x.d("MicroMsg.CrashUpload", "crash:[%s] len:[%d]", w.hbv + "crash/" + str + "." + str2 + ".crashlog", Integer.valueOf(aVar.toString().length())); a(aVar); a(str3, aVar); return fs(str, str2); } private static void a(a aVar) { if (aVar.xkl) { File file = new File(com.tencent.mm.compatible.util.e.hbx); if (!file.exists()) { file.mkdirs(); } File[] listFiles = file.listFiles(); if (listFiles != null) { for (File file2 : listFiles) { if (bi.bA(file2.lastModified()) > 604800000) { x.i("MicroMsg.CrashUpload", "dealWithSdcardCrash del old file: %s", file2.getPath()); file2.delete(); } } } x.i("MicroMsg.CrashUpload", "dealWithSdcardCrash %s", com.tencent.mm.compatible.util.e.hbx + "crash_" + new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new Date()) + ".txt"); a(r0, aVar); } } private static void a(String str, a aVar) { if (!new File(str).exists()) { int i = ad.getContext().getSharedPreferences("system_config_prefs", 0).getInt("default_uin", 0); StringBuilder stringBuilder = new StringBuilder(); if (i == 0) { String eY = bi.eY(ad.getContext()); if (bi.oN(eY)) { stringBuilder.append("uin[" + Integer.toString((Build.DEVICE + Build.FINGERPRINT + Build.MANUFACTURER + Build.MODEL).hashCode()) + "] "); } else { stringBuilder.append("uin[" + eY + "] "); } } else { stringBuilder.append("uin[" + o.getString(i) + "] "); } stringBuilder.append(x.cfZ()); stringBuilder.append(" BRAND:[" + Build.BRAND + "] "); String[] yR = com.tencent.mm.compatible.e.q.yR(); stringBuilder.append("c1[" + yR[0] + "] "); stringBuilder.append("c2[" + yR[1] + "] "); stringBuilder.append("\n"); e.d(str, stringBuilder.toString().getBytes()); } if (e.bN(str) > 10485760) { b.deleteFile(str); } e.d(str, (aVar.toString() + "\n").getBytes()); } }
9,885
0.549317
0.535862
213
45.408451
44.498005
497
false
false
0
0
0
0
0
0
0.985915
false
false
0
067e85f494735ebc39e7c53a56237ddc4c34c678
4,063,039,104,218
de927bbbaf5eb279aec5836b9d6a9d36b4d5aee0
/Desktop/Score.java
568f7f7be47475fff39fce5d5b132ad52c173903
[]
no_license
oliverlangmo/java_flappy_birds_in_space
https://github.com/oliverlangmo/java_flappy_birds_in_space
50c8e150d9676a684c973597c407e42261dbc2a2
441aaa3179d417f75dae9cf1436376f2222f124c
refs/heads/master
2021-01-13T17:05:46.097000
2016-11-04T01:59:03
2016-11-04T01:59:03
72,804,695
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Score here. * * @author (your name) * @version (a version number or a date) */ public class Score extends Actor { private int value = 0; private String text = "Score: "; private int stringLength; java.awt.Color color = java.awt.Color.WHITE; FlappyWorld flappyWorld; public Score() { stringLength = (text.length() + 2) * 16; setImage(new GreenfootImage(stringLength, 24)); GreenfootImage image = getImage(); java.awt.Font font = image.getFont(); image.setFont(font.deriveFont(24.0F)); // use larger font updateImage(); } public void addedToWorld(World world) { flappyWorld = (FlappyWorld) world; } protected void updateImage() { GreenfootImage image = getImage(); image.clear(); image.setColor(color); image.drawString(text + value, 1, 18); } /** * Act - do whatever the Score wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { value = flappyWorld.getScore(); updateImage(); } }
UTF-8
Java
1,275
java
Score.java
Java
[]
null
[]
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Score here. * * @author (your name) * @version (a version number or a date) */ public class Score extends Actor { private int value = 0; private String text = "Score: "; private int stringLength; java.awt.Color color = java.awt.Color.WHITE; FlappyWorld flappyWorld; public Score() { stringLength = (text.length() + 2) * 16; setImage(new GreenfootImage(stringLength, 24)); GreenfootImage image = getImage(); java.awt.Font font = image.getFont(); image.setFont(font.deriveFont(24.0F)); // use larger font updateImage(); } public void addedToWorld(World world) { flappyWorld = (FlappyWorld) world; } protected void updateImage() { GreenfootImage image = getImage(); image.clear(); image.setColor(color); image.drawString(text + value, 1, 18); } /** * Act - do whatever the Score wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { value = flappyWorld.getScore(); updateImage(); } }
1,275
0.607843
0.598431
51
23.941177
22.320667
79
false
false
0
0
0
0
0
0
0.490196
false
false
0
fac4619e15a8ae5b33a6f8f5840bc193cb5f9776
23,407,571,804,268
9083610b64fbf93aa0b96656f28405ea80d1e399
/app/src/main/java/ru/startandroid/develop/firstproject/ui/screens/three/FragmentRegister.java
27aab74521036be68cc6c9d30812eacc4f31afc3
[]
no_license
yurasika25/My-project
https://github.com/yurasika25/My-project
cebeaa596e2bd65ba6410e3ae61f82f5749e5e1d
0913f998438f6b417847ad5903821adb7becea85
refs/heads/master
2022-12-18T20:11:15.329000
2020-09-17T13:54:12
2020-09-17T13:54:12
285,273,916
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.startandroid.develop.firstproject.ui.screens.three; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; import ru.startandroid.develop.firstproject.R; public class FragmentRegister extends Fragment implements RegisterView { private RegisterPresenter presenter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.register, container, false); presenter = new RegisterPresenter(); return view; } @Override public void onPause() { super.onPause(); presenter.exitFromView(); } @Override public void onResume() { super.onResume(); presenter.enterWithView(this); } @Override public void navigateToRegister() { } @Override public void navigateToPhoto() { } }
UTF-8
Java
1,029
java
FragmentRegister.java
Java
[]
null
[]
package ru.startandroid.develop.firstproject.ui.screens.three; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; import ru.startandroid.develop.firstproject.R; public class FragmentRegister extends Fragment implements RegisterView { private RegisterPresenter presenter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.register, container, false); presenter = new RegisterPresenter(); return view; } @Override public void onPause() { super.onPause(); presenter.exitFromView(); } @Override public void onResume() { super.onResume(); presenter.enterWithView(this); } @Override public void navigateToRegister() { } @Override public void navigateToPhoto() { } }
1,029
0.680272
0.680272
48
20.458334
21.860313
74
false
false
0
0
0
0
0
0
0.395833
false
false
0
ba349cbe739b46302133c0a40f5e39ef0feaeae6
13,185,549,636,736
e68058ae12ebdc730663d090b4f7a10440dc39c9
/Hotel Management/src/main/java/com/ngominhnhi/mapper/RoomMapper.java
cb51e7876ab983efce2de0e27b259e4e48b867b1
[]
no_license
javaspringsecurity/Hotel-Management
https://github.com/javaspringsecurity/Hotel-Management
006721dcd04ebc6b7fa2990693288d3c52018d39
c91f7caa0150d12843880c2fd96a8fc76753bc42
refs/heads/master
2022-12-21T23:39:18.086000
2019-06-11T05:29:13
2019-06-11T05:29:13
191,299,198
0
0
null
false
2022-12-15T23:59:47
2019-06-11T05:21:31
2019-06-11T05:29:32
2022-12-15T23:59:45
4,165
0
0
14
CSS
false
false
package com.ngominhnhi.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.ngominhnhi.entities.Room; public class RoomMapper implements RowMapper<Room>{ public Room mapRow(ResultSet rs, int rowNum) throws SQLException { Room room= new Room(); room.setId(rs.getInt("id")); room.setName(rs.getString("name")); room.setStandard(rs.getString("standard")); room.setStatus(rs.getString("status")); return room; } }
UTF-8
Java
500
java
RoomMapper.java
Java
[]
null
[]
package com.ngominhnhi.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.ngominhnhi.entities.Room; public class RoomMapper implements RowMapper<Room>{ public Room mapRow(ResultSet rs, int rowNum) throws SQLException { Room room= new Room(); room.setId(rs.getInt("id")); room.setName(rs.getString("name")); room.setStandard(rs.getString("standard")); room.setStatus(rs.getString("status")); return room; } }
500
0.754
0.754
20
24
20.30271
67
false
false
0
0
0
0
0
0
1.3
false
false
0