blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
1a6f1184291741853c6fc2f715fc0020ffd55369
|
Java
|
AngLi2/DesignPatterns
|
/src/abstractfactory/demo/AbstractWhiteHuman.java
|
UTF-8
| 291
| 3.140625
| 3
|
[] |
no_license
|
/**
*
*/
package abstractfactory.demo;
/**
* @author Ang Li
*
*/
public abstract class AbstractWhiteHuman implements Human{
public void getColor() {
System.out.println("The color of white human is white");
}
public void talk() {
System.out.println("White human talk");
}
}
| true
|
a1a8db1bb745a8011631cbd73fcad8be3a36ca22
|
Java
|
vitaliy-zinchenko/spring-batch-example
|
/src/main/java/zinchenko/sb/dao/ProductDao.java
|
UTF-8
| 174
| 1.8125
| 2
|
[] |
no_license
|
package zinchenko.sb.dao;
import zinchenko.sb.model.Product;
/**
* Created by zinchenko on 30.08.14.
*/
public interface ProductDao {
void save(Product product);
}
| true
|
8e10f4531cd85b2220f58f1726022cfe8a468be0
|
Java
|
HJRumbo/PrimerParcial
|
/app/src/main/java/com/example/primerparcial/NotaActivity.java
|
UTF-8
| 10,409
| 2.28125
| 2
|
[] |
no_license
|
package com.example.primerparcial;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class NotaActivity extends AppCompatActivity {
DecimalFormat df = new DecimalFormat("0.00");
ArrayList<Corte> listaPrimer, listaCorte, listaSegundo;
DaoCorte daoCorte;
DaoMateria daoMateria;
Corte corte;
String nombreMat = "";
String codigoMat = "";
int numerCorte, total = 100, porcentInt = 0;
double notaCalcu, notaTotal = 0, porcent, notaa = 0, calporcent, nota1=0, nota2=0, nota3=0;
Dialog dialogo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nota);
listaCorte = new ArrayList<>();
daoCorte = new DaoCorte(NotaActivity.this);
daoMateria = new DaoMateria(NotaActivity.this);
dialogo = new Dialog(NotaActivity.this);
obtener();
notasPrimerCorte();
notasSegundoCorte();
notasTercerCorte();
}
public void obtener(){
Bundle parametros = this.getIntent().getExtras();
if(parametros !=null){
nombreMat = getIntent().getStringExtra("nombre");
codigoMat = getIntent().getStringExtra("codigo");
}
final TextView nombreText = (TextView)findViewById(R.id.textMateria);
final TextView codigoText = (TextView)findViewById(R.id.textCodigo);
nombreText.setText(nombreMat);
codigoText.setText(codigoMat);
}
public void onClick(View view){
Intent miIntent = new Intent(NotaActivity.this,MainActivity.class);
startActivity(miIntent);
}
public ArrayList<Corte> buscarNotas(String codigoMate){
return daoCorte.verMateria(codigoMate);
}
public void notasPrimerCorte(){
char encontro = 'N';
listaPrimer = new ArrayList<>();
listaPrimer = buscarNotas(codigoMat);
final Button botonAdd = (Button)findViewById(R.id.btnAddPrimer);
final TextView primerCorte = (TextView)findViewById(R.id.txtNumPCorte);
final TextView nota = (TextView)findViewById(R.id.txtNotaPCorte);
final TextView codigoText = (TextView)findViewById(R.id.textCodigo);
if(listaPrimer == null){
primerCorte.setText("Primer corte");
nota.setText("0.0");
botonAdd.setEnabled(true);
}else{
for (Corte corte: listaPrimer
) {
if(corte.getNumCorte()==1){
nota1 = nota1 + corte.getNotaCalculada();
encontro = 'S';
}
}
if(encontro=='S' && codigoText.getText().toString() == codigoMat){
nota.setText(""+nota1);
botonAdd.setEnabled(false);
}
}
}
public void notasTercerCorte(){
char encontro = 'N';
listaPrimer = new ArrayList<>();
listaPrimer = buscarNotas(codigoMat);
final Button botonAdd = (Button)findViewById(R.id.btnAddTercer);
final TextView tercerCorte = (TextView)findViewById(R.id.txtNumTCorte);
final TextView nota = (TextView)findViewById(R.id.txtNotaTCorte);
final TextView codigoText = (TextView)findViewById(R.id.textCodigo);
if(listaPrimer == null){
tercerCorte.setText("Tercer corte");
nota.setText("0.0");
botonAdd.setEnabled(true);
}else{
for (Corte corte: listaPrimer
) {
if(corte.getNumCorte()==3){
nota3 = nota3 + corte.getNotaCalculada();
encontro = 'S';
}
}
if(encontro=='S' && codigoText.getText().toString() == codigoMat){
nota.setText(""+nota3);
botonAdd.setEnabled(false);
}
}
}
public void notasSegundoCorte(){
char encontro = 'N';
listaPrimer = new ArrayList<>();
listaPrimer = buscarNotas(codigoMat);
final Button botonAdd = (Button)findViewById(R.id.btnAddSegundo);
final TextView primerCorte = (TextView)findViewById(R.id.txtNumSCorte);
final TextView nota = (TextView)findViewById(R.id.txtNotaSCorte);
final TextView codigoText = (TextView)findViewById(R.id.textCodigo);
if(listaPrimer == null){
primerCorte.setText("Segundo corte");
nota.setText("0.0");
botonAdd.setEnabled(true);
}else{
for (Corte corte: listaPrimer
) {
if(corte.getNumCorte()==2){
nota2 = nota2 + corte.getNotaCalculada();
encontro = 'S';
}
}
if(encontro=='S' && codigoText.getText().toString() == codigoMat){
nota.setText(""+nota2);
botonAdd.setEnabled(false);
}
}
}
public void onClickAdd(View view) {
notaTotal = 0;notaa = 0; total = 100; notaCalcu = 0;
porcentInt = 0; nota1=0; nota2=0;nota3=0;
dialogo.setTitle("Nuevo registro");
dialogo.setCancelable(true);
dialogo.setContentView(R.layout.dialogo_corte);
dialogo.show();
final TextView txtMensaje = (TextView)dialogo.findViewById(R.id.txtMensaje);
final Button botonGuard = (Button)dialogo.findViewById(R.id.btnGuardAct);
botonGuard.setEnabled(false);
switch (view.getId()){
case R.id.btnAddPrimer:
txtMensaje.setText("Actividades del primer corte");
numerCorte = 1;
break;
case R.id.btnAddSegundo:
txtMensaje.setText("Actividades del segundo corte");
numerCorte = 2;
break;
case R.id.btnAddTercer:
txtMensaje.setText("Actividades del tercer corte");
numerCorte = 3;
break;
}
}
EditText nota;
EditText porcentaje;
public void AddActividad(View view) {
final EditText actividad = (EditText)dialogo.findViewById(R.id.txtActividad);
porcentaje = (EditText)dialogo.findViewById(R.id.txtPorcent);
nota = (EditText)dialogo.findViewById(R.id.txtNotaAct);
final Button botonAdd = (Button)dialogo.findViewById(R.id.btnAddAct);
final Button botonGuard = (Button)dialogo.findViewById(R.id.btnGuardAct);
porcentInt = Integer.valueOf(porcentaje.getText().toString());
porcent = Double.valueOf(porcentaje.getText().toString());
notaa = Double.valueOf(nota.getText().toString());
if(porcentInt>total){
Toast.makeText(getApplication(), "El porcentaje que le sobra es "+ total +"%.", Toast.LENGTH_SHORT).show();
}else {
if (notaa > 5.0) {
Toast.makeText(getApplication(), "La nota no puede ser mayor que 5.0", Toast.LENGTH_SHORT).show();
} else {
calporcent = (porcent / 100);
notaCalcu = calporcent * notaa;
notaTotal = notaTotal + notaCalcu;
total = total - porcentInt;
final TextView notaTo = (TextView) dialogo.findViewById(R.id.txtNotaTotal);
final TextView restante = (TextView) dialogo.findViewById(R.id.txtRestante);
final TextView codigo = (TextView)findViewById(R.id.textCodigo);
notaTo.setText("" + df.format(notaTotal));
restante.setText("Restante: " + total + " %");
corte = new Corte(
numerCorte,
actividad.getText().toString(),
porcentInt,
notaa,
notaCalcu,
codigo.getText().toString()
);
listaCorte.add(corte);
limpiar();
}
}
if (total <= 0){
botonAdd.setEnabled(false);
botonGuard.setEnabled(true);
}
}
public void limpiar(){
final EditText actividad = (EditText)dialogo.findViewById(R.id.txtActividad);
final EditText porcentaje = (EditText)dialogo.findViewById(R.id.txtPorcent);
final EditText nota = (EditText)dialogo.findViewById(R.id.txtNotaAct);
actividad.setText("");
porcentaje.setText("");
nota.setText("");
actividad.requestFocus();
}
public void clickCancel(View view){
dialogo.dismiss();
}
public void guardar(View view){
try{
daoCorte.insertar(listaCorte);
notasPrimerCorte();
notasSegundoCorte();
notasTercerCorte();
dialogo.dismiss();
editarMateria();
}catch (Exception e){
Toast.makeText(getApplication(), "Error", Toast.LENGTH_SHORT).show();
}
}
double primeraNota = 0, segundanota = 0, terceranota = 0, notaMateria;
public void editarMateria(){
listaCorte = daoCorte.verMateria(codigoMat);
for (Corte corte: listaCorte
) {
if(corte.getNumCorte()==1){
primeraNota = primeraNota + corte.getNotaCalculada();
}
}
for (Corte corte: listaCorte
) {
if(corte.getNumCorte()==2){
segundanota = segundanota + corte.getNotaCalculada();
}
}
for (Corte corte: listaCorte
) {
if(corte.getNumCorte()==3){
terceranota = terceranota + corte.getNotaCalculada();
}
}
notaMateria = (primeraNota*0.3)+(segundanota*0.3)+(terceranota*0.4);
daoMateria.EditarNota(codigoMat, notaMateria);
}
public void conPrimer(View view){
Intent miIntent = new Intent(NotaActivity.this,CortesActivity.class);
miIntent.putExtra("nombre", nombreMat);
miIntent.putExtra("codigo", codigoMat);
miIntent.putExtra("numeroCorte", 1);
startActivity(miIntent);
}
}
| true
|
cf640bc7c9926cef150a03e65658708636efafcf
|
Java
|
shiyouping/rtalpha
|
/server/base-parent/base-core/src/main/java/com/rtalpha/base/core/constant/CacheName.java
|
UTF-8
| 299
| 1.625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.rtalpha.base.core.constant;
/**
* @author Ricky
* @since Apr 16, 2017
*
*/
public interface CacheName {
String CUSTOMER = "customer";
String AGENT = "agent";
String VERIFICATION_CODE = "verificationCode";
String PACKAGE_TOUR = "packageTour";
String MULTIPART = "multipart";
}
| true
|
3cf8d9a4045259ed2b2d633a147beea5f507f11c
|
Java
|
asosa9991/sprintboot_botocamp
|
/src/test/java/com/trade/autumnboot/utils/FileUtilsTest.java
|
UTF-8
| 2,275
| 2.21875
| 2
|
[] |
no_license
|
package com.trade.autumnboot.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
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.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import com.trade.autumnboot.dto.MockData;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=RANDOM_PORT)
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public class FileUtilsTest {
@Autowired
FileUtils fileUtils;
@Test
public void test_StoreMockDataFile() {
List<MockData> mockDataList= new ArrayList<>();
MockData data = new MockData();
data.setOnDate(LocalDate.now());
mockDataList.add(data);
String fileName = fileUtils.store("AAPL", "START-DATE", "END-DATE", "GENERATOR-TYPE", mockDataList, false);
assertThat(fileName).isEqualTo("src/main/resources/data/"+"AAPL_START-DATE_END-DATE_GENERATOR-TYPE.json");
}
@Test
public void test_retrieveDataFile() {
List<String> files = fileUtils.list();
assertThat(files).isNotNull();
assertThat(files.size()).isGreaterThan(0);
}
@Test
public void test_DeleteFile() {
List<MockData> mockDataList= new ArrayList<>();
MockData data = new MockData();
data.setOnDate(LocalDate.now());
mockDataList.add(data);
String fileName = fileUtils.store("AAPL", "START-DATE", "END-DATE", "GENERATOR-TYPE-DELETE-TEST", mockDataList, false);
assertThat(fileName).isEqualTo("src/main/resources/data/"+"AAPL_START-DATE_END-DATE_GENERATOR-TYPE-DELETE-TEST.json");
fileName = "AAPL_START-DATE_END-DATE_GENERATOR-TYPE-DELETE-TEST.json";
String status = fileUtils.delete(fileName);
assertThat(status).isEqualTo("DELETED");
}
@Test
public void test_DeleteFileNotFound() {
String fileName = "NonExistingFile.json";
String status = fileUtils.delete(fileName);
assertThat(status).isEqualTo("FILE NOT FOUND");
}
}
| true
|
36bf0c434507310e0b70d206a47d191d41c40f3c
|
Java
|
shaiRos/Scholarship-System
|
/ScholarshipSystem code/src/ScholarshipSystem/NotificationManager.java
|
UTF-8
| 7,544
| 3.09375
| 3
|
[] |
no_license
|
package ScholarshipSystem;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* Database that manages instances of notifications and saves their states for
* each user.
*
* @author Bryan Hyunh
* @version final (4/12/19)
*/
public class NotificationManager {
private HashMap<Integer, ArrayList<Notification>> userNotifications = new HashMap<>();
/**
* deals with the connection between Users and their notification. links
* specific notifications to specific users that can be accessed between
* different runs of the program allows for sending notifications to user's to
* be possible and easy
*
* @param id
* the ID of the user
*/
public NotificationManager(int id) {
setIntegerNotifications(deserialize());
if (userFound(id) == false) {
this.addUserToMap(id);
}
serialize();
}
/**
* deals with the connection between Users and their notification. links
* specific notifications to specific users that can be accessed between
* different runs of the program allows for sending notifications to user's to
* be possible and easy
*
* @param users
*/
public NotificationManager(Integer... users) {
setIntegerNotifications(deserialize());
for (Integer user : users) {
addUserToMap(user);
}
serialize();
}
/**
* returns a string list of notification titles that are under the user's id
*
* @param userID
* @return
*/
public ArrayList<String> getNotificationTitles(int userID) {
ArrayList<String> notificationTitles = new ArrayList<>();
ArrayList<Notification> notifs = getNotifications(userID);
System.out.println(userID);
for (Notification n : notifs) {
notificationTitles.add(n.getTitle());
// System.out.println(n.getTitle());
}
return notificationTitles;
}
/**
* adds a user to the system, allowing them to now recieve notifications.
*
* @param user
*/
public void addUserToMap(Integer user) {
userNotifications.put(user, new ArrayList<Notification>());
serialize();
}
/**
* gets notifications of a specific user
*
* @param Integerid
* @return
*/
public ArrayList<Notification> getNotifications(int userid) {
return userNotifications.get(userid);
}
/**
* adds a user if absent from key set
*
* @param user
*/
private boolean userFound(Integer user) {
boolean result = false;
for (Integer u : userNotifications.keySet()) {
if (u.equals(user))
result = true;
}
// System.out.println(user + " was absent from the system, but it's gucci now");
return result;
}
/**
* sends notification to user. NOTE!!! the notification will be duplicated and
* argument cannot be used to reference the notification associated with user
*
* @param user
* @param notification
*/
public void sendNotification(Integer user, Notification notification) {
// userFound(user);
ArrayList<Notification> notif = getNotifications(user);
notif.add(new Notification(notification));
userNotifications.put(user, notif);
serialize();
}
/**
* returns all the users of a certain notification
*
* @param notification
* @return
*/
public ArrayList<Integer> IntegersOfNotification(Notification notification) {
ArrayList<Integer> ret = new ArrayList<Integer>();
ArrayList<Integer> users = new ArrayList<Integer>(userNotifications.keySet());
for (Integer user : users) {
userFound(user);
for (Notification note : getNotifications(user)) {
if (note.compareTo(notification)) {
ret.add(user);
}
}
}
return ret;
}
/**
* get notification instance associated with user
*
* @param user
* @param notification
* @return
*/
public Notification getIntegersInstanceOfNotification(Integer user, Notification notification) {
userFound(user);
for (Notification note : getNotifications(user)) {
if (note.compareTo(notification)) {
return note;
}
}
return null;
}
/**
* marks the notification of a user as read
*
* @param user
* @param notification
*/
public void userReadNotification(Integer user, Notification notification) {
userFound(user);
notification = getIntegersInstanceOfNotification(user, notification);
notification.markAsRead();
serialize();
}
/**
* sends out notification to multiple users
*
* @param notification
* @param users
*/
public void sendMassNotification(Notification notification, Integer... users) {
for (Integer user : users) {
sendNotification(user, notification);
}
serialize();
}
/**
* sends out notifications to multiple users
*
* @param notification
* @param users
*/
public void sendMassNotification(Notification notification, ArrayList<Integer> users) {
for (Integer user : users) {
sendNotification(user, notification);
}
serialize();
}
/**
*
*
* Neatly printout the users and their notifications
*
*
*/
public void printOut() {
System.out.println(
"----------------------------------------------------start Printout------------------------------------------");
ArrayList<Integer> users = new ArrayList<Integer>(userNotifications.keySet());
for (Integer user : users) {
System.out.println("--------------------------------------------" + user
+ "--------------------------------------------");
for (Notification note : getNotifications(user)) {
System.out.println(note);
System.out.println();
System.out.println("##################################");
}
}
System.out.println(
"----------------------------------------------------end Printout------------------------------------------");
}
/**
*
* Returns the hash map from this class
*
* @return userNotifications
*/
public HashMap<Integer, ArrayList<Notification>> getIntegerNotifications() {
return userNotifications;
}
/**
*
* Sets the userNotifications
*
* @param userNotifications
*/
public void setIntegerNotifications(HashMap<Integer, ArrayList<Notification>> userNotifications) {
this.userNotifications = userNotifications;
}
/**
*
* Saves the notifications and their link to Users for future use
*
*/
public void serialize() {
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("notifications.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(userNotifications);
fileOut.close();
out.close();
System.out.println("notifications.ser was found, and has been serialized");
} catch (FileNotFoundException e) {
System.out.println("notifications.ser not found");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* Retrieves the notifications and their link for users from file directory
*
* @return hashmap
*
*
*/
public HashMap<Integer, ArrayList<Notification>> deserialize() {
HashMap<Integer, ArrayList<Notification>> e = null;
try {
FileInputStream fileIn = new FileInputStream("notifications.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (HashMap<Integer, ArrayList<Notification>>) in.readObject();
in.close();
fileIn.close();
} catch (Exception k) {
System.out.println("students.ser was not found");
return new HashMap<Integer, ArrayList<Notification>>();
}
return e;
}
}
| true
|
95896b589b6d883ac0302aa40385502e309f12d1
|
Java
|
4effo/ipf
|
/commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/core/validate/XONValidator.java
|
UTF-8
| 3,185
| 1.78125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openehealth.ipf.commons.ihe.xds.core.validate;
import static org.apache.commons.lang3.Validate.notNull;
import static org.openehealth.ipf.commons.ihe.xds.core.validate.ValidationMessage.*;
import static org.openehealth.ipf.commons.ihe.xds.core.validate.ValidatorAssertions.*;
import java.util.List;
import org.openehealth.ipf.commons.ihe.xds.core.hl7.HL7;
import org.openehealth.ipf.commons.ihe.xds.core.hl7.HL7Delimiter;
/**
* Validates a XON string.
* @author Jens Riemschneider
*/
public class XONValidator implements ValueValidator {
private final OIDValidator oidValidator = new OIDValidator();
@Override
public void validate(String hl7XON) throws XDSMetaDataException {
notNull(hl7XON, "hl7XON cannot be null");
List<String> parts = HL7.parse(HL7Delimiter.COMPONENT, hl7XON);
String organizationName = HL7.get(parts, 1, true);
metaDataAssert(organizationName != null, ORGANIZATION_NAME_MISSING, hl7XON);
String hl7HD = HL7.get(parts, 6, false);
if (hl7HD != null) {
List<String> hdParts = HL7.parse(HL7Delimiter.SUBCOMPONENT, hl7HD);
metaDataAssert(HL7.get(hdParts, 1, false) == null,
HD_MUST_NOT_HAVE_NAMESPACE_ID, hl7XON);
metaDataAssert("ISO".equals(HL7.get(hdParts, 3, true)),
UNIVERSAL_ID_TYPE_MUST_BE_ISO, hl7XON);
String oid = HL7.get(hdParts, 2, true);
metaDataAssert(oid != null, HD_NEEDS_UNIVERSAL_ID, hl7XON);
oidValidator.validate(oid);
}
else {
String idNumber = HL7.get(parts, 10, true);
if (idNumber == null) {
idNumber = HL7.get(parts, 3, true);
}
if (idNumber != null) {
oidValidator.validate(idNumber);
}
}
metaDataAssert(parts.size() <= 10, ORGANIZATION_TOO_MANY_COMPONENTS);
metaDataAssert(HL7.get(parts, 2, false) == null, ORGANIZATION_TOO_MANY_COMPONENTS);
metaDataAssert(HL7.get(parts, 4, false) == null, ORGANIZATION_TOO_MANY_COMPONENTS);
metaDataAssert(HL7.get(parts, 5, false) == null, ORGANIZATION_TOO_MANY_COMPONENTS);
metaDataAssert(HL7.get(parts, 7, false) == null, ORGANIZATION_TOO_MANY_COMPONENTS);
metaDataAssert(HL7.get(parts, 8, false) == null, ORGANIZATION_TOO_MANY_COMPONENTS);
metaDataAssert(HL7.get(parts, 9, false) == null, ORGANIZATION_TOO_MANY_COMPONENTS);
}
}
| true
|
78ab15097d33077633d0203342ab4fcfa56ff909
|
Java
|
saurabhpandya/KarzaAssignment
|
/app/src/main/java/com/karzaassignment/capture/CapturedImageActivity.java
|
UTF-8
| 1,720
| 2.203125
| 2
|
[] |
no_license
|
package com.karzaassignment.capture;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import com.bumptech.glide.Glide;
import com.karzaassignment.R;
import com.karzaassignment.databinding.ActivityCapturedImageBinding;
import com.karzaassignment.gallery.CapturedImagesActivity;
import java.io.File;
public class CapturedImageActivity extends AppCompatActivity implements View.OnClickListener {
private ActivityCapturedImageBinding binding;
private String imagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_captured_image);
binding.btnNext.setOnClickListener(this);
binding.btnRetake.setOnClickListener(this);
setTitle("Comfirm Image");
getData();
setData();
}
private void getData() {
imagePath = getIntent().getStringExtra("image");
}
private void setData() {
File file = new File(imagePath);
Glide.with(this)
.load(file)
.into(binding.imgvwCaotured);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_retake:
File file = new File(imagePath);
file.delete();
finish();
break;
case R.id.btn_next:
startActivity(new Intent(this, CapturedImagesActivity.class));
break;
}
}
@Override
public void onBackPressed() {
}
}
| true
|
1a05a47893d18583ca466340ca8b9a81ed486929
|
Java
|
arishkinnov/anovikova
|
/src/ru/anovikova/lesson20/WeatherService.java
|
UTF-8
| 1,384
| 2.296875
| 2
|
[] |
no_license
|
package ru.anovikova.lesson20;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import ru.anovikova.lesson20.dto.Location;
import ru.anovikova.lesson20.dto.ResponseFields;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class WeatherService {
public Location[] search(String locality) throws IOException {
URL url = new URL("https://www.metaweather.com/api/location/search/?query=" + locality);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Location[] location = objectMapper.readValue(url, Location[].class);
return location;
}
public ResponseFields location (int woeid) throws IOException {
URL url = new URL("https://www.metaweather.com/api/location/" + woeid + "/");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
ResponseFields responseFields = objectMapper.readValue(url, ResponseFields.class);
return responseFields;
}
}
| true
|
18f49c9ca105a80b65055e0c1d8174ba4844a38f
|
Java
|
iamhge/spring_study
|
/spring_intro/hello-spring/src/main/java/hello/hellospring/domain/Member.java
|
UTF-8
| 641
| 2.734375
| 3
|
[] |
no_license
|
package hello.hellospring.domain;
import javax.persistence.*;
// @Entity : jpa가 관리하는 entity
@Entity
public class Member {
// IDENTITY 전략 : db에 값을 넣으면 db가 값을 자동으로 생성해주는 것.
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; // 시스템이 정함
private String name; // 고객이 회원가입 시 지정
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true
|
88c067b2cf2ca33093145f5884ccff902091588e
|
Java
|
jfulop99/training-solutions
|
/src/main/java/introdate/PerformanceTest.java
|
UTF-8
| 535
| 3.109375
| 3
|
[] |
no_license
|
package introdate;
import java.time.LocalDate;
import java.time.LocalTime;
public class PerformanceTest {
public static void main(String[] args) {
Performance performance1 = new Performance(LocalDate.of(2020, 2, 3), "Deep Purple", LocalTime.of(18, 00), LocalTime.of(22, 00));
Performance performance2 = new Performance(LocalDate.of(1986, 8, 15), "Queen", LocalTime.of(18, 00), LocalTime.of(22, 00));
System.out.println(performance1.getInfo());
System.out.println(performance2.getInfo());
}
}
| true
|
44f9f52a3fd8e6139652b332e05c7729f6c96fec
|
Java
|
kristine-sl-bachelor/big-data-assignment
|
/src/test/java/b/discover/ActivityYearTest.java
|
UTF-8
| 3,102
| 2.53125
| 3
|
[] |
no_license
|
package b.discover;
import b.discover.c.over_50.AuthorsPublications;
import b.discover.d.activity_year.ActivityYearMapper;
import b.discover.d.activity_year.ActivityYearReducer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.apache.hadoop.mrunit.mapreduce.ReduceDriver;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ActivityYearTest {
private MapDriver< LongWritable, Text, Text, IntWritable > mapDriver;
private ReduceDriver< Text, IntWritable, Text, Text > reduceDriver;
private final String AUTHOR_1 = "Author1", AUTHOR_2 = "Author2";
private final int YEAR_1 = 2000, YEAR_2 = 2015;
@Before
public void setup() {
ActivityYearMapper mapper = new ActivityYearMapper();
ActivityYearReducer reducer = new ActivityYearReducer();
mapDriver = MapDriver.newMapDriver( mapper );
reduceDriver = ReduceDriver.newReduceDriver( reducer );
}
@Test
public void testMapper() throws IOException {
Text input1 = new Text( getXMLAuthorYear( AUTHOR_1, AUTHOR_2, YEAR_1 ) );
Text input2 = new Text( getXMLAuthorYear( AUTHOR_1, AUTHOR_2, YEAR_2 ) );
LongWritable longWritable = new LongWritable();
mapDriver.withInput( longWritable, input1 )
.withInput( longWritable, input2 )
.withOutput( new Text( AUTHOR_1 ), new IntWritable( YEAR_1 ) )
.withOutput( new Text( AUTHOR_2 ), new IntWritable( YEAR_1 ) )
.withOutput( new Text( AUTHOR_1 ), new IntWritable( YEAR_2 ) )
.withOutput( new Text( AUTHOR_2 ), new IntWritable( YEAR_2 ) )
.runTest();
}
@Test
public void testReducer() throws IOException {
int[] years = { YEAR_2, YEAR_1 };
reduceDriver.withInput( new Text( AUTHOR_1 ), getYearList( years, AuthorsPublications.NUMBER_OF_PUBLICATIONS + 1 ) )
.withInput( new Text( AUTHOR_2 ), getYearList( years, AuthorsPublications.NUMBER_OF_PUBLICATIONS ) )
.withOutput( new Text( AUTHOR_1 ), new Text( YEAR_1 + "-" + YEAR_2 ) )
.runTest();
}
private String getXMLAuthorYear( String author1, String author2, int year ) {
return "<article>"
+ "<author>" + author1 + "</author>"
+ "<author>" + author2 + "</author>"
+ "<year>" + year + "</year>"
+ "</article>";
}
private List< IntWritable > getYearList( int[] years, int publications ) {
List< IntWritable > output = new ArrayList< IntWritable >();
// To make sure the reducer catches it, since it needs more than a set number of publications
for( int i = 0; i < publications; i += years.length) {
for ( int year : years ) {
output.add( new IntWritable( year ) );
}
}
return output;
}
}
| true
|
731d44fab8a717807996bcac1189dc6363f383e1
|
Java
|
etsugua/pacmanpp
|
/src/pacmanpp/GameImages.java
|
UTF-8
| 5,865
| 2.75
| 3
|
[] |
no_license
|
package pacmanpp;
import java.awt.Font;
import java.awt.Image;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* GameImages purpose is to hold the various game images in one single point,
* working as a Manager of sorts.
*/
public class GameImages
{
private static GameImages instance = null;
// movable entities
private Image [][] pacmanSprites;
private Image [][] ghostSprites;
// shot
private Image shotSprite;
// world
private Image world;
// nomnoms
private Image [] nomnoms;
// info options
private Image [] optionSprites;
private Font scorefont = new Font(Font.MONOSPACED, Font.BOLD, 26);
private GameImages()
{
try
{
// load the pacman sprites
pacmanSprites = new Image[5][3];
//UP
pacmanSprites[Constants.UP][0] = ImageIO.read(new File("resources/imgs/pacman/pacman_closed.png"));
pacmanSprites[Constants.UP][1] = ImageIO.read(new File("resources/imgs/pacman/pacman_up_0.png"));
pacmanSprites[Constants.UP][2] = ImageIO.read(new File("resources/imgs/pacman/pacman_up_1.png"));
//DOWN
pacmanSprites[Constants.DOWN][0] = ImageIO.read(new File("resources/imgs/pacman/pacman_closed.png"));
pacmanSprites[Constants.DOWN][1] = ImageIO.read(new File("resources/imgs/pacman/pacman_down_0.png"));
pacmanSprites[Constants.DOWN][2] = ImageIO.read(new File("resources/imgs/pacman/pacman_down_1.png"));
//LEFT
pacmanSprites[Constants.LEFT][0] = ImageIO.read(new File("resources/imgs/pacman/pacman_closed.png"));
pacmanSprites[Constants.LEFT][1] = ImageIO.read(new File("resources/imgs/pacman/pacman_left_0.png"));
pacmanSprites[Constants.LEFT][2] = ImageIO.read(new File("resources/imgs/pacman/pacman_left_1.png"));
//RIGHT
pacmanSprites[Constants.RIGHT][0] = ImageIO.read(new File("resources/imgs/pacman/pacman_closed.png"));
pacmanSprites[Constants.RIGHT][1] = ImageIO.read(new File("resources/imgs/pacman/pacman_right_0.png"));
pacmanSprites[Constants.RIGHT][2] = ImageIO.read(new File("resources/imgs/pacman/pacman_right_1.png"));
// load the ghost sprites
ghostSprites = new Image[7][4];
ghostSprites[Constants.SPAWN][0] = ImageIO.read(new File("resources/imgs/ghost/split/ghost_split_0.png"));
ghostSprites[Constants.SPAWN][1] = ImageIO.read(new File("resources/imgs/ghost/split/ghost_split_1.png"));
ghostSprites[Constants.SPAWN][2] = ImageIO.read(new File("resources/imgs/ghost/split/ghost_split_2.png"));
//UP
ghostSprites[Constants.NORMAL_UP][0] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_up_0.png"));
ghostSprites[Constants.NORMAL_UP][1] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_up_1.png"));
//DOWN
ghostSprites[Constants.NORMAL_DOWN][0] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_down_0.png"));
ghostSprites[Constants.NORMAL_DOWN][1] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_down_1.png"));
//LEFT
ghostSprites[Constants.NORMAL_LEFT][0] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_left_0.png"));
ghostSprites[Constants.NORMAL_LEFT][1] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_left_1.png"));
//RIGHT
ghostSprites[Constants.NORMAL_RIGHT][0] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_right_0.png"));
ghostSprites[Constants.NORMAL_RIGHT][1] = ImageIO.read(new File("resources/imgs/ghost/normal/ghost_move_right_1.png"));
ghostSprites[Constants.BLUE][0] = ImageIO.read(new File("resources/imgs/ghost/blue/ghost_blue_0.png"));
ghostSprites[Constants.BLUE][1] = ImageIO.read(new File("resources/imgs/ghost/blue/ghost_blue_1.png"));
ghostSprites[Constants.BLUE][2] = ImageIO.read(new File("resources/imgs/ghost/blue/ghost_blue_2.png"));
ghostSprites[Constants.BLUE][3] = ImageIO.read(new File("resources/imgs/ghost/blue/ghost_blue_3.png"));
ghostSprites[Constants.JOIN][0] = ImageIO.read(new File("resources/imgs/ghost/join/ghost_join_0.png"));
ghostSprites[Constants.JOIN][1] = ImageIO.read(new File("resources/imgs/ghost/join/ghost_join_1.png"));
ghostSprites[Constants.JOIN][2] = ImageIO.read(new File("resources/imgs/ghost/join/ghost_join_2.png"));
// load the world sprite
world = ImageIO.read(new File("resources/imgs/map/world.png"));
// load the nomnoms sprites
nomnoms = new Image[2];
nomnoms[0] = ImageIO.read(new File("resources/imgs/general/nomnom.png"));
nomnoms[1] = ImageIO.read(new File("resources/imgs/general/nomnomCrystal.png"));
// load the option sprites
optionSprites = new Image [4];
optionSprites[Constants.RESET_GAME] = ImageIO.read(new File("resources/imgs/system/newgame.png"));
optionSprites[Constants.MUTE] = ImageIO.read(new File("resources/imgs/system/sound_on.png"));
optionSprites[Constants.UNMUTE] = ImageIO.read(new File("resources/imgs/system/sound_off.png"));
optionSprites[Constants.EXIT] = ImageIO.read(new File("resources/imgs/system/exit.png"));
// load the shot sprite
shotSprite = ImageIO.read(new File("resources/imgs/general/shot.png"));
}
catch (Exception ex)
{
Logger.getLogger(GameImages.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static GameImages getInstance()
{
if (instance == null)
instance = new GameImages();
return instance;
}
protected Image[][] getPacmanSprite ()
{
return pacmanSprites;
}
protected Image[][] getGhostSprites ()
{
return ghostSprites;
}
protected Image getShotSprite() {
return shotSprite;
}
protected Image getWorldSprite ()
{
return world;
}
protected Image [] getNomNomSprites()
{
return nomnoms;
}
protected Image [] getOptionSprites ()
{
return optionSprites;
}
protected Font getScoreFont ()
{
return scorefont;
}
}
| true
|
a2c4e1717e112133677ef6bc75d7e1379da4c72a
|
Java
|
Balnian/Extract
|
/src/Extract.java
|
UTF-8
| 4,761
| 3.0625
| 3
|
[] |
no_license
|
/**
* Created by 201250541 on 2015-04-08.
*/
import java.io.*;
public class Extract {
public static void main( String args[] )
{
if(args.length != 2)
{
System.out.println("Vous avez donnée: "+args.length+" Fichier(s) a la ligne de commande alors que nous en voulons seulement que 2 pas plus pas moins");
System.exit(0);
}
File source = new File(args[0]);
File target = new File(args[1]);
if(!source.exists())
{
System.out.println(args[0]+"n'existe pas");
System.exit(0);
}
else if (source.isDirectory())
{
System.out.println(args[0]+"n'existe pas");
System.exit(0);
}
else if( !args[0].toLowerCase().endsWith(".html"))
{
System.out.println(args[0]+" n'est pas un fichier HTML valide");
System.exit(0);
}
if(!target.exists())
{
System.out.println(args[1]+"n'existe pas");
System.exit(0);
}
else if (target.isDirectory())
{
System.out.println(args[1]+"n'existe pas");
System.exit(0);
}
else if( !args[1].toLowerCase().endsWith(".html"))
{
System.out.println(args[1]+" n'est pas un fichier HTML valide");
System.exit(0);
}
ShowTime(GetA(ReadFile(args[0])),args[1],args[0]);
//ShowTime(RipA(ReadFile(args[0])),args[1],args[0]);
}
private static String ReadFile(String file)
{
System.out.println("ReadFile Begin");
BufferedReader reader;
boolean pasFini = true;
String ligne;
String fichier="";
try
{
reader = new BufferedReader(
new FileReader( file ) );
while( pasFini )
{
ligne = reader.readLine();
if( ligne != null )
{
fichier += ligne ;
}
else
{
pasFini = false;
}
}
reader.close();
}
catch( IOException ioe )
{
System.err.println( ioe );
System.exit( 1 );
}
System.out.println("ReadFile End");
return fichier;
}
private static String GetA(String sourceTxt)
{
System.out.println("GetA Begin");
String carry="";
Integer pos=0;
String valuePairs="";
while ((pos =sourceTxt.indexOf("<a href=",(pos==0)?pos:pos+8)) != -1 )
{
carry += sourceTxt.substring(pos,sourceTxt.indexOf("</a>",pos)+4);
carry+=";";
}
System.out.println("GetA End");
return carry;
}
//Trop Overkill (rip l'url et le inner HTML puis les concataines sous le format: URL,innerHTML;URL2,innerHTML2;...
private static String RipA(String sourceTxt)
{
System.out.println("RipA Begin");
String carry;
Integer pos;
String valuePairs="";
while ((pos =sourceTxt.lastIndexOf("<a href=")) != -1 )
{
carry = sourceTxt.substring(pos,sourceTxt.lastIndexOf("</a>")+4);
sourceTxt = sourceTxt.substring(0,pos);
valuePairs+=carry.substring(carry.indexOf('"')+1,carry.lastIndexOf('"'));
valuePairs+=',';
valuePairs+=carry.substring(carry.indexOf(">")+1,carry.lastIndexOf("</"));
valuePairs+=';';
}
System.out.println("RipA End");
return valuePairs;
}
private static void ShowTime(String data,String target,String sourceName)
{
System.out.println("ShowTime Begin");
String val[] = data.split(";");
PrintWriter writer;
try
{
writer = new PrintWriter(
new BufferedWriter(
new FileWriter( target ) ) );
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<head><meta charset=\"utf-8\"></head>");
writer.println("<body>");
writer.println("Hyperliens estraits du fichier <b>"+sourceName+"</b>");
writer.println("<ul>");
for (int i = 0; i < val.length; i++) {
writer.println("<li>"+ val[i]+"</li>");
}
writer.println("</ul>");
writer.println("</body>");
writer.println("</html>");
writer.close();
}
catch( IOException ioe )
{
System.err.println( ioe );
System.exit( 1 );
}
System.out.println("ShowTime Begin");
}
}
| true
|
9ff8f94c6de03721a997fa4a0a6d292af6ae5a46
|
Java
|
haleeexis/c-o-d-e-s
|
/src/linkedlists/ListNode.java
|
UTF-8
| 208
| 2.359375
| 2
|
[] |
no_license
|
package linkedlists;
/**
* Created by alexisherrera on 9/9/17.
*/
public class ListNode<Data> {
public ListNode<Data> next;
public Data d;
public ListNode(Data d) {
this.d = d;
}
}
| true
|
89222b2039a778ee23f61c55a0a522169ba0ea5a
|
Java
|
parkje0927/SpringBoot_RESTful_webservice
|
/src/main/java/com/example/restfulwebservice/exception/ExceptionResponse.java
|
UTF-8
| 507
| 2.25
| 2
|
[] |
no_license
|
package com.example.restfulwebservice.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor //모든 객체를 갖고 있는 생성자
@NoArgsConstructor //기본 생성자
public class ExceptionResponse {
/**
* 예외가 발생한 시간
* 예외가 발생한 메세지
* 예외가 발생 내용
*/
private Date timeStamp;
private String message;
private String details;
}
| true
|
53b5d3a1afe8b25e869b74b5b4011bc64c3cb325
|
Java
|
426Brian/JUC
|
/juc-demo01/src/main/java/com/designPattern/single/SingleEnum.java
|
UTF-8
| 159
| 2.3125
| 2
|
[] |
no_license
|
package com.designPattern.single;
public enum SingleEnum {
// 枚举元素本身就是单列
INSTANCE;
public void singleOperation(){
}
}
| true
|
951b38bef02b13273c0e4fc6386da003add97ca0
|
Java
|
edorn18/KeyLimePie
|
/m5/given_parser/ast/FuncParamInstruction.java
|
UTF-8
| 506
| 2.265625
| 2
|
[] |
no_license
|
package ast;
import java.util.Hashtable;
import java.util.List;
import java.io.PrintWriter;
public class FuncParamInstruction
implements Instruction
{
private final String varName;
private final LLVMType varType;
public FuncParamInstruction(String varName, LLVMType varType) {
this.varName = varName;
this.varType = varType;
}
public void printInstruction(PrintWriter outFile) {
outFile.println("\t%_P_" + varName + " = alloca " + varType.getLLVMTypeName());
}
}
| true
|
f1bb379f65e0fe722790e370103d877d9e2f4d1e
|
Java
|
jadzalla/fermat-unused
|
/fermat-p2p-api/src/main/java/com/bitdubai/fermat_p2p_api/layer/p2p_communication/commons/enums/FermatPacketType.java
|
UTF-8
| 3,958
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
/*
* @#FMPPacketType.java - 2015
* Copyright bitDubai.com., All rights reserved.
* You may not modify, use, reproduce or distribute this software.
* BITDUBAI/CONFIDENTIAL
*/
package com.bitdubai.fermat_p2p_api.layer.p2p_communication.commons.enums;
/**
* The enum <code>com.bitdubai.fermat_p2p_api.layer.p2p_communication.commons.enums.FermatPacketType</code> define
* all types of Fermat Packet cam be
* <p/>
*
* Created by Roberto Requena - (rart3001@gmail.com) on 01/09/15.
*
* @version 1.0
* @since Java JDK 1.7
*/
public enum FermatPacketType {
// Definition types
/**
* This type is use when a server handshake respond
*/
SERVER_HANDSHAKE_RESPOND ("SRV_HS_RESP"),
/**
* This type is use when a vpn server handshake respond
*/
VPN_SERVER_HANDSHAKE_RESPOND ("VPN_SRV_HS_RESP"),
/**
* This type is use when a component registration request
*/
COMPONENT_REGISTRATION_REQUEST ("COMP_REG_REQ"),
/**
* This type is use when a component registration request is complete
*/
COMPLETE_COMPONENT_REGISTRATION("COMPL_COMP_REG"),
/**
* This type is use when need a list the components registered in the server
*/
REQUEST_LIST_COMPONENT_REGISTERED("REQ_LIST_COMP_REG"),
/**
* This type is use when a component disconnect request is made
*/
COMPONENT_DISCONNECT_REQUEST ("COMP_DISC_REQ"),
/**
* This type is use when a message delivery notification is made
*/
MESSAGE_DELIVERY_NOTIFICATION ("MSG_DEL_NOT"),
/**
* This type is use when a component connection request is made
*/
COMPONENT_CONNECTION_REQUEST ("COMP_CONNECT_REQ"),
/**
* This type is use when a component connection respond is made
*/
COMPONENT_CONNECTION_RESPOND ("COMP_CONNECT_RES"),
/**
* This type is use when a component connection request is complete, are
* participants are connected to the vpn, and is ready to send message
*/
COMPLETE_COMPONENT_CONNECTION_REQUEST("COMPL_COMP_CONNECT_REQ"),
/**
* This type is use whe an component send a message to another component
*/
MESSAGE_TRANSMIT ("MSG_TRANS");
/**
* Represent the code
*/
private String code;
/**
* Constructor whit parameter
*
* @param code
*/
private FermatPacketType(String code){
this.code = code;
}
/**
* (no-javadoc)
* @see Object#toString()
*/
@Override
public String toString() {
return this.code;
}
/**
* Return the FermatPacketType represented by the code pass as parameter
*
* @param code
* @return FermatPacketType
*/
public static FermatPacketType getByCode(final String code){
switch (code){
case "SRV_HS_RESP" : return FermatPacketType.SERVER_HANDSHAKE_RESPOND;
case "VPN_SRV_HS_RESP" : return FermatPacketType.VPN_SERVER_HANDSHAKE_RESPOND;
case "COMP_REG_REQ" : return FermatPacketType.COMPONENT_CONNECTION_REQUEST;
case "COMPL_COMP_REG" : return FermatPacketType.COMPLETE_COMPONENT_REGISTRATION;
case "REQ_LIST_COMP_REG" : return FermatPacketType.REQUEST_LIST_COMPONENT_REGISTERED;
case "COMP_DISC_REQ" : return FermatPacketType.COMPONENT_DISCONNECT_REQUEST;
case "MSG_DEL_NOT" : return FermatPacketType.MESSAGE_DELIVERY_NOTIFICATION;
case "COMP_CONNECT_REQ" : return FermatPacketType.COMPONENT_CONNECTION_REQUEST;
case "COMP_CONNECT_RES" : return FermatPacketType.COMPONENT_CONNECTION_RESPOND;
case "COMPL_COMP_CONNECT_REQ" : return FermatPacketType.COMPLETE_COMPONENT_CONNECTION_REQUEST;
case "MSG_TRANS" : return FermatPacketType.MESSAGE_TRANSMIT;
default: throw new IllegalArgumentException();
}
}
}
| true
|
c8aff828806f4b125ae84b85000d2b31f3f48449
|
Java
|
synlHR/meizuMall
|
/src/main/java/com/jojo/pojo/Address.java
|
UTF-8
| 2,147
| 2.296875
| 2
|
[] |
no_license
|
package com.jojo.pojo;
import java.io.Serializable;
import java.util.List;
public class Address implements Serializable {
private Integer aid;
private Integer uid;
private String name;
private String tel;
private String province;
private String city;
private String country;
private String addresDetail;
private static final long serialVersionUID = 1L;
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel == null ? null : tel.trim();
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city == null ? null : city.trim();
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country == null ? null : country.trim();
}
public String getAddresDetail() {
return addresDetail;
}
public void setAddresDetail(String addresDetail) {
this.addresDetail = addresDetail == null ? null : addresDetail.trim();
}
@Override
public String toString() {
return "Address{" +
"aid=" + aid +
", uid=" + uid +
", name='" + name + '\'' +
", tel='" + tel + '\'' +
", province='" + province + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
", addresDetail='" + addresDetail+
'}';
}
}
| true
|
4c23aa25963e7cb096cae6aa9fa98662aa7bbfc2
|
Java
|
29592/IOT
|
/KPC IoT 공유/02 JSP Servlet/02 lab/lab12 문제 20180206/src폴더에복사하세요/jdbcex/emp/EmpDAO.java
|
UTF-8
| 3,329
| 2.671875
| 3
|
[] |
no_license
|
package jdbcex.emp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import jdbcex.DBManager;
public class EmpDAO {
public EmpVO getEmp(int EmpNo) {
Connection conn = DBManager.getConnection();
EmpVO vo = null;
try {
PreparedStatement stmt = null;
ResultSet rs = null;
stmt = conn
.prepareStatement("SELECT empno, ename, job FROM emp WHERE empno = ?");
stmt.setInt(1, EmpNo);
rs = stmt.executeQuery();
while (rs.next()) {
vo = new EmpVO();
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
vo.setEmpNo(empno);
vo.setEname(ename);
vo.setJob(job);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return vo;
}
public ArrayList<EmpVO> getEmpList(int deptno) {
Connection conn = DBManager.getConnection();
ArrayList<EmpVO> arrayList = new ArrayList<EmpVO>();
EmpVO vo = null;
try {
PreparedStatement stmt = null;
ResultSet rs = null;
stmt = conn.prepareStatement("SELECT * FROM emp where deptno = ?");
stmt.setInt(1, deptno);
rs = stmt.executeQuery();
while (rs.next()) {
vo = new EmpVO();
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
vo.setEmpNo(empno);
vo.setEname(ename);
vo.setJob(job);
arrayList.add(vo);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return arrayList;
}
public int insertEmp(EmpVO vo) {
Connection conn = DBManager.getConnection();
int resultCnt = 0;
try {
PreparedStatement stmt = null;
stmt = conn
.prepareStatement("Insert into emp (empno, ename, job) values(?, ?, ?)");
stmt.setInt(1, vo.getEmpNo());
stmt.setString(2, vo.getEname());
stmt.setString(3, vo.getJob());
resultCnt = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resultCnt;
}
public int deleteEmp(int empNo) {
Connection conn = DBManager.getConnection();
int resultCnt = 0;
try {
PreparedStatement stmt = null;
stmt = conn.prepareStatement("DELETE FROM emp WHERE empno = ?");
stmt.setInt(1, empNo);
resultCnt = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resultCnt;
}
public int updateEmp(EmpVO vo) {
Connection conn = DBManager.getConnection();
int resultCnt = 0;
try {
PreparedStatement stmt = null;
stmt = conn
.prepareStatement("UPDATE emp SET ename = ?, job = ? where empno = ?");
stmt.setString(1, vo.getEname());
stmt.setString(2, vo.getJob());
stmt.setInt(3, vo.getEmpNo());
resultCnt = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resultCnt;
}
}
| true
|
915a8dd9c110be195316045f159c8b3dc8ebb94e
|
Java
|
tovikfekih/L3-Miage-depot-TP
|
/POO/TP4-1/src/Epaisseur.java
|
UTF-8
| 43
| 1.585938
| 2
|
[] |
no_license
|
public enum Epaisseur {
LARGE , ETROIT
}
| true
|
bea51212a2e9c3f1867bbdca293d46da7850f452
|
Java
|
nebbii/HetFruitHuisje
|
/src/hetfruithuisje/db.java
|
UTF-8
| 1,002
| 2.375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hetfruithuisje;
import java.sql.*;
import javax.swing.*;
/**
*
* @author Sammy Guergachi <sguergachi at gmail.com>
*/
public class db {
private static final String USERNAME="root";
private static final String PASSWORD="root";
private static final String CON_STRING="jdbc:mysql://localhost:8889/hetfruithuisje";
Connection conn = null;
public static Connection java_db(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(CON_STRING, USERNAME, PASSWORD);
System.out.println("Conntected");
return conn;
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
| true
|
273c50767281a5f431da42d3c71cbd0e908d1186
|
Java
|
mbbush/BartRunnerAndroid
|
/app/src/main/java/com/dougkeen/bart/networktasks/FareContentHandler.java
|
UTF-8
| 1,094
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.dougkeen.bart.networktasks;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.HashMap;
import java.util.Map;
public class FareContentHandler extends DefaultHandler {
public FareContentHandler() {
super();
}
private String fare;
public String getFare() {
return fare;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("fare".equals(localName)) {
Map<String, String> attributeMap = new HashMap<>();
for (int i = attributes.getLength() - 1; i >= 0; i--) {
attributeMap.put(attributes.getLocalName(i), attributes.getValue(i));
}
if (attributeMap.containsKey("class")
&& "cash".equals(attributeMap.get("class"))
&& attributeMap.get("amount") != null) {
fare = "$" + attributeMap.get("amount");
}
}
}
}
| true
|
6b3089e2a5f3ea4882134e4586a472d824f729e5
|
Java
|
badrjee/Editique_TEST_2
|
/src/main/java/fr/meg/batch/service/ClientServiceImpl.java
|
UTF-8
| 711
| 2.21875
| 2
|
[] |
no_license
|
package fr.meg.batch.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import fr.meg.batch.dao.ClientRepository;
import fr.meg.batch.domain.Client;
public class ClientServiceImpl implements ClientService {
@Autowired
private ClientRepository repo;
public void saveClient(Client c) {
repo.save(c);
}
public Client getValidatedClient(int id) {
Client result = new Client();
Optional<Client> c = repo.findById(id);
if(c.isPresent()) result =c.get();
return result;
}
public List<Client> getAllClient() {
return repo.findAll();
}
public void deleteClient(int id) {
repo.deleteById(id);
}
}
| true
|
bf2f938013e617aa4af4e29974bb786fdeb0d5b6
|
Java
|
Saffierr/inleiding-java
|
/src/h04/Opdracht7.java
|
UTF-8
| 766
| 3.21875
| 3
|
[] |
no_license
|
package h04;
import java.awt.*;
import java.applet.Applet;
public class Opdracht7 extends Applet
{
public void paint(Graphics g)
{
setSize(1000, 1000);
setBackground(Color.GRAY);
g.setColor(Color.BLACK);
g.fillRect(150, 200, 150, 110);
g.drawRect(150, 200, 150, 110);
g.setColor(Color.WHITE);
g.fillOval(155, 205, 20, 20);
g.drawOval(155, 205, 20, 20);
g.setColor(Color.WHITE);
g.fillOval(275, 205, 20, 20);
g.drawOval(275, 205, 20, 20);
g.setColor(Color.WHITE);
g.fillOval(155, 285, 20, 20);
g.drawOval(155, 285, 20, 20);
g.setColor(Color.WHITE);
g.fillOval(275, 285, 20, 20);
g.drawOval(275, 285, 20, 20);
}
}
| true
|
c89520db542bed5813253b87297a95edee676424
|
Java
|
SorghumBlue/supermarket
|
/src/main/java/com/kgc/dao/BillMapper.java
|
UTF-8
| 364
| 1.828125
| 2
|
[] |
no_license
|
package com.kgc.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.kgc.pojo.Bill;
public interface BillMapper extends BaseMapper<Bill> {
int deleteByPrimaryKey(Long id);
int insertSelective(Bill record);
Bill selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Bill record);
int updateByPrimaryKey(Bill record);
}
| true
|
e79a38637ea041f233791eb269273511e47c1008
|
Java
|
Tashimadilrukshi/InsertionSort
|
/InsertionSorting.java
|
UTF-8
| 899
| 3.390625
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class InsertionSorting {
public static void insertionSorting(int arr[]){
int k ,temp,j ;
for(int i=1;i<arr.length;i++){
k=arr[i];
j=i-1;
while(j>=0 && k<arr[j]){
temp=arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;
j--;
}
}
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int n= s.nextInt();
System.out.println();
int[] arr=new int[n];
for(int i=0; i<arr.length; i++){
arr[i]=s.nextInt();
}
System.out.println();
insertionSorting(arr);
}
}
| true
|
e47ea1bb220376e44ac92e244ebc542d4799d3cb
|
Java
|
xhom/vue-creater
|
/src/main/java/com/vz/vue/model/Column.java
|
UTF-8
| 2,736
| 2.703125
| 3
|
[] |
no_license
|
package com.vz.vue.model;
/**
* 字段实体
* @auhtor visy.wang
*/
public class Column {
private String name; //字段名
/**
* 关于字段注释的约定:
* 1.如果注释不是一个正确格式的json对象,则不提取任何信息,整个注释会被当作字段的描述
* 2.如果注释内容为json对象并符合以下约定则会提取其中的信息,并在页面生成时应用:
* {
* "desc": "姓名", //字段描述
* "input": "select", //控件类型,选填,默认input, 可选值见:INPUT_TYPE
* "type": ["required","email"] //校验类型,选填,默认required, 可选值见:VALIDATE_TYPE
* }
*/
private String comment; //列注释
private String dataType; //列数据类型
private Integer maxLength; //字段最大长度
private Boolean isNull; //是否必填
private Boolean isPriKey; //是否主键
private String type; //列类型
private Boolean isRow = true; //基础字段
private Boolean isCond = true; //是否条件字段
private Boolean isField = true; //是否编辑字段
private Boolean isRule = true; //是否校验字段
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public Integer getMaxLength() {
return maxLength;
}
public void setMaxLength(Integer maxLength) {
this.maxLength = maxLength;
}
public Boolean getIsNull() {
return isNull;
}
public void setIsNull(Boolean aNull) {
isNull = aNull;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getIsPriKey() {
return isPriKey;
}
public void setIsPriKey(Boolean priKey) {
isPriKey = priKey;
}
public Boolean getIsField() {
return isField;
}
public void setIsField(Boolean field) {
isField = field;
}
public Boolean getIsCond() {
return isCond;
}
public void setIsCond(Boolean cond) {
isCond = cond;
}
public Boolean getIsRule() {
return isRule;
}
public void setIsRule(Boolean rule) {
isRule = rule;
}
public Boolean getIsRow() {
return isRow;
}
public void setIsRow(Boolean row) {
isRow = row;
}
}
| true
|
b249b0c6fc5919514a82aff51393d8d5515065ab
|
Java
|
Jackalantern29/QubeMC
|
/QCRewards/src/com/Jackalantern29/QCRewards/Listeners/Listeners.java
|
UTF-8
| 435
| 1.992188
| 2
|
[] |
no_license
|
package com.Jackalantern29.QCRewards.Listeners;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.event.Listener;
public class Listeners {
static List<Listener> list = new ArrayList<Listener>();
public static List<Listener> getListeners() {
list.clear();
list.add(new JoinListener());
list.add(new SignCreateListener());
list.add(new SignInteractListener());
return list;
}
}
| true
|
36739628f33c92471b2e7745526184fd3428b58b
|
Java
|
SYYP/knowledgeshare
|
/app/src/main/java/www/knowledgeshare/com/knowledgeshare/utils/MyContants.java
|
UTF-8
| 4,902
| 1.664063
| 2
|
[] |
no_license
|
package www.knowledgeshare.com.knowledgeshare.utils;
public class MyContants {
public static String FILENAME = "config.xml";
public static String BASEURL = "http://39.107.91.92:82/";
public static String LXKURL = "http://39.107.91.92:82/api/v2/";//47.104.173.223/api/v2/index
public static String IMGBASEURL = "";
//短信发送
public static final String verifycodes = BASEURL + "api/v2/verifycodes";
//绑定微信获取验证码
public static final String bindWxSms = BASEURL + "api/v2/verifycodes/wx-bind-code";
//注册第一步
public static final String registSetOne = BASEURL + "api/v2/register/set-one";
//注册第二步
public static final String registSetTwo = BASEURL + "api/v2/register/set-two";
//获取标签
public static final String tag = BASEURL + "api/v2/tag";
//登录授权
public static final String login = BASEURL + "api/v2/tokens";
//启动信息
public static final String bootstrappers = BASEURL + "api/v2/bootstrappers";
//找回密码发送短信
public static final String getPwdCode = BASEURL + "api/v2/verifycodes/get-pwd-code";
//密码找回第一步验证手机号
public static final String getOnePwd = BASEURL + "api/v2/password/get-one-pwd";
//重置密码第二步
public static final String getTwoPwd = BASEURL + "api/v2/password/set-two-pwd";
//购物车列表
public static final String cartList = BASEURL + "api/v2/order/cart-list";
//购物车结算
public static final String submitOrder = BASEURL + "api/v2/order/submit-order";
//删除购物车
public static final String delCart = BASEURL + "api/v2/order/del-cart";
//修改密码
public static final String editPwd = BASEURL + "api/v2/user/edit-pwd";
//我的订阅
public static final String rss = BASEURL + "api/v2/user/rss";
//已购 轻松音乐课
public static final String buyXk = BASEURL + "api/v2/user/buy-xk";
//已购 音乐大师班
public static final String buyZl = BASEURL + "api/v2/user/buy-zl";
//添加笔记
public static final String addNote = BASEURL + "api/v2/note/add";
//学习列表
public static final String noteList = BASEURL + "api/v2/note";
//历史今天收藏
public static final String dayFavorite = BASEURL + "api/v2/note/day-favorite";
//历史今天取消收藏
public static final String dayNoFacorite = BASEURL + "api/v2/note/day-no-favorite";
//编辑笔记
public static final String editNote = BASEURL + "api/v2/note/edit";
//删除笔记
public static final String delNote = BASEURL + "api/v2/note/del";
//个人信息
public static final String userInfo = BASEURL + "api/v2/user/info";
//更换头像
public static final String uploadAvatar = BASEURL + "api/v2/user/upload-avatar";
//个人信息更新
public static final String editInfo = BASEURL + "api/v2/user/edit-info";
//购买记录
public static final String buyHistory = BASEURL + "api/v2/user/buy-history";
//意见反馈
public static final String feedBack = BASEURL + "api/v2/user/feedback";
//帮助中心
public static final String help = BASEURL + "api/v2/help";
//注册协议
public static final String registration = BASEURL + "api/v2/reg";
//关于我们
public static final String aboutUs = BASEURL + "api/v2/aboutus";
//学习,右上角专栏课程通知
public static final String notice = BASEURL + "api/v2/note/notices";
//充值
public static final String recharge = BASEURL + "api/v2/user/recharge";
//我的收藏
public static final String favorite = BASEURL + "api/v2/user/favorite";
//我的金句
public static final String gold = BASEURL + "api/v2/user/gold";
//下载数据获取接口
public static final String downLoad = BASEURL + "api/v2/down";
//消息通知
public static final String nitification = BASEURL + "api/v2/user/notifications";
//学习笔记
public static final String notes = BASEURL + "api/v2/user/notes";
//签到
public static final String signIn = BASEURL + "api/v2/user/sign-in";
//是否绑定手机
public static final String isBindMobile = BASEURL + "api/v2/is-bind-mobile";
//绑定手机
public static final String bindMobile = BASEURL + "api/v2/bind-mobile";
//个人中心绑定微信(token)
public static final String bindWx = BASEURL + "api/v2/user/bind-wx";
//删除消息通知(token)
public static final String delNotification = BASEURL + "api/v2/user/del-notification";
//任务详情
public static final String taskList = BASEURL + "api/v2/user/task-list";
//我的账号 金额列表
public static final String changeShow = BASEURL + "api/v2/user/recharge-show";
//退出
public static final String logout = BASEURL + "api/v2/user/logout";
}
| true
|
6ae050088bcfc41d3f3d1dc3b571ea577f6f3fd8
|
Java
|
chapie1/unbbayes
|
/unbbayes.prs.mebn/src/test/java/unbbayes/prs/mebn/ontology/StartrekTestSet.java
|
UTF-8
| 2,947
| 2.21875
| 2
|
[] |
no_license
|
package unbbayes.prs.mebn.ontology;
import java.io.File;
import java.text.NumberFormat;
import java.util.Locale;
import unbbayes.io.mebn.UbfIO;
import unbbayes.prs.mebn.MultiEntityBayesianNetwork;
import unbbayes.prs.mebn.kb.KnowledgeBase;
import unbbayes.prs.mebn.kb.powerloom.PowerLoomKB;
import unbbayes.prs.mebn.ssbn.ISSBNGenerator;
import unbbayes.prs.mebn.ssbn.Query;
import unbbayes.prs.mebn.ssbn.giaalgorithm.ExplosiveSSBNGenerator;
/**
* TODO use JUnit Framework.
*
*/
public class StartrekTestSet extends TestSet{
//Names of files
private static final String STARTREK_UBF_FILE = "examples/mebn/StarTrek/StarTrek.ubf";
private static final String TEST_FILE_NAME = "StarTrekTestSet.log";
private static final String PATH = "examples/mebn/Tests/StarTrekTestSet";
private static final String KB_SITUATION1 = "examples/mebn/StarTrek/KnowledgeBase_Situation1.plm";
//Variables
private MultiEntityBayesianNetwork mebn;
private static int testNumber = 0;
public StartrekTestSet(ISSBNGenerator ssbnGenerator){
super(ssbnGenerator);
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMaximumFractionDigits(2);
//Loading the network
UbfIO io = UbfIO.getInstance();
try {
mebn = io.loadMebn(new File(STARTREK_UBF_FILE));
} catch (Exception e) {
e.printStackTrace();
logManager.appendln(e.toString());
finishLog(PATH + "/" + TEST_FILE_NAME);
System.exit(1);
}
File directory = new File(PATH);
if(!directory.exists()){
directory.mkdir();
}
}
public static void main(String arguments[]){
ISSBNGenerator ssbnGenerator = new ExplosiveSSBNGenerator();
TestSet testSet = new StartrekTestSet(ssbnGenerator);
testSet.executeTests();
testSet.finishLog(PATH + "/" + TEST_FILE_NAME);
}
public void executeTests(){
executeTest1();
}
public void executeTest1(){
Query query = createQueryNode_HarmPotential_ST4_T3(mebn);
executeTestCase(
1,
query.getQueryNode().getResident().getName(),
query.getQueryNode().getResident().getMFrag().getName(),
KB_SITUATION1 ,
query);
}
private void executeTestCase(int index, String nameResidentNode, String nameMFrag,
String findingFileName, Query query){
printTestHeader(index, nameResidentNode);
testNumber++;
KnowledgeBase kb = PowerLoomKB.getNewInstanceKB();
kb.createGenerativeKnowledgeBase(mebn);
boolean loaded = loadFindingModule(kb, findingFileName);
if(!loaded){
return;
}
query.setKb(kb);
executeQueryAndPrintResults(query, PATH + "/" + "Test" + testNumber + ".xml");
}
private Query createQueryNode_HarmPotential_ST4_T3(MultiEntityBayesianNetwork mebn) {
return createGenericQueryNode(mebn, "Starship_MFrag", "HarmPotential", new String[]{"st", "t"}, new String[]{"ST4", "T3"}, null);
}
}
| true
|
265276fbff8cc94fa0662b1ea04140ba000357fb
|
Java
|
LirolaJose/cerebro-back
|
/src/test/java/com/dataart/cerebro/service/AdvertisementOrderServiceTest.java
|
UTF-8
| 2,814
| 2.109375
| 2
|
[] |
no_license
|
package com.dataart.cerebro.service;
import com.dataart.cerebro.controller.dto.AdvertisementOrderDTO;
import com.dataart.cerebro.domain.*;
import com.dataart.cerebro.email.EmailService;
import com.dataart.cerebro.repository.AdditionalServiceRepository;
import com.dataart.cerebro.repository.AdvertisementOrderRepository;
import com.dataart.cerebro.repository.AdvertisementRepository;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
class AdvertisementOrderServiceTest {
@Test
void whenOrderIsAddedThenEmailsAreSend() {
//given
AdvertisementOrderRepository advertisementOrderRepositoryMock = mock(AdvertisementOrderRepository.class);
EmailService emailServiceMock = mock(EmailService.class);
UserInfo customerInfoMock = mock(UserInfo.class);
UserInfoService userInfoServiceMock = mock(UserInfoService.class);
AdvertisementOrderDTO advertisementDTOMock = mock(AdvertisementOrderDTO.class);
AdvertisementRepository advertisementRepositoryMock = mock(AdvertisementRepository.class);
AdditionalServiceService additionalServiceServiceMock = mock(AdditionalServiceService.class);
AdditionalServiceRepository additionalServiceRepository = mock(AdditionalServiceRepository.class);
AdvertisementService advertisementServiceMock = mock(AdvertisementService.class);
AdvertisementOrderService advertisementOrderService = new AdvertisementOrderService(advertisementOrderRepositoryMock,
emailServiceMock, userInfoServiceMock, advertisementRepositoryMock, advertisementServiceMock, additionalServiceServiceMock, additionalServiceRepository);
AdvertisementOrder advertisementOrder = new AdvertisementOrder();
Advertisement ad = new Advertisement();
ad.setPrice(20.0);
ad.setType(Type.SELL);
ad.setStatus(Status.ACTIVE);
advertisementOrder.setAdvertisement(ad);
AdvertisementOrder exceptedOrder = new AdvertisementOrder();
Advertisement ad1 = new Advertisement();
ad1.setStatus(Status.SOLD);
exceptedOrder.setAdvertisement(ad1);
when(userInfoServiceMock.getCurrentUser()).thenReturn(customerInfoMock);
when(advertisementServiceMock.findAdvertisementById(anyLong())).thenReturn(ad);
when(additionalServiceServiceMock.getAdditionalServicesTotalPrice(anySet())).thenReturn((0.0));
when(advertisementOrderRepositoryMock.save(any())).thenReturn(exceptedOrder);
//when
advertisementOrderService.createNewAdvertisementOrder(advertisementDTOMock);
//then
verify(emailServiceMock, times(1)).sendEmailAboutPurchase(exceptedOrder, customerInfoMock);
verify(emailServiceMock, times(1)).sendEmailAboutSell(exceptedOrder, customerInfoMock);
}
}
| true
|
d9e6d6f7a313cfb6c92844e2992f0ef0e265ded9
|
Java
|
harperjiang/LeetCode
|
/src/verify_preorder_sequence_in_binary_tree/Solution.java
|
UTF-8
| 763
| 2.921875
| 3
|
[] |
no_license
|
package verify_preorder_sequence_in_binary_tree;
public class Solution {
int verify(int[] preorder, int pointer, int lb, int ub) {
if (pointer >= preorder.length) {
return 0;
}
int root = preorder[pointer];
if (root > ub || root < lb) {
return 0;
}
int llength = verify(preorder, pointer + 1, lb, root);
int rlength = verify(preorder, pointer + 1 + llength, root, ub);
return llength + rlength + 1;
}
public boolean verifyPreorder(int[] preorder) {
return preorder.length == verify(preorder, 0, -1, 10001);
}
public static void main(String[] args) {
System.out.println(new Solution().verifyPreorder(new int[]{5, 2, 1, 3, 6}));
}
}
| true
|
d5933eea26d0cd235f54481519c120ac2be90d9d
|
Java
|
adowning/rocky
|
/android_bak_newest/app/src/main/java/com/andrews/app/tracker/ParseSyncService.java
|
UTF-8
| 15,829
| 1.875
| 2
|
[] |
no_license
|
///*
// * Copyright (c) 2017 Bartek Fabiszewski
// * http://www.fabiszewski.net
// *
// * This file is part of μlogger-android.
// * Licensed under GPL, either version 3, or any later.
// * See <http://www.gnu.org/licenses/>
// */
//
//package com.andrews.app.tracker;
//
//import android.annotation.SuppressLint;
//import android.app.AlarmManager;
//import android.app.IntentService;
//import android.app.PendingIntent;
//import android.content.Context;
//import android.content.Intent;
//import android.database.Cursor;
//import android.icu.text.SimpleDateFormat;
//import android.icu.util.Calendar;
//import android.os.Build;
//import android.provider.Settings;
//import android.support.annotation.RequiresApi;
//import android.util.Log;
//
//import com.cloudant.sync.documentstore.DocumentStore;
//import com.cloudant.sync.documentstore.DocumentStoreException;
//import com.cloudant.sync.documentstore.DocumentStoreNotDeletedException;
//import com.cloudant.sync.documentstore.DocumentStoreNotOpenedException;
//import com.cloudant.sync.replication.Replicator;
//import com.cloudant.sync.replication.ReplicatorBuilder;
//import com.parse.Parse;
//import com.parse.ParseObject;
//
//import org.json.JSONException;
//
//import java.io.File;
//import java.io.IOException;
//import java.net.ConnectException;
//import java.net.MalformedURLException;
//import java.net.NoRouteToHostException;
//import java.net.URI;
//import java.net.URISyntaxException;
//import java.net.UnknownHostException;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import static android.app.PendingIntent.FLAG_ONE_SHOT;
//
///**
// * Service synchronizing local database positions with remote server.
// *
// */
//
//public class ParseSyncService extends IntentService {
//
// private static final String TAG = ParseSyncService.class.getSimpleName();
// public static final String BROADCAST_SYNC_FAILED = "net.fabiszewski.ulogger.broadcast.sync_failed";
// public static final String BROADCAST_SYNC_DONE = "net.fabiszewski.ulogger.broadcast.sync_done";
// String deviceId;
//
// private DbAccess db;
// private WebHelper web;
// private ParseHelper parse;
// private static boolean isAuthorized = false;
// private static PendingIntent pi = null;
//
// final private static int FIVE_MINUTES = 1000 * 60 * 5;
//
//
// /**
// * Constructor
// */
// public ParseSyncService() {
// super("ParseSyncService");
// }
// // Main data model object
// private DocumentStore mDocumentStore;
//
// private static LocationsModel sTasks;
// private static final String DOCUMENT_STORE_DIR = "data";
// private static final String DOCUMENT_STORE_NAME = "tasks";
// private LocationAdapter mTaskAdapter;
// @SuppressLint("HardwareIds")
// @Override
// public void onCreate() {
// super.onCreate();
// Log.d(TAG, "[parseSync create]");
// File path = getBaseContext().getDir("documentstores", Context.MODE_PRIVATE);
//
// deviceId = Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
// parse = new ParseHelper(this);
// db = DbAccess.getInstance();
// db.open(this);
// if (sTasks == null) {
// // Model needs to stay in existence for lifetime of app.
// try {
// this.sTasks = new LocationsModel(this.getApplicationContext());
// } catch (URISyntaxException e) {
// e.printStackTrace();
// }
// }
//
// // Register this activity as the listener to replication updates
// // while its active.
//// this.sTasks.setReplicationListener(this);
// URI uri = null;
// File path2 = this.getApplicationContext().getDir(
// DOCUMENT_STORE_DIR,
// Context.MODE_PRIVATE
// );
//
// try {
// this.mDocumentStore = DocumentStore.getInstance(new File(path2, DOCUMENT_STORE_NAME));
// } catch (DocumentStoreNotOpenedException e) {
// Log.e(TAG, "Unable to open DocumentStore", e);
// }
// try {
// Log.d(TAG, "uri xxxxx");
// String username = "8e41cb6a-9660-44fc-a60e-3cbd4c952423-bluemix";
// String dbName = "raw_location_updates";
// String apiKey = "neciandervendisymandarda";
// String apiSecret = "a52173490312d0b5aabdb38e3647138a898741a0";
// String host = username + ".cloudant.com";
//
// // We recommend always using HTTPS to talk to Cloudant.
// uri = new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName, null, null);
//// uri = new URI("http://74.192.104.240:8082/locationupdates");
// // uri = new URI("https://50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix:96b969836e91f94661cba0fbc9e4fa38e0984cc16de8818e23d87af1ff91c482@50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix.cloudant.com/raw_location_updates");
//// uri = new URI("https://iHknLlWH7Ep1p9wKHnNkuTi1rIQcnDldQ_rp4fBKnVx8:96b969836e91f94661cba0fbc9e4fa38e0984cc16de8818e23d87af1ff91c482@50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix.cloudant.com/raw_location_updates");
//// uri = new URI("https", "iHknLlWH7Ep1p9wKHnNkuTi1rIQcnDldQ_rp4fBKnVx8" + ":" + "96b969836e91f94661cba0fbc9e4fa38e0984cc16de8818e23d87af1ff91c482", "50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix.cloudant.com", 443, "/" + "raw_location_updates", null, null);
//// uri = new URI( "https://50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix:96b969836e91f94661cba0fbc9e4fa38e0984cc16de8818e23d87af1ff91c482@50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix.cloudant.com");
//// return new URI("https://iHknLlWH7Ep1p9wKHnNkuTi1rIQcnDldQ_rp4fBKnVx8:96b969836e91f94661cba0fbc9e4fa38e0984cc16de8818e23d87af1ff91c482@50c7e1e9-f42d-4571-8264-6db36cec19e6-bluemix.cloudant.com/raw_location_updates");
//
// } catch (URISyntaxException e) {
// e.printStackTrace();
// }
// Log.d(TAG, uri.toString());
//
// Replicator replicator = ReplicatorBuilder.push()
// .from(this.mDocumentStore)
// .to(uri)
//// .iamApiKey("iHknLlWH7Ep1p9wKHnNkuTi1rIQcnDldQ_rp4fBKnVx8")
// .build();
//// Replicator replicator = ReplicatorBuilder.push().from( this.mDocumentStore).to(uri).build();
//// Fire-and-forget (there are easy ways to monitor the state too)
//// replicator.start();
// }
//
// /**
// * Handle synchronization intent
// * @param intent Intent
// */
// @RequiresApi(api = Build.VERSION_CODES.N)
// @Override
// protected void onHandleIntent(Intent intent) {
// Log.d(TAG, "[parseSync start]");
//
// if (pi != null) {
// // cancel pending alarm
// if (Logger.DEBUG) { Log.d(TAG, "[websync cancel alarm]"); }
// AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// if (am != null) {
// am.cancel(pi);
// }
// pi = null;
// }
//
// if (!isAuthorized) {
// try {
// parse.authorize();
// } catch (WebAuthException|IOException |JSONException e) {
// handleError(e);
// return;
// }
//
// isAuthorized = true;
// }
//
// // get track id
// int trackId = getTrackId();
// if (trackId > 0) {
// doSync(trackId);
// }
// }
//
// /**
// * Get track id
// * If the track hasn't been registered on server yet,
// * get set up new track on the server and get new id
// * @return Track id
// */
// @RequiresApi(api = Build.VERSION_CODES.N)
// private int getTrackId() {
// int trackId = db.getTrackId();
// if (trackId == 0) {
// String trackName = db.getTrackName();
// trackId = 1;
//// trackId = web.startTrack(trackName);
//// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
//// db.setTrackId(Integer.valueOf(timeStamp));
// db.setTrackId(trackId);
//// db.setTrackId(trackId);
//
// // schedule retry
//// handleError(e);
//
//// isAuthorized = false;
//
//// // reauthorize and retry
//// web.authorize();
//// isAuthorized = true;
//// trackId = web.startTrack(trackName);
//// db.setTrackId(trackId);
//// } catch (WebAuthException|IOException|JSONException e2) {
//// // schedule retry
//// handleError(e2);
//
//
//// timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
// return trackId;
//// return trackId;
// }
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
// return trackId;
//
//// return Integer.valueOf(timeStamp);
//
// }
// private void createNewTask(Map<String, String> params) {
// Location t = new Location(params);
// sTasks.createDocument(t);
// reloadTasksFromModel();
// }
//
// /**
// * Synchronize all positions in database.
// * Skips already synchronized, uploads new ones
// * @param trackId Current track id
// */
// private void doSync(int trackId) {
// Log.d(TAG, "do sync");
// // iterate over positions in db
// Cursor cursor = db.getUnsynced();
// // suppress as it requires target api 19
// //noinspection TryFinallyCanBeTryWithResources
// try {
// while (cursor.moveToNext()) {
// int rowId = cursor.getInt(cursor.getColumnIndex(DbContract.Positions._ID));
// Map<String, String> params = cursorToMap(cursor);
// params.put(WebHelper.PARAM_TRACKID, String.valueOf(trackId));
// params.put("deviceId", deviceId);
//
//// web.postPosition(params);
// parse.postPosition(params);
// createNewTask(params);
// db.setSynced(rowId);
// Intent intent = new Intent(BROADCAST_SYNC_DONE);
// sendBroadcast(intent);
// }
// } catch (Exception e) {
// // handle web errors
// if (Logger.DEBUG) { Log.d(TAG, "[websync io exception: " + e + "]"); }
// // schedule retry
// // handleError(e);
//
//// if (Logger.DEBUG) { Log.d(TAG, "[websync auth exception: " + e + "]"); }
// isAuthorized = false;
//
// // reauthorize and retry
// // web.authorize();
// isAuthorized = true;
// doSync(trackId);
//
// // schedule retry
// // handleError(e2);
//
// } finally {
// cursor.close();
// }
// }
//
// /**
// * Actions performed in case of synchronization error.
// * Send broadcast to main activity, schedule retry if tracking is on.
// *
// * @param e Exception
// */
// private void handleError(Exception e) {
// String message;
// if (e instanceof UnknownHostException) {
//// message = getString(R.string.e_unknown_host, e.getMessage());
// } else if (e instanceof MalformedURLException || e instanceof URISyntaxException) {
//// message = getString(R.string.e_bad_url, e.getMessage());
// } else if (e instanceof ConnectException || e instanceof NoRouteToHostException) {
//// message = getString(R.string.e_connect, e.getMessage());
// } else {
// message = e.getMessage();
// }
// message = e.getMessage();
// if (Logger.DEBUG) { Log.d(TAG, "[websync retry: " + message + "]"); }
//
// db.setError(message);
// Intent intent = new Intent(BROADCAST_SYNC_FAILED);
// intent.putExtra("message", message);
// sendBroadcast(intent);
// // retry only if tracking is on
// if (LoggerService.isRunning()) {
// if (Logger.DEBUG) { Log.d(TAG, "[websync set alarm]"); }
// AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Intent syncIntent = new Intent(getApplicationContext(), ParseSyncService.class);
// pi = PendingIntent.getService(this, 0, syncIntent, FLAG_ONE_SHOT);
// if (am != null) {
// am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + FIVE_MINUTES, pi);
// }
// }
// }
//
// /**
// * Convert cursor to map of request parameters
// *
// * @param cursor Cursor
// * @return Map of parameters
// */
// private Map<String, String> cursorToMap(Cursor cursor) {
// Map<String, String> params = new HashMap<>();
// params.put(WebHelper.PARAM_TIME, DbAccess.getTime(cursor));
// params.put(WebHelper.PARAM_LAT, DbAccess.getLatitude(cursor));
// params.put(WebHelper.PARAM_LON, DbAccess.getLongitude(cursor));
// if (DbAccess.hasAltitude(cursor)) {
// params.put(WebHelper.PARAM_ALT, DbAccess.getAltitude(cursor));
// }
// if (DbAccess.hasSpeed(cursor)) {
// params.put(WebHelper.PARAM_SPEED, DbAccess.getSpeed(cursor));
// }
// if (DbAccess.hasBearing(cursor)) {
// params.put(WebHelper.PARAM_BEARING, DbAccess.getBearing(cursor));
// }
// if (DbAccess.hasAccuracy(cursor)) {
// params.put(WebHelper.PARAM_ACCURACY, DbAccess.getAccuracy(cursor));
// }
// if (DbAccess.hasProvider(cursor)) {
// params.put(WebHelper.PARAM_PROVIDER, DbAccess.getProvider(cursor));
// }
// return params;
// }
//
// /**
// * Cleanup
// */
// @Override
// public void onDestroy() {
// if (Logger.DEBUG) { Log.d(TAG, "[websync stop]"); }
// if (db != null) {
// db.close();
// }
// super.onDestroy();
// }
//
//
// private void reloadTasksFromModel() {
// try {
// List<Location> tasks = this.sTasks.allTasks();
// this.mTaskAdapter = new LocationAdapter(this, tasks);
//// this.setListAdapter(this.mTaskAdapter);
// } catch (DocumentStoreException e) {
// throw new RuntimeException(e);
// }
// }
// //
// // HELPER METHODS
// //
//
//// private void reloadReplicationSettings() {
//// try {
//// this.sTasks.reloadReplicationSettings();
//// } catch (URISyntaxException e) {
//// Log.e(TAG, "Unable to construct remote URI from configuration", e);
////
//// }
//// }
//
// /**
// * Called by TasksModel when it receives a replication complete callback.
// * TasksModel takes care of calling this on the main thread.
// */
// void replicationComplete() {
// reloadTasksFromModel();
//// Toast.makeText(getApplicationContext(),
//// R.string.replication_completed,
//// Toast.LENGTH_LONG).show();
//// dismissDialog(DIALOG_PROGRESS);
// }
//
// /**
// * Called by TasksModel when it receives a replication error callback.
// * TasksModel takes care of calling this on the main thread.
// */
// void replicationError() {
// Log.i(TAG, "error()");
// reloadTasksFromModel();
//// Toast.makeText(getApplicationContext(),
//// R.string.replication_error,
//// Toast.LENGTH_LONG).show();
//// dismissDialog(DIALOG_PROGRESS);
// }
//
//}
| true
|
774bc6522e662c839ce2eb51b75b7444a5ab1be9
|
Java
|
whtss/javashare
|
/src/A154PolymorphicPet.java
|
UTF-8
| 98
| 2.171875
| 2
|
[] |
no_license
|
public class A154PolymorphicPet {
String name;
public void eat() {//宠物要吃
}
}
| true
|
3df936e95735185bdadde20b8b12d2ca935055a1
|
Java
|
IsabelManiega/Functions
|
/app/src/main/java/com/functions/Theme4ExercActivity.java
|
UTF-8
| 4,105
| 1.960938
| 2
|
[] |
no_license
|
/*
* Created by Isabel Maniega on 27/07/18 10:56
* Copyright (c) 2018. All rights reserved.
*
* Last modified 27/07/18 10:56
*/
package com.functions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
import com.functions.adapter.Theme4Adapter;
import com.functions.models.Theme4;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class Theme4ExercActivity extends AppCompatActivity {
@BindView(R.id.fab) FloatingActionButton fab;
@BindView(R.id.list)
ListView listView;
@BindView(R.id.toolbar) Toolbar toolbar;
private ActionBar bar;
Parcelable savedRecyclerLayoutState;
private Theme4Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exerc3);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
bar = getSupportActionBar();
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent back = new Intent(Theme4ExercActivity.this, MainActivity.class);
startActivity(back);
finish();
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Theme4ExercActivity.this, Youtube4Activity.class);
startActivity(intent);
}
});
final ArrayList<Theme4> theme4 = new ArrayList<Theme4>();
theme4.add(new Theme4(R.drawable.hiperbola1 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola2 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola3 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola4 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola5 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_,R.string.vacio, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola6 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_,R.string.vacio, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola7 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_,R.string.vacio, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola8 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_,R.string.vacio, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola9 ,R.string.y, R.string.vacio,R.string.lineal,R.string.x_,R.string.vacio, R.string.vacio, R.string.vacio, R.string.vacio));
theme4.add(new Theme4(R.drawable.hiperbola10 ,R.string.y,R.string.vacio,R.string.lineal,R.string.x_,R.string.vacio, R.string.vacio, R.string.vacio, R.string.vacio));
//Cuando rote la pantalla se quede en item correspondiente:
// When rotate the screen give item:
savedRecyclerLayoutState = listView.onSaveInstanceState();
adapter = new Theme4Adapter(this, theme4);
listView.setAdapter(adapter);
listView.onRestoreInstanceState(savedRecyclerLayoutState);
}
@Override
public void onBackPressed() {
Intent back = new Intent(Theme4ExercActivity.this, MainActivity.class);
startActivity(back);
finish();
super.onBackPressed();
}
}
| true
|
1a20baac64a2d82addf6a16ffea748f1a4d56092
|
Java
|
AlanSolohaga/Mafalda
|
/app/src/main/java/com/project/mafalda/model/SonidoClick.java
|
UTF-8
| 697
| 2.1875
| 2
|
[] |
no_license
|
package com.project.mafalda.model;
import android.content.Context;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import com.project.mafalda.R;
public class SonidoClick {
private static SonidoClick mIntance;
private MediaPlayer click;
private static Context mContext;
public SonidoClick(Context context) {
mContext = context;
click = MediaPlayer.create(mContext,R.raw.plop);
}
public static synchronized SonidoClick getInstance(Context context){
if(mIntance == null){
mIntance = new SonidoClick(context);
}
return mIntance;
}
public void play(){
click.start();
}
}
| true
|
b6004b8151fc688a8936e351083424858ec9d744
|
Java
|
mdardinier/M2_API_REST_Plateforme_Cours
|
/plateforme-cours/src/main/java/fr/ul/miage/m2/sid/plateformecours/entity/Utilisateur.java
|
UTF-8
| 2,573
| 2.3125
| 2
|
[] |
no_license
|
package fr.ul.miage.m2.sid.plateformecours.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.hateoas.RepresentationModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "utilisateur")
public class Utilisateur extends RepresentationModel<Utilisateur> {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String email;
private String nom;
private String prenom;
@ManyToMany
@JoinTable(
name = "Utilisateur_Cours",
joinColumns = {@JoinColumn(name = "id")}, inverseJoinColumns = {@JoinColumn(name = "ID_COURS")}
)
private List<Cours> cours;
public Utilisateur(String email, String nom, String prenom) {
setEmail(email);
setNom(nom);
setPrenom(prenom);
setCours(new ArrayList<Cours>());
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Utilisateur other = (Utilisateur) obj;
if (cours == null) {
if (other.cours != null)
return false;
}
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nom == null) {
if (other.nom != null)
return false;
} else if (!nom.equals(other.nom))
return false;
if (prenom == null) {
if (other.prenom != null)
return false;
} else if (!prenom.equals(other.prenom))
return false;
//Modification pour comparer uniquement le contenu des cours achetés un par un
if(cours.size() != other.cours.size()) {
return false;
}
for(int i = 0; i < cours.size();i++) {
if(! cours.get(i).equals(other.cours.get(i))) {
return false;
}
}
return true;
}
}
| true
|
845451d3bfeca90c9d6fc7d2007171a0d2c4b90c
|
Java
|
SoftverInzenjeringETFSA/SI2014Tim5
|
/Implementacija/App/Blagajna/src/main/java/ba/unsa/etf/si/tim5/blagajna/gui/ZaboraviliLozinkuWindow.java
|
UTF-8
| 5,213
| 2.3125
| 2
|
[] |
no_license
|
package ba.unsa.etf.si.tim5.blagajna.gui;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import ba.unsa.etf.si.tim5.blagajna.dodaci.Dao;
import ba.unsa.etf.si.tim5.blagajna.dodaci.SlanjeMaila;
import ba.unsa.etf.si.tim5.blagajna.dodaci.Utility;
import ba.unsa.etf.si.tim5.blagajna.entiteti.Korisnik;
import ba.unsa.etf.si.tim5.blagajna.util.HibernateUtil;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
public class ZaboraviliLozinkuWindow {
final static Logger logger=Logger.getLogger(ZaboraviliLozinkuWindow.class);
JFrame frmPromjenaLozinke;
private JTextField textField;
ArrayList<Korisnik> sviKorisnici=new ArrayList<Korisnik>();
Korisnik logovaniKorisnik;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZaboraviliLozinkuWindow window = new ZaboraviliLozinkuWindow();
window.frmPromjenaLozinke.setVisible(true);
} catch (Exception e) {
logger.error("Greška pri otvaranju glavne forme!" + e.getMessage(), e);
}
}
});
}
public void ucitajSveKorisnike(){
sviKorisnici= Dao.getInstance().dajSveKorisnike();
}
/**
* Create the application.
*/
public ZaboraviliLozinkuWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPromjenaLozinke = new JFrame();
frmPromjenaLozinke.setTitle("Promjena lozinke");
frmPromjenaLozinke.setBounds(100, 100, 460, 152);
frmPromjenaLozinke.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frmPromjenaLozinke.getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblUnesiteVaEmail = new JLabel("Unesite va\u0161 e-mail:");
frmPromjenaLozinke.getContentPane().add(lblUnesiteVaEmail, "4, 4, right, default");
textField = new JTextField();
frmPromjenaLozinke.getContentPane().add(textField, "6, 4, 11, 1, fill, default");
textField.setColumns(10);
JButton btnNewButton = new JButton("Po\u0161alji novu lozinku");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ucitajSveKorisnike();
String email=textField.getText();
int a=Utility.getInstance().generisiPassword();
boolean dobarEmail=false;
for(int i=0;i<sviKorisnici.size();i++)
{
if(sviKorisnici.get(i).getMail().equals(email))
{
System.out.println("dobar");
dobarEmail=true;
String[] m = {email};
sviKorisnici.get(i).setLozinka(Utility.getInstance().MD5(String.valueOf(a)));
textField.setText("");
Session session = HibernateUtil.getSessionFactory()
.openSession();
sviKorisnici.get(i).urediKorisnika(session);
session.close();
SlanjeMaila.getInstance().sendFromGMail(m, "Promjena lozinke", "Vaša nova lozinka je: "+ String.valueOf(a));
JOptionPane.showMessageDialog(null, "Vaša lozinka je poslana, provjerite inbox vašeg e-mail-a!", "InfoBox: " + "Uspješno slanje maila.", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(dobarEmail==false)
{
JOptionPane.showMessageDialog(null, "Email je netačan, pokušajte ponovo!", "InfoBox: " + "Greška", JOptionPane.INFORMATION_MESSAGE);
textField.setText("");
}
}
});
frmPromjenaLozinke.getContentPane().add(btnNewButton, "6, 6, 11, 1");
JLabel lblNewLabel = new JLabel("Napomena: Une\u0161eni mail mora biti onaj sa kojim ste prijavljeni na sistem.");
frmPromjenaLozinke.getContentPane().add(lblNewLabel, "4, 8, 21, 1");
}
}
| true
|
106a9ddd832238b0c85086b620ae96ce83aa5b4a
|
Java
|
DevBoost/EMFText
|
/Incubation/org.emftext.commons.jsglr/src-strategoxt/org/strategoxt/imp/runtime/parser/ast/AstNode.java
|
UTF-8
| 6,621
| 2.40625
| 2
|
[] |
no_license
|
package org.strategoxt.imp.runtime.parser.ast;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import lpg.runtime.IAst;
import lpg.runtime.IAstVisitor;
import lpg.runtime.IPrsStream;
import lpg.runtime.IToken;
import org.eclipse.core.resources.IResource;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermPrinter;
import org.spoofax.interpreter.terms.InlinePrinter;
//import org.strategoxt.imp.runtime.Environment;
import org.strategoxt.imp.runtime.parser.tokens.SGLRToken;
//import org.strategoxt.imp.runtime.stratego.adapter.IStrategoAstNode;
/**
* A node of an SGLR abstract syntax tree.
*
* @author Lennart Kats <L.C.L.Kats add tudelft.nl>
*/
public class AstNode implements IAst, Iterable<AstNode> {
// Globally unique object (circumvent interning)
/** The sort name for strings. */
public static final String STRING_SORT = new String("<string>");
// TODO2: Read-only array list
static final ArrayList<AstNode> EMPTY_LIST = new ArrayList<AstNode>(0);
protected final ArrayList<AstNode> children;
private final String sort;
private String constructor;
private IStrategoTerm term;
private IToken leftToken, rightToken;
private AstNode parent;
// Accessors
/**
* Returns the constructor name of this node, or null if not applicable.
*/
public String getConstructor() {
return constructor;
}
public void setConstructor(String constructor) {
this.constructor = constructor;
}
public String getSort() {
return sort;
}
public boolean isList() {
return false;
}
public IResource getResource() {
return getRoot().getResource();
}
// (concrete type exposed by IAst interface)
public final ArrayList<AstNode> getChildren() {
assert EMPTY_LIST.size() == 0;
return children;
}
/** Get the leftmost token associated with this node. */
public IToken getLeftIToken() {
return leftToken;
}
/** Get the leftmost token associated with this node. */
public IToken getRightIToken() {
return rightToken;
}
/** Set the leftmost token associated with this node. */
protected void setLeftIToken(IToken value) {
leftToken = value;
}
/** Set the leftmost token associated with this node. */
protected void setRightIToken(IToken value) {
rightToken = value;
}
public AstNode getParent() {
return parent;
}
private void setParent(AstNode value) {
parent = value;
}
public RootAstNode getRoot() {
AstNode result = this;
while (result.getParent() != null)
result = result.getParent();
if (!(result instanceof RootAstNode))
throw new IllegalStateException("Tree not initialized using RootAstNode.create()");
else
return (RootAstNode) result;
}
public IStrategoTerm getTerm() {
// if (term != null) return term;
//else return Environment.getTermFactory().wrap(this);
return term;
}
// Initialization
/**
* Create a new AST node and set it to be the parent node of its children.
*/
public AstNode(String sort, IToken leftToken, IToken rightToken, String constructor,
ArrayList<AstNode> children) {
assert children != null;
this.constructor = constructor;
this.sort = sort;
this.leftToken = leftToken;
this.rightToken = rightToken;
this.children = children;
if (leftToken != null)
setReferences(leftToken, rightToken, children);
}
private void setReferences(IToken leftToken, IToken rightToken, ArrayList<AstNode> children) {
IPrsStream parseStream = leftToken.getIPrsStream();
int tokenIndex = leftToken.getTokenIndex();
int endTokenIndex = rightToken.getTokenIndex();
// Set ast node for tokens before children, and set parent references
for (int childIndex = 0, size = children.size(); childIndex < size; childIndex++) {
AstNode child = children.get(childIndex);
child.setParent(this);
int childStart = child.getLeftIToken().getTokenIndex();
int childEnd = child.getRightIToken().getTokenIndex();
while (tokenIndex < childStart) {
SGLRToken token = (SGLRToken) parseStream.getTokenAt(tokenIndex++);
if (token.getAstNode() == null)
token.setAstNode(this);
}
tokenIndex = childEnd + 1;
}
// Set ast node for tokens after children
while (tokenIndex <= endTokenIndex) {
SGLRToken token = (SGLRToken) parseStream.getTokenAt(tokenIndex++);
token.setAstNode(this);
}
}
// General access
public Iterator<AstNode> iterator() {
return children.iterator();
}
// map(getSort)
public static List<String> getSorts(List<? extends AstNode> children) {
List<String> result = new ArrayList<String>(children.size());
for (AstNode node : children) {
result.add(node.getSort());
}
return result;
}
@Override
public int hashCode() {
return getTerm().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AstNode) {
return this == obj || ((AstNode) obj).getTerm().equals(getTerm());
} else {
return false;
}
}
// Visitor support
public void accept(IAstVisitor visitor) {
if (visitor.preVisit(this)) {
for (int i = 0, size = children.size(); i < size; i++) {
children.get(i).accept(visitor);
}
}
visitor.postVisit(this);
}
// LPG legacy/compatibility
/**
* Get all children (including the null ones).
*
* @deprecated Unused; ATermAstNode does not include null children.
*/
@Deprecated
public ArrayList<AstNode> getAllChildren() {
return getChildren();
}
@Deprecated
public IToken[] getPrecedingAdjuncts() {
return getLeftIToken().getPrecedingAdjuncts();
}
@Deprecated
public IToken[] getFollowingAdjuncts() {
return getRightIToken().getFollowingAdjuncts();
}
@Deprecated
public AstNode getNextAst() {
return null;
}
/**
* Pretty prints the AST formed by this node.
*
* @see #prettyPrint(ITermPrinter)
* @see #yield()
*/
@Override
public final String toString() {
ITermPrinter result = new InlinePrinter();
prettyPrint(result);
return result.getString();
}
public void prettyPrint(ITermPrinter printer) {
printer.print(constructor == null ? "<null>" : constructor);
//sb.append(':');
//sb.append(sort);
printer.print("(");
if (getChildren().size() > 0) {
getChildren().get(0).prettyPrint(printer);
for (int i = 1; i < getChildren().size(); i++) {
printer.print(",");
getChildren().get(i).prettyPrint(printer);
}
}
printer.print(")");
}
/**
* Return the input string that formed this AST.
*/
public String yield() {
return getLeftIToken().getIPrsStream().toString(getLeftIToken(), getRightIToken());
}
}
| true
|
977d1b1247225204c354d5f435c1568fa1758848
|
Java
|
TuratoDavide/UdA
|
/src/java/myapp/dao/TeamDaoImpl.java
|
UTF-8
| 1,789
| 2.328125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package myapp.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import myapp.model.Team;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
@Repository("TeamDao")
public class TeamDaoImpl implements TeamDao {
@Autowired
private SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
public Team findById(int idTeam) {
return (Team) getSession().get(Team.class, idTeam);
}
public Team saveTeam(Team team) {
getSession().persist(team);
getSession().flush();
return team;
}
public void deleteTeam(int id) {
Team e = (Team) getSession().load(Team.class, id);
if(e!=null) getSession().delete(e);
}
@SuppressWarnings("unchecked")
public List<Team> findAllTeam() {
Criteria criteria = getSession().createCriteria(Team.class);
return (List<Team>) criteria.list();
}
public int getLast() {
//String hql = "SELECT MAX(IdTeam) FROM Team";
String hql2 = "SELECT IdTeam FROM TEAM ORDER BY IdTeam DESC LIMIT 0,1";
Query q = getSession().createSQLQuery(hql2);
if(q.uniqueResult() == null) {
return 0;
}
int t = (int) q.uniqueResult();
return t;
}
}
| true
|
067b06b7223820f6bd2555a65cfb974884420880
|
Java
|
sumitporwal/Faculty-Information-System
|
/Faculty_Management_System/src/main/java/Service/Bus_Service_Imp.java
|
UTF-8
| 1,674
| 2.25
| 2
|
[] |
no_license
|
package Service;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import DAO.Bus_DAO;
import Model.Bus;
import Model.BusMidStops;
@Service
@Transactional
public class Bus_Service_Imp implements Bus_Service {
@Autowired
Bus_DAO bus_dao;
@Override
public Bus findByBus(String bus) {
return bus_dao.findByBus(bus);
}
@Override
public void addBus(Bus bus) {
bus_dao.addBus(bus);
}
@Override
public void deleteBus(Bus bus) {
bus_dao.deleteBus(bus);
}
@Override
public List<Bus> getBusList() {
return bus_dao.getBusList();
}
@Override
public void updateBus(Bus bus) {
bus_dao.updateBus(bus);
}
@Override
public Bus findBusById(long bus_id) {
return bus_dao.findById(bus_id);
}
@Override
public void addBusStops(BusMidStops bus_mid_stops) {
bus_dao.addBusStops(bus_mid_stops);
}
@Override
public void deleteBusStops(BusMidStops bus_mid_stops) {
bus_dao.deleteBusStops(bus_mid_stops);
}
@Override
public List<BusMidStops> getBusStopsList(long bus_id) {
return bus_dao.getBusStopsList(bus_id);
}
@Override
public void updateBusStops(BusMidStops bus_mid_stops) {
bus_dao.updateBusStops(bus_mid_stops);
}
@Override
public BusMidStops findBusStopsById(long stop_id) {
return bus_dao.findBusStopsById(stop_id);
}
}
| true
|
ea0696a20c1c48df8b06dbbab5b7bd9e5a72c4d4
|
Java
|
manueljscruz/Gescar
|
/app/src/main/java/g3w/gescarcopytest/fragments/CarFragment.java
|
UTF-8
| 2,432
| 2.234375
| 2
|
[] |
no_license
|
package g3w.gescarcopytest.fragments;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import g3w.gescarcopytest.Adapters.CarAdapter;
import g3w.gescarcopytest.CarDataset;
import g3w.gescarcopytest.ListCar;
import g3w.gescarcopytest.R;
/**
* Created by Manuel Cruz on 29/10/2017.
*/
public class CarFragment extends android.support.v4.app.Fragment {
private RecyclerView mRecyclerView;
private ArrayList<CarDataset> mList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_car, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_listcars2);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
CarAdapter adapter = (CarAdapter) mRecyclerView.getAdapter();
if (mList.size()== llm.findLastCompletelyVisibleItemPosition()+1)
{
ArrayList<CarDataset> listAux = ((ListCar) getActivity()).getSetCarList();
for (int i = 0; i < listAux.size(); i++)
{
adapter.addListItem(listAux.get(i), mList.size());
}
}
}
});
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(llm);
mList = ((ListCar) getActivity()).getSetCarList();
CarAdapter adapter = new CarAdapter(getActivity(), mList);
mRecyclerView.setAdapter(adapter);
return view;
}
}
| true
|
70a4752e7e040edaa09e626a297d1ef7e27c1559
|
Java
|
shivam87430/Spring-Jpa-Demo
|
/src/test/java/Main.java
|
UTF-8
| 3,519
| 2.796875
| 3
|
[] |
no_license
|
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import services.JPAServices;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext("config", "services");
JPAServices jpaServices = ctx.getBean(JPAServices.class);
//Question 3
jpaServices.save();
jpaServices.findAll();
System.out.println("ID 4 is deleted from Person");
jpaServices.delete(4);
jpaServices.findAll();
System.out.println("Check Id 3 is present or not");
System.out.println(jpaServices.checkPeople(3));
jpaServices.count();
/*Question 5*/
System.out.println(jpaServices.findPersonByFirstName("Shivam"));
System.out.println("\n");
System.out.println(jpaServices.findPersonByLastName("Chaudhary"));
System.out.println("\n");
//System.out.println(jpaServices.findPersonBy Id(3));
/*Question 6*/
jpaServices.findFirstNameCustom(27);
/*Question 7*/
jpaServices.findFirstNameAndLastNameCustom(27);
/*Question 8*/
jpaServices.customFindAllPerson(27);
/*Question 9*/
Integer count = jpaServices.countByFirstName("Peter");
System.out.println("Number of People from Peter Name is : " + count);
/*Question 10*/
Integer count1 = jpaServices.countByMethodOfPersonRepository("Peter");
System.out.println("Number of People From Peter Name is : " + count1);
System.out.println("This is distinct type");
jpaServices.findDistinctPersonByName("Peter");
System.out.println("This is through Name");
jpaServices.findByFirstNameOrAge("Shivam", 34);
System.out.println("\n");
System.out.println("This is through Age");
jpaServices.findByFirstNameOrAge("sdfaasd", 21);
System.out.println("This is through And Method of Person");
jpaServices.findByFirstNameAndAge("Shivam", 21);
System.out.println("This is example of between");
jpaServices.findByAgeBetween(20, 30);
System.out.println("This is example of Less Than");
jpaServices.findByAgeLessThan(27);
System.out.println("This is example of Greater Than");
jpaServices.findByAgeGreaterThan(27);
System.out.println("This is example of Like Method");
jpaServices.findByFirstNameLike("%S%");
System.out.println("This is example of Not Method");
jpaServices.findByFirstNameNot("Peter");
System.out.println("This is example of In Method");
jpaServices.findByAgeIn(Arrays.asList(23, 25, 27));
System.out.println("This is example of Ignore Method");
jpaServices.findByFirstNameIgnoreCase("shivam");
/*Question 11 */
System.out.println("This function print person greater than 25 and order by id in Descending order");
jpaServices.findByAgeGreaterThanAndOrderByIdDesc(25);
/*Question 12*/
System.out.println("This is through Sort Class");
jpaServices.findAll(25, new Sort(Sort.Direction.DESC, "id"));
/*Question 13*/
System.out.println("This is of Pageable type");
jpaServices.findAll(new PageRequest(2, 3));
}
}
| true
|
3de4200aa26e9ee539973cc977b83bca9ebaccdd
|
Java
|
FionaDong/deppDemo
|
/com.caribe.stone.core/src/test/java/foo/domain/Person.java
|
UTF-8
| 1,488
| 2.515625
| 3
|
[] |
no_license
|
package foo.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@NamedQuery(name="findAll",
query="select e from Person e")
public class Person extends BaseObject {
private static final long serialVersionUID = 2970135183705353062L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 200, nullable = false)
private String name;
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", birthday=" + birthday
+ "]";
}
private Date createdDate;
@PrePersist
public void prePersist(){
setCreatedDate(new Date());
}
@Temporal(TemporalType.DATE)
@Column(nullable = false)
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
| true
|
1ae7ba9a007f7f74ca22e3ba477620001955d90c
|
Java
|
Goddywu/juc
|
/designPatterns/singleton/Single04.java
|
UTF-8
| 360
| 2.703125
| 3
|
[] |
no_license
|
package singleton;
// 静态内部类,刚加载类的时候不加载静态内部类,类加载器只加载一次
public class Single04 {
private Single04() {
}
private static class Single04Holder {
private final static Single04 instance = new Single04();
}
public static Single04 getInstance() {
return Single04Holder.instance;
}
}
| true
|
455f442f2e9094a46b29e13ec9a7fa45ab24285c
|
Java
|
luimuniz/Secretery-System-BETA
|
/src/java/com/secretarysystem/bean/FielBean.java
|
UTF-8
| 5,258
| 1.945313
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.secretarysystem.bean;
import com.secretarysystem.dao.CidadeDAO;
import com.secretarysystem.dao.FielDAO;
import com.secretarysystem.model.Cidade;
import com.secretarysystem.model.Fiel;
import com.secretarysystem.util.JSFUtil;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
/**
*
* @author Luiz
*/
@ManagedBean
@ViewScoped
public class FielBean implements Serializable{
private static final long serialVersionUID = 1l;
private Fiel fiel = new Fiel();
private Cidade cidade;
private Calendar calendar;
private Boolean editar = true;
private HtmlInputText inputNome;
private ArrayList<Fiel> fieis;
public static List<Cidade> cidades = new ArrayList<>();
private HtmlInputText inputCidade;
static{
CidadeDAO dao = new CidadeDAO();
try {
cidades = dao.listaCidades();
System.out.println("Sucesso ao listar as cidades");
} catch (SQLException ex) {
System.out.println("Erro ao listar as cidades");
Logger.getLogger(FielBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Cidade> sugerirCidades(String consulta) {
List<Cidade> cidadesSugeridas = new ArrayList<>();
for (Cidade cidade : this.cidades) {
if (cidade.getNome().toLowerCase().startsWith(consulta.toLowerCase())) {
cidadesSugeridas.add(cidade);
}
}
return cidadesSugeridas;
}
public Fiel getFiel() {
return fiel;
}
public void setFiel(Fiel fiel) {
this.fiel = fiel;
}
public List<Cidade> getCidades() {
return cidades;
}
public void setCidades(List<Cidade> cidades) {
this.cidades = cidades;
}
public HtmlInputText getInputCidade() {
return inputCidade;
}
public void setInputCidade(HtmlInputText inputCidade) {
this.inputCidade = inputCidade;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public HtmlInputText getInputNome() {
return inputNome;
}
public void setInputNome(HtmlInputText inputNome) {
this.inputNome = inputNome;
}
public Calendar getCalendar() {
return calendar;
}
public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}
public ArrayList<Fiel> getFieis() {
return fieis;
}
public void setFieis(ArrayList<Fiel> fieis) {
this.fieis = fieis;
}
public Boolean getEditar() {
return editar;
}
public void ativarEdicao() {
this.editar = this.editar != true;
}
public void onRowSelect(SelectEvent event) {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("cadfiel.xhtml");
} catch (IOException iOException) {
iOException.printStackTrace();
}
}
@PostConstruct
public void prepararPesquisa(){
try{
FielDAO dao = new FielDAO();
fieis = dao.listaFieis2();
} catch (SQLException ex){
ex.printStackTrace();
JSFUtil.adicionarMensagenErro(ex.getMessage());
}
}
public void novoFiel(){
try {
System.out.println("Teste");
fiel.setTelefone(fiel.getTelefone().replaceAll("[(,),-]", ""));
FielDAO dao = new FielDAO();
System.out.print("Nome Fiel: " + fiel.getNome());
dao.salvar(fiel);
JSFUtil.adicionarMensagenSucesso("Fiel salvo com sucesso!");
} catch (Exception ex) {
ex.printStackTrace();
JSFUtil.adicionarMensagenErro(ex.getMessage());
}
}
public void editarFiel(){
try {
System.out.println("Teste");
fiel.setTelefone(fiel.getTelefone().replaceAll("[(,),-]", ""));
FielDAO dao = new FielDAO();
System.out.print("Nome Fiel: " + fiel.getNome());
dao.editar(fiel);
JSFUtil.adicionarMensagenSucesso("Fiel editado com sucesso!");
} catch (Exception ex) {
ex.printStackTrace();
JSFUtil.adicionarMensagenErro(ex.getMessage());
}
}
}
| true
|
605407e0d33b6ff890a06cdebcf94fb99719a5a0
|
Java
|
stephendengbl/toutiao
|
/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/dto/ArticleDto.java
|
UTF-8
| 282
| 1.601563
| 2
|
[] |
no_license
|
package com.heima.article.dto;
import com.heima.article.entity.ApArticle;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class ArticleDto extends ApArticle {
/**
* 文章内容
*/
private String content;
}
| true
|
ba5343c81407e56a490c5719b5f813377d78fe4c
|
Java
|
rajeshchandrane/webhook
|
/webhook/src/Zwayam/WebhookController.java
|
UTF-8
| 1,900
| 2.203125
| 2
|
[] |
no_license
|
package Zwayam;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import Zwayam.WebhookResponse;
@Controller
@RequestMapping("/webhook")
public class WebhookController {
static final Logger logger = Logger.getLogger(WebhookController.class);
/*@RequestMapping(value = "/WsJobTitlePost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String WsJobTitlePost(HttpServletRequest request, HttpServletResponse response) throws IOException{
Enumeration en = request.getParameterNames();
String data = null;
while (en.hasMoreElements()) {
data = (String) en.nextElement();
}
return "Java Developer";
}*/
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody WebhookResponse webhook(@RequestBody String obj) throws JsonProcessingException{
ObjectMapper mapperObj = new ObjectMapper();
logger.info("Enter into post method"+obj.toString());
System.out.println(obj);
//WebhookResponse request = (WebhookResponse) mapperObj.writeValueAsString(new WebhookResponse());
// logger.info(mapperObj.writeValueAsString(new WebhookResponse()));
return new WebhookResponse("Hello! " + obj, "Text " + obj);
}
}
| true
|
5dacd8dbba56b41f8cc214a8471963b6df712ddf
|
Java
|
gouree/Java.Session5.Assignment2
|
/Session5Assignment2/src/InterfaceExample.java
|
WINDOWS-1252
| 4,931
| 4.0625
| 4
|
[] |
no_license
|
/*
* Create an interface Stack in package myPack with following methods
Methods:
void push(int I)
int pop()
Create two sub classes inheriting the Stack interface.
class FixedStack that can accept a fixed numbers of integers. The size of the Stack will be specified
in the constructor. If the number of integers exceed the size, Stack overflow message should be
displayed.
class VariableStack that can accept numbers more than its size. The size of the Stack will be
specified in the constructor. If the number of integers exceed the size, the stack should
automatically grow to accommodate the new element.
*/
public class InterfaceExample
{
public static void main(String args[])
{
Stack f= new FixedStack(); //creating object of FixedStack
VariableStack v= new VariableStack(); //creating object of VariableStack
int val;
System.out.println("Fixed stack operations");
System.out.println("***********************");
//push elements in fixedstack
System.out.println("Push Operations");
System.out.println("****************");
f.push(10);
f.push(20);
f.push(30);
f.push(40);
//pop elements from fixedstack
System.out.println("Pop Operations");
System.out.println("****************");
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
System.out.println("Variable stack operations");
System.out.println("***********************");
//push elements in variablestack
System.out.println("Push Operations");
System.out.println("****************");
v.push(10);
v.push(20);
v.push(30);
v.push(40);
//pop elements from variablestack
System.out.println("Pop Operations");
System.out.println("****************");
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
val=f.pop();
System.out.println("popped element = "+val);
}
}
//create interface stack
interface Stack
{
public void push(int i);
public int pop();
}
//fixedstack implements the interface stack
class FixedStack implements Stack
{
int s[]=new int[20]; //creating an array for stack
int top=0; //top pointing to the index of topmost element
int size; //size specifies size of stack
FixedStack()
{
size =3; //stack size is initialized to 3
}
//method to push elements in stack
public void push(int i)
{
if(top==size)
{
System.out.println("Stack overflow!!!");
}
else
{
top++;
s[top]=i;
System.out.println();
System.out.println("value of stack---->");
System.out.println();
for(int j=1;j<=top;j++)
{
System.out.print(" "+s[j]+" ");
}
}
}
//method to pop elements from stack
public int pop()
{
if(top==0)
{
System.out.println(" Stack underflow");
return(0);
}
else
{
int val=s[top];
top--;
System.out.println();
System.out.println("value of stack---->");
System.out.println();
for(int j=1;j<=top;j++)
{
System.out.print(" "+s[j]+" ");
}
return(val);
}
}
}
class VariableStack implements Stack
{
int s[]=new int[20]; // declaring an array for stack
int top=0;
int size;
VariableStack()
{
size =3; //initializing size of the stack
}
// method to push elements in stack
public void push(int i)
{
//if size exceeds the initialized size add extra memory to stack
if(top==size)
{
System.out.println("Adding extra memory!!!");
size++;
top++;
s[top]=i;
System.out.println("value of stack---->");
System.out.println();
for(int j=1;j<=top;j++)
{
System.out.print(" "+s[j]+" ");
}
}
else
{
top++;
s[top]=i;
System.out.println();
System.out.println("value of stack---->");
System.out.println();
for(int j=1;j<=top;j++)
{
System.out.print(" "+s[j]+" ");
}
}
}
//method to pop elements from stack
public int pop()
{
if(top==0)
{
System.out.println(" Stack underflow");
return(0);
}
else
{
int val=s[top];
top--;
System.out.println();
System.out.println("value of stack---->");
System.out.println();
for(int j=1;j<=top;j++)
{
System.out.print(" "+s[j]+" ");
}
return(val);
}
}
}
| true
|
ec5445fd8a82d3179dc5b9bb504abfb4382c4f91
|
Java
|
Vaculik/automated-timetabling
|
/src/main/java/cz/muni/fi/parser/StructuralModelParserImpl.java
|
UTF-8
| 5,432
| 2.75
| 3
|
[] |
no_license
|
package cz.muni.fi.parser;
import cz.muni.fi.model.structural.StructuralModel;
import cz.muni.fi.model.structural.dual.Arm;
import cz.muni.fi.model.structural.dual.DualGraph;
import cz.muni.fi.model.GeographicCoordinates;
import cz.muni.fi.model.structural.dual.Site;
import cz.muni.fi.model.structural.primal.Link;
import cz.muni.fi.model.structural.primal.Node;
import cz.muni.fi.model.structural.primal.PrimalGraph;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.*;
public class StructuralModelParserImpl implements StructuralModelParser {
private JSONObject json;
public StructuralModelParserImpl(JSONObject json) {
this.json = json;
}
public StructuralModel parseStructuralModel() {
JSONObject primalGraphJson = json.getJSONObject("graph_primal");
PrimalGraph primalGraph = parsePrimalGraph(primalGraphJson);
JSONObject dualGraphJson = json.getJSONObject("graph_dual");
DualGraph dualGraph = parseDualGraph(dualGraphJson);
return new StructuralModel(primalGraph, dualGraph);
}
private PrimalGraph parsePrimalGraph(JSONObject primalGraphJson) {
Map<Long, Node> nodes = parseNodesOfPrimalGraph(primalGraphJson);
Set<Link> links = parseLinksOfPrimalGraph(primalGraphJson, nodes);
return new PrimalGraph(nodes, links);
}
private Map<Long, Node> parseNodesOfPrimalGraph(JSONObject primalGraphJson) {
Map<Long, Node> resultNodes = new HashMap<>();
JSONArray vertices = primalGraphJson.getJSONArray("V");
for (int i = 0; i < vertices.length(); i++) {
long key = vertices.getLong(i);
Node node = new Node(key);
resultNodes.put(key, node);
}
return resultNodes;
}
private Set<Link> parseLinksOfPrimalGraph(JSONObject primalGraphJson, Map<Long, Node> nodes) {
Set<Link> resultLinks = new HashSet<>();
JSONArray edges = primalGraphJson.getJSONArray("E");
for (int i = 0; i < edges.length(); i++) {
JSONArray linkJson = edges.getJSONArray(i);
try {
Link link = parseLink(linkJson, nodes);
resultLinks.add(link);
link.getFirstNode().addLink(link);
link.getSecondNode().addLink(link);
} catch (NullPointerException ex) {
// ex.printStackTrace();
}
}
return resultLinks;
}
private Link parseLink(JSONArray linkJson, Map<Long, Node> nodes) {
long fromKey = linkJson.getLong(0);
long toKey = linkJson.getLong(1);
Node fromNode = nodes.get(fromKey);
Node toNode = nodes.get(toKey);
return new Link(fromNode, toNode);
}
private DualGraph parseDualGraph(JSONObject dualGraphJson) {
Map<Long, Site> sites = parseSitesOfDualGraph(dualGraphJson);
return new DualGraph(sites);
}
private Map<Long, Site> parseSitesOfDualGraph(JSONObject dualGraphJson) {
Map<Long, Site> resultSites = new HashMap<>();
for (String key : dualGraphJson.keySet()) {
int siteId = Integer.parseInt(key);
JSONObject siteJson = dualGraphJson.getJSONObject(key);
Site site = parseSiteWithoutArms(siteId, siteJson);
resultSites.put(Long.parseLong(key), site);
}
for (Map.Entry<Long, Site> entry : resultSites.entrySet()) {
String key = entry.getKey().toString();
JSONArray siteArmsJson = dualGraphJson.getJSONObject(key).getJSONArray("arms");
List<Arm> arms = parseSiteArms(siteArmsJson, resultSites);
entry.getValue().setArms(arms);
}
return resultSites;
}
private Site parseSiteWithoutArms(int siteId, JSONObject siteJson) {
double latitude = siteJson.getDouble("latitude");
double longitude = siteJson.getDouble("longitude");
GeographicCoordinates coordinates = new GeographicCoordinates(latitude, longitude);
return new Site(siteId, coordinates);
}
private List<Arm> parseSiteArms(JSONArray armsArrayJson, Map<Long, Site> sites) {
List<Arm> resultArms = new ArrayList<>();
for (int i = 0; i < armsArrayJson.length(); i++) {
JSONObject armJson = armsArrayJson.getJSONObject(i);
resultArms.add(parseArm(armJson, sites));
}
return resultArms;
}
private Arm parseArm(JSONObject armJson, Map<Long, Site> sites) {
Arm.Builder armBuilder = new Arm.Builder();
int armAngle = armJson.getInt("arm_angle");
armBuilder.armAngle(armAngle);
int armNum = armJson.getInt("arm_num");
armBuilder.armNum(armNum);
int armOffset = armJson.getInt("arm_offset");
armBuilder.armOffset(armOffset);
int leftLanes = armJson.getInt("left_lanes");
armBuilder.leftLanes(leftLanes);
int rightLanes = armJson.getInt("right_lanes");
armBuilder.rightLanes(rightLanes);
if (armJson.has("osm_way_id")) {
long osmWayId = armJson.getLong("osm_way_id");
armBuilder.osmWayId(osmWayId);
}
String streetName = armJson.getString("street_name");
armBuilder.streetName(streetName);
long nextSiteId = armJson.getLong("next_site");
armBuilder.nextSite(sites.get(nextSiteId));
return armBuilder.build();
}
}
| true
|
0650d4543d4adbbc4017632b043ec28cf22fa887
|
Java
|
giupardeb/FootballGame
|
/parser/src/parseFromCSV.java
|
UTF-8
| 5,988
| 3.0625
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class parseFromCSV {
/**
* @param args
*/
public static void main(String[] args) {
try {
read("database.csv");
} catch (IOException e) {
e.printStackTrace();
}
}
// NOTE
// Non so se utilizzi questo file, quindi ti faccio notare che qui c'era un errore di sintassi
// In pratica non tornavi Giocatori[] ma qualcos'altro.
private static Giocatori[] read(String fileName) throws IOException {
// Ha più senso avere queste due linee dentro
Giocatori vett[] = new Giocatore [568];
int i = 0; // TIP: usa degli spazi invece di i=0. il codice è più leggibile.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String currentLine;
while ((currentLine = br.readLine()) != null) {
Giocatore player = giocatore(currentLine);
vett[i++] = player;
}
br.close();
return vett;
}
private static final String CENTROCAMPISTA = "Centrocampista";
private static final String PORTIERE = "Portiere";
private static final String ATTACCANTE = "Attaccante";
private static final String DIFENSORE = "Difensore";
// TODO Questo torner� Giocatore e non Object
private static Giocatore giocatore(String line) {
String[] giocatoreString = line.split(",");
String ruolo = giocatoreString[0]; // Difensore, Centrocampista, Attaccante o Portiere
String nome = giocatoreString[1];
String squadra = giocatoreString[2];
String nazionalita = giocatoreString[3];
byte velocita = Byte.parseByte(giocatoreString[4]);
byte resistenza = Byte.parseByte(giocatoreString[5]);
byte forza = Byte.parseByte(giocatoreString[6]);
byte morale = Byte.parseByte(giocatoreString[7]);
byte eta = Byte.parseByte(giocatoreString[8]);
byte condizione = Byte.parseByte(giocatoreString[9]);
byte tecnica = Byte.parseByte(giocatoreString[10]);
byte aggressivita = Byte.parseByte(giocatoreString[11]);
byte creativita = Byte.parseByte(giocatoreString[12]);
byte decisione = Byte.parseByte(giocatoreString[13]);
byte carisma = Byte.parseByte(giocatoreString[14]);
String posizione = giocatoreString[15];
byte giocoDiSquadra = Byte.parseByte(giocatoreString[16]);
boolean essenziale = Boolean.parseBoolean(giocatoreString[17]);
byte mediaVoti = Byte.parseByte(giocatoreString[18]);
if(ruolo == CENTROCAMPISTA || ruolo == ATTACCANTE || ruolo == DIFENSORE){
byte cross = Byte.parseByte(giocatoreString[19]);
byte dribling = Byte.parseByte(giocatoreString[20]);
byte colpoDiTesta = Byte.parseByte(giocatoreString[21]);
byte passaggio = Byte.parseByte(giocatoreString[22]);
byte tiro = Byte.parseByte(giocatoreString[23]);
byte contrasto = Byte.parseByte(giocatoreString[24]);
byte movimento = Byte.parseByte(giocatoreString[25]);
byte abilitaDifesa = Byte.parseByte(giocatoreString[26]);
byte abilitaAttacco = Byte.parseByte(giocatoreString[27]);
byte abilitaCentrcampo = Byte.parseByte(giocatoreString[28]);
byte valoreGenerale = Byte.parseByte(giocatoreString[29]);
double valoreMercato = Double.parseDouble(giocatoreString[30]);
}
else{
byte dotiAeree = Byte.parseByte(giocatoreString[19]);
byte agilita = Byte.parseByte(giocatoreString[20]);
byte comunicazione = Byte.parseByte(giocatoreString[21]);
byte bloccareTiro = Byte.parseByte(giocatoreString[22]);
byte calciare = Byte.parseByte(giocatoreString[23]);
byte riflessi = Byte.parseByte(giocatoreString[24]);
byte rimessa = Byte.parseByte(giocatoreString[25]);
byte valoreGenerale = Byte.parseByte(giocatoreString[26]);
double valoreMercato = Double.parseDouble(giocatoreString[27]);
}
// TODO - per ogni caratteristica!
// TODO casting per (byte)'s e booleans
// NOTE devi definire il giocatore, altrimenti non lo puoi ritornare.
// Inoltre ti ho aggiustato un pò gli else if, così il codice è + leggibile
Giocatore giocatore = null;
if (ruolo == CENTROCAMPISTA) {
giocatore = new Centrocampista(nome, squadra, nazionalita,
velocita, resistenza, forza,
morale, eta, condizione,
tecnica, aggressivita, creativita,
decisione, carisma, posizione,
giocoDiSquadra, essenziale, mediaVoti,
cross, dribling, colpoDiTesta,
passaggio, tiro, contrasto,
movimento, abilitaDifesa, abilitaAttacco,
abilitaCentrcampo, valoreGenerale, valoreMercato);
} else if(ruolo == PORTIERE) {
giocatore = new Portiere(nome, squadra, nazionalita,
velocita, resistenza, forza,
morale, eta, condizione,
tecnica, aggressivita, creativita,
decisione, carisma, posizione,
giocoDiSquadra, essenziale, mediaVoti,
dotiAeree, agilita, comunicazione,
bloccareTiro, calciare, riflessi,
rimessa, valoreGenerale, valoreMercato);
} else if (ruolo == ATTACCANTE) {
giocatore = new Attaccante(nome, squadra, nazionalita,
velocita, resistenza, forza,
morale, eta, condizione,
tecnica, aggressivita, creativita,
decisione, carisma, posizione,
giocoDiSquadra, essenziale, mediaVoti,
cross, dribling, colpoDiTesta,
passaggio, tiro, contrasto,
movimento, abilitaDifesa, abilitaAttacco,
abilitaCentrcampo, valoreGenerale, valoreMercato);
} else if(ruolo == DIFENSORE) {
giocatore = new Difensore(nome, squadra, nazionalita,
velocita, resistenza, forza,
morale, eta, condizione,
tecnica, aggressivita, creativita,
decisione, carisma, posizione,
giocoDiSquadra, essenziale, mediaVoti,
cross, dribling, colpoDiTesta,
passaggio, tiro, contrasto,
movimento, abilitaDifesa, abilitaAttacco,
abilitaCentrcampo, valoreGenerale, valoreMercato);
}
return giocatore;
}
}
| true
|
3d1c2eb882501c1185d3dbbaa45c51c8257dfede
|
Java
|
forseed/concurrency_demo
|
/src/main/java/demo/threadgroup/ThreadGroupCreate.java
|
UTF-8
| 1,787
| 3.375
| 3
|
[] |
no_license
|
package demo.threadgroup;
import java.util.Arrays;
/**
* 线程组相关api
*/
public class ThreadGroupCreate {
public static void main(String[] args) {
//use the name
ThreadGroup tg1 = new ThreadGroup("TG1");
new Thread(tg1, "t1") {
@Override
public void run() {
while (true) {
try {
System.out.println(getThreadGroup().getName());
System.out.println(getThreadGroup().getParent());
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}.start();
//use the parent and group name
ThreadGroup tg2 = new ThreadGroup(tg1, "TG2");
new Thread(tg2, "t2") {
@Override
public void run() {
while (true) {
try {
Thread[] threads = new Thread[tg1.activeCount()];
tg1.enumerate(threads);
Arrays.asList(threads).forEach(System.out::println);
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}.start();
//主线程
ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
Thread[] ts = new Thread[mainGroup.activeCount()];
mainGroup.enumerate(ts, true);
Arrays.asList(ts).forEach(x -> System.out.println(">>>" + x));
//测试打断
mainGroup.interrupt();
}
}
| true
|
91f4ba479c07a418c93c723ea6350cdda70ec8a0
|
Java
|
samkingsly07/MyClassAssistant
|
/myclassassistant/sources/assistant/genuinecoder/s_assistant/main/notes/NoteCreate.java
|
UTF-8
| 5,289
| 2
| 2
|
[] |
no_license
|
package assistant.genuinecoder.s_assistant.main.notes;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.p003v7.app.AppCompatActivity;
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 assistant.genuinecoder.s_assistant.C0520R;
import assistant.genuinecoder.s_assistant.main.AppBase;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class NoteCreate extends AppCompatActivity {
static final /* synthetic */ boolean $assertionsDisabled = false;
EditText body;
final FirebaseDatabase database = FirebaseDatabase.getInstance();
Spinner spinner;
EditText sub;
final DatabaseReference table_user = this.database.getReference();
EditText title;
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) C0520R.layout.note_create);
((Button) findViewById(C0520R.C0522id.noteSaveButton)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
NoteCreate.this.saveData();
}
});
this.spinner = (Spinner) findViewById(C0520R.C0522id.pinSpinner);
this.spinner.setAdapter(new ArrayAdapter<>(this, 17367049, AppBase.divisions));
}
/* access modifiers changed from: private */
public void saveData() {
this.title = (EditText) findViewById(C0520R.C0522id.noteTitle);
this.body = (EditText) findViewById(C0520R.C0522id.noteBody);
this.sub = (EditText) findViewById(C0520R.C0522id.subjectNote);
if (this.title.length() == 0) {
Toast toast1 = Toast.makeText(this, "Fill the Title ", 1);
toast1.setGravity(48, 0, 180);
toast1.getView().setBackgroundResource(C0520R.C0521drawable.sssssss);
((TextView) toast1.getView().findViewById(16908299)).setTextColor(-1);
toast1.show();
} else if (this.body.length() == 0) {
Toast toast12 = Toast.makeText(this, "Fill the Body ", 1);
toast12.setGravity(48, 0, 180);
toast12.getView().setBackgroundResource(C0520R.C0521drawable.sssssss);
((TextView) toast12.getView().findViewById(16908299)).setTextColor(-1);
toast12.show();
} else if (this.sub.length() == 0) {
Toast toast = Toast.makeText(this, "Fill The Subject", 1);
toast.setGravity(48, 0, 180);
toast.getView().setBackgroundResource(C0520R.C0521drawable.sssssss);
((TextView) toast.getView().findViewById(16908299)).setTextColor(-1);
toast.show();
} else {
this.table_user.addValueEventListener(new ValueEventListener() {
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String ss1 = "t" + ds.child("note").getChildrenCount();
try {
DatabaseReference ss = NoteCreate.this.table_user.child("user1").child("note").child(ss1);
ss.child("Subject").setValue(NoteCreate.this.sub.getText().toString());
ss.child("title").setValue(NoteCreate.this.title.getText().toString());
ss.child("Body").setValue(NoteCreate.this.body.getText().toString());
NoteCreate.this.table_user.child("user1").child("position").child(NoteCreate.this.title.getText().toString()).child("pos").setValue(ss1);
Toast toast1 = Toast.makeText(NoteCreate.this, "Note Created ", 1);
toast1.setGravity(48, 0, 180);
toast1.getView().setBackgroundResource(C0520R.C0521drawable.sssssss);
((TextView) toast1.getView().findViewById(16908299)).setTextColor(-1);
toast1.show();
NoteCreate.this.table_user.removeEventListener((ValueEventListener) this);
NoteCreate.this.finish();
} catch (Exception e) {
Exception exc = e;
Toast toast12 = Toast.makeText(NoteCreate.this, "ERROR OCCURRED ", 1);
toast12.setGravity(48, 0, 180);
toast12.getView().setBackgroundResource(C0520R.C0521drawable.sssssss);
((TextView) toast12.getView().findViewById(16908299)).setTextColor(-1);
toast12.show();
NoteCreate.this.finish();
}
}
}
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
}
| true
|
6c619fc766ee65848bc0ccdfe74c492a9e5cb0b1
|
Java
|
henrypoter/rocketmq-spring
|
/springmvcTemplate2/src/main/java/com/study/listener/MySecondBizConsumer.java
|
UTF-8
| 2,008
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.study.listener;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
@RocketMQMessageListener(/*nameServer = "192.168.11.188:9876",*/ consumerGroup = "string-topic-consumer", topic = "string-topic")
public class MySecondBizConsumer implements RocketMQListener<MessageExt> {
private static final Logger LOG = LoggerFactory.getLogger(MySecondBizConsumer.class);
//C0A80BB423435B2133B14B89A4240010
//C0A80BB423435B2133B14B85862D000E
@Override
public void onMessage(MessageExt msg) {
LOG.error("MySecondBizConsumer onMessage:{}",msg);
System.out.printf("second-consumer msg comming \n");
System.out.printf("------- msg received: %s \n", msg);
RocketMQUtil.appendLineToFile("F:/logs/2.txt", String.format(" on msg ..second-consumer msgid: %s msg:%s", msg.getMsgId(), msg.toString()));
//throw new RuntimeException("exception..");
}
}
| true
|
20fbc4e675e1c8b86ac97b453e5e1fd79f81afaa
|
Java
|
NCIEVS/evsrestapi-client-SDK
|
/java-examples/src/test/java/gov/nih/nci/evs/api/test/SearchTests.java
|
UTF-8
| 7,834
| 2.3125
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package gov.nih.nci.evs.api.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import gov.nih.nci.evs.api.client.EvsRestClient;
import gov.nih.nci.evs.api.model.ConceptResultList;
/**
* Search tests.
*/
public class SearchTests {
/** The logger. */
private static Logger logger = LoggerFactory.getLogger(SearchTests.class);
/** The client. */
private static EvsRestClient client = null;
/** The terminology. */
private static String terminology = "ncit";
/**
* Setup class.
*
* @throws Exception the exception
*/
@BeforeAll
public static void setupClass() throws Exception {
client = new EvsRestClient();
}
/**
* Test get concept by search term.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTerm() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "melanoma", 5, null, null, null,
null, null, null, null, null);
logger.info("Get concept by search term=melanoma");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term and concept status.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermConceptStatus() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "respiratory", 5, "Header_Concept",
null, null, null, null, null, null, null);
logger.info("Get concept by search term=respiratory, status=Header_Concept");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term and contributing source.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermContributingSource() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "melanoma", 5, null, "CDISC", null,
null, null, null, null, null);
logger.info("Get concept by search term=melanoma, contributingSource=CDISC");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term and definition source.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermDefinitionSource() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "melanoma", 5, null, null, "NCI",
null, null, null, null, null);
logger.info("Get concept by search term=dsDNA, definitionSource=NCI");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term and synonym source.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermSynonymSource() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "dsDNA", null, null, null, null,
"NCI", "PT", null, null, null);
logger.info("Get concept by search term=dsDNA, synonymSource=NCI, synonymTermGroup=PT");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by code.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermAsCode() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "C3224", null, null, null, null,
null, null, null, null, null);
logger.info("Get concept by search term=C3224");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term type "match".
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermMatch() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "enzyme", 5, null, null, null, null,
null, "match", null, null);
logger.info("Get concept by search term=enzyme, type=match");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term type "startsWith".
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermStartsWith() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "enzyme", 5, null, null, null, null,
null, "startsWith", null, null);
logger.info("Get concept by search term=enzyme, type=startsWith");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term type "phrase".
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermPhrase() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "malignant melanoma", 5, null, null,
null, null, null, "phrase", null, null);
logger.info("Get concept by search term=malignant melanoma, type=phrase");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term type "fuzzy".
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermFuzzy() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "enzyme", 5, null, null, null, null,
null, "fuzzy", null, null);
logger.info("Get concept by search term=enzyme, type=fuzzy");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts= " + list);
}
/**
* Test concept by search term type "AND".
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermAnd() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "malignant melanoma", 5, null, null,
null, null, null, "AND", null, null);
logger.info("Get concept by search term=malignant melanoma, type=AND");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by search term type "OR".
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermOr() throws Exception {
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "malignant melanoma", 5, null, null,
null, null, null, "OR", null, null);
logger.info("Get concept by search term=malignant melanoma, type=OR");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by property.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsBySearchTermHighlights() throws Exception {
List<String> includes = new ArrayList<>();
includes.add("synonyms");
includes.add("highlights");
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "enzyme", 5, null, null, null, null,
null, null, null, includes);
logger.info("Get concept by search term=XAV05295I5 (with highlights)");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
/**
* Test concept by property.
*
* @throws Exception the exception
*/
@Test
public void testFindConceptsByProperty() throws Exception {
List<String> includes = new ArrayList<>();
includes.add("properties");
final ConceptResultList list = client.findConceptsBySearchTerm(terminology, "XAV05295I5", null, null, null,
null, null, null, null, "FDA_UNII_Code", includes);
logger.info("Get concept by search term=XAV05295I5, property=FDA_UNII_Code");
logger.info(" base url = " + client.getApiUrl());
logger.info(" concepts = " + list);
}
}
| true
|
e5f1da84c65d286c4b1c1217b53e1070166aa1be
|
Java
|
lolson/bash_scripts
|
/scripts/java/TestMBeanServiceMonitor.java
|
UTF-8
| 2,662
| 2.390625
| 2
|
[] |
no_license
|
import java.util.*;
import java.util.Hashtable;
import java.io.IOException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.MemoryMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;
public class TestMBeanServiceMonitor
{
private static MBeanServerConnection connection;
private static JMXConnector connector;
public static void Connection(String hostname, String port) throws IOException
{
Integer portInteger = Integer.valueOf(port);
Hashtable h = new Hashtable();
String urlString = "service:jmx:remoting-jmx://" + hostname + ":" + port;
// JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+hostname+":"+port+"/jmxrmi");
JMXServiceURL address = new JMXServiceURL(urlString);
connector = JMXConnectorFactory.connect(address,null);
connection = connector.getMBeanServerConnection();
System.out.println("GOT THE MBeanServerConnection---SUCCESSFULLY");
}
private static void listAllJBossAS7MBeans() throws Exception
{
//ObjectName serviceRef=new ObjectName("jboss.as:*");
//ObjectName serviceRef=new ObjectName("*.*:*");
ObjectName serviceRef=new ObjectName("*.*:*");
Set<ObjectName> mbeans = connection.queryNames(serviceRef, null);
for (ObjectName on : mbeans) {
System.out.println("\t ObjectName : "+on);
}
}
private static void getThreadDetails() throws Exception
{
ObjectName serviceRef=new ObjectName("java.lang:type=Threading");
Integer daemonThreadCount=(Integer)connection.getAttribute(serviceRef, "DaemonThreadCount");
System.out.println("\t daemonThreadCount : "+daemonThreadCount);
}
public static void main(String[] args) throws Exception
{
String hostname = args[0];
String port = args[1];
/*
***** The port binding should be defined inside your "standalone-full.xml" file. *****
*
<subsystem xmlns="urn:jboss:domain:jmx:1.1">
<show-model value="true"/>
<jmx-connector registry-binding="jmx-connector-registry" server-binding="jmx-connector-server"/>
</subsystem>
*/
Connection(hostname, port);
System.out.println("\n\t All JBoss AS7 MBean Listing \n\n");
listAllJBossAS7MBeans() ;
}
}
| true
|
ce9378429f9684ff37a9ccc55807237ec3a567be
|
Java
|
jldupont/gwt-gephi-toolkit
|
/src/org/gephi/graph/dhns/event/AbstractEvent.java
|
UTF-8
| 1,432
| 1.960938
| 2
|
[] |
no_license
|
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <mathieu.bastian@gephi.org>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Gephi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.graph.dhns.event;
import org.gephi.graph.api.GraphEvent;
import org.gephi.graph.api.GraphEvent.EventType;
import org.gephi.graph.api.GraphView;
/**
*
* @author Mathieu Bastian
*/
public abstract class AbstractEvent<T> {
private final GraphEvent.EventType eventType;
private final T data;
private final GraphView view;
public AbstractEvent(EventType eventType, GraphView view, T data) {
this.eventType = eventType;
this.data = data;
this.view = view;
}
public T getData() {
return data;
}
public EventType getEventType() {
return eventType;
}
public GraphView getView() {
return view;
}
}
| true
|
28eaac22437f0c75cadc6ac0687865d67c744eff
|
Java
|
mkorzeniowska/GeneratorNPC
|
/NpcWeb/NpcWeb/src/utility/NpcInsert.java
|
UTF-8
| 1,565
| 2.65625
| 3
|
[] |
no_license
|
package utility;
import java.sql.*;
import dataSource.NpcConProvider;
import model.Person;
public class NpcInsert {
private static String CREATE = String.format(
"INSERT [dbo].[Person] ([personID], [plec], [imie], [nazwisko], [rasa], [podrasa], [klasa], [charakter], [sila], [kondycja], [zrecznosc], [inteligencja], [madrosc], [charyzma], [wyglad], [osobowosc])"
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
public static void insertPerson(Person p) throws SQLException {
try (Connection conn = NpcConProvider.getConnection();
PreparedStatement prepStmt = conn.prepareStatement(CREATE)) {
prepStmt.setInt(1,p.getId());
prepStmt.setString(2, p.getSex());
prepStmt.setString(3, p.getName());
prepStmt.setString(4, p.getSurname());
prepStmt.setString(5, p.getRace());
prepStmt.setString(6, p.getSubrace());
prepStmt.setString(7, p.getJob());
prepStmt.setString(8, p.getCharacter());
prepStmt.setInt(9,p.getStrength());
prepStmt.setInt(10,p.getConstitution());
prepStmt.setInt(11,p.getDexterity());
prepStmt.setInt(12,p.getIntelligence());
prepStmt.setInt(13,p.getWisdom());
prepStmt.setInt(14,p.getCharisma());
prepStmt.setString(15, p.getApperance());
prepStmt.setString(16, p.getPersonality());
prepStmt.executeUpdate();
conn.close();
}
}
}
// pierwotnie dałbym tak:
// + "VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, '%s', '%s)",
| true
|
db85fbc03057c8fae2c372a5bf1eb737278d6565
|
Java
|
atomixnmc/pecia
|
/src/main/java/nl/flotsam/pecia/ItemizedList.java
|
UTF-8
| 1,657
| 2.484375
| 2
|
[] |
no_license
|
/*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.flotsam.pecia;
/**
* A document element representing an itemized list. Note that - contrary to the
* DocBook document model - the {@link ItemizedList} abstraction is used both
* for itemized lists as well as ordered lists. So, if you invoke
* {@link Contents#orderedList()}, you still get an {@link ItemizedList} in
* return.
*
* @author Wilfred Springer
*
* @param <T>
* The type of the parent container element.
*/
public interface ItemizedList<T> extends DocumentElement<T> {
/**
* Adds a new list item, populates it with a {@link Para} containing the
* <code>text</code> passed in.
*
* @param text
* The text to be inserted into the list item.
* @return The current itemized list.
*/
ItemizedList<T> item(String text);
/**
* Adds a new list item, allowing the list item to be populated in any
* specific way you desire.
*
* @return The {@link ListItem} to be populated.
*/
ListItem<? extends ItemizedList<T>> item();
}
| true
|
a4f650759c7b596452282d7632dad9a7dcd3dda8
|
Java
|
zeeem/zeeem.AndroidProject.projotno-elearning
|
/app/src/main/java/com/jeeon/zeeem/projotnoelearning/SelectTreatment.java
|
UTF-8
| 23,129
| 2.171875
| 2
|
[] |
no_license
|
package com.jeeon.zeeem.projotnoelearning;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class SelectTreatment extends AppCompatActivity {
LinearLayout buttonLayoutToShuffle;
TextView treatmentText;
Button b1,b2,b3,b4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_treatment);
setTitle("কেস সমাধান");
treatmentText = (TextView) findViewById(R.id.treatmentText);
b1 = (Button) findViewById(R.id.treatmentBtn1);
b2 = (Button) findViewById(R.id.treatmentBtn2);
b3 = (Button) findViewById(R.id.treatmentBtn3);
b4 = (Button) findViewById(R.id.treatmentBtn4);
buttonLayoutToShuffle = (LinearLayout) findViewById(R.id.buttonLayoutToShuffle);
//for shuffling answers
Random random = new Random();
int numberOfMethods = 4;
switch(random.nextInt(numberOfMethods)) {
case 0:
shuffle3();
break;
case 1:
shuffle2();
break;
case 2:
shuffle1();
break;
case 3:
shuffle4();
break;
default:
shuffle3();
break;
}
if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==2){
treatmentText.setText("নিস্নে গ্লোকোমা এর জন্য সম্ভাব্য কয়েকটি চিকিৎসা উল্লেখ করা হয়েছে। আপনি উপযুক্ত চিকিৎসা/গুলো নিবাচন করুন");
b1.setText("অ্যান্টিবায়োটিক আই ড্রপ");
b2.setText("স্টেরয়েড আই ড্রপ");
b3.setText("রেফার করে দিন");
b4.setText("হোম এ্যাডভাইস");
}
}
public void treatmentBtn1_clicked(View view){
if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==1){
//change score
StaticLogics.PrimaryCaseSolveScore -= 2.5;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b1.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.VISIBLE);
correctAns_disease.setVisibility(View.GONE);
diseaseAnsDetails.setText("কারন এ্যাট্রোপিন ১% আই ড্রপ এক্ষেত্রে ব্যবহার করা হয় না।");
nextDiseaseSelectStep.setText("দয়া করে আবার চেষ্টা করুন");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, SelectTreatment.class);
startActivity(intent);
finish();
}
});
}
else if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==2){
//change score
StaticLogics.PrimaryCaseSolveScore -= 2.5;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b1.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.VISIBLE);
correctAns_disease.setVisibility(View.GONE);
diseaseAnsDetails.setText("কারন অ্যান্টিবায়োটিক আই ড্রপ এক্ষেত্রে ব্যবহার করা হয় না।");
nextDiseaseSelectStep.setText("দয়া করে আবার চেষ্টা করুন");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, SelectTreatment.class);
startActivity(intent);
finish();
}
});
}
}
public void treatmentBtn2_clicked(View view){
if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==1){
if(!StaticLogics.mul_treatment_Ans_count_1){
//change score
StaticLogics.PrimaryCaseSolveScore += 5;
StaticLogics.mul_treatment_Ans_count_1=true;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b2.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.GONE);
correctAns_disease.setVisibility(View.VISIBLE);
diseaseAnsDetails.setText("কারন ক্লোরামফেনিকল ০.৫% আই ড্রপ এই রোগের জন্য প্রথম চিকিৎসা।");
nextDiseaseSelectStep.setText("পরবর্তী ধাপে যান");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(StaticLogics.mul_treatment_Ans_count_1 && StaticLogics.mul_treatment_Ans_count_2){
Intent intent = new Intent(SelectTreatment.this, CaseResult.class);
startActivity(intent);
finish();
}
else {
//start a new dialog
subDialog();
//finish();
}
}
});
}
else
Toast.makeText(this, "You have already selected this answer", Toast.LENGTH_SHORT).show();
}
else if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==2){
//change score
StaticLogics.PrimaryCaseSolveScore -= 2.5;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b2.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.VISIBLE);
correctAns_disease.setVisibility(View.GONE);
diseaseAnsDetails.setText("কারন স্টেরয়েড আই ড্রপ এক্ষেত্রে ব্যবহার করা হয় না।");
nextDiseaseSelectStep.setText("দয়া করে আবার চেষ্টা করুন");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, SelectTreatment.class);
startActivity(intent);
finish();
}
});
}
}
public void treatmentBtn3_clicked(View view){
if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==1){
//change score
StaticLogics.PrimaryCaseSolveScore -= 2.5;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b3.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.VISIBLE);
correctAns_disease.setVisibility(View.GONE);
diseaseAnsDetails.setText("কারন এখনই এই রোগীকে রেফার করার প্রয়োজন নাই।");
nextDiseaseSelectStep.setText("দয়া করে আবার চেষ্টা করুন");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, SelectTreatment.class);
startActivity(intent);
finish();
}
});
}
else if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==2){
//change score
StaticLogics.PrimaryCaseSolveScore += 5;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b3.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.GONE);
correctAns_disease.setVisibility(View.VISIBLE);
diseaseAnsDetails.setText("কারন এক্ষেত্রে একজন চক্ষু বিশেষজ্ঞের সরনাপন্ন হওয়া অতীব জরুরী।");
nextDiseaseSelectStep.setText("পরবর্তী ধাপে যান");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, CaseResult.class);
startActivity(intent);
finish();
}
});
}
}
public void treatmentBtn4_clicked(View view){
if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==1){
if(!StaticLogics.mul_treatment_Ans_count_2){
//change score
StaticLogics.PrimaryCaseSolveScore += 5;
StaticLogics.mul_treatment_Ans_count_2=true;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b4.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.GONE);
correctAns_disease.setVisibility(View.VISIBLE);
diseaseAnsDetails.setText("কারন এক্ষেত্রে চোখে নরম কাপড় দিয়ে মৃদু গরম সেক দিলে আরাম পাওয়া যায়। ");
nextDiseaseSelectStep.setText("পরবর্তী ধাপে যান");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(StaticLogics.mul_treatment_Ans_count_1 && StaticLogics.mul_treatment_Ans_count_2){
Intent intent = new Intent(SelectTreatment.this, CaseResult.class);
startActivity(intent);
finish();
}
else {
//start a new dialog
subDialog();
//finish();
}
}
});
}
else
Toast.makeText(this, "You have already selected this answer", Toast.LENGTH_SHORT).show();
}
else if(StaticLogics.current_PrimaryCaseSolve_LevelRunning==2){
//change score
StaticLogics.PrimaryCaseSolveScore -= 2.5;
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setText(b4.getText());
//for wrong ans
wrongAns_disease.setVisibility(View.VISIBLE);
correctAns_disease.setVisibility(View.GONE);
diseaseAnsDetails.setText("কারন এক্ষেত্রে একজন চক্ষু বিশেষজ্ঞের সরনাপন্ন হওয়া অতীব জরুরী।");
nextDiseaseSelectStep.setText("দয়া করে আবার চেষ্টা করুন");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, SelectTreatment.class);
startActivity(intent);
finish();
}
});
}
}
public void subDialog(){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SelectTreatment.this);
View mView = getLayoutInflater().inflate(R.layout.select_disease_dialog_window, null);
final TextView selectedDiseaseName = (TextView) mView.findViewById(R.id.selectedDiseaseName);
final TextView wrongAns_disease = (TextView) mView.findViewById(R.id.wrongAns_disease);
final TextView correctAns_disease = (TextView) mView.findViewById(R.id.correctAns_disease);
final TextView diseaseAnsDetails = (TextView) mView.findViewById(R.id.diseaseAnsDetails);
Button nextDiseaseSelectStep = (Button) mView.findViewById(R.id.nextDiseaseSelectStep);
selectedDiseaseName.setVisibility(View.GONE);
//for wrong ans
wrongAns_disease.setVisibility(View.GONE);
correctAns_disease.setVisibility(View.VISIBLE);
correctAns_disease.setText("আপনার আরও সঠিক উত্তর রয়েছে। চুড়ান্ত ফলাফলের জন্য সঠিক উত্তর/গুলো নিবাচন করুন।");
diseaseAnsDetails.setVisibility(View.GONE);
nextDiseaseSelectStep.setText(" পরবর্তী ধাপে যান");
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
nextDiseaseSelectStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SelectTreatment.this, SelectTreatment.class);
startActivity(intent);
finish();
}
});
}
//shuffle methods
public void shuffle1(){
int childcount = buttonLayoutToShuffle.getChildCount();
// create array
View[] children = new View[childcount];
// get children of linearlayout
for (int i=0; i < childcount; i++){
children[i] = buttonLayoutToShuffle.getChildAt(i);
}
//now remove all children
buttonLayoutToShuffle.removeAllViews();
//first position
buttonLayoutToShuffle.addView(children[2]);
//second position
buttonLayoutToShuffle.addView(children[0]);
//third position
buttonLayoutToShuffle.addView(children[1]);
buttonLayoutToShuffle.addView(children[3]);
}
public void shuffle2(){
int childcount = buttonLayoutToShuffle.getChildCount();
// create array
View[] children = new View[childcount];
// get children of linearlayout
for (int i=0; i < childcount; i++){
children[i] = buttonLayoutToShuffle.getChildAt(i);
}
//now remove all children
buttonLayoutToShuffle.removeAllViews();
//first position
buttonLayoutToShuffle.addView(children[1]);
//second position
buttonLayoutToShuffle.addView(children[2]);
//third position
buttonLayoutToShuffle.addView(children[3]);
buttonLayoutToShuffle.addView(children[0]);
}
public void shuffle3(){
int childcount = buttonLayoutToShuffle.getChildCount();
// create array
View[] children = new View[childcount];
// get children of linearlayout
for (int i=0; i < childcount; i++){
children[i] = buttonLayoutToShuffle.getChildAt(i);
}
//now remove all children
buttonLayoutToShuffle.removeAllViews();
buttonLayoutToShuffle.addView(children[0]);
//first position
buttonLayoutToShuffle.addView(children[1]);
//second position
buttonLayoutToShuffle.addView(children[2]);
//third position
buttonLayoutToShuffle.addView(children[3]);
}
public void shuffle4(){
int childcount = buttonLayoutToShuffle.getChildCount();
// create array
View[] children = new View[childcount];
// get children of linearlayout
for (int i=0; i < childcount; i++){
children[i] = buttonLayoutToShuffle.getChildAt(i);
}
//now remove all children
buttonLayoutToShuffle.removeAllViews();
buttonLayoutToShuffle.addView(children[3]);
buttonLayoutToShuffle.addView(children[1]);
//first position
buttonLayoutToShuffle.addView(children[0]);
//second position
buttonLayoutToShuffle.addView(children[2]);
//third position
}
}
| true
|
f4c742696cba03a1c055e30d29d0d564049ad44f
|
Java
|
joaope-code/lista-1
|
/src/com/company/Exercicio16.java
|
UTF-8
| 538
| 3.125
| 3
|
[] |
no_license
|
package com.company;
import java.util.Scanner;
public class Exercicio16 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Qual o tamanho da área a ser pintada?");
int area = scan.nextInt();
int ap = area/3;
int tinta = 18;
int result = ap/tinta;
int valor = 80;
System.out.println("A quantidade de latas de tintas vai ser " + Math.round(result));
System.out.println("Vai custar " +result*80);
}
}
| true
|
a36959ec0293d264031ae616a99b7bc3a74b6774
|
Java
|
is8bella/IntroToJavaWorkshop
|
/src/MadLibs.java
|
UTF-8
| 579
| 2.78125
| 3
|
[] |
no_license
|
import javax.swing.JOptionPane;
public class MadLibs
{
public static void main(String[] args)
{
/*String verb = JOptionPane.showInputDialog("Please enter a verb in past tense");
String adj = JOptionPane.showInputDialog("Please enter an adjective");
String noun = JOptionPane.showInputDialog("Please enter a noun");
JOptionPane.showMessageDialog(null, "Loading Madlib");
JOptionPane.showMessageDialog(null, "The " + adj + " " + noun + " " + verb + " his way to the store but was dissapointed to see that its favorate style of socks were not in stock");
*/
}
}
| true
|
ba36f2091ed34ad92b53417ae5474ae89ac5a173
|
Java
|
gujiacun/Homework
|
/20170427/src/com/_520it/pss/test/MemberDAOTest.java
|
UTF-8
| 2,559
| 3.234375
| 3
|
[] |
no_license
|
// 需求:创建MemberDAO的测试类,测试IMember的各种与数据库交互的方法
// 在原有基础上,把原有的代码重构设计,把重复的代码封装成另一个类,以后要写几十个方法,操作几百张表时减少代码量
// 把Statement对象转换为PreparedStatement对象
package src.com._520it.pss.test;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import src.com._520it.pss.dao.IMemberDAO;
import src.com._520it.pss.dao.impl.MemberDAOImpl;
import src.com._520it.pss.member.Member;
public class MemberDAOTest {
// 测试方法,增加一个新成员
@Test
public void testAdd() throws Exception {
// 建实体类的对象
Member member01 = new Member(8, "Saito", 20);
// 建实现类的对象
IMemberDAO memberDAO = new MemberDAOImpl();
memberDAO.add(member01);
}
// 测试方法,删除一个退出的成员
@Test
public void testDelete() throws Exception {
IMemberDAO memberDAO = new MemberDAOImpl();
memberDAO.delete(5L);
}
// 修改Risa的年龄信息,改为18
@Test
public void testUpdate() throws Exception {
Member member = new Member();
IMemberDAO memberDAO = new MemberDAOImpl();
// 先把要修改的数据通过实体类的set方法传入新建的Member对象里,这样把对象传入实现类的方法中时,对象就自带数据,方法内部可以调用
member.setAge(18);
memberDAO.update(2L, member);
}
// 根据主键(id)查Manaka的信息
@Test
public void testGet() throws Exception {
IMemberDAO memberDAO = new MemberDAOImpl();
memberDAO.get(4L);
}
// 根据主键(id)查Manaka的信息
@Test
public void testGetMember() throws Exception {
IMemberDAO memberDAO = new MemberDAOImpl();
Member member = memberDAO.getMember(4L);
System.out.println(member.toString());
}
// 查所有人信息
@Test
public void testListAll() throws Exception {
IMemberDAO memberDAO = new MemberDAOImpl();
List<Member> list = memberDAO.listAll();
for (Member member : list) {
System.out.println(member);
}
}
}
/**
* 小结:
* Statement表示静态SQL语句的对象,在建String时已经把SQL里面的参数值设置好
* PreparedStatement表示预编译的SQL语句对象,建String时里面的参数只用占位符?表示,
* 在后面语句中再设置具体的值
*/
| true
|
23a174aeca5e3223c55686838c7a642fa477f65d
|
Java
|
cbonami/mmm
|
/mmm-util/mmm-util-core/src/main/java/net/sf/mmm/util/math/api/NumberType.java
|
UTF-8
| 5,016
| 2.875
| 3
|
[
"Apache-2.0"
] |
permissive
|
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.math.api;
import net.sf.mmm.util.lang.api.attribute.AttributeReadMaximumValue;
import net.sf.mmm.util.lang.api.attribute.AttributeReadMinimumValue;
/**
* This class represents the {@link Class type} reflecting a specific {@link Number}. It allows to check attributes like
* {@link #isDecimal()} or to {@link #getExactnessDifference(NumberType) compare} {@link NumberType}s.<br>
* Further it acts as factory to create according numbers {@link NumberType#valueOf(String) from string} or
* {@link NumberType#valueOf(String) by converting an given number}.<br>
* This is a class and NOT an {@link Enum} to be extensible.
*
* @see net.sf.mmm.util.math.base.MathUtilImpl#getNumberType(Class)
* @param <NUMBER> is the generic type of the {@link #getNumberClass() represented number-class}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.1
*/
public interface NumberType<NUMBER extends Number> extends AttributeReadMinimumValue<NUMBER>,
AttributeReadMaximumValue<NUMBER> {
/**
* This method gets an instance of the {@link #getNumberClass() represented number-class} with the numeric value given
* by <code>number</code>.
*
* @param number is the numeric value to convert.
* @param failIfUnprecise - if <code>true</code> and conversion causes precision loss, a
* {@link NumberConversionException} is thrown, if <code>false</code> this method acts like a primitive cast
* and conversion is always successfully.
* @return a {@link Number} instance of the {@link #getNumberClass() represented number-class} with the value of the
* given <code>number</code>. This will be the same instance as <code>number</code> if it is an
* {@link Class#isInstance(Object) instance} of the {@link #getNumberClass() represented number-class} .
* @throws NumberConversionException if the conversion will loose precision (e.g. when converting a decimal
* {@link Double} to {@link Integer})
*/
NUMBER valueOf(Number number, boolean failIfUnprecise) throws NumberConversionException;
/**
* This method gets an instance of the {@link #getNumberClass() represented number-class} with the numeric value
* identified by the given string <code>number</code>.
*
* @param number is the string to be parsed as number.
* @return the parsed number of the according type.
* @throws NumberConversionException if the given <code>number</code> has an illegal format.
*/
NUMBER valueOf(String number) throws NumberConversionException;
/**
* This method gets the {@link Class} reflecting the {@link Number} represented by this {@link NumberType}.
*
* @return the number type.
*/
Class<NUMBER> getNumberClass();
/**
* This method determines if the represented {@link #getNumberClass() Number} is a decimal value.<br>
* E.g. {@link Double}, {@link Float}, or {@link java.math.BigDecimal} represent decimal values while {@link Integer}
* or {@link Long} are NOT decimal.
*
* @return <code>true</code> if the represented {@link #getNumberClass() Number} is a decimal value.
*/
boolean isDecimal();
/**
* This method gets the difference of the exactness of this {@link NumberType} and the given <code>otherType</code>.<br>
* <b>ATTENTION:</b><br>
* Some types such as {@link Double} and {@link java.math.BigInteger} are NOT really comparable so the exactness
* difference might only make sense if the compared {@link NumberType types} are both {@link #isDecimal() decimal} or
* both {@link #isDecimal() non-decimal} (mathematical integers). However the order of typical types is:<br>
* <ol>
* <li>{@link Byte}</li>
* <li>{@link Short}</li>
* <li>{@link Integer}</li>
* <li>{@link Long}</li>
* <li>{@link Float}</li>
* <li>{@link Double}</li>
* <li>{@link java.math.BigInteger}</li>
* <li>{@link java.math.BigDecimal}</li>
* </ol>
*
* @param otherType is the {@link NumberType} to compare with.
* @return the difference of the exactness. Will be <code>0</code> if this {@link NumberType} is equal to
* <code>otherType</code>, positive if this {@link NumberType} is more exact (later in the examples above) and
* negative if <code>otherType</code> is more exact.
*/
int getExactnessDifference(NumberType<?> otherType);
/**
* {@inheritDoc}
*
* Will return <code>null</code> in case of an unbounded type such as {@link java.math.BigInteger}.
*
* @since 4.0.0
*/
@Override
NUMBER getMinimumValue();
/**
* {@inheritDoc}
*
* Will return <code>null</code> in case of an unbounded type such as {@link java.math.BigInteger}.
*
* @since 4.0.0
*/
@Override
NUMBER getMaximumValue();
}
| true
|
9f59eb20f9603b98dd70c5c7f3848beb7e184f75
|
Java
|
BaharHaciimam/JavaCamp
|
/gameProject/src/gameProject/Gamer.java
|
UTF-8
| 1,259
| 2.8125
| 3
|
[] |
no_license
|
package gameProject;
public class Gamer {
private int gamerId;
private String firstName;
private String lastName;
private String nationalIdentity;
private int yearOfBirth;
public Gamer() {
}
public Gamer(int gamerId, String firstName, String lastName, String nationalIdentity, int yearOfBirth) {
super();
this.gamerId = gamerId;
this.firstName = firstName;
this.lastName = lastName;
this.nationalIdentity = nationalIdentity;
this.yearOfBirth = yearOfBirth;
}
public int getGamerId() {
return gamerId;
}
public void setGamerId(int gamerId) {
this.gamerId = gamerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNationalIdentity() {
return nationalIdentity;
}
public void setNationalIdentity(String nationalIdentity) {
this.nationalIdentity = nationalIdentity;
}
public int getYearOfBirth() {
return yearOfBirth;
}
public void setYearOfBirth(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
}
| true
|
c32ba885a2b24026ad97945353468bf1a3b6a778
|
Java
|
softwareengineerhub/spring
|
/JTA/My-Spring5-JTA-database-jms/src/main/java/com/mycompany/my/spring5/jta/org/service/BusinessService.java
|
UTF-8
| 1,151
| 2.078125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.my.spring5.jta.org.service;
import javax.transaction.Transactional;
import com.mycompany.my.spring5.jta.org.model.Company;
import com.mycompany.my.spring5.jta.org.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author Denys.Prokopiuk
*/
@Service
@Transactional
public class BusinessService {
@Autowired
private CompanyService companyService;
@Autowired
private EmployeeService employeeService;
@Autowired
private NotificationServiceXA notificationService;
@Autowired
private NotificationServiceXAWithTemplate notificationServiceXAWithTemplate;
public void process(Employee employee, Company company) {
notificationService.makeNotification();
notificationServiceXAWithTemplate.makeNotification();
companyService.save(company);
employeeService.save(employee);
}
}
| true
|
d8f54fb03446356623fc75c32e80181c93eb82b7
|
Java
|
VladimirZhyzhKin1/jd1-academy
|
/Chapter 5/Working with files/FileWrite.java
|
UTF-8
| 1,499
| 3.515625
| 4
|
[] |
no_license
|
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileWrite {
public static void main(String[] args) throws IOException {
FileReader fileIn = null;
FileWriter fileOut = null;
try {
File name = new File("file.txt");
System.out.println(name.getAbsoluteFile());
System.out.println(name.canRead());
System.out.println(name.delete());//мы удаляем файл, поэтому все остальное не выполняется и false до того как createNewFile()
System.out.println("name.canRead() " + name.canRead());
System.out.println("name.exists() " + name.exists());
System.out.println("name.createNewFile() " + name.createNewFile());
System.out.println("name.exists() " + name.exists());
fileIn = new FileReader("file.txt");
fileOut = new FileWriter("copied_file.txt");
int a;
//копирование содержимого файла file.txt
while ((a = fileIn.read()) != -1) {
fileOut.write(a);//чтение содержимого file.txt и запись в файл в copied_file.txt
}
} finally {
if (fileIn != null) {
fileIn.close();
}
if (fileOut != null) {
fileOut.close();
}
}
}
}
| true
|
e0797afba23f645cae4a840180c285cae3395622
|
Java
|
YairAlfredoVargasDelgado/proyecto-impuestos
|
/src/main/java/com/poo/impuestovehicular/entidades/Marca.java
|
UTF-8
| 1,477
| 2.609375
| 3
|
[] |
no_license
|
package com.poo.impuestovehicular.entidades;
import java.util.ArrayList;
import java.util.Objects;
public class Marca extends EntidadBase {
private String nombre;
private String código;
private ArrayList<Vehículo> vehículos;
public Marca() {}
@Override
public String toString() {
return super.toString() + ";" + getCódigo() + ";" + getNombre();
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCódigo() {
return código;
}
public void setCódigo(String código) {
this.código = código;
}
public ArrayList<Vehículo> getVehículos() {
return vehículos;
}
public void setVehículos(ArrayList<Vehículo> vehículos) {
this.vehículos = vehículos;
}
@Override
public int hashCode() {
int hash = 7;
hash = 11 * hash + Objects.hashCode(this.nombre);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Marca other = (Marca) obj;
if (!Objects.equals(this.nombre, other.nombre)) {
return false;
}
return true;
}
}
| true
|
20e3cb6cbd61e632f92ef1333a43aef1394b7f97
|
Java
|
kaiminRyan/springboot-demo
|
/multidatasource/src/main/java/com/ryan/springboot/service/Impl/UserServiceImpl.java
|
UTF-8
| 815
| 2.1875
| 2
|
[] |
no_license
|
package com.ryan.springboot.service.Impl;
import com.ryan.springboot.dao.cluster.CityDao;
import com.ryan.springboot.dao.master.UserDao;
import com.ryan.springboot.domain.City;
import com.ryan.springboot.domain.User;
import com.ryan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by kaimin on 2017/4/18.
* time : 下午4:15
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private CityDao cityDao;
@Override
public User findUserByName(String userName) {
User user = userDao.findByName(userName);
City city = cityDao.findByName("杭州");
user.setCity(city);
return user;
}
}
| true
|
1a64d6da36d88e149791651b9fcd2ba3cc506a30
|
Java
|
smalldirector/reflectionx
|
/src/test/java/com/pleasecode/reflectionx/data/annotations/ClassAnnotationB.java
|
UTF-8
| 470
| 2.21875
| 2
|
[
"MIT"
] |
permissive
|
package com.pleasecode.reflectionx.data.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(ClassAnnotationBs.class)
public @interface ClassAnnotationB {
int age() default 0;
}
| true
|
ac94c2e52c1938f286239e9fdbe3b262c7e31d38
|
Java
|
hdxszxx/ProxyCrawler
|
/src/main/java/com/zxx/proxycrawler/util/DailiUtil.java
|
UTF-8
| 1,613
| 2.484375
| 2
|
[] |
no_license
|
package com.zxx.proxycrawler.util;
import cn.hutool.json.JSONArray;
import com.zxx.proxycrawler.entity.Proxy;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author zxx
* @version 1.0
* @date 2019/11/20 15:47
*/
public class DailiUtil {
public static List<Proxy> getProxy(){
String url = SettingUtil.getValue("outdaili");
List<Proxy> daili = new ArrayList<Proxy>();
try {
System.out.println("开始获取本地缓存的代理");
File file = new File(url);
if (!file.exists()) {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String a = null;
while ((a = br.readLine())!=null){
sb.append(a);
}
br.close();
fr.close();
JSONArray jsonArray = new JSONArray(sb.toString());
daili = jsonArray.toList(Proxy.class);
System.out.println("当前获取到的代理数为:"+daili.size());
return daili;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("当前获取到的代理数为:"+daili.size());
return daili;
}
}
| true
|
20c28fa5ecc3729dc5234478352302e29a2343d0
|
Java
|
htl-leonding-project/nfc-meal-counter
|
/application-server/src/main/java/at/htl/mealcounter/control/ConsumationRepository.java
|
UTF-8
| 3,565
| 2.21875
| 2
|
[] |
no_license
|
package at.htl.mealcounter.control;
import at.htl.mealcounter.entity.Consumation;
import at.htl.mealcounter.entity.NfcCard;
import at.htl.mealcounter.entity.Person;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TemporalType;
import javax.transaction.Transactional;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.System.out;
@ApplicationScoped
public class ConsumationRepository implements PanacheRepository<Consumation> {
@Inject
EntityManager em;
@Inject
PersonRepository personRepository;
public Consumation findByDateAndPerson(LocalDate myDate, Person person) {
Consumation consumation;
try {
consumation = em.createQuery("select c from Consumation c where " +
"c.date = :DATE AND " +
"c.person.id = :ID", Consumation.class)
.setParameter("DATE", myDate)
.setParameter("ID", person.getId())
.getSingleResult();
}catch (NoResultException e){
consumation = null;
}
return consumation;
}
@Transactional
public void readFromCsv() {
URL url = Thread.currentThread().getContextClassLoader().getResource("consumations.csv");
try (Stream<String> stream = Files.lines(Paths.get(url.getPath()), StandardCharsets.UTF_8)) {
stream.skip(1)
.map(c -> c.split(";"))
.map(c -> new Consumation(
personRepository.findById(Long.parseLong(c[2])),
LocalDate.parse(c[0]),
Boolean.parseBoolean(c[1])))
.peek(out::println)
.forEach(em::merge);
} catch (IOException e) {
e.printStackTrace();
}
}
@Transactional
public void fillWithTestData() {
for (int i = 1; i <= personRepository.findAll().list().size(); i++) {
for (int j = 1; j <= 12; j++) {
YearMonth yearMonthObject = YearMonth.of(2020, j);
int daysInMonth = yearMonthObject.lengthOfMonth();
for (int k = 1; k <= daysInMonth; k++) {
String month = String.valueOf(j);
String day= String.valueOf(k);
String date = "";
boolean consumed = true;
int zahl = (int)((Math.random()) * 2 + 1);
if(j < 10){
month = "0"+j;
}
if(k < 10){
day = "0"+k;
}
date = "2020-"+month+"-"+day;
consumed = zahl == 1;
Consumation consumation = new Consumation(personRepository.findById((long)i),LocalDate.parse(date),consumed);
em.merge(consumation);
}
}
}
}
}
| true
|
573491bf5cebdda1494fadd40472aea297b9b2a6
|
Java
|
msj521/official_website
|
/java/sific/src/main/java/com/example/model/User.java
|
UTF-8
| 674
| 1.898438
| 2
|
[] |
no_license
|
package com.example.model;
import java.io.Serializable;
import java.util.Date;
import com.example.config.DateSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
@Data
public class User implements Serializable {
private static final long serialVersionUID = -5881416787437583017L;
private int fid;
private String user_name;
private String password;
private String email;
private String record_status;
private String tel;
@JsonSerialize(using = DateSerializer.class)
private Date create_time;//查询 开始添加时间
@JsonSerialize(using = DateSerializer.class)
private Date update_time;//查询 结束添加时间
}
| true
|
6728498fbd0ace2e684b12b1375749da70f175e5
|
Java
|
DSuzumoto-3333/ClueGame
|
/src/gameEngine/Board.java
|
UTF-8
| 38,578
| 3.40625
| 3
|
[] |
no_license
|
package gameEngine;
import java.util.*;
import java.util.Set;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.util.HashSet;
import java.io.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* Represents the game board itself, and contains methods pertaining to player movement. Also handles loading in data from setup and layout files provided. The board uses a singleton design,
* so the method .getInstance() must be used rather than creating a new instance through the constructor.
* @author Derek Suzumoto
* @author Luke Wakumoto
*/
public class Board extends JPanel implements MouseListener{
//Constants for grid size
private static int boardWidth;
private static int boardHeight;
//The game board itself
private BoardCell[][] gameBoard;
//Sets for calculating viable targets to move to.
private Set<BoardCell> targets;
private Stack<BoardCell> visited;
//Strings for loading in data from the layout and setup configuration files.
private String layoutConfigFile, setupConfigFile;
//Map to contain all the tile characters
private Map<Character, Room> roomMap;
private static Board boardInstance = new Board();
//Set to hold all player objects involved in the game
private ArrayList<Player> players;
//ArrayList to hold all the cards in the game's deck.
private ArrayList<Card> deck;
//A set to hold the answer to the game's mystery, or the solution.
private Set<Card> solution;
//Variables to determine how the state of the turn engine
private boolean turnComplete;
private int currentPlayerNumber = 0, currentRoll;
private Player currentPlayer, humanPlayer;
private String currentSuggestion, currentStatus;
private Player currentDisprover;
//Save the game's JFrame
private ClueGame frame;
//Save the game's card panel and control panel
private GameCardPanel cardPanel;
private GameControlPanel controlPanel;
/**
* Since we're using a singleton pattern, our constructor is essentially empty. We will use .initialize() after setting and loading the configuration files.
* This allows us to re-use the same instance, as we don't want to have multiple game-boards, but leaves us the freedom to re-call .setConfigFiles() and .initialize() and "reset"
* The board.
*/
public Board() {
super();
}
/**
* Takes in the string for the layout and setup files, and sets the instance variable strings to them.
* @param layoutFile - A string containing the name of a .cvs file that holds information about every cell and their attributes. Assumed to be in the "data/" directory.
* @param setupFile - A string containing the name of a .txt file that holds the name and character of every room on the board, as well as defines Walkway and Unused spaces. Assumed to be in the "data/" directory.
*/
public void setConfigFiles(String layoutFile, String setupFile) {
layoutConfigFile = "data/" + layoutFile;
setupConfigFile = "data/" + setupFile;
}
/**
* Method to handle any thrown BadConfigFormatExceptions from loadSetupConfig() and loadLayoutConfig(). Can be recalled to clear and reset the game board,
* or load a new board if setConfigFiles() is called first. After config file data is loaded, the method also calls for adjacency lists to be populated.
*/
public void initialize() {
//Allocate memory for instance variables
targets = new HashSet<BoardCell>();
visited = new Stack<BoardCell>();
roomMap = new HashMap<Character, Room>();
players = new ArrayList<Player>();
deck = new ArrayList<Card>();
//Add the mouse listener to the panel
addMouseListener(this);
//Try to load the setup and layout config files, and initialize the game instance variables. Catch and handle BadConfigFormatExceptions here.
try {
//Load the setup file first.
loadSetupConfig();
//Then generate the game board based on the rooms specified in the setup file
loadLayoutConfig();
//Once the files are loaded properly, parse the newly generated board and build adjacency lists.
setAdjLists();
//Deal the cards and determine the solution to the game.
dealCards();
}
//In the event of a bad input file, print out the error message to the console, and write the error to a log.
catch (BadConfigFormatException e) {
System.out.println("Invalid config file detected. Please check the log file in data for more information.");
}
}
/**
* A void method used to read in the provided room configuration file, and populate roomMap with new room objects.
* @throws BadConfigFormatException - In the event that the setup file is bad, the program will throw an exception with a message explaining the problem.
*/
public void loadSetupConfig() throws BadConfigFormatException {
try {
//Open the file and prepare a string to read the line into. Add a line counter in case of errors.
FileReader reader = new FileReader(setupConfigFile);
Scanner scanner = new Scanner(reader);
String line;
int i = 0;
//Read all lines in the file.
while(scanner.hasNextLine()) {
line = scanner.nextLine();
//If the line is null, the bottom of the file has been reached.
if(line.length() == 0) {
scanner.close();
break;
}
//If the line doesn't start with a slash indicating that it's a comment, split it.
if(!(line.charAt(0) == '/')) {
String[] data = line.split(",");
//Pre-declare a few commonly used variables.
Room room;
char initial;
//Since the 2nd entry is always a name, format it here to remove the space at the beginning.
String name = data[1].replaceFirst("\\s+","");
switch(data[0]) {
//If the entry declares a room
case "Room":
//Verify the entry has the proper length
if(data.length == 3) {
//Create a new room and put it in the map with the key being it's initial.
room = new Room(name);
initial = data[2].replaceFirst("\\s+","").charAt(0);
roomMap.put(initial, room);
//Create a room card, and add it to the deck.
deck.add(new Card(name, CardType.ROOM));
}
//Throw an exception if the entry is not the correct length.
else {
scanner.close();
throw new BadConfigFormatException("Invalid format in " + setupConfigFile + " on line " + i + ": Line contains the wrong number of entries for a Room object.");
}
break;
//If the entry declares a non-room space
case "Space":
//Verify the entry has the proper length
if(data.length == 3) {
//Create a new room and put it in the map with the key being it's initial.
room = new Room(name);
initial = data[2].replaceFirst("\\s+","").charAt(0);
roomMap.put(initial, room);
}
//Throw an exception if the entry is not the correct length.
else {
scanner.close();
throw new BadConfigFormatException("Invalid format in " + setupConfigFile + " on line " + i + ": Line contains the wrong number of entries for a Space object.");
}
break;
//If the entry declares a weapon
case "Weapon":
//Verify the entry has the proper length
if(data.length == 2) {
//Add a new weapon card to the deck.
deck.add(new Card(name, CardType.WEAPON));
}
//Throw an exception if the entry is not the correct length.
else {
scanner.close();
throw new BadConfigFormatException("Invalid format in " + setupConfigFile + " on line " + i + ": Line contains the wrong number of entries for a Weapon object.");
}
break;
case "Player":
if(data.length == 7) {
//Create a new person object
//Read in all the RGB values the file provides, and convert them to ints.
int redVal = Integer.parseInt(data[2].replaceFirst("\\s+","").replace(",",""));
int greenVal = Integer.parseInt(data[3].replaceFirst("\\s+","").replace(",",""));
int blueVal = Integer.parseInt(data[4].replaceFirst("\\s+","").replace(",",""));
int playerRow = Integer.parseInt(data[5].replaceFirst("\\s+","").replace(",",""));
int playerCol = Integer.parseInt(data[6].replaceFirst("\\s+","").replace(",",""));
//Create the new player object, saved as humanPlayer
humanPlayer = new HumanPlayer(name, new Color(redVal, greenVal, blueVal), playerRow, playerCol);
players.add(humanPlayer);
//Add a new weapon card to the deck.
deck.add(new Card(name, CardType.PERSON));
}
//Throw an exception if the entry is not the correct length.
else {
scanner.close();
throw new BadConfigFormatException("Invalid format in " + setupConfigFile + " on line " + i + ": Line contains the wrong number of entries for a Player object.");
}
break;
case "NPC":
if(data.length == 7) {
//Create a new person object
//Read in all the RGB values the file provides, and convert them to ints.
int redVal = Integer.parseInt(data[2].replaceFirst("\\s+","").replace(",",""));
int greenVal = Integer.parseInt(data[3].replaceFirst("\\s+","").replace(",",""));
int blueVal = Integer.parseInt(data[4].replaceFirst("\\s+","").replace(",",""));
int playerRow = Integer.parseInt(data[5].replaceFirst("\\s+","").replace(",",""));
int playerCol = Integer.parseInt(data[6].replaceFirst("\\s+","").replace(",",""));
//Create the new player object.
players.add(new ComputerPlayer(name, new Color(redVal, greenVal, blueVal), playerRow, playerCol));
//Add a new weapon card to the deck.
deck.add(new Card(name, CardType.PERSON));
}
//Throw an exception if the entry is not the correct length.
else {
scanner.close();
throw new BadConfigFormatException("Invalid format in " + setupConfigFile + " on line " + i + ": Line contains the wrong number of entries for an NPC object.");
}
break;
default:
throw new BadConfigFormatException("Attempted to specify tile of unknown type: " + data[0] + " in " + setupConfigFile + " On line " + i);
}
}
//Increment the counter and close the file.
i++;
}
}
//If the file is not found, throw a new BadConfigFormatException.
catch(FileNotFoundException e){
throw new BadConfigFormatException("File 'data/" + setupConfigFile + " not found. Please check the data directory.");
}
}
/**
* A void method used to read in the board configuration file, create a new gameBoard array, and populate it with cells based on the config data.
* @throws BadConfigFormatException - In the event that the setup file is bad, the program will throw an exception with a message explaining the problem.
*/
public void loadLayoutConfig() throws BadConfigFormatException {
try {
//Open the layout file and create an ArrayList of strings to hold each line in the file.
FileReader reader = new FileReader(layoutConfigFile);
Scanner scanner = new Scanner(reader);
ArrayList<String> board = new ArrayList<String>();
//Save each line from the file to board, and close.
while(scanner.hasNextLine()) {
board.add(scanner.nextLine());
}
scanner.close();
//The height of the board is the number of rows, and the width is the length of each row.
boardHeight = board.size();
boardWidth = board.get(0).split(",").length;
//Iterate through board and begin creating tiles. Store them in gameBoard. Initialize a line counter.
gameBoard = new BoardCell[boardHeight][boardWidth];
int i = 0;
for(String line : board) {
//Split the line into tiles and ensure there are the right amount of tiles specified.
String[] data = line.split(",");
if(data.length == boardWidth) {
for(int j = 0; j < data.length; j++) {
//Put a new cell in gameBoard at i,j
gameBoard[i][j] = new BoardCell(i,j);
switch(data[j].charAt(0)) {
case 'X':
gameBoard[i][j].setUnused();
break;
case 'W':
gameBoard[i][j].setWalkway();
//Check to see if it's a doorway.
if(data[j].length() == 2) {
char direction = data[j].charAt(1);
//Set the door direction to the indicated direction.
switch(direction){
case '^':
gameBoard[i][j].setDoor(DoorDirection.UP);
break;
case '<':
gameBoard[i][j].setDoor(DoorDirection.LEFT);
break;
case '>':
gameBoard[i][j].setDoor(DoorDirection.RIGHT);
break;
case 'v':
gameBoard[i][j].setDoor(DoorDirection.DOWN);
break;
}
}
break;
default:
char Initial = data[j].charAt(0);
Room room = roomMap.get(Initial);
//Make sure the room is specified in roomMap.
if(!(room == null)) {
//If the room tile has only one character, it's just an empty room tile.
if(data[j].length() == 1) {
gameBoard[i][j].setRoom(Initial, false, false);
}
else {
//If the room cell has two character specified, determine what type of cell it is.
switch(data[j].charAt(1)) {
//If it's a center cell, set it as such and save it in the room object.
case '*':
gameBoard[i][j].setRoom(Initial, false, true);
room.setCenterCell(gameBoard[i][j]);
break;
//If it's a label cell, set it as such and save it in the room object.
case '#':
gameBoard[i][j].setRoom(Initial, true, false);
room.setLabelCell(gameBoard[i][j]);
break;
//If it's a secret passage, determine if the secret passage is valid.
default:
room = roomMap.get(data[j].charAt(1));
//If it's a valid secret passage, set the cells secretPassage char.
if(!(room == null)) {
gameBoard[i][j].setRoom(Initial, false, false);
gameBoard[i][j].setSecretPassage(data[j].charAt(1));
}
//If it's not, throw a new exception.
else {
throw new BadConfigFormatException("Invalid line format on line " + i + " in " + layoutConfigFile + ", Secret passage to invalid room specified.");
}
break;
}
}
}
else {
throw new BadConfigFormatException("Invalid line format on line " + i + " in " + layoutConfigFile + ", Invalid room of type " + Initial + " specified.");
}
}
}
}
//Throw an error if an invalid entry is detected.
else {
throw new BadConfigFormatException("Invalid line format on line " + i + " in " + layoutConfigFile + ", wrong number of tiles specified.");
}
i++;
}
}
//If the file is not found, throw a new BadConfigFormatException.
catch(FileNotFoundException e){
throw new BadConfigFormatException("File 'data/" + setupConfigFile + " not found. Please check the data directory.");
}
}
/**
* A method to set every tile in the gameBoard's adjacency lists. Non-central room tiles and unused tiles will have empty adjacency lists. Walkway tiles will only hold adjacencies with other walkway tiles,
* Unless the walkway is a door, in which case it will also hold it's corresponding room's center tile. Room centers will hold adjacency to all doors connecting to the room, and the room center of any rooms
* linked by secret passage.
*/
public void setAdjLists() {
//Iterate through every tile.
for(int i = 0; i < boardHeight; i++) {
for(int j = 0; j < boardWidth; j++) {
//All walkway and door tiles will have an adjacency list.
BoardCell current = gameBoard[i][j];
if(current.getInitial() == 'W') {
//Pass in a DoorDirection to specify the direction the next tile is from the current tile, useful for linking doors to the proper rooms.
//Check tile above.
if(i > 0) {
checkAdjTile(current, i - 1, j, DoorDirection.UP);
}
//Check tile below
if(i < boardHeight - 1) {
checkAdjTile(current, i + 1, j, DoorDirection.DOWN);
}
//Check tile to the left
if(j > 0) {
checkAdjTile(current, i, j - 1, DoorDirection.LEFT);
}
//Check tile to the right
if(j < boardWidth - 1) {
checkAdjTile(current, i, j + 1, DoorDirection.RIGHT);
}
}
//Otherwise, if the tile has a secret passage, link the secret passage tile of this room to the center of the other room.
else if (!(current.getSecretPassage() == 'X')){
BoardCell secret = getRoom(current.getSecretPassage()).getCenterCell();
BoardCell center = getRoom(current).getCenterCell();
secret.addAdjacency(center);
}
}
}
}
/**
* A method used to determine if a tile will be a valid adjacency to the current tile.
* @param current - The board cell that will have it's adjacency list added to if the tile tested is valid.
* @param i - The row position of the cell that is being tested for valid adjacency.
* @param j - The column position of the cell that is being tested for valid adjacency.
* @param direction - The direction that the tile being tested is in with respect to the current tile.
*/
public void checkAdjTile(BoardCell current, int i, int j, DoorDirection direction) {
BoardCell nextTo = gameBoard[i][j];
//If the tile above exists, and is another walkway tile, add it to the adjacency list.
if(nextTo.getInitial() == 'W') {
current.addAdjacency(nextTo);
}
//If the tile next to the current tile is a room tile, and the current tile is a doorway facing the proper direction, add the center of the room to the adjacency list.
else if(current.isDoorway() &&
!(nextTo.getInitial() == 'X') &&
!(nextTo.getInitial() == 'W') &&
current.getDoorDirection().equals(direction)){
BoardCell center = getRoom(nextTo).getCenterCell();
current.addAdjacency(center);
center.addAdjacency(current);
}
}
/**
* A method to calculate every possible board cell that a player, human or computer, can move to given the number they roll.
* @param startCell - The board cell to start on
* @param length - The length of the roll, as an integer.
*/
public void calcTargets(BoardCell startCell, int length) {
targets.clear();
visited.clear();
calcTargetsRecursive(startCell, length);
}
/**
* Moves through the board, checking for all possible paths a player could take away from the starting cell, and
* adds all possible locations to targets. Adds tiles that have already been visited by the calculation function,
* but can't be landed on by the player, to visited.
* @param startCell - The starting position to calculate a roll from.
* @param length - The length of the roll, an integer from 0-6.
*/
public void calcTargetsRecursive(BoardCell startCell, int length) {
//Push the current cell to the top of the visited stack.
visited.push(startCell);
//If we have made it to the end of our roll, determine if the cell is a valid target
if(length == 0) {
//If the cell is not occupied, or if it is a room (which can be occupied by multiple people), the cell is a valid target
if(!(startCell.getOccupied()) || startCell.isRoomCenter()) {
//The cell is added to the targets set.
targets.add(startCell);
}
}
//If the end of the roll has not been reached, but the cell is a room center, determine if the roll can stop here (If the room center is the start of the roll, we must leave).
else if(startCell.isRoomCenter() && visited.size() > 1){
targets.add(startCell);
}else{
//Grab every tile in the cell's adjacency list, and iterate through them.
Set<BoardCell> T = startCell.getAdjList();
for(BoardCell t : T) {
//If the cell isn't in visited, and is either not occupied or a room center, run calcTargetsRecursive() again.
if(!(visited.contains(t)) && (!t.getOccupied() || t.isRoomCenter())) {
calcTargetsRecursive(t, length-1);
}
}
}
//Pop the tile once all the paths branching from below are analyzed so that a different path can use this tile again.
visited.pop();
}
/**
* Method to generate the game's solution, then deal the remaining cards amongst the players.
*/
public void dealCards() throws BadConfigFormatException{
//Declare a set to count how many types of cards the setup file specified.
Set<CardType> types = new HashSet<CardType>();
for(Card card : deck) {
//If a card in the deck specifies a new type of card, add it to the set.
if(!(types.contains(card.getType()))) {
types.add(card.getType());
}
}
//Ensure that the setup file specified all 3 types of cards expected: (room, weapon, and person)
if(types.size() == 3) {
//Allocate memory for the solution set.
solution = new HashSet<Card>();
//Create a copy of deck
ArrayList<Card> deckCopy = new ArrayList<Card>(deck);
//Add one card of each type to the set, removing each card from the deck so it is not used again.
solution.add(getCardOfType(CardType.ROOM));
solution.add(getCardOfType(CardType.PERSON));
solution.add(getCardOfType(CardType.WEAPON));
Random rand = new Random();
for(Player player : players) {
for(int i = 0; i < 3; i++) {
int random = rand.nextInt(deck.size());
player.updateHand(new Card(deck.get(random)));
deck.remove(random);
}
}
//Restore the deck.
deck = deckCopy;
}
//If not, throw a new BadConfigFormatException.
else {
throw new BadConfigFormatException("Error: Setup file " + setupConfigFile + " does not specify all 3 required types of cards.");
}
}
/**
* Used to grab a card of a certain type from the deck. Once a random card of the correct type is found, it will remove it from the deck and return a deep copy.
* Will continue to loop until a card of the correct type is found.
* @param type
* @return
*/
public Card getCardOfType(CardType type) {
//Loop until the correct type of card is found.
Random rand = new Random();
while(true) {
//Generate a random number.
int random = rand.nextInt(deck.size());
//If the card at that index in the deck is the proper type, return it.
if(deck.get(random).getType() == type) {
//Use a copy constructor to make a deep copy.
Card card = new Card(deck.get(random));
//Remove the card from the deck so it's not used again.
deck.remove(random);
//Return the new card.
return card;
}
}
}
/**
* Returns true if the accusation set contains the same elements as the solution set, indicating the player made
* a correct accusation.
* @param accusation - A set of cards representing the accusation being made.
* @return
*/
public boolean checkAccusation(Set<Card> accusation) {
//Iterate through each card in both set
for(Card solutionCard : solution) {
for(Card accusationCard : accusation) {
//If they are the same type of card but are not equal, return false.
if(solutionCard.getType().equals(accusationCard.getType()) && !accusationCard.equals(solutionCard)) {
return false;
}
}
}
//If the loop does not find an incorrect card, return true
return true;
}
/**
* A method to check a suggestion. Checks all players that are not the accuser for the cards in their hand
* to determine if the suggestion is valid.
* @param suggestion - The suggestion made by a player being handled.
* @param suggestor - The person who made the suggestion
* @return - The card that debunks the suggestion, null if none found.
*/
public Card checkSuggestion(Set<Card> suggestion, Player suggester) {
//Check every player's hand
for(Player player : players) {
//If the player isn't the suggester, and the player has a debunking card
if(!player.equals(suggester)) {
Card match = player.disproveSuggestion(suggestion);
if(match != null) {
currentDisprover = player;
return match;
}
}
}
//If nothing is found, return null.
return null;
}
/**
* Method to handle a suggestion, performing various tasks, such as moving the suggested player to the suggesting player's position/room,
* and updating the game's status variables.
* @param suggestion - A set of cards making up the suggestion.
* @param suggester - The player that made the suggestion.
*/
public void handleSuggestion(Set<Card> suggestion, Player suggester) {
//Move the suggested player to the room
Card suggestedPlayerCard = null;
for(Card card : suggestion) {
if(card.getType() == CardType.PERSON) {
suggestedPlayerCard = card;
break;
}
}
for(Player player : players) {
if(!(suggestedPlayerCard == null) && suggestedPlayerCard.getName().equals(player.getName())) {
player.setPosition(suggester.getPosition());
//Ensure that the player can remain in the room on their next turn.
player.setCanStay(true);
}
}
//Create the suggestion message
Card suggestedRoomCard = null, suggestedWeaponCard = null;
for(Card card : suggestion) {
switch(card.getType()) {
case ROOM:
suggestedRoomCard = card;
break;
case WEAPON:
suggestedWeaponCard = card;
break;
default:
break;
}
}
currentSuggestion = suggestedPlayerCard.getName() + " in the " + suggestedRoomCard.getName()
+ " with the " + suggestedWeaponCard.getName() + ".";
//Determine if the suggestion is disproved.
Card isDisproved = checkSuggestion(suggestion, suggester);
//If the suggestion is disproved, set the status message accordingly
if(isDisproved != null) {
//If the suggester is not the human player, only update the state variable for status to say it has been disproved.
if(suggester instanceof ComputerPlayer) {
currentStatus = "Suggestion has been disproved!";
}
//If the suggester is the human player, set the status state variable to the name of the disproving card.
else {
currentStatus = isDisproved.getName();
//Update the GUI for the player since suggestions happen after the update for human players.
ShowHumanPlayerSuggestion(isDisproved);
}
//Update the current player's seen set
currentPlayer.addSeen(isDisproved);
}
//If not, set the status message to "Could not disprove suggestion"
else {
currentStatus = "Could not disprove suggestion.";
//Set the current player to remember their accusation
currentPlayer.setAccusation(suggestion);
//Update the GUI manually if the player is a human player
if(suggester instanceof HumanPlayer) {
//Update the GUI for the player since suggestions happen after the update for human players.
ShowHumanPlayerSuggestion(isDisproved);
}
}
}
/**
* Method to handle each turn in the game. Most logic for ComputerPlayer turns is done here, as their turns are processed instantly.
* Turns for HumanPlayers are also started here, but much of the logic is separated into the GUI component classes as the HumanPlayer
* turn is mainly event-driven.
*/
public void handleTurn() {
//Ensure that, while the turn is happening, the next turn cannot begin.
turnComplete = false;
//Set the current player.
currentPlayer = players.get(currentPlayerNumber);
//Clear necessary state variables
currentDisprover = null;
currentSuggestion = "";
currentStatus = "";
//Iterate to the next player, looping at 6
currentPlayerNumber++;
if(currentPlayerNumber == players.size()) {
currentPlayerNumber = 0;
}
//Get a roll length
Random rand = new Random();
currentRoll = rand.nextInt(6) + 1;
//Calculate the possible targets for the player to move to.
calcTargets(currentPlayer.getPosition(), currentRoll);
//If the player is a computer player, run all the necessary computer player methods.
if(currentPlayer instanceof ComputerPlayer) {
//The turn will be over in an instant.
turnComplete = true;
//If the computer has figured out the solution, end the game
if(currentPlayer.getAccusation() != null) {
//At this point, the game should always be lost. Notify the player and exit the game.
boolean gameLost = checkAccusation(currentPlayer.getAccusation());
if(gameLost) {
JOptionPane.showMessageDialog(frame,
"The NPCs have solved the game before you.\nBetter luck next time!",
"Game Lost!",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
//If not, let the computer player do a regular turn, instead.
else {
//Move the current player
currentPlayer.move();
//If the player has moved to a room, let them make a suggestion.
if(currentPlayer.getPosition().isRoomCenter()) {
//Handle the player's suggestion.
handleSuggestion(((ComputerPlayer) currentPlayer).createSuggestion(), currentPlayer);
}
//Repaint the board and let the turn end
repaint();
}
}
//If it's a human, don't note that the turn is over yet and handle some GUI stuff
else {
//If the player was moved to their current position by a suggestion, make sure that they can stay for
//this turn, and that the target for their current position will be drawn.
if(currentPlayer.getCanStay() || targets.size() == 0) {
targets.add(currentPlayer.getPosition());
currentPlayer.setCanStay(false);
}
//Draw the targets for the player to move to
repaint();
}
}
/**
* A method used to draw the game board and the objects moving along it as the game plays
* @param g - The graphics object to draw on.
*/
public void paintComponent(Graphics g) {
//Call the superclass
super.paintComponent(g);
//Calculate the tile sizes
int tileWidth = getWidth() / gameBoard[0].length;
int tileHeight = getHeight() / gameBoard.length;
//Draw the board
for(int i = 0; i < 23; i++) {
for(int j = 0; j < 26; j++) {
int xOffset = tileWidth * j;
int yOffset = tileHeight * i;
gameBoard[i][j].draw(tileWidth, tileHeight, xOffset, yOffset, g);
}
}
//Draw the room labels
for(Map.Entry<Character, Room> entry : roomMap.entrySet()) {
entry.getValue().draw(tileWidth, tileHeight, g);
}
//Only draw the targets if the player is a human.
if(currentPlayer instanceof HumanPlayer) {
for(BoardCell target : targets) {
g.setColor(Color.white);
g.fillRect(target.getCol() * tileWidth, target.getRow() * tileHeight, tileWidth, tileHeight);
g.setColor(Color.blue);
g.drawRect(target.getCol() * tileWidth, target.getRow() * tileHeight, tileWidth, tileHeight);
}
}
//Draw the players
for(Player player : players) {
player.draw(tileWidth, tileHeight, g);
}
}
/**
* Abstract Methods to handle all types of Mouse Events, since the board implements MouseListener. Most of these will
* remain empty, as we don't want to perform any actions during them.
*/
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
//When the mouse is pressed, make sure it's the player's turn.
if(currentPlayer instanceof HumanPlayer) {
//Search for every cell in targets and see if the click landed inside of it.
BoardCell newTarget = null;
for(BoardCell cell : targets) {
if(cell.containsClick(e.getX(), e.getY())) {
newTarget = cell;
break;
}
}
//If no target was clicked, display an error.
if(newTarget == null) {
JOptionPane.showMessageDialog(frame,
"Error: Please select a valid target.",
"Invalid Target",
JOptionPane.ERROR_MESSAGE);
}
//If a target was clicked, move the player to it and allow them to end their turn.
else {
//Move the player
((HumanPlayer) currentPlayer).setNewTarget(newTarget);
currentPlayer.move();
//Repaint so that the player moves
repaint();
//If the new target is a room, prompt the player to make a suggestion
if(newTarget.isRoomCenter()) {
//Get the room card.
String roomName = getRoom(newTarget).getName();
Card roomCard = new Card(roomName, CardType.ROOM);
//Create the dialog box.
SuggestDialog dialog = new SuggestDialog(frame, roomCard);
dialog.setVisible(true);
}
//Set currentPlayer to null to prevent re-drawing targets.
currentPlayer = null;
//Repaint the board and end the turn
repaint();
turnComplete = true;
}
}
//If not, display an error.
else {
JOptionPane.showMessageDialog(frame,
"Error: You may not select a new position while it is not your turn.",
"Wait your Turn",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Forces the Control Panel and Card Panel GUI components to update. Called after a player creates a suggestion, as the event for a
* player to submit the suggestion happens after the next button is pressed, where the GUI typically updates.
* @param newSeen - The card that was shown to the HumanPlayer to disprove their suggestion. It must be added here.
*/
public void ShowHumanPlayerSuggestion(Card newSeen) {
controlPanel.displayGuess(currentSuggestion, humanPlayer);
controlPanel.displayGuessResult(currentStatus, currentDisprover);
if(currentDisprover != null) {
cardPanel.addSeenCardGUI(newSeen, currentDisprover.getColor());
}
}
/**
* Returns the instance of the board, saved in boardInstance. This is the easiest way for us to access the singleton instance of the game board.
* @return - The static, single Board object instance.
*/
public static Board getInstance() {
return boardInstance;
}
/**
* Returns a set of board cells representing the possible places a player could move to after using calcTargets() given a certain starting point and roll length.
* @return - A set of board cells the player can move to.
*/
public Set<BoardCell> getTargets(){
return targets;
}
/**
* Grabs a cell from the gameBoard at row, col, and returns it.
* @param row - The row position of the desired cell
* @param col - The column position of the desired cell.
* @return - A board cell that occupies the desired location.
*/
public BoardCell getCell(int row, int col) {
return gameBoard[row][col];
}
/**
* Returns the number of rows in the board, or it's height.
* @return - An int representing the height of the board.
*/
public static int getNumRows() {
return boardHeight;
}
/**
* Returns the number of columns in the board, or it's width.
* @return - An int representing the width of the board.
*/
public static int getNumColumns() {
return boardWidth;
}
/**
* Returns the room with the initial passed in.
* @param Key - The char initial of the desired room
* @return - The room identified by the character provided, null if not found.
*/
public Room getRoom(char Key) {
return roomMap.get(Key);
}
/**
* returns the room that the cell passed in is a part of, including unused and walkway.
* @param cell - A board cell
* @return - The room the board cell occupies, including "Walkway" and "Unused", as both are specified in roomMap.
*/
public Room getRoom(BoardCell cell) {
return roomMap.get(cell.getInitial());
}
/**
* Returns the adjacency list of the tile at the position provided.
* @param row - The row position of the desired cell
* @param col - The column position of the desired cell
* @return - The adjacency list of the tile at (row, col)
*/
public Set<BoardCell> getAdjList(int row, int col){
return gameBoard[row][col].getAdjList();
}
/**
* Returns the list of players in the game.
* @return
*/
public ArrayList<Player> getPlayers(){
return players;
}
/**
* Returns the solution to the game.
* @return
*/
public Set<Card> getSolution(){
return solution;
}
/**
* Set the solution to the game, for testing purposes.
* @param soln - The desired solution to the game as a set
*/
public void setSolution(Set<Card> soln) {
solution = new HashSet<Card>(soln);
}
/**
* Method to get the game's card deck from the board.
* @return - An arraylist representing the deck of cards in play.
*/
public ArrayList<Card> getDeck(){
return deck;
}
/**
* Method to return if the current turn is complete.
* @return - Boolean, true if turn is complete, false if not.
*/
public boolean getTurnComplete() {
return turnComplete;
}
/**
* Method to return the current roll for the current target set.
* @return - Int representing the roll of a die.
*/
public int getCurrentRoll() {
return currentRoll;
}
/**
* Method to get the current turn's player.
* @return - The player who's turn it is.
*/
public Player getCurrentPlayer() {
return currentPlayer;
}
/**
* Method to get the human player.
* @return - The human player.
*/
public Player getHumanPlayer() {
return humanPlayer;
}
/**
* Method to set the current suggestion formatted as a string
* @param suggestion - The suggestion to display on the GUI.
*/
public void setCurrentSuggestion(String suggestion) {
currentSuggestion = suggestion;
}
/**
* Method to get the current suggestion formatted as a string
* @return - A string representing the current suggestion.
*/
public String getCurrentSuggestion() {
return currentSuggestion;
}
/**
* Method to set the status of the current suggestion formatted as a string
* @param status - A string representing the status of the current suggestion.
*/
public void setCurrentStatus(String status) {
currentStatus = status;
}
/**
* Method to get the status of the current suggestion formatted as a string
* @return - A string representing the status of the current suggestion.
*/
public String getCurrentStatus() {
return currentStatus;
}
/**
* Method to get the current disprover of the current suggestion
* @return - The player that disproved the current suggestion.
*/
public Player getCurrentDisprover() {
return currentDisprover;
}
/**
* A method to set the JFrame/Clue game object for the board, used for drawing popups and dialogues.
* @param cluegame - The ClueGame object JFrame that the game is being drawn on.
*/
public void setFrame(ClueGame cluegame) {
frame = cluegame;
}
/**
* A method to set the game's GameCardPanel, for use in updating the GUI as the game plays.
* @param panel - The game's card panel.
*/
public void setCardPanel(GameCardPanel panel) {
cardPanel = panel;
}
public void setControlPanel(GameControlPanel panel) {
controlPanel = panel;
}
}
| true
|
a54ac1afc9b0c83f28f398c7021af1d5cbdaa187
|
Java
|
dubanghui888888/ccm-b2b2c-service
|
/ccm-b2b2c-service/mb-bg-ext-core/src/main/java/com/mb/ext/core/entity/product/ProductGroupEntity.java
|
UTF-8
| 1,868
| 2.015625
| 2
|
[] |
no_license
|
package com.mb.ext.core.entity.product;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.mb.ext.core.entity.GroupEntity;
import com.mb.ext.core.entity.merchant.MerchantEntity;
import com.mb.framework.entity.AbstractBaseEntity;
/**
* The persistent class for the product_group database table.
*
*/
@Entity
@Table(name = "product_group")
@NamedQuery(name = "ProductGroupEntity.findAll", query = "SELECT u FROM ProductGroupEntity u")
public class ProductGroupEntity extends AbstractBaseEntity
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "PRODUCTGROUP_UUID")
@GenericGenerator(name = "PRODUCTGROUP_UUID", strategy = "uuid")
@Column(name = "PRODUCTGROUP_UUID", nullable = false, length = 36)
private String productGroupUuid;
public String getProductGroupUuid() {
return productGroupUuid;
}
public void setProductGroupUuid(String productGroupUuid) {
this.productGroupUuid = productGroupUuid;
}
public ProductEntity getProductEntity() {
return productEntity;
}
public void setProductEntity(ProductEntity productEntity) {
this.productEntity = productEntity;
}
public GroupEntity getGroupEntity() {
return groupEntity;
}
public void setGroupEntity(GroupEntity groupEntity) {
this.groupEntity = groupEntity;
}
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PRODUCT_UUID")
private ProductEntity productEntity;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "GROUP_UUID")
private GroupEntity groupEntity;
}
| true
|
3a90209fb4dc107252920ecca051378daf2fd477
|
Java
|
CKIA/orm
|
/orm-mybatis/src/main/java/com/ckia/test/service/impl/TestService.java
|
UTF-8
| 670
| 2.234375
| 2
|
[] |
no_license
|
package com.ckia.test.service.impl;
import com.ckia.test.annotation.dataBase.DataBase;
import com.ckia.test.annotation.stringValideation.StringValidation;
import org.springframework.stereotype.Component;
/**
* @author ckia
* @description: 自测试自定义注解配置
* @title: ckia学习累积使用
* @projectName orm
* @date 19-6-9上午5:34
*/
@Component
public class TestService {
@StringValidation("qqqqqqqqqq")
//默认(第一)数据源
// @DataBase("db1")
public void dbTest(){
System.out.println("dbT1");
}
//第二数据源
// @DataBase("db2")
public void dbTest2(){
System.out.println("dbT2");
}
}
| true
|
e44f09fd010bd9be73abac3b85c8dc937e6ffdd3
|
Java
|
ITWater/HeiKeOnline
|
/src/top/aiteyou/entity/griefstore/Letter.java
|
UTF-8
| 1,592
| 1.992188
| 2
|
[] |
no_license
|
package top.aiteyou.entity.griefstore;
import java.io.Serializable;
import java.sql.Timestamp;
import top.aiteyou.entity.User;
/**
* 解忧杂货店-信
*@author :tb
*@version 2018年5月3日 上午10:18:46
*/
public class Letter implements Serializable{
private static final long serialVersionUID = 2144202143975229547L;
private Integer id;
private Integer fromUserId;
private Integer toUserId;
private Integer replyLetterId;
private String text;
private Timestamp time;
private String imageUrl;//信封图片地址
//绑定类
private User author;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getFromUserId() {
return fromUserId;
}
public void setFromUserId(Integer fromUserId) {
this.fromUserId = fromUserId;
}
public Integer getToUserId() {
return toUserId;
}
public void setToUserId(Integer toUserId) {
this.toUserId = toUserId;
}
public Integer getReplyLetterId() {
return replyLetterId;
}
public void setReplyLetterId(Integer replyLetterId) {
this.replyLetterId = replyLetterId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
}
| true
|
2f3a449703312359b73de7ca81e7b9c76fced261
|
Java
|
olealgoritme/smittestopp_src
|
/v1.1.2/decompiled/c/a/a/a.java
|
UTF-8
| 3,098
| 1.742188
| 2
|
[] |
no_license
|
package c.a.a;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public abstract interface a
extends IInterface
{
public static abstract class a
extends Binder
implements a
{
public a()
{
attachInterface(this, "android.support.customtabs.ICustomTabsCallback");
}
public IBinder asBinder()
{
return this;
}
public boolean onTransact(int paramInt1, Parcel paramParcel1, Parcel paramParcel2, int paramInt2)
{
if (paramInt1 != 2)
{
if (paramInt1 != 3)
{
if (paramInt1 != 4)
{
if (paramInt1 != 5)
{
if (paramInt1 != 6)
{
if (paramInt1 != 1598968902) {
return super.onTransact(paramInt1, paramParcel1, paramParcel2, paramInt2);
}
paramParcel2.writeString("android.support.customtabs.ICustomTabsCallback");
return true;
}
paramParcel1.enforceInterface("android.support.customtabs.ICustomTabsCallback");
paramParcel1.readInt();
if (paramParcel1.readInt() != 0) {
Uri localUri = (Uri)Uri.CREATOR.createFromParcel(paramParcel1);
}
paramParcel1.readInt();
if (paramParcel1.readInt() != 0) {
paramParcel1 = (Bundle)Bundle.CREATOR.createFromParcel(paramParcel1);
}
paramParcel2.writeNoException();
return true;
}
paramParcel1.enforceInterface("android.support.customtabs.ICustomTabsCallback");
paramParcel1.readString();
if (paramParcel1.readInt() != 0) {
paramParcel1 = (Bundle)Bundle.CREATOR.createFromParcel(paramParcel1);
}
paramParcel2.writeNoException();
return true;
}
paramParcel1.enforceInterface("android.support.customtabs.ICustomTabsCallback");
if (paramParcel1.readInt() != 0) {
paramParcel1 = (Bundle)Bundle.CREATOR.createFromParcel(paramParcel1);
}
paramParcel2.writeNoException();
return true;
}
paramParcel1.enforceInterface("android.support.customtabs.ICustomTabsCallback");
paramParcel1.readString();
if (paramParcel1.readInt() != 0) {
paramParcel1 = (Bundle)Bundle.CREATOR.createFromParcel(paramParcel1);
}
paramParcel2.writeNoException();
return true;
}
paramParcel1.enforceInterface("android.support.customtabs.ICustomTabsCallback");
paramParcel1.readInt();
if (paramParcel1.readInt() != 0) {
paramParcel1 = (Bundle)Bundle.CREATOR.createFromParcel(paramParcel1);
}
paramParcel2.writeNoException();
return true;
}
}
}
/* Location:
* Qualified Name: c.a.a.a
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true
|
7331efad78a43884d78c4a1ccad6546182746bb9
|
Java
|
Dreamwei-cn/cn.cloud
|
/cn.cloud.shop-api/cn.cloud.goods-api/src/main/java/cn/cloud/goods_api/util/BaseModel.java
|
UTF-8
| 377
| 1.898438
| 2
|
[] |
no_license
|
package cn.cloud.goods_api.util;
import java.io.Serializable;
import javax.persistence.Id;
/**
* @author Dream
* 类
*/
public class BaseModel implements Serializable ,Cloneable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
protected Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| true
|
de68493363b1e0d69296cb249003658061bc0e01
|
Java
|
ocarbonie/AnimalClass
|
/src/com/company/Dog.java
|
UTF-8
| 428
| 3.515625
| 4
|
[] |
no_license
|
package com.company;
/*
*All mice are Animals but all Animals are not mice
*/
public class Dog extends Animal {
public Dog(){
super();
System.out.println("Now I am a dog");
}
@Override
public String eat() {
return "A dog eats...";
}
@Override
public String sleep(){
return "A dog sleep...";
}
public String bark(){
return" A dog barks...";
}
}
| true
|
263c8f72456f559ed00dd0d69e488c2e304503b2
|
Java
|
nikitagalayda/SDRefactorProject
|
/src/com/system/measurement/Units/Yard.java
|
UTF-8
| 374
| 2.40625
| 2
|
[] |
no_license
|
package com.system.measurement.Units;
import java.math.BigDecimal;
import java.util.HashMap;
import com.system.measurement.Unit;
public class Yard extends Unit {
public Yard() {
conversionMap = new HashMap<String, String>();
conversionMap.put("cm", "91.44");
conversionMap.put("in", "36");
conversionMap.put("ft", "3");
conversionMap.put("m", "0.9144");
}
}
| true
|
117d39501b084a81e3f6bab28a2f5604b16fc13a
|
Java
|
loveprotocol/jdg_android-0.0.1
|
/app/src/main/java/com/imhc2/plumboard/mvvm/view/activity/mypage/StampActivity.java
|
UTF-8
| 6,837
| 2.078125
| 2
|
[] |
no_license
|
package com.imhc2.plumboard.mvvm.view.activity.mypage;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.imhc2.plumboard.R;
import com.imhc2.plumboard.commons.querys.FirestoreQuerys;
import com.imhc2.plumboard.mvvm.model.domain.Cnstv;
import com.imhc2.plumboard.mvvm.model.domain.CnstvUser;
import com.xw.repo.BubbleSeekBar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import butterknife.BindView;
import butterknife.ButterKnife;
import timber.log.Timber;
public class StampActivity extends AppCompatActivity {
@BindView(R.id.activity_stamp_toolbar) Toolbar mToolbar;
@BindView(R.id.activity_stamp_stateBtn) Button stateBtn;
@BindView(R.id.activity_stamp_state_tv) TextView stateTv;
@BindView(R.id.activity_stamp_seekbar) BubbleSeekBar seekbar;
@BindView(R.id.activity_stamp_sub_tv1) TextView subTv1;
@BindView(R.id.activity_stamp_sub_tv2) TextView subTv2;
@BindView(R.id.activity_stamp_sub_tv3) TextView subTv3;
@BindView(R.id.activity_stamp_dayTv) TextView dayTv;
FirebaseFirestore firestore;
FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stamp);
ButterKnife.bind(this);
firestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
initToolbar();
getEvnt();
String text1 = getString(R.string.StampActivity_sub1);
subTv1.setText(Html.fromHtml(text1));
String text2 = getString(R.string.StampActivity_sub2);
subTv2.setText(Html.fromHtml(text2));
String text3 = getString(R.string.StampActivity_sub3);
subTv3.setText(Html.fromHtml(text3));
}
private void getEvnt() {
FirestoreQuerys.INSTANCE.getEventUserCnstv(firestore, mAuth.getCurrentUser().getUid())
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
CnstvUser cnstvUser = task.getResult().toObject(CnstvUser.class);
FirestoreQuerys.INSTANCE.getEventCnstv(firestore)
.get()
.addOnCompleteListener(task1 -> {
if (task1.isSuccessful()) {
Cnstv cnstv = task1.getResult().toObject(Cnstv.class);
getStampState(cnstvUser,cnstv);
}
});
}
});
}
private void initToolbar() {
mToolbar.setTitle(R.string.StampActivity_toolbarTitle);
mToolbar.setTitleTextColor(getResources().getColor(R.color.colorPlumBoardSub));
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void getStampState(CnstvUser cnstvUser,Cnstv cnstv) {
seekbar.setEnabled(false);
seekbar.setProgress(cnstvUser.getPrgs().size());
Timber.e("seekbar size = " + cnstvUser.getPrgs().size());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1); //어제 구하기(오늘 날짜에서 하루를 뺌.)
String date = sdf.format(calendar.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DATE, 0); //오늘
String date2 = sdf.format(calendar2.getTime());
Timber.e("cnstvUser.getPrgs() = " + cnstvUser.getPrgs());
Timber.e("yesterday = " + date);
Timber.e("today = " + date2);
Timber.e("cnstvUser.getPrgs().size() = " + cnstvUser.getPrgs().size());
Timber.e("cnstvUser.getPrgs().contains(date) = " + cnstvUser.getPrgs().contains(date));
Timber.e("cnstvUser.getPrgs().contains(date2) = " + cnstvUser.getPrgs().contains(date2));
if (cnstvUser.getPrgs().size() == 0 || cnstvUser.getPrgs().contains(date) || cnstvUser.getPrgs().contains(date2)) {
seekbar.setBubbleColor(Color.parseColor("#30FCAD"));
seekbar.setSecondTrackColor(Color.parseColor("#30FCAD"));
seekbar.setThumbColor(Color.parseColor("#30FCAD"));
switch (cnstvUser.getPrgs().size()) {
case 1:
Timber.e("dayTv = 1 이다");
dayTv.setText("1일차 진행 중");
break;
case 2:
Timber.e("dayTv = 2 이다");
dayTv.setText("2일차 진행 중");
break;
case 3:
Timber.e("dayTv = 3 이다");
dayTv.setText("3일차 완료");
break;
default:
Timber.e("else 이다");
break;
}
} else {
if (cnstvUser.getPrgs().size() > 1 && !cnstvUser.getPrgs().contains(date) || !cnstvUser.getPrgs().contains(date2)) {
dayTv.setText("다음 캠페인 완료 시 초기화 됩니다");
seekbar.setBubbleColor(Color.parseColor("#9E9E9E"));
seekbar.setSecondTrackColor(Color.parseColor("#9E9E9E"));
seekbar.setThumbColor(Color.parseColor("#9E9E9E"));
}
}
Long stamp = Long.parseLong(cnstvUser.getEvntCt().toString());
Double done = Double.parseDouble(cnstv.getRatePerCt().toString()) * stamp;
stateBtn.setText(Math.round(done * 100) + "%");
Double sRate = Double.parseDouble(cnstv.getMRate().toString());
stateTv.setText("(" + cnstvUser.getPrgs().size() + "/" + "3" + ")");
if (done < sRate) {
stateBtn.setBackgroundColor(getResources().getColor(R.color.colorPointStateError));
} else if (done.equals(sRate)) {
stateBtn.setBackgroundColor(getResources().getColor(R.color.colorPlumBoard));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
| true
|
5871b757104d26a7a99cfe0102a43b763cf5e7a6
|
Java
|
sangho210/JAVA_Practice
|
/work/demo/src/com/day10/Test11.java
|
UTF-8
| 648
| 3.234375
| 3
|
[] |
no_license
|
package com.day10;
class Outer3 {
static int a=10;
int b=20;
public static class Inner {
int c=30;
public void write() {
System.out.println(a);
// System.out.println(b);
System.out.println(c);
Outer3 o = new Outer3();
System.out.println(o.b);
}
}
public void print() {
Inner ob = new Inner();
ob.write();
}
}
public class Test11 {
public static void main(String[] args) {
Outer3 out = new Outer3();
out.print();
Outer3.Inner inner = new Outer3.Inner();
inner.write();
}
}
| true
|
1ae4a7a4206346460806ef399a96e8bdcc98ff1d
|
Java
|
kanadara13/biz-office
|
/src/main/java/com/biz/office/service/material/MaterialManager.java
|
UTF-8
| 531
| 2.203125
| 2
|
[] |
no_license
|
package com.biz.office.service.material;
import com.biz.office.domain.material.Material;
import com.biz.office.repository.material.MaterialRepository;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
@Component
public class MaterialManager {
private MaterialRepository repository;
@Inject
public MaterialManager(MaterialRepository repository) {
this.repository = repository;
}
public Material save(Material material) {
return repository.save(material);
}
}
| true
|
3df0bcaae06bacda83046c1b05d217e9e847e209
|
Java
|
bluemixmg/upy-hibernate
|
/com/inverse/ing/AreadepericiaId.java
|
UTF-8
| 2,386
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.inverse.ing;
// Generated 09/05/2017 03:21:15 PM by Hibernate Tools 4.0.1.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* AreadepericiaId generated by hbm2java
*/
@Embeddable
public class AreadepericiaId implements java.io.Serializable {
private String descripcion;
private Character estatus;
private int codigoarea;
public AreadepericiaId() {
}
public AreadepericiaId(int codigoarea) {
this.codigoarea = codigoarea;
}
public AreadepericiaId(String descripcion, Character estatus, int codigoarea) {
this.descripcion = descripcion;
this.estatus = estatus;
this.codigoarea = codigoarea;
}
@Column(name="descripcion")
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
@Column(name="estatus", length=1)
public Character getEstatus() {
return this.estatus;
}
public void setEstatus(Character estatus) {
this.estatus = estatus;
}
@Column(name="codigoarea", nullable=false)
public int getCodigoarea() {
return this.codigoarea;
}
public void setCodigoarea(int codigoarea) {
this.codigoarea = codigoarea;
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof AreadepericiaId) ) return false;
AreadepericiaId castOther = ( AreadepericiaId ) other;
return ( (this.getDescripcion()==castOther.getDescripcion()) || ( this.getDescripcion()!=null && castOther.getDescripcion()!=null && this.getDescripcion().equals(castOther.getDescripcion()) ) )
&& ( (this.getEstatus()==castOther.getEstatus()) || ( this.getEstatus()!=null && castOther.getEstatus()!=null && this.getEstatus().equals(castOther.getEstatus()) ) )
&& (this.getCodigoarea()==castOther.getCodigoarea());
}
public int hashCode() {
int result = 17;
result = 37 * result + ( getDescripcion() == null ? 0 : this.getDescripcion().hashCode() );
result = 37 * result + ( getEstatus() == null ? 0 : this.getEstatus().hashCode() );
result = 37 * result + this.getCodigoarea();
return result;
}
}
| true
|
c3be95652c3da4c2bf1a62d20ef6ea5a3b624784
|
Java
|
weizhangming/Project
|
/mianshi/src/com/boco/demo01/PaiLie.java
|
UTF-8
| 895
| 3.125
| 3
|
[] |
no_license
|
package com.boco.demo01;
import java.util.ArrayList;
import java.util.List;
public class PaiLie {
private static String str="12";
public static void main(String[] args) {
List<String> list=new ArrayList<String>();
if(str!=null&&str.length()>0){
help(0,str.toCharArray(),list);
}
System.out.println(list.toString());
}
private static void help(int i, char[] charArray, List<String> list) {
// TODO Auto-generated method stub
if(i==charArray.length){
String val=String.valueOf(charArray);
if(!list.contains(val)){
list.add(val);
}
}else{
for(int j=i;j<charArray.length;j++){
swap(i,j,charArray);
help(i+1,charArray,list);
swap(i,j,charArray);
}
}
}
private static void swap(int i, int j, char[] charArray) {
char temp=charArray[i];
charArray[i]=charArray[j];
charArray[j]=temp;
}
}
| true
|
0c917d6f84b6e77c720933924fc14952acbaf93f
|
Java
|
yao-cz/SpringMVc
|
/src/main/java/ydp/day01/Test/Test2.java
|
UTF-8
| 5,652
| 2.71875
| 3
|
[] |
no_license
|
package ydp.day01.Test;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
public class Test2 {
public static void main(String[] args) throws IOException {
//建立通信,三次握手
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(80));
//是否为阻塞,这里设置为非堵塞
serverSocketChannel.configureBlocking(false);
//创建存放socket的容器
Selector selector = Selector.open();
//注册身份,这里是selector自身,所以是SelectionKey.OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// System.out.println("Http Server Started.");
while (true) {
if (selector.select(3000) == 0) {
continue;
}
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
httpHandle(key);
keyIterator.remove();
}
}
}
private static void httpHandle(SelectionKey key) throws IOException {
if (key.isAcceptable()) {
acceptHandle(key);
} else if (key.isReadable()) {
requestHandle(key);
}
}
private static void acceptHandle(SelectionKey key) throws IOException {
SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
socketChannel.configureBlocking(false);
socketChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
private static void requestHandle(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
byteBuffer.clear();
if (socketChannel.read(byteBuffer) == -1) {
socketChannel.close();
return;
}
byteBuffer.flip();
String requestMsg = new String(byteBuffer.array());
String url = requestMsg.split("\r\n")[0].split(" ")[1];
System.out.println(requestMsg);
System.out.println("Request: " + url);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("HTTP/1.1 200 OK\r\n");
stringBuilder.append("Content-Type:text/html;charset=utf-8\r\n");
stringBuilder.append("\r\n");
stringBuilder.append("<html><head><title>HttpTest</title></head><body>");
String res = myres(url);
stringBuilder.append(res);
// String content = HttpServer.contentMap.get(url);
// stringBuilder.append(content != null ? content : "404");
stringBuilder.append("</body></html>");
socketChannel.write(ByteBuffer.wrap(stringBuilder.toString().getBytes()));
socketChannel.close();
}
private static String myres(String url) {
if (url.contains(".ico"))
return "";
String[] split = url.split("\\?");
String s = "404";
try {
Class<?> aClass = Class.forName("ydp.day01.Test.UserController");
Method[] methods = aClass.getDeclaredMethods();
UserController userController = (UserController) aClass.getDeclaredConstructor().newInstance();
for (Method method : methods) {
//判断是否是注解
if (method.isAnnotationPresent(MyRequestMapping.class)) {
//判断url是否指向该方法
if (split[0].replace("/", "").equals(method.getName())) {
if (split.length > 1) {
String[] paras = split[1].split("&");
HashMap<String, String> map = new HashMap<>();
for (String para : paras) {
String[] split1 = para.split("=");
map.put(split1[0], split1[1]);
}
//判断类型
Parameter[] parameters = method.getParameters();
Object[] parameters2 = new Object[parameters.length];
// System.out.println("1111111111111111111111??"+parameters2.length);
// System.out.println("1111111111111111111111??"+parameters.length);
for (int i = 0; i < parameters.length; i++) {
String type = parameters[i].getType().getSimpleName();
if (type.equals("int")) {
//这里如果不设置idea的-parameter时会空指针异常;
parameters2[i] = Integer.parseInt(map.get(parameters[i].getName()));
}
}
s = (String) method.invoke(userController,parameters2);
} else {
s = (String) method.invoke(userController);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
}
| true
|
e2f4aef800181e505962f86a73ee3126fd16892c
|
Java
|
xumusen/hexing
|
/CanDao/src/com/utils/DBUtil.java
|
UTF-8
| 5,954
| 2.65625
| 3
|
[] |
no_license
|
package com.utils;
import java.sql.*;
import java.util.ResourceBundle;
import com.ddl.CancelOrder;
import com.ddl.Test;
import com.ddl.Test2;
import com.ddl.Testpay;
import com.ddl.Testxc;
import net.sf.json.JSONObject;
public class DBUtil {
// 这里可以设置数据库名称
/*
* private final static String URL =
* "jdbc:sqlserver://www.baofengrose.com:2433;DatabaseName=hexing"; private
* static final String USER="sa"; private static final String
* PASSWORD="Xuc2008@126.com";
*/
static ResourceBundle resource = ResourceBundle.getBundle("web");
private final static String URL = resource.getString("URL");
private static final String USER = resource.getString("USER");
private static final String PASSWORD = resource.getString("PASSWORD");
private static Connection conn = null;
// 静态代码块(将加载驱动、连接数据库放入静态块中)
static {
try {
// 1.加载驱动程序
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 2.获得数据库的连接
conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 对外提供一个方法来获取数据库连接
public static Connection getConnection() {
return conn;
}
// 测试用例
public static void main(String[] args) throws Exception {
// 3.通过数据库的连接操作数据库,实现增删改查
Statement stmt = conn.createStatement();
// ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句 ,返回一个结果集(ResultSet)对象。
// ResultSet rs = stmt.executeQuery("SELECT * from orderCancelCollect ");
// ResultSet rs = stmt.executeQuery("SELECT * from orderCollect ");
ResultSet rs = stmt.executeQuery(" SELECT * FROM temporder AS t");
// ResultSet rs = stmt.executeQuery("SELECT x.ods_order_postdineinorder_orderid
// ,x.ods_order_postdineinorder_products,x.ods_order_postdineinorder_storeid,x.ods_order_postdineinorder_ordertime,x.ods_order_postdineinorder_paymentdetails,
// x.ods_order_postdineinorder_orderdate FROM xiaochengxu AS x");
/*
* while(rs.next()){//如果对象中有数据,就会循环打印出来 String
* ods_order_postdineinorder_orderid=rs.getString(
* "ods_order_postdineinorder_orderid");
* System.out.println(ods_order_postdineinorder_orderid); String
* ods_order_postdineinorder_products=rs.getString(
* "ods_order_postdineinorder_products");
* System.out.println(ods_order_postdineinorder_products); String
* ods_order_postdineinorder_storeid=rs.getString(
* "ods_order_postdineinorder_storeid");
* System.out.println(ods_order_postdineinorder_storeid);
* //Testxc.postDineorder(ods_order_postdineinorder_orderid,
* ods_order_postdineinorder_storeid, ods_order_postdineinorder_products);
*
*
* String ods_order_postdineinorder_ordertime=rs.getString(
* "ods_order_postdineinorder_ordertime");
* System.out.println(ods_order_postdineinorder_ordertime); String
* ods_order_postdineinorder_paymentdetails=rs.getString(
* "ods_order_postdineinorder_paymentdetails");
* System.out.println(ods_order_postdineinorder_paymentdetails); String
* ods_order_postdineinorder_orderdate=rs.getString(
* "ods_order_postdineinorder_orderdate");
* System.out.println(ods_order_postdineinorder_orderdate);
* Testpay.postDineorder(ods_order_postdineinorder_orderid,
* ods_order_postdineinorder_storeid,ods_order_postdineinorder_paymentdetails,
* ods_order_postdineinorder_orderdate,ods_order_postdineinorder_ordertime);
*
*
*
*
* // JSONObject jsonobj = JSONObject.fromObject(cell);// 将字符串转化成json对象
* //JSONObject jsonobject = JSONObject.fromObject(jsonobj.getString("data"));//
* 将字符串转化成json对象 //String actionName=jsonobj.getString("actionName");
*
* if(actionName.equals("candao.order.postDineInOrder")){
* Test.postDineorder(cell); }else if(actionName.equals("candao.retail.order")){
* Test2.retailOrder(cell); }else
* if(actionName.equals("candao.order.postDineInStatus")){
* CancelOrder.CancelOrder(cell); }else
* if(actionName.equals("candao.retail.updateOrderStatus")){
* System.out.println("更新新零售订单状态啦啦啦啦啦"); }
*
* }
*/
while (rs.next()) {
// System.out.println(rs.getString("req"));
// Test.postDineorder(rs.getString("req"));
String cell = rs.getString("json");
System.out.println(cell);
/*
* String
* cancelorder="{\"accessKey\":\"782b5654d5f7a26e\",\"actionName\":\"candao.order.postDineInStatus\",\"timestamp\":1578580506485,\"ticket\":\"4863d892-dfc8-41ff-915b-50fd2b9ba582\",\"sign\":\"c7ea8bc8e2ab6c7beb9f58c8c2e28f82\",\"serviceType\":\"pos\",\"vendor\":\"seito\",\"storeId\":\"Y0074\",\"data\":{\"orderId\":\"202001090066843\",\"status\":-1,\"cancelReason\":501,\"updateTime\":\"2020-01-09 11:32:58\"}}"
* ; String seitoorder=""; String ncrorder=""; String yitunnelorder=""; String
* jian24order="";
*/
JSONObject jsonobj = JSONObject.fromObject(cell);// 将字符串转化成json对象
// JSONObject jsonobject = JSONObject.fromObject(jsonobj.getString("data"));//
// 将字符串转化成json对象
String actionName = jsonobj.getString("actionName");
if (actionName.equals("candao.order.postDineInOrder")) {
Test.postDineorder(cell);
} else if (actionName.equals("candao.retail.order")) {
Test2.retailOrder(cell);
} else if (actionName.equals("candao.order.postDineInStatus")) {
CancelOrder.CancelOrder(cell);
} else if (actionName.equals("candao.retail.updateOrderStatus")) {
System.out.println("更新新零售订单状态啦啦啦啦啦");
}
}
}
}
| true
|
d1612e74f4870f7b91c8ec06acc94812ca3272b4
|
Java
|
daohuyenptit/Example
|
/NoteApp/app/src/main/java/com/example/dell/noteapp/EditNoteActivity.java
|
UTF-8
| 10,333
| 1.640625
| 2
|
[] |
no_license
|
package com.example.dell.noteapp;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class EditNoteActivity extends AppCompatActivity implements View.OnClickListener, com.bumptech.glide.module.GlideModule {
NoteController controller;
ImageView imgSelect, imgdelete;
ImageView imgcamera, imggallery;
EditText edtDate, edtTime, edtContent;
Note note;
int REQUEST_CODE = 20;
int REQUEST_CODE_GALLERY = 21;
DrawerLayout drawerLayout;
Toolbar toolbar;
TextView txtlock;
String newpath, oldpath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
addControl();
ActionBar();
checkPermission();
getNote();
datePicker();
timePicker();
imgdelete.setOnClickListener(this);
imgSelect.setOnClickListener(this);
controller = new NoteController(EditNoteActivity.this);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void getNote() {
Intent i = getIntent();
note = (Note) i.getSerializableExtra("note");
oldpath = note.getImage();
Glide.with(this).load(oldpath).into(imgSelect);
Date date = note.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String ngay = df.format(date);
edtDate.setText(ngay.substring(0, 10));
edtTime.setText(ngay.substring(11));
edtContent.setText(note.getContent());
}
public void addControl() {
edtContent = findViewById(R.id.edtContent);
edtTime = findViewById(R.id.edtTime);
edtDate = findViewById(R.id.edtDate);
imgSelect = findViewById(R.id.imgSelect);
imgdelete = findViewById(R.id.imageDelete);
toolbar = findViewById(R.id.toobar);
drawerLayout = findViewById(R.id.drawer);
imgcamera = findViewById(R.id.imgcamera);
imggallery = findViewById(R.id.imggallery);
imggallery.setOnClickListener(this);
imgcamera.setOnClickListener(this);
}
public void ActionBar() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void getimgCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE);
}
public void getimgGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgSelect.setImageBitmap(bitmap);
}
if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imgSelect.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1001);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1001) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
checkPermission();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.mnuAdd:
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String date = edtDate.getText().toString().trim() + " " + edtTime.getText().toString().trim();
Date time = df.parse(date);
BitmapDrawable bitmapDrawable = (BitmapDrawable) imgSelect.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
newpath = Utils.saveToInternalStorage(bitmap, System.currentTimeMillis() + "", EditNoteActivity.this);
Note noteedit = new Note(newpath, edtContent.getText().toString(), time);
noteedit.setId(note.getId());
controller.editNote(noteedit);
Intent intent = new Intent();
setResult(101, intent);
finish();
} catch (ParseException e) {
e.printStackTrace();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.imgSelect:
AlertDialog.Builder builder = new AlertDialog.Builder(EditNoteActivity.this);
builder.setMessage("What kind of style do you want to select ?");
builder.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getimgCamera();
}
});
builder.setNegativeButton("GALLERY", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getimgGallery();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
break;
case R.id.imageDelete:
imgSelect.setImageResource(R.drawable.image_default);
break;
case R.id.imgcamera:
getimgCamera();
break;
case R.id.imggallery:
getimgGallery();
break;
}
}
public void datePicker() {
edtDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(EditNoteActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
edtDate.setText("" + i + "-" + (i1 + 1) + "-" + i2);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
}
public void timePicker() {
edtTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int mi = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(EditNoteActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
edtTime.setText(i + ":" + i1);
}
}, hour, mi, true);
timePickerDialog.show();
}
});
}
@Override
public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
}
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
}
}
| true
|
9516a2c6a8d6317e71a0557e8989c9718e2f246b
|
Java
|
pramod6019/axelaauto
|
/src/axela/service/Service_Target_Update.java
|
UTF-8
| 16,429
| 1.625
| 2
|
[] |
no_license
|
// smitha nag 28, 29 march 2013
package axela.service;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.rowset.CachedRowSet;
import cloudify.connect.Connect;
public class Service_Target_Update extends Connect {
public String msg = "";
public String update = "";
public String updateB = "";
public String comp_id = "0";
// public String branch_id = "0", dr_branch_id = "0";
// public String branch_name = "";
public String year = "";
// public String target_id = "0";
public String service_target_id = "0";
public String StrSql = "";
public String SqlJoin = "";
public String service_target_jc_count = "0", service_target_pms_count = "0";
public String service_target_labour_amount = "0";
public String service_target_parts_amount = "0";
public String service_target_oil_amount = "0";
public String service_target_tyre_amount = "0";
public String service_target_break_count = "0";
public String service_target_break_amount = "0";
public String service_target_battery_amount = "0";
public String service_target_accessories_amount = "0";
public String service_target_vas_amount = "0", service_target_extwarranty_amount = "0";
public String service_target_battery_count = "0", service_target_extwarranty_count = "0", service_target_tyre_count = "0";
public String service_target_wheelalignment_amount = "0", service_target_cng_amount = "0";
public String service_target_startdate = "";
public String service_target_enddate = "";
public Connection conntx = null;
public Statement stmttx = null;
public String StrSearch = "";
public String QueryString = "";
public String month = "", month_name = "";
public String status = "";
public String service_target_entry_id = "";
public String service_target_entry_date = "";
public String service_target_modified_id = "";
public String service_target_modified_date = "";
public String emp_id = "";
public String Service_target_emp_id = "";
public String emp_name = "";
public String entry_by = "", entry_date = "", modified_by = "",
modified_date = "";
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
CheckSession(request, response);
HttpSession session = request.getSession(true);
comp_id = CNumeric(GetSession("comp_id", request));
CheckPerm(comp_id, "service_target_edit", request, response);
if (!comp_id.equals("0")) {
emp_id = CNumeric(GetSession("emp_id", request));
Service_target_emp_id = CNumeric(PadQuotes(request.getParameter("emp_id")));
msg = PadQuotes(request.getParameter("msg"));
emp_name = ExecuteQuery("SELECT emp_name FROM " + compdb(comp_id) + "axela_emp WHERE emp_id=" + Service_target_emp_id + "");
service_target_id = CNumeric(PadQuotes(request.getParameter("service_target_id")));
month = CNumeric(PadQuotes(request.getParameter("month")));
month_name = TextMonth(Integer.parseInt(month) - 1);
month_name = month_name.substring(0, 3);
QueryString = PadQuotes(request.getQueryString());
update = PadQuotes(request.getParameter("update"));
updateB = PadQuotes(request.getParameter("update_button"));
year = CNumeric(PadQuotes(request.getParameter("year")));
if (update.equals("yes")) {
// SOP("yes");
status = "Update";
PopulateFields(response);
}
if (updateB.equals("Update")) {
GetValues(request, response);
service_target_modified_id = CNumeric(GetSession("emp_id", request));
service_target_modified_date = ToLongDate(kknow());
UpdateFields(request);
response.sendRedirect(response.encodeRedirectURL("service-target-list.jsp?dr_executives=" + Service_target_emp_id + "&dr_year=" + year + "&msg=" + "Target Updated Successfully!"));
}
}
} catch (Exception ex) {
SOPError("Axelaauto== " + this.getClass().getName());
SOPError("Error in "
+ new Exception().getStackTrace()[0].getMethodName() + ": "
+ ex);
}
}
private void GetValues(HttpServletRequest request,
HttpServletResponse response) {
service_target_jc_count = CNumeric(PadQuotes(request.getParameter("txt_jc_count")));
service_target_pms_count = CNumeric(PadQuotes(request.getParameter("txt_pms_count")));
service_target_labour_amount = CNumeric(PadQuotes(request.getParameter("txt_labour_amt")));
service_target_parts_amount = CNumeric(PadQuotes(request.getParameter("txt_parts_amt")));
service_target_oil_amount = CNumeric(PadQuotes(request.getParameter("txt_oil_amt")));
service_target_tyre_count = CNumeric(PadQuotes(request.getParameter("txt_tyre_count")));
service_target_tyre_amount = CNumeric(PadQuotes(request.getParameter("txt_tyre_amt")));
service_target_break_count = CNumeric(PadQuotes(request.getParameter("txt_break_count")));
service_target_break_amount = CNumeric(PadQuotes(request.getParameter("txt_break_amt")));
service_target_battery_count = CNumeric(PadQuotes(request.getParameter("txt_battery_count")));
service_target_battery_amount = CNumeric(PadQuotes(request.getParameter("txt_battery_amt")));
service_target_accessories_amount = CNumeric(PadQuotes(request.getParameter("txt_accessories_amt")));
service_target_vas_amount = CNumeric(PadQuotes(request.getParameter("txt_vas_amt")));
service_target_extwarranty_count = CNumeric(PadQuotes(request.getParameter("txt_extwarranty_count")));
service_target_extwarranty_amount = CNumeric(PadQuotes(request.getParameter("txt_extwarranty_amt")));
service_target_wheelalignment_amount = CNumeric(PadQuotes(request.getParameter("txt_wheelalignment_amt")));
service_target_cng_amount = CNumeric(PadQuotes(request.getParameter("txt_cng_amt")));
entry_by = PadQuotes(request.getParameter("entry_by"));
entry_date = PadQuotes(request.getParameter("entry_date"));
modified_by = PadQuotes(request.getParameter("modified_by"));
modified_date = PadQuotes(request.getParameter("modified_date"));
}
private void PopulateFields(HttpServletResponse response) {
if (!service_target_id.equals("0")) {
// SOP("service==" + service_target_id);
StrSql = "SELECT service_target_id, service_target_emp_id,"
+ " COALESCE(service_target_startdate, '') AS service_target_startdate,"
+ " COALESCE(service_target_enddate, '') AS service_target_enddate,"
+ " COALESCE(service_target_jc_count, 0) AS service_target_jc_count,"
+ " COALESCE(service_target_pms_count, 0) AS service_target_pms_count,"
+ " COALESCE(service_target_labour_amount, 0) AS service_target_labour_amount,"
+ " COALESCE(service_target_parts_amount, 0) AS service_target_parts_amount,"
+ " COALESCE(service_target_oil_amount, 0) AS service_target_oil_amount,"
+ " COALESCE(service_target_tyre_count, 0) AS service_target_tyre_count,"
+ " COALESCE(service_target_tyre_amount, 0) AS service_target_tyre_amount,"
+ " COALESCE(service_target_break_count, 0) AS service_target_break_count,"
+ " COALESCE(service_target_break_amount, 0) AS service_target_break_amount,"
+ " COALESCE(service_target_battery_count, 0) AS service_target_battery_count,"
+ " COALESCE(service_target_battery_amount, 0) AS service_target_battery_amount,"
+ " COALESCE(service_target_accessories_amount, 0) AS service_target_accessories_amount,"
+ " COALESCE(service_target_vas_amount, 0) AS service_target_vas_amount,"
+ " COALESCE(service_target_extwarranty_count, 0) AS service_target_extwarranty_count,"
+ " COALESCE(service_target_extwarranty_amount, 0) AS service_target_extwarranty_amount,"
+ " COALESCE(service_target_wheelalign_amount, 0) AS service_target_wheelalign_amount,"
+ " COALESCE(service_target_cng_amount, 0) AS service_target_cng_amount,"
+ " COALESCE(service_target_entry_date, '') AS service_target_entry_date,"
+ " COALESCE(service_target_entry_id, '0') AS service_target_entry_id,"
+ " COALESCE(service_target_modified_date, '') AS service_target_modified_date,"
+ " COALESCE(service_target_modified_id, '0') AS service_target_modified_id";
SqlJoin = " FROM " + compdb(comp_id) + "axela_service_target"
+ " WHERE service_target_emp_id=" + Service_target_emp_id + ""
+ " AND SUBSTR(service_target_startdate, 1, 6) >= " + year + doublenum(Integer.parseInt(month))
+ " AND SUBSTR(service_target_enddate, 1, 6)<=" + year + doublenum(Integer.parseInt(month));
StrSql = StrSql + SqlJoin;
// SOP("StrSql===pop=" + StrSql);
CachedRowSet crs = processQuery(StrSql, 0);
try {
while (crs.next()) {
service_target_id = crs.getString("service_target_id");
service_target_jc_count = crs.getString("service_target_jc_count");
service_target_pms_count = crs.getString("service_target_pms_count");
service_target_labour_amount = crs.getString("service_target_labour_amount");
service_target_parts_amount = crs.getString("service_target_parts_amount");
service_target_oil_amount = crs.getString("service_target_oil_amount");
service_target_tyre_count = crs.getString("service_target_tyre_count");
service_target_tyre_amount = crs.getString("service_target_tyre_amount");
service_target_break_count = crs.getString("service_target_break_count");
service_target_break_amount = crs.getString("service_target_break_amount");
service_target_battery_count = crs.getString("service_target_battery_count");
service_target_battery_amount = crs.getString("service_target_battery_amount");
service_target_accessories_amount = crs.getString("service_target_accessories_amount");
service_target_vas_amount = crs.getString("service_target_vas_amount");
service_target_extwarranty_count = crs.getString("service_target_extwarranty_count");
service_target_extwarranty_amount = crs.getString("service_target_extwarranty_amount");
service_target_wheelalignment_amount = crs.getString("service_target_wheelalign_amount");
service_target_cng_amount = crs.getString("service_target_cng_amount");
service_target_entry_id = crs.getString("service_target_entry_id");
entry_by = Exename(comp_id, crs.getInt("service_target_entry_id"));
entry_date = strToLongDate(crs.getString("service_target_entry_date"));
service_target_modified_id = crs.getString("service_target_modified_id");
if (!service_target_modified_id.equals("0")) {
modified_by = Exename(comp_id, Integer.parseInt(service_target_modified_id));
modified_date = strToLongDate(crs.getString("service_target_modified_date"));
}
}
} catch (Exception ex) {
SOPError("Axelaauto== " + this.getClass().getName());
SOPError("Error in " + new Exception().getStackTrace()[0].getMethodName() + ": " + ex);
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void UpdateFields(HttpServletRequest request) throws SQLException {
try {
// SOP("update fields");
service_target_id = CNumeric(ExecuteQuery("SELECT service_target_id"
+ " FROM " + compdb(comp_id) + "axela_service_target"
+ " WHERE SUBSTR(service_target_startdate,1,6) = '" + year + doublenum(Integer.parseInt(month)) + "'"
+ " AND SUBSTR(service_target_enddate,1,6) = '" + year + doublenum(Integer.parseInt(month)) + "'"
+ " AND service_target_emp_id = " + Service_target_emp_id + ""));
// SOP("updatefield target_id===== " + target_id);
conntx = connectDB();
conntx.setAutoCommit(false);
stmttx = conntx.createStatement();
if (service_target_id.equals("0")) {
AddTargetFields();
}
UpdateTargetFields();
conntx.commit();
} catch (Exception ex) {
if (conntx.isClosed()) {
msg = "<br>Transaction Error!";
SOPError("connection is closed.....");
}
if (!conntx.isClosed() && conntx != null) {
conntx.rollback();
msg = "<br>Transaction Error!";
SOPError("connection rollback...");
}
SOPError("Axelaauto== " + this.getClass().getName());
SOPError("Error in "
+ new Exception().getStackTrace()[0].getMethodName() + ": "
+ ex);
} finally {
conntx.setAutoCommit(true);
if (stmttx != null && !stmttx.isClosed()) {
stmttx.close();
}
if (conntx != null && !conntx.isClosed()) {
conntx.close();
}
}
}
public void AddTargetFields() throws SQLException {
try {
int days = DaysInMonth(Integer.parseInt(year), Integer.parseInt(month));
StrSql = "INSERT INTO " + compdb(comp_id)
+ "axela_service_target ( "
+ " service_target_emp_id, service_target_startdate,service_target_enddate, "
+ " service_target_entry_id, service_target_entry_date ) "
+ " VALUES "
+ " (" + Service_target_emp_id + ","
+ " " + year + doublenum(Integer.parseInt(month)) + "01000000" + ","
+ " " + year + doublenum(Integer.parseInt(month)) + days + "000000" + ","
+ " " + emp_id + ","
+ " " + ToLongDate(kknow()) + ")";
// SOP("add==" + StrSql);
stmttx.execute(StrSql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmttx.getGeneratedKeys();
while (rs.next()) {
service_target_id = rs.getString(1);
// SOP("inside add targets===targetid===" + target_id);
}
rs.close();
} catch (Exception ex) {
if (conntx.isClosed()) {
msg = "<br>Transaction Error!";
SOPError("conn is closed.....");
}
if (!conntx.isClosed() && conntx != null) {
conntx.rollback();
msg = "<br>Transaction Error!";
SOPError("connection rollback...");
}
SOPError("Axelaauto== " + this.getClass().getName());
SOPError("Error in "
+ new Exception().getStackTrace()[0].getMethodName() + ": "
+ ex);
}
}
public void UpdateTargetFields() throws SQLException {
try {
StrSql = "UPDATE " + compdb(comp_id) + "axela_service_target "
+ " SET"
+ " service_target_jc_count= " + service_target_jc_count + ", "
+ " service_target_pms_count= " + service_target_pms_count + ", "
+ " service_target_labour_amount= " + service_target_labour_amount + ", "
+ " service_target_parts_amount= " + service_target_parts_amount + ", "
+ " service_target_oil_amount= " + service_target_oil_amount + ", "
+ " service_target_tyre_count= " + service_target_tyre_count + ", "
+ " service_target_tyre_amount= " + service_target_tyre_amount + ", "
+ " service_target_break_count= " + service_target_break_count + ", "
+ " service_target_break_amount= " + service_target_break_amount + ", "
+ " service_target_battery_count= " + service_target_battery_count + ", "
+ " service_target_battery_amount= " + service_target_battery_amount + ", "
+ " service_target_accessories_amount= " + service_target_accessories_amount + ", "
+ " service_target_vas_amount= " + service_target_vas_amount + ", "
+ " service_target_extwarranty_count= " + service_target_extwarranty_count + ", "
+ " service_target_extwarranty_amount= " + service_target_extwarranty_amount + ", "
+ " service_target_wheelalign_amount= " + service_target_wheelalignment_amount + ", "
+ " service_target_cng_amount= " + service_target_cng_amount + ", "
+ " service_target_modified_id = " + service_target_modified_id + ", "
+ "service_target_modified_date=" + service_target_modified_date + " "
+ " WHERE service_target_id=" + service_target_id + "";
// SOP("Strsql update targets===" + StrSql);
stmttx.execute(StrSql);
} catch (Exception ex) {
if (conntx.isClosed()) {
msg = "<br>Transaction Error!";
SOPError("conn is closed.....");
}
if (!conntx.isClosed() && conntx != null) {
conntx.rollback();
msg = "<br>Transaction Error!";
SOPError("connection rollback...");
}
SOPError("Axelaauto== " + this.getClass().getName());
SOPError("Error in "
+ new Exception().getStackTrace()[0].getMethodName() + ": "
+ ex);
}
}
}
| true
|
9c5cf2fbb8398f58e719164fdcc4e650e8d96700
|
Java
|
barakgonen/AvroSchemaEvolution
|
/src/test/java/org/barakg/avro/schema/evolution/utils/FileReadingUtils.java
|
UTF-8
| 1,773
| 2.609375
| 3
|
[] |
no_license
|
package org.barakg.avro.schema.evolution.utils;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileReadingUtils {
public static String getFileContent(String pathToFile) {
Path path = Paths.get(pathToFile);
String data = null;
try {
Stream<String> lines = Files.lines(path);
data = lines.collect(Collectors.joining("\n"));
lines.close();
data = StringUtils.deleteWhitespace(data);
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static String getFileContent(String fileName, Class c){
InputStream inputStream = c.getClassLoader().getResourceAsStream(fileName);
String data = null;
try {
data = StringUtils.deleteWhitespace(readFromInputStream(inputStream));
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private static String readFromInputStream(InputStream inputStream)
throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br
= new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line);
}
}
return resultStringBuilder.toString();
}
}
| true
|
df94c22ead0342398c3f526b1292a7bf70f03abc
|
Java
|
Bilyana-Vatev-80/Java-OOP
|
/EasterRaces/src/easterRaces/repositories/interfaces/DriverRepository.java
|
UTF-8
| 902
| 3.015625
| 3
|
[] |
no_license
|
package easterRaces.repositories.interfaces;
import easterRaces.entities.cars.Car;
import easterRaces.entities.drivers.Driver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DriverRepository<T> implements Repository<Driver>{
private Collection<Driver> models;
public DriverRepository() {
this.models = new ArrayList<>();
}
@Override
public Driver getByName(String name) {
for (Driver drive : models) {
if(drive.getName().equals(name)){
return drive;
}
}
return null;
}
@Override
public Collection<Driver> getAll() {
return this.models;
}
@Override
public void add(Driver model) {
this.models.add(model);
}
@Override
public boolean remove(Driver model) {
return this.models.remove(model);
}
}
| true
|
98e058588cf876e16ed8a9b34df91ee269f5e81a
|
Java
|
jasondyjohnson/chores
|
/src/main/java/com/jasondyjohnson/domain/ChoreReward.java
|
UTF-8
| 641
| 2.453125
| 2
|
[] |
no_license
|
package com.jasondyjohnson.domain;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Set;
/**
* Created by Jason on 2/20/2016.
*/
@Data
@Entity
@NoArgsConstructor(access= AccessLevel.PROTECTED)
public class ChoreReward {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private long id;
@Column(unique=true)
@NotNull
private String name;
@NotNull
private int points;
public ChoreReward(String name, int points) {
this.name = name;
this.points = points;
}
}
| true
|
a8e910a14fb2ed8980b56786c4d95dd1ad0fe8ae
|
Java
|
QuChunhe/databus
|
/src/main/java/databus/util/Recorder.java
|
UTF-8
| 5,292
| 2.71875
| 3
|
[] |
no_license
|
package databus.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Recorder {
public Recorder(String recordFileName){
this.recordFileName = recordFileName;
}
public Map<String, String> load(){
HashMap<String, String> data = new HashMap<>();
File file = new File(recordFileName);
if (!file.exists() || !file.isFile()) {
return data;
}
try (BufferedReader reader = Files.newBufferedReader(file.toPath(),
StandardCharsets.UTF_8)) {
String line;
while((line=reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
String[] parts = line.split("=", 2);
if (parts.length == 2) {
data.put(parts[0].trim(), parts[1].trim());
}
}
} catch (IOException e) {
log.error("Can't load data from "+recordFileName, e);
}
return data;
}
public void save(Map<String, String> data) {
if (data.size() == 0) {
return;
}
FileChannel fileChannel = getRecordFileChannel(recordFileName);
if (null == fileChannel) {
log.error("FileChannel is null, and can't save "+data.toString());
return;
}
StringBuilder builder = new StringBuilder(128);
builder.append("#")
.append(new Date().toString());
for(Map.Entry<String, String> e : data.entrySet()) {
builder.append(LINE_SEPERATOR)
.append(e.getKey())
.append('=')
.append(e.getValue());
}
synchronized (this) {
//guarantee atomic overwrite
long currentFileLength = builder.length();
for(long i=currentFileLength; i<prevFileLength; i++) {
builder.append(' ');
}
prevFileLength = currentFileLength;
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ByteBuffer byteBuffer;
try {
byteBuffer = encoder.encode(CharBuffer.wrap(builder, 0, builder.length()));
} catch (CharacterCodingException e) {
log.error("Can't encode "+builder.toString(), e);
return;
}
int size = byteBuffer.limit() - byteBuffer.position();
try {
int length = fileChannel.write(byteBuffer, 0);
fileChannel.truncate(length);
if (length != size) {
log.error(size+" bytes , only "+length+" write to file");
}
} catch (IOException e) {
log.error("Can't write "+data.toString()+" to "+recordFileName);
}
}
}
public void close() {
if (null != recordFileChannel) {
synchronized (this) {
if (null != recordFileChannel) {
try {
recordFileChannel.close();
recordFileChannel = null;
} catch (IOException e) {
log.error("Can't close "+recordFileName, e);
}
}
}
}
}
private FileChannel openFileChannel(String fileName) {
File file = new File(fileName);
if (file.exists() && !file.isFile()) {
log.error(fileName + " isn't a file");
return null;
}
FileChannel fileChannel = null;
try {
fileChannel = FileChannel.open(file.toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE);
} catch (IOException e) {
log.error("Can't open FileChannel for "+fileName);
}
return fileChannel;
}
private FileChannel getRecordFileChannel(String fileName) {
if (null == recordFileChannel) {
synchronized (this) {
if (null == recordFileChannel) {
recordFileChannel = openFileChannel(fileName);
}
}
}
return recordFileChannel;
}
private static Log log = LogFactory.getLog(Recorder.class);
private static final String LINE_SEPERATOR = System.getProperty("line.separator", "\\n");
private FileChannel recordFileChannel = null;
private final String recordFileName;
private long prevFileLength = 0;
}
| true
|
1ba10a603ac031fb1524e92bdeaa4d435cb41149
|
Java
|
2017GraduateGroup/keeln
|
/src/main/java/com/keeln/mybatisgenerate/query/PageResult.java
|
UTF-8
| 1,687
| 2.296875
| 2
|
[] |
no_license
|
package com.keeln.mybatisgenerate.query;
import com.google.common.collect.Lists;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
*/
public class PageResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
private List<T> pageData = Lists.newArrayList();
private int pageNo = BaseQuery.DEFAULT_PAGE;
private int totalCount; // 总的数目
private int pageSize = BaseQuery.DEFAULT_PAGE_SIZE; //每一页数目
public List<T> getPageData() {
return pageData;
}
public void setPageData(List<T> pageData) {
this.pageData = pageData;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getTotalPage() {
if (pageNo < 1) {
pageNo = BaseQuery.DEFAULT_PAGE;
}
return totalCount / pageSize + (totalCount % pageSize == 0 ? 0 : 1);
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public PageResult() {
}
public PageResult(int size, int no, int count) {
pageSize = size;
pageNo = no;
totalCount = count;
pageData = new LinkedList<T>();
}
public PageResult(int size, int no, int count, List<T> tList) {
pageSize = size;
pageNo = no;
totalCount = count;
pageData = tList;
}
}
| true
|
02311cafc0008dff75bfbb7c0b7b1292087c672c
|
Java
|
julywerneck/algorithms-and-data-structures
|
/algorithms/06-is-java/tp01q06.java
|
UTF-8
| 2,841
| 3.59375
| 4
|
[] |
no_license
|
public class tp01q06 {
public static boolean isFim(String str) {
return str.length() >= 3 && str.charAt(0) == 'F' && str.charAt(1) == 'I' && str.charAt(2) == 'M';
} // Verificar se é 'FIM'
public static boolean isVogal(String str) {
boolean vogal = true;
for(int i = 0; vogal == true && i < str.length(); i++) {
if(str.charAt(i) != 'a' && str.charAt(i) != 'A' && str.charAt(i) != 'e' && str.charAt(i) != 'E' && str.charAt(i) != 'i' && str.charAt(i) != 'I' && str.charAt(i) != 'o' && str.charAt(i) != 'O' && str.charAt(i) != 'u' && str.charAt(i) != 'U') {
vogal = false;
}
}
return vogal;
} // Verifica se é uma string formada apenas de vogais - varre toda a str e caso encontre algo diferente das vogais seta valor como false e sai do for
public static boolean isConso(String str) {
boolean consoante = true;
for(int i = 0; consoante == true && i < str.length(); i++) {
if((str.charAt(i) < 'A' || str.charAt(i) > 'Z') && (str.charAt(i) < 'a' || str.charAt(i) > 'z')){
consoante = false;
} else if(str.charAt(i) == 'a' || str.charAt(i) == 'A' || str.charAt(i) == 'e' || str.charAt(i) == 'E' || str.charAt(i) == 'I' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'O' || str.charAt(i) == 'U' || str.charAt(i) == 'u') {
consoante = false;
}
}
return consoante;
} // Verifica se a string é formada apenas por consoante - verifica se é letra depois verifica se é apenas vogal e seta o valor como false nesses casos
public static boolean isInt(String str) {
boolean inteiro = true;
for(int i = 0; inteiro == true && i < str.length(); i++) {
int check = (int)str.charAt(i);
if(check < 48 || check > 57) {
inteiro = false;
}
}
return inteiro;
} // Verifica se a string é um inteiro - varre a str verificando se é formada apenas por numeros
public static boolean isReal(String str) {
boolean real = true;
for(int i = 0; real == true && i < str.length(); i++) {
int check = (int)str.charAt(i);
if(check < 48 || check > 57 || check != 46 || check != 44) {
real = false;
}
}
return real;
}
public static void main(String[] args) {
String str[] = new String[10000];
int numEntrada = 0;
do {
str[numEntrada] = MyIO.readLine();
} while(isFim(str[numEntrada++]) == false);
// Leitura da entrada enquanto diferente de FIM
numEntrada--;
for(int i = 0; i < numEntrada; i++) {
if(isVogal(str[i]) == true) {
MyIO.println("SIM NAO NAO NAO");
} else if(isConso(str[i]) == true) {
MyIO.println("NAO SIM NAO NAO");
} else if(isInt(str[i]) == true) {
MyIO.println("NAO NAO SIM SIM");
} else if(isReal(str[i]) == true) {
MyIO.println("NAO NAO NAO SIM");
} else {
MyIO.println("NAO NAO NAO NAO");
}
}
}
}
| true
|
43ad042898ab7ccbc13dc11a49b3e2b352040e14
|
Java
|
kokoharry/Portalwebsite
|
/src/test/java/com/kokoharry/website/manager/service/impl/CodeGenrateServiceImplTest.java
|
UTF-8
| 3,615
| 2.03125
| 2
|
[] |
no_license
|
package com.kokoharry.website.manager.service.impl;
import com.kokoharry.website.manager.service.ICodeGenrateService;
import com.kokoharry.website.manager.service.IMenuService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
/**
* Created by luyb on 2017/10/17.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={ "classpath:spring-mybatis.xml" })
public class CodeGenrateServiceImplTest {
@Resource
public ICodeGenrateService codeGenrateService;
@Test
public void createTableBySqlUpload() throws Exception {
String sql = "CREATE TABLE `amass_event` (" +
" `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' 自增主键'," +
" `device_type` bigint(20) DEFAULT NULL COMMENT '设备类型'," +
" `log_original` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '日志原文'," +
" `log_level` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '日志等级'," +
" `number` int(11) DEFAULT NULL COMMENT '数量缺省1 全局'," +
" `module` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '模块'," +
" `log_type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '日志类型'," +
" `protocol` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '协议 全局'," +
" `src_ip` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '源IP'," +
" `dest_ip` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '目的IP'," +
" `event` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '事件'," +
" `event_summary` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '事件摘要'," +
" `src_port` int(11) DEFAULT NULL COMMENT '源端口'," +
" `dest_port` int(11) DEFAULT NULL COMMENT '目的端口'," +
" `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '名称'," +
" `attribute` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '属性'," +
" PRIMARY KEY (`id`) USING BTREE" +
") ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '收集事件' ROW_FORMAT = Compact;";
String i = codeGenrateService.createTableBySqlUpload(sql);
}
@Test
public void dropTempTable() throws Exception {
String tableName = "tempTable_testd803a5a1-3d73-4662-b815-247fe1734d8a";
int i = codeGenrateService.dropTempTable(tableName);
}
@Test
public void test(){
String path = "E:\\MyWork\\Portalwebsite\\target\\Portalwebsite\\tempFiles\\tempTable_amass_event_c3cccf9f" +
"-025b-414b-85c3-420a82cb8966\\com\\kokoharry\\bean";
File f = new File(path);
if(!f.exists()){
try {
f.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true
|
d1f140e14b6ea73c33c9bf0a4ed8fcb06a52e412
|
Java
|
MateenKhan/SpringCore
|
/src/main/java/seven/AwesomeFeature.java
|
UTF-8
| 121
| 1.921875
| 2
|
[] |
no_license
|
package seven;
public class AwesomeFeature {
public void awesomeLogic() {
System.out.println("Awesomness!!");
}
}
| true
|