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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
408eef0a1ad5a7627570bfd61c755c9e5204f3af | Java | newshikeshengxian/ShiKe | /store/src/main/java/com/sk/store/po/ProducrTwo.java | UTF-8 | 612 | 1.945313 | 2 | [] | no_license | package com.sk.store.po;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class ProducrTwo {
private String ptId;
private String ptName;
private String poId;
private List<ProductThree> productThree;
public String getPtId() {
return ptId;
}
public void setPtId(String ptId) {
this.ptId = ptId;
}
public String getPtName() {
return ptName;
}
public void setPtName(String ptName) {
this.ptName = ptName;
}
public String getPoId() {
return poId;
}
public void setPoId(String poId) {
this.poId = poId;
}
}
| true |
1edcc7f767498050f7ec413afd564a0b23166a14 | Java | Rhadamys/ddm-usach | /src/Otros/BotonImagen.java | UTF-8 | 10,047 | 2.734375 | 3 | [] | 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 Otros;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
* @author mam28
*/
public final class BotonImagen extends JButton implements MouseListener, ChangeListener{
private Image imagenActual;
private Image imagenMouseNormal;
private Image imagenMouseSobre;
private Image imagenMousePresionado;
private Image imagenDeshabilitado;
public BotonImagen(){
this.setContentAreaFilled(false);
this.setBorder(null);
this.setOpaque(false);
this.setCursor(Constantes.CURSOR);
repaint();
this.addMouseListener(this);
this.addChangeListener(this);
}
/**
* Inicializar un botón con imagen de fondo.
* @param numBoton Numero del botón que se creará (Ver en Constantes)
*/
public BotonImagen(int numBoton){
String imgNormal = Constantes.VACIO;
String imgSobre = Constantes.VACIO;
String imgPresionado = Constantes.VACIO;
String imgDeshabilitado = Constantes.VACIO;
switch(numBoton){
case Constantes.BTN_NORMAL:
imgNormal = Constantes.BOTON;
imgSobre = Constantes.BOTON_SOBRE;
imgPresionado = Constantes.BOTON_PRESIONADO;
imgDeshabilitado = Constantes.BOTON_DESHABILITADO;
break;
case Constantes.BTN_REDONDO:
imgNormal = Constantes.BOTON_REDONDO;
imgSobre = Constantes.BOTON_REDONDO_SOBRE;
imgPresionado = Constantes.BOTON_REDONDO_PRESIONADO;
break;
case Constantes.BTN_ATAQUE:
imgNormal = Constantes.ATAQUE;
imgSobre = Constantes.ATAQUE_SOBRE;
imgPresionado = Constantes.ATAQUE_PRESIONADO;
imgDeshabilitado = Constantes.ATAQUE_DESHABILITADO;
break;
case Constantes.BTN_INVOCACION:
imgNormal = Constantes.INVOCACION;
imgSobre = Constantes.INVOCACION_SOBRE;
imgPresionado = Constantes.INVOCACION_PRESIONADO;
imgDeshabilitado = Constantes.INVOCACION_DESHABILITADO;
break;
case Constantes.BTN_MAGIA:
imgNormal = Constantes.MAGIA;
imgSobre = Constantes.MAGIA_SOBRE;
imgPresionado = Constantes.MAGIA_PRESIONADO;
imgDeshabilitado = Constantes.MAGIA_DESHABILITADO;
break;
case Constantes.BTN_MOVIMIENTO:
imgNormal = Constantes.MOVIMIENTO;
imgSobre = Constantes.MOVIMIENTO_SOBRE;
imgPresionado = Constantes.MOVIMIENTO_PRESIONADO;
imgDeshabilitado = Constantes.MOVIMIENTO_DESHABILITADO;
break;
case Constantes.BTN_TRAMPA:
imgNormal = Constantes.TRAMPA;
imgSobre = Constantes.TRAMPA_SOBRE;
imgPresionado = Constantes.TRAMPA_PRESIONADO;
imgDeshabilitado = Constantes.TRAMPA_DESHABILITADO;
break;
case Constantes.BTN_PAUSA:
imgNormal = Constantes.PAUSA;
imgSobre = Constantes.PAUSA_SOBRE;
imgPresionado = Constantes.PAUSA_PRESIONADO;
imgDeshabilitado = Constantes.PAUSA_DESHABILITADO;
break;
case Constantes.BTN_ATRAS:
imgNormal = Constantes.ATRAS;
imgSobre = Constantes.ATRAS_SOBRE;
imgPresionado = Constantes.ATRAS_PRESIONADO;
break;
case Constantes.BTN_MARCO:
imgSobre = Constantes.MARCO_SELECCION;
break;
case Constantes.BTN_NUEVA_PARTIDA:
imgNormal = Constantes.NUEVA_PARTIDA;
imgSobre = Constantes.NUEVA_PARTIDA_SOBRE;
imgPresionado = Constantes.NUEVA_PARTIDA_PRESIONADO;
break;
case Constantes.BTN_NUEVO_TORNEO:
imgNormal = Constantes.TORNEO;
imgSobre = Constantes.TORNEO_SOBRE;
imgPresionado = Constantes.TORNEO_PRESIONADO;
break;
case Constantes.BTN_MODIFICAR_PUZZLE:
imgNormal = Constantes.MODIFICAR_PUZZLE;
imgSobre = Constantes.MODIFICAR_PUZZLE_SOBRE;
imgPresionado = Constantes.MODIFICAR_PUZZLE_PRESIONADO;
break;
case Constantes.BTN_INFO_CRIATURAS:
imgNormal = Constantes.INFO_CRIATURAS;
imgSobre = Constantes.INFO_CRIATURAS_SOBRE;
imgPresionado = Constantes.INFO_CRIATURAS_PRESIONADO;
break;
case Constantes.BTN_SALIR:
imgNormal = Constantes.SALIR;
imgSobre = Constantes.SALIR_SOBRE;
imgPresionado = Constantes.SALIR_PRESIONADO;
break;
case Constantes.BTN_TODOS_CONTRA_TODOS:
imgNormal = Constantes.TODOS_CONTRA_TODOS;
imgSobre = Constantes.TODOS_CONTRA_TODOS_SOBRE;
imgPresionado = Constantes.TODOS_CONTRA_TODOS_PRESIONADO;
break;
case Constantes.BTN_SOBREVIVIENTE:
imgNormal = Constantes.SOBREVIVIENTE;
imgSobre = Constantes.SOBREVIVIENTE_SOBRE;
imgPresionado = Constantes.SOBREVIVIENTE_PRESIONADO;
break;
}
imagenMouseNormal = new ImageIcon(getClass().getResource(imgNormal)).getImage();
imagenMouseSobre = new ImageIcon(getClass().getResource(imgSobre)).getImage();
imagenMousePresionado = new ImageIcon(getClass().getResource(imgPresionado)).getImage();
imagenDeshabilitado = new ImageIcon(getClass().getResource(imgDeshabilitado)).getImage();
this.imagenActual = imagenMouseNormal;
this.setContentAreaFilled(false);
this.setBorder(null);
this.setOpaque(false);
this.setFont(Constantes.FUENTE_14PX);
this.setCursor(Constantes.CURSOR);
this.setForeground(Color.white);
repaint();
this.addMouseListener(this);
this.addChangeListener(this);
}
@Override
public void paint(Graphics g) {
g.drawImage(imagenActual, 0, 0, getWidth(), getHeight(), this);
super.paint(g);
}
/**
* Define la imagen que se mostrará cuando el mouse se encuentre sobre
* el botón
* @param imagen String - Nombre del archivo
*/
public final void setImagenSobre(String imagen){
imagenMouseSobre = new ImageIcon(getClass().getResource(imagen)).getImage();
}
/**
* Define la imagen que se mostrará cuando el mouse salga del botón.
* @param imagen String - Nombre del archivo
*/
public final void setImagenNormal(String imagen){
imagenMouseNormal = new ImageIcon(getClass().getResource(imagen)).getImage();
}
/**
* Define la imagen que se mostrará cuando se presiona el botón.
* @param imagen String - Nombre del archivo
*/
public final void setImagenPresionado(String imagen){
imagenMousePresionado = new ImageIcon(getClass().getResource(imagen)).getImage();
}
/**
* Define la imagen que se mostrará cuando el botón esté deshabilitado.
* @param imagen String - Nombre del archivo
*/
public final void setImagenDeshabilitado(String imagen){
imagenDeshabilitado = new ImageIcon(getClass().getResource(imagen)).getImage();
}
public final void setImagenActual(int i){
switch(i){
case 0: this.imagenActual = this.imagenMouseNormal;
break;
case 1: this.imagenActual = this.imagenMouseSobre;
break;
case 2: this.imagenActual = this.imagenMousePresionado;
break;
default: this.imagenActual = this.imagenDeshabilitado;
}
this.repaint();
}
@Override
public void mouseClicked(MouseEvent me) {
// Nada
}
@Override
public void mousePressed(MouseEvent me) {
if(isEnabled()){
setImagenActual(2);
}else{
setImagenActual(3);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if(e.getX() > 0 && e.getX() < e.getComponent().getWidth() &&
e.getY() > 0 && e.getY() < e.getComponent().getHeight()){
if(isEnabled()){
Reproductor.reproducirEfecto(Constantes.CLICK);
setImagenActual(1);
}else{
setImagenActual(3);
}
}else{
mouseExited(e);
}
}
@Override
public void mouseEntered(MouseEvent me) {
if(isEnabled()){
setImagenActual(1);
}else{
setImagenActual(3);
}
}
@Override
public void mouseExited(MouseEvent me) {
if(isEnabled()){
setImagenActual(0);
}else{
setImagenActual(3);
}
}
@Override
public void stateChanged(ChangeEvent ce) {
if(isEnabled()){
setImagenActual(0);
}else{
setImagenActual(3);
}
}
}
| true |
4a13c419358ea6cf4950bcb3d973ab9519078068 | Java | jsogard/kata-vending-machine | /src/vending_machine/Tests.java | UTF-8 | 1,756 | 2.734375 | 3 | [] | no_license | package vending_machine;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(JUnit4.class)
public class Tests {
private VendingMachine vendingMachine;
@Before
public void instantiateDefaults(){
vendingMachine = new VendingMachine();
}
@Test
public void initialDisplay(){
Assert.assertEquals("INSERT COIN", vendingMachine.checkDisplay());
}
@Test
public void rejectsInReturn(){
for(Money moneyType: Money.values()){
if(VendingMachine.isAccepted(moneyType)){
Assert.assertTrue(vendingMachine.insertMoney(moneyType));
Assert.assertEquals(0, (int)vendingMachine.emptyCoinReturn().get(moneyType));
}
else{
Assert.assertFalse(vendingMachine.insertMoney(moneyType));
Assert.assertEquals(1, (int)vendingMachine.emptyCoinReturn().get(moneyType));
}
}
}
@Test
public void insertCoinsProperValue(){
double initChange = vendingMachine.getChangeValue(), delta = 0;
for(Money moneyType : Money.values()){
vendingMachine.insertMoney(moneyType);
if(VendingMachine.isAccepted(moneyType))
delta += moneyType.getValue();
}
Assert.assertEquals(initChange + delta, vendingMachine.getChangeValue(), 0.009);
}
@Test
public void insertCoinsProperDisplay(){
double initChange = vendingMachine.getChangeValue(), delta = 0;
for(Money moneyType : Money.values()){
vendingMachine.insertMoney(moneyType);
if(VendingMachine.isAccepted(moneyType))
delta += moneyType.getValue();
}
Assert.assertEquals(String.format("$%.2f", initChange + delta), vendingMachine.checkDisplay());
}
}
| true |
fd394f5c01c3e8929d277ce2193231821ee12820 | Java | srees16/Java-OOP | /ReviseJava/src/tut42practice.java | UTF-8 | 330 | 2.90625 | 3 | [] | no_license |
public class tut42practice {
private int day;
private int month;
private int year;
tut42practice (int i, int j, int k) {
day = i;
month= j;
year = k;
System.out.printf("We got Independence on%s \n" , this);
}
public String toString () {
return String.format("% d/%d/%d", day, month, year);
}
}
| true |
5c11404c804f5923f6dd20d14f6bf84c34e744a9 | Java | wqf6146/WooSport | /app/build/generated/source/apt/release/com/yhrjkf/woyundong/activity/PersonalActivity$$ViewBinder.java | UTF-8 | 4,236 | 1.65625 | 2 | [] | no_license | // Generated code from Butter Knife. Do not modify!
package com.yhrjkf.woyundong.activity;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.ViewBinder;
public class PersonalActivity$$ViewBinder<T extends com.yhrjkf.woyundong.activity.PersonalActivity> implements ViewBinder<T> {
@Override public void bind(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131624146, "field 'img_my_touxiang'");
target.img_my_touxiang = finder.castView(view, 2131624146, "field 'img_my_touxiang'");
view = finder.findRequiredView(source, 2131624144, "field 'rl_my_touxiang'");
target.rl_my_touxiang = finder.castView(view, 2131624144, "field 'rl_my_touxiang'");
view = finder.findRequiredView(source, 2131624169, "field 'rl_my_qm'");
target.rl_my_qm = finder.castView(view, 2131624169, "field 'rl_my_qm'");
view = finder.findRequiredView(source, 2131624147, "field 'rl_my_nicheng'");
target.rl_my_nicheng = finder.castView(view, 2131624147, "field 'rl_my_nicheng'");
view = finder.findRequiredView(source, 2131624152, "field 'rl_my_yx'");
target.rl_my_yx = finder.castView(view, 2131624152, "field 'rl_my_yx'");
view = finder.findRequiredView(source, 2131624155, "field 'rl_my_sex'");
target.rl_my_sex = finder.castView(view, 2131624155, "field 'rl_my_sex'");
view = finder.findRequiredView(source, 2131624158, "field 'rl_my_sg'");
target.rl_my_sg = finder.castView(view, 2131624158, "field 'rl_my_sg'");
view = finder.findRequiredView(source, 2131624161, "field 'rl_my_tz'");
target.rl_my_tz = finder.castView(view, 2131624161, "field 'rl_my_tz'");
view = finder.findRequiredView(source, 2131624164, "field 'rl_my_csny'");
target.rl_my_csny = finder.castView(view, 2131624164, "field 'rl_my_csny'");
view = finder.findRequiredView(source, 2131624149, "field 'tv_my_nicheng'");
target.tv_my_nicheng = finder.castView(view, 2131624149, "field 'tv_my_nicheng'");
view = finder.findRequiredView(source, 2131624151, "field 'tv_my_sjh'");
target.tv_my_sjh = finder.castView(view, 2131624151, "field 'tv_my_sjh'");
view = finder.findRequiredView(source, 2131624154, "field 'tv_my_yx'");
target.tv_my_yx = finder.castView(view, 2131624154, "field 'tv_my_yx'");
view = finder.findRequiredView(source, 2131624157, "field 'tv_my_sex'");
target.tv_my_sex = finder.castView(view, 2131624157, "field 'tv_my_sex'");
view = finder.findRequiredView(source, 2131624160, "field 'tv_my_sg'");
target.tv_my_sg = finder.castView(view, 2131624160, "field 'tv_my_sg'");
view = finder.findRequiredView(source, 2131624163, "field 'tv_my_tz'");
target.tv_my_tz = finder.castView(view, 2131624163, "field 'tv_my_tz'");
view = finder.findRequiredView(source, 2131624166, "field 'tv_my_csny'");
target.tv_my_csny = finder.castView(view, 2131624166, "field 'tv_my_csny'");
view = finder.findRequiredView(source, 2131624168, "field 'tv_my_bmi'");
target.tv_my_bmi = finder.castView(view, 2131624168, "field 'tv_my_bmi'");
view = finder.findRequiredView(source, 2131624171, "field 'tv_my_qm'");
target.tv_my_qm = finder.castView(view, 2131624171, "field 'tv_my_qm'");
view = finder.findRequiredView(source, 2131624143, "field 'tv_save_btn'");
target.tv_save_btn = finder.castView(view, 2131624143, "field 'tv_save_btn'");
view = finder.findRequiredView(source, 2131624141, "field 'mImgBack'");
target.mImgBack = finder.castView(view, 2131624141, "field 'mImgBack'");
}
@Override public void unbind(T target) {
target.img_my_touxiang = null;
target.rl_my_touxiang = null;
target.rl_my_qm = null;
target.rl_my_nicheng = null;
target.rl_my_yx = null;
target.rl_my_sex = null;
target.rl_my_sg = null;
target.rl_my_tz = null;
target.rl_my_csny = null;
target.tv_my_nicheng = null;
target.tv_my_sjh = null;
target.tv_my_yx = null;
target.tv_my_sex = null;
target.tv_my_sg = null;
target.tv_my_tz = null;
target.tv_my_csny = null;
target.tv_my_bmi = null;
target.tv_my_qm = null;
target.tv_save_btn = null;
target.mImgBack = null;
}
}
| true |
22d639a57492ad3c278df061c62e8e5814e294d4 | Java | ashok-hariharan/TicketingApplication | /src/main/java/com/ashok/TicketingApplication/repository/TicketingRepository.java | UTF-8 | 308 | 1.742188 | 2 | [] | no_license | package com.ashok.TicketingApplication.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.ashok.TicketingApplication.model.Ticket;
@Repository
public interface TicketingRepository extends JpaRepository<Ticket, Integer>{
} | true |
6d36098273e37a68e6f97f3913400ec0080b0ada | Java | mukesh89m/automation | /src/test/java/com/snapwiz/selenium/tests/staf/datacreation/apphelper/PracticeTest.java | UTF-8 | 109,186 | 2.140625 | 2 | [] | no_license | package com.snapwiz.selenium.tests.staf.datacreation.apphelper;
import com.mongodb.DBCollection;
import com.snapwiz.selenium.tests.staf.datacreation.uihelper.RandomNumber;
import com.snapwiz.selenium.tests.staf.datacreation.Driver;
import com.snapwiz.selenium.tests.staf.datacreation.ReadTestData;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import java.sql.ResultSet;
import java.util.*;
public class PracticeTest extends Driver {
public void startTest(int index) {
try {
Thread.sleep(1000);
//Driver.driver.findElement(By.cssSelector("span[title='Practice']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElements(By.xpath("//div[@class='al-content-header-row']/div[1]/span")).get(index));
Thread.sleep(3000);
} catch (Exception e) {
Assert.fail("Exception in starting the practice test", e);
}
}
public void startTLOLevelPracticeTest(int tloIndex) {
try {
List<String> tlonames = new PracticeTest().tloNames();
System.out.println(tlonames.get(tloIndex));
//List<WebElement> practicebuttons = Driver.driver.findElements(By.cssSelector("div[tloname='"+tlonames.get(tloIndex)+"']"));
List<WebElement> tlolist = Driver.driver.findElements(By.className("al-terminal-objective-title"));
for (WebElement tlo : tlolist) {
if (tlo.getText().equals(tlonames.get(tloIndex))) {
Actions action = new Actions(Driver.driver);
action.moveToElement(tlo).build().perform();
break;
}
}
/*WebElement we = Driver.driver.findElement(By.className(classname));
MouseHover.mouserhover("al-terminal-objective-title");*/
Driver.driver.findElement(By.cssSelector("div[tloname='" + tlonames.get(tloIndex) + "']")).click();
//Driver.driver.findElement(By.className("al-terminal-objective-title"))
//((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();",practicebuttons.get(practicebuttons.size()-1));
Thread.sleep(3000);
//((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();",practicebuttons.get(practicebuttons.size()-1));
} catch (Exception e) {
Assert.fail("Exception in app helper method startTLOLevelPracticeTest in class SelectChapterForTest", e);
}
}
public void quitTestAndGoToDashboard() {
try {
Driver.driver.findElement(By.className("al-quit-diag-test-icon")).click();
Thread.sleep(1000);
Driver.driver.findElement(By.className("ls-practice-test-view-report")).click();
Thread.sleep(2000);
} catch (Exception e) {
Assert.fail("Exception in quitting the practice test", e);
}
}
public void attemptInCorrect(int noOfQuestions)
{
try {
int timer=1;
int questionCount = 0;
while(timer!=0) {
boolean attempted = false;
//True False and Single Select Question Type
try {
driver.findElement(By.className("answer-choice-label-wrapper"));
String correctAnswer=Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctAnswerOption=correctAnswer.charAt(17);
String correctChoice=Character.toString(correctAnswerOption);
String answerIndex="0";
if(correctChoice.equals("A")) {
answerIndex = "2";
}
else if (correctChoice.equals("B")) {
answerIndex = "1";
}
else if (correctChoice.equals("C")) {
answerIndex = "1";
}
else if (correctChoice.equals("D")) {
answerIndex = "1";
}
driver.findElement(By.xpath("//div[@class='al-diag-test-answerChoices-content-wrapper']/div["+answerIndex+"]/div[1]/label")).click();
attempted = true;
}
catch (Exception e) {
}
//Multiple Selection Question Type
if(attempted ==false) {
try {
driver.findElement(By.className("multiple-selection-answer-choice-label-wrapper"));
String correctAnswer1 = driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctOption1;
if (correctAnswer1.charAt(17) == '(') {
correctOption1 = correctAnswer1.charAt(18);
} else {
correctOption1 = correctAnswer1.charAt(17);
}
String correctChoice1 = Character.toString(correctOption1); //Answer 1
String correctAnswer2 = driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctOption2 = correctAnswer2.charAt(22);
String correctChoice2 = Character.toString(correctOption2); //Answer 2
String answerIndex1 = "0",answerIndex2 = "0";
if((correctChoice1.equals("A") && correctChoice2.equals("B")) || (correctChoice1.equals("B") && correctChoice2.equals("A")) ) {
answerIndex1="3"; answerIndex2 = "4";
}
else if(correctChoice1.equals("A") && correctChoice2.equals("C") || (correctChoice1.equals("C") && correctChoice2.equals("A"))) {
answerIndex1="2"; answerIndex2 = "4";
}
else if(correctChoice1.equals("A") && correctChoice2.equals("D") || (correctChoice1.equals("D") && correctChoice2.equals("A"))) {
answerIndex1="2"; answerIndex2 = "3";
}
else if(correctChoice1.equals("A") && correctChoice2.equals("E") || (correctChoice1.equals("E") && correctChoice2.equals("A"))) {
answerIndex1="2"; answerIndex2 = "3";
}
else if(correctChoice1.equals("A") && correctChoice2.equals("F") || (correctChoice1.equals("F") && correctChoice2.equals("A"))) {
answerIndex1="2"; answerIndex2 = "3";
}
else if((correctChoice1.equals("B") && correctChoice2.equals("C")) || (correctChoice1.equals("C") && correctChoice2.equals("B")) ) {
answerIndex1="1"; answerIndex2 = "4";
}
else if(correctChoice1.equals("B") && correctChoice2.equals("D") || (correctChoice1.equals("D") && correctChoice2.equals("B"))) {
answerIndex1="1"; answerIndex2 = "3";
}
else if(correctChoice1.equals("B") && correctChoice2.equals("E") || (correctChoice1.equals("E") && correctChoice2.equals("B"))) {
answerIndex1="1"; answerIndex2 = "3";
}
else if(correctChoice1.equals("B") && correctChoice2.equals("F") || (correctChoice1.equals("F") && correctChoice2.equals("B"))) {
answerIndex1="1"; answerIndex2 = "3";
}
else if((correctChoice1.equals("C") && correctChoice2.equals("D")) || (correctChoice1.equals("D") && correctChoice2.equals("C")) ) {
answerIndex1="1"; answerIndex2 = "2";
}
else if(correctChoice1.equals("C") && correctChoice2.equals("E") || (correctChoice1.equals("E") && correctChoice2.equals("C"))) {
answerIndex1="1"; answerIndex2 = "2";
}
else if(correctChoice1.equals("C") && correctChoice2.equals("F") || (correctChoice1.equals("F") && correctChoice2.equals("C"))) {
answerIndex1="1"; answerIndex2 = "2";
}
else if((correctChoice1.equals("D") && correctChoice2.equals("E")) || (correctChoice1.equals("E") && correctChoice2.equals("D"))) {
answerIndex1="1"; answerIndex2 = "2";
}
else if(correctChoice1.equals("D") && correctChoice2.equals("F") || (correctChoice1.equals("F") && correctChoice2.equals("D"))) {
answerIndex1="1"; answerIndex2 = "2";
}
else if((correctChoice1.equals("E") && correctChoice2.equals("F")) || (correctChoice1.equals("F") && correctChoice2.equals("E")) ) {
answerIndex1="1"; answerIndex2 = "2";
}
driver.findElement(By.xpath("//div[@class='al-diag-test-answerChoices-content-wrapper']/div[" + answerIndex1 + "]/div[1]/label")).click();
driver.findElement(By.xpath("//div[@class='al-diag-test-answerChoices-content-wrapper']/div[" + answerIndex2 + "]/div[1]/label")).click();
attempted = true;
} catch (Exception e) {
}
}
//Drop Down Question Type
if(attempted == false) {
try {
driver.findElement(By.className("sbHolder"));
String correctAnswerText=Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
String correctAnswer=correctAnswerText.substring(16, correctAnswerText.length());
Driver.driver.findElement(By.className("sbToggle")).click();
Thread.sleep(1000);
/*Driver.driver.findElement(By.linkText(correctAnswer)).click();*/
String values = Driver.driver.findElement(By.cssSelector("ul[class='sbOptions']")).getText();
String [] val = values.split("\n");
for(String element:val)
{
if(!element.equals(correctAnswer))
{
Driver.driver.findElement(By.linkText(element)).click();
break;
}
}
attempted = true;
} catch (Exception e) {
}
}
//Text Entry Question Type
if(attempted == false) {
try {
driver.findElement(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']"));
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys("deliberately");
attempted = true;
}
catch (Exception e) {
}
}
/*(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.className("al-diag-test-submit-button"))).click();*/
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
try {
Driver.driver.findElement(By.className("al-notification-message-body"));
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
Driver.driver.findElement(By.className("al-practice-test-submit-button")).click();
Thread.sleep(1000);
}
}
catch (Exception e) {
}
Thread.sleep(500);
try {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
}
catch (Exception e) {
}
Thread.sleep(1000);
questionCount++;
if(noOfQuestions == 0) {
try {
Driver.driver.findElement(By.cssSelector("span[id='timer-label']"));
}
catch (Exception e) {
timer = 0;
}
}
else {
if(noOfQuestions == questionCount) {
timer = 0;
}
}
}
}
catch (Exception e) {
Assert.fail("Exception while attempting the diagnostic question as correct",e);
}
}
public void attemptCorrect(int noOfQuestions)
{
try {
int timer=1;
int questionCount = 0;
while(timer!=0) {
boolean attempted = false;
//True False and Single Select Question Type
try {
driver.findElement(By.className("answer-choice-label-wrapper"));
String correctAnswer=Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctAnswerOption=correctAnswer.charAt(17);
String correctChoice=Character.toString(correctAnswerOption);
String answerIndex="0";
if(correctChoice.equals("A")) {
answerIndex = "1";
}
else if (correctChoice.equals("B")) {
answerIndex = "2";
}
else if (correctChoice.equals("C")) {
answerIndex = "3";
}
else if (correctChoice.equals("D")) {
answerIndex = "4";
}
driver.findElement(By.xpath("//div[@class='al-diag-test-answerChoices-content-wrapper']/div["+answerIndex+"]/div[1]/label")).click();
attempted = true;
}
catch (Exception e) {
}
//Multiple Selection Question Type
if(attempted ==false) {
try {
driver.findElement(By.className("multiple-selection-answer-choice-label-wrapper"));
String correctAnswer1 = driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctOption1;
if (correctAnswer1.charAt(17) == '(') {
correctOption1 = correctAnswer1.charAt(18);
} else {
correctOption1 = correctAnswer1.charAt(17);
}
String correctChoice1 = Character.toString(correctOption1); //Answer 1
String correctAnswer2 = driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctOption2 = correctAnswer2.charAt(22);
String correctChoice2 = Character.toString(correctOption2); //Answer 2
String answerIndex = "0";
if (correctChoice1.equals("A")) {
answerIndex = "1";
} else if (correctChoice1.equals("B")) {
answerIndex = "2";
} else if (correctChoice1.equals("C")) {
answerIndex = "3";
} else if (correctChoice1.equals("D")) {
answerIndex = "4";
} else if (correctChoice1.equals("E")) {
answerIndex = "5";
} else if (correctChoice1.equals("F")) {
answerIndex = "6";
}
driver.findElement(By.xpath("//div[@class='al-diag-test-answerChoices-content-wrapper']/div[" + answerIndex + "]/div[1]/label")).click();
answerIndex = "0";
if (correctChoice2.equals("A")) {
answerIndex = "1";
} else if (correctChoice2.equals("B")) {
answerIndex = "2";
} else if (correctChoice2.equals("C")) {
answerIndex = "3";
} else if (correctChoice2.equals("D")) {
answerIndex = "4";
} else if (correctChoice2.equals("E")) {
answerIndex = "5";
} else if (correctChoice2.equals("F")) {
answerIndex = "6";
}
driver.findElement(By.xpath("//div[@class='al-diag-test-answerChoices-content-wrapper']/div[" + answerIndex + "]/div[1]/label")).click();
attempted = true;
} catch (Exception e) {
}
}
//Drop Down Question Type
if(attempted == false) {
try {
driver.findElement(By.className("sbHolder"));
String correctAnswerText=Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
String correctAnswer=correctAnswerText.substring(16, correctAnswerText.length());
Driver.driver.findElement(By.className("sbToggle")).click();
Thread.sleep(1000);
Driver.driver.findElement(By.linkText(correctAnswer)).click();
attempted = true;
} catch (Exception e) {
}
}
//Text Entry Question Type
if(attempted == false) {
try {
driver.findElement(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']"));
String correctAnswerText=Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
String correctAnswer=correctAnswerText.substring(16, correctAnswerText.length());
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys(correctAnswer);
attempted = true;
}
catch (Exception e) {
}
}
/*(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.className("al-diag-test-submit-button"))).click();*/
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
try {
Driver.driver.findElement(By.className("al-notification-message-body"));
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
Driver.driver.findElement(By.className("al-practice-test-submit-button")).click();
Thread.sleep(1000);
}
}
catch (Exception e) {
}
Thread.sleep(500);
try {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
}
catch (Exception e) {
}
Thread.sleep(1000);
if(noOfQuestions == 0) {
try {
Driver.driver.findElement(By.cssSelector("span[id='timer-label']"));
} catch (Exception e) {
timer = 0;
}
}
else {
if(noOfQuestions == questionCount) {
timer = 0;
}
}
questionCount++;
}
}
catch (Exception e) {
Assert.fail("Exception while attempting the diagnostic question as correct",e);
}
}
public List<String> tloNames() {
List<String> tlonames = new ArrayList<String>();
try {
String tlo1 = ReadTestData.readDataByTagName("tlos", "tlo1", "0");
String tlo2 = ReadTestData.readDataByTagName("tlos", "tlo2", "0");
String tlo3 = ReadTestData.readDataByTagName("tlos", "tlo3", "0");
String tlo4 = ReadTestData.readDataByTagName("tlos", "tlo4", "0");
String tlo5 = ReadTestData.readDataByTagName("tlos", "tlo5", "0");
String tlo6 = ReadTestData.readDataByTagName("tlos", "tlo6", "0");
String tlo7 = ReadTestData.readDataByTagName("tlos", "tlo7", "0");
tlonames.add(tlo1);
tlonames.add(tlo2);
tlonames.add(tlo3);
tlonames.add(tlo4);
tlonames.add(tlo5);
tlonames.add(tlo6);
tlonames.add(tlo7);
} catch (Exception e) {
Assert.fail("Exception in fetching TLO names from test data", e);
}
return tlonames;
}
public List<String> tloIds() {
List<String> tloids = new ArrayList<String>();
try {
String tlo1 = ReadTestData.readDataByTagName("tloids", "tlo1", "0");
String tlo2 = ReadTestData.readDataByTagName("tloids", "tlo2", "0");
String tlo3 = ReadTestData.readDataByTagName("tloids", "tlo3", "0");
String tlo4 = ReadTestData.readDataByTagName("tloids", "tlo4", "0");
String tlo5 = ReadTestData.readDataByTagName("tloids", "tlo5", "0");
String tlo6 = ReadTestData.readDataByTagName("tloids", "tlo6", "0");
String tlo7 = ReadTestData.readDataByTagName("tloids", "tlo7", "0");
tloids.add(tlo1);
tloids.add(tlo2);
tloids.add(tlo3);
tloids.add(tlo4);
tloids.add(tlo5);
tloids.add(tlo6);
tloids.add(tlo7);
} catch (Exception e) {
Assert.fail("Exception in fetching TLO names from test data", e);
}
return tloids;
}
public void AttemptCorrectAnswer(int confidencelevel) {
try {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String correcttextanswer = corranswertext.substring(16, lastindex);
if (Driver.driver.findElements(By.className("multiple-selection-answer-choice-label-wrapper")).size() > 0) {
String corranswer1 = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
if (corranswer1.length() > 21) {
char correctanswer1 = corranswer1.charAt(22);
String correctchoice1 = Character.toString(correctanswer1);
List<WebElement> answer1 = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice1 : answer1) {
if (answerchoice1.getText().trim().equals(correctchoice1)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice1);
break;
}
}
}
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
} else if (Driver.driver.findElements(By.className("answer-choice-label-wrapper")).size() > 0) //single select and true/false question type
{
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
} else if (Driver.driver.findElements(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']")).size() > 0) {
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys(correcttextanswer);
} else if (Driver.driver.findElements(By.className("sbHolder")).size() > 0) {
try {
Driver.driver.findElement(By.className("sbToggle")).click();
//Thread.sleep(2000);
Driver.driver.findElement(By.linkText(correcttextanswer)).click();
//Thread.sleep(5000);
} catch (Exception e) {
Assert.fail("Exception in App helper attemptQuestion in class PracticeTest", e);
}
}
if (confidencelevel != 0)
Driver.driver.findElement(By.cssSelector("a[id='" + confidencelevel + "']")).click();//click on confidence level
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Thread.sleep(3000);
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
Driver.driver.findElement(By.className("al-practice-test-submit-button")).click();
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
} catch (Exception e) {
Assert.fail("Exception in App helper AttemptCorrectAnswer in class PracticeTest", e);
}
}
public int questionDifficulty() {
String diff = null;
try {
List<WebElement> debugvalues = Driver.driver.findElements(By.id("show-debug-question-id-label"));
diff = debugvalues.get(1).getText();
} catch (Exception e) {
Assert.fail("Exception in app helper questionDifficulty in class PracticeTest", e);
}
return Integer.parseInt(diff.substring(13));
}
public void questionPresentCheck(String tcIndex) {
try {
DBCollection collection = com.snapwiz.selenium.tests.staf.datacreation.apphelper.DBConnect.mongoConnect("UserQuestionHistory");
int userid = 0, classid = 0;
String username = ReadTestData.readDataByTagName("", "user_id", tcIndex);
ResultSet userids = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("SELECT id as userid from t_user where username like '" + username + "';");
while (userids.next()) {
userid = userids.getInt("userid");
}
ResultSet classsections = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("SELECT id as classid FROM t_class_section where name like 'studtitle';");
while (classsections.next()) {
classid = classsections.getInt("classid");
}
String tlonamefound = Driver.driver.findElement(By.className("al-diagtest-skills-evaluted-ul")).getText().substring(2);
List<String> tlonames = new PracticeTest().tloNames(); //Get TLO names
int index = 0; //Get index at which the TLO is present
for (String tlo : tlonames) {
if (tlo.equals(tlonamefound))
break;
index++;
}
List<Double> profs = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getProficienciesFromMongo(userid, classid); //Get the proficiency of the TLO found
Double tloprof = profs.get(index);
int proficiency = (int) (tloprof * 100);
tlonamefound = tlonamefound.replaceAll("'", "''");
List<Integer> quesids = new ArrayList<Integer>();
//List<Integer> qidsgrcq = new ArrayList<Integer>();
ResultSet rstidltcq = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("select tq.id as qids from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and" +
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and" +
" ta.id = 11052 and tms.name like '" + tlonamefound + "' and tq.status = 80 order by tq.computed_difficulty;");
while (rstidltcq.next()) {
quesids.add(rstidltcq.getInt("qids"));
}
List<Integer> notattemptedquestions = new ArrayList<Integer>();
for (Integer qids : quesids) {
int value = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getAttemptedQuestions(qids, collection, userid, classid);
if (value == 0) {
notattemptedquestions.add(qids);
}
}
Map<Integer, Integer> qid_diff = new HashMap<Integer, Integer>();
for (Integer qid : notattemptedquestions) {
ResultSet comp_diff = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("select tq.computed_difficulty as comp_difficulty from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and" +
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and" +
" ta.id = 11052 and tms.name like '" + tlonamefound + "' and tq.status = 80 and tq.id = " + (qid) + ";");
while (comp_diff.next()) {
qid_diff.put(qid, comp_diff.getInt("comp_difficulty"));
}
}
Set set = qid_diff.entrySet();
Iterator i = set.iterator();
Iterator i2 = set.iterator();
while (i2.hasNext()) {
Map.Entry me2 = (Map.Entry) i2.next();
System.out.print("QID: " + me2.getKey() + " ");
System.out.print("CD :" + me2.getValue() + " ");
System.out.println("Distance :" + Math.abs((proficiency - (Integer) me2.getValue())));
}
System.out.println();
System.out.println();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
qid_diff.put((Integer) me.getKey(), Math.abs((proficiency - (Integer) me.getValue())));
}
Integer min = Collections.min(qid_diff.values());
System.out.println("Minimum Value of Distance " + min);
List<Integer> expectedqid = new ArrayList<Integer>();
Iterator i_min = set.iterator();
while (i_min.hasNext()) {
Map.Entry me_min = (Map.Entry) i_min.next();
if ((Integer) me_min.getValue() == min) {
expectedqid.add((Integer) me_min.getKey());
}
}
for (Integer qid : expectedqid) System.out.println("Expected questions " + qid);
List<Integer> expected_comp_diff = new ArrayList<Integer>();
for (Integer qid : expectedqid) {
ResultSet comp_diff = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("select tq.computed_difficulty as comp_difficulty from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and" +
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and" +
" ta.id = 11052 and tms.name like '" + tlonamefound + "' and tq.status = 80 and tq.id = " + (qid) + ";");
while (comp_diff.next()) {
expected_comp_diff.add(comp_diff.getInt("comp_difficulty"));
}
}
int rangeLower = 0, rangeUpper = 0;
for (Integer compdiff : expected_comp_diff) {
rangeLower = compdiff - 15;
rangeUpper = compdiff + 15;
System.out.println("Expected Computed Difficulty range " + (compdiff - 15) + "-" + (compdiff + 15));
}
System.out.println();
int questiondifficulty = questionDifficulty();
System.out.println("computed difficulty found " + questiondifficulty);
boolean inRange = false;
if (questiondifficulty >= rangeLower && questiondifficulty <= rangeUpper)
inRange = true;
if (inRange == false) {
Assert.fail("Question not as Expected. " + "Difficulty Found " + questiondifficulty + ". Expected in Range " + rangeLower + "-" + rangeUpper + " from TLO " + tlonamefound + " with Proficiency " + proficiency);
}
/*int suggesstedidfromlowerside =0;
int suggestedidfromupperside =0;
if(qidsltcq.size() > 0)
suggesstedidfromlowerside = qidsltcq.get(0);
if(qidsgrcq.size()>0)
suggestedidfromupperside = qidsgrcq.get(0);
int lowercomputeddifficulty=0;
ResultSet computeddifffromlowerside = DBConnect.st.executeQuery("SELECT computed_difficulty as compdifflower from t_questions where id= '"+suggesstedidfromlowerside+"'");
while(computeddifffromlowerside.next())
{
lowercomputeddifficulty = computeddifffromlowerside.getInt("compdifflower");
}
int uppercomputeddifficulty=0;
ResultSet computeddifffromupperside = DBConnect.st.executeQuery("SELECT computed_difficulty as compdiffupper from t_questions where id= '"+suggestedidfromupperside+"'");
while(computeddifffromupperside.next())
{
uppercomputeddifficulty = computeddifffromupperside.getInt("compdiffupper");
}
//String question_id = Driver.driver.findElement(By.id("show-debug-question-id-label")).getText().substring(13);
//System.out.println("Qeustion ID found "+question_id);
System.out.println("lower comp diff "+lowercomputeddifficulty);
System.out.println("upper comp diff "+uppercomputeddifficulty);
int rangelower = 0; int rangeupper = 0;
if(lowercomputeddifficulty == 0 && uppercomputeddifficulty !=0)
{
rangelower = uppercomputeddifficulty-10;
rangeupper = uppercomputeddifficulty+10;
}
else if (uppercomputeddifficulty == 0 && lowercomputeddifficulty !=0)
{
rangelower = lowercomputeddifficulty-10;
rangeupper = lowercomputeddifficulty+10;
}
else if(uppercomputeddifficulty - cqtloprof < cqtloprof - lowercomputeddifficulty)
{
rangelower = uppercomputeddifficulty-10;
rangeupper = uppercomputeddifficulty+10;
}
else if(uppercomputeddifficulty - cqtloprof > cqtloprof - lowercomputeddifficulty)
{
rangelower = lowercomputeddifficulty-10;
rangeupper = lowercomputeddifficulty+10;
}
else
{
rangelower = lowercomputeddifficulty-10;
rangeupper = uppercomputeddifficulty+10;
}
System.out.println("Lower Range "+rangelower);
System.out.println("Upper Range "+rangeupper);
String nextQuesTloName = Driver.driver.findElement(By.className("al-diagtest-skills-evaluted-ul")).getText().substring(2).replaceAll("'", "''");
System.out.println("Next Ques TLO "+nextQuesTloName);
boolean inRange = false;
int questiondifficulty = new PracticeTest().questionDifficulty();
System.out.println("Difficulty found "+questiondifficulty);
if(questiondifficulty >=rangelower && questiondifficulty <=rangeupper )
inRange = true;
*/
/*List<Integer> notatteptedltquest_notinrange = new ArrayList<Integer>();
List<Integer> notatteptedgrquest_notinrange = new ArrayList<Integer>();
List<Integer> qidsltcq_notinrange = new ArrayList<Integer>();
List<Integer> qidsgrcq_notinrange = new ArrayList<Integer>();
List<Integer> inrangeqids = new ArrayList<Integer>();
List<Integer> notattemptedquestinrange = new ArrayList<Integer>();
if(inRange == false) //checking if there are non-attempted questions in the TLO which are in Range
{
ResultSet inrangequestions = DBConnect.st.executeQuery("select tq.id as qids from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and"+
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and"+
" ta.id = 11052 and tms.name like '"+nextQuesTloName+"' and tq.status = 80 and tq.computed_difficulty >= "+(rangelower)+" and tq.computed_difficulty <= "+(rangeupper)+";");
while(inrangequestions.next())
{
inrangeqids.add(inrangequestions.getInt("qids"));
}
for(Integer qids : inrangeqids)
{
int value = DBConnect.getAttemptedQuestions(qids,collection,userid,classid);
if(value == 0)
{
notattemptedquestinrange.add(qids);
}
}
for(Integer ques : inrangeqids) System.out.println("In range questions "+ques);
for(Integer ques : notattemptedquestinrange) System.out.println("Not attempted questions "+ques);
if(notattemptedquestinrange.size() > 0)
Assert.fail("There are questions in this TLO which has computed difficulty in the suggested range and are not attempted but are still not presented as the next question");
}
if(inRange == false)
{
//int currentquestdiff = questionDifficulty();
ResultSet rstidltcq_notinrange = DBConnect.st.executeQuery("select tq.id as qids from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and"+
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and"+
" ta.id = 11052 and tms.name like '"+nextQuesTloName+"' and tq.status = 80 and tq.computed_difficulty < "+(rangelower)+" order by tq.computed_difficulty desc;");
while(rstidltcq_notinrange.next())
{
qidsltcq_notinrange.add(rstidltcq_notinrange.getInt("qids"));
}
ResultSet rstidgrcq_notinrange = DBConnect.st.executeQuery("select tq.id as qids from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and"+
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and"+
" ta.id = 11052 and tms.name like '"+nextQuesTloName+"' and tq.status = 80 and tq.computed_difficulty > "+(rangeupper)+" order by tq.computed_difficulty;");
while(rstidgrcq_notinrange.next())
{
qidsgrcq_notinrange.add(rstidgrcq_notinrange.getInt("qids"));
}
int suggesstedidfromlowerside_notinrange =0;
int suggestedidfromupperside_notinrange =0;
for(Integer qids : qidsltcq_notinrange)
{
int value = DBConnect.getAttemptedQuestions(qids,collection,userid,classid);
if(value == 0)
{
notatteptedltquest_notinrange.add(qids);
suggesstedidfromlowerside_notinrange = notatteptedltquest_notinrange.get(0);
break;
}
}
for(Integer qids : qidsgrcq_notinrange)
{
int value = DBConnect.getAttemptedQuestions(qids,collection,userid,classid);
if(value == 0)
{
notatteptedgrquest_notinrange.add(qids);
suggestedidfromupperside_notinrange = notatteptedgrquest_notinrange.get(0);
break;
}
}
int lowercomputeddifficulty_notinrange=0;
ResultSet computeddifffromlowerside_notinrange = DBConnect.st.executeQuery("SELECT computed_difficulty as compdifflower from t_questions where id= '"+suggesstedidfromlowerside_notinrange+"'");
while(computeddifffromlowerside_notinrange.next())
{
lowercomputeddifficulty_notinrange = computeddifffromlowerside_notinrange.getInt("compdifflower");
}
int uppercomputeddifficulty_notinrange=0;
ResultSet computeddifffromupperside_notinrange = DBConnect.st.executeQuery("SELECT computed_difficulty as compdiffupper from t_questions where id= '"+suggestedidfromupperside_notinrange+"'");
while(computeddifffromupperside_notinrange.next())
{
uppercomputeddifficulty_notinrange = computeddifffromupperside_notinrange.getInt("compdiffupper");
}
System.out.println("suggested from lower side not in range "+lowercomputeddifficulty_notinrange);
System.out.println("suggested from upper side no in range "+uppercomputeddifficulty_notinrange);
//int questiondiff = questionDifficulty();
//System.out.println("Question Difficulty found "+questiondiff);
if(questiondifficulty == lowercomputeddifficulty_notinrange || questiondifficulty == uppercomputeddifficulty_notinrange)
inRange=true;
}
if(inRange == false)
{
new Screenshot().captureScreenshotFromAppHelper();
Assert.fail("Next question difficulty not in range. Found Difficulty");
}*/
//int lastidofltcq = qidsltcq.get(qidsltcq.size()-1);
} catch (Exception e) {
Assert.fail("Exception in App helper questionPresentCheck in class PracticeTest", e);
}
}
public void questionPresentCheckRepeatFlow(String tcIndex) {
try {
//String practiceassessmentname= ReadTestData.readDataByTagName("", "practiceassessmentname",tcIndex);
int assessmentid = 205642;
/*ResultSet rstassmtid = DBConnect.st.executeQuery("select id as assessment_id from t_assessment where name like '"+practiceassessmentname+"' and assessment_type like 'Adaptive Component Practice';");
while(rstassmtid.next())
{
assessmentid = rstassmtid.getInt("assessment_id");
}*/
// System.out.println("Assessment ID "+assessmentid);
DBCollection collection = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.mongoConnect("UserQuestionHistory");
int userid = 0, classid = 0;
String username = ReadTestData.readDataByTagName("", "user_id", tcIndex);
ResultSet userids = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("SELECT id as userid from t_user where username like '" + username + "';");
while (userids.next()) {
userid = userids.getInt("userid");
}
ResultSet classsections = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("SELECT id as classid FROM t_class_section where name like 'studrepeattitle';");
while (classsections.next()) {
classid = classsections.getInt("classid");
}
String tlonamefound = Driver.driver.findElement(By.className("al-diagtest-skills-evaluted-ul")).getText().substring(2);
List<String> tlonames = new PracticeTest().tloNames(); //Get TLO names
int index = 0; //Get index at which the TLO is present
for (String tlo : tlonames) {
if (tlo.equals(tlonamefound))
break;
index++;
}
List<Double> profs = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getProficienciesFromMongo(userid, classid); //Get the proficiency of the TLO found
Double tloprof = profs.get(index);
int proficiency = (int) (tloprof * 100);
tlonamefound = tlonamefound.replaceAll("'", "''");
List<Integer> quesids = new ArrayList<Integer>();
//List<Integer> qidsgrcq = new ArrayList<Integer>();
ResultSet rstidltcq = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("select tq.id as qids from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and" +
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and" +
" ta.id = " + assessmentid + " and tms.name like '" + tlonamefound + "' and tq.status = 80 order by tq.computed_difficulty;");
while (rstidltcq.next()) {
quesids.add(rstidltcq.getInt("qids"));
}
List<Integer> questions = new ArrayList<Integer>();
for (Integer qids : quesids) {
int value = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getAttemptedQuestions(qids, collection, userid, classid);
if (value == 0) {
questions.add(qids);
System.out.println("Unattempted question with id " + qids + " expected. TLO " + tlonamefound);
}
}
System.out.println("Size initially " + questions.size());
if (questions.size() == 0) //If all questions are attempted
{
for (Integer qids : quesids) {
int value = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getQuestions(qids, collection, userid, classid, "skipped"); //checking for skipped questions
if (value != 0) {
questions.add(qids);
System.out.println("Skipped question with id " + qids + " expected. Questions Exhaused TLO " + tlonamefound);
}
}
}
if (questions.size() == 0) //If there are no skipped questions, checking for incorrectly answered questions
{
for (Integer qids : quesids) {
int value = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getQuestions(qids, collection, userid, classid, "incorrect"); //checking for incorrectly answered questions
if (value != 0) {
questions.add(qids);
System.out.println("Incorrect question with id " + qids + " expected. Questions Exhaused TLO " + tlonamefound);
}
}
}
if (questions.size() == 0) //If there are no skipped and incorrect questions, checking for correctly answered questions
{
for (Integer qids : quesids) {
int value = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.getQuestions(qids, collection, userid, classid, "correct"); //checking for correctly answered questions
if (value != 0) {
questions.add(qids);
System.out.println("Correct question with id " + qids + " expected. Questions Exhausted TLO: " + tlonamefound);
}
}
}
String question_id_found = Driver.driver.findElement(By.id("show-debug-question-id-label")).getText().substring(13);
System.out.println("Question Found " + question_id_found);
//if(!tlonamefound.equals("Outline the characteristics that make a company admired."))
//{
if (!questions.contains(Integer.parseInt(question_id_found))) {
Assert.fail("Question Found " + question_id_found + ". Expected " + questions + " from TLO " + tlonamefound);
}
//}
Map<Integer, Integer> qid_diff = new HashMap<Integer, Integer>();
for (Integer qid : questions) {
ResultSet comp_diff = com.snapwiz.selenium.tests.staf.orion.apphelper.DBConnect.st.executeQuery("select tq.computed_difficulty as comp_difficulty from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and" +
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and" +
" ta.id = " + assessmentid + " and tms.name like '" + tlonamefound + "' and tq.status = 80 and tq.id = " + (qid) + ";");
while (comp_diff.next()) {
qid_diff.put(qid, comp_diff.getInt("comp_difficulty"));
}
}
Set set = qid_diff.entrySet();
Iterator i = set.iterator();
Iterator i2 = set.iterator();
while (i2.hasNext()) {
Map.Entry me2 = (Map.Entry) i2.next();
System.out.print("QID: " + me2.getKey() + " ");
System.out.print("CD :" + me2.getValue() + " ");
System.out.println("Distance :" + Math.abs((proficiency - (Integer) me2.getValue())));
}
System.out.println();
System.out.println();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
qid_diff.put((Integer) me.getKey(), Math.abs((proficiency - (Integer) me.getValue())));
}
Integer min = Collections.min(qid_diff.values());
System.out.println("Minimum Value of Distance " + min);
List<Integer> expectedqid = new ArrayList<Integer>();
Iterator i_min = set.iterator();
while (i_min.hasNext()) {
Map.Entry me_min = (Map.Entry) i_min.next();
if ((Integer) me_min.getValue() == min) {
expectedqid.add((Integer) me_min.getKey());
}
}
//for(Integer qid : expectedqid) System.out.println("Expected questions "+qid);
List<Integer> expected_comp_diff = new ArrayList<Integer>();
for (Integer qid : expectedqid) {
ResultSet comp_diff = DBConnect.st.executeQuery("select tq.computed_difficulty as comp_difficulty from t_questions tq, t_assessment ta, t_question_set tqs, t_question_set_item tqsi,t_master_skill tms, t_question_skill_map tqsm where ta.id = tqs.assessment_id and" +
" tq.id = tqsi.question_id and tqs.id = tqsi.question_set_id and tms.id = tqsm.master_skill_id and tq.id = tqsm.question_id and" +
" ta.id = " + assessmentid + " and tms.name like '" + tlonamefound + "' and tq.status = 80 and tq.id = " + (qid) + ";");
while (comp_diff.next()) {
expected_comp_diff.add(comp_diff.getInt("comp_difficulty"));
}
}
int rangeLower = 0, rangeUpper = 0;
for (Integer compdiff : expected_comp_diff) {
rangeLower = compdiff - 15;
rangeUpper = compdiff + 15;
System.out.println("Expected Computed Difficulty range " + (compdiff - 15) + "-" + (compdiff + 15));
}
System.out.println();
int questiondifficulty = questionDifficulty();
System.out.println("computed difficulty found " + questiondifficulty);
boolean inRange = false;
if (questiondifficulty >= rangeLower && questiondifficulty <= rangeUpper)
inRange = true;
if (inRange == false) {
Assert.fail("Question not as Expected. " + "Difficulty Found " + questiondifficulty + ". Expected in Range " + rangeLower + "-" + rangeUpper + " from TLO " + tlonamefound + " with Proficiency " + proficiency);
}
} catch (Exception e) {
Assert.fail("", e);
}
}
public void attemptRandomly(int noOfQuestions)
{
try
{
for(int i = 0 ; i<noOfQuestions;i++)
{
try {
String corranswer=Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer=corranswer.charAt(17);
String correctchoice=Character.toString(correctanswer);
System.out.println("Correct Answer "+correctchoice);
if(correctchoice.equals("A") || correctchoice.equals("B") || correctchoice.equals("C") || correctchoice.equals("D")) {
int random = new RandomNumber().generateRandomNumber(0, 100);
if(random > 70) {
if(correctchoice.equals("A") || correctchoice.equals("C") || correctchoice.equals("D")) {
correctchoice = "B";
}
else
correctchoice = "A";
}
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
}
else {
Driver.driver.findElement(By.className("qtn-label")).click();
}
}
catch (Exception e) {
}
int confidencelevel = new RandomNumber().generateRandomNumber(0, 5);
if(confidencelevel!=0)
{
Driver.driver.findElement(By.cssSelector("a[id='"+confidencelevel+"']")).click();//click on confidence level
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
try {
Driver.driver.findElement(By.className("al-notification-message-body"));
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
Driver.driver.findElement(By.className("al-practice-test-submit-button")).click();
Thread.sleep(1000);
}
}
catch (Exception e) {
}
Thread.sleep(500);
try {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
}
catch (Exception e) {
}
Thread.sleep(1000);
}
}
catch(Exception e)
{
Assert.fail("Exception in app helper attemptRandomly in class DiagnosticTest",e);
}
}
public void openLastPracticeTest() {
try {
List<WebElement> allPractice = Driver.driver.findElements(By.cssSelector("span[title='Practice']"));
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", allPractice.get(allPractice.size() - 1));//click on latest created practice test
Thread.sleep(2000);
} catch (Exception e) {
Assert.fail("Exception in App helper openLastPracticeTest in class PracticeTest", e);
}
}
public void attemptPracticeQuesFromEachTLO(int questionsFromEachTLO, String answerChoice, int confidence, boolean useHints, boolean useSolutionText) {
try {
List<String> tlonames = new PracticeTest().tloNames(); //Get TLO names
//List<String> tlosattempted = new ArrayList<String>();
int tlo1cnt = 0;
int tlo2cnt = 0;
int tlo3cnt = 0;
int tlo4cnt = 0;
int tlo5cnt = 0;
int tlo6cnt = 0;
int tlo7cnt = 0;
boolean done = false;
while (done == false) {
String tlonamefound = Driver.driver.findElement(By.className("al-diagtest-skills-evaluted-ul")).getText().substring(2); //TLO from Question Page
System.out.println(tlonamefound);
System.out.println(tlonames.get(4));
if (tlonamefound.equals(tlonames.get(0)))
tlo1cnt++;
if (tlonamefound.equals(tlonames.get(1)))
tlo2cnt++;
if (tlonamefound.equals(tlonames.get(2)))
tlo3cnt++;
if (tlonamefound.equals(tlonames.get(3)))
tlo4cnt++;
if (tlonamefound.equals(tlonames.get(4)))
tlo5cnt++;
if (tlonamefound.equals(tlonames.get(5)))
tlo6cnt++;
if (tlonamefound.equals(tlonames.get(6)))
tlo7cnt++;
//for loop ends
System.out.println(tlo1cnt + " " + tlo2cnt + " " + tlo3cnt + " " + tlo4cnt + " " + tlo5cnt + " " + tlo6cnt + " " + tlo7cnt);
if (tlo1cnt >= questionsFromEachTLO && tlo2cnt >= questionsFromEachTLO && tlo3cnt >= questionsFromEachTLO && tlo4cnt >= questionsFromEachTLO && tlo5cnt >= questionsFromEachTLO && tlo6cnt >= questionsFromEachTLO && tlo7cnt >= questionsFromEachTLO)
done = true;
attemptQuestion(answerChoice, confidence, useHints, useSolutionText);
} //while loop ends
} catch (Exception e) {
Assert.fail("Exception in App helper attemptPracticeQuesFromEachTLO in class PracticeTest", e);
}
}
public void attemptQuestion(String answeroption, int confidencelevel, boolean useHints, boolean useSolutionText) {
try {
if (answeroption.equalsIgnoreCase("skip")) {
if (useHints == true)
Driver.driver.findElement(By.cssSelector("img[title=\"Hint\"]")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
} //logic for skipping questions ends
else if (answeroption.equalsIgnoreCase("correct")) {
String confidence = Integer.toString(confidencelevel);
if (useHints == true)
Driver.driver.findElement(By.cssSelector("img[title=\"Hint\"]")).click();
if (Driver.driver.findElements(By.className("multiple-selection-answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer;
if (corranswer.charAt(17) == '(')
correctanswer = corranswer.charAt(18);
else
correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
String corranswer1 = corranswer;
char correctanswer1 = corranswer1.charAt(22);
String correctchoice1 = Character.toString(correctanswer1);
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
List<WebElement> answer1 = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice1 : answer1) {
if (answerchoice1.getText().trim().equals(correctchoice1)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice1);
break;
}
}
} else if (Driver.driver.findElements(By.className("answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
} else if (Driver.driver.findElements(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']")).size() > 0) {
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String corrcttextanswer = corranswertext.substring(16, lastindex);
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys(corrcttextanswer);
} else if (Driver.driver.findElements(By.className("sbHolder")).size() > 0) {
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String corrcttextanswer = corranswertext.substring(16, lastindex);
Driver.driver.findElement(By.className("sbToggle")).click();
Thread.sleep(2000);
Driver.driver.findElement(By.linkText(corrcttextanswer)).click();
Thread.sleep(5000);
}
Thread.sleep(2000);
if (confidencelevel != 0) {
Driver.driver.findElement(By.cssSelector("a[id='" + confidence + "']")).click();//click on confidence level
Thread.sleep(2000);
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
} //attepting correct answer ends
else {
int recommendation = Driver.driver.findElements(By.className("al-notification-message-wrapper")).size();
if (recommendation > 0) {
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.contains("Looks like you might want to study this objective in WileyPLUS. Go to WileyPLUS for")) {
Thread.sleep(3000);
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("span[id='exit-practice-test-block']")));
//Driver.driver.findElement(By.cssSelector("span[id='exit-practice-test-block']")).click();
}
}
if (useHints == true) {
Driver.driver.findElement(By.cssSelector("img[title=\"Hint\"]")).click();
Thread.sleep(2000);
int hintpopup = Driver.driver.findElements(By.className("al-notification-message-header")).size();
if (hintpopup > 0) {
Driver.driver.findElement(By.xpath("/html/body")).click();
Thread.sleep(2000);
}
}
String confidence = Integer.toString(confidencelevel);
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String corrcttextanswer = corranswertext.substring(16, lastindex);
if (Driver.driver.findElements(By.className("multiple-selection-answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer;
if (corranswer.charAt(17) == '(')
correctanswer = corranswer.charAt(18);
else
correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer); //first correct choice
char correctanswer1 = corranswer.charAt(22);
String correctchoice1 = Character.toString(correctanswer1); //second correct choice
if ((correctchoice.equals("A") && correctchoice1.equals("B")) || (correctchoice.equals("B") && correctchoice1.equals("A"))) {
correctchoice = "C";
correctchoice1 = "D";
} else if (correctchoice.equals("A") && correctchoice1.equals("C") || (correctchoice.equals("C") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "D";
} else if (correctchoice.equals("A") && correctchoice1.equals("D") || (correctchoice.equals("D") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "C";
} else if (correctchoice.equals("A") && correctchoice1.equals("E") || (correctchoice.equals("E") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "C";
} else if (correctchoice.equals("A") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "C";
} else if ((correctchoice.equals("B") && correctchoice1.equals("C")) || (correctchoice.equals("C") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "D";
} else if (correctchoice.equals("B") && correctchoice1.equals("D") || (correctchoice.equals("D") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "C";
} else if (correctchoice.equals("B") && correctchoice1.equals("E") || (correctchoice.equals("E") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "C";
} else if (correctchoice.equals("B") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "C";
} else if ((correctchoice.equals("C") && correctchoice1.equals("D")) || (correctchoice.equals("D") && correctchoice1.equals("C"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if (correctchoice.equals("C") && correctchoice1.equals("E") || (correctchoice.equals("E") && correctchoice1.equals("C"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if (correctchoice.equals("C") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("C"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if ((correctchoice.equals("D") && correctchoice1.equals("E")) || (correctchoice.equals("E") && correctchoice1.equals("D"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if (correctchoice.equals("D") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("D"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if ((correctchoice.equals("E") && correctchoice1.equals("F")) || (correctchoice.equals("F") && correctchoice1.equals("E"))) {
correctchoice = "A";
correctchoice1 = "B";
}
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
List<WebElement> answer1 = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice1 : answer1) {
if (answerchoice1.getText().trim().equals(correctchoice1)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice1);
break;
}
}
} else if (Driver.driver.findElements(By.className("answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
if (correctchoice.equals("A"))
correctchoice = "B";
else if (correctchoice.equals("B"))
correctchoice = "A";
else if (correctchoice.equals("C"))
correctchoice = "D";
else if (correctchoice.equals("D"))
correctchoice = "C";
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
} else if (Driver.driver.findElements(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']")).size() > 0) {
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys(corrcttextanswer + "bh");
} else if (Driver.driver.findElements(By.className("sbHolder")).size() > 0) {
Driver.driver.findElement(By.className("sbToggle")).click();
Thread.sleep(2000);
String values = Driver.driver.findElement(By.cssSelector("ul[class='sbOptions']")).getText();
//values = values.replaceAll("\n", " ");
String[] val = values.split("\n");
for (String element : val) {
if (!element.equals(corrcttextanswer)) {
Driver.driver.findElement(By.linkText(element)).click();
break;
}
}
}
// ((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.xpath("/html/body/div[3]/div/div[2]/div[2]/div[2]/div/div/div[2]/div[2]/div/div/label")));
// Thread.sleep(2000);
Thread.sleep(2000);
if (confidencelevel != 0) {
Driver.driver.findElement(By.cssSelector("a[id='" + confidence + "']")).click();//click on confidence level
Thread.sleep(2000);
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
}
} catch (Exception e) {
Assert.fail("Exception in App helper attemptQuestion in class PracticeTest", e);
}
}
public void submitOnlyQuestion() {
try {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
} catch (Exception e) {
Assert.fail("Exception in App helper submitOnlyQuestion in class PracticeTest", e);
}
}
public void practiceTestAttempt(int confidencelevel, int numberofquestionattempt, String answeroption, boolean useHints, boolean showSolutionText) {
try {
for (int i = 0; i < numberofquestionattempt; i++) {
int random = new RandomNumber().generateRandomNumber(0, 100);
if (random > 50) answeroption = "correct";
else if (random > 20 && random < 50) answeroption = "incorrect";
else answeroption = "skip";
if (answeroption.equalsIgnoreCase("skip")) {
if (useHints == true)
Driver.driver.findElement(By.cssSelector("img[title=\"Hint\"]")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
}
//logic for skipping questions ends
else if (answeroption.equalsIgnoreCase("correct")) {
String confidence = Integer.toString(confidencelevel);
if (useHints == true)
Driver.driver.findElement(By.cssSelector("img[title=\"Hint\"]")).click();
if (Driver.driver.findElements(By.className("multiple-selection-answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer;
if (corranswer.charAt(17) == '(')
correctanswer = corranswer.charAt(18);
else
correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
String corranswer1 = corranswer;
char correctanswer1 = corranswer1.charAt(22);
String correctchoice1 = Character.toString(correctanswer1);
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
List<WebElement> answer1 = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice1 : answer1) {
if (answerchoice1.getText().trim().equals(correctchoice1)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice1);
break;
}
}
} else if (Driver.driver.findElements(By.className("answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
} else if (Driver.driver.findElements(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']")).size() > 0) {
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String corrcttextanswer = corranswertext.substring(16, lastindex);
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys(corrcttextanswer);
} else if (Driver.driver.findElements(By.className("sbHolder")).size() > 0) {
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String corrcttextanswer = corranswertext.substring(16, lastindex);
Driver.driver.findElement(By.className("sbToggle")).click();
Thread.sleep(2000);
Driver.driver.findElement(By.linkText(corrcttextanswer)).click();
Thread.sleep(5000);
}
Thread.sleep(2000);
if (confidencelevel != 0) {
Driver.driver.findElement(By.cssSelector("a[id='" + confidence + "']")).click();//click on confidence level
Thread.sleep(2000);
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
}
//attepting correct answer ends
else {
if (useHints == true)
Driver.driver.findElement(By.cssSelector("img[title=\"Hint\"]")).click();
Thread.sleep(2000);
int hintpopup = Driver.driver.findElements(By.className("al-notification-message-header")).size();
if (hintpopup > 0) {
Driver.driver.findElement(By.xpath("/html/body")).click();
Thread.sleep(2000);
}
String confidence = Integer.toString(confidencelevel);
String corranswertext = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
int lastindex = corranswertext.length();
String corrcttextanswer = corranswertext.substring(16, lastindex);
if (Driver.driver.findElements(By.className("multiple-selection-answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer;
if (corranswer.charAt(17) == '(')
correctanswer = corranswer.charAt(18);
else
correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer); //first correct choice
char correctanswer1 = corranswer.charAt(22);
String correctchoice1 = Character.toString(correctanswer1); //second correct choice
System.out.println("Correct answer 1 in attemptincorrect in muliple chocce " + correctchoice);
System.out.println("Correct answer 2 in attemptincorrect in muliple chocce " + correctchoice1);
if ((correctchoice.equals("A") && correctchoice1.equals("B")) || (correctchoice.equals("B") && correctchoice1.equals("A"))) {
correctchoice = "C";
correctchoice1 = "D";
} else if (correctchoice.equals("A") && correctchoice1.equals("C") || (correctchoice.equals("C") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "D";
} else if (correctchoice.equals("A") && correctchoice1.equals("D") || (correctchoice.equals("D") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "C";
} else if (correctchoice.equals("A") && correctchoice1.equals("E") || (correctchoice.equals("E") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "C";
} else if (correctchoice.equals("A") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("A"))) {
correctchoice = "B";
correctchoice1 = "C";
} else if ((correctchoice.equals("B") && correctchoice1.equals("C")) || (correctchoice.equals("C") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "D";
} else if (correctchoice.equals("B") && correctchoice1.equals("D") || (correctchoice.equals("D") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "C";
} else if (correctchoice.equals("B") && correctchoice1.equals("E") || (correctchoice.equals("E") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "C";
} else if (correctchoice.equals("B") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("B"))) {
correctchoice = "A";
correctchoice1 = "C";
} else if ((correctchoice.equals("C") && correctchoice1.equals("D")) || (correctchoice.equals("D") && correctchoice1.equals("C"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if (correctchoice.equals("C") && correctchoice1.equals("E") || (correctchoice.equals("E") && correctchoice1.equals("C"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if (correctchoice.equals("C") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("C"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if ((correctchoice.equals("D") && correctchoice1.equals("E")) || (correctchoice.equals("E") && correctchoice1.equals("D"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if (correctchoice.equals("D") && correctchoice1.equals("F") || (correctchoice.equals("F") && correctchoice1.equals("D"))) {
correctchoice = "A";
correctchoice1 = "B";
} else if ((correctchoice.equals("E") && correctchoice1.equals("F")) || (correctchoice.equals("F") && correctchoice1.equals("E"))) {
correctchoice = "A";
correctchoice1 = "B";
}
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
List<WebElement> answer1 = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice1 : answer1) {
if (answerchoice1.getText().trim().equals(correctchoice1)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice1);
break;
}
}
} else if (Driver.driver.findElements(By.className("answer-choice-label-wrapper")).size() > 0) {
String corranswer = Driver.driver.findElement(By.id("show-debug-correct-answer-block")).getText();
char correctanswer = corranswer.charAt(17);
String correctchoice = Character.toString(correctanswer);
if (correctchoice.equals("A"))
correctchoice = "B";
else if (correctchoice.equals("B"))
correctchoice = "A";
else if (correctchoice.equals("C"))
correctchoice = "D";
else if (correctchoice.equals("D"))
correctchoice = "C";
List<WebElement> answer = Driver.driver.findElements(By.className("qtn-label"));
for (WebElement answerchoice : answer) {
if (answerchoice.getText().trim().equals(correctchoice)) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", answerchoice);
break;
}
}
} else if (Driver.driver.findElements(By.cssSelector("span[class='input-tag-wrapper question-element-wrapper']")).size() > 0) {
Driver.driver.findElement(By.cssSelector("input[id='1']")).sendKeys(corrcttextanswer + "bh");
} else if (Driver.driver.findElements(By.className("sbHolder")).size() > 0) {
Driver.driver.findElement(By.className("sbToggle")).click();
Thread.sleep(2000);
String values = Driver.driver.findElement(By.cssSelector("ul[class='sbOptions']")).getText();
//values = values.replaceAll("\n", " ");
String[] val = values.split("\n");
for (String element : val) {
if (!element.equals(corrcttextanswer)) {
Driver.driver.findElement(By.linkText(element)).click();
break;
}
}
}
// ((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.xpath("/html/body/div[3]/div/div[2]/div[2]/div[2]/div/div/div[2]/div[2]/div/div/label")));
// Thread.sleep(2000);
Thread.sleep(2000);
if (confidencelevel != 0) {
Driver.driver.findElement(By.cssSelector("a[id='" + confidence + "']")).click();//click on confidence level
Thread.sleep(2000);
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
int noticesize = Driver.driver.findElements(By.className("al-notification-message-body")).size();
if (noticesize == 1)
{
String notice = Driver.driver.findElement(By.className("al-notification-message-body")).getText();
if (notice.equals("You will build your proficiency faster if you say how confident you feel about the question before answering.")) {
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Submit\"]")));
Thread.sleep(2000);
}
}
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("img[title=\"Next\"]")));
Thread.sleep(2000);
}
}
Driver.driver.findElement(By.className("al-quit-diag-test-icon")).click();
Thread.sleep(1000);
Driver.driver.findElement(By.className("al-diag-test-continue-later")).click();
Thread.sleep(2000);
} catch (Exception e) {
Assert.fail("Exception in App helper method AdaptiveTestInBetween in class practicetest", e);
}
}
//@author Sumit
//open a TLO level practice test based on Index(just passed the index of TLO needs to be opened
public void openTLOLevelPracticeTestBasedOnIndex(int tloIndex) {
try {
List<WebElement> tloList = Driver.driver.findElements(By.className("al-terminal-objective-title"));
new Actions(Driver.driver).moveToElement(tloList.get(tloIndex)).build().perform();
List<WebElement> allPractice = Driver.driver.findElements(By.cssSelector("div[title='Practice']"));
for (WebElement practice : allPractice) {
if (practice.isDisplayed() == true) {
practice.click();
Thread.sleep(2000);
break;
}
}
} catch (Exception e) {
Assert.fail("Exception in App helper method openTLOLevelPracticeTestBasedOnIndex in class PracticeTest", e);
}
}
public void startTestLS(int testNo) {
try {
//Driver.driver.findElement(By.cssSelector("span[title='Practice']")).click();
if(testNo == 1) {
(new WebDriverWait(Driver.driver, 12))
.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Personalized Practice - Ch 3: Así es mi familia")));
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.linkText("Personalized Practice - Ch 3: Así es mi familia")));
}
else if(testNo == 2) {
(new WebDriverWait(Driver.driver, 12))
.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Personalized Practice - Ch 2: The Chemical Foundation of Life")));
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.linkText("Personalized Practice - Ch 2: The Chemical Foundation of Life")));
}
Thread.sleep(3000);
} catch (Exception e) {
Assert.fail("Exception in starting the practice test", e);
}
}
//starting static practice test like the one for ls course type
public void startStaticPracticeTestLS() {
try {
//Driver.driver.findElement(By.cssSelector("span[title='Practice']")).click();
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("a[data-type='static_assessment']")));
Thread.sleep(3000);
} catch (Exception e) {
Assert.fail("Exception in starting the practice test", e);
}
}
public void attemptCorrectAnswerLS(int numberofQuestions) {
try {
boolean skipOthers;
int random = new RandomNumber().generateRandomNumber(0, 100);
for(int i=0 ;i<numberofQuestions;i++) {
System.out.println("Question No "+i);
skipOthers = false;
try {
if(random <= 60) {
(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.className("choice-value"))).click();
}
else {
Driver.driver.findElements(By.className("choice-value")).get(1).click();
}
} catch (Exception e) {
skipOthers = true;
}
/*if (Driver.driver.findElements(By.className("preview-multiple-select-answer-choice")).size() > 0)
new AttemptDiagnosticQuestion().attemptMultipleSelection("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.className("preview-single-selection-answer-choices")).size() > 0)
new AttemptDiagnosticQuestion().attemptMultipleChoice("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.className("true-false-answer-choices")).size() > 0)
new AttemptDiagnosticQuestion().attemptTrueFalse("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.cssSelector("div[class='text-entry-input-wrapper visible_redactor_input_wrapper']")).size() > 0)
new AttemptDiagnosticQuestion().attemptTextEntry("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.cssSelector("div[class='text-entry-dropdown-wrapper visible_redactor_input_wrapper']")).size() > 0)
new AttemptDiagnosticQuestion().attemptTextDropDown("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.className("numeric_entry_student_title")).size() > 0)
new AttemptDiagnosticQuestion().attemptNumericEntryWithUnits("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.cssSelector("div[class='text-entry-input-wrapper visible_redactor_input_wrapper']")).size() > 0)
new AttemptDiagnosticQuestion().attemptAdvancedNumeric("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.cssSelector("div[class='symb-notation-math-edit-icon-preview']")).size() > 0)
new AttemptDiagnosticQuestion().attemptExpressionEvaluator("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
else if (Driver.driver.findElements(By.cssSelector("div[id='html-editor-non-draggable']")).size() > 0)
new AttemptDiagnosticQuestion().attemptEssayType("correct", false, false, new RandomNumber().generateRandomNumber(1, 4), "");
*/
try {
(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.id("submit-practice-question-button"))).click();
}
catch (Exception e) {
}
// ((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.id("submit-practice-question-button")));
try {
Driver.driver.findElement(By.className("al-notification-message-body"));
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
if (Driver.driver.findElement(By.id("next-practice-question-button")).isDisplayed() == true) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.id("next-practice-question-button")));
} else {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.id("submit-practice-question-button")));
}
}
catch (Exception e) {
}
try {
(new WebDriverWait(Driver.driver, 4))
.until(ExpectedConditions.presenceOfElementLocated(By.id("next-practice-question-button"))).click();
}
catch (Exception e) {
}
}
}
catch (Exception e) {
Assert.fail("Exception in App helper AttemptCorrectAnswer in class PracticeTest", e);
}
}
public void attemptStaticPractice(int numberofQuestions)
{
try {
boolean skipOthers;
int random = new RandomNumber().generateRandomNumber(0, 100);
for (int i = 0; i < numberofQuestions; i++) {
System.out.println("Question No " + i);
skipOthers = false;
try {
if (random <= 60) {
(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.className("choice-value"))).click();
} else {
Driver.driver.findElements(By.className("choice-value")).get(1).click();
}
} catch (Exception e) {
try {
(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.className("true-false-student-answer-label"))).click();
}
catch (Exception e1) {
}
}
try {
(new WebDriverWait(Driver.driver, 2))
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[value='Submit Answer']"))).click();
}
catch (Exception e) {
}
try {
Driver.driver.findElement(By.className("al-notification-message-body"));
Driver.driver.findElement(By.cssSelector("div[id='close-al-notification-dialog']")).click();
if (Driver.driver.findElement(By.cssSelector("input[value='Next Question']")).isDisplayed() == true) {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("input[value='Next Question']")));
} else {
((JavascriptExecutor) Driver.driver).executeScript("arguments[0].click();", Driver.driver.findElement(By.cssSelector("input[value='Submit Answer']")));
}
}
catch (Exception e) {
}
try {
(new WebDriverWait(Driver.driver, 4))
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[value='Next Question']"))).click();
}
catch (Exception e) {
}
}
}
catch (Exception e) {
}
}
}
| true |
d1226a367ba786dc99fcae53dfc16d0f2fed7fe7 | Java | NKCS-XSY/engpker | /engpker/src/main/java/edu/nk/pker/model/po/QuestionType.java | UTF-8 | 1,902 | 2.328125 | 2 | [] | no_license | package edu.nk.pker.model.po;
// Generated 2015-5-20 10:08:13 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* QuestionType generated by hbm2java
*/
@Entity
@Table(name = "question_type", catalog = "pker")
public class QuestionType implements java.io.Serializable {
private Integer id;
private String name;
private boolean subjective;
private Set<Question> questions = new HashSet<Question>(0);
public QuestionType() {
}
public QuestionType(String name, boolean subjective) {
this.name = name;
this.subjective = subjective;
}
public QuestionType(String name, boolean subjective, Set<Question> questions) {
this.name = name;
this.subjective = subjective;
this.questions = questions;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "name", nullable = false, length = 20)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "subjective", nullable = false)
public boolean isSubjective() {
return this.subjective;
}
public void setSubjective(boolean subjective) {
this.subjective = subjective;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "questionType")
public Set<Question> getQuestions() {
return this.questions;
}
public void setQuestions(Set<Question> questions) {
this.questions = questions;
}
}
| true |
c9c2f0062db53aa5c310e52100d476b643a22cee | Java | rickshunph/distributed_system | /assignment4server/RabbitMq/src/main/java/RecvMT.java | UTF-8 | 3,876 | 2.375 | 2 | [] | no_license | import com.github.f4b6a3.uuid.UuidCreator;
import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.MessageProperties;
import io.swagger.client.model.LiftRide;
import java.io.IOException;
import java.util.Arrays;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class RecvMT {
// persistent
private final static String QUEUE_NAME = "threadExQ";
// non-persistent
// private final static String QUEUE_NAME = "threadExQ-non";
private static final int NUM_OF_THREAD = 20;
private static final Logger logger = LogManager.getLogger(RecvMT.class);
public static void main(String[] argv) throws Exception {
LiftRideDao liftRideDAO = new LiftRideDao();
// DynamoDAO dynamoDAO = new DynamoDAO();
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("username");
factory.setPassword("password");
factory.setVirtualHost("/");
factory.setHost("localhost");
final Connection connection = factory.newConnection();
Runnable runnable = () -> {
try {
final Channel channel = connection.createChannel();
// non-persistent
// channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// persistent
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
// System.out.println("ok: " + ok);
// max one message per receiver
// manuel
channel.basicQos(1);
System.out.println(" [*] (" + NUM_OF_THREAD +
") Threads waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
try {
String message = new String(delivery.getBody(), "UTF-8");
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
System.out.println(
"Callback thread ID = " + Thread.currentThread().getId() + " Received '" + message
+ "'");
String[] splitMessage = message.split("\n");
// System.out.println(Arrays.toString(splitMessage));
if (splitMessage.length != 5) {
// System.out.println("Error! Invalid length of input message: " + message);
logger.error("Trouble! message: " + message);
} else {
LiftRide newLiftRide = new LiftRide();
newLiftRide.setResortID(splitMessage[0]);
newLiftRide.setDayID(splitMessage[1]);
newLiftRide.setSkierID(splitMessage[2]);
newLiftRide.setTime(splitMessage[3]);
newLiftRide.setLiftID(splitMessage[4]);
liftRideDAO.createLiftRide(newLiftRide);
// dynamoDAO.createLiftRide(newLiftRide);
// dynamoDAO.createLiftRideWithUuid(newLiftRide);
logger.debug("message: (" + message + " ) got!");
}
} catch (Exception e) {
logger.error("Trouble! ", e);
}
};
// process messages
// manuel ack
channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { });
// auto ack
// channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
} catch (IOException ex) {
logger.log(Level.FATAL, ex);
}
};
// start threads and block to receive messages
for (int i = 0; i < NUM_OF_THREAD; i++) {
Thread recv = new Thread(runnable);
recv.start();
}
// Thread recv1 = new Thread(runnable);
// Thread recv2 = new Thread(runnable);
// Thread recv3 = new Thread(runnable);
// recv1.start();
// recv2.start();
// recv3.start();
}
} | true |
0ea122f11e3e70acffd515ada1ce94ebd700e3f3 | Java | RicardoBenetero/academiaDespo | /HandsOnExcecoesNaPratica/src/Video1.java | UTF-8 | 493 | 2.921875 | 3 | [] | no_license |
public class Video1 {
public double porcao(double valor, double porCento) throws ForaDoIntervaloException {
if (porCento > 100 || porCento < 0) {
throw new ForaDoIntervaloException(String.valueOf(porCento));
}
return valor * porCento / 100;
}
public static void main(String[] args) {
Video1 video1 = new Video1();
try {
video1.porcao(1000, -56);
} catch (ForaDoIntervaloException e) {
e.printStackTrace();
}
}
}
| true |
10cb580912e3e5ea602b89861ec7f3d54b2581d3 | Java | chezkibot/Java-Project | /src/primitives/Limits.java | UTF-8 | 2,268 | 2.625 | 3 | [] | no_license | /*************************************************
* class
* Limits
* contains limit for geometry/s
* double value for Coordinates on x,y,x
* two for each (x for 1 to 7,y from 3,8, z from 9,-4)
**************************************************/
package primitives;
import geometries.Geometry;
import java.util.ArrayList;
public class Limits {
private double xMaxLimit;
private double xMinLimit;
private double yMaxLimit;
private double yMinLimit;
private double zMaxLimit;
private double zMinLimit;
// ***************** Constructors ********************** //
public Limits()
{
this.xMaxLimit = Double.MAX_VALUE;
this.xMinLimit = Double.MIN_VALUE;
this.yMaxLimit = Double.MAX_VALUE;
this.yMinLimit = Double.MIN_VALUE;
this.zMaxLimit = Double.MAX_VALUE;
this.zMinLimit = Double.MIN_VALUE;
}
public Limits(double xMaxLimit, double xMinLimit, double yMaxLimit, double yMinLimit, double zMaxLimit, double zMinLimit) {
this.xMaxLimit = xMaxLimit;
this.xMinLimit = xMinLimit;
this.yMaxLimit = yMaxLimit;
this.yMinLimit = yMinLimit;
this.zMaxLimit = zMaxLimit;
this.zMinLimit = zMinLimit;
}
// ***************** Getters/Setters ********************** //
public double getxMaxLimit() {
return xMaxLimit;
}
public void setxMaxLimit(int xMaxLimit) {
this.xMaxLimit = xMaxLimit;
}
public double getxMinLimit() {
return xMinLimit;
}
public void setxMinLimit(int xMinLimit) {
this.xMinLimit = xMinLimit;
}
public double getyMaxLimit() {
return yMaxLimit;
}
public void setyMaxLimit(int yMaxLimit) {
this.yMaxLimit = yMaxLimit;
}
public double getyMinLimit() {
return yMinLimit;
}
public void setyMinLimit(int yMinLimit) {
this.yMinLimit = yMinLimit;
}
public double getzMaxLimit() {
return zMaxLimit;
}
public void setzMaxLimit(int zMaxLimit) {
this.zMaxLimit = zMaxLimit;
}
public double getzMinLimit() {
return zMinLimit;
}
public void setzMinLimit(int zMinLimit) {
this.zMinLimit = zMinLimit;
}
}
| true |
abd0ac9c70f0739b69b6a1d5354ba0eac59ad437 | Java | Devil-ReaperL/Trash | /JavaEE项目成果物(2)/04 源码/cloud_oa/src/com/icss/oa/login/action/LoginAction.java | UTF-8 | 3,096 | 2.1875 | 2 | [] | no_license | package com.icss.oa.login.action;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.icss.oa.common.BaseAction;
import com.icss.oa.login.service.UserService;
import com.icss.oa.system.pojo.Employee;
import com.icss.oa.common.MyRealm;
import com.opensymphony.xwork2.ModelDriven;
@Controller
@Scope("prototype")
@ParentPackage("struts-default")
@Namespace("/login")
public class LoginAction extends BaseAction implements ModelDriven<Employee> {
private Employee emp = new Employee();
@Autowired
UserService service;
@Autowired
private MyRealm realm;
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
/**
* 提供ajax接口,做异步用户名密码验证
* @return
* @throws IOException
*/
@Action(value = "login")
public String login() throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String security = new Sha256Hash(emp.getPassword(), "icssoa", 10).toBase64();
emp.setPassword(security);
// 封装用户名和密码
UsernamePasswordToken token = new UsernamePasswordToken(emp.getEmpNum(),security);
// 设置RememberMe
token.setRememberMe(false);
/*通过shiro登录*/
Subject currentUser = SecurityUtils.getSubject();
try {
currentUser.login(token);
} catch (UnknownAccountException e) {
out.write("nw");
System.out.print("用户名错误");
return null;
} catch (IncorrectCredentialsException e) {
out.write("pw");
System.out.print("密码错误");
return null;
}
//清理用户权限缓存
realm.removeUserCache(emp.getEmpNum());
//在session范围中存储用户数据
request.getSession().setAttribute("empnum", emp.getEmpNum());
Employee queryemp= service.empObj(emp.getEmpNum());
request.getSession().setAttribute("queryemp", queryemp);
//获得session的数据
String username = (String) request.getSession().getAttribute("empnum");
Employee empele = (Employee) request.getSession().getAttribute("queryemp");
System.out.println(username);
String elename = empele.getEmpName();
System.out.println(elename);
out.write("y");
return null;
}
@Override
public Employee getModel() {
// TODO Auto-generated method stub
return emp;
}
} | true |
02799acf72ff09433ece3f92ac459beb855d8c25 | Java | jonhare/nativelibs4java | /libraries/BridJ/src/main/java/org/bridj/util/AnnotationUtils.java | UTF-8 | 5,211 | 2.046875 | 2 | [] | no_license | /*
* BridJ - Dynamic and blazing-fast native interop for Java.
* http://bridj.googlecode.com/
*
* Copyright (c) 2010-2013, Olivier Chafik (http://ochafik.com/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Olivier Chafik nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.bridj.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.lang.reflect.Proxy;
import org.bridj.ann.Forwardable;
/**
* Util methods for annotations (inheritable annotations, forwarded annotations,
* annotations from AnnotatedElements and/or direct annotation arrays...)
*
* @author ochafik
*/
public class AnnotationUtils {
public static <A extends Annotation> A getInheritableAnnotation(Class<A> ac, AnnotatedElement m, Annotation... directAnnotations) {
return getAnnotation(ac, true, m, directAnnotations);
}
public static <A extends Annotation> A getAnnotation(Class<A> ac, AnnotatedElement m, Annotation... directAnnotations) {
return getAnnotation(ac, false, m, directAnnotations);
}
private static boolean isForwardable(Class<? extends Annotation> ac) {
return ac.isAnnotationPresent(Forwardable.class);
}
public static boolean isAnnotationPresent(Class<? extends Annotation> ac, Annotation... annotations) {
return isAnnotationPresent(ac, isForwardable(ac), annotations);
}
private static boolean isAnnotationPresent(Class<? extends Annotation> ac, boolean isForwardable, Annotation... annotations) {
for (Annotation ann : annotations) {
if (ac.isInstance(ann)) {
return true;
}
if (isForwardable) {
if (ann.annotationType().isAnnotationPresent(ac)) {
return true;
}
}
}
return false;
}
public static boolean isAnnotationPresent(Class<? extends Annotation> ac, AnnotatedElement m, Annotation... directAnnotations) {
boolean isForwardable = isForwardable(ac);
if (m != null) {
if (isForwardable) {
if (isAnnotationPresent(ac, true, m.getAnnotations())) {
return true;
}
} else {
if (m.isAnnotationPresent(ac)) {
return true;
}
}
}
if (directAnnotations != null) {
return isAnnotationPresent(ac, isForwardable, directAnnotations);
}
return false;
}
private static <A extends Annotation> A getAnnotation(Class<A> ac, boolean inherit, AnnotatedElement m, Annotation... directAnnotations) {
if (directAnnotations != null) {
for (Annotation ann : directAnnotations) {
if (ac.isInstance(ann)) {
return ac.cast(ann);
}
}
}
if (m == null) {
return null;
}
A a = m.getAnnotation(ac);
if (a != null) {
return a;
}
if (inherit) {
if (m instanceof Member) {
return getAnnotation(ac, inherit, ((Member) m).getDeclaringClass());
}
if (m instanceof Class<?>) {
Class<?> c = (Class<?>) m, dc = c.getDeclaringClass();
Class p = c.getSuperclass();
while (p != null) {
a = getAnnotation(ac, true, p);
if (a != null) {
return a;
}
p = p.getSuperclass();
}
if (dc != null) {
return getAnnotation(ac, inherit, dc);
}
}
}
return null;
}
}
| true |
0b097957194c180e6cd3a6733805f40be526d1fe | Java | SurabheeSinha/DonateForGood | /app/src/main/java/com/surabheesinha/donateforgood/Model/JsonRespProposal.java | UTF-8 | 619 | 1.882813 | 2 | [] | no_license | package com.surabheesinha.donateforgood.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by surabheesinha on 10/26/18.
*/
public class JsonRespProposal {
@SerializedName("proposals")
@Expose
public ProjectsModel[] proposals;
public ProjectsModel[] getProposals() {
return proposals;
}
/*public List<ProjectsModel> proposals ;
public List<ProjectsModel> getProposals() {
return proposals;
}
public void setProposals(List<ProjectsModel> proposals) {
this.proposals = proposals;
}*/
}
| true |
7dcbc0ce1ffbb7bd3872d558a1a69b3e29d68b6a | Java | lemontia/mockitoTest | /src/main/java/kr/sample/demo/entity/Member.java | UTF-8 | 473 | 2.4375 | 2 | [] | no_license | package kr.sample.demo.entity;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import javax.persistence.*;
@Entity
@Table(name = "Member")
@Getter
@ToString
public class Member {
@Id @GeneratedValue
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
@Builder
public Member(String name, Integer age) {
this.name = name;
this.age = age;
}
}
| true |
84d32d47ea43cf07494d527675c4f93ed845b71f | Java | openlookeng/hetu-core | /presto-spi/src/test/java/io/prestosql/spi/plan/SetOperationNodeTest.java | UTF-8 | 3,114 | 1.960938 | 2 | [] | no_license | /*
* 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 io.prestosql.spi.plan;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import org.mockito.Mock;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.testng.Assert.assertEquals;
public class SetOperationNodeTest
{
@Mock
private PlanNodeId mockId;
private SetOperationNode setOperationNodeUnderTest;
@BeforeMethod
public void setUp() throws Exception
{
initMocks(this);
setOperationNodeUnderTest = new SetOperationNode(mockId, Arrays.asList(),
ImmutableListMultimap.of(new Symbol("name"), new Symbol("name")), Arrays.asList(new Symbol("name"))) {
@Override
public PlanNode replaceChildren(List<PlanNode> newChildren)
{
return null;
}
};
}
@Test
public void testGetOutputSymbols() throws Exception
{
// Setup
final List<Symbol> expectedResult = Arrays.asList(new Symbol("name"));
// Run the test
final List<Symbol> result = setOperationNodeUnderTest.getOutputSymbols();
// Verify the results
assertEquals(expectedResult, result);
}
@Test
public void testGetSymbolMapping() throws Exception
{
// Setup
final ListMultimap<Symbol, Symbol> expectedResult = ImmutableListMultimap.of(new Symbol("name"),
new Symbol("name"));
// Run the test
final ListMultimap<Symbol, Symbol> result = setOperationNodeUnderTest.getSymbolMapping();
// Verify the results
assertEquals(expectedResult, result);
}
@Test
public void testSourceOutputLayout() throws Exception
{
// Setup
final List<Symbol> expectedResult = Arrays.asList(new Symbol("name"));
// Run the test
final List<Symbol> result = setOperationNodeUnderTest.sourceOutputLayout(0);
// Verify the results
assertEquals(expectedResult, result);
}
@Test
public void testSourceSymbolMap() throws Exception
{
// Setup
final Map<Symbol, Symbol> expectedResult = new HashMap<>();
// Run the test
final Map<Symbol, Symbol> result = setOperationNodeUnderTest.sourceSymbolMap(0);
// Verify the results
assertEquals(expectedResult, result);
}
}
| true |
efa1c09e69f79771b4ce012b185ca35a578a0227 | Java | coolamit25vyas/microservice | /microservice2/microservice2/src/main/java/microservice2/config/EchoConfig.java | UTF-8 | 933 | 1.921875 | 2 | [] | no_license | package microservice2.config;
import org.springframework.cloud.sleuth.SpanExtractor;
import org.springframework.cloud.sleuth.SpanInjector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import microservice2.SpanExtractor.CustomHttpServletRequestSpanExtractor;
import microservice2.SpanExtractor.CustomHttpServletResponseSpanInjector;
@Configuration
public class EchoConfig {
@Bean
@Primary
SpanExtractor<HttpServletRequest> customHttpServletRequestSpanExtractor() {
return new CustomHttpServletRequestSpanExtractor();
}
@Bean
@Primary
SpanInjector<HttpServletResponse> customHttpServletResponseSpanInjector() {
return new CustomHttpServletResponseSpanInjector();
}
} | true |
5f7239007f150b3052722da01e702c87e17b7860 | Java | SAO-Project/Minor-Bank-System | /simple/src/app/IBankDB.java | UTF-8 | 3,366 | 3 | 3 | [] | no_license | package app;
import java.util.Collection;
import java.util.Optional;
/**
* @author Alex Avila
* @version 1.0
* @since 10/10/20
* This interface was mostly implemented to be able to abstract the storage implementation and only cares
* about getting the right information and being able to update and create this information.
*/
public interface IBankDB {
/**
* add a customer to the customer hash table which key should be their full name
* @param customer
*/
void addCustomer(Customer customer);
/**
* gets the collection of customers by taking tha values of the customer hash tables.
* @return returns a list of customers
*/
Collection<Customer> getCustomers();
/**
* Checks if the bank contains a customer of a certain name
* @param fullName name of the seachee customer
* @return returns whether if the customer is in the bank or not
*/
boolean containsCustomer(String fullName);
/**
* get a customer using their respective full name if the name is in the bank
* @param fullName the name of the Customer
* @return returns the Customer of the name fullName
*/
Optional<Customer> getCustomer(String fullName);
/**
* Get a customer using their respective
* @param id
* @return
*/
Optional<Customer> getCustomer(int id);
/**
* checks if the bank contains a Checkings account
* @param accountNumber uses account number to query account
* @return returns the account of certain account number
*/
boolean containsChecking(int accountNumber);
/**
* checks if the bank contains a Saving account
* @param accountNumber uses account number to query account
* @return returns the account of certain account number
*/
boolean containsSavings(int accountNumber);
/**
* checks if the bank contains a Credit account
* @param accountNumber uses account number to query account
* @return returns the account of certain account number
*/
boolean containsCredit(int accountNumber);
/**
* Checks if the bank contains this account.
* @param accountNumber uses account number to query account.
* @return returns the account of certain account number.
*/
boolean containsAccountNumber(int accountNumber);
/**
* gets account using its account number
* @param accountNumber queries account using account number
* @return returns the respective account of the account number
*/
Optional<Account> getAccount(int accountNumber);
/**
* adds a transactions that was made when the users does a transaction
* @param transaction the transaction information message of the Customer to be added
*/
void addTransaction(Transaction transaction);
/**
* get all the transactions made by all the Customers in the bank
* @return return a list of all the transactions
*/
Collection<Transaction> getTransactions();
/**
* get all the transactions of a certain customer
* @param customer the customer to get the transactions from
* @return return a list of all customer transactions
*/
Collection<Transaction> getTransactions(Customer customer);
/**
* get the bank statement of an specific customer
* @param customer the bankStatement's customer
* @return return the bank statement of the user.
*/
Optional<BankStatement> getBankStatement(Customer customer);
/**
* Get next available ID.
* @return Next available ID.
*/
int getNextId();
}
| true |
e0d5afa053a1907b2406b99f97cf80ab2be98162 | Java | bitsofinfo/hazelcast-consul-discovery-spi | /src/main/java/org/bitsofinfo/hazelcast/discovery/consul/ConsulDiscoveryStrategyFactory.java | UTF-8 | 1,962 | 1.9375 | 2 | [
"Apache-2.0"
] | permissive | package org.bitsofinfo.hazelcast.discovery.consul;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import com.hazelcast.config.properties.PropertyDefinition;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.discovery.DiscoveryNode;
import com.hazelcast.spi.discovery.DiscoveryStrategy;
import com.hazelcast.spi.discovery.DiscoveryStrategyFactory;
public class ConsulDiscoveryStrategyFactory implements DiscoveryStrategyFactory {
private static final Collection<PropertyDefinition> PROPERTIES =
Arrays.asList(new PropertyDefinition[]{
ConsulDiscoveryConfiguration.CONSUL_HOST,
ConsulDiscoveryConfiguration.CONSUL_PORT,
ConsulDiscoveryConfiguration.CONSUL_SERVICE_NAME,
ConsulDiscoveryConfiguration.CONSUL_HEALTHY_ONLY,
ConsulDiscoveryConfiguration.CONSUL_SERVICE_TAGS,
ConsulDiscoveryConfiguration.CONSUL_REGISTRATOR,
ConsulDiscoveryConfiguration.CONSUL_REGISTRATOR_CONFIG,
ConsulDiscoveryConfiguration.CONSUL_DISCOVERY_DELAY_MS,
ConsulDiscoveryConfiguration.CONSUL_ACL_TOKEN,
ConsulDiscoveryConfiguration.CONSUL_SSL_ENABLED,
ConsulDiscoveryConfiguration.CONSUL_SSL_SERVER_CERT_FILE_PATH,
ConsulDiscoveryConfiguration.CONSUL_SSL_SERVER_CERT_BASE64,
ConsulDiscoveryConfiguration.CONSUL_SSL_SERVER_HOSTNAME_VERIFY
});
public Class<? extends DiscoveryStrategy> getDiscoveryStrategyType() {
// Returns the actual class type of the DiscoveryStrategy
// implementation, to match it against the configuration
return ConsulDiscoveryStrategy.class;
}
public Collection<PropertyDefinition> getConfigurationProperties() {
return PROPERTIES;
}
public DiscoveryStrategy newDiscoveryStrategy(DiscoveryNode discoveryNode,
ILogger logger,
Map<String, Comparable> properties ) {
return new ConsulDiscoveryStrategy( discoveryNode, logger, properties );
}
}
| true |
5c642edfaa20c4e74004b6320c4ba52da14ec487 | Java | jasem41/android-Quran | /app/src/main/java/bego/com/alqowyy/db/surah/SurahHelper.java | UTF-8 | 3,666 | 2.265625 | 2 | [] | no_license | package bego.com.alqowyy.db.surah;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import bego.com.alqowyy.model.ItemSurah;
import static android.provider.MediaStore.Audio.Playlists.Members._ID;
import static bego.com.alqowyy.db.surah.DbSurah.SurahColumns.CHAPTERID;
import static bego.com.alqowyy.db.surah.DbSurah.SurahColumns.SURANAME;
import static bego.com.alqowyy.db.surah.DbSurah.SurahColumns.SURANAME_ID;
import static bego.com.alqowyy.db.surah.DbSurah.TABLE_NAME;
public class SurahHelper {
private Context c;
private DbSurahHelper dbSurahHelper;
private SQLiteDatabase database;
public SurahHelper(Context c) {
this.c = c;
}
public SurahHelper open() throws SQLException {
dbSurahHelper = new DbSurahHelper(c);
database = dbSurahHelper.getWritableDatabase();
return this;
}
public void close() {
dbSurahHelper.close();
}
public ArrayList<ItemSurah> getByKey(String param) {
String result = "";
Cursor cursor = database.query(TABLE_NAME, null, SURANAME_ID + " LIKE ?", new String[]{'%' + param + '%'}, null, null, _ID + " ASC", null);
cursor.moveToFirst();
ArrayList<ItemSurah> arrayList = new ArrayList<>();
ItemSurah itemSurah;
if (cursor.getCount() > 0) {
do {
itemSurah = new ItemSurah();
itemSurah.setId(cursor.getInt(cursor.getColumnIndexOrThrow(_ID)));
itemSurah.setChapterid(cursor.getString(cursor.getColumnIndexOrThrow(CHAPTERID)));
itemSurah.setSuraname(cursor.getString(cursor.getColumnIndexOrThrow(SURANAME)));
itemSurah.setSuraname_id(cursor.getString(cursor.getColumnIndexOrThrow(SURANAME_ID)));
arrayList.add(itemSurah);
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
cursor.close();
return arrayList;
}
public ArrayList<ItemSurah> getAllData() {
String result = "";
Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, _ID + " ASC", null);
cursor.moveToFirst();
ArrayList<ItemSurah> arrayList = new ArrayList<>();
ItemSurah itemSurah;
if (cursor.getCount() > 0) {
do {
itemSurah = new ItemSurah();
itemSurah.setId(cursor.getInt(cursor.getColumnIndexOrThrow(_ID)));
itemSurah.setChapterid(cursor.getString(cursor.getColumnIndexOrThrow(CHAPTERID)));
itemSurah.setSuraname(cursor.getString(cursor.getColumnIndexOrThrow(SURANAME)));
itemSurah.setSuraname_id(cursor.getString(cursor.getColumnIndexOrThrow(SURANAME_ID)));
arrayList.add(itemSurah);
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
cursor.close();
return arrayList;
}
public long insert(ItemSurah itemSurah) {
ContentValues values = new ContentValues();
values.put(CHAPTERID, itemSurah.getChapterid());
values.put(SURANAME, itemSurah.getSuraname());
values.put(SURANAME_ID, itemSurah.getSuraname_id());
return database.insert(TABLE_NAME, null, values);
}
public void beginTransaction() {
database.beginTransaction();
}
public void setTransactionSuccess() {
database.setTransactionSuccessful();
}
public void endTransaction() {
database.endTransaction();
}
}
| true |
efd326a2698e1e76816e36f7d8498cacbb5e7d77 | Java | YunXiuRZ/zeroJudge-Java | /a225/src/a225/a225.java | UTF-8 | 1,222 | 3.703125 | 4 | [] | no_license | package a225;
import java.util.Scanner;
import java.util.Arrays;
public class a225 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
int n = Integer.parseInt(scanner.nextLine());
String[] input = scanner.nextLine().split(" ");
Element[] numbers = new Element[n];
for(int i = 0; i < input.length; i++) {
Element e = new Element(Integer.parseInt(input[i]));
numbers[i] = e;
}
Arrays.sort(numbers);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++)
sb.append(numbers[i].value + " ");
System.out.println(sb);
}
}
}
class Element implements Comparable<Element>{
public int value;
public int digits;
public int tens;
public Element(int n) {
value = n;
digits = value%10;
tens = value/10;
}
public int getDigits() {
return digits;
}
public int getTens() {
return tens;
}
public int compareTo(Element e) {
if(this.getDigits() > e.getDigits())
return 1;
else if(this.getDigits() < e.getDigits())
return -1;
else {
if(this.getTens() > e.getTens())
return -1;
else if(this.getTens() < e.getTens())
return 1;
else
return 0;
}
}
} | true |
1302ec71d0b4de42cdbdaaec3d4d7a195f002853 | Java | phjwww97/phjwww97github.io | /src/Ch04진단문제/Ch04Ex02_16.java | UTF-8 | 557 | 3.03125 | 3 | [] | no_license | package Ch04진단문제;
import java.util.*;
public class Ch04Ex02_16 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b;
int c;
int d;
int q=0;
char ch='A';
if(a<=6) {
for (b=0;b<a;b++) {
for (c=a;c>b;c--){
System.out.printf("%c",ch);
ch++;
}
for(d=0;d<b;d++){
System.out.printf("%d",q);
q++;
}
System.out.printf("\n");
}
}
}
} | true |
d022df1fef6ff72e1422c3c204e9fb8a62884044 | Java | franm3e/Distributed-Systems | /Practica2/Cliente/MsgConexion.java | UTF-8 | 2,658 | 2.78125 | 3 | [] | no_license | package remoto;
import javax.jms.*;
import javax.naming.*;
import java.util.Scanner;
/**
*
* @author Francisco Martínez Esteso, Julián Morales Núñez
*/
public class MsgConexion {
public String nombreCola = "jms/Noticias";
public Context contexto = null; // Contexto JNDI
public TopicConnectionFactory factoria = null;
public TopicConnection conexionCola = null;
public TopicSession sesionCola = null;
public Topic cola = null;
public MsgConexion() {
}
public static void main(String[] args){
try {
// Obtenemos el contexto JNDI actual
InitialContext iniCtx = new InitialContext();
// Buscamos los recursos sobre él.
TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("jms/FactoriaConexiones");
Topic t = (Topic) iniCtx.lookup("jms/Noticias");
// Creamos la conexión sobre la factoria de conexiones.
TopicConnection conexion = tcf.createTopicConnection();
// Creamos el publisher sobre la sesión.
TopicSession sesion = conexion.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = sesion.createPublisher(t);
conexion.start();
// Creamos el subscriber y su escucha
TopicSubscriber subscriber = sesion.createSubscriber(t);
subscriber.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
String recibido = null;
TextMessage mes = (TextMessage) message;
recibido = mes.getText();
System.out.println("Mensaje recibido:" + recibido);
} catch (JMSException ex) {
}
}
}
});
String mensaje = null;
do {
System.out.println("Introduce mensaje: ");
// https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner scan = new Scanner(System.in);
mensaje = scan.nextLine();
TextMessage msj = sesion.createTextMessage();
msj.setText(mensaje);
publisher.publish(msj);
} while (!"exit".equals(mensaje));
publisher.close();
conexion.close();
} catch (Exception ex) {}
}
}
| true |
969c5824afb875b821bb247604ea570fb6b210a1 | Java | huangjixin/zhiwo-mall | /fushenlan-java/cloud-job/src/main/java/com/fulan/application/controller/ScheduleController.java | UTF-8 | 17,486 | 2.046875 | 2 | [] | no_license | package com.fulan.application.controller;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.matchers.StringMatcher.StringOperatorName;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.fulan.application.handle.quartz.QuartzConfigration;
import com.fulan.application.util.date.DateUtil;
import com.fulan.application.util.str.StringUtil;
/**
* schedeule任务类
*/
@Controller
@RequestMapping("/scheduleman")
public class ScheduleController {
private static Logger logger = LoggerFactory.getLogger(ScheduleController.class);
@Resource
private Scheduler scheduler;
@Autowired
private QuartzConfigration quartzConfigration;
/**
* 任务列表
*/
@RequestMapping("/list")
public ModelAndView listJobs(HttpServletRequest request, String queryJobName) throws SchedulerException {
ModelAndView view = new ModelAndView();
if (StringUtils.isNotBlank(queryJobName)) {
queryJobName = queryJobName.trim();
}
Integer count = 0;
List<String> groups = scheduler.getJobGroupNames();
// 获取正在执行的job
Integer executingJobCount = scheduler.getCurrentlyExecutingJobs().size();
List<HashMap<String, Object>> jobList = new ArrayList<HashMap<String, Object>>();
Map<String, String> executingJobsMap = new HashMap<String, String>();
for (JobExecutionContext context : scheduler.getCurrentlyExecutingJobs()) {
executingJobsMap.put(context.getJobDetail().getKey().getGroup() + context.getJobDetail().getKey().getName(), "1");
}
for (String group : groups) {
@SuppressWarnings("serial")
Set<JobKey> jobKeys = scheduler.getJobKeys(new GroupMatcher<JobKey>(group, StringOperatorName.EQUALS) {
});
for (JobKey jobKey : jobKeys) {
if (StringUtils.isNotBlank(queryJobName) && !jobKey.toString().contains(queryJobName)) {
continue;
}
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
HashMap<String, Object> jobInfoMap = new HashMap<String, Object>();
// 触发器
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
Map<String, Object> triggerStatusMap = new HashMap<String, Object>();
for (Trigger trigger : triggers) {
TriggerState state = scheduler.getTriggerState(trigger.getKey());
triggerStatusMap.put(trigger.getKey().toString().replace(".", ""), state.name() + ":" + state.ordinal());
if (trigger instanceof CronTriggerImpl) {
jobInfoMap.put("crondesc", "cron表达式:" + ((CronTriggerImpl) trigger).getCronExpression());
jobInfoMap.put("preFire", DateUtil.format(trigger.getPreviousFireTime(), "yyyy-MM-dd HH:mm:ss"));
jobInfoMap.put("nextFire", DateUtil.format(trigger.getNextFireTime(), "yyyy-MM-dd HH:mm:ss"));
} else {
jobInfoMap.put("crondesc", "执行频率:" + ((SimpleTriggerImpl) trigger).getRepeatInterval() / 1000 + "秒");
jobInfoMap.put("preFire", DateUtil.format(trigger.getPreviousFireTime(), "yyyy-MM-dd HH:mm:ss"));
jobInfoMap.put("nextFire", DateUtil.format(trigger.getNextFireTime(), "yyyy-MM-dd HH:mm:ss"));
}
}
jobInfoMap.put("triggers", triggers);
jobInfoMap.put("jobDetail", jobDetail);
if (executingJobsMap.containsKey(jobDetail.getKey().getGroup() + jobDetail.getKey().getName())) {
jobInfoMap.put("isRunning", "正在运行");
} else {
jobInfoMap.put("isRunning", "停止");
}
jobInfoMap.put("triggerStatusMap", triggerStatusMap);
jobList.add(jobInfoMap);
count++;
}
}
view.addObject("executingJobCount", executingJobCount);
view.addObject("count", count);
view.addObject("jobList", jobList);
view.addObject("scheduler", scheduler);
view.addObject("groups", groups);
view.addObject("queryJobName", queryJobName);
view.addObject("isValidScheduleServer", 1);
view.setViewName("jobList");
return view;
}
/**
* 添加任务页面
*/
@RequestMapping(value = "/showadd")
public ModelAndView showAddJob(HttpServletRequest request, String queryJobName) throws SchedulerException {
ModelAndView view = new ModelAndView();
// 任务所属组
List<String> jobGroups = scheduler.getJobGroupNames();
view.addObject("groups", jobGroups);
view.addObject("queryJobName", queryJobName);
// 存在的任务类
Map<String, List<String>> jobClassesMap = quartzConfigration.getJobClassesMap();
view.addObject("jobClassesMap", jobClassesMap);
view.setViewName("jobAdd");
return view;
}
/**
* 添加任务的处理,处理完成后返回任务列表
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/addJob")
@ResponseBody
public Map<String, String> addJob(HttpServletRequest request, HttpServletResponse response, String queryJobName)
throws SchedulerException, IOException {
Map<String, String> resultMap = new HashMap<String, String>();
try {
if (queryJobName != null && !"".equals(queryJobName)) {
try {
queryJobName = URLEncoder.encode(queryJobName, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("ConfigHelp.getUrl", e);
}
}
String group = request.getParameter("jobGroup").trim();
String jobName = request.getParameter("jobName").trim();
String jobClassName = request.getParameter("jobClassName").trim();
String[] argsNames = StringUtil.trimArray(request.getParameterValues("argsNames"));
String[] argsValues = StringUtil.trimArray(request.getParameterValues("argsValues"));
String triggerType = request.getParameter("triggerType").trim();
// 验证任务是否存在
boolean flag = scheduler.checkExists(JobKey.jobKey(jobName, group));
if (flag) {
resultMap.put("success", "0");
resultMap.put("msg", "任务重名,已经存在标识为:\"" + group + "." + jobName + "\" 的任务!");
return resultMap;
}
Trigger trigger = null;
if ("1".equals(triggerType)) {
String rate = request.getParameter("rate").trim();
String times = request.getParameter("times").trim();
Integer rateInt = new Integer(rate);
Integer timesInt = new Integer(times);
trigger = newTrigger().withIdentity(jobName, group).withSchedule(simpleSchedule().withIntervalInMinutes(rateInt).withRepeatCount(timesInt).withMisfireHandlingInstructionFireNow()).build();
} else if ("2".equals(triggerType)) {
String second = request.getParameter("secondField");
String minute = request.getParameter("minutesField");
String hour = request.getParameter("hourField");
String day = request.getParameter("dayField");
String month = request.getParameter("monthField");
String week = request.getParameter("weekField");
String year = request.getParameter("yearField");
String cronExpression = String.format("%s %s %s %s %s %s %s", second, minute, hour, day, month, week, year);
boolean isValid = CronExpression.isValidExpression(cronExpression);
if (!isValid) {
resultMap.put("success", "0");
resultMap.put("msg", "cron表达式填写错误,您的表达式是:" + cronExpression);
return resultMap;
}
try {
trigger = newTrigger().withIdentity(jobName, group).withSchedule(cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed()).build();
} catch (Exception e) {
logger.error("addJob:", e);
}
} else {
String cronExpression = String.format("%s %s %s %s %s %s %s", "0", "*", "*", "*", "*", "?", "2099");
boolean isValid = CronExpression.isValidExpression(cronExpression);
if (!isValid) {
resultMap.put("success", "0");
resultMap.put("msg", "cron表达式填写错误,您的表达式是:" + cronExpression);
return resultMap;
}
try {
trigger = newTrigger().withIdentity(jobName, group).withSchedule(cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed()).build();
} catch (Exception e) {
logger.error("addJob:", e);
}
}
@SuppressWarnings("rawtypes")
Class jobClass = null;
try {
jobClass = Class.forName(jobClassName);
} catch (ClassNotFoundException e1) {
logger.error("addJob:", e1);
}
if (jobClass == null) {
resultMap.put("success", "0");
resultMap.put("msg", "类不存在,您的类是:" + jobClassName);
return resultMap;
}
JobDetail job = newJob(jobClass).withIdentity(jobName, group).build();
JobDataMap map = job.getJobDataMap();
for (int i = 0; i < argsNames.length; i++) {
if (!argsNames[i].trim().equals("参数名")) {
map.put(argsNames[i], argsValues[i]);
}
}
scheduler.scheduleJob(job, trigger);
} catch (Exception e) {
logger.error("addJob:", e);
resultMap.put("success", "0");
resultMap.put("msg", "添加失败");
return resultMap;
}
resultMap.put("success", "1");
resultMap.put("msg", "添加成功");
return resultMap;
}
/**
* 执行某个TASK一次
*/
@RequestMapping(value = "/executeOnce")
public void executeOnce(HttpServletRequest request, HttpServletResponse response, String queryJobName,
String jobKey) throws SchedulerException {
StringUtil.trim(queryJobName);
StringUtil.trim(jobKey);
try {
String group = jobKey.substring(0, jobKey.indexOf("."));
String jobName = jobKey.substring(jobKey.indexOf(".")+1);
Trigger trigger = newTrigger().withIdentity(jobName + UUID.randomUUID().toString() + "MANUALLY", group).withPriority(100).forJob(JobKey.jobKey(jobName, group)).build();
scheduler.scheduleJob(trigger);
response.sendRedirect(request.getContextPath() + "/scheduleman/list.do?queryJobName=" + queryJobName);
} catch (IOException e) {
logger.error("executeOnce:", e);
}
}
/**
* 中断TASK执行
*/
@RequestMapping(value = "/interruptJob")
public void interruptJob(HttpServletRequest request, HttpServletResponse response, String queryJobName,
String jobKey) throws SchedulerException {
StringUtil.trim(queryJobName);
StringUtil.trim(jobKey);
try {
String group = jobKey.substring(0, jobKey.indexOf("."));
String jobName = jobKey.substring(jobKey.indexOf(".") + 1);
scheduler.interrupt(JobKey.jobKey(jobName, group));
response.sendRedirect(request.getContextPath() + "/scheduleman/list.do?queryJobName=" + queryJobName);
} catch (Exception e) {
logger.error("interruptJob:", e);
}
}
/**
* 显示修改页面
*/
@RequestMapping(value = "/showEditJob")
public ModelAndView showEditJob(HttpServletRequest request, HttpServletResponse response, String queryJobName,
String jobKey) throws SchedulerException {
ModelAndView view = new ModelAndView();
StringUtil.trim(queryJobName);
StringUtil.trim(jobKey);
String group = jobKey.substring(0, jobKey.indexOf("."));
String jobName = jobKey.substring(jobKey.indexOf(".") + 1);
// 任务信息
JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(jobName, group));
Trigger trigger = scheduler.getTrigger(TriggerKey.triggerKey(jobName, group));
view.addObject("jobDetail", jobDetail);
view.addObject("trigger", trigger);
view.addObject("queryJobName", queryJobName);
if (trigger instanceof SimpleTrigger) {
view.addObject("triggerType", 1);
} else {
view.addObject("triggerType", 2);
}
List<String> jobGroups = scheduler.getJobGroupNames();
view.addObject("jobGroups", jobGroups);
view.setViewName("edit");
return view;
}
/**
* 修改处理
*/
@RequestMapping(value = "/editJob")
@ResponseBody
public Map<String, String> editJob(HttpServletRequest request, HttpServletResponse response, String queryJobName)
throws SchedulerException {
Map<String, String> resultMap = new HashMap<String, String>();
try {
if (queryJobName != null && !"".equals(queryJobName)) {
try {
queryJobName = URLEncoder.encode(queryJobName, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("editJob", e);
}
}
String jobKey = request.getParameter("jobKey").trim();
String triggerType = request.getParameter("triggerType").trim();
String group = jobKey.substring(0, jobKey.indexOf("."));
String jobName = jobKey.substring(jobKey.indexOf(".") + 1);
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(JobKey.jobKey(jobName, group));
jobName = triggers.get(0).getKey().getName();
group = triggers.get(0).getKey().getGroup();
Trigger trigger = null;
if ("1".equals(triggerType)) {
String rate = request.getParameter("rate").trim();
String times = request.getParameter("times").trim();
Integer rateInt = new Integer(rate);
Integer timesInt = new Integer(times);
trigger = newTrigger().withIdentity(jobName, group).withSchedule(simpleSchedule().withIntervalInMinutes(rateInt).withRepeatCount(timesInt).withMisfireHandlingInstructionFireNow()).build();
} else if ("2".equals(triggerType)) {
String second = request.getParameter("secondField");
String minute = request.getParameter("minutesField");
String hour = request.getParameter("hourField");
String day = request.getParameter("dayField");
String month = request.getParameter("monthField");
String week = request.getParameter("weekField");
String cronExpression = String.format("%s %s %s %s %s %s", second, minute, hour, day, month, week);
boolean isValid = CronExpression.isValidExpression(cronExpression);
if (!isValid) {
resultMap.put("success", "0");
resultMap.put("msg", "cron表达式填写错误,您的表达式是:" + cronExpression);
return resultMap;
}
try {
trigger = newTrigger().withIdentity(jobName, group).withSchedule(cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed()).build();
} catch (Exception e) {
logger.error("newTrigger Exception",e);
resultMap.put("success", "0");
resultMap.put("msg", "修改失败");
return resultMap;
}
} else {
String cronExpression = String.format("%s %s %s %s %s %s %s", "0", "*", "*", "*", "*", "?", "2099");
boolean isValid = CronExpression.isValidExpression(cronExpression);
if (!isValid) {
resultMap.put("success", "0");
resultMap.put("msg", "cron表达式填写错误,您的表达式是:" + cronExpression);
return resultMap;
}
try {
trigger = newTrigger().withIdentity(jobName, group).withSchedule(cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed()).build();
} catch (Exception e) {
logger.error("newTrigger Exception",e);
resultMap.put("success", "0");
resultMap.put("msg", "修改失败");
return resultMap;
}
}
scheduler.rescheduleJob(trigger.getKey(), trigger);
} catch (Exception e) {
logger.error("newTrigger Exception",e);
resultMap.put("success", "0");
resultMap.put("msg", "修改失败");
return resultMap;
}
resultMap.put("success", "1");
resultMap.put("msg", "修改成功");
return resultMap;
}
/**
* 删除TASK
*/
@RequestMapping(value = "/deleteJob")
public void deleteJob(HttpServletRequest request, HttpServletResponse response, String queryJobName) throws SchedulerException {
try {
if (queryJobName != null && !"".equals(queryJobName)) {
try {
queryJobName = URLEncoder.encode(queryJobName, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("deleteJob:", e);
}
}
String jobKey = request.getParameter("jobKey").trim();
String group = jobKey.substring(0, jobKey.indexOf("."));
String jobName = jobKey.substring(jobKey.indexOf(".")+1);
scheduler.deleteJob(JobKey.jobKey(jobName, group));
} catch (Exception e) {
logger.error("deleteJob:", e);
}
try {
response.sendRedirect(request.getContextPath() + "/scheduleman/list.do?queryJobName=" + queryJobName);
} catch (IOException e) {
logger.error("deleteJob:", e);
}
}
}
| true |
1a6124d6a2f552aa39e02d258d5705adda0070ea | Java | ramy-git/politician-webservices-rest-soap | /facebook-graph-api-using-springboot-master/src/main/java/com/macrosoft/test/RestController.java | UTF-8 | 2,306 | 1.992188 | 2 | [] | no_license | package com.macrosoft.test;
import com.macrosoft.test.data.Place;
import com.macrosoft.test.service.facade.FacebookServiceFacade;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Version;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@org.springframework.web.bind.annotation.RestController
public class RestController
{
@Value("${access.token:test}")
private String MY_ACCESS_TOKEN;
private static List<Place> places;
private final FacebookServiceFacade facebookServiceFacade;
@Autowired
public RestController(FacebookServiceFacade facebookServiceFacade)
{
this.facebookServiceFacade = facebookServiceFacade;
}
@RequestMapping("/facebookData")
public List<Place> getPlaces() throws IOException
{
return places = this.facebookServiceFacade.fetchFacebookData();
}
@RequestMapping("/searchByName")
public List<Place> getitem(@RequestParam("name") String name) throws IOException
{
return places.stream().filter(place -> place.getName() != null && place.getName().toLowerCase().contains(name.toLowerCase())).collect(Collectors.toList());
}
@RequestMapping("/searchByCountry")
public List<Place> getPlacesByCountry(@RequestParam("countryName") String countryName) throws IOException
{
return places.stream().filter(place -> place.getCountry() != null && place.getCountry().toLowerCase().contains(countryName.toLowerCase())).collect(Collectors.toList());
}
@RequestMapping("/searchByCity")
public List<Place> getPlacesByCity(@RequestParam("cityName") String cityName) throws IOException
{
return places.stream().filter(place -> place.getCity() != null && place.getCity().toLowerCase().contains(cityName.toLowerCase())).collect(Collectors.toList());
}
}
| true |
7700440d08356fec39cc50badbae4c47906e67ee | Java | dlcnd9401/phoenix | /src/main/java/kr/gudi/phoenix/service/MasterService.java | UTF-8 | 4,300 | 2.0625 | 2 | [] | no_license | package kr.gudi.phoenix.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import kr.gudi.phoenix.dao.MasterDaoInterface;
import kr.gudi.util.HttpUtil;
@Service
public class MasterService implements MasterServiceInterface {
@Autowired
MasterDaoInterface mdi;
public HashMap<String, Object> map;
public HashMap<String, Object> map2;
public HashMap<String, Object> param;
@Override
public HashMap<String, Object> setClockupData(HashMap<String, Object> param) {
map = new HashMap<String, Object>();
System.out.println(param);
map.put("status", mdi.setClockupData(param));
System.out.println("map " + map);
return map;
}
@Override
public HashMap<String, Object> fileOutput(MultipartFile[] file, HttpServletRequest req) {
map = new HashMap<String, Object>();
map2 = new HashMap<String, Object>();
param = HttpUtil.getParameterMap(req);
System.out.println(param);
for(int i = 0; i < file.length; i++){
String name = file[i].getOriginalFilename();
String path2 = "resources/img/";
System.out.println(name);
try {
byte[] bytes = file[i].getBytes();
String path = "";
// 개발 툴에서만 사용 할것!
/*path = "E:/Git/phoenix2/src/main/webapp/" + path2 + name;*/
/*path = "C:/Users/GD/git/phoenix/src/main/webapp/" + path2 + name;*/
path = req.getSession().getServletContext().getRealPath("/") + path2 + name;
// System.out.println("name " + name + " path " + path);
File f = new File(path);
System.out.println("F" + f);
System.out.println(param);
if(f.exists()){
f = new File(path);
OutputStream out = new FileOutputStream(f);
out.write(bytes);
out.close();
// path = "";
path = path2 + name;
map.put("path", path);
map.put("sname", param.get("sname"));
map.put("name", param.get("name"));
map.put("mKind", param.get("mKind"));
map.put("mshape", param.get("mshape"));
map.put("scode", param.get("scode"));
map.put("code", param.get("code"));
map.put("price", param.get("price"));
map.put("introduce", param.get("introduce"));
map2 = setClockupData(map);
System.out.println(param);
}
System.out.println("map " + map);
System.out.println("map2 " + map2);
} catch (IOException e) {
e.printStackTrace();
}
}
return map2;
}
@Override
public HashMap<String, Object> stocklistselect() {
map = new HashMap<String, Object>();
map.put("list", mdi.stocklistselect());
return map;
}
@Override
public HashMap<String, Object> stocklistpaging(HashMap<String, Object> param) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("data", mdi.stocklistpaging(param));
map.put("totCnt", mdi.stocklisttotcnt());
return map;
}
@Override
public HashMap<String, Object> stockupdate(HashMap<String, Object> param) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("status", mdi.stockupdate(param));
return map;
}
@Override
public HashMap<String, Object> userlistselect(HashMap<String, Object> param) {
map = new HashMap<String, Object>();
map.put("list", mdi.userlistselect(param));
return map;
}
@Override
public HashMap<String, Object> userlistpaging(HashMap<String, Object> param) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("data", mdi.userlistpaging(param));
map.put("totCnt", mdi.userlisttotcnt());
return map;
}
}
| true |
dc164ad8ca157c9966f0e07f4658438d5366b0d8 | Java | nautysagar/MyCodingSpace | /designpattern/behaviour/template/GermanMeal.java | UTF-8 | 489 | 2.875 | 3 | [] | no_license | package behaviour.template;
public class GermanMeal extends Meal{
public GermanMeal() {
// TODO Auto-generated constructor stub
}
@Override
public void prepareIngredient() {
// TODO Auto-generated method stub
System.out.println("Adding german salt in cooking");
}
@Override
public void cook() {
// TODO Auto-generated method stub
System.out.println("cooking in German Stoves");
}
@Override
public void cleanup() {
System.out.println("Throwing papers");
}
}
| true |
b0988c899e8284213889ca8585b7c63ab1c1d201 | Java | JainathJaiswal/sniper | /src/main/java/com/jai/world/rest/ITaskApi.java | UTF-8 | 1,305 | 2.15625 | 2 | [] | no_license | package com.jai.world.rest;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jai.world.repository.jpadomain.Task;
@RestController
@RequestMapping("/v1")
@CrossOrigin("*")
public interface ITaskApi {
@GetMapping(value = "/tasks")
public ResponseEntity<List<Task>> getAllTasks();
@PostMapping(value = "/tasks")
public ResponseEntity<Task> addTask(@RequestBody Task task);
@DeleteMapping(value = "/tasks/{id}")
public ResponseEntity<?> deleteTask(@PathVariable Long id);
@PutMapping(value = "/tasks/{id}")
public ResponseEntity<Task> updateTask(@PathVariable("id") Long id,@RequestBody Task task);
@GetMapping(value = "/tasks/{id}")
public ResponseEntity<Task> getTaskById(@PathVariable("id") Long id);
}
| true |
f8a40caec0b8261a33af9722f247c4e8142b88e4 | Java | locnguyen95/Energy-Watch | /app/src/main/java/com/example/pc/energywatch/forget.java | UTF-8 | 2,011 | 2.21875 | 2 | [] | no_license | package com.example.pc.energywatch;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class forget extends AppCompatActivity {
Button send;
EditText mail;
FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forget);
auth = FirebaseAuth.getInstance();
send = (Button) findViewById(R.id.send_btn);
mail = (EditText) findViewById(R.id.input_mail);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = mail.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(com.example.pc.energywatch.forget.this, "Please enter Email", Toast.LENGTH_SHORT).show();
return;
}
auth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(forget.this,"We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(forget.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
} | true |
234912a184ec3a7990c678d5d7c427706b46712a | Java | wille/jrat | /modules/fs-controller/src/jrat/module/fs/packets/Packet34CustomDirectory.java | UTF-8 | 583 | 2.21875 | 2 | [] | no_license | package jrat.module.fs.packets;
import jrat.controller.Slave;
import jrat.controller.packets.incoming.IncomingPacket;
import jrat.module.fs.ui.PanelFileSystem;
public class Packet34CustomDirectory implements IncomingPacket {
@Override
public void read(Slave slave) throws Exception {
String where = slave.readLine().replace("/", slave.getFileSeparator()).replace("\\", slave.getFileSeparator());
PanelFileSystem frame = (PanelFileSystem) slave.getPanel(PanelFileSystem.class);
if (frame != null) {
frame.getFilesPanel().getRemoteTable().setDirectory(where);
}
}
}
| true |
2fb7516e1575f123b634f6727a5aaf9f2a3739e5 | Java | mgmarques/Chess_Game | /src/chess/pieces/Queen.java | UTF-8 | 3,504 | 3.296875 | 3 | [] | no_license | package chess.pieces;
import board.Board;
import board.Position;
import chess.ChessPiece;
import chess.enums.Color;
public class Queen extends ChessPiece {
public Queen(Board board, Color color) {
super(board, color);
}
public Queen(Board board, Color color, int moveCount) {
super(board, color, moveCount);
}
@Override
public String toString() {
return "Q";
}
@Override
public boolean[][] possibleMoves() {
boolean[][] ChessBoard = new boolean[getBoard().getRows()][getBoard().getColumns()];
Position p = new Position(0, 0);
// Above move
p.setValues(position.getRow() - 1, position.getColumn());
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow() - 1, p.getColumn());
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Below move
p.setValues(position.getRow() + 1, position.getColumn());
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow() + 1, p.getColumn());
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Left move
p.setValues(position.getRow(), position.getColumn() - 1);
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow(), p.getColumn() - 1);
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Right move
p.setValues(position.getRow(), position.getColumn() + 1);
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow(), p.getColumn() + 1);
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Up-Left move
p.setValues(position.getRow() - 1, position.getColumn() - 1);
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow() - 1, p.getColumn() - 1);
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Down-Left move
p.setValues(position.getRow() + 1, position.getColumn() - 1);
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow() + 1, p.getColumn() - 1);
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Up-Right move
p.setValues(position.getRow() - 1, position.getColumn() + 1);
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow() - 1, p.getColumn() + 1);
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
// Down-Right move
p.setValues(position.getRow() + 1, position.getColumn() + 1);
while (getBoard().positionExists(p) && !getBoard().therIsAPiece(p)) {
ChessBoard[p.getRow()][p.getColumn()] = true;
p.setValues(p.getRow() + 1, p.getColumn() + 1);
}
if (getBoard().positionExists(p) && isTherOpponentPiece(p))
ChessBoard[p.getRow()][p.getColumn()] = true;
return ChessBoard;
}
}
| true |
8040dbe05bb3955e33863808600d436e181674ac | Java | efsn/origin | /src/main/java/org/codeyn/util/MacAddress.java | UTF-8 | 7,982 | 1.882813 | 2 | [
"Apache-2.0"
] | permissive | package org.codeyn.util;
import org.codeyn.util.file.FileUtil;
import org.codeyn.util.yn.ArrayUtil;
import org.codeyn.util.yn.StrmUtil;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 获取本机网卡物理地址
*/
public final class MacAddress {
/**
* windows: Physical Address. . . . . . . . . : 00-13-02-9A-A2-3B
* <p>
* linux : eth0 Link encap:Ethernet HWaddr 00:10:5C:FC:B2:7C BROADCAST
* MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0
* frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0
* txqueuelen:1000 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b) Base address:0xd880
* Memory:fe980000-fe9a0000
* <p>
* Solaris/SunOS
* 在Solaris和SunOS系统中,以太网的设备一般被称为le0或ie0。为了找到以太网设备的MAC地址,首先你必须成为超级用户
* ,即root,可以通过使用su命令实现。然后键入ifconfig –a并查看返回信息。例如: # ifconfig -a le0:
* flags=863<UP,BROADCAST,NOTRAILERS,RUNNING,MULTICAST> mtu 1500 inet
* 131.225.80.209 netmask fffff800 broadcast 131.225.87.255 ether
* 8:0:20:10:d2:ae
* 注意:在Solaris和SunOS系统中,默认是去掉了MAC地址各个字段中的排在前面的0。在上面的例子中,这台机器的实际MAC地址应该为
* :08:00:20:10:d2:ae。
* <p>
* aix: # netstat -in Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
* en0 1500 link#2 0.11.25.8.1d.81 21609570 0 3880375 3 0 en0 1500
* 150.100.16 150.100.16.183 21609570 0 3880375 3 0 lo0 16896 link#1 95267 0
* 95830 0 0 lo0 16896 127 127.0.0.1 95267 0 95830 0 0 lo0 16896 ::1 95267 0
* 95830 0 0
* <p>
* FreeBSD 在一个FreeBSD系统中,使用dmesg命令将显示本机的MAC地址和其他一些信息。
* <p>
* HP 在HP系统中,以太网的地址被典型的称为lan0。通过键入lanscan并查看返回信息就可以得到MAC地址。例如: $ lanscan
* Hardware Station Dev Hardware Net-Interface NM Encapsulation Mjr Path
* Address lu State NameUnit State ID Methods Num 2.0.2 0x08000935C99D 0 UP
* lan0 UP 4 ETHER 52
* 注意:HP系统中,默认是去掉了MAC地址各个字段的分割符“:”。在上面的例子中,这台机器的实际MAC地址应该为
* :08:00:09:35:C9:9D。 在农发行HP-UX上 crsapp1#[/]lanscan Hardware Station Crd
* Hdw Net-Interface NM MAC HP-DLPI DLPI Path Address In# State NamePPA ID
* Type Support Mjr# 0/0/12/0/0/0/0/4/0/0/0 0xD8D385F667D3 2 UP lan2 snap2 3
* ETHER Yes 119 0/0/12/0/0/0/0/4/0/0/1 0xD8D385F667D2 3 UP lan3 snap3 4
* ETHER Yes 119 0/0/14/0/0/0/0/2/0/0/0 0x3C4A923B191C 4 UP lan4 snap4 5
* ETHER Yes 119 0/0/14/0/0/0/0/2/0/0/1 0x3C4A923B191D 5 UP lan5 snap5 6
* ETHER Yes 119 1/0/0/1/0 0x1CC1DE104797 6 UP lan6 snap6 7 ETHER Yes 119
* 1/0/12/0/0/0/0/4/0/0/0 0xD8D385F67027 9 UP lan9 snap9 10 ETHER Yes 119
* 1/0/12/0/0/0/0/4/0/0/1 0xD8D385F67026 10 UP lan10 snap10 11 ETHER Yes 119
* 1/0/14/0/0/0/0/2/0/0/0 0x3C4A923B19C0 11 UP lan11 snap11 12 ETHER Yes 119
* 1/0/14/0/0/0/0/2/0/0/1 0x3C4A923B19C1 12 UP lan12 snap12 13 ETHER Yes 119
* LinkAgg0 0xD8D385F667D1 900 UP lan900 snap900 15 ETHER Yes 119 LinkAgg1
* 0xD8D385F667D0 901 UP lan901 snap901 16 ETHER Yes 119 LinkAgg2
* 0x000000000000 902 DOWN lan902 snap902 17 ETHER Yes 119 LinkAgg3
* 0x000000000000 903 DOWN lan903 snap903 18 ETHER Yes 119 LinkAgg4
* 0x000000000000 904 DOWN lan904 snap904 19 ETHER Yes 119
*/
static private List<String> collectHWaddrByCMD(List<String> list) {
if (list == null) list = new ArrayList<String>(3);
try {
boolean linux = File.separatorChar == '/';
String cmd = null;
if (linux) {
cmd = "/sbin/ifconfig -a";
String osname = System.getProperty("os.name");
if (osname != null) {
osname = osname.toUpperCase();
if (osname.indexOf("AIX") >= 0) {
cmd = "netstat -i";
} else if (osname.indexOf("BSD") >= 0) {
cmd = "dmesg";// 未经测试
}
}
} else {
cmd = "ipconfig /all";
}
Process p = Runtime.getRuntime().exec(cmd);
if (p == null) {
return list;
}
InputStream i = p.getInputStream();
if (i == null) {
return list;
}
try {
String s = StrmUtil.stm2Str(i);
collectMacAddressFromString(list, s);
} finally {
i.close();
}
return list;
} catch (Throwable ex) {
return list;
}
}
static private List<String> collectHWaddr_ByConfigFile(List<String> list) {
if (list == null) list = new ArrayList<String>(3);
try {
boolean linux = File.separatorChar == '/';
if (!linux) return list;
java.io.File[] cfgfns = FileUtil.listFiles(
"/etc/sysconfig/network-scripts/", "ifcfg-*", 0);
if (cfgfns == null || cfgfns.length == 0) {
return list;
}
for (int i = 0; i < cfgfns.length; i++) {
try {
String s = FileUtil.file2str(cfgfns[i].getAbsolutePath());
collectMacAddressFromString(list, s);
} catch (Exception ex) {
}
}
} catch (Exception e) {
}
return list;
}
private static void collectMacAddressFromString(List<String> r, String s) {
Pattern pattern = Pattern.compile("([1234567890ABCDEFabcdef]{1,2}(\\-|\\:|\\.)){5}[1234567890ABCDEFabcdef]{1,2}");
Matcher mt = pattern.matcher(s);
int end = 0;
while (mt.find(end)) {
end = mt.end();
String addr = mt.group().toUpperCase().replace('-', ':').replace('.', ':');
if ("00:00:00:00:00:00".equals(addr)) // 我的win7上有蛮多这个信息,去掉他们
continue;
/**
* 00:50:56:C0:00 排除以该网址打头的地址,这些地址应该都是虚拟网卡生成的。
*/
if (addr == null || addr.startsWith("00:50:56:C0:00")) {
continue;
}
String[] ss = addr.split("\\:");
addr = "";
for (int i = 0; i < ss.length; i++) {
String a = ss[i];
if (a.length() == 1) {
a = "0" + a;
}
if (addr.length() > 0) addr = addr + ":";
addr = addr + a;
}
if (!r.contains(addr)) r.add(addr);
}
}
public static final List<String> collectHWaddr() {
List<String> list = collectHWaddr_ByConfigFile(null);
list = collectHWaddrByCMD(list);
return list;
}
/**
* 返回找到的物理地址,可能返回长度为0的数组,数组的内容形如:00:15:58:2E:46:B7
*/
public static final String[] getMacAddresses() {
List<String> list = collectHWaddr();
return list.toArray(new String[0]);
}
/**
* 返回第一个物理地址,如果不能找到物理地址,则返回""
*/
public static final String getMacAddress() {
String[] l = getMacAddresses();
return l != null && l.length > 0 ? l[0] : "";
}
public static void main(String[] args) {
System.out.println(ArrayUtil.array2displaystr(getMacAddresses()));
System.out.println(ArrayUtil.array2displaystr(getMacAddresses()));
}
}
| true |
5e148f96c920693901a0002a93d1ac4117c51a4b | Java | llj668/HOCCSLATs | /src/models/test/pronun/PronunItems.java | UTF-8 | 3,600 | 2.453125 | 2 | [] | no_license | package models.test.pronun;
import java.util.*;
public class PronunItems {
public static List<String> priority_phoneme = Collections.singletonList(
"er"
);
public static List<String> consonants = Arrays.asList(
"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t",
"x", "z"
);
public static List<String> double_consonants = Arrays.asList(
"zh", "ch", "ng", "sh"
);
public static List<String> vowels = Arrays.asList(
"i", "u", "v", "o", "e", "a", "y", "w"
);
public static List<String> double_vowels = Arrays.asList(
"ao", "au", "ai", "ua", "uo", "ia", "iu", "ui", "ei", "ou"
);
public static List<String> triple_vowels = Arrays.asList(
"yue", "iao", "uai"
);
public static List<List<String>> phonemes = Arrays.asList(
priority_phoneme, double_consonants, consonants, triple_vowels, double_vowels, vowels
);
public static Map<String, String> consonantType = new HashMap<String, String>(){{
put("d", "plosive");
put("t", "plosive");
put("g", "plosive");
put("b", "plosive");
put("p", "plosive");
put("k", "plosive");
put("m", "nasal");
put("n", "nasal");
put("ng", "nasal");
put("j", "affricate");
put("q", "affricate");
put("z", "affricate");
put("zh", "affricate");
put("c", "affricate");
put("ch", "affricate");
put("x", "fricative");
put("h", "fricative");
put("f", "fricative");
put("s", "fricative");
put("sh", "fricative");
put("r", "approxi");
put("l", "l_approxi");
}};
// Error pattern
public static List<String> double_vowels_for_pattern = Arrays.asList(
"ao", "au", "ai", "ua", "uo", "ia", "iu", "ei", "ou", "er"
);
public static List<String> triple_vowels_for_pattern = Arrays.asList(
"yue", "iao", "uai", "ui"
);
public static List<String> stops = Arrays.asList(
"d", "g"
);
public static List<String> aspiration = Arrays.asList("p","t","k","c","q","ch");
public static List<String> deaspiration = Arrays.asList("b","d","g","z","j","zh");
public static Map<ErrorPattern, String> patternName = new HashMap<ErrorPattern, String>(){{
put(ErrorPattern.CONSONANT_ASSIMILATION, "Consonant assimilation");
put(ErrorPattern.SYLLABLE_INITIAL_DELETION, "Syllable initial deletion");
put(ErrorPattern.FRONTING_1, "Fronting: /sh/ → [s]");
put(ErrorPattern.FRONTING_2, "Fronting: /x/ → [sh]");
put(ErrorPattern.FRONTING_3, "Fronting: /g/ → [d]");
put(ErrorPattern.BACKING, "Backing: /s/ → [sh]");
put(ErrorPattern.X_VELARISATION, "X velarisation");
put(ErrorPattern.STOPPING_1, "Stopping: /z/ → [d]");
put(ErrorPattern.STOPPING_2, "Stopping: /sh/ → [d]");
put(ErrorPattern.STOPPING_3, "Stopping: /h/ → [g]");
put(ErrorPattern.AFFRICATION, "Affrication");
put(ErrorPattern.DEASPIRATION, "Deaspiration");
put(ErrorPattern.ASPIRATION, "Aspiration");
put(ErrorPattern.GLIDING, "Gliding");
put(ErrorPattern.FINAL_N_DELETION, "Final /n/ deletion");
put(ErrorPattern.BACKING_N, "Backing: /n/ → [ng]");
put(ErrorPattern.FINAL_NG_DELETION, "Final /ng/ deletion");
put(ErrorPattern.TRIPHTHONG_REDUCTION, "Triphthong reduction");
put(ErrorPattern.DIPHTHONG_REDUCTION, "Diphthong reduction");
}};
}
| true |
2275c3b15d5ef49a79089f3876a04d6cd199cbf5 | Java | Jon-Soo/facecto-code-base-starter | /src/main/java/com/facecto/code/base/handler/CodeExceptionHandler.java | UTF-8 | 2,464 | 2.28125 | 2 | [] | no_license | package com.facecto.code.base.handler;
import com.facecto.code.base.CodeException;
import com.facecto.code.base.CodeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
/**
* CodeException handler
* @author Jon So, https://cto.pub, https://facecto.com, https://github.com/facecto
* @version v1.1.0 (2021/8/08)
*/
@Slf4j
@RestControllerAdvice
public class CodeExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public CodeResult handleIllegalArgumentException(IllegalArgumentException e)
{
log.error("Params error.");
return CodeResult.error(500,"Params error.");
}
@ExceptionHandler(SecurityException.class)
public CodeResult handleSecurityException(SecurityException e){
log.error("No access allowed.");
return CodeResult.error(500,"No access allowed.");
}
@ExceptionHandler(NullPointerException.class)
public CodeResult handleNullPointerException(NullPointerException e){
log.error("Null pointer exception.");
return CodeResult.error(500,"Null pointer exception.");
}
@ExceptionHandler(NoHandlerFoundException.class)
public CodeResult handlerNoFoundException(NoHandlerFoundException e) {
log.error(e.getMessage(), e);
return CodeResult.error(404, "Corresponding resource not found.");
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public CodeResult handlerHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
log.error("Request type is not supported.");
return CodeResult.error(500,"Request type is not supported.");
}
@ExceptionHandler(CodeException.class)
public CodeResult handleCodeException(CodeException e) {
return CodeResult.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public CodeResult handleRuntimeException(RuntimeException e){
log.error(e.getMessage(),e);
return CodeResult.error(500,e.getMessage());
}
@ExceptionHandler(Exception.class)
public CodeResult handleException(Exception e) {
log.error(e.getMessage(), e);
return CodeResult.error(e.getLocalizedMessage());
}
} | true |
9ce72de0ece4b2959bb52d4df7ca56eba7118dab | Java | cdapio/cdap | /cdap-api/src/main/java/io/cdap/cdap/api/workflow/WorkflowForkNode.java | UTF-8 | 1,297 | 2.140625 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.api.workflow;
import java.util.List;
/**
* Represents the FORK node in the {@link Workflow}
*/
public class WorkflowForkNode extends WorkflowNode {
private final List<List<WorkflowNode>> branches;
public WorkflowForkNode(String nodeId, List<List<WorkflowNode>> branches) {
super(nodeId, WorkflowNodeType.FORK);
this.branches = branches;
}
public List<List<WorkflowNode>> getBranches() {
return branches;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("WorkflowForkNode{");
sb.append("nodeId=").append(nodeId);
sb.append(", branches=").append(branches);
sb.append('}');
return sb.toString();
}
}
| true |
dc4c6d3984de2c5c4c80fdd49d8a305de473d773 | Java | imamNurul/PENILAIN_SISWA | /src/MI_MAK/dao/Mapel.java | UTF-8 | 2,932 | 2.3125 | 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 MI_MAK.dao;
import com.stripbandunk.jwidget.annotation.TableColumn;
import java.sql.Timestamp;
import java.util.Objects;
/**
*
* @author Alvian Syakh
*/
public class Mapel {
private int id;
@TableColumn(number = 1, name = "Kode Mapel")
private String kd_mapel;
@TableColumn(number = 2, name = "Mata Pelajaran")
private String nama_mapel;
@TableColumn(number = 3, name = "Keterangan")
private String keterangan;
private int flag;
private String createdby;
private Timestamp createddate;
private String updatedby;
private Timestamp updateddate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getKd_mapel() {
return kd_mapel;
}
public void setKd_mapel(String kd_mapel) {
this.kd_mapel = kd_mapel;
}
public String getNama_mapel() {
return nama_mapel;
}
public void setNama_mapel(String nama_mapel) {
this.nama_mapel = nama_mapel;
}
public String getKeterangan() {
return keterangan;
}
public void setKeterangan(String keterangan) {
this.keterangan = keterangan;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getCreatedby() {
return createdby;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public Timestamp getCreateddate() {
return createddate;
}
public void setCreateddate(Timestamp createddate) {
this.createddate = createddate;
}
public String getUpdatedby() {
return updatedby;
}
public void setUpdatedby(String updatedby) {
this.updatedby = updatedby;
}
public Timestamp getUpdateddate() {
return updateddate;
}
public void setUpdateddate(Timestamp updateddate) {
this.updateddate = updateddate;
}
@Override
public String toString() {
return getKd_mapel()+"-"+getNama_mapel();
}
@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + Objects.hashCode(this.kd_mapel);
hash = 79 * hash + Objects.hashCode(this.nama_mapel);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Mapel other = (Mapel) obj;
if (!Objects.equals(this.kd_mapel, other.kd_mapel)) {
return false;
}
if (!Objects.equals(this.nama_mapel, other.nama_mapel)) {
return false;
}
return true;
}
}
| true |
1960d2a9af283919e7370b4cc47bf406963e9c3c | Java | hiddenpower1/LeetCode | /GrayCode.java | UTF-8 | 586 | 3.140625 | 3 | [] | no_license | import java.util.ArrayList;
public class GrayCode {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(n<0)
return null;
//n ==0
result.add(0);
//n>0
int base = 1;
for(int i = 1;i<=n;i++){
int index = result.size()-1;
for(int j=index;j>=0;j--){
result.add(result.get(j)+base);
}
base = base*2;
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true |
59a381aa6a0c698971d2d40f2f177dfbde3cf228 | Java | AntonSemenov87/Cyb_Selenium | /src/test/java/synchronization_tests/ExplicitWaitTests.java | UTF-8 | 731 | 2.28125 | 2 | [] | no_license | package synchronization_tests;
import Pages.practice_cybertek_pages.DynamicLoading1Page;
import org.testng.annotations.Test;
import utilities.Driver;
public class ExplicitWaitTests {
@Test
public void waitForInputBoxTest () {
// 1 - get the page
Driver.getDriver().get("http://practice.cybertekschool.com/dynamic_loading/1");
// 2 - create Object to use webElements
DynamicLoading1Page dynamicLoading1Page = new DynamicLoading1Page();
// 3 - click on Start button
dynamicLoading1Page.startButton.click();
// 4 - we try to send keys
dynamicLoading1Page.usernameInput.sendKeys("tomsmith");
dynamicLoading1Page.passwordInput.sendKeys("");
}
}
| true |
97711fbdba29909d3c76cf195e3f39d75660658e | Java | black-dog/uocolle-web | /src/main/java/jmason/fish/collection/ServletInitializer.java | UTF-8 | 444 | 1.851563 | 2 | [] | no_license | package jmason.fish.collection;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SuppressWarnings("deprecation")
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FishCollectionApplication.class);
}
} | true |
83473628f07536721b09c28f8dbcd7795b268bdb | Java | helciogc/auladeprogramacao2 | /webArquiteto/JavaSource/br/com/webarquiteto/basicas/Fisica.java | UTF-8 | 879 | 2.515625 | 3 | [] | no_license | package br.com.webarquiteto.basicas;
import java.util.Date;
public class Fisica extends Cliente {
// atributos primarios
private long codFisica;
private String numCpf;
// construtores
public Fisica(String nomePessoa, String telefoneResidencial,
String telefoneComercial, String telefoneCelular,
Date dataNascimento, Endereco endereco, String numCpf) {
super(nomePessoa, telefoneResidencial, telefoneComercial,
telefoneCelular, dataNascimento, endereco);
this.numCpf = numCpf;
}
public Fisica() {
super();
}
// gets e sets
public long getCodFisica() {
return codFisica;
}
public void setCodFisica(long codFisica) {
this.codFisica = codFisica;
}
public String getNumCpf() {
return numCpf;
}
public void setNumCpf(String numCpf) {
this.numCpf = numCpf;
}
}
| true |
a48d67e1ab11c402afd40d8a6b63128a0137e3fe | Java | adufilie/metaas-fork | /src/main/java/uk/co/badgersinfoil/metaas/impl/MXMLASBlockImpl.java | UTF-8 | 1,758 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | package uk.co.badgersinfoil.metaas.impl;
import org.asdt.core.internal.antlr.AS3Parser;
import uk.co.badgersinfoil.metaas.dom.ASField;
import uk.co.badgersinfoil.metaas.dom.ASMethod;
import uk.co.badgersinfoil.metaas.dom.MXMLASBlock;
import uk.co.badgersinfoil.metaas.impl.antlr.LinkedListTree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* @author Anton.I.Neverov
*/
public class MXMLASBlockImpl extends ASTScriptElement implements MXMLASBlock {
public MXMLASBlockImpl(LinkedListTree ast) {
super(ast);
}
public List<String> getImports() {
ASTIterator i = new ASTIterator(ast);
LinkedListTree imp;
List<String> result = new ArrayList<String>();
while ((imp = i.search(AS3Parser.IMPORT)) != null) {
result.add(ASTUtils.identStarText(imp.getFirstChild()));
}
return result;
}
public List<ASField> getFields() {
List<ASField> results = new LinkedList<ASField>();
ASTIterator blockIter = new ASTIterator(ast);
for (; blockIter.hasNext(); ) {
LinkedListTree member = blockIter.next();
if (member.getType() == AS3Parser.VAR_DEF) {
results.add(new ASTASField(member));
}
}
return Collections.unmodifiableList(results);
}
public List<ASMethod> getMethods() {
List<ASMethod> results = new LinkedList<ASMethod>();
ASTIterator blockIter = new ASTIterator(ast);
for (; blockIter.hasNext(); ) {
LinkedListTree member = blockIter.next();
if (member.getType() == AS3Parser.METHOD_DEF) {
results.add(new ASTASMethod(member));
}
}
return Collections.unmodifiableList(results);
}
}
| true |
6e230d0249d12e58871869b75bf2a4c568d55742 | Java | alexfabianojr/Store-Stock | /src/main/java/Application/services/RemoveProductLogic.java | UTF-8 | 2,180 | 2.625 | 3 | [] | no_license | package Application.services;
import org.json.JSONObject;
import javax.imageio.IIOException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.InputMismatchException;
import java.util.stream.Stream;
import static Application.services.RewriteLogic.rewriteLogic;
public class RemoveProductLogic {
public static void removeProductLogic(int primaryKey, int quantity) {
try {
Stream<String> lines = Files.lines(Paths.get("C:\\StockDataBase\\stockdatabase.txt"));
String databaseJSON = lines.skip(primaryKey - 1).findFirst().get();
JSONObject jsonObject = new JSONObject(databaseJSON);
String getName = jsonObject.getString("name");
String getType = jsonObject.getString("type");
Double getWeight = jsonObject.getDouble("weight");
Double getDimension = jsonObject.getDouble("dimension");
Double getPrice = jsonObject.getDouble("price");
int newQuantity = jsonObject.getInt("quantity") - quantity;
rewriteLogic(primaryKey, getName, getType, getWeight, getDimension, getPrice, newQuantity);
}
catch (IllegalStateException exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
catch (IllegalArgumentException exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
catch (NullPointerException exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
catch (ArrayIndexOutOfBoundsException exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
catch (InputMismatchException exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
catch (IOException exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
catch (Exception exception) {
System.out.printf(MessageFormat.format("Error: {0}", exception));
}
}
}
| true |
eee48cb8aeef435c6ff41c0d71db80faefdd0723 | Java | tgirard12/montpellierjug-spock | /src/main/java/com/jugmontpellier/TwitterServiceImpl.java | UTF-8 | 619 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package com.jugmontpellier;
import com.jugmontpellier.entity.Speaker;
import com.jugmontpellier.entity.Talk;
import org.springframework.stereotype.Component;
@Component
public class TwitterServiceImpl implements TwitterService {
@Override
public String getLastTweet(Speaker speaker) {
Talk talk = null;
if (speaker.getTalks() != null)
talk = speaker.getTalks().stream()
.findFirst()
.orElse(null);
if (talk == null)
return "";
return "Ce soir, session " + talk.getTitle() + " au @montpellierjug !!";
}
}
| true |
5d0c178d3d48c915714df63d5de7e8b194de85b7 | Java | RCoccaro3/TirocinioSmart-2.0 | /webapp/src/main/java/it/unisa/di/tirociniosmart/web/ConvenzionamentoForm.java | UTF-8 | 1,765 | 2.203125 | 2 | [] | no_license | package it.unisa.di.tirociniosmart.web;
/**
* Oggetto utilizzato per la mappatura dei campi del form di richiesta convenzionamento HTML. Questo
* oggetto viene passato come parametro ai controller dalla dispatcher servlet quando un utente
* sottomette il modulo di richiesta di convenzionamento.
*/
public class ConvenzionamentoForm extends RegistrazioneForm {
ConvenzionamentoForm() {
super();
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getSesso() {
return sesso;
}
public void setSesso(String sesso) {
this.sesso = sesso;
}
public String getIdAzienda() {
return idAzienda;
}
public void setIdAzienda(String idAzienda) {
this.idAzienda = idAzienda;
}
public String getNomeAzienda() {
return nomeAzienda;
}
public void setNomeAzienda(String nomeAzienda) {
this.nomeAzienda = nomeAzienda;
}
public String getPartitaIvaAzienda() {
return partitaIvaAzienda;
}
public void setPartitaIvaAzienda(String partitaIvaAzienda) {
this.partitaIvaAzienda = partitaIvaAzienda;
}
public String getIndirizzoAzienda() {
return indirizzoAzienda;
}
public void setIndirizzoAzienda(String indirizzoAzienda) {
this.indirizzoAzienda = indirizzoAzienda;
}
public boolean isSenzaBarriere() {
return senzaBarriere;
}
public void setSenzaBarriere(boolean senzaBarriere) {
this.senzaBarriere = senzaBarriere;
}
private String telefono;
private String sesso;
private String idAzienda;
private String nomeAzienda;
private String partitaIvaAzienda;
private String indirizzoAzienda;
private boolean senzaBarriere;
}
| true |
d00925942577cf78c37ebd645b934641e9053680 | Java | kingoneperson/spring-cloud-template | /spring-cloud-service-order/src/main/java/com/storm/spring/cloud/service/order/hystrix/AccountServiceHystrix.java | UTF-8 | 392 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package com.storm.spring.cloud.service.order.hystrix;
import com.storm.spring.cloud.service.order.feign.AccountService;
import com.storm.spring.cloud.service.order.pojo.User;
import org.springframework.stereotype.Component;
@Component
public class AccountServiceHystrix implements AccountService {
@Override
public User getUser(String phoneNum) {
return new User();
}
}
| true |
b7e1212776c14121548dff60e8c0fa08034ca32d | Java | hive4bee/fitness | /fitness/src/main/action/OrderProductAction.java | UTF-8 | 1,261 | 2.140625 | 2 | [] | no_license | package main.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cart.CartDAO;
import cart.CartDTO;
import command.CommandAction;
import member.MemberDAO;
import member.MemberDTO;
//OrderProductAction
public class OrderProductAction implements CommandAction {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
String flag = request.getParameter("flag");
String mid = request.getParameter("mid");
String[] cart_nums = request.getParameterValues("cart_num");
// Enumeration<String> enu = request.getParameterNames();
// while(enu.hasMoreElements()) {
// String imsi = enu.nextElement();
// System.out.println(imsi);
// String[] imsi2 = request.getParameterValues(imsi);
// for(String str : imsi2) {
// System.out.println(str);
// }
// }
MemberDTO mdto =null;
List<CartDTO> list = null;
if(flag.equals("cart")) {
MemberDAO dao = MemberDAO.getInstance();
CartDAO dao2 = CartDAO.getInstance();
mdto=dao.getUserInfo(mid);
list=dao2.getOrderList2(cart_nums);
}
request.setAttribute("list", list);
request.setAttribute("mdto", mdto);
return "/main/orderProduct.jsp";
}
}
| true |
0004460430664cd1cdda935c45d78b8cdb7218d3 | Java | fracz/refactor-extractor | /results-java/apereo--cas/6b121ab0b1c150db9781eca3c8b2c654c803e55f/before/YubiKeyApplicationContextWrapper.java | UTF-8 | 1,086 | 2.015625 | 2 | [] | no_license | package org.jasig.cas.adaptors.yubikey;
import org.jasig.cas.authentication.AuthenticationHandler;
import org.jasig.cas.web.BaseApplicationContextWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* This is {@link YubiKeyApplicationContextWrapper}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Component
public class YubiKeyApplicationContextWrapper extends BaseApplicationContextWrapper {
@Autowired
@Qualifier("yubikeyAuthenticationHandler")
private AuthenticationHandler authenticationHandler;
@Autowired
@Qualifier("yubikeyAuthenticationMetaDataPopulator")
private YubiKeyAuthenticationMetaDataPopulator populator;
/**
* Initialize root application context.
*/
@PostConstruct
protected void initializeRootApplicationContext() {
addAuthenticationHandler(this.authenticationHandler);
addAuthenticationMetadataPopulator(this.populator);
}
} | true |
3e11facf8637f9f4afaf03c5a67c0aa186535e1c | Java | loafer/spring4-tutorials | /spring-event/src/test/java/com/github/loafer/hello/listener/order/ZhangsanListener.java | UTF-8 | 1,027 | 2.59375 | 3 | [
"MIT"
] | permissive | package com.github.loafer.hello.listener.order;
import com.github.loafer.hello.listener.NiHaoEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;
/**
* 当eventType、sourceType都匹配时接收并处理消息
*
* @author zhaojh.
*/
@Component(value = "zhangsan")
public class ZhangsanListener implements SmartApplicationListener {
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return eventType == NiHaoEvent.class;
}
@Override
public boolean supportsSourceType(Class<?> sourceType) {
return sourceType == String.class;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
String message = String.format("张三在李四之前收到了消息:%s", event.getSource());
System.out.println(message);
}
@Override
public int getOrder() {
return 1;
}
}
| true |
44883e5e5913040f49bae57aacebcd37b21b8c96 | Java | wonjin-do/DesignPattern | /designPattern/src/youtube/chap01_Stragy/kevinsVilliage/mode/DrivingMode.java | UTF-8 | 111 | 1.8125 | 2 | [] | no_license | package youtube.chap01_Stragy.kevinsVilliage.mode;
public interface DrivingMode {
void setupDrivingMode();
}
| true |
797b2ecb5645ded6920eac61c09e693c1e756267 | Java | SabujSana/MediCareApp | /app/src/main/java/com/example/medicare/RoktoSolpota.java | UTF-8 | 3,193 | 2.1875 | 2 | [] | no_license | package com.example.medicare;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class RoktoSolpota extends Activity{
TextView tvRoktoSolpota,tvRoktoSolpota1,tvRoktoSolpota2,tvRoktoSolpota3,tvRoktoSolpota4,tvRoktoSolpota5,tvRoktoSolpota6,tvRoktoSolpota7,tvRoktoSolpota8,tvRoktoSolpota9,tvRoktoSolpota10,tvRoktoSolpota11,tvRoktoSolpota12,tvRoktoSolpota13,tvRoktoSolpota14,tvRoktoSolpota15,tvRoktoSolpota16,tvRoktoSolpota17,tvRoktoSolpota18,tvRoktoSolpota19,tvRoktoSolpota20,tvRoktoSolpota21,tvRoktoSolpota22;
Typeface font;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.rokto_solpota);
tvRoktoSolpota=(TextView)findViewById(R.id.tv_roktoSolpota);
tvRoktoSolpota1=(TextView)findViewById(R.id.tv_roktoSolpota1);
tvRoktoSolpota2=(TextView)findViewById(R.id.tv_roktoSolpota2);
tvRoktoSolpota3=(TextView)findViewById(R.id.tv_roktoSolpota3);
tvRoktoSolpota4=(TextView)findViewById(R.id.tv_roktoSolpota4);
tvRoktoSolpota5=(TextView)findViewById(R.id.tv_roktoSolpota5);
tvRoktoSolpota6=(TextView)findViewById(R.id.tv_roktoSolpota6);
tvRoktoSolpota7=(TextView)findViewById(R.id.tv_roktoSolpota7);
tvRoktoSolpota8=(TextView)findViewById(R.id.tv_roktoSolpota8);
tvRoktoSolpota9=(TextView)findViewById(R.id.tv_roktoSolpota9);
tvRoktoSolpota10=(TextView)findViewById(R.id.tv_roktoSolpota10);
tvRoktoSolpota11=(TextView)findViewById(R.id.tv_roktoSolpota11);
tvRoktoSolpota12=(TextView)findViewById(R.id.tv_roktoSolpota12);
tvRoktoSolpota13=(TextView)findViewById(R.id.tv_roktoSolpota13);
tvRoktoSolpota14=(TextView)findViewById(R.id.tv_roktoSolpota14);
tvRoktoSolpota15=(TextView)findViewById(R.id.tv_roktoSolpota15);
tvRoktoSolpota16=(TextView)findViewById(R.id.tv_roktoSolpota16);
tvRoktoSolpota17=(TextView)findViewById(R.id.tv_roktoSolpota17);
tvRoktoSolpota18=(TextView)findViewById(R.id.tv_roktoSolpota18);
tvRoktoSolpota19=(TextView)findViewById(R.id.tv_roktoSolpota19);
tvRoktoSolpota20=(TextView)findViewById(R.id.tv_roktoSolpota20);
tvRoktoSolpota21=(TextView)findViewById(R.id.tv_roktoSolpota21);
tvRoktoSolpota22=(TextView)findViewById(R.id.tv_roktoSolpota22);
font=Typeface.createFromAsset(getAssets(), "S.TTF");
tvRoktoSolpota.setTypeface(font);
tvRoktoSolpota1.setTypeface(font);
tvRoktoSolpota2.setTypeface(font);
tvRoktoSolpota3.setTypeface(font);
tvRoktoSolpota4.setTypeface(font);
tvRoktoSolpota5.setTypeface(font);
tvRoktoSolpota6.setTypeface(font);
tvRoktoSolpota7.setTypeface(font);
tvRoktoSolpota8.setTypeface(font);
tvRoktoSolpota9.setTypeface(font);
tvRoktoSolpota10.setTypeface(font);
tvRoktoSolpota11.setTypeface(font);
tvRoktoSolpota12.setTypeface(font);
tvRoktoSolpota14.setTypeface(font);
tvRoktoSolpota15.setTypeface(font);
tvRoktoSolpota16.setTypeface(font);
tvRoktoSolpota17.setTypeface(font);
tvRoktoSolpota18.setTypeface(font);
tvRoktoSolpota19.setTypeface(font);
tvRoktoSolpota20.setTypeface(font);
tvRoktoSolpota21.setTypeface(font);
tvRoktoSolpota22.setTypeface(font);
}
}
| true |
3556747fa601e594d5c0511568762cae6d7b9b57 | Java | wangsf66/smt-app | /src/main/java/com/smt/app/SmtAppApplication.java | UTF-8 | 800 | 1.734375 | 2 | [] | no_license | package com.smt.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import com.douglei.orm.spring.boot.starter.TransactionComponentScan;
import com.smt.app.util.MappingContextRegisterListener;
@EnableEurekaClient
@SpringBootApplication
@ComponentScan(basePackages= "com.smt")
@TransactionComponentScan(packages = "com.smt")
public class SmtAppApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SmtAppApplication.class);
springApplication.addListeners(new MappingContextRegisterListener());
springApplication.run(args);
}
}
| true |
a70487ac721858f76073ac7ae593f4e5f644b189 | Java | teslaCA/AP_ItemValidationService | /src/main/java/org/opentestsystem/ap/ivs/config/IvsProperties.java | UTF-8 | 629 | 1.515625 | 2 | [] | no_license | package org.opentestsystem.ap.ivs.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "ivs")
public class IvsProperties {
private String gitLabSecret;
private String validationQueue;
private String validationTopicExchange;
private String systemUserName;
private String systemFullName;
private String cptExecutablePath;
private String validationCommitMessage = "Validating item commit ";
}
| true |
2e2dfbd9149b73391993e952c217c7fcf76eedfd | Java | arjunshahi/CRUD-with-java-spring | /src/main/java/com/itn/controller/AdminController.java | UTF-8 | 404 | 1.648438 | 2 | [] | no_license |
package com.itn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class AdminController {
@RequestMapping(value={"/Admin/Home","/admin/home"}, method=RequestMethod.GET)
public String adminPage(){
return"adminpage";
}
}
| true |
c34ece5f54057ddd6551b8b0d129d19fd167e5dc | Java | bob313/CS3114Proj4 | /src/AirObject.java | UTF-8 | 4,134 | 3.203125 | 3 | [] | no_license | /**
* Air traffic control general object type interface
* All tracked objects must have a bounding prism and a name
* *
*
* @author {Your Name Here}
* @version {Put Something Here}
*
*/
public class AirObject implements Comparable<AirObject> {
private String obj;
private String name; // Name for this AirObject
private int xOrig;
private int yOrig;
private int zOrig;
private int xWidth;
private int yWidth;
private int zWidth;
/**
* * Constructor for base AirObject
*
* @param object
* The object
* @param inname
* name
* @param xorig
* xorigin
* @param yorig
* yorigin
* @param zorig
* zorigin
* @param xwidth
* xwidth
* @param ywidth
* ywidth
* @param zwidth
* zwidth
*/
public AirObject(
String object,
String inname,
String xorig,
String yorig,
String zorig,
String xwidth,
String ywidth,
String zwidth) {
obj = object;
name = inname;
xOrig = Integer.parseInt(xorig);
yOrig = Integer.parseInt(yorig);
zOrig = Integer.parseInt(zorig);
xWidth = Integer.parseInt(xwidth);
yWidth = Integer.parseInt(ywidth);
zWidth = Integer.parseInt(zwidth);
}
/**
* Gets the object type
*
* @return the type of object
*/
public String getObject() {
return obj;
}
/**
* Getter for x origin
*
* @return x origin
*/
public int getXorig() {
return xOrig;
}
/**
* Getter for x width
*
* @return x width
*/
public int getXwidth() {
return xWidth;
}
/**
* Getter for y origin
*
* @return y origin
*/
public int getYorig() {
return yOrig;
}
/**
* Getter for y width
*
* @return y width
*/
public int getYwidth() {
return yWidth;
}
/**
* Getter for z origin
*
* @return z origin
*/
public int getZorig() {
return zOrig;
}
/**
* Getter for z width
*
* @return z width
*/
public int getZwidth() {
return zWidth;
}
/**
* Getter for name
*
* @return name
*/
public String getName() {
return name;
}
/**
* Compare against a (name) String.
*
* @param it
* The String to compare to
*
* @return Standard values for compareTo
*/
public int compareTo(AirObject it) {
return name.compareTo(it.getName());
}
/**
* Returns a string containing fields
*
* @return a string form
*/
public String string() {
return (this.getObject().substring(0, 1).toUpperCase() + this
.getObject().substring(1) + " " + this.getName() + " " + this
.getXorig() + " " + this.getYorig() + " " + this.getZorig()
+ " " + this.getXwidth() + " " + this.getYwidth() + " " + this
.getZwidth());
}
/**
*
* @param level
* is which dimension
* @return the dimension
*/
public int getDimStart(int level) {
if (level == 0) {
return xOrig;
}
else if (level == 1) {
return yOrig;
}
else {
return zOrig;
}
}
/**
*
* @param level
* is which dimension
* @return the dimension
*/
public int getDimEnd(int level) {
if (level == 0) {
return (xOrig + xWidth);
}
else if (level == 1) {
return (yOrig + yWidth);
}
else {
return (zOrig + zWidth);
}
}
}
| true |
b349d194ac449a9cb882fbcf1d343c02561ef409 | Java | heroumcaslu/maratona-java | /src/com/devdojo/blocosdeinicializacao/Customer.java | UTF-8 | 778 | 3.8125 | 4 | [] | no_license | package com.devdojo.blocosdeinicializacao;
public class Customer {
//1 - Primeiro é alocado espaço na memória para o objeto
//2 - Cada atributo é criado com os valores default ou explicitados
//3 - Bloco de inicialização é executado
//4 - Construtor é executado
private int[] installments = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
//Bloco de inicialização (deve ser criado antes do construtor, pórem não importa onde você crie ele será executado antes).
{
System.out.println("Bloco de inicialização");
}
public Customer() {
System.out.println("Construtor");
}
public int[] getInstallments() {
return installments;
}
public void setInstallments(int[] installments) {
this.installments = installments;
}
}
| true |
98067b9adf0c1b468e304271ec32b9a3202016cb | Java | ukiras123/DataStructure-Algorithm | /src/com/datastructure/treeNgraph/graph/EdgeList.java | UTF-8 | 457 | 3.09375 | 3 | [
"MIT"
] | permissive | package com.datastructure.treeNgraph.graph;
/**
* Created by Kiran on 9/26/18.
*/
public class EdgeList {
int[][] graph = {{0, 1}, {1, 2}, {1, 3}, {2, 3}};
// Since node 3 has edges to nodes 1 and 2, {1, 3} and {2, 3} are in the edge list.
// Sometimes it's helpful to pair our edge list with a list of all the nodes.
// For example, what if a node doesn't have any edges connected to it? It wouldn't show up in our edge list at all!
}
| true |
3ab4399c133e20542ee7895a17fc82ad165523ec | Java | MarkoNad/Procedural-landscape-and-roads | /src/hr/fer/zemris/engine/texture/ModelTexture.java | UTF-8 | 2,488 | 2.671875 | 3 | [] | no_license | package hr.fer.zemris.engine.texture;
public class ModelTexture {
private static final int NO_ID = -1;
private final int textureID;
private final int normalMapID;
private float shineDamper = 1;
private float reflectivity = 0;
private boolean hasTransparency = false;
private boolean usesFakeLighting = false;
public ModelTexture(int textureID) {
this(textureID, NO_ID);
}
public ModelTexture(int textureID, int normalMapID) {
this.textureID = textureID;
this.normalMapID = normalMapID;
}
public boolean hasTransparency() {
return hasTransparency;
}
public void setHasTransparency(boolean hasTransparency) {
this.hasTransparency = hasTransparency;
}
public boolean usesFakeLighting() {
return usesFakeLighting;
}
public void setUsesFakeLighting(boolean usesFakeLighting) {
this.usesFakeLighting = usesFakeLighting;
}
public int getTextureID() {
return textureID;
}
public int getNormalMapID() {
return normalMapID;
}
public float getShineDamper() {
return shineDamper;
}
public void setShineDamper(float shineDamper) {
this.shineDamper = shineDamper;
}
public float getReflectivity() {
return reflectivity;
}
public void setReflectivity(float reflectivity) {
this.reflectivity = reflectivity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (hasTransparency ? 1231 : 1237);
result = prime * result + normalMapID;
result = prime * result + Float.floatToIntBits(reflectivity);
result = prime * result + Float.floatToIntBits(shineDamper);
result = prime * result + textureID;
result = prime * result + (usesFakeLighting ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ModelTexture other = (ModelTexture) obj;
if (hasTransparency != other.hasTransparency)
return false;
if (normalMapID != other.normalMapID)
return false;
if (Float.floatToIntBits(reflectivity) != Float.floatToIntBits(other.reflectivity))
return false;
if (Float.floatToIntBits(shineDamper) != Float.floatToIntBits(other.shineDamper))
return false;
if (textureID != other.textureID)
return false;
if (usesFakeLighting != other.usesFakeLighting)
return false;
return true;
}
}
| true |
a1646fbaaeed14bb94b38ee554806a63a48a7e9f | Java | NaeemHafiz/BookApp | /app/src/main/java/com/mtechsoft/bookapp/data/local/AppRoomDatabase.java | UTF-8 | 1,378 | 2.296875 | 2 | [] | no_license | //package com.mtechsoft.bookapp.data.local;
//
//import android.content.Context;
//
//import androidx.annotation.NonNull;
//
//import com.mtechsoft.bookapp.data.local.model.Chapter;
//
//
//@Database(entities = {Chapter.class}, version = 1, exportSchema = false)
//public abstract class AppRoomDatabase extends RoomDatabase {
//
//// public abstract DepartmentDao departmentDao();
//
// private static volatile AppRoomDatabase INSTANCE;
//
// public static AppRoomDatabase getDatabase(final Context context) {
// if (INSTANCE == null) {
// synchronized (AppRoomDatabase.class) {
// if (INSTANCE == null) {
// // Create database here
// INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
// AppRoomDatabase.class, "app_database")
// .addCallback(sRoomDatabaseCallback)
// .addMigrations()
// .build();
// }
// }
// }
// return INSTANCE;
// }
//
// private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
// @Override
// public void onOpen(@NonNull SupportSQLiteDatabase db) {
// super.onOpen(db);
// // Add any data in database here
// }
// };
//
//} | true |
d7ed751ef231dd2a6523888c1d4ed82bfadcd112 | Java | League-of-Legends-Math-Model/champStats | /calculated/src/calculated/runeTranslate.java | UTF-8 | 3,071 | 2.609375 | 3 | [] | no_license | package calculated;
import org.json.*;
import java.util.*;
public class runeTranslate {
JSONObject runeData;
ArrayList<Rune> statMods;
public ArrayList<Rune> getStats(){
return statMods;
}
private void setRuneInfo() throws JSONException {
for (Iterator<?> jkey = runeData.keys(); jkey.hasNext(); ){
String helper = (String)jkey.next();
int friend = runeData.getJSONObject(helper).getInt("id");
JSONObject stat = runeData.getJSONObject(helper).getJSONObject("stat");
Iterator<String> skey = stat.keys();
Rune blue = new Rune(1000, 0, 0);
while (skey.hasNext()){
String modifier = (String)skey.next();
switch(modifier){
case "FlatArmorMod":
blue = new Rune(friend, 8, stat.getDouble(modifier));
break;
case "FlatHPPoolMod":
blue = new Rune(friend, 0, stat.getDouble(modifier));
break;
case "FlatMPPoolMod":
blue = new Rune(friend, 2, stat.getDouble(modifier));
break;
case "FlatMagicDamageMod":
blue = new Rune(friend, 6, stat.getDouble(modifier));
break;
case "FlatPhysicalDamageMod":
blue = new Rune(friend, 4, stat.getDouble(modifier));
break;
case "FlatSpellBlockMod":
blue = new Rune(friend, 10, stat.getDouble(modifier));
break;
case "PercentAttackSpeedMod":
blue = new Rune(friend, 14, stat.getDouble(modifier));
break;
case "PercentHPPoolMod":
blue = new Rune(friend, 15, 1 + stat.getDouble(modifier));
break;
case "PercentMovementSpeedMod":
blue = new Rune(friend, 16, stat.getDouble(modifier));
break;
case "rFlatArmorModPerLevel":
blue = new Rune(friend, 9, stat.getDouble(modifier));
break;
case "rFlatHPModPerLevel":
blue = new Rune(friend, 1, stat.getDouble(modifier));
break;
case "rFlatMPModPerLevel":
blue = new Rune(friend, 3, stat.getDouble(modifier));
break;
case "rFlatMagicDamageModPerLevel":
blue = new Rune(friend, 7, stat.getDouble(modifier));
break;
case "rFlatPhysicalDamageModPerLevel":
blue = new Rune(friend, 5, stat.getDouble(modifier));
break;
case "rFlatSpellBlockModPerLevel":
blue = new Rune(friend, 11, stat.getDouble(modifier));
break;
case "rPercentCooldownMod":
blue = new Rune(friend, 12, stat.getDouble(modifier));
break;
case "rPercentCooldownModPerLevel":
blue = new Rune(friend, 13, stat.getDouble(modifier));
break;
default:
}
statMods.add(blue);
}
}
}
/*
* double hp;
double hpperlevel;
double mp;
double mpperlevel;
double armor;
double armorperlevel;
double attackdamage;
double attackdamageperlevel;
double abilitypower;
double abilitypowerperlevel;
double spellblock;
double spellblockperlevel;
double movespeed;
double attackspeedoffset;
double attackspeedperlevel;
double cooldownreduction;
double bonusattackspeed;
double attackspeed;
*/
public runeTranslate(JSONObject r) throws JSONException {
runeData = r.getJSONObject("data");
statMods = new ArrayList<Rune>();
setRuneInfo();
}
}
| true |
03ce2ce020178b9c7df623ade06d3961c7e4a1b0 | Java | velevatanas/GeoGuide | /src/MainPackage/MainMenu.java | UTF-8 | 1,089 | 3.546875 | 4 | [] | no_license | package MainPackage;
import java.io.IOException;
public class MainMenu extends Menu {
private String startingWords;
public MainMenu() {
super();
setItems("1 - Continents", "2 - Countries", "9 - Exit");
startingWords = "LET ME SHOW YOU SOME OF THE WORLD!\n"
+ "CHOOSE FROM THE MENU WHETHER YOU WANT INFO FOR A SPECIFIC COUNTRY OR FOR A WHOLE CONTINENT";
}
@Override
protected void printMenu() {
System.out.println(startingWords);
sleep();
beep();
drawLine();
}
protected int takeChoiceForMainMenu() {
int choice = 0;
while (choice != 1 && choice != 2 && choice != 9) {
try {
String input = getIn().readLine();
if (isDigit(input)) {
throw new GeoException();
}
choice = Integer.parseInt(input);
if ((choice != 1 && choice != 2 && choice != 9)) {
throw new GeoException();
}
} catch (GeoException e) {
printItems();
} catch (IOException e) {
printItems();
} catch (NumberFormatException e) {
printItems();
}
}
return choice;
}
}
| true |
d6a1fd8cdca72b2c48edf4a99656f3d30d62bf96 | Java | vpzomtrrfrt/theandrewmod | /java/net/reederhome/colin/theandrewmod/command/SevenEightNineCommand.java | UTF-8 | 3,954 | 2.140625 | 2 | [] | no_license | package net.reederhome.colin.theandrewmod.command;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityFallingBlock;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.reederhome.colin.theandrewmod.TheAndrewMod;
public class SevenEightNineCommand implements ICommand {
private List<String> aliases;
public SevenEightNineCommand() {
this.aliases = new ArrayList();
this.aliases.add("789");
}
@Override
public int compareTo(Object arg0) {
return 0;
}
@Override
public List addTabCompletionOptions(ICommandSender var1, String[] var2) {
return var2.length == 1 ? CommandBase.getListOfStringsMatchingLastWord(var2, MinecraftServer.getServer().getAllUsernames()) : null;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender var1) {
return var1.canCommandSenderUseCommand(3, getCommandName());
}
@Override
public List getCommandAliases() {
return this.aliases;
}
@Override
public String getCommandName() {
return this.aliases.get(0);
}
@Override
public String getCommandUsage(ICommandSender var1) {
return "789 [player]";
}
@Override
public boolean isUsernameIndex(String[] var1, int var2) {
return false;
}
static Entity forEnemy;
@Override
public void processCommand(ICommandSender var1, String[] var2) {
World world = var1.getEntityWorld();
double posX, posY, posZ;
if(var2.length>0) {
EntityPlayer ep = CommandBase.getPlayer(var1,var2[0]);
if(ep==null) {var1.addChatMessage(new ChatComponentText("Player "+var2[0]+" doesn't exist!"));return;}
posX=ep.posX;
posY=ep.posY;
posZ=ep.posZ;
}
else if(var1 instanceof EntityPlayer) {
EntityPlayer ep = (EntityPlayer) var1;
posX=ep.posX;
posY=ep.posY;
posZ=ep.posZ;
}
else {
ChunkCoordinates coords = var1.getPlayerCoordinates();
posX=coords.posX;
posY=coords.posY;
posZ=coords.posZ;
}
EntityItem seven = new EntityItem(world, posX, posY+3, posZ, new ItemStack(Items.diamond,7));
world.spawnEntityInWorld(seven);
EntityItem eight = new EntityItem(world, posX, posY+5, posZ, new ItemStack(Items.emerald,8));
world.spawnEntityInWorld(eight);
forEnemy=null;
if(var1 instanceof Entity&&var2.length>0) {
forEnemy=(Entity) var1;
}
for(int i = 0; i < 9; i++) {
EntityFallingBlock nine = new EntityFallingBlock(world, posX, posY+9+i, posZ, Blocks.anvil) {
Entity enemy = forEnemy;
protected void fall(float par1)
{
if (true)
{
int var2 = MathHelper.ceiling_float_int(par1 - 1.0F);
if (var2 > 0)
{
ArrayList var3 = new ArrayList(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox));
DamageSource var5 = TheAndrewMod.deathBy789;
Iterator var6 = var3.iterator();
while (var6.hasNext())
{
Entity var7 = (Entity)var6.next();
if(enemy==null) {var7.attackEntityFrom(var5,20.0f);}
else var7.attackEntityFrom(new EntityDamageSource(TheAndrewMod.deathBy789.damageType+".player", enemy), 20.0f);
}
}
}
}
};
nine.field_145812_b=1;
world.spawnEntityInWorld(nine);
}
}
}
| true |
670d9324939c19cfdd04de6867b8156100b88e5c | Java | SarahCam/codeclan_work | /week_07/day_2/StereoLab/src/main/java/MP3.java | UTF-8 | 164 | 2.390625 | 2 | [] | no_license | public class MP3 implements IConnect {
public MP3() {
}
@Override
public String connect(Stereo stereo) {
return "Connected: MP3";
}
}
| true |
de5428de393a6d632c05abb96dc422867790ffa6 | Java | B-Z-Web-Developing-Inc/socialmedia-1 | /src/main/java/pl/coderslab/socialmedia/service/implementation/TweetServiceImpl.java | UTF-8 | 1,649 | 2.109375 | 2 | [] | no_license | package pl.coderslab.socialmedia.service.implementation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.coderslab.socialmedia.model.Tweet;
import pl.coderslab.socialmedia.model.User;
import pl.coderslab.socialmedia.repository.TweetRepository;
import pl.coderslab.socialmedia.service.TweetService;
import java.util.ArrayList;
import java.util.List;
@Service
public class TweetServiceImpl implements TweetService {
@Autowired
TweetRepository tweetRepository;
@Override
public List<Tweet> findAllByAuthor(User author) {
try {
List<Tweet> tweets=tweetRepository.findAllByAuthor(author);
return tweets;
} catch (NullPointerException e) {
e.printStackTrace();
}
return new ArrayList<>();
}
@Override
public Tweet save(Tweet tweet) {
return tweetRepository.saveAndFlush(tweet);
}
@Override
public List<Tweet> findAllByAuthorIn(List<User> authors) {
try {
List<Tweet> tweets=tweetRepository.findAllByAuthorIn(authors);
return tweets;
} catch (NullPointerException e) {
e.printStackTrace();
}
return new ArrayList<>();
}
@Override
public Tweet findById(long tweetId) {
try {
return tweetRepository.findById(tweetId);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Tweet> findAllByGroup_Id(long id) {
return tweetRepository.findAllByGroup_Id(id);
}
}
| true |
82a7348f52087f4fc28f99db81386eea390e9b4e | Java | RomainGuarinoni/ImageJAVA | /Expr.java | UTF-8 | 1,545 | 3.75 | 4 | [
"MIT"
] | permissive | class Expr {
public double eval(double x, double y) {
return 0;
}
}
class X extends Expr {
public double eval(double x, double y) {
return x;
}
public String toString() {
return ("X");
}
}
class Y extends Expr {
public double eval(double x, double y) {
return y;
}
public String toString() {
return ("Y");
}
}
class Sin extends Expr {
Expr op;
Sin(Expr o) {
op = o;
}
public double eval(double x, double y) {
return (Math.sin(Math.PI * op.eval(x, y)));
}
public String toString() {
return ("sin(Pi*" + op + ")");
}
}
class Cos extends Expr {
Expr op;
Cos(Expr o) {
op = o;
}
public double eval(double x, double y) {
return Math.cos(Math.PI * op.eval(x, y));
}
public String toString() {
return ("cos(Pi*" + op + ")");
}
}
class Moyenne extends Expr {
Expr op1;
Expr op2;
Moyenne(Expr o1, Expr o2) {
op1 = o1;
op2 = o2;
}
public double eval(double x, double y) {
return (op1.eval(x, y) + op2.eval(x, y)) / 2;
}
public String toString() {
return ("(" + op1 + "+" + op2 + ")/2");
}
}
class Mult extends Expr {
Expr op1;
Expr op2;
Mult(Expr o1, Expr o2) {
op1 = o1;
op2 = o2;
}
public double eval(double x, double y) {
return op1.eval(x, y) * op2.eval(x, y);
}
public String toString() {
return (op1 + "*" + op2);
}
} | true |
65810fd65ce88bed216c8dca9d8902f13a1aa20f | Java | taraskovaliv/webcam_handler | /src/main/java/com/kovaliv/imageHandlers/Filters/Filter.java | UTF-8 | 165 | 2.171875 | 2 | [] | no_license | package com.kovaliv.imageHandlers.Filters;
import java.awt.image.BufferedImage;
public interface Filter {
BufferedImage filter(BufferedImage bufferedImage);
}
| true |
6832c63fcc5c5d4154e771ecd74d4ddafaed0a2c | Java | rhuanpablo13/BLVendasSimples | /src/sistemavendas/vendas/NCarrinhoCompras.java | UTF-8 | 16,582 | 2.6875 | 3 | [] | 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 sistemavendas.vendas;
import infra.abstratas.NegocioSimples;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import sistemavendas.controle.CProduto;
import sistemavendas.negocio.NProduto;
/**
*
* @author rhuan
*/
public class NCarrinhoCompras extends NegocioSimples {
private String descricao;
private HashMap<NProduto, Integer> produtos;
public NCarrinhoCompras() {
this.produtos = new HashMap();
SimpleDateFormat formate = new SimpleDateFormat("dd/MM/yyyy");
String dateFormat = formate.format(new Date());
this.descricao = ("carrinho_" + dateFormat);
}
public NCarrinhoCompras(int id, String descricao) {
this.id = id;
this.descricao = descricao;
this.produtos = new HashMap();
}
public NCarrinhoCompras(HashMap<NProduto, Integer> produtos) {
this.produtos = produtos;
}
/////////////// MÉTODOS PARA ADICIONAR PRODUTOS ////////////////////////
/**
* @param produto
* @param quantidade
* @return true para adicionado, false para não adicionado
*/
public boolean adicionarProduto(NProduto produto, Integer quantidade) throws IllegalArgumentException {
// Se o carrinho estiver vazio ou não tiver o produto passado por parametro
if (produtos.isEmpty() || !produtos.containsKey(produto)) {
//System.out.println(produto.toString());
produtos.put(produto, quantidade);
return true;
}
// Se o produto já existe no carrinho
if (produtos.containsKey(produto)) {
int quantidadeJaNoCarrinho = produtos.get(produto);
boolean podeAdicionar = existeQuantidadeSuficienteEmEstoque(produto, quantidade, quantidadeJaNoCarrinho);
if (podeAdicionar) {
produtos.put(produto, (quantidade + quantidadeJaNoCarrinho));
} else {
throw new IllegalArgumentException("Não existe quantidade em estoque suficiente do produto: " + produto.getCodigo() + " - " + produto.getNome());
}
}
return true;
}
/**
* Verifica se a somatoria da quantidade do produto que já existe no carrinho, com
* a quantidade que o usuário deseja adicionar, é menor que a quantidade em estoque.
* @param produto
* @param quantidade
* @param quantidadeJaNoCarrinho
* @return
*/
private boolean existeQuantidadeSuficienteEmEstoque(NProduto produto, Integer quantidade, Integer quantidadeJaNoCarrinho) {
// se tentar adicionar mais produtos que disponível no estoque retorna false
int soma = quantidade + quantidadeJaNoCarrinho;
return (soma <= produto.getQtdEstoque());
}
/**
* Verifica se a somatoria da quantidade do produto que já existe no carrinho, com
* a quantidade que o usuário deseja adicionar, é menor que a quantidade em estoque.
* @param produto
* @param quantidade
* @return
*/
public boolean existeQuantidadeSuficienteEmEstoque(NProduto produto, Integer quantidade) {
// se tentar adicionar mais produtos que disponível no estoque retorna false
if (produtos.containsKey(produto)) {
int quantidadeJaNoCarrinho = produtos.get(produto);
return existeQuantidadeSuficienteEmEstoque(produto, quantidade, quantidadeJaNoCarrinho);
}
return false;
}
/////////////// MÉTODOS PARA REMOVER PRODUTOS ////////////////////////
public void removerTodos(NProduto produto) {
if (produtos.containsKey(produto)) {
produtos.remove(produto);
}
}
public void removerQuantidadeProduto(NProduto produto, Integer quantidade) {
if (produtos.containsKey(produto)) {
Integer qtdJaNoCarrinho = produtos.get(produto);
if (qtdJaNoCarrinho < quantidade) {
produtos.remove(produto);
} else {
produtos.replace(produto, (qtdJaNoCarrinho - quantidade));
}
}
}
/////////////// MÉTODOS PARA RECUPERAR PRODUTOS ////////////////////////
public List<NProduto> buscarProdutos(String nome) {
List<NProduto> temp = new ArrayList();
for (Map.Entry<NProduto, Integer> produto : produtos.entrySet()) {
NProduto key = produto.getKey();
if (key.getNome().equals(nome)) {
temp.add(key);
}
}
return temp;
}
public List<NProduto> buscarProduto(Integer codigo) {
List<NProduto> temp = new ArrayList();
for (Map.Entry<NProduto, Integer> produto : produtos.entrySet()) {
NProduto key = produto.getKey();
if (key.getCodigo().equals(codigo)) {
temp.add(key);
}
}
return temp;
}
public List<NProduto> buscarProdutoPorId(Integer id) {
List<NProduto> temp = new ArrayList();
for (Map.Entry<NProduto, Integer> produto : produtos.entrySet()) {
NProduto key = produto.getKey();
if (key.getId().equals(id)) {
temp.add(key);
}
}
return temp;
}
public List<NProduto> buscarProdutoPorGrupo(Integer idGrupo) {
List<NProduto> temp = new ArrayList();
for (Map.Entry<NProduto, Integer> produto : produtos.entrySet()) {
NProduto key = produto.getKey();
if (key.getIdGrupo().equals(idGrupo)) {
temp.add(key);
}
}
return temp;
}
public List<NProduto> buscarProdutoPorFornecedor(Integer idFornecedor) {
List<NProduto> temp = new ArrayList();
for (Map.Entry<NProduto, Integer> produto : produtos.entrySet()) {
NProduto key = produto.getKey();
if (key.getIdFornecedor().equals(idFornecedor)) {
temp.add(key);
}
}
return temp;
}
public HashMap<NProduto, Integer> buscarTodosProdutos() {
return produtos;
}
public List<NProduto> buscarListaProdutos() {
List<NProduto> ps = new ArrayList();
for (Map.Entry<NProduto, Integer> entry : produtos.entrySet()) {
ps.add(entry.getKey());
}
return ps;
}
public int count() {
return produtos.size();
}
////////// MÉTODOS PARA ALTERAÇÕES DE PRODUTOS NO CARRINHO /////////////////
public void alteraQuantidade(NProduto produto, Integer novaQuantidade) throws IllegalArgumentException {
if (produtos.containsKey(produto)) {
if (produto.getQtdEstoque() >= novaQuantidade) {
produtos.replace(produto, novaQuantidade);
} else {
throw new IllegalArgumentException("Não existe quantidade em estoque suficiente do produto: " + produto.getCodigo() + " - " + produto.getNome());
}
}
}
/////////////////////// MÉTODOS DE PROCESSAMENTO ///////////////////////////
/**
* Calcula o valor total do carrinho de compras
* @return Double
*/
public Double getTotal() {
Double soma = (double) 0;
for (Map.Entry<NProduto, Integer> entrySet : produtos.entrySet()) {
NProduto produto = entrySet.getKey();
Integer quantidade = entrySet.getValue();
soma += calculaTotalPorProduto(produto, quantidade);
}
return soma;
}
private Double calculaTotalPorProduto(NProduto produto, Integer quantidade) {
return produto.getValorVenda() * quantidade;
}
/**
* Aplica desconto sobre o valor do total do carrinho de compras,
* podendo aplicar um desconto em valor monetário, ou porcentagem
*
* @param valorDesconto
* @param tipo
* @return Double | Valor total do carrinho subtraido do desconto aplicado
* @throws Exception
*/
public Double aplicarDesconto(Double valorDesconto, TipoDesconto tipo) throws Exception {
Double total = getTotal();
switch (tipo) {
case DINHEIRO:
return total - valorDesconto;
case PORCENTAGEM:
return (total - (total * valorDesconto) / 100);
}
throw new Exception("Não foi possível aplicar desconto!");
}
/**
* Aplica desconto sobre o valor do total do carrinho de compras,
* podendo aplicar um desconto em valor monetário, ou porcentagem
*
* @param valorTotal
* @param valorDesconto
* @param tipo
* @return Double | Valor total do carrinho subtraido do desconto aplicado
* @throws Exception
*/
public Double aplicarDesconto(Double valorTotal, Double valorDesconto, TipoDesconto tipo) throws Exception {
switch (tipo) {
case DINHEIRO:
return valorTotal - valorDesconto;
case PORCENTAGEM:
return (valorTotal - (valorTotal * valorDesconto) / 100);
}
throw new Exception("Não foi possível aplicar desconto!");
}
public Double aplicarDesconto(Double valorTotal, Float valorDesconto, TipoDesconto tipo) throws Exception {
switch (tipo) {
case DINHEIRO:
return valorTotal - valorDesconto;
case PORCENTAGEM:
return (valorTotal - (valorTotal * valorDesconto) / 100);
}
throw new Exception("Não foi possível aplicar desconto!");
}
public Double aplicarDesconto(BigDecimal valorTotal, Double valorDesconto, TipoDesconto tipo) throws Exception {
switch (tipo) {
case DINHEIRO:
return valorTotal.doubleValue() - valorDesconto;
case PORCENTAGEM:
return (valorTotal.doubleValue() - (valorTotal.doubleValue() * valorDesconto) / 100);
}
throw new Exception("Não foi possível aplicar desconto!");
}
@Override
public String toString() {
return "CarrinhoCompras = " + "id: " + id + ", descricao: " + descricao + ", produtos: \n" + produtos + "\n";
}
@Override
public Integer getId() {
return super.getId(); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setId(Integer id) {
super.setId(id); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final NCarrinhoCompras other = (NCarrinhoCompras) obj;
if (!Objects.equals(other.getId(), this.id)) return false;
if (!Objects.equals(other.getTotal(), this.getTotal())) return false;
if (!Objects.equals(other.count(), this.count())) return false;
for (Map.Entry<NProduto, Integer> entry : other.produtos.entrySet()) {
NProduto produtoother = entry.getKey();
Integer quantidadeother = entry.getValue();
/* Verifica se neste carrinho contem o produto do outro carrinho*/
if (this.produtos.containsKey(produtoother)) {
Integer quantidadeLocal = this.produtos.get(produtoother);
/* Verifica se houve alteração na quantidade de produtos deste carrinho */
if (!Objects.equals(quantidadeLocal, quantidadeother)) return false;
} else {
return false;
}
}
return true;
}
/**
* Subtrai este carrinho pelo passado por parametro
* @param carrinho
* @return
*/
public NCarrinhoCompras menos(NCarrinhoCompras carrinho) {
HashMap<NProduto, Integer> produtosRetorno = new HashMap();
for (Map.Entry<NProduto, Integer> entry : this.produtos.entrySet()) {
NProduto produto = entry.getKey();
Integer quantidade = entry.getValue();
if (!carrinho.produtos.containsKey(produto)) {
Integer quantidadeAntes =
produtosRetorno.put(produto, (quantidade));
}
}
return new NCarrinhoCompras(produtosRetorno);
}
public boolean temMaisProdutosQue(NCarrinhoCompras carrinho) {
if (this.count() > carrinho.count()) return true;
if (this.count() < carrinho.count()) return false;
/* Compra a quantidade */
return this.quatidadeItens() > carrinho.quatidadeItens();
}
public NCarrinhoCompras recuperarDiferencaEntreCarrinhos(NCarrinhoCompras carrinhoAntigo) {
boolean include = false; // incluir em [produtosRetorno] os produtos excedentes do carrinho
HashMap<NProduto, Integer> produtosRetorno = new HashMap();
HashMap<NProduto, Integer> produtosA;
HashMap<NProduto, Integer> produtosB;
if (this.count() > carrinhoAntigo.count()) {
produtosA = this.buscarTodosProdutos();
produtosB = carrinhoAntigo.buscarTodosProdutos();
include = true;
} else if (this.count() < carrinhoAntigo.count()){
produtosA = carrinhoAntigo.buscarTodosProdutos();
produtosB = this.buscarTodosProdutos();
} else {
produtosA = this.buscarTodosProdutos();
produtosB = carrinhoAntigo.buscarTodosProdutos();
}
for (Map.Entry<NProduto, Integer> entry : produtosA.entrySet()) {
NProduto produtoA = entry.getKey();
Integer quantidadeA = entry.getValue();
/* Verifica se neste carrinho produtosLocal contem o produto do outro carrinho */
if (produtosB.containsKey(produtoA)) {
Integer quantidadeB = produtosB.get(produtoA);
/* Verifica se houve alteração na quantidade de produtos deste carrinho */
if (!Objects.equals(quantidadeB, quantidadeA)) {
/* Pega a diferença entre a quantidade, para atualizar o estoque corretamente*/
if (quantidadeB > quantidadeA) {
produtosRetorno.put(produtoA, (quantidadeB - quantidadeA));
} else {
produtosRetorno.put(produtoA, quantidadeA);
CProduto controllerProduto = new CProduto();
}
}
} else {
if (include) {
produtosRetorno.put(produtoA, quantidadeA);
}
}
}
return new NCarrinhoCompras(produtosRetorno);
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public boolean isEmpty() {
return produtos.isEmpty();
}
public int quatidadeItens() {
int soma = 0;
for (int qtd : produtos.values()) {
soma += qtd;
}
return soma;
}
public int quatidadeItens(NProduto produto) {
return produtos.containsKey(produto) ? produtos.get(produto) : -1;
}
}
| true |
a41e174fd45b22a22884a9f2012ac1f2981728fe | Java | sahak05/Bank-of-Abdoul | /ATM/src/Main.java | UTF-8 | 8,564 | 3.546875 | 4 | [] | no_license | import java.util.*;
public class Main {
public static void main(String[] args) {
// initialize the scanner
Scanner scan = new Scanner(System.in);
//init the bank
Bank theBank = new Bank("Bank of Abdoul");
//I got a bank now
//for testing to not create a user everytime (Jane Doe of blind spot)
User user = theBank.addUser("Jane","Doe", "1234");
//add a checking account for our user
Account newAccount = new Account("Checking", user, theBank);
user.addAccount(newAccount);
theBank.addAccount(newAccount);
User curUser;
while(true){
//stay in the login prompt until successful login
curUser = Main.mainMenuPrompt(theBank, scan);
//stay in the main menu until user quits
Main.printUserMenu(curUser, scan);
}
}
/**
* Want to keep the login space open until we have a real user of the Bank
* @param {Bank} theBank
* @param {Scanner}scan
* @return User
*/
public static User mainMenuPrompt(Bank theBank, Scanner scan) {
//inits
String userID, pin;
User authUser;
//prompt the user for user ID/pin combo until a correct one is reached
do {
System.out.printf("\n\nWelcome to %s\n\n", theBank.getName());
System.out.print("Enter user ID: ");
userID=scan.nextLine();
System.out.print("Enter pin: ");
pin = scan.nextLine();
//try to get the user correspond to the ID/pin combo
authUser = theBank.userLogin(userID, pin);
if(authUser == null)
System.out.println("Incorrect user ID/pin combination. Please try again");
}
while(authUser==null); //continue looping untill successful login
return authUser;
}
public static void printUserMenu(User theUser, Scanner sc){
//print a summary of the user's accounts
theUser.printAccountsSummary();
//init
int choice;
//user menu
do {
System.out.printf("Welcome %s, what would you like to do?\n", theUser.getFirstName());
System.out.println("1) Show account transaction history");
System.out.println("2) Withdrawl");
System.out.println("3) Deposit");
System.out.println("4) Transfer");
System.out.println("5) Quit");
System.out.println();
System.out.print("Enter choice: ");
choice = sc.nextInt();
if(choice <1 || choice>5)
System.out.println("Invalid choice. Please choose 1-5");
}while(choice<1 || choice>5);
//process the choice
switch (choice) {
case 1 -> Main.showTransHistory(theUser, sc);
case 2 -> Main.withdrawlFunds(theUser, sc);
case 3 -> Main.depositFunds(theUser, sc);
case 4 -> Main.transferFunds(theUser, sc);
case 5 -> sc.nextLine();
}
//redisplay the menu unless the user wants to quit
if(choice!=5) {
Main.printUserMenu(theUser, sc);
}
}
/**
* proceed a fund deposit to an account
* @param theUser
* @param sc
*/
private static void depositFunds(User theUser, Scanner sc) {
//inits
int toAcct;
String memo;
double amount;
double acctBal;
//get the account to transfer from
do {
System.out.printf("Enter the number (1-%d) of the account\n"+"to deposit in: ",theUser.numAccounts());
toAcct = sc.nextInt()-1;
if(toAcct <0|| toAcct> theUser.numAccounts())
System.out.println("Invalid account. Pleas try again.");
}while(toAcct <0|| toAcct> theUser.numAccounts());
acctBal = theUser.getAcctBalance(toAcct);
//the amount to transfer
do {
System.out.printf("Enter the amount to transfer (max $%.02f): $ ", acctBal);
amount = sc.nextDouble();
if(amount <0)
System.out.println("Amount must be greater than zero.");
}while(amount <0);
//gobble up the rest of the previous input
sc.nextLine();
//get a memo
System.out.print("Enter a memo: ");
memo = sc.nextLine();
//do the withdrawal
theUser.addAcctTransaction(toAcct, amount, memo);
}
/**
* process a fund withdrawal from an account
* @param theUser the logged-in user object
* @param sc th scanner
*/
private static void withdrawlFunds(User theUser, Scanner sc) {
//inits
int fromAcct;
String memo;
double amount;
double acctBal;
//get the account to transfer from
do {
System.out.printf("Enter the number (1-%d) of the account\n"+"to withdraw from: ",theUser.numAccounts());
fromAcct = sc.nextInt()-1;
if(fromAcct <0|| fromAcct> theUser.numAccounts())
System.out.println("Invalid account. Pleas try again.");
}while(fromAcct <0|| fromAcct> theUser.numAccounts());
acctBal = theUser.getAcctBalance(fromAcct);
//the amount to transfer
do {
System.out.printf("Enter the amount to withdraw (max $%.02f): $ ", acctBal);
amount = sc.nextDouble();
if(amount <0)
System.out.println("Amount must be greater than zero.");
else if(amount>acctBal)
System.out.printf("Amount mustn't be greater than balance of $%.02f.\n", acctBal);
}while(amount <0|| amount> acctBal);
//gobble up the rest of the previous input
sc.nextLine();
//get a memo
System.out.print("Enter a memo: ");
memo = sc.nextLine();
//do the withdrawal
theUser.addAcctTransaction(fromAcct, -1*amount, memo);
}
public static void transferFunds(User theUser, Scanner sc) {
//inits
int fromAcct;
int toAcct;
double amount;
double acctBal;
//get the account to transfer from
do {
System.out.printf("Enter the number (1-%d) of the account\n"+"to transfer from: ",theUser.numAccounts());
fromAcct = sc.nextInt()-1;
if(fromAcct <0|| fromAcct> theUser.numAccounts())
System.out.println("Invalid account. Pleas try again.");
}while(fromAcct <0|| fromAcct> theUser.numAccounts());
acctBal = theUser.getAcctBalance(fromAcct);
//account to transfer to
do {
System.out.printf("Enter the number (1-%d) of the account\n"+"to transfer to: ",theUser.numAccounts());
toAcct = sc.nextInt()-1;
if(toAcct <0|| toAcct> theUser.numAccounts())
System.out.println("Invalid account. Pleas try again.");
}while(toAcct <0|| toAcct> theUser.numAccounts());
//the amount to transfer
do {
System.out.printf("Enter the amount to transfer (max $%.02f): $ ", acctBal);
amount = sc.nextDouble();
if(amount <0)
System.out.println("Amount must be greater than zero.");
else if(amount>acctBal)
System.out.printf("Amount mustn't be greater than balance of $%.02f.\n", acctBal);
}while(amount <0|| amount> acctBal);
//finally, do the transfer
theUser.addAcctTransaction(fromAcct, -1*amount, String.format("Transfer to account %s",
theUser.getAcctUUID(toAcct)));
theUser.addAcctTransaction(toAcct, amount, String.format("Transfer from account %s",
theUser.getAcctUUID(fromAcct)));
}
/**
* Show the transaction history for an account
* @param {User} theUser
* @param {Scanner} sc
*/
public static void showTransHistory(User theUser, Scanner sc) {
int theAcct;
//get the account whose transaction history to look at
do {
System.out.printf("Enter the number (1-%d) of the account\n whose transactions you want to see:",
theUser.numAccounts());
theAcct = sc.nextInt()-1;
if(theAcct<0|| theAcct >theUser.numAccounts())
System.out.println("Invalid account. Pleas try again.");
}while(theAcct<0|| theAcct >theUser.numAccounts());
//print the transaction history
theUser.printAccTransHistory(theAcct);
}
}
| true |
bc8a23f4423fd189331b787fb3ef32d57edd2ce9 | Java | KevinVanthuyne/simple-webshop | /src/main/java/ui/controller/handlers/RequestHandler.java | UTF-8 | 1,365 | 2.5 | 2 | [] | no_license | package ui.controller.handlers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import domain.Role;
import domain.ShopService;
import ui.controller.WebshopController;
public abstract class RequestHandler {
protected ShopService shop;
public void setService(ShopService shop) {
if (shop == null) {
throw new IllegalArgumentException("Invalid ShopService");
}
this.shop = shop;
}
public ShopService getService() {
return shop;
}
public void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/*
TEMPLATE FOR EXTENDING HANDLERS
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import domain.Role;
import domain.ShopService;
import ui.controller.WebshopController;
public class Handler extends RequestHandler {
public Handler() {}
public Handler(ShopService shop) {
setService(shop);
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Role[] roles = {Role.ADMINISTRATOR, Role.CUSTOMER};
WebshopController.checkRole(request, roles);
}
}
*/
}
| true |
494c7a26ca856ec9b5c6b6e2bcba77add465979d | Java | fanweimei/JavaLearning | /src/p14collect/ArrayListTest_06.java | GB18030 | 1,819 | 4.09375 | 4 | [] | no_license | package p14collect;
import java.util.*;
/*
* ArrayListϰ⣺ȥArrayListеظԪ
* ԶҪдequalsΪArrayListͨequalsжǷͬ
*/
public class ArrayListTest_06 {
//ȥ
static ArrayList uniqueList(ArrayList list){
ArrayList newList = new ArrayList();
Iterator it = list.iterator();
while(it.hasNext()){
Object obj = it.next();
if(!newList.contains(obj)){
newList.add(obj);
}
}
return newList;
}
static void testUniqueList(){
ArrayList list = new ArrayList();
list.add("a01");
list.add("a03");
list.add("a01");
list.add("a02");
list.add("a04");
list.add("a01");
list.add("a03");
System.out.println(list); //[a01, a03, a01, a02, a04, a01, a03]
list = uniqueList(list);
System.out.println(list); //[a01, a03, a02, a04]
}
//ʱϼPersonȥֶͬĶ
static void testUniqueList2(){
ArrayList list = new ArrayList();
list.add(new Person("p01",10));
list.add(new Person("p02",20));
list.add(new Person("p03",30));
list.add(new Person("p01",10));
list = uniqueList(list);
System.out.println(list); //[p01-10, p02-20, p03-30]
}
public static void main(String[] args) {
//testUniqueList();
testUniqueList2();
}
}
class Person {
private String name;
private int age;
Person(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String toString(){
return this.name+"-"+this.age;
}
//Ҫдequals
public boolean equals(Object o){
Person p = (Person) o;
return this.getName().equals(p.getName()) && this.getAge() == p.getAge();
}
}
| true |
c3c4b8016f6e4fc80011943d44ee798fa476f873 | Java | watertreestar/Design-Pattern | /src/com/ranger/design/principal/dependenceinvertion/Test.java | UTF-8 | 815 | 2.953125 | 3 | [] | no_license | /**
*
*/
package com.ranger.design.principal.dependenceinvertion;
/**
* @author Ranger
* 高层模块
*/
public class Test {
// v1
// public static void main(String[] args) {
// Ranger ranger = new Ranger();
// ranger.studyJavaCourse();
// ranger.studyFECourse();
// }
// v2 接口方法注入
// public static void main(String[] args) {
// Ranger ranger = new Ranger();
// // 构建一个课程内
// ICourse javaCourse = new JavaCourse();
// ranger.studyCourse(javaCourse);
// }
// v3 构造器注入
// public static void main(String[] args) {
// Ranger ranger = new Ranger(new JavaCourse());
// ranger.studyCourse();
// }
// v4 setter 注入
public static void main(String[] args) {
Ranger ranger = new Ranger();
ranger.setiCourse(new JavaCourse());
ranger.studyCourse();
}
}
| true |
a73ca5ef085d092ccd7a1c2110d441cf2b0658b3 | Java | GitsMuthukumarJ/Task5 | /Exception.java | UTF-8 | 728 | 3.6875 | 4 | [] | no_license | //Create separate package ExceptionHandling
package ExceptionHandling;
//create class Exception
public class Exception
{
//main method
public static void main(String[] args)
{
//create try block
try
{
int data = 50 / 0;
//integer array c has length of 1
int c[]= {1};
c[42]=99;
}
//create catch block for ArithmeticException
catch (ArithmeticException f)
{
System.out.println("divide by 0:" + f);
}
//create catch block for ArithmeticException
catch (ArrayIndexOutOfBoundsException k)
{
System.out.println("array index oob" + k);
}
//Create finally keyword
finally
{
System.out.println("i always executed");
}
System.out.println("rest of the code");
}
} | true |
628f49637d14ed316536ea11645f7a123b48f6cd | Java | DanPizzini/BadgerSettleDownBST-List-Visualizer | /src/P9Tests.java | UTF-8 | 9,151 | 3.203125 | 3 | [] | no_license | //////////////////// ALL ASSIGNMENTS INCLUDE THIS SECTION /////////////////////
//
// Title: (P09 Badgers Settle Down)
// Files: (Sett.java, Badger.java, P9Tests.java)
// Course: (300, fall, 2018-2019)
//
// Author: (Dante Pizzni)
// Email: (pizzini@wisc.edu)
// Lecturer's Name: (Gary Dahl)
//
//////////////////// PAIR PROGRAMMERS COMPLETE THIS SECTION ///////////////////
//
// Partner Name: (Joseph Cambio)
// Partner Email: (jcambio@wisc.edu)
// Partner Lecturer's Name: (Gary Dahl)
//
// VERIFY THE FOLLOWING BY PLACING AN X NEXT TO EACH TRUE STATEMENT:
// _X_ Write-up states that pair programming is allowed for this assignment.
// _X_ We have both read and understand the course Pair Programming Policy.
// _X_ We have registered our team prior to the team registration deadline.
//
///////////////////////////// CREDIT OUTSIDE HELP /////////////////////////////
//
// Students who get help from sources other than their partner must fully
// acknowledge and credit those sources of help here. Instructors and TAs do
// not need to be credited here, but tutors, friends, relatives, room mates,
// strangers, and others do. If you received no outside help from either type
// of source, then please explicitly indicate NONE.
//
// Persons: (identify each person and describe their help in detail)
// Online Sources: (identify each URL and describe their assistance in detail)
//
/////////////////////////////// 80 COLUMNS WIDE ///////////////////////////////
import java.util.List;
import java.util.NoSuchElementException;
/**
* This Class contains the Badger and Sett tests methods and reports if they passed or failed
*
* @author jdcam
*
*/
public class P9Tests {
/**
* This method runs all of the Badger tests
*
* @return a boolean if the tests passed or failed
*/
public static boolean runAllBadgerTests() { // returns true when all Badger tests pass
if (LeftLowerTest() && RightLowerTest() && BadgerConstrTest()) { // if metohds are true
System.out.println("All Badger Tests passed!"); // report to console
return true;
} // return true
System.out.println("One or more Badger tests failed"); // if they are false report to console
return false;
}
/**
* This method runs all of the Sett tests and reports if they passed or failed to the console
*
* @return
*/
public static boolean runAllSettTests() { // returns true when all Sett tests pass
if (getTopBadgerTest() && isEmptyTest() && settleBadgerTest() && findBadgerTest()
&& countBadgerTest() && getAllBadgersTest() && getheightTest() && getLargestBadgerTest()
&& clearTest() && settConstrTest()) { // if statement that if all tests pass
System.out.println("All Sett tests passed!"); // reports they passed to console
return true;
}
System.out.println("One or more Sett tests failed!"); // if they fail it also reports it to the
// console
return false;
}
/**
* Tets the gettopBadger method in sett
*
* @return
*/
public static boolean getTopBadgerTest() {
Sett sett1 = new Sett(); // creates a sett
sett1.settleBadger(50); // Settles a top badger in the sett
sett1.settleBadger(70);// settles rest of badgers in sett
sett1.settleBadger(40);
if (sett1.getTopBadger().getSize() == 50) // makes sure that get top badger returns the actual
// top badger
return true;
System.out.println("Test1 fail");
return false;
}
/**
* Checks to see if Sett is empty
*
* @return
*/
public static boolean isEmptyTest() {
Sett sett1 = new Sett(); // creates a sett with out any badgers
if (sett1.isEmpty()) // If isEmpty works this method returns true
return true;
System.out.println("Test2 fail");
return false;
}
/**
* Checks to see if settleBadger works
*
* @return
*/
public static boolean settleBadgerTest() {
try { // uses a try catch block to see if it throws exception
Sett sett1 = new Sett();
sett1.settleBadger(50); // two badgers of the same size are added
sett1.settleBadger(50);
} catch (IllegalArgumentException e) { // catches the exception and returns true if caught
return true;
}
System.out.println("Test3 fail");
return false;
}
/**
* Checks to see if findBadger method works
*
* @return
*/
public static boolean findBadgerTest() {
Sett sett1 = new Sett(); // creates sett
sett1.settleBadger(60);// add badgers
sett1.settleBadger(70);
try { // using try catch to check if an exception is thrown
sett1.findBadger(69); // finding a badger that isn't in the sett
} catch (NoSuchElementException e) { // Catches exception and returns true
return true;
}
System.out.println("Test4 fail");
return false;
}
/**
* Test the countBadger method
*
* @return
*/
public static boolean countBadgerTest() {
Sett sett = new Sett(); // creates a sett
sett.settleBadger(55); // settles 4 badgers
sett.settleBadger(40);
sett.settleBadger(66);
sett.settleBadger(32);
if (sett.countBadger() == 4) // if the count method works return true
return true;
System.out.println("Test5 fail");
return false;
}
/**
* Tests the getAllBadgers mxethod
*
* @return
*/
public static boolean getAllBadgersTest() {
Sett sett = new Sett(); // creates a sett
sett.settleBadger(32); // adds badgers
sett.settleBadger(14);// the smallest badger
sett.settleBadger(35);
java.util.List<Badger> Bt; // created a list with type badger
Bt = sett.getAllBadgers();
if (Bt.get(0).getSize() == 14) // if the badger at element 0 size is 14 (the smallest badger) the
// test passed
return true;
System.out.println("Test6 fail");
return false;
}
/**
* Tests the getHeightMethod
*
* @return
*/
public static boolean getheightTest() {
Sett sett = new Sett(); // creates sett
sett.settleBadger(32); // adds badgers to BST with height of three
sett.settleBadger(31);
sett.settleBadger(34);
sett.settleBadger(35);
if (sett.getHeight() == 3) // if its computes the correct height the test passed
return true;
System.out.println("Test7 fail");
return false;
}
/**
* Test the getLargestBadger mthod
*
* @return
*/
public static boolean getLargestBadgerTest() {
Sett sett = new Sett(); // creates a sett
sett.settleBadger(34);// adds badgers
sett.settleBadger(98); // largest badger
sett.settleBadger(91);
sett.settleBadger(15);
if (sett.getLargestBadger().getSize() == 98) // if the method returns 98 test passed
return true;
System.out.println("Test8 fail");
return false;
}
/**
* test the clear method
*
* @return
*/
public static boolean clearTest() {
Sett sett = new Sett(); // creates a sett
sett.settleBadger(30); // adds badgers
sett.settleBadger(34);
sett.settleBadger(35);
sett.clear(); // runs the clear method
if (sett.getHeight() == 0) { // if the height of the sett is now zero the test passed
return true;
}
System.out.println("Test9 fail");
return false;
}
/**
* Tests the constructor of sett class
*
* @return
*/
public static boolean settConstrTest() {
Sett sett = new Sett(); // creates sett
if (sett != null) // makes sure sett is not null
// note that while the sett is empty it is not null
return true;
System.out.println("Test10 fail");
return false;
}
/**
* tests the LeftLowerNeightbor method
*
* @return
*/
public static boolean LeftLowerTest() {
Badger B1 = new Badger(50); // creates two new badgers
Badger B2 = new Badger(44);
B1.setLeftLowerNeighbor(B2); // sets b2 as lower left neighbor of B1
if (B1.getLeftLowerNeighbor().getSize() == 44) // Checks to see if the getLeftLowerNeighbor
// returns the neighbor set
return true;
return false;
}
/**
* Tests RightLowerNeighbor method
*
* @return
*/
public static boolean RightLowerTest() {
Badger B1 = new Badger(50); // adds two badgers
Badger B2 = new Badger(44);
B1.setRightLowerNeighbor(B2); // sets B2 as B1 right lower neighbor
if (B1.getRightLowerNeighbor().getSize() == 44) // checks to see if B2 is actually B1 left lower
// neighbor
return true;
return false;
}
/**
* Tests the constructor of the class Badger
*
* @return
*/
public static boolean BadgerConstrTest() {
Badger B1 = new Badger(30); // creates a badger with size 30
if (B1 != null) // makes sure there actually is a badger present
return true;
return false;
}
/**
* Main method calls the two test method runners
*
* @param args
*/
public static void main(String[] args) {
runAllBadgerTests();
runAllSettTests();
}
}
| true |
bb80b0fe50215c8971631ea9757d669f1bc52c32 | Java | kaya151/develop | /src/main/java/com/tuomi/develop/service/TouristService.java | UTF-8 | 254 | 1.796875 | 2 | [] | no_license | package com.tuomi.develop.service;
import com.tuomi.develop.entity.Tourist;
import org.apache.ibatis.annotations.Param;
public interface TouristService {
Tourist selectByNameAndPwd(@Param("userName") String name, @Param("passWord") String pwd);
}
| true |
29e7d9004e8e4b8ebce63ebad2117aa7025fb9b0 | Java | SayScl/community | /src/main/java/com/shigan/controller/supermarket/SupermarketController.java | UTF-8 | 21,550 | 2.015625 | 2 | [] | no_license | package com.shigan.controller.supermarket;
import com.shigan.pojo.Limit;
import com.shigan.pojo.User;
import com.shigan.pojo.common.Common;
import com.shigan.pojo.supermarket.*;
import com.shigan.service.QiniuUploadService;
import com.shigan.service.UserService;
import com.shigan.service.supermarketservice.*;
import org.apache.catalina.startup.Catalina;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Administrator on 2017/7/12.
*/
@Controller
@RequestMapping("market")
public class SupermarketController {
@Autowired
private QiniuUploadService qiniuUploadService;
@Autowired
private OrderService orderService;
@Autowired
private UserService userService;
@Autowired
private ShopcarService shopcarService;
@Autowired
private ProductService productService;
@Autowired
private CategoryService categoryService;
@Autowired
private DisscussService disscussService;
//跳转到社区超市页面
@RequestMapping("tosupermarket")
public String tosupermarket(Model model,HttpServletRequest request){
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
List<Disscuss> disscusses = disscussService.getmarketdiscuss(user.getCommunityid());
//获得所有分类
List<Category> categorys = categoryService.getcategory();
//获得该用户下的购物项
List<Shopcaritems> shopcaritemsList = shopcarService.getshopcaritemsbyuserid(user.getId());
if(shopcaritemsList!=null){
for(Category c:categorys){
//获得每个分类下的商品
List<Product> products = productService.getproductinfoByCategoryid(c.getId());
//判断这个商品是否已经在购物项中,如果在显示数量
for(Product p:products){
boolean flag=true;
for(Shopcaritems sc:shopcaritemsList){
if(p.getId()==sc.getProductid()){
flag=false;
p.setProductcount(sc.getProductcount());
break;
}
}
if(flag){
p.setProductcount(0);
}
}
c.setProducts(products);
}
}else{
for(Category c:categorys){
//获得每个分类下的商品
List<Product> products = productService.getproductinfoByCategoryid(c.getId());
c.setProducts(products);
}
}
Shopcar shopc=new Shopcar();
shopc.setUserid(user.getId());
Shopcar shopcar = shopcarService.getshopcarbyuserid(shopc);
if(shopcar!=null){
shopcar.setShopcaritemscount(shopcaritemsList.size());
model.addAttribute("shopcar",shopcar);
model.addAttribute("categorys",categorys);
}else{
Shopcar shopc1=new Shopcar();
shopc1.setTotalprice(0.0);
shopc1.setShopcaritemscount(0);
model.addAttribute("categorys",categorys);
model.addAttribute("shopcar",shopc1);
}
model.addAttribute("discuss",disscusses);
return "/market/supermarket";
}
//跳转到购物车页面(添加到购物车)
@PostMapping("shopcaritems")
@ResponseBody
public Map shopcaritems(@RequestBody List<Shopcaritems> list, HttpServletRequest request){
HttpSession session = request.getSession();
//获得登录用户
User user =(User) session.getAttribute("user");
Shopcar checkshopcar1=new Shopcar();
checkshopcar1.setUserid(user.getId());
double totalprice;
Shopcar getshopcarbyuserid1 = shopcarService.getshopcarbyuserid(checkshopcar1);
if(getshopcarbyuserid1!=null){
totalprice=getshopcarbyuserid1.getTotalprice();
}else{
totalprice=0;
}
//从前台获得购物项详细信息
for(int i=0;i<list.size();i++){
Shopcaritems sp=new Shopcaritems();
//获得购物项数量
sp.setProductcount(list.get(i).getProductcount());
//获得购物项中商品信息
Product product = productService.getproductinfoById(list.get(i).getProductid());
double producttotalprice;
double newprice;
//查找购物项中是否已经存在该商品
Shopcaritems getshopcaritemsbyproductid = shopcarService.getshopcaritemsbyproductid(list.get(i).getProductid());
if(getshopcaritemsbyproductid!=null){
int count=0;
Integer productcount = getshopcaritemsbyproductid.getProductcount();
Integer newproductcount = list.get(i).getProductcount();
count=productcount-newproductcount;
if(count>0){
newprice=product.getPrice()*(newproductcount-productcount);
producttotalprice=getshopcaritemsbyproductid.getProducttotalprice()+newprice;
sp.setProductcount(newproductcount);
}else{
newprice=product.getPrice()*(newproductcount-productcount);
producttotalprice=getshopcaritemsbyproductid.getProducttotalprice()+newprice;
sp.setProductcount(newproductcount);
}
//计算购物车总价
totalprice=totalprice+newprice;
}else{
producttotalprice=product.getPrice()*list.get(i).getProductcount();
//计算购物车总价
totalprice=totalprice+producttotalprice;
}
//获得购物项价格
sp.setProducttotalprice(producttotalprice);
sp.setProductid(list.get(i).getProductid());
sp.setUserid(user.getId());
//查看购物项中是否已经存在这个商品如果有执行修改操作,没有做增加操作
List<Shopcaritems> checkshopitems = shopcarService.getshopcaritemsbyuserid(user.getId());
boolean flag=true;
for(int j=0;j<checkshopitems.size();j++){
if(checkshopitems.get(j).getProductid()==list.get(i).getProductid()){
flag=false;
break;
}else{
continue;
}
}
if(flag){
//增加购物项
int addshopcaritems = shopcarService.addshopcaritems(sp);
}else{
//作购物项的修改
int updatebyproductid = shopcarService.updatebyproductid(sp);
}
}
//获得这个用户的购物项
List<Shopcaritems> shopcaritems = shopcarService.getshopcaritemsbyuserid(user.getId());
StringBuffer s=new StringBuffer();
//将这个用户下的商品名字保存进去
for(int k=0;k<shopcaritems.size();k++){
Shopcaritems cs=new Shopcaritems();
Product product = productService.getproductinfoById(shopcaritems.get(k).getProductid());
cs.setProductname(product.getProductname());
cs.setProductid(product.getId());
int kk = shopcarService.updateshopcaritemsproductnamebyproductid(cs);
}
//获得购物项id集
for(int j=0;j<shopcaritems.size();j++){
if(j==shopcaritems.size()-1){
s.append(shopcaritems.get(j).getId());
}else{
s.append(shopcaritems.get(j).getId()+",");
}
}
Shopcar sc=new Shopcar();
sc.setItemsid(s.toString());
sc.setUserid(user.getId());
sc.setTotalprice(totalprice);
//将这个用户的购物车信息保存到数据库
Shopcar checkshopcar = shopcarService.getshopcarbyuserid(sc);
//查看购物车中是否已经有该用户的购物车信息
if(checkshopcar!=null){
//如果存在执行修改购物车信息操作
int updateshopcarbyuserid = shopcarService.updateshopcarbyuserid(sc);
}else{
//不存在执行添加购物车信息
int addshopcar = shopcarService.addshopcar(sc);
}
Shopcar spc=new Shopcar();
spc.setUserid(user.getId());
//获得该用户购物车中最新消息
Shopcar getshopcarbyuserid = shopcarService.getshopcarbyuserid(spc);
String itemsid = getshopcarbyuserid.getItemsid();
String[] split = itemsid.split(",");
//将购物项集转成集合
List list1=new ArrayList();
for(int jj=0;jj<split.length;jj++){
list1.add(split[jj]);
}
//查到购物车里的购物项
List<Shopcaritems> getshopcaritemsbyid = shopcarService.getshopcaritemsbyid(list1);
//添加到最新的购物车实体类中,用于传到页面
getshopcarbyuserid.setShopcaritems(getshopcaritemsbyid);
Map map=new HashMap();
map.put("shopcar",getshopcarbyuserid);
return map;
}
//在购物车页面删除购物项与购物车
@RequestMapping("deleteshopcaritems")
@ResponseBody
public String deleteshopcaritems(HttpServletRequest request){
String productid = request.getParameter("productid");
String oldprice = request.getParameter("oldprice");
String id = request.getParameter("id");
Shopcar shopcar=new Shopcar();
HttpSession session = request.getSession();
User user =(User) session.getAttribute("user");
shopcar.setUserid(user.getId());
//查找购物车
Shopcar sp = shopcarService.getshopcarbyuserid(shopcar);
//获得新的总价
double newTotalprice=sp.getTotalprice()-Double.parseDouble(oldprice);
//获得新产itemsid集
String itemsid = sp.getItemsid();
//删除没用的productid
String[] split = itemsid.split(",");
List list=new ArrayList();
for(int j=0;j<split.length;j++){
list.add(split[j]);
}
StringBuffer newitems=new StringBuffer();
//查看是否有要删除的productid
for(int jj=0;jj<list.size();jj++){
if(list.get(jj).equals(id)){
list.remove(list.get(jj));
}
}
for(int jjj=0;jjj<list.size();jjj++){
if(jjj==0){
newitems.append(list.get(jjj));
}else{
newitems.append(",");
newitems.append(list.get(jjj));
}
}
shopcar.setTotalprice(newTotalprice);
shopcar.setItemsid(newitems.toString());
//修改最新的购物车
shopcarService.updateshopcarbyuserid(shopcar);
int i = shopcarService.deleteshopcaritemsbyproductid(Integer.parseInt(productid));
int k = shopcarService.getcountshopcaritems(user.getId());
if(k==0){
shopcarService.deleteshopcarbyuserid(user.getId());
}
return "success";
}
//修改购物项单项总价
@RequestMapping("uproducttotal")
@ResponseBody
public String uproducttotal(HttpServletRequest request){
String productid = request.getParameter("productid");
String totalprice = request.getParameter("totalprice");
String productcount = request.getParameter("productcount");
Shopcaritems si=new Shopcaritems();
si.setProductid(Integer.parseInt(productid));
si.setProducttotalprice(Double.parseDouble(totalprice));
si.setProductcount(Integer.parseInt(productcount));
int i = shopcarService.updatebyproductid(si);
if(i>0){
return "success";
}else{
return "faild";
}
}
//跳转到结算页面
@RequestMapping("toorder")
public String toorder(HttpServletRequest request,Model model){
HttpSession session = request.getSession();
//从session得到用户
User user = (User)session.getAttribute("user");
Shopcar shopcar=new Shopcar();
shopcar.setUserid(user.getId());
//获得该用户的购物车信息
Shopcar sp = shopcarService.getshopcarbyuserid(shopcar);
String itemsid = sp.getItemsid();
String[] split = itemsid.split(",");
List list=new ArrayList();
for(int i=0;i<split.length;i++){
list.add(split[i]);
}
//获得该用户购物车中的购物项
double tp=0;
List<Shopcaritems> shopcaritems = shopcarService.getshopcaritemsbyid(list);
for(Shopcaritems spi:shopcaritems){
tp=tp+spi.getProducttotalprice();
}
sp.setShopcaritems(shopcaritems);
sp.setTotalprice(tp);
model.addAttribute("user",user);
model.addAttribute("shopcar",sp);
return "/market/confirmorder";
}
//跳转到支付页面
@RequestMapping("toplay")
public String toplay(HttpServletRequest request,
Model model){
String id = request.getParameter("id");
if(id!=null && id!=""){
Order getorderbyid = orderService.getorderbyid(Integer.parseInt(id));
model.addAttribute("order",getorderbyid);
return "/market/play";
}else{
String name = request.getParameter("name");
String address = request.getParameter("address");
String time = request.getParameter("time");
String totalprice = request.getParameter("totalprice");
String play = request.getParameter("play");
Order order=new Order();
order.setAddress(address);
order.setName(name);
order.setTime(time);
order.setTotalprice(Double.parseDouble(totalprice));
order.setPlay(play);
order.setPlaystatu(0);
order.setReback(0);
Date date=new Date();
StringBuffer orderid=new StringBuffer();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
order.setCreatetime(format.format(date));
//获得模块图片
List<Limit> limits = userService.getLimits();
String path = limits.get(0).getPath();
order.setPath(path);
//获得登录用户信息
HttpSession session = request.getSession();
User user =(User) session.getAttribute("user");
//获得商品列表
int count=0;
List<Shopcaritems> shopcaritems = shopcarService.getshopcaritemsbyuserid(user.getId());
StringBuffer shoplist=new StringBuffer();
for(int i=0;i<shopcaritems.size();i++){
count=count+shopcaritems.get(i).getProductcount();
StringBuffer a=new StringBuffer();
String productname = shopcaritems.get(i).getProductname();
Double producttotalprice = shopcaritems.get(i).getProducttotalprice();
Integer productcount = shopcaritems.get(i).getProductcount();
a.append(productname);
a.append(",");
a.append(producttotalprice);
a.append(",");
a.append(productcount);
shoplist.append(a);
if(i==shopcaritems.size()-1){
shoplist.append("");
}else{
shoplist.append(":");
}
}
//获得购订单编号
StringBuffer od=new StringBuffer("SQCS");
//自增量
od.append(shopcaritems.get(0).getProductid());
od.append(new Date());
od.append(user.getCommunityid());
order.setOrderid(od.toString());
order.setCount(count);
order.setShoplist(shoplist.toString());
order.setUserid(user.getId());
order.setPhonenumber(user.getPhoneNumber());
order.setCommunityid(user.getCommunityid());
//支付成功保存入订单表
orderService.addorder(order);
shopcarService.deleteshopcaritemsbyuserid(user.getId());
shopcarService.deleteshopcarbyuserid(user.getId());
model.addAttribute("order",order);
return "/market/play";
}
}
//跳转到订单页
@RequestMapping("showorder")
public String showorder(HttpServletRequest request,Model model){
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
List<Order> shoporders = orderService.getorderbyuserid(user.getId());
//获得商品列表
for(int i=0;i<shoporders.size();i++){
String shoplist = shoporders.get(i).getShoplist();
String[] s1 = shoplist.split(":");
List<Shopcaritems> list=new ArrayList<Shopcaritems>();
for(int j=0;j<s1.length;j++){
Shopcaritems sp=new Shopcaritems();
String[] s2 = s1[j].split(",");
sp.setProductname(s2[0]);
sp.setProducttotalprice(Double.parseDouble(s2[1]));
sp.setProductcount(Integer.parseInt(s2[2]));
list.add(sp);
}
shoporders.get(i).setShopcaritems(list);
}
model.addAttribute("shoporders",shoporders);
return "/market/order";
}
//支付成功后修改商品信息
@RequestMapping("play")
@ResponseBody
public String play(HttpServletRequest request){
String shoplist = request.getParameter("shoplist");
String orderid = request.getParameter("orderid");
Order order=new Order();
order.setOrderid(orderid);
order.setPlaystatu(1);
order.setSendstatu(2);
order.setEvaluatestatu(0);
String[] s1 = shoplist.split(":");
//支付后,修改商品库存
for(int j=0;j<s1.length;j++){
Product product=new Product();
Shopcaritems sp=new Shopcaritems();
String[] s2 = s1[j].split(",");
product.setProductname(s2[0]);
Double price = Common.div(Double.parseDouble(s2[1]), Double.parseDouble(s2[2]), 1);
System.out.print(price);
product.setPrice(price);
Product product1 = productService.getproductbynameprice(product);
Integer oldstore = product1.getStore();
product.setStore(oldstore-Integer.parseInt(s2[2]));
productService.updateproductbynameprice(product);
}
int i = orderService.updateplaystatu(order);
return "success";
}
//跳转到评价页面
@RequestMapping("todiscuss")
public String todiscuss(HttpServletRequest request,Model model){
String id = request.getParameter("id");
model.addAttribute("id",id);
return "/market/discuss";
}
//评论
@RequestMapping("discuss")
@ResponseBody
public String discuss(HttpServletRequest request){
String content = request.getParameter("content");
HttpSession session = request.getSession();
User user =(User) session.getAttribute("user");
String id = request.getParameter("id");
String img = request.getParameter("img");
Disscuss dis=new Disscuss();
dis.setContent(content);
dis.setModelid(1);
dis.setPath(img);
dis.setUserid(user.getId());
dis.setName(user.getName());
dis.setCommunityid(user.getCommunityid());
Date d=new Date();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dis.setCreatetime(format.format(d));
int i = disscussService.adddisscuss(dis);
Order order=new Order();
order.setId(Integer.parseInt(id));
order.setEvaluatestatu(1);
if(i>0){
int j = orderService.updateotherstatubyid(order);
if(j>0){
return "success";
}else{
return "faild";
}
}else{
return "faild";
}
}
@RequestMapping("todiscussone")
public String discussone(HttpServletRequest request){
String id = request.getParameter("id");
Order order=new Order();
order.setId(Integer.parseInt(id));
order.setSendstatu(1);
int i = orderService.updateotherstatubyid(order);
return "redirect:/market/showorder";
}
//七牛
@RequestMapping("token")
@ResponseBody
public String token(){
String token = this.qiniuUploadService.getUploadToken();
return token;
}
//申请退款
@RequestMapping("reback")
@ResponseBody
public String reback(HttpServletRequest request){
String id = request.getParameter("id");
Order order=new Order();
order.setReback(1);
order.setId(Integer.parseInt(id));
int i = orderService.updateotherstatubyid(order);
if(i>0){
return "success";
}else{
return "faild";
}
}
}
| true |
b66c80b0b6159094b3e0e13bdc798c2ea21aaf02 | Java | LIm-JY/aia202003 | /java_project/PhoneBook/src/ver01/PhoneBookMain.java | UTF-8 | 281 | 2.5625 | 3 | [] | no_license | package ver01;
public class PhoneBookMain {
public static void main(String[] args) {
PhoneInfor info = new PhoneInfor("손흥민", "000-8888-9999" , "2000.11.11");
info.showinfor();
info = new PhoneInfor("박지성","000-7777-5678");
info.showinfor();
}
}
| true |
bb6c4fa565b2ddb665002f5c0a584096fce7cf7f | Java | ma345564280/ivy-root | /src/main/java/com/ivy/root/service/impl/OrderServiceImpl.java | UTF-8 | 2,675 | 2.171875 | 2 | [] | no_license | package com.ivy.root.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ivy.root.common.exception.BusinessException;
import com.ivy.root.common.request.AppointmentRequest;
import com.ivy.root.common.rootenum.AppointmentStatusEnum;
import com.ivy.root.common.rootenum.ProjectTypeEnum;
import com.ivy.root.common.rootenum.ResponseCodeEnum;
import com.ivy.root.dao.AppointmentMapper;
import com.ivy.root.domain.Appointment;
import com.ivy.root.service.OrderService;
import com.ivy.root.dao.OrderMapper;
import com.ivy.root.domain.Order;
import com.ivy.root.vo.DaySumStatisticVo;
import com.ivy.root.vo.StatisticVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.*;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
OrderMapper orderMapper;
@Autowired
AppointmentMapper appointmentMapper;
@Override
public StatisticVo queryDesignerOrdersOverView(Long designerId , Integer days) throws ParseException, NoSuchFieldException, IllegalAccessException {
if(designerId == null) {
return null;
}
Long totalOrders = orderMapper.counterAllOrders(designerId);
List<Order> ordersInDays = orderMapper.statisticOrdersByDay(designerId, days);
List<DaySumStatisticVo> daySumStatisticVos = DaySumStatisticVo.getInstance(Order.class, "createTime", days, ordersInDays, "yyyy-MM-dd", Calendar.DATE);
return new StatisticVo(totalOrders, daySumStatisticVos);
}
@Override
public int saveAppointment(Appointment appointment) {
appointment.setStatus(Byte.valueOf(String.valueOf(AppointmentStatusEnum.DESIGN_COMPANY.getCode())));
appointment.setCreateTime(new Date());
int count = appointmentMapper.insertSelective(appointment);
return count;
}
@Override
public PageInfo queryAppointment(AppointmentRequest request) {
if (request == null) {
throw new BusinessException(ResponseCodeEnum.WRONG_OR_EMPTY_PARAM);
}
PageHelper.startPage(request.getPageNo(), request.getPageSize());
List<Appointment> appointments = appointmentMapper.queryAppointmentByCondition(request);
if(appointments != null && appointments.size() > 0) {
appointments.stream().forEach(a -> {
a.setProjectTypeDesc(ProjectTypeEnum.getDescription(Integer.valueOf(a.getProjectType())));
});
}
PageInfo<Appointment> pageInfo = new PageInfo<>(appointments);
return pageInfo;
}
}
| true |
4afac89838f8dedf212a37e65d8eed2d9c198721 | Java | barbupetcu/current-account | /src/main/java/com/test/current/account/infrastructure/security/jwt/JwtProperties.java | UTF-8 | 398 | 1.734375 | 2 | [] | no_license | package com.test.current.account.infrastructure.security.jwt;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Getter
@Setter
@Component
@ConfigurationProperties("application.security.jwt")
public class JwtProperties {
private String secret;
private String issuer;
} | true |
9530da05bd8371992813a485b2fcaecdad95d9ef | Java | Arnauld/graphql-sandbox | /src/main/java/assetmngt/core/MarketPlace.java | UTF-8 | 499 | 2.5 | 2 | [] | no_license | package assetmngt.core;
/**
* @author <a href="http://twitter.com/aloyer">@aloyer</a>
*/
public class MarketPlace {
public static MarketPlace NYSE_PARIS = new MarketPlace("025", "NYSE EN PARIS", Country.FR);
public final String code;
public final String label;
public final Country country;
public MarketPlace(String marketCode, String marketLabel, Country country) {
this.code = marketCode;
this.label = marketLabel;
this.country = country;
}
}
| true |
5c16f42732928380ef91ee1433c1d3914b17adf0 | Java | JJCCGGRR24/Arreglos-2-parcial | /Acme-Newspaper/src/test/java/usecases/test1/UseCase06_3Test.java | UTF-8 | 4,981 | 2.265625 | 2 | [] | no_license |
package usecases.test1;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import services.ArticleService;
import services.NewspaperService;
import utilities.AbstractTest;
import domain.Article;
import domain.Newspaper;
@ContextConfiguration(locations = {
"classpath:spring/junit.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class UseCase06_3Test extends AbstractTest {
//SUT
@Autowired
private NewspaperService newspaperService;
@Autowired
private ArticleService articleService;
// 6. An actor who is authenticated as a user must be able to:
// 3. Write an article and attach it to any newspaper that has not been published, yet.
// Note that articles may be saved in draft mode, which allows to modify them later, or
// final model, which freezes them forever.
@Test
public void driver() {
final Object testingData[][] = {
{
//comprobaremos que un user puede editar un articlecorrectamente
//ya que cumple todo los requisitos
"user1", "title1", "24/10/2018 00:00", "summary1", "body1", "https://www.youtube.com/watch?v=GwrnjtW-rfk", "article13", null
}, {
//comprobaremos que un user al intentar editar un article no se le permitirá
//porque está ya en modo final
"user3", "title1", "24/10/2018 00:00", "summary1", "body1", "https://www.youtube.com/watch?v=GwrnjtW-rfk", "article2", IllegalArgumentException.class
}, {//comprobaremos también que un user puede publicar un articulo a un newspaper si no
// esta publicado
"user1", "title1", "24/10/2018 00:00", "summary1", "body1", "https://www.youtube.com/watch?v=GwrnjtW-rfk", "newspaper4", null
}, {
//comprobaremos que un user al intentar publicar un articulo a un newspaper ya publicado no
// le permitira
"user3", "title1", "24/10/2018 00:00", "summary1", "body1", "https://www.youtube.com/watch?v=GwrnjtW-rfk", "newspaper2_3", IllegalArgumentException.class
}
};
for (int i = 0; i < 2; i++)
this.templateEdit((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (String) testingData[i][3], (String) testingData[i][4], (String) testingData[i][5], super.getEntityId((String) testingData[i][6]),
((Class<?>) testingData[i][7]));
for (int i = 2; i < testingData.length; i++)
this.templatePublish((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (String) testingData[i][3], (String) testingData[i][4], (String) testingData[i][5], super.getEntityId((String) testingData[i][6]),
((Class<?>) testingData[i][7]));
}
protected void templatePublish(final String username, final String title, final String moment, final String summary, final String body, final String pictures, final int newspaperId, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
super.authenticate(username);
//buscamos el articulo
final Article article = this.articleService.create();
//editamos el articulo
article.setTitle(title);
final SimpleDateFormat pattern = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final Date date = pattern.parse(moment);
article.setMoment(date);
article.setSummary(summary);
article.setBody(body);
final Collection<String> pics = new ArrayList<String>();
pics.add(pictures);
article.setPictures(pics);
final Newspaper newspaper = this.newspaperService.findOne(newspaperId);
article.setNewspaper(newspaper);
this.articleService.save(article);
this.articleService.flush();
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
super.unauthenticate();
}
protected void templateEdit(final String username, final String title, final String moment, final String summary, final String body, final String pictures, final int articleId, final Class<?> expected) {
Class<?> caught;
caught = null;
try {
super.authenticate(username);
//buscamos el articulo
final Article article = this.articleService.findOne(articleId);
//editamos el articulo
article.setTitle(title);
final SimpleDateFormat pattern = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final Date date = pattern.parse(moment);
article.setMoment(date);
article.setSummary(summary);
article.setBody(body);
final Collection<String> pics = new ArrayList<String>();
pics.add(pictures);
article.setPictures(pics);
this.articleService.save(article);
this.articleService.flush();
} catch (final Throwable oops) {
caught = oops.getClass();
}
super.checkExceptions(expected, caught);
super.unauthenticate();
}
}
| true |
ee1ae52d6958133b0b21bfbbb4a3f516872e9694 | Java | lochel/VANESA | /src/graph/jung/graphDrawing/MyVertexFillPaintFunction.java | UTF-8 | 3,222 | 2.578125 | 3 | [] | no_license | package graph.jung.graphDrawing;
import java.awt.Color;
import java.awt.Paint;
import java.util.Iterator;
import java.util.Set;
import com.google.common.base.Function;
import biologicalElements.Pathway;
import biologicalObjects.edges.BiologicalEdgeAbstract;
import biologicalObjects.nodes.BiologicalNodeAbstract;
import configurations.NetworkSettings;
import configurations.NetworkSettingsSingelton;
import edu.uci.ics.jung.visualization.picking.PickedState;
public class MyVertexFillPaintFunction implements
Function<BiologicalNodeAbstract, Paint> {
protected PickedState<BiologicalNodeAbstract> psV;
protected PickedState<BiologicalEdgeAbstract> psE;
private Pathway pw;
protected boolean graphTheory = false;
NetworkSettings settings = NetworkSettingsSingelton.getInstance();
public MyVertexFillPaintFunction(PickedState<BiologicalNodeAbstract> psV,
PickedState<BiologicalEdgeAbstract> psE, Pathway pw) {
this.psV = psV;
this.psE = psE;
this.pw = pw;
}
private Paint getFillPaintWithoutGraphTheory(BiologicalNodeAbstract v) {
if(pw.getRootNode()==v){
if(psV.getPicked().isEmpty() || psV.getPicked().contains(v)){
return Color.RED;
}
}
// mark Environment nodes in hierarchical Nodes.
if(pw instanceof BiologicalNodeAbstract){
BiologicalNodeAbstract bna = (BiologicalNodeAbstract) pw;
if(bna.getEnvironment().contains(v)){
return v.getColor().brighter();
}
}
if (psV.getPicked().isEmpty()) {
if (psE.getPicked().isEmpty()) {
return v.getColor();
} else {
// Set set = ps.getPickedEdges();
BiologicalEdgeAbstract bea;
for (Iterator<BiologicalEdgeAbstract> it = psE.getPicked()
.iterator(); it.hasNext();) {
bea = it.next();
if (v == bea.getFrom() || v == bea.getTo()) {
return v.getColor().brighter().brighter();
}
}
return Color.LIGHT_GRAY.brighter();
}
} else {
if (psV.isPicked(v))
return v.getColor();
else {
BiologicalNodeAbstract w;
Iterator<BiologicalNodeAbstract> iter = pw.getGraph().getJungGraph().getNeighbors(v).iterator();
while(iter.hasNext()) {
w = iter.next();
if (psV.isPicked(w))
return v.getColor().brighter().brighter();
}
Set<BiologicalEdgeAbstract> set = psE.getPicked();
BiologicalEdgeAbstract bea;
for (Iterator<BiologicalEdgeAbstract> it = set.iterator(); it
.hasNext();) {
bea = it.next();
if (v == bea.getFrom() || v == bea.getTo())
return v.getColor().brighter().brighter();
}
return Color.LIGHT_GRAY.brighter();
}
}
}
private Paint getFillPaintWithGraphTheory(BiologicalNodeAbstract v) {
if (psV.isPicked(v)) {
return Color.YELLOW;
} else {
return Color.white;
}
}
public void setGraphTheory(boolean graphTheory) {
this.graphTheory = graphTheory;
}
/*public Paint getNewLoadedDrawPaint(Vertex v) {
return Color.red;
}*/
@Override
public Paint apply(BiologicalNodeAbstract bna) {
if (!graphTheory) {
return getFillPaintWithoutGraphTheory(bna);
} else {
return getFillPaintWithGraphTheory(bna);
}
}
}
| true |
fa19da492d411b77d383981927144e60fc9bb1c9 | Java | FelixBaensch/CdkDescriptorCalculator | /DescriptorCalculator/src/controller/MoleculePaneController.java | UTF-8 | 13,338 | 2.390625 | 2 | [] | no_license | package controller;
//<editor-fold defaultstate="collapsed" desc="imports">
import java.util.Map;
import java.util.Map.Entry;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import model.Data;
import model.Identifier;
import org.openscience.cdk.qsar.IDescriptor;
import util.Globals;
import util.UtilityMethods;
import view.MoleculePane;
//</editor-fold>
/**
* Controller class for the MoleculePane
*
* @author Felix Bänsch, 19.05.2016
*/
public class MoleculePaneController {
//<editor-fold defaultstate="collapsed" desc="private variables">
private MoleculePane moleculePane; //Pane for the molecule information window
private Stage moleculePaneStage; //Stage for the molecuelPane
private Data data; //Instance for the molecule data
private int index; //int for the internal index of the selected molecule
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="constructor">
/**
* Creates a new controller for the MoleculePane
*
* @param aStage Stage
* @param aData Data
* @param anIdentifier Identifier
* @param aMoleculePane MoleculePane
*/
public MoleculePaneController(Stage aStage, Data aData, Identifier anIdentifier,
MoleculePane aMoleculePane) {
//<editor-fold defaultstate="collapsed" desc="check">
if (aData == null) {
throw new IllegalArgumentException("aData must not be null");
}
//</editor-fold>
this.data = aData;
this.index = Integer.parseInt(anIdentifier.toString("Counter"));
this.moleculePane = aMoleculePane;
// this.moleculePane.setMinSize(Globals.moleculePaneWidth, Globals.moleculePaneHeight);
// this.moleculePane.setPrefSize(Globals.moleculePaneWidth, Globals.moleculePaneHeight);
// this.moleculePane.setMaxSize(Globals.moleculePaneWidth, Globals.moleculePaneHeight);
this.moleculePane.bindSize();
Scene tmpScene = new Scene(this.moleculePane, Globals.moleculePaneWidth, Globals.moleculePaneHeight);
this.moleculePane.getStylesheets().add("/view/MoleculePaneStyle.css");
this.moleculePaneStage = new Stage();
this.moleculePaneStage.setScene(tmpScene);
this.moleculePaneStage.setTitle(this.data.getMolecule(this.index).getName());
this.moleculePaneStage.initModality(Modality.WINDOW_MODAL);
this.moleculePaneStage.initOwner(aStage);
this.moleculePaneStage.setMinWidth(Globals.moleculePaneWidth);
this.moleculePaneStage.setMinHeight(Globals.moleculePaneHeight);
// this.moleculePaneStage.setResizable(false);
this.moleculePaneStage.show();
moleculePane.getTabPane().setMaxHeight(moleculePane.getDesAnchorPane().getHeight());
moleculePane.getTabPane().setMinHeight(moleculePane.getDesAnchorPane().getHeight());
moleculePane.getDesAnchorPane().setMinHeight(moleculePane.getDesTitledPane().getHeight() - Globals.headerHeight);
moleculePane.getDesAnchorPane().setMaxHeight(moleculePane.getDesTitledPane().getHeight() - Globals.headerHeight);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="public methods">
//<editor-fold defaultstate="collapsed" desc="setContent">
/**
* Sets content to the moleculePane
*/
public void setContent() {
this.setStructure();
this.setInfoContent();
this.setPropetiesContent();
this.setDescriptorContent();
this.addListener();
}
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private methods">
//<editor-fold defaultstate="collapsed" desc="setInfoContent">
/**
* Sets content to the infoListView
*/
private void setInfoContent() {
ObservableList<String> tmpInfoList = FXCollections.observableArrayList();
double tmpMass = this.data.getMolecule(this.index).getMass();
int tmpAtomCount = this.data.getMolecule(this.index).getAtomCount();
int tmpBondCount = this.data.getMolecule(this.index).getBondCount();
int tmpCharge = this.data.getMolecule(this.index).getCharge();
tmpInfoList.add("ID:\t" + this.data.getMolecule(this.index).getIdentifier().toString("Counter"));
tmpInfoList.add("Molecular Mass:\t" + String.valueOf(tmpMass));
tmpInfoList.add("Atoms:\t" + String.valueOf(tmpAtomCount));
tmpInfoList.add("Bonds:\t" + String.valueOf(tmpBondCount));
tmpInfoList.add("Charge:\t" + String.valueOf(tmpCharge));
tmpInfoList.add("Check:\t" + this.data.getMolecule(this.index).isChecked());
this.moleculePane.getInfoListView().setItems(tmpInfoList);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPropertiesContent">
/**
* Sets content to the propertiesListView
*/
private void setPropetiesContent() {
ObservableList<String> tmpPropertiesList = FXCollections.observableArrayList();
Map<Object, Object> tmpPropertiesMap = this.data.getMolecule(this.index).getProperties();
String tmpKey;
String tmpValue;
for (Entry<Object, Object> tmpEntry : tmpPropertiesMap.entrySet()) {
tmpKey = tmpEntry.getKey().toString();
if (tmpEntry.getValue() != null) {
tmpValue = tmpEntry.getValue().toString();
} else {
tmpValue = "no value found";
}
tmpPropertiesList.add(UtilityMethods.getOnlyAscii(tmpKey + ":\t" + tmpValue));
}
this.moleculePane.getPropertiesListView().setItems(tmpPropertiesList);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setDescriptorContent">
/**
* Sets content to the descriptorListView
*/
private void setDescriptorContent() {
Map<Object, Object> tmpResultMap = this.data.getMolecule(this.index).getResultsMap();
String tmpName;
String tmpValue;
//atomic
ObservableList<String> tmpAtomicList = FXCollections.observableArrayList();
for(Entry<Object, Object> tmpEntry : tmpResultMap.entrySet()){
if(UtilityMethods.isDescriptorTypeOf((IDescriptor) tmpEntry.getKey(), Globals.atomic)){
tmpName = UtilityMethods.getDescriptorName((IDescriptor) tmpEntry.getKey());
tmpName = UtilityMethods.getOnlyAscii(tmpName);
if(tmpEntry.getValue() != null){
tmpValue = tmpEntry.getValue().toString();
tmpValue = UtilityMethods.getOnlyAscii(tmpValue);
// tmpValue = UtilityMethods.cutOfStringValue(tmpValue);
} else {
tmpValue = "NaN";
}
tmpAtomicList.add(tmpName + ": \t" + tmpValue);
}
}
if(tmpAtomicList.isEmpty()){
tmpAtomicList.add("no descriptor value found");
}
this.moleculePane.getAtomicListView().setItems(tmpAtomicList);
//atomPair
ObservableList<String> tmpAtomPairList = FXCollections.observableArrayList();
tmpAtomPairList.clear();
for(Entry<Object, Object> tmpEntry : tmpResultMap.entrySet()){
if(UtilityMethods.isDescriptorTypeOf((IDescriptor) tmpEntry.getKey(), Globals.atomPair)){
tmpName = UtilityMethods.getDescriptorName((IDescriptor) tmpEntry.getKey());
tmpName = UtilityMethods.getOnlyAscii(tmpName);
if(tmpEntry.getValue() != null){
tmpValue = tmpEntry.getValue().toString();
tmpValue = UtilityMethods.getOnlyAscii(tmpValue);
// tmpValue = UtilityMethods.cutOfStringValue(tmpValue);
} else {
tmpValue = "Nan";
}
tmpAtomPairList.add(tmpName + ": \t" + tmpValue);
}
}
if(tmpAtomPairList.isEmpty()){
tmpAtomPairList.add("no descriptor value found");
}
this.moleculePane.getAtomPairListView().setItems(tmpAtomPairList);
//bond
ObservableList<String> tmpBondList = FXCollections.observableArrayList();
for(Entry<Object, Object> tmpEntry : tmpResultMap.entrySet()){
if(UtilityMethods.isDescriptorTypeOf((IDescriptor) tmpEntry.getKey(), Globals.bond)){
tmpName = UtilityMethods.getDescriptorName((IDescriptor) tmpEntry.getKey());
tmpName = UtilityMethods.getOnlyAscii(tmpName);
if(tmpEntry.getValue() != null){
tmpValue = tmpEntry.getValue().toString();
tmpValue = UtilityMethods.getOnlyAscii(tmpValue);
// tmpValue = UtilityMethods.cutOfStringValue(tmpValue);
} else {
tmpValue = "NaN";
}
tmpBondList.add(tmpName + ": \t" + tmpValue);
}
}
if(tmpBondList.isEmpty()){
tmpBondList.add("no descriptor value found");
}
this.moleculePane.getBondListView().setItems(tmpBondList);
//molecular
ObservableList<String> tmpMolecularList = FXCollections.observableArrayList();
for(Entry<Object, Object> tmpEntry : tmpResultMap.entrySet()){
if(UtilityMethods.isDescriptorTypeOf((IDescriptor) tmpEntry.getKey(), Globals.molecular)){
tmpName = UtilityMethods.getDescriptorName((IDescriptor) tmpEntry.getKey());
tmpName = UtilityMethods.getOnlyAscii(tmpName);
if(tmpEntry.getValue() != null){
tmpValue = tmpEntry.getValue().toString();
tmpValue = UtilityMethods.getOnlyAscii(tmpValue);
// tmpValue = UtilityMethods.cutOfStringValue(tmpValue);
} else {
tmpValue = "NaN";
}
tmpMolecularList.add(tmpName + ": \t" + tmpValue);
}
}
if(tmpMolecularList.isEmpty()){
tmpMolecularList.add("no descriptor value found");
}
this.moleculePane.getMolecularListView().setItems(tmpMolecularList);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setStructure">
/**
* Sets an image to the structureAnchorPane
*/
private void setStructure() {
int tmpWidth = (int) (this.moleculePane.getStructurePane().getWidth() - 2 * Globals.mainPaneInsets);
int tmpHeight = (int) (this.moleculePane.getStructurePane().getHeight() - 2 * Globals.mainPaneInsets);
ImageView tmpImageView = new ImageView();
tmpImageView.setImage(this.data.getMolecule(this.index).createImage(tmpWidth, tmpHeight));
this.moleculePane.getStructurePane().getChildren().add(tmpImageView);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="addListener">
/**
* Adds Listeners and EventHandlers to the MoleculePane
*/
private void addListener() {
//<editor-fold defaultstate="collapsed" desc="closeButton">
/**
* Adds an EventHandler to the CloseButton which closes this stage
*/
this.moleculePane.getCloseButton().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
MoleculePaneController.this.moleculePaneStage.close();
}
});
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="width ChangeListener">
/**
* ChangeListener for the width, sets new image
*/
this.moleculePane.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
MoleculePaneController.this.setStructure();
}
});
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="height ChangeListener">
/**
* ChangeListener for the height, sets new image
*/
this.moleculePane.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
MoleculePaneController.this.setStructure();
moleculePane.getTabPane().setMaxHeight(moleculePane.getDesAnchorPane().getHeight());
moleculePane.getTabPane().setMinHeight(moleculePane.getDesAnchorPane().getHeight());
moleculePane.getDesAnchorPane().setMinHeight(moleculePane.getDesTitledPane().getHeight() - Globals.headerHeight);
moleculePane.getDesAnchorPane().setMaxHeight(moleculePane.getDesTitledPane().getHeight() - Globals.headerHeight);
}
});
//</editor-fold>
}
//</editor-fold>
//</editor-fold>
}
| true |
6b30c79c683b1b7dba2cfbdb8843ab71daf9ee80 | Java | greyhawk/learning-akka | /akkademy-db-client/src/main/java/com/akkademy/messages/KeyNotFoundException.java | UTF-8 | 375 | 2.09375 | 2 | [
"MIT"
] | permissive | package com.akkademy.messages;
import java.io.Serializable;
/**
* KeyNotFoundException
* @author ging wu
* @date 2018/12/5
*/
public class KeyNotFoundException extends Exception implements Serializable {
private final String key;
public KeyNotFoundException(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
| true |
98dd76d54d390e50693bc0de958f79ae8a9353ce | Java | finos/legend-pure | /legend-pure-m3-core/src/test/java/org/finos/legend/pure/m3/tests/function/base/tracing/AbstractTestTraceSpan.java | UTF-8 | 7,373 | 1.945313 | 2 | [
"Apache-2.0",
"CC0-1.0"
] | permissive | // Copyright 2020 Goldman Sachs
//
// 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.finos.legend.pure.m3.tests.function.base.tracing;
import org.finos.legend.pure.m3.tests.AbstractPureTestWithCoreCompiled;
import org.finos.legend.pure.m3.exception.PureAssertFailException;
import io.opentracing.util.GlobalTracer;
import org.junit.*;
import java.lang.reflect.Field;
import java.util.Map;
public abstract class AbstractTestTraceSpan extends AbstractPureTestWithCoreCompiled
{
protected static final InMemoryTracer tracer = new InMemoryTracer();
@Test
public void testTraceSpan()
{
compileTestSource("fromString.pure", "function testTraceSpan():Nil[0]\n" +
"{\n" +
" meta::pure::functions::tracing::traceSpan(|print('Hello World',1), 'Test Execute');\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
Assert.assertTrue(tracer.spanExists("Test Execute"));
}
@Test
public void testTraceSpanWithReturnValue()
{
compileTestSource("fromString.pure", "function testTraceSpan():Nil[0]\n" +
"{\n" +
" let text = meta::pure::functions::tracing::traceSpan(|' World', 'Test Execute');\n" +
" print('Hello' + $text, 1);\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
}
@Test
public void testTraceSpanWithAnnotations()
{
compileTestSource("fromString.pure", "function testTraceSpan():Nil[0]\n" +
"{\n" +
" let annotations = newMap([\n" +
" pair('key1', 'value1'), \n" +
" pair('key2', 'value2')\n" +
" ]); \n" +
" meta::pure::functions::tracing::traceSpan(|print('Hello World',1), 'Test Execute', |$annotations);\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
Assert.assertTrue(tracer.spanExists("Test Execute"));
Map<Object, Object> tags = this.tracer.getTags("Test Execute");
Assert.assertEquals(tags.get("key1"), "value1");
Assert.assertEquals(tags.get("key2"), "value2");
}
@Test
public void testTraceSpanUsingEval()
{
compileTestSource("fromString.pure", "function testTraceSpan():Nil[0]\n" +
"{\n" +
" let res = meta::pure::functions::tracing::traceSpan_Function_1__String_1__V_m_->eval(|'Hello World', 'Test Execute');\n" +
" print($res,1);" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
Assert.assertTrue(tracer.spanExists("Test Execute"));
}
@Test
public void testDoNoTraceIfTracerNotRegistered()
{
tracer.reset();
unregisterTracer();
compileTestSource("fromString.pure", "function testTraceSpan():Nil[0]\n" +
"{\n" +
" meta::pure::functions::tracing::traceSpan(|print('Hello World',1), 'Test Execute');\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
Assert.assertFalse(tracer.spanExists("Test Execute"));
GlobalTracer.registerIfAbsent(tracer);
}
@Test
public void testTraceSpanShouldHandleErrorWhileEvaluatingTagsLamda()
{
compileTestSource("fromString.pure", "function getTags(): Map<String, String>[1] {" +
" assert('a' == 'b', |''); " +
" newMap([ \n" +
" pair('key1', '') \n" +
" ]); \n" +
"}" +
"function testTraceSpan():Nil[0]\n" +
"{\n" +
" meta::pure::functions::tracing::traceSpan(|print('Hello World',1), 'Test Execute', |getTags(), false);\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
Assert.assertTrue(tracer.spanExists("Test Execute"));
Map<Object, Object> tags = this.tracer.getTags("Test Execute");
Assert.assertTrue(tags.get("Exception").toString().startsWith("Unable to resolve tags - "));
}
@Test
public void testTraceSpanShouldHandleStackOverflowErrorWhileEvaluatingTagsLamda()
{
compileTestSource("fromString.pure", "function getTags(): Map<String, String>[1] {" +
" getTags(); \n" +
"}" +
"function testTraceSpan():Nil[0]\n" +
"{\n" +
" meta::pure::functions::tracing::traceSpan(|print('Hello World', 1), 'Test Execute', |getTags(), false);\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
Assert.assertEquals("'Hello World'", this.functionExecution.getConsole().getLine(0));
Assert.assertTrue(tracer.spanExists("Test Execute"));
Map<Object, Object> tags = this.tracer.getTags("Test Execute");
Assert.assertTrue(tags.get("Exception").toString().startsWith("Unable to resolve tags - "));
}
@Test(expected = PureAssertFailException.class)
public void testTraceSpanShouldNotHandleErrorWhileEvaluatingTagsLamda()
{
compileTestSource("fromString.pure", "function getTags(): Map<String, String>[1] {" +
" assert('a' == 'b', |''); " +
" newMap([ \n" +
" pair('key1', '') \n" +
" ]); \n" +
"}" +
"function testTraceSpan():Nil[0]\n" +
"{\n" +
" meta::pure::functions::tracing::traceSpan(|print('Hello World',1), 'Test Execute', |getTags());\n" +
"}\n");
this.execute("testTraceSpan():Nil[0]");
}
@AfterClass
public static void tearDown()
{
tracer.reset();
unregisterTracer();
}
private static void unregisterTracer()
{
try
{
// HACK since GlobalTracer api doesnt provide a way to reset the tracer which is needed for testing
Field tracerField = GlobalTracer.get().getClass().getDeclaredField("isRegistered");
tracerField.setAccessible(true);
tracerField.set(GlobalTracer.get(), false);
Assert.assertFalse(GlobalTracer.isRegistered());
}
catch (Exception ignored)
{
}
}
}
| true |
5faf1e0bfde97d8a0c45198c127c93b720f9b082 | Java | SerenaMB1/FlockingApplication | /AssignmentHome/src/assignmentMain.java | UTF-8 | 7,413 | 3.015625 | 3 | [] | no_license |
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Hashtable;
import Birds.randomBirds;
import dF.Utils;
import drawing.Canvas;
public class assignmentMain {
//Initial Coordinates
public double x = 100.0;
public double y = 100.0;
//
double addX;
double addY;
//initial amount of birds
int maxBirds = 10;
double rand;
//Declaring
ArrayList<randomBirds> birds;
//Bird Speed - Slider values
//Initial time increments
int deltaTime;
static final int speedMin = 20;
static final int speedMax = 100;
static final int speedInit = 20;
//Alignment - Slider values
//
double kA;
static final int alignmentMin = 0;
static final int alignmentMax = 100;
static final int alignmentInit = 0;
//Alignment - Slider values
//
double kC;
static final int cohesionMin = 0;
static final int cohesionMax = 100;
static final int cohesionInit = 0;
//Alignment - Slider values
//
double kS;
static final int seperationMin = 0;
static final int seperationMax = 100;
static final int seperationInit = 0;
//Game loop
boolean continueRunning = true;
public assignmentMain() {
//SLIDER - Bird Speed
deltaTime = speedInit;
//Declaring new instance of slider
JSlider birdSpeed = new JSlider(JSlider.HORIZONTAL, speedMin,speedMax,speedInit);
//adding ticks to the slider
birdSpeed.setMajorTickSpacing(20);
birdSpeed.setMinorTickSpacing(5);
birdSpeed.setPaintTicks(true);
birdSpeed.setPaintLabels(true);
Hashtable speed = new Hashtable();
speed.put(new Integer(50), new JLabel("Speed"));
birdSpeed.setLabelTable(speed);
birdSpeed.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
deltaTime = birdSpeed.getValue();
}
});
//Slider For Alignment
kA = alignmentInit;
//Declaring new instance of slider
JSlider alignment = new JSlider(JSlider.HORIZONTAL, alignmentMin,alignmentMax,alignmentInit);
//adding ticks to the slider
alignment.setMajorTickSpacing(25);
alignment.setMinorTickSpacing(5);
alignment.setPaintTicks(true);
alignment.setPaintLabels(true);
Hashtable alignment1 = new Hashtable();
alignment1.put(new Integer(50), new JLabel("Alignment"));
alignment.setLabelTable(alignment1);
alignment.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
kA = alignment.getValue();
}
});
//Slider For Cohesion
kC = cohesionInit;
//Declaring new instance of slider
JSlider Cohesion = new JSlider(JSlider.HORIZONTAL, cohesionMin,cohesionMax,cohesionInit);
//adding ticks to the slider
Cohesion.setMajorTickSpacing(25);
Cohesion.setMinorTickSpacing(5);
Cohesion.setPaintTicks(true);
Cohesion.setPaintLabels(true);
Hashtable Cohesion1 = new Hashtable();
Cohesion1.put(new Integer(50), new JLabel("Cohesion"));
Cohesion.setLabelTable(Cohesion1);
Cohesion.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
kC = Cohesion.getValue();
}
});
//Slider For separation
kS = seperationInit;
//Declaring new instance of slider
JSlider separation = new JSlider(JSlider.HORIZONTAL, cohesionMin,cohesionMax,cohesionInit);
//adding ticks to the slider
separation.setMajorTickSpacing(25);
separation.setMinorTickSpacing(5);
separation.setPaintTicks(true);
separation.setPaintLabels(true);
Hashtable separation1 = new Hashtable();
separation1.put(new Integer(50), new JLabel("Separation"));
separation.setLabelTable(separation1);
separation.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
kS = separation.getValue();
}
});
//Instantiating new frame
JFrame frame = new JFrame();
//Instantiating new canvas
Canvas canvas = new Canvas();
//Instantiating new label for program title
JLabel label = new JLabel("Flockety Flock Flock");
//Instantiating new Lower panel
JPanel lowerpanel = new JPanel();
//Instantiating new button to add more birds to the frame
JButton addBirdButton = new JButton("Add new bird");
JButton removeBirdButton = new JButton("Remove Bird");
//Changing lower panel layout from border to flowlayout
lowerpanel.setLayout(new FlowLayout());
//adding items to the frame
frame.setTitle("Flock the Frame");
frame.setSize(1200, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(canvas);
frame.add(lowerpanel, BorderLayout.SOUTH);
//adding items to the canvas
canvas.add(label);
//adding items to the lower panel
lowerpanel.add(addBirdButton, BorderLayout.PAGE_END);
lowerpanel.add(removeBirdButton, BorderLayout.PAGE_END);
lowerpanel.add(birdSpeed,BorderLayout.PAGE_END);
lowerpanel.add(alignment,BorderLayout.PAGE_END);
lowerpanel.add(Cohesion,BorderLayout.PAGE_END);
lowerpanel.add(separation,BorderLayout.PAGE_END);
label.setHorizontalAlignment(SwingConstants.CENTER);
//instantiating new array list for the birds
ArrayList<randomBirds> birds = new ArrayList<randomBirds>();
//Adding and listening for the add bird button
addBirdButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
addBirdButton.setText("done");
double xCoordinate = x+(int)addX ;
double yCoordinate = y+(int)addY;
addX = (Utils.randomDouble())*500;
addY = (Utils.randomDouble())*500;
birds.add(new randomBirds(canvas, xCoordinate, yCoordinate));
}
});
//Adding and listening for the add bird button
removeBirdButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
birds.remove(0).undraw();
}
});
//Loop used to add the initial 10 birds to the flock
for (int i = 0; i < maxBirds; i++){
double xCoordinate = x+(int)addX ;
double yCoordinate = y+(int)addY;
//Used to randomise the angles in which they appear on the screen
addX = (Utils.randomDouble())*500;
addY = (Utils.randomDouble())*500;
//Adds the birds to the array as they are made
birds.add(new randomBirds(canvas, xCoordinate, yCoordinate));
}
// game loop
// The game loop will undraw then update and then draw each bird again to
//ensure the smooth running of the graphics.
while (continueRunning) {
Utils.pause(deltaTime);
for (randomBirds ss: birds) {
ss.undraw();
}
for (randomBirds ss: birds) {
ss.update(deltaTime);
}
for (randomBirds ss : birds) {
ss.draw();
}
for ( randomBirds ss : birds){
//these are the flocking methods that have been asigned to the
//array.
ss.alignment(birds, deltaTime, kA);
ss.Cohesion(birds, deltaTime, kC);
ss.separation(birds, deltaTime, kS);
ss.wrapPosition(1200,900);
}
}
}
public static void main(String[] args) {
new assignmentMain();
}
} | true |
98170dfe41330628a79a2a3f1b96e386c86c0d09 | Java | olgaviho/otm-harjoitustyo | /MyStudies/src/test/java/dao/DatabaseUserDaoTest.java | UTF-8 | 1,871 | 2.71875 | 3 | [] | no_license |
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import mystudies.dao.Database;
import mystudies.dao.DatabaseUserDao;
import mystudies.domain.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author olgaviho
*/
public class DatabaseUserDaoTest {
Database database;
User user;
User user2;
DatabaseUserDao userDao;
@Before
public void setUp() throws Exception {
database = new Database("jdbc:sqlite:mystudiestest.db");
Connection conn = database.getConnection();
PreparedStatement stmt = conn.prepareStatement("CREATE TABLE if not exists users (id integer PRIMARY KEY, name varchar(20))");
stmt.execute();
userDao = new DatabaseUserDao(database);
user = new User(123, "nimi");
user2 = new User(124, "nimi");
}
@Test
public void returnsNullWhenDoesntFindUser() throws SQLException {
assertEquals(null,userDao.findOne(678));
}
@Test
public void itIsPossibleToSaveAndFindUsers() throws SQLException {
userDao.save(user);
assertEquals("nimi",userDao.findOne(user.getId()).getName());
}
@Test
public void findAllFindsAllUsers() throws SQLException {
userDao.save(user);
userDao.save(user2);
List<User> twoUsers = userDao.findAll();
assertEquals(2,twoUsers.size());
}
@After
public void tearDown() throws SQLException {
Connection conn = database.getConnection();
PreparedStatement stmt = conn.prepareStatement("DROP TABLE users");
stmt.executeUpdate();
stmt.close();
conn.close();
}
}
| true |
0374bc4f6f16ada19707089a4542782e1b20312a | Java | psoursos/Sir-examples | /SAGdesign/src/SAG/impl/GoalImpl.java | UTF-8 | 9,378 | 1.648438 | 2 | [] | no_license | /**
*/
package SAG.impl;
import SAG.Actor;
import SAG.Goal;
import SAG.SAGPackage;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Goal</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link SAG.impl.GoalImpl#getRequirements <em>Requirements</em>}</li>
* <li>{@link SAG.impl.GoalImpl#getName <em>Name</em>}</li>
* <li>{@link SAG.impl.GoalImpl#getDepender <em>Depender</em>}</li>
* <li>{@link SAG.impl.GoalImpl#getDependee <em>Dependee</em>}</li>
* </ul>
*
* @generated
*/
public class GoalImpl extends MinimalEObjectImpl.Container implements Goal {
/**
* The default value of the '{@link #getRequirements() <em>Requirements</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRequirements()
* @generated
* @ordered
*/
protected static final String REQUIREMENTS_EDEFAULT = null;
/**
* The cached value of the '{@link #getRequirements() <em>Requirements</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRequirements()
* @generated
* @ordered
*/
protected String requirements = REQUIREMENTS_EDEFAULT;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getDepender() <em>Depender</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDepender()
* @generated
* @ordered
*/
protected Actor depender;
/**
* The cached value of the '{@link #getDependee() <em>Dependee</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDependee()
* @generated
* @ordered
*/
protected EList<Actor> dependee;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GoalImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return SAGPackage.Literals.GOAL;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getRequirements() {
return requirements;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRequirements(String newRequirements) {
String oldRequirements = requirements;
requirements = newRequirements;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, SAGPackage.GOAL__REQUIREMENTS, oldRequirements, requirements));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, SAGPackage.GOAL__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Actor getDepender() {
if (depender != null && depender.eIsProxy()) {
InternalEObject oldDepender = (InternalEObject)depender;
depender = (Actor)eResolveProxy(oldDepender);
if (depender != oldDepender) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, SAGPackage.GOAL__DEPENDER, oldDepender, depender));
}
}
return depender;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Actor basicGetDepender() {
return depender;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDepender(Actor newDepender, NotificationChain msgs) {
Actor oldDepender = depender;
depender = newDepender;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SAGPackage.GOAL__DEPENDER, oldDepender, newDepender);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDepender(Actor newDepender) {
if (newDepender != depender) {
NotificationChain msgs = null;
if (depender != null)
msgs = ((InternalEObject)depender).eInverseRemove(this, SAGPackage.ACTOR__MY_GOAL, Actor.class, msgs);
if (newDepender != null)
msgs = ((InternalEObject)newDepender).eInverseAdd(this, SAGPackage.ACTOR__MY_GOAL, Actor.class, msgs);
msgs = basicSetDepender(newDepender, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, SAGPackage.GOAL__DEPENDER, newDepender, newDepender));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Actor> getDependee() {
if (dependee == null) {
dependee = new EObjectResolvingEList<Actor>(Actor.class, this, SAGPackage.GOAL__DEPENDEE);
}
return dependee;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case SAGPackage.GOAL__DEPENDER:
if (depender != null)
msgs = ((InternalEObject)depender).eInverseRemove(this, SAGPackage.ACTOR__MY_GOAL, Actor.class, msgs);
return basicSetDepender((Actor)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case SAGPackage.GOAL__DEPENDER:
return basicSetDepender(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case SAGPackage.GOAL__REQUIREMENTS:
return getRequirements();
case SAGPackage.GOAL__NAME:
return getName();
case SAGPackage.GOAL__DEPENDER:
if (resolve) return getDepender();
return basicGetDepender();
case SAGPackage.GOAL__DEPENDEE:
return getDependee();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case SAGPackage.GOAL__REQUIREMENTS:
setRequirements((String)newValue);
return;
case SAGPackage.GOAL__NAME:
setName((String)newValue);
return;
case SAGPackage.GOAL__DEPENDER:
setDepender((Actor)newValue);
return;
case SAGPackage.GOAL__DEPENDEE:
getDependee().clear();
getDependee().addAll((Collection<? extends Actor>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case SAGPackage.GOAL__REQUIREMENTS:
setRequirements(REQUIREMENTS_EDEFAULT);
return;
case SAGPackage.GOAL__NAME:
setName(NAME_EDEFAULT);
return;
case SAGPackage.GOAL__DEPENDER:
setDepender((Actor)null);
return;
case SAGPackage.GOAL__DEPENDEE:
getDependee().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case SAGPackage.GOAL__REQUIREMENTS:
return REQUIREMENTS_EDEFAULT == null ? requirements != null : !REQUIREMENTS_EDEFAULT.equals(requirements);
case SAGPackage.GOAL__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case SAGPackage.GOAL__DEPENDER:
return depender != null;
case SAGPackage.GOAL__DEPENDEE:
return dependee != null && !dependee.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (requirements: ");
result.append(requirements);
result.append(", name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //GoalImpl
| true |
fd0716ad8becdecc12c659c3edadf9f29cde556c | Java | jyn199/mybatisdemo | /src/main/java/com/app/mybatis/plugins/pagable/dialects/OracleDialect.java | UTF-8 | 586 | 2.3125 | 2 | [] | no_license | package com.app.mybatis.plugins.pagable.dialects;
import com.app.mybatis.plugins.pagable.Dialect;
public class OracleDialect implements Dialect {
@Override
public String buildPaginationSql(String originalSql, int offset, int length) {
StringBuilder paginationSql = new StringBuilder(originalSql);
paginationSql.insert(0, "select t2.*, rownum rn from ( ")
.append(" ) t2 where rownum < ").append(offset + length);
paginationSql.insert(0, "select t1.* from ( ").append(" ) t1 where t1.rn >= ")
.append(offset);
return paginationSql.toString();
}
}
| true |
31c1feaab7a0446e5e598f2db734b236870f2571 | Java | octavian-h/npanday | /components/dotnet-executable/src/main/java/npanday/executable/impl/VersionComparer.java | UTF-8 | 2,328 | 2 | 2 | [
"Apache-2.0",
"zlib-acknowledgement"
] | 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 npanday.executable.impl;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import javax.annotation.Nullable;
import java.util.List;
/**
* @author <a href="mailto:me@lcorneliussen.de>Lars Corneliussen, Faktum Software</a>
*/
public class VersionComparer
{
public static boolean isVendorVersionMissmatch( String capability, String requirement )
{
return capability != null && !requirement.equals( capability );
}
public static boolean isFrameworkVersionMissmatch( List<String> capability, final String requirement )
{
if ( capability != null && capability.size() > 0 )
{
if ( !Iterables.any(
capability, new Predicate<String>()
{
public boolean apply( @Nullable String frameworkVersion )
{
return normalize(requirement).equals( normalize(frameworkVersion) );
}
}
) )
{
return true;
}
}
return false;
}
private static String normalize( String version )
{
if ( version.equals( "1.0.3705") )
{
return "1.0";
}
if ( version.equals( "1.1.4322") )
{
return "1.1";
}
if ( version.equals( "2.0.50727") )
{
return "2.0";
}
if ( version.equals( "v4.0.30319") )
{
return "4.0";
}
return version;
}
}
| true |
dae07087e1069ceece2bbe2a17765b681d1f2dfe | Java | marcusvpr/mprest | /src/main/java/com/mpxds/mprest/domain/xml/atox/SignatureMethod.java | UTF-8 | 474 | 2.015625 | 2 | [
"MIT"
] | permissive | package com.mpxds.mprest.domain.xml.atox;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="SignatureMethod")
public class SignatureMethod {
//
@XmlAttribute(name="Algorithm")
private String Algorithm;
// ---
public String getAlgorithm() { return Algorithm; }
// ---
@Override
public String toString() {
//
return "SignatureMethod[Algorithm=" + Algorithm + "|]SignatureMethod";
}
} | true |
f7dd85c875bbccf6dee3ab570d4f892496c30947 | Java | Sasikala0105/Assign1 | /Assignment1/src/StressRelief.java | UTF-8 | 321 | 2.515625 | 3 | [] | no_license |
public class StressRelief {
String sukhasana,balasana;
public StressRelief(String m,String n) {
}
public void setPoses(String m,String n) {
this.sukhasana=m;
this.balasana=n;
}
public String getsukhasana() {
return sukhasana;
}
public String getbalasana() {
return balasana;
}
} | true |
c228963a457b99945fedfcea43c11f7cd6cf4f62 | Java | novastosha/Sweet-Candy | /src/main/java/dev/nova/thecandybot/game/base/GameInstance.java | UTF-8 | 1,174 | 2.40625 | 2 | [] | no_license | package dev.nova.thecandybot.game.base;
import dev.nova.thecandybot.Main;
import dev.nova.thecandybot.commands.base.Command;
import dev.nova.thecandybot.game.pushboxes.Grid;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import javax.annotation.OverridingMethodsMustInvokeSuper;
public abstract class GameInstance extends ListenerAdapter {
private final Member member;
private final TextChannel channel;
private final Game game;
public GameInstance(Game game, Member member, TextChannel channel, Command... commands){
this.member = member;
this.game = game;
this.channel = channel;
Main.registerCommands(commands);
Main.registerEvents(this);
}
public TextChannel getChannel() {
return channel;
}
public Game getGame() {
return game;
}
public Member getMember() {
return member;
}
public abstract void newGame() throws Grid.GridMakingException;
@OverridingMethodsMustInvokeSuper
public void endGame(){
game.instances.remove(member);
}
}
| true |
33f432c11a8208249e1e0f24663291ea5ce7ac5f | Java | jacobfrose/Secret-Shopper-Application | /src/common/DynamicCombobox.java | UTF-8 | 1,400 | 2.796875 | 3 | [] | no_license | package common;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
public class DynamicCombobox {
/**
* Updates specified DefaultComboBoxModel "model" with the query determined by "columns", "tableName", and "conditions".
* @param model
* @param columns
* @param tableName
* @param conditions
*/
public static void updateComboBox(DefaultComboBoxModel model, JComboBox comboBox, String columns, String tableName, String conditions, Connection con)
{
model = (DefaultComboBoxModel) comboBox.getModel();
model.removeAllElements();
try {
ResultSet result = con.createStatement().executeQuery("SELECT "+ columns + " FROM " + tableName + " WHERE "+ conditions);
ResultSetMetaData meta = result.getMetaData();
while(result.next())
{
String item = "";
for(int i = 1; i <= meta.getColumnCount(); i++)
{
try
{
item += result.getString(i);
if(i < meta.getColumnCount())
{
item += " | ";
}
}
catch(NullPointerException n)
{
}
}
model.addElement(item);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
comboBox.setSelectedIndex(-1);
}
} | true |
4cd08929e1564f0bf1931775db770a44bdb7ffa2 | Java | lastFeynman/Introduction_to_Algorithms | /src/part3/chapter10/section10_1/Practice10_1_5.java | UTF-8 | 998 | 3.25 | 3 | [] | no_license | package part3.chapter10.section10_1;
public class Practice10_1_5 {
}
class DoubleEndQueue{
int[] queue = new int[21];
int head = 0;
int tail = 0;
public boolean isEmpty(){
return head == tail;
}
public boolean isFull(){
return (tail+1)%queue.length == head;
}
public boolean enterHead(int x){
if(isFull())
return false;
head = (head-1)%queue.length;
queue[head] = x;
return true;
}
public boolean enterTail(int x){
if(isFull())
return false;
queue[tail] = x;
tail = (tail+1)%queue.length;
return true;
}
public int exitHead(){
if(isEmpty())
return Integer.MIN_VALUE;
int x = queue[head];
head = (head+1)%queue.length;
return x;
}
public int exitTail(){
if(isEmpty())
return Integer.MIN_VALUE;
tail = (tail-1)%queue.length;
return queue[tail];
}
} | true |
de9d22c745896a1843e862b5d742dd93266bffd9 | Java | itdatao/takeaway-client | /src/main/java/com/ruoyi/web/controller/CommentController.java | UTF-8 | 1,541 | 1.921875 | 2 | [] | no_license | package com.ruoyi.web.controller;
import com.ruoyi.web.common.AjaxResult;
import com.ruoyi.web.form.CommentForm;
import com.ruoyi.web.service.CommentService;
import com.ruoyi.web.vo.CommentVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 客户端评论接口
*
* @Author Huhuitao
* @Date 2021/2/3 15:21
*/
@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {
@Autowired
@Qualifier("CommentServiceImpl")
private CommentService commentService;
@ApiOperation("分页查询客户所有评论")
@GetMapping("/list")
public AjaxResult list(@RequestParam(value = "tagId",required = false) Integer tagId,
@RequestParam(value = "page",defaultValue = "1") Integer page,
@RequestParam(value = "size",defaultValue = "10") Integer size) {
return AjaxResult.success(commentService.list(tagId,page,size));
}
//添加评论
@ApiOperation("添加评论")
@PostMapping("/add")
public AjaxResult addComment(HttpServletRequest request, @RequestBody CommentForm commentForm){
String token = request.getHeader("token");
commentService.addComment(token,commentForm);
return AjaxResult.success("添加评论成功!");
}
}
| true |
819f0490a97860e16084b9b3f6497d9c9f9fc8bc | Java | mathck/BARK_it | /app/src/main/java/com/barkitapp/android/_main/SettingsFragment.java | UTF-8 | 1,439 | 1.585938 | 2 | [] | no_license | package com.barkitapp.android._main;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.barkitapp.android.R;
import com.barkitapp.android._core.services.InternalAppData;
import com.barkitapp.android._core.services.MasterList;
import com.barkitapp.android._core.utility.SharedPrefKeys;
import com.barkitapp.android.parse_backend.objects.FeaturedLocation;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.pnikosis.materialishprogress.ProgressWheel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
| true |
5aa9709031651ca2edd7576084fd536f38e04698 | Java | Sciss/bdb-je | /test/com/sleepycat/je/rep/impl/RepGroupImplTest.java | UTF-8 | 2,219 | 1.96875 | 2 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | /*-
* Copyright (C) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle Berkeley
* DB Java Edition made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle Berkeley DB Java Edition for a copy of the
* license and additional information.
*/
package com.sleepycat.je.rep.impl;
import static org.junit.Assert.assertEquals;
import java.net.UnknownHostException;
import org.junit.Test;
import com.sleepycat.je.rep.utilint.RepTestUtils;
import com.sleepycat.util.test.TestBase;
public class RepGroupImplTest extends TestBase {
@Test
public void testSerializeDeserialize()
throws UnknownHostException {
for (int formatVersion = RepGroupImpl.MIN_FORMAT_VERSION;
formatVersion <= RepGroupImpl.MAX_FORMAT_VERSION;
formatVersion++) {
final int electable = 5;
final int monitor = 1;
final int secondary =
(formatVersion < RepGroupImpl.FORMAT_VERSION_3) ?
0 :
3;
RepGroupImpl group =
RepTestUtils.createTestRepGroup(electable, monitor, secondary);
String s1 = group.serializeHex(formatVersion);
String tokens[] = s1.split(TextProtocol.SEPARATOR_REGEXP);
assertEquals(
1 + /* The Rep group itself */ +
electable + monitor + secondary, /* the individual nodes. */
tokens.length);
RepGroupImpl dgroup = RepGroupImpl.deserializeHex(tokens, 0);
assertEquals("Version", formatVersion, dgroup.getFormatVersion());
if (formatVersion == RepGroupImpl.INITIAL_FORMAT_VERSION) {
assertEquals("Deserialized version " + formatVersion,
group, dgroup);
}
String s2 = dgroup.serializeHex(formatVersion);
assertEquals("Reserialized version " + formatVersion, s1, s2);
}
}
}
| true |
47c8a88a07c0cda5c69526a9bc71dfd745170bb6 | Java | myeongin/findHero | /findhero/src/main/java/com/findhero/mapper/ReviewMapper.java | UTF-8 | 1,059 | 1.914063 | 2 | [] | no_license | package com.findhero.mapper;
import java.util.HashMap;
import java.util.List;
import com.findhero.vo.HeroVo;
import com.findhero.vo.ReviewVo;
import com.findhero.vo.RsVo;
import com.findhero.vo.UserVo;
public interface ReviewMapper {
List<ReviewVo> selectReview(HashMap<String,Object> selects);
void writeReview(HashMap<String, Object> params);
List<ReviewVo> reviewList(int userNo, int heroNo);
ReviewVo getReview(int reviewNo);
int getReviewNo(HashMap<String, Object> params);
void insertReview(ReviewVo review);
//리뷰쓰기
void registerReview(ReviewVo review);
//리뷰목록(나중에)
List<ReviewVo> reviewListMapper(int heroNo, int reviewNo);
void remove(int reviewNo);
HeroVo selectHero(int heroNo);
RsVo selectRs(int rsNo);
UserVo selectUser(int userNo);
List<ReviewVo> reviewList(HashMap<String, Object> review);
List<UserVo> selectUserList(int heroNo);
int selectUserCountByUserNoAndHeroNo(HashMap<String, Object> params);
}
| true |
67d3d7d0dde96d56dc86345a87755ccc8273595e | Java | nv3ob61/RSSFeed | /src/org/monmo/java/main/Main.java | UTF-8 | 1,403 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2020 nv3ob61
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.monmo.java.main;
import org.monmo.java.app.App;
/**
*
* @author mon-mode
*/
public final class Main {
//clave de acceso: Declaramos la constante del serial como private para que
//no pueda ser accesible desde fuera.
private static final String ACCESS_UID = "mon_mode2020";
//Punto de entrada al programa
public static final void main(String[] args) {
if (args.length == 1 && args[0].equals(ACCESS_UID)) {
// Crear aplicación
final App APP = new App();
//Lanzar aplicación
APP.launchApp();
} else {
System.out.println("Acceso Denegado");
System.out.println("---");
System.out.println("Contacte con su servicio técnico");
}
}
}
| true |
33d7fb0a8c581915c094ac663e929a9d110d4858 | Java | stupidcupid/multithreading | /src/com/multithreading/pc12/Test.java | UTF-8 | 396 | 2.484375 | 2 | [] | no_license | package com.multithreading.pc12;
/**
* Created by nanzhou on 2017/6/1.
*/
public class Test {
public static void main(String[] args) throws InterruptedException{
Task task = new Task();
MyThread1 myThread1= new MyThread1(task);
myThread1.start();
Thread.sleep(100);
MyThread2 myThread2 = new MyThread2(task);
myThread2.start();
}
}
| true |
f2ed96a4788bdb68a67777011386c626a0962ac5 | Java | todoee/todoee | /todoee-service/src/main/java/io/todoee/service/module/ServiceModule.java | UTF-8 | 439 | 1.84375 | 2 | [] | no_license | package io.todoee.service.module;
import com.google.inject.AbstractModule;
import io.todoee.service.provider.CircuitBreakerProvider;
import io.vertx.circuitbreaker.CircuitBreaker;
/**
*
* @author James.zhang
*
*/
public class ServiceModule extends AbstractModule {
@Override
protected void configure() {
bind(CircuitBreaker.class).toProvider(CircuitBreakerProvider.class).asEagerSingleton();
}
}
| true |