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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fe1d5386e37670d651a851a9dc40a9528ae86888
|
Java
|
aleepolicarps/StarWars2D
|
/src/main/java/upm/cmsc/starwars/states/StoryBoardState.java
|
UTF-8
| 1,629
| 2.765625
| 3
|
[] |
no_license
|
package upm.cmsc.starwars.states;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class StoryBoardState extends BasicGameState{
Image bg;
Image storyboard;
Image back;
String text = "Princess Leia was captured by Darth Vader!\n\n" +
"Our hero, Luke Skywalker, and his friends must now come and rescue her.\n" +
"Unfortunately, Darth Vader's whereabouts are unknown. Luke must now defeat\n" +
"different kinds of enemies to gain information about Darth Vader and rescue.\n" +
"Princess Leia.\n" +
"\nWill he succeed? Or will it be too late?";
@Override
public void init(GameContainer gc, StateBasedGame s) throws SlickException {
bg = new Image("menu/bg.png");
storyboard = new Image("menu/storyboard.png");
back = new Image("menu/back.png");
}
@Override
public void render(GameContainer gc, StateBasedGame s, Graphics g) throws SlickException {
g.drawImage(bg, 0, 0);
storyboard.draw(240,50);
g.drawString(text, 80, 150);
back.draw(320,500);
}
@Override
public void update(GameContainer gc, StateBasedGame s, int delta) throws SlickException {
int posX = Mouse.getX();
int posY = Mouse.getY();
if((posX>320 && posX<450)&& (posY>70 && posY<95)){
if(Mouse.isButtonDown(Input.MOUSE_LEFT_BUTTON)){
s.enterState(State.MENU);
}
}
}
@Override
public int getID() {
return State.STORYBOARD;
}
}
| true
|
f3c156e4e23792512485534973a88af87a8ee3ff
|
Java
|
chanthoeurntuon20/backup_codeb22
|
/backup-b22/lesson/src/practice1/Person.java
|
UTF-8
| 418
| 3.375
| 3
|
[] |
no_license
|
package practice1;
public class Person {
String name;
private int age ;
Person(){
}
Person(String name){
this.name = name;
}
Person(int age){
this.age = age;
}
Person(String name, int age){
this.name = name;
setAge(age);
getAge();
}
void setAge(int age) {
this.age = age;
}
int getAge() {
return age;
}
public String toString() {
return name + age;
}
}
| true
|
96ead4f639359f8172c8a5967f9f541d78c93f1f
|
Java
|
ShoyoNara/Revisao05
|
/src/revisao05/Revisao05.java
|
UTF-8
| 2,675
| 3.734375
| 4
|
[] |
no_license
|
package revisao05;
import javax.swing.JOptionPane;
/**
*
* @author samuc
*/
public class Revisao05 {
/**
* Uma empresa concederá um aumento de salário aos seus funcionários,
* variável de acordo com o cargo, conforme a tabela abaixo. Faça um
* programa que leia o salário e o código do cargo de um funcionário e
* calcule o seu novo salário. Se o cargo do funcionário não estiver na
* tabela, ele deverá, então, receber 15% de aumento. Mostre o salário
* antigo, o novo salário e a diferença entre ambos.
*/
public static void main(String[] args) {
double salario, codigocargo, novosalario, diferença, aumento;
salario = Double.parseDouble(JOptionPane.showInputDialog("Informe seu Salario atual: R$"));
codigocargo = Double.parseDouble(JOptionPane.showInputDialog("Informe seu código de funcionario: "));
if(codigocargo == 310){
aumento = salario * 0.05;
novosalario = salario + aumento;
diferença = novosalario - salario;
JOptionPane.showMessageDialog(null, "seu salario antigo é de: R$"+salario+"\n Você ganhara um aumento de: R$"+aumento+ "\n seu novo salario sera de: R$"+novosalario+
"\n E a diferença é de: R$"+diferença);
}
else if(codigocargo == 456){
aumento = salario * 0.075;
novosalario = salario + aumento;
diferença = novosalario - salario;
JOptionPane.showMessageDialog(null, "seu salario antigo é de: R$"+salario+"\n Você ganhara um aumento de: R$"+aumento+ "\n seu novo salario sera de: R$"+novosalario+
"\n E a diferença é de: R$"+diferença);
}
else if(codigocargo == 885){
aumento = salario * 0.1;
novosalario = salario + aumento;
diferença = novosalario - salario;
JOptionPane.showMessageDialog(null, "seu salario antigo é de: R$"+salario+"\n Você ganhara um aumento de: R$"+aumento+ "\n seu novo salario sera de: R$"+novosalario+
"\n E a diferença é de: R$"+diferença);
}
else{
aumento = salario * 0.15;
novosalario = salario + aumento;
diferença = novosalario - salario;
JOptionPane.showMessageDialog(null, "seu salario antigo é de: R$"+salario+"\n Você ganhara um aumento de: R$"+aumento+ "\n seu novo salario sera de: R$"+novosalario+
"\n E a diferença é de: R$"+diferença);
}
}
}
| true
|
f984bd19923772161e09f8cd062daf7027781914
|
Java
|
song121382/aizuji
|
/microservice-loverent-risk-intf-v1/src/main/java/org/gz/risk/common/request/RiskReq.java
|
UTF-8
| 606
| 1.875
| 2
|
[] |
no_license
|
package org.gz.risk.common.request;
import java.io.Serializable;
public class RiskReq implements Serializable {
private static final long serialVersionUID = 2708680782712837058L;
/*
* 订单号
*/
private String loanRecordId;
/**
* {@link CreditNode}
* 审批阶段,目前只支持1审和3审
*/
private String phase;
public String getLoanRecordId() {
return loanRecordId;
}
public void setLoanRecordId(String loanRecordId) {
this.loanRecordId = loanRecordId;
}
public String getPhase() {
return phase;
}
public void setPhase(String phase) {
this.phase = phase;
}
}
| true
|
e62ec2702edbee078f8e95638ef6bfdf4d195650
|
Java
|
jleifer/CodeLavender
|
/src/cLPackage/DeleteTopicServlet.java
|
UTF-8
| 1,432
| 2.359375
| 2
|
[] |
no_license
|
package cLPackage;
import cLPackage.dataStore.Topic;
import com.googlecode.objectify.ObjectifyService;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
/**
* Created by Yifang Cao on 4/21/2017.
*/
public class DeleteTopicServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String topicIdString =req.getParameter("topicId");
String userIdString =req.getParameter("userId");
String courseIdString =req.getParameter("courseId");
String moduleIdString =req.getParameter("moduleId");
Long topicId = Long.parseLong(topicIdString);
Topic topic = null;
List<Topic> topicList = ObjectifyService.ofy().load().type(Topic.class).list();
for (int i = 0 ; i < topicList.size(); i++){
if(topicList.get(i).id.longValue()==topicId.longValue()){
topic = topicList.get(i);
}
}
System.out.print("deleting "+topic.id);
//delete it
ObjectifyService.ofy().delete().entity(topic).now();
HttpSession session = req.getSession();
resp.sendRedirect("newModule?userId="+userIdString+"&courseId="+courseIdString+"&moduleId="+moduleIdString);
}
}
| true
|
d80b09b71611087538115a189600df6588d4e945
|
Java
|
fibgit/api_testing
|
/src/test/java/cityNamesTests.java
|
UTF-8
| 1,338
| 2.171875
| 2
|
[] |
no_license
|
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.equalTo;
import io.restassured.http.ContentType;
import org.junit.*;
public class cityNamesTests {
@Test
public void beverlyHillsTest(){
given().
when().
get("http://zippopotam.us/us/90210").
then().
assertThat().
body("places[0].'place name'",equalTo ("Beverly Hills")).
and().statusCode(200).
and().contentType(ContentType.JSON);
}
@Test
public void pretoriaTest(){
given().
when().
get("https://zippopotam.us/ZA/0002").
then().
assertThat().
body("places[0].'place name'",equalTo ("Pretoria")).
and().statusCode(200).
and().contentType(ContentType.JSON);
}
@Test
public void saintPierreAndMiquelonTest(){
given().
when().
get("http://api.zippopotam.us/PM/97500").
then().
assertThat().
body("places[0].'place name'",equalTo ("Miquelon")).
and().
body("places[1].'place name'",equalTo ("Saint-Pierre")).
and().statusCode(200).
and().contentType(ContentType.JSON);
}
}
| true
|
e8b4b92b95ca0b87efb2d97306c108c6bfbdb959
|
Java
|
ridwan3110/Apotek-Sederhana-Latihan
|
/Apotek/src/com/ridwan/dialog/Trx_Bytgl.java
|
UTF-8
| 5,534
| 1.851563
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ridwan.dialog;
import com.ridwan.DAO.TransaksiDao;
import com.ridwan.Interface.TransaksiInterface;
import com.ridwan.model.ReportTransaksi;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.swing.JRViewer;
/**
*
* @author ciwong
*/
public class Trx_Bytgl extends javax.swing.JDialog {
private TransaksiInterface transaksiDao = new TransaksiDao();
/**
* Creates new form Trx_Bytgl
*/
public Trx_Bytgl() {
initComponents();
setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tgl_awal = new com.toedter.calendar.JDateChooser();
tgl_akhir = new com.toedter.calendar.JDateChooser();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("TGL MULAI :");
jLabel2.setText("TGL AKHIR :");
jButton1.setText("CETAK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(tgl_awal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(36, 36, 36)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tgl_akhir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(161, 161, 161))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(tgl_akhir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tgl_awal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(jButton1)
.addContainerGap(65, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
TransaksiDao dao = new TransaksiDao();
List<ReportTransaksi> transaksi = dao.getTransaksi(tgl_awal.getDate(), tgl_akhir.getDate());
JasperPrint jasperPrint = JasperFillManager.fillReport(this.getClass().getClassLoader().getResourceAsStream("com/ridwan/Laporan/LaporanTransaksi.jasper")
, null, new JRBeanCollectionDataSource(transaksi));
JRViewer jrv = new JRViewer(jasperPrint);
TampilReport report = new TampilReport("Laporan Transaksi Berdasarkan Tanggal", jrv);
} catch (JRException ex) {
Logger.getLogger(Trx_Bytgl.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private com.toedter.calendar.JDateChooser tgl_akhir;
private com.toedter.calendar.JDateChooser tgl_awal;
// End of variables declaration//GEN-END:variables
}
| true
|
10f325438594bd9fc62d7b18593c09c2540e761a
|
Java
|
27786653/SSO
|
/ssoserver/src/org/jasig/cas/authentication/handler/UsernamePasswordCaptchaCredential.java
|
UTF-8
| 559
| 2.140625
| 2
|
[] |
no_license
|
package org.jasig.cas.authentication.handler;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.jasig.cas.authentication.UsernamePasswordCredential;
public class UsernamePasswordCaptchaCredential extends
UsernamePasswordCredential {
/**
*
*/
private static final long serialVersionUID = -864735145551932618L;
@NotNull
@Size(min=1,message = "required.captcha")
private String captcha;
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
}
| true
|
74a0e14fe62f9f062a4e89df68f8d822e81a3f02
|
Java
|
haroldoramirez/biblioteca
|
/app/validators/SiteFormData.java
|
UTF-8
| 1,725
| 2.84375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
package validators;
import models.Pais;
import org.apache.commons.validator.routines.UrlValidator;
import play.data.validation.ValidationError;
import java.util.ArrayList;
import java.util.List;
public class SiteFormData {
public String titulo = "";
public String url = "";
public String pais = "";
/** Necessario para instanciar o form */
public SiteFormData() {}
public SiteFormData(String titulo, String url, Pais pais) {
this.titulo = titulo;
this.url = url;
this.pais = pais.getNome();
}
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<>();
if (titulo == null || titulo.length() == 0) {
errors.add(new ValidationError("titulo", "Preencha o título"));
} else if (titulo.length() > 250) {
errors.add(new ValidationError("titulo", "Título com no máximo 250 caractéres"));
}
if (url == null || url.length() == 0) {
errors.add(new ValidationError("url", "Preencha a URL"));
} else if (url.length() > 400) {
errors.add(new ValidationError("url", "URL com no máximo 400 caractéres"));
}else {
String[] schemes = {"http","https","ftp"}; // DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (!urlValidator.isValid(url)) {
errors.add(new ValidationError("url", "Endereço do site é inválido"));
}
}
if (pais == null || pais.length() == 0) {
errors.add(new ValidationError("pais", "Selecione o país"));
}
return errors.isEmpty() ? null : errors;
}
}
| true
|
646cb576baba43c44409e757199494436e54f7f4
|
Java
|
995270418L/java_learn
|
/src/main/java/com/steve/ifeve/multipartline/chapter10/Taxi2.java
|
UTF-8
| 1,363
| 3.015625
| 3
|
[] |
no_license
|
package com.steve.ifeve.multipartline.chapter10;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import java.awt.*;
import java.util.HashSet;
import java.util.Set;
/**
* Created by liu on 6/4/17.
* 线程安全的Taxi and Dispatcher 类,是通过锁住关键部分来实现的,而不是整个方法
*/
@ThreadSafe
public class Taxi2 {
@GuardedBy("this") private Point location, destination;
@GuardedBy("this") private final Dispatcher2 dispatcher;
public Taxi2(Dispatcher2 dispatcher) {
this.dispatcher = dispatcher;
}
public synchronized Point getLocation(){
return location;
}
public void setLocation(Point location){
boolean reachedDestination;
synchronized (this) {
this.location = location;
reachedDestination = location.equals(destination);
}
if(reachedDestination){
dispatcher.notifyAvailable(this);
}
}
}
class Dispatcher2{
@GuardedBy("this") private final Set<Taxi2> taxis;
@GuardedBy("this") private final Set<Taxi2> availableTaxis;
Dispatcher2() {
this.taxis = new HashSet<>();
this.availableTaxis = new HashSet<>();
}
public synchronized void notifyAvailable(Taxi2 taxi){
availableTaxis.add(taxi);
}
// 地图上标记方法
}
| true
|
923f55ec8286113a994eb93a3fdf95f56a3f6365
|
Java
|
lishuangwei/AccountManager
|
/AccountManager/app/src/main/java/com/android/accountmanager/ui/account/SelectGenderFragment.java
|
UTF-8
| 3,700
| 2.21875
| 2
|
[] |
no_license
|
package com.android.accountmanager.ui.account;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.accountmanager.R;
public class SelectGenderFragment extends BaseDialogFragment implements RadioGroup.OnCheckedChangeListener {
private int mSelectWhich = -1;
private TextView mTextTitle;
private RadioGroup mRadiogroup;
private RadioButton mRadioMan, mRadioFeman;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) LayoutInflater.from(getActivity())
.inflate(R.layout.custon_setgender_layout, null);
mTextTitle = (TextView) layout.findViewById(R.id.text_title);
mRadiogroup = (RadioGroup) layout.findViewById(R.id.radio_group);
mRadiogroup.setOnCheckedChangeListener(this);
mRadioMan = (RadioButton) layout.findViewById(R.id.radio_man);
mRadioFeman = (RadioButton) layout.findViewById(R.id.radio_feman);
String[] choices = {getString(R.string.item_male), getString(R.string.item_female)};
Bundle args = getArguments();
String title = args.getString("title");
String summary = args.getString("summary");
setDefaultSummary(summary);
mTextTitle.setText(title);
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity(), R.style.BottomDialog);
builder.setCancelable(true);
builder.setView(layout);
return builder.create();
}
@Override
public void onStart() {
super.onStart();
Window window = getDialog().getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.gravity = Gravity.BOTTOM;
window.getDecorView().setPadding(0, 0, 0, 0);
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(params);
}
private void setDefaultSummary(String str) {
if (str.equals(getString(R.string.item_male))) {
mRadioMan.setChecked(true);
mSelectWhich = 0;
} else if (str.equals(getString(R.string.item_female))) {
mRadioFeman.setChecked(true);
mSelectWhich = 1;
} else {
mRadioFeman.setChecked(false);
mRadioMan.setChecked(false);
mSelectWhich = -1;
}
}
private void updateSex(int choice) {
if (!(getActivity() instanceof AccountContract.AccountView)) return;
final AccountContract.AccountView accountView = (AccountContract.AccountView) getActivity();
if (choice != mSelectWhich) {
accountView.onSexUpdate(choice);
}
}
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i) {
case R.id.radio_man:
Log.d("test", "onCheckedChanged: man");
updateSex(0);
if (null != getDialog() && getDialog().isShowing()) getDialog().dismiss();
break;
case R.id.radio_feman:
Log.d("test", "onCheckedChanged: feman");
updateSex(1);
if (null != getDialog() && getDialog().isShowing()) getDialog().dismiss();
break;
}
}
}
| true
|
3e8d992bf231c83935bc42b0eec854c4b433b64b
|
Java
|
akityty/module2-trien-khai-LinkedList-giong-java.util.LinkedList
|
/src/MyLinkedList.java
|
UTF-8
| 2,777
| 3.546875
| 4
|
[] |
no_license
|
public class MyLinkedList<E> {
public MyLinkedList() {
}
class Node {
private Node next;
private Object data;
private Node(Object data) {
this.data = data;
}
private Object getData() {
return this.data;
}
}
private Node head;
private int numNodes;
public MyLinkedList(Object data) {
head = new Node(data);
}
public void add(int index, E e) {
Node temp = head;
Node holder;
for (int i = 0; i < index - 1 && temp != null; i++) {
temp = temp.next;
}
holder = temp.next;
temp.next = new Node(e);
temp.next.next = holder;
numNodes++;
}
public void addFirst(Object e) {
Node temp = head;
head = new Node(e);
head.next = temp;
numNodes++;
}
public void addLast(Object e) {
Node temp = head;
for (int i = 0; temp.next != null; i++) {
temp = temp.next;
}
temp.next = new Node(e);
numNodes++;
}
public E remove(int index) {
Node pre = head;
Node temp = head;
for (int i = 0; i < index; i++) {
pre = temp;
temp = temp.next;
}
Object holder = temp.getData();
pre.next = temp.next;
temp = null;
numNodes--;
return (E) holder;
}
public boolean remove(E e) {
Node temp = head;
for (int i = 0; temp != null; i++) {
if (temp.getData() == e) {
remove(i);
return true;
}
temp = temp.next;
}
return false;
}
public E get(int index) {
Node temp = head;
for (int i = 0; i < index && temp != null; i++) {
temp = temp.next;
}
Object result = temp.getData();
return (E) result;
}
public E getFirst() {
return (E) head.getData();
}
public E getLast() {
return get(numNodes -1);
}
public void clear(){
Node temp = head;
for(int i =0; temp != null; i++){
temp = null;
temp = temp.next;
}
}
public void printf(){
Node temp = head;
for(int i = 0; temp != null; i++){
System.out.println(temp.getData());
temp=temp.next;
}
}
public int size(){
return numNodes;
}
public E clone(){
return (E) this;
}
public boolean contains(E e){
Node temp = head;
for( int i = 0; temp != null; i++){
if(temp.getData()==e){
return true;
}
temp =temp.next;
}
return false;
}
}
| true
|
9c966cdcb44f3c33912d2e96ad57c628e6c28cf1
|
Java
|
jiaoyunliang/nrsd
|
/src/main/java/com/rsd/service/impl/BnzPackageRecordServiceImpl.java
|
UTF-8
| 2,001
| 2.0625
| 2
|
[] |
no_license
|
package com.rsd.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rsd.domain.BnzPackageRecordModel;
import com.rsd.mapper.BnzPackageRecordMapper;
import com.rsd.service.BnzPackageRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author admin
* @ClassName hdx
* @Description 打包资质记录
* @Date 2019/7/1 16:53
* @Version 1.0
**/
@Service("bnzPackageRecord")
public class BnzPackageRecordServiceImpl implements BnzPackageRecordService {
@Autowired
private BnzPackageRecordMapper bnzPackageRecordMapper;
@Override
public void insert(BnzPackageRecordModel bnzPackageRecordModel) throws Exception {
bnzPackageRecordMapper.insert(bnzPackageRecordModel);
}
@Override
public Page<List<BnzPackageRecordModel>> findPackageRecordPage(BnzPackageRecordModel bnzPackageRecordModel) throws Exception {
Page<List<BnzPackageRecordModel>> page = PageHelper.startPage(bnzPackageRecordModel.getPageInput().getCurrent(), bnzPackageRecordModel.getPageInput().getSize());
List<BnzPackageRecordModel> bnzPackageRecordModelList = bnzPackageRecordMapper.findPackageRecordPage(bnzPackageRecordModel);
return page;
}
@Override
public List<BnzPackageRecordModel> selectInstitutionQuaPackState(BnzPackageRecordModel bnzPackageRecordModel) throws Exception {
List<BnzPackageRecordModel> bnzPackageRecordModelList = bnzPackageRecordMapper.selectInstitutionQuaPackState(bnzPackageRecordModel);
return bnzPackageRecordModelList;
}
@Override
public List<BnzPackageRecordModel> selectProductQuaQuaPackState(BnzPackageRecordModel bnzPackageRecordModel) throws Exception {
List<BnzPackageRecordModel> bnzPackageRecordModelList = bnzPackageRecordMapper.selectProductQuaQuaPackState(bnzPackageRecordModel);
return bnzPackageRecordModelList;
}
}
| true
|
a3bb2e55bb4164a82e94992bfff459146e91e36f
|
Java
|
bodar/shavenmaven
|
/test/com/googlecode/shavenmaven/config/SectionedPropertiesTest.java
|
UTF-8
| 1,158
| 2.59375
| 3
|
[] |
no_license
|
package com.googlecode.shavenmaven.config;
import com.googlecode.totallylazy.Option;
import org.junit.Test;
import java.util.Properties;
import static com.googlecode.shavenmaven.config.SectionedProperties.sectionedProperties;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class SectionedPropertiesTest {
@Test
public void returnsNoneIfSectionDoesNotExist() throws Exception {
assertThat(sectionedProperties("").section("impossible").isEmpty(), is(true));
}
@Test
public void returnsPropertiesForSection() throws Exception {
final Option<Properties> auth = sectionedProperties(
"[default]\n" +
"some.prop = some.value\n" +
"[auth]\n" +
"privates3.prefix = s3://solo-commons\n\n" +
"privates3.access_key=meerkatteam\n")
.section("auth");
assertThat(auth.get().getProperty("privates3.prefix"), is("s3://solo-commons"));
assertThat(auth.get().getProperty("privates3.access_key"), is("meerkatteam"));
assertThat(auth.get().size(), is(2));
}
}
| true
|
15b0127b61e24fc49d499dcdc4b8dc1896faa435
|
Java
|
NobleYd/JavaIntroduction
|
/main/src/java/文件.java
|
UTF-8
| 151
| 1.804688
| 2
|
[] |
no_license
|
import java.io.File;
public class 文件 {
public static void main(String[] args) {
File dir ;
// dir.listFiles(filter)
}
}
| true
|
976e1363a3c52466676352be80ddcb6e227f415d
|
Java
|
biligeny/pega-logviewer
|
/src/main/java/com/pega/gcs/logviewer/catalog/HotfixEntryDetailPanel.java
|
UTF-8
| 15,825
| 1.765625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* Copyright (c) 2017 Pegasystems Inc.
*
* Contributors:
* Manu Varghese
*******************************************************************************/
package com.pega.gcs.logviewer.catalog;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import com.pega.gcs.fringecommon.log4j2.Log4j2Helper;
import com.pega.gcs.fringecommon.utilities.FileUtilities;
import com.pega.gcs.logviewer.LogViewerUtil;
import com.pega.gcs.logviewer.catalog.model.HotfixColumn;
import com.pega.gcs.logviewer.catalog.model.HotfixEntry;
import com.pega.gcs.logviewer.catalog.model.HotfixStatus;
public class HotfixEntryDetailPanel extends JPanel {
private static final long serialVersionUID = -3435154792009295016L;
private static final Log4j2Helper LOG = new Log4j2Helper(HotfixEntryDetailPanel.class);
private HotfixEntry hotfixEntry;
private List<HotfixColumn> hotfixColumnList;
private JEditorPane hfixIdEditorPane;
private JEditorPane hfixDescEditorPane;
private JLabel stateLabel;
private JLabel statusLabel;
private JTextArea dependencyTextArea;
private HotfixRecordEntryTable hotfixRecordEntryTable;
public HotfixEntryDetailPanel(HotfixEntry hotfixEntry, List<HotfixColumn> hotfixColumnList) {
super();
this.hotfixEntry = hotfixEntry;
this.hotfixColumnList = hotfixColumnList;
setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.weightx = 1.0D;
gbc1.weighty = 0.0D;
gbc1.fill = GridBagConstraints.BOTH;
gbc1.anchor = GridBagConstraints.NORTHWEST;
gbc1.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1;
gbc2.gridy = 0;
gbc2.weightx = 1.0D;
gbc2.weighty = 0.0D;
gbc2.fill = GridBagConstraints.BOTH;
gbc2.anchor = GridBagConstraints.NORTHWEST;
gbc2.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 0;
gbc3.gridy = 1;
gbc3.weightx = 1.0D;
gbc3.weighty = 1.0D;
gbc3.fill = GridBagConstraints.BOTH;
gbc3.anchor = GridBagConstraints.NORTHWEST;
gbc3.insets = new Insets(2, 2, 2, 2);
gbc3.gridwidth = GridBagConstraints.REMAINDER;
JPanel detailsPanel = getDetailsPanel();
JScrollPane dependencyJScrollPane = getDependencyScrollPane();
JScrollPane tableJScrollPane = getTableScrollPane();
add(detailsPanel, gbc1);
add(dependencyJScrollPane, gbc2);
add(tableJScrollPane, gbc3);
populateData();
}
private JScrollPane getDependencyScrollPane() {
JTextArea dependencyTextArea = getDependencyTextArea();
JScrollPane dependencyScrollPane = new JScrollPane(dependencyTextArea);
return dependencyScrollPane;
}
private JScrollPane getTableScrollPane() {
HotfixRecordEntryTable hotfixRecordEntryTable = getHotfixRecordEntryTable();
JScrollPane tableScrollPane = new JScrollPane(hotfixRecordEntryTable);
return tableScrollPane;
}
private JEditorPane getHfixIdEditorPane() {
if (hfixIdEditorPane == null) {
hfixIdEditorPane = new JEditorPane();
hfixIdEditorPane.setSize(Integer.MAX_VALUE, 80);
hfixIdEditorPane.setEditable(false);
hfixIdEditorPane.setContentType("text/html");
hfixIdEditorPane.setOpaque(false);
hfixIdEditorPane.setBackground(this.getBackground());
StyleSheet styleSheet = FileUtilities.getStyleSheet(this.getClass(), "styles.css");
if (styleSheet != null) {
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
StyleSheet htmlStyleSheet = htmlEditorKit.getStyleSheet();
htmlStyleSheet.addStyleSheet(styleSheet);
hfixIdEditorPane.setEditorKitForContentType("text/html", htmlEditorKit);
}
hfixIdEditorPane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
if (hyperlinkEvent.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(hyperlinkEvent.getURL().toURI());
} catch (Exception ex) {
LOG.error("Error in invoking browser url: " + hyperlinkEvent.getURL(), ex);
}
}
}
}
});
}
return hfixIdEditorPane;
}
private JEditorPane getHfixDescEditorPane() {
if (hfixDescEditorPane == null) {
hfixDescEditorPane = new JEditorPane();
hfixDescEditorPane.setEditable(false);
hfixDescEditorPane.setContentType("text/html");
hfixDescEditorPane.setOpaque(false);
hfixDescEditorPane.setBackground(this.getBackground());
StyleSheet styleSheet = FileUtilities.getStyleSheet(this.getClass(), "styles.css");
if (styleSheet != null) {
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
StyleSheet htmlStyleSheet = htmlEditorKit.getStyleSheet();
htmlStyleSheet.addStyleSheet(styleSheet);
hfixDescEditorPane.setEditorKitForContentType("text/html", htmlEditorKit);
}
hfixDescEditorPane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
if (hyperlinkEvent.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(hyperlinkEvent.getURL().toURI());
} catch (Exception ex) {
LOG.error("Error in invoking browser url: " + hyperlinkEvent.getURL(), ex);
}
}
}
}
});
}
return hfixDescEditorPane;
}
private JLabel getStateLabel() {
if (stateLabel == null) {
stateLabel = new JLabel();
}
return stateLabel;
}
private JLabel getStatusLabel() {
if (statusLabel == null) {
statusLabel = new JLabel();
}
return statusLabel;
}
private JTextArea getDependencyTextArea() {
if (dependencyTextArea == null) {
dependencyTextArea = new JTextArea();
dependencyTextArea.setRows(5);
dependencyTextArea.setEditable(false);
dependencyTextArea.setBackground(null);
dependencyTextArea.setBorder(null);
dependencyTextArea.setCursor(new Cursor(Cursor.TEXT_CURSOR));
}
return dependencyTextArea;
}
private HotfixRecordEntryTable getHotfixRecordEntryTable() {
if (hotfixRecordEntryTable == null) {
HotfixRecordEntryTableModel hotfixRecordEntryTableModel = new HotfixRecordEntryTableModel(hotfixEntry,
hotfixColumnList);
hotfixRecordEntryTable = new HotfixRecordEntryTable(hotfixRecordEntryTableModel);
}
return hotfixRecordEntryTable;
}
private JPanel getDetailsPanel() {
JPanel detailsPanel = new JPanel();
detailsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.weightx = 0.0D;
gbc1.weighty = 1.0D;
gbc1.fill = GridBagConstraints.BOTH;
gbc1.anchor = GridBagConstraints.NORTHWEST;
gbc1.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1;
gbc2.gridy = 0;
gbc2.weightx = 1.0D;
gbc2.weighty = 1.0D;
gbc2.fill = GridBagConstraints.BOTH;
gbc2.anchor = GridBagConstraints.NORTHWEST;
gbc2.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 0;
gbc3.gridy = 1;
gbc3.weightx = 0.0D;
gbc3.weighty = 1.0D;
gbc3.fill = GridBagConstraints.BOTH;
gbc3.anchor = GridBagConstraints.NORTHWEST;
gbc3.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc4 = new GridBagConstraints();
gbc4.gridx = 1;
gbc4.gridy = 1;
gbc4.weightx = 1.0D;
gbc4.weighty = 1.0D;
gbc4.fill = GridBagConstraints.BOTH;
gbc4.anchor = GridBagConstraints.NORTHWEST;
gbc4.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc5 = new GridBagConstraints();
gbc5.gridx = 0;
gbc5.gridy = 2;
gbc5.weightx = 0.0D;
gbc5.weighty = 1.0D;
gbc5.fill = GridBagConstraints.BOTH;
gbc5.anchor = GridBagConstraints.NORTHWEST;
gbc5.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc6 = new GridBagConstraints();
gbc6.gridx = 1;
gbc6.gridy = 2;
gbc6.weightx = 1.0D;
gbc6.weighty = 1.0D;
gbc6.fill = GridBagConstraints.BOTH;
gbc6.anchor = GridBagConstraints.NORTHWEST;
gbc6.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc7 = new GridBagConstraints();
gbc7.gridx = 0;
gbc7.gridy = 3;
gbc7.weightx = 0.0D;
gbc7.weighty = 1.0D;
gbc7.fill = GridBagConstraints.BOTH;
gbc7.anchor = GridBagConstraints.NORTHWEST;
gbc7.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc8 = new GridBagConstraints();
gbc8.gridx = 1;
gbc8.gridy = 3;
gbc8.weightx = 1.0D;
gbc8.weighty = 1.0D;
gbc8.fill = GridBagConstraints.BOTH;
gbc8.anchor = GridBagConstraints.NORTHWEST;
gbc8.insets = new Insets(2, 2, 2, 2);
Font existingFont = getFont();
String existingFontName = existingFont.getName();
int existFontSize = existingFont.getSize();
Font newFont = new Font(existingFontName, Font.BOLD, existFontSize);
JLabel idNameLabel = new JLabel("Hotfix ID: ");
JLabel descriptionNameLabel = new JLabel("Hotfix Description: ");
JLabel stateNameLabel = new JLabel("Hotfix State: ");
JLabel statusNameLabel = new JLabel("Hotfix Status: ");
idNameLabel.setFont(newFont);
descriptionNameLabel.setFont(newFont);
stateNameLabel.setFont(newFont);
statusNameLabel.setFont(newFont);
JEditorPane hfixIdEditorPane = getHfixIdEditorPane();
JEditorPane hfixDescEditorPane = getHfixDescEditorPane();
JLabel stateLabel = getStateLabel();
JLabel statusLabel = getStatusLabel();
detailsPanel.add(idNameLabel, gbc1);
detailsPanel.add(hfixIdEditorPane, gbc2);
detailsPanel.add(descriptionNameLabel, gbc3);
detailsPanel.add(hfixDescEditorPane, gbc4);
detailsPanel.add(stateNameLabel, gbc5);
detailsPanel.add(stateLabel, gbc6);
detailsPanel.add(statusNameLabel, gbc7);
detailsPanel.add(statusLabel, gbc8);
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
return detailsPanel;
}
private void populateData() {
JEditorPane hfixIdEditorPane = getHfixIdEditorPane();
JEditorPane hfixDescEditorPane = getHfixDescEditorPane();
JLabel stateLabel = getStateLabel();
JLabel statusLabel = getStatusLabel();
JTextArea dependencyTextArea = getDependencyTextArea();
String hotfixId;
String description;
String data;
HotfixColumn hotfixColumn;
int columnIndex;
CatalogManagerWrapper catalogManagerWrapper = CatalogManagerWrapper.getInstance();
hotfixId = hotfixEntry.getHotfixId();
data = catalogManagerWrapper.getWorkItemHyperlinkText(hotfixId);
hfixIdEditorPane.setText(data);
hotfixColumn = HotfixColumn.HOTFIX_DESCRIPTION;
columnIndex = hotfixColumnList.indexOf(hotfixColumn);
description = hotfixEntry.getHotfixEntryData(hotfixColumn, columnIndex);
data = catalogManagerWrapper.getWorkDescHyperlinkText(description);
hfixDescEditorPane.setText(data);
hotfixColumn = HotfixColumn.PXHOTFIXSTATE;
columnIndex = hotfixColumnList.indexOf(hotfixColumn);
data = hotfixEntry.getHotfixEntryData(hotfixColumn, columnIndex);
stateLabel.setText(data);
// catalog doesnt have status
HotfixStatus hotfixStatus = hotfixEntry.getHotfixStatus();
if (hotfixStatus != null) {
data = hotfixStatus.getDisplayString();
} else {
data = "";
}
statusLabel.setText(data);
StringBuilder sb = new StringBuilder();
TreeSet<HotfixEntry> totalBackwardHotfixEntrySet = new TreeSet<>();
LogViewerUtil.recursiveEvaluateBackwardHotfixEntrySet(hotfixEntry, totalBackwardHotfixEntrySet);
for (HotfixEntry hotfixEntry : totalBackwardHotfixEntrySet) {
HotfixColumn hfixColumn = HotfixColumn.HOTFIX_DESCRIPTION;
columnIndex = hotfixColumnList.indexOf(hfixColumn);
String hfixDesc = hotfixEntry.getHotfixEntryData(hotfixColumn, columnIndex);
sb.append(hotfixEntry.getHotfixId());
sb.append(": ");
sb.append(hfixDesc);
sb.append("\n");
}
sb.append("\n");
sb.append(hotfixId);
sb.append(": ");
sb.append(description);
sb.append("\n\n");
Set<HotfixEntry> forwardHotfixEntryList = hotfixEntry.getForwardHotfixEntrySet();
for (HotfixEntry hotfixEntry : forwardHotfixEntryList) {
HotfixColumn hfixColumn = HotfixColumn.HOTFIX_DESCRIPTION;
columnIndex = hotfixColumnList.indexOf(hfixColumn);
String hfixDesc = hotfixEntry.getHotfixEntryData(hotfixColumn, columnIndex);
sb.append(hotfixEntry.getHotfixId());
sb.append(": ");
sb.append(hfixDesc);
sb.append("\n");
}
dependencyTextArea.setText(sb.toString());
}
}
| true
|
d3137a8163a9c8225c742862b6cb940f837814ac
|
Java
|
brunomendola/spring-jpa-composite-pk-with-relationships
|
/src/main/java/net/brunomendola/demo/spring/jpa/compositepkwithrelationships/model/ProfileAction.java
|
UTF-8
| 987
| 2.109375
| 2
|
[] |
no_license
|
package net.brunomendola.demo.spring.jpa.compositepkwithrelationships.model;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(of = {"profile", "action"}, callSuper = false)
@ToString(of = {"profile", "action"})
@Entity
@IdClass(ProfileActionPK.class)
@Table(name = "S3TSG_SPR_SAT_SAZ")
public class ProfileAction implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "SPR_SAT_SAZ_SPR_COD", referencedColumnName = "SPR_COD", nullable = false)
private Profile profile;
@Id
@ManyToOne
@JoinColumns({@JoinColumn(name = "SPR_SAT_SAZ_SAT_COD", referencedColumnName = "SAT_SAZ_SAT_COD", nullable = false), @JoinColumn(name = "SPR_SAT_SAZ_SAZ_SUBID", referencedColumnName = "SAT_SAZ_SUBID", nullable = false)})
private ActivityAction action;
public ProfileAction(Profile profile, ActivityAction action) {
this.profile = profile;
this.action = action;
}
}
| true
|
728d9dd31dff07a7641dac4927db2ed67956eb62
|
Java
|
xxStevensxx/Soc_projet6
|
/PayMyBudy/src/test/java/com/pay/my/budy/controller/MainControllerTest.java
|
UTF-8
| 1,544
| 1.6875
| 2
|
[] |
no_license
|
package com.pay.my.budy.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class MainControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void homeControllerTest() throws Exception {
//WHEN
//GIVEN
//THEN
mockMvc.perform(get("/home")).andExpect(status().isOk());
}
@Test
public void loginControllerTest() throws Exception {
//WHEN
//GIVEN
//THEN
mockMvc.perform(get("/login")).andExpect(status().isOk());
}
@Test
public void submitFormLoginTest() throws Exception {
//WHEN
//GIVEN
//THEN
mockMvc.perform(get("/login")).andExpect(status().isOk());
}
@Test
public void contactControllerTest() throws Exception {
//WHEN
//GIVEN
//THEN
mockMvc.perform(get("/contact")).andExpect(status().isOk());
}
@Test
public void transfertControllerTest() throws Exception {
//WHEN
//GIVEN
//THEN
mockMvc.perform(get("/transfert")).andExpect(status().isOk());
}
}
| true
|
3e6dac5cfe1b9c3ecfae62dcd6f42e37b2e845a8
|
Java
|
wang-ke01/Java01_List_Set_Map
|
/day16_JDK5新特性/src/cn/itcast03/ListDemo.java
|
GB18030
| 897
| 4.09375
| 4
|
[] |
no_license
|
package cn.itcast03;
import java.util.ArrayList;
import java.util.Random;
public class ListDemo {
public static void main(String[] args) {
/*
* ϵǶױ
* ȡ101-20֮Ҫظ
*
* A:Ķ
* B:һ洢ļ
* C:һͳƱ0ʼ
* D:жͳƱǷС10
* ǣȲһǷڣھӣCount++ھͲ
*
* E:
* */
Random rd = new Random();
ArrayList<Integer> al =new ArrayList<Integer>();
int count=0;
while(count<10){
int num = rd.nextInt(20)+1;
if(!al.contains(num)){
al.add(num);
count++;
}
}
//
for(Integer x:al){
System.out.println(x);
}
}
}
| true
|
f6181fa5ade5519658312a82e0ede5a2e31936ba
|
Java
|
zsmome/Teacher
|
/day09_homework_beating3_baseadapter/src/main/java/com/zsmome/day09_homework_beating3_baseadapter/util/JSONParseUtil.java
|
UTF-8
| 2,303
| 2.765625
| 3
|
[] |
no_license
|
package com.zsmome.day09_homework_beating3_baseadapter.util;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 解析JSON
* Created by Administrator on 2017/3/26.
*/
public class JSONParseUtil {
/**
* 定一接口
*/
public interface OnJSONParseListener {
void OnJSONParseComplete(String json);
}
//定义一个接口成员变量
private OnJSONParseListener mListener;
/**
* 解析网络上的JSON
*/
public void parseJSON(String url, OnJSONParseListener listener) {
this.mListener = listener;
//开始解析
new ParseJSONTask().execute(url);
}
/**
* 解析JSON
*/
class ParseJSONTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
//输入流
InputStream is = null;
try {
//建立连接
URL url = new URL(params[0]);
//打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//获得输入流
is = conn.getInputStream();
//存放json字符串
StringBuilder sb = new StringBuilder();
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1) {
String s = new String(buffer, 0, len);
sb.append(s);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 执行任务之后
*/
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null) {
mListener.OnJSONParseComplete(s);
Log.i("JsonStr", s);
}
}
}
}
| true
|
76f782a2fcd432d9e7a27ca22017bc7c05571e7c
|
Java
|
danmoct/Gas-Pump-Simulator
|
/SRC/Strategy_Classes/Ready_M1.java
|
UTF-8
| 193
| 2.1875
| 2
|
[] |
no_license
|
package Strategy_Classes;
//strategy pattern
public class Ready_M1 extends Ready_Msg {
public void ready_msg()
{
System.out.println("\nREADY TO PUMP. \n");
}
}
| true
|
acc975628a7b484396f78403783bd9b6a1895e30
|
Java
|
justfordream/my-2
|
/CMUPayWebPay/src/main/java/com/huateng/bean/CmuPayResponse.java
|
UTF-8
| 3,601
| 2.28125
| 2
|
[] |
no_license
|
package com.huateng.bean;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* 省公司网厅->中国移动统一支付系统的“支付”交易<br>
* 支付响应
*
* @author Gary
*/
public class CmuPayResponse {
/**
* 商户标识
*/
@JsonProperty
private String MerID;
/**
* 订单标识
*/
@JsonProperty
private String OrderID;
/**
* 支付结果,标识支付是否成功以及失败的原因
*/
@JsonProperty
private String RspCode;
/**
* 对于支付结果的描述信息
*/
@JsonProperty
private String RspInfo;
/**
* 省公司自定义,当统一支付系统通知支付结果时,携带此变量,省公司可以用此变量维护session等
*/
@JsonProperty
private String MerVAR;
/**
* 交易日期时间
*/
@JsonProperty
private String OrderTime;
/**
* 订单金额,单位为“分”
*/
@JsonProperty
private String Payed;
/**
* 币种,默认人民币
*/
@JsonProperty
private String CurType;
/**
* UPAY10002 支付请求将用户重定向回中国省公司移动网上营业厅时填写
*/
@JsonProperty
private String MCODE;
/**
* 银行签名
*/
@JsonProperty
private String Sig;
@JsonIgnore
public String getMerID() {
return MerID;
}
@JsonIgnore
public void setMerID(String merID) {
MerID = merID;
}
@JsonIgnore
public String getOrderID() {
return OrderID;
}
@JsonIgnore
public void setOrderID(String orderID) {
OrderID = orderID;
}
@JsonIgnore
public String getRspCode() {
return RspCode;
}
@JsonIgnore
public void setRspCode(String rspCode) {
RspCode = rspCode;
}
@JsonIgnore
public String getRspInfo() {
return RspInfo;
}
@JsonIgnore
public void setRspInfo(String rspInfo) {
RspInfo = rspInfo;
}
@JsonIgnore
public String getMerVAR() {
return MerVAR;
}
@JsonIgnore
public void setMerVAR(String merVAR) {
MerVAR = merVAR;
}
@JsonIgnore
public String getOrderTime() {
return OrderTime;
}
@JsonIgnore
public void setOrderTime(String orderTime) {
OrderTime = orderTime;
}
@JsonIgnore
public String getPayed() {
return Payed;
}
@JsonIgnore
public void setPayed(String payed) {
Payed = payed;
}
@JsonIgnore
public String getCurType() {
return CurType;
}
@JsonIgnore
public void setCurType(String curType) {
CurType = curType;
}
@JsonIgnore
public String getMCODE() {
return MCODE;
}
@JsonIgnore
public void setMCODE(String mCODE) {
MCODE = mCODE;
}
@JsonIgnore
public String getSig() {
return Sig;
}
@JsonIgnore
public void setSig(String sig) {
Sig = sig;
}
/**
* 获取签名字符串
*
* @return
*/
public String assemlyPlainText() {
StringBuffer sb = new StringBuffer();
if (StringUtils.isNotBlank(this.MerID)) {
sb.append("MERID=" + this.MerID + "|");
}
if (StringUtils.isNotBlank(this.OrderID)) {
sb.append("ORDERID=" + this.OrderID + "|");
}
if (StringUtils.isNotBlank(this.RspCode)) {
sb.append("RSPCODE=" + this.RspCode + "|");
}
if (StringUtils.isNotBlank(this.MerVAR)) {
sb.append("MERVAR=" + this.MerVAR + "|");
}
if (StringUtils.isNotBlank(this.OrderTime)) {
sb.append("ORDERTIME=" + this.OrderTime + "|");
}
if (StringUtils.isNotBlank(this.Payed)) {
sb.append("PAYED=" + this.Payed + "|");
}
if (StringUtils.isNotBlank(this.CurType)) {
sb.append("CURTYPE=" + this.CurType + "|");
}
if (StringUtils.isNotBlank(this.MCODE)) {
sb.append("MCODE=" + this.MCODE + "|");
}
return sb.toString();
}
}
| true
|
eeaf45dd0f8524aa5040243c9a215011e3924dd6
|
Java
|
sofiaasseggaf/EPortfolio
|
/app/src/main/java/com/project/eportfolio/model/matapelajaran/MsMatapelajaran.java
|
UTF-8
| 4,833
| 1.953125
| 2
|
[] |
no_license
|
package com.project.eportfolio.model.matapelajaran;
import java.io.Serializable;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MsMatapelajaran implements Serializable, Parcelable
{
@SerializedName("id")
@Expose
private String id;
@SerializedName("sekolahid")
@Expose
private String sekolahid;
@SerializedName("guruid")
@Expose
private String guruid;
@SerializedName("name")
@Expose
private String name;
@SerializedName("createdby")
@Expose
private Object createdby;
@SerializedName("createddate")
@Expose
private String createddate;
@SerializedName("updateby")
@Expose
private Object updateby;
@SerializedName("updatedate")
@Expose
private Object updatedate;
@SerializedName("isactive")
@Expose
private String isactive;
public final static Creator<MsMatapelajaran> CREATOR = new Creator<MsMatapelajaran>() {
@SuppressWarnings({
"unchecked"
})
public MsMatapelajaran createFromParcel(Parcel in) {
return new MsMatapelajaran(in);
}
public MsMatapelajaran[] newArray(int size) {
return (new MsMatapelajaran[size]);
}
}
;
private final static long serialVersionUID = 1256472097940198845L;
protected MsMatapelajaran(Parcel in) {
this.id = ((String) in.readValue((String.class.getClassLoader())));
this.sekolahid = ((String) in.readValue((String.class.getClassLoader())));
this.guruid = ((String) in.readValue((String.class.getClassLoader())));
this.name = ((String) in.readValue((String.class.getClassLoader())));
this.createdby = ((Object) in.readValue((Object.class.getClassLoader())));
this.createddate = ((String) in.readValue((String.class.getClassLoader())));
this.updateby = ((Object) in.readValue((Object.class.getClassLoader())));
this.updatedate = ((Object) in.readValue((Object.class.getClassLoader())));
this.isactive = ((String) in.readValue((String.class.getClassLoader())));
}
/**
* No args constructor for use in serialization
*
*/
public MsMatapelajaran() {
}
/**
*
* @param sekolahid
* @param updatedate
* @param guruid
* @param createdby
* @param createddate
* @param updateby
* @param isactive
* @param name
* @param id
*/
public MsMatapelajaran(String id, String sekolahid, String guruid, String name, Object createdby, String createddate, Object updateby, Object updatedate, String isactive) {
super();
this.id = id;
this.sekolahid = sekolahid;
this.guruid = guruid;
this.name = name;
this.createdby = createdby;
this.createddate = createddate;
this.updateby = updateby;
this.updatedate = updatedate;
this.isactive = isactive;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSekolahid() {
return sekolahid;
}
public void setSekolahid(String sekolahid) {
this.sekolahid = sekolahid;
}
public String getGuruid() {
return guruid;
}
public void setGuruid(String guruid) {
this.guruid = guruid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getCreatedby() {
return createdby;
}
public void setCreatedby(Object createdby) {
this.createdby = createdby;
}
public String getCreateddate() {
return createddate;
}
public void setCreateddate(String createddate) {
this.createddate = createddate;
}
public Object getUpdateby() {
return updateby;
}
public void setUpdateby(Object updateby) {
this.updateby = updateby;
}
public Object getUpdatedate() {
return updatedate;
}
public void setUpdatedate(Object updatedate) {
this.updatedate = updatedate;
}
public String getIsactive() {
return isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(id);
dest.writeValue(sekolahid);
dest.writeValue(guruid);
dest.writeValue(name);
dest.writeValue(createdby);
dest.writeValue(createddate);
dest.writeValue(updateby);
dest.writeValue(updatedate);
dest.writeValue(isactive);
}
public int describeContents() {
return 0;
}
}
| true
|
1d5f34eabef674643e68b9312993ec0e7751ffc2
|
Java
|
GabeOchieng/ggnn.tensorflow
|
/data/libgdx/TiledMapPacker_printUsage.java
|
UTF-8
| 1,074
| 2.8125
| 3
|
[] |
no_license
|
private static void printUsage() {
System.out.println("Usage: INPUTDIR [OUTPUTDIR] [--strip-unused] [--combine-tilesets] [-v]");
System.out.println("Processes a directory of Tiled .tmx maps. Unable to process maps with XML");
System.out.println("tile layer format.");
System.out.println(" --strip-unused omits all tiles that are not used. Speeds up");
System.out.println(" the processing. Smaller tilesets.");
System.out.println(" --combine-tilesets instead of creating a tileset for each map,");
System.out.println(" this combines the tilesets into some kind");
System.out.println(" of monster tileset. Has problems with tileset");
System.out.println(" location. Has problems with nested folders.");
System.out.println(" Not recommended.");
System.out.println(" -v outputs which tiles are stripped and included");
System.out.println();
}
| true
|
b9fec784c33f90b19271ed4972f610724c9963cb
|
Java
|
brianwalker96/battleJava
|
/src/Ship.java
|
UTF-8
| 199
| 1.664063
| 2
|
[] |
no_license
|
public class Ship {
int row;
int col;
int direction;
/* 0
3 1
2
*/
int size;
public Ship (){
}
}
| true
|
ba9d3e4bf1464dc17067c0a12bd58c6b23f9c3f5
|
Java
|
rezaact/my-cool-apps
|
/src/main/java/id/co/hans/sample/server/utility/SessionHelper.java
|
UTF-8
| 2,737
| 2.453125
| 2
|
[] |
no_license
|
package id.co.hans.sample.server.utility;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import id.co.hans.sample.shared.model.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class SessionHelper {
public static String session_name_filepath="filepath";
public static String session_name_filename="filename";
public static SessionHelper getInstance() {
return new SessionHelper();
}
public HttpSession getHttpSession() {
return getHttpServletRequest().getSession();
}
public HttpServletRequest getHttpServletRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attributes.getRequest();
}
public User getUserFromSession() {
User user = (User) getHttpSession().getAttribute("user");
if (user != null) {
return user;
}
return null;
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public static String MD5(String text)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
public boolean generateFileDownloadNE(List<String> list, String filepath, String filename){
String status = "";
try{
FileWriter outFile = new FileWriter(filepath + "/" + filename);
PrintWriter out = new PrintWriter(outFile);
for (String data : list){
out.println(data);
}
out.flush();
out.close();
}catch (Exception ex) {
return false;
}
return true;
}
}
| true
|
337e9e4410b39406ca3755b10fa7388892426f27
|
Java
|
AdemTEN/Java_Exercises
|
/Java_EXercises/src/Exercise_01/Exercise_01_12.java
|
UTF-8
| 542
| 3.921875
| 4
|
[] |
no_license
|
/*
(Average speed in kilometers) Assume a runner runs 24 miles in 1 hour, 40 minutes,
and 35 seconds. Write a program that displays the average speed in kilometers per
hour. (Note that 1 mile is 1.6 kilometers.)
*/
package Exercise_01;
public class Exercise_01_12 {
public static void main(String[] args) {
double kmOfRunner = 24 * 1.6;
double secondOfRunner = (100 * 60) + 35;
double averageRunner = (kmOfRunner * 3600.0) / secondOfRunner;
System.out.println("The average of Runner is: " + averageRunner);
}
}
| true
|
3b0beb143358eaa0380281cf69ce0279972d572b
|
Java
|
AlexMcG/SapientTraining
|
/JavaProject/src/mainpack/Average.java
|
UTF-8
| 317
| 3.375
| 3
|
[] |
no_license
|
package mainpack;
//Average an array of values.
class Average {
public static void main(String args[]) {
double[] nums = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for (i = 0; i < nums.length; i++) {
result = result + nums[i];
}
System.out.println("Average is " + result / nums.length);
}
}
| true
|
6352510806a7a68359a7fccdefaefaae05c8a751
|
Java
|
ayceclglgl/realm
|
/src/test/java/com/realm/controller/RealmControllerTest.java
|
UTF-8
| 4,740
| 2.1875
| 2
|
[] |
no_license
|
package com.realm.controller;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.realm.converters.UserRealmToRealmResponse;
import com.realm.exceptions.RealmNotFound;
import com.realm.model.UserRealm;
import com.realm.service.RealmService;
public class RealmControllerTest {
RealmController controller;
MockMvc mockMvc;
@Mock
RealmService service;
@Mock
UserRealmToRealmResponse userRealmToRealmResponse;
UserRealm userRealm;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
controller = new RealmController(service, userRealmToRealmResponse);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new ExceptionHandlerController())
.build();
userRealm = new UserRealm(1L, "Name", "Description", "");
}
@Test
public void createRealmTestJSON() throws Exception {
mockMvc.perform(post("/service/user/realm")
.contentType(MediaType.APPLICATION_JSON)
.content("{ \"name\": \"name\", \"description\": \"description\" } "))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated());
verify(service).createRealm("name", "description");
verify(userRealmToRealmResponse).convert(any());
}
@Test
public void createRealmTestJSONInvalidRealmName() throws Exception {
mockMvc.perform(post("/service/user/realm")
.contentType(MediaType.APPLICATION_JSON)
.content("{ \"name\": \"\", \"description\": \"description\" } "))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
verify(service, never()).createRealm("", "");
verify(userRealmToRealmResponse, never()).convert(any());
}
@Test
public void createRealmTestXML() throws Exception {
mockMvc.perform(post("/service/user/realm")
.contentType(MediaType.APPLICATION_XML)
.content("<realm name = \"name\"> <description>description</description> </realm>"))
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(status().isCreated());
verify(service).createRealm("name", "description");
verify(userRealmToRealmResponse).convert(any());
}
@Test
public void createRealmTestXMLInvalidRealmName() throws Exception {
mockMvc.perform(post("/service/user/realm")
.contentType(MediaType.APPLICATION_XML)
.content("<realm name = \"\"> <description>description</description> </realm>"))
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(status().isBadRequest());
verify(service, never()).createRealm("", "");
verify(userRealmToRealmResponse, never()).convert(any());
}
@Test
public void getRealmTestJSON() throws Exception {
when(service.getById(anyLong())).thenReturn(userRealm);
mockMvc.perform(get("/service/user/realm/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
verify(service).getById(Long.valueOf(1));
verify(userRealmToRealmResponse).convert(any());
}
@Test
public void getRealmTestJSONInvalidArgument() throws Exception {
mockMvc.perform(get("/service/user/realm/1a")
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isBadRequest());
verify(service, never()).getById(anyLong());
verify(userRealmToRealmResponse, never()).convert(any());
}
@Test
public void getRealmTestXML() throws Exception {
when(service.getById(anyLong())).thenReturn(userRealm);
mockMvc.perform(get("/service/user/realm/1")
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk());
verify(service).getById(Long.valueOf(1));
verify(userRealmToRealmResponse).convert(any());
}
@Test
public void getRealmTestXMLInvalidArgument() throws Exception {
mockMvc.perform(get("/service/user/realm/1a")
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isBadRequest());
verify(service, never()).getById(anyLong());
verify(userRealmToRealmResponse, never()).convert(any());
}
}
| true
|
b26844d0399589cf1eaecc07cebd44c6c491e2ef
|
Java
|
pablopes/projetopais
|
/src/main/java/br/com/pablopes/searchpais/repository/PaisRepository.java
|
UTF-8
| 334
| 1.546875
| 2
|
[] |
no_license
|
package br.com.pablopes.searchpais.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import br.com.pablopes.searchpais.model.Pais;
public interface PaisRepository extends JpaRepository<Pais, Integer> , JpaSpecificationExecutor<Pais>{}
| true
|
db80b80ae499bca543f9e66a80994352bb1477e3
|
Java
|
cescott/AppleCatcher
|
/AppleCatcher/core/src/com/andersonescott/objects/Entity.java
|
UTF-8
| 1,189
| 3.15625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.andersonescott.objects;
import com.badlogic.gdx.graphics.Texture;
public abstract class Entity {
protected double[] coords = new double[2];
protected double[] velocity = new double[2];
protected double[] acceleration = new double[2];
protected Texture image;
public Entity (double[] tempCoords){
coords = tempCoords;
}
public void update(float delta){
velocity[0] = velocity[0]+(acceleration[0]*delta);
velocity[1] = velocity[1]+(acceleration[1]*delta);
coords[0] += velocity[0]*delta;
coords[1] += velocity[1]*delta;
}
public double x() {
return coords[0];
}
public double y(){
return coords[1];
}
public void setCoords(double[] coords) {
this.coords = coords;
}
public double[] getVelocity() {
return velocity;
}
public void setVelocity(double[] velocity) {
this.velocity = velocity;
}
public double[] getAcceleration() {
return acceleration;
}
public void setAcceleration(double[] accel) {
acceleration = accel;
}
public Texture getImage(){
return image;
}
}
| true
|
fffd3b028a5535c9854fcb6d60b407757cf42666
|
Java
|
githubwangxingxin/eclipesuanfa
|
/suanshu/src/com/wxx/bigdecimaltest/TestHa.java
|
UTF-8
| 273
| 2.03125
| 2
|
[] |
no_license
|
package com.wxx.bigdecimaltest;
import java.util.Random;
public class TestHa {
public static void main(String[] args) {
Random random=new Random();
System.out.println("aaaaaaaasa");
System.out.println("random.nextInt(1000)"+random.nextInt(10000));
}
}
| true
|
1023ffb740ce91ff571209f096f981ecb904152d
|
Java
|
filsky0599/Progetto-H21
|
/server/src/main/java/it/skinjobs/api/ComponentAPI.java
|
UTF-8
| 6,512
| 2.3125
| 2
|
[] |
no_license
|
package it.skinjobs.api;
import it.skinjobs.model.Component;
import it.skinjobs.model.ComponentFamily;
import it.skinjobs.dto.ComponentDTO;
import it.skinjobs.repository.ComponentFamilies;
import it.skinjobs.repository.Components;
import it.skinjobs.utils.Callable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Jessica Vecchia
*
* The REST controller transforms all the methods into web services and the classes into JSON object. The methods define
* calls to URLs via HTTP request(POST, GET, PUT, DELETE...)
*/
@RestController
public class ComponentAPI extends BaseAPI<Component, ComponentDTO, Integer> {
@Autowired
private Components components;
@Autowired
private ComponentFamilies componentFamilies;
@Autowired
private ReadySetupAPI readySetupAPI;
/**
*
* @return ResponseBody
*
* This API returns all the components in the database.
*/
@CrossOrigin(origins = "*")
@GetMapping("/components")
public @ResponseBody Iterable<Component> getAll() {
return components.findAll();
}
/**
*
* @param index
* @return ResponseBody
*
* This API return a component according to its id.
*/
@CrossOrigin(origins = "*")
@GetMapping("/component/{index}")
public ResponseEntity<Iterable<Component>> getAllByType(@PathVariable Integer index) {
List<Component> result = components.findByTypeId(index);
return new ResponseEntity<>(result, HttpStatus.OK);
}
/**
*
* @param index
* @return ResponseEntity
*
* This API returns components according to their component type.
*/
@CrossOrigin(origins = "*")
@GetMapping("/components/{index}")
public ResponseEntity<Component> getById(@PathVariable Integer index) {
Optional<Component> result = this.components.findById(index);
return new ResponseEntity<>(result.get(), HttpStatus.OK);
}
@CrossOrigin(origins = "*")
/**
*
* @param headers
* @param componentDTO
* @return ResponseEntity
*
* This API allows the admin to add a new component.
*/
@PostMapping("/component")
public ResponseEntity<Component> newElement(@RequestHeader Map<String, String> headers,
@RequestBody ComponentDTO componentDTO) {
return super.sessionOperation(headers, componentDTO, new Callable<>() {
@Override
public ResponseEntity<Component> call(ComponentDTO componentDTO) {
Component component = new Component();
component.setName(componentDTO.getName());
component.setPrice(componentDTO.getPrice());
component.setPower(componentDTO.getPower());
Optional<ComponentFamily> optionalFamily = componentFamilies.findById(componentDTO.getFamilyId());
if (optionalFamily.isPresent()) {
component.setComponentFamily(optionalFamily.get());
return new ResponseEntity<>(components.save(component), HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
});
}
/**
*
* @param headers
* @param componentDTO
* @param index
* @return ResponseEntity
*
* This API allows the admin to modify a component.
*/
@CrossOrigin(origins = "*")
@PutMapping("/component/{index}")
public ResponseEntity<Component> updateElement(@RequestHeader Map<String, String> headers,
@RequestBody ComponentDTO componentDTO, final @PathVariable Integer index) {
return super.sessionOperation(headers, componentDTO, new Callable<>() {
@Override
public ResponseEntity<Component> call(ComponentDTO componentDTO) {
Optional<ComponentFamily> optionalFamily = componentFamilies.findById(componentDTO.getFamilyId());
if (optionalFamily.isPresent()) {
return components.findById(index).map(component -> {
component.setName(componentDTO.getName());
component.setPrice(componentDTO.getPrice());
component.setPower(componentDTO.getPower());
component.setComponentFamily(optionalFamily.get());
return new ResponseEntity<>(components.save(component), HttpStatus.OK);
}).orElseGet(() -> null);
} else {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
});
};
/**
*
* @param headers
* @param index
* @return boolean
*
* This API allows the admin to delete a component.
*/
@CrossOrigin(origins = "*")
@DeleteMapping("/component/{index}")
public ResponseEntity<Boolean> deleteElement(@RequestHeader Map<String, String> headers, @PathVariable Integer index) {
return super.sessionDeleteOperation(headers, index);
}
/**
* @author Andrei Blindu
* @author Jessica Vecchia
* @param familyId
* @return Boolean
*/
public Boolean deleteCascade(Integer familyId) {
Iterable<Component> componentList = this.components.findComponentsByFamilyId(familyId);
for (Component component : componentList) {
this.deleteEntity(component.getId());
}
return true;
}
/**
* @author Andrei Blindu
* @author Jessica Vecchia
* @param index
* @return Booolean
*/
@Override
protected Boolean deleteEntity(Integer index) {
if (components.findById(index).isPresent()) {
readySetupAPI.deleteCascade(index);
components.deleteById(index);
return true;
} else {
return false;
}
}
}
| true
|
d723c259a787e19c26c5c41d6937abf7788ec59f
|
Java
|
ajeet04/NewsSource
|
/app/src/main/java/com/nickelfox/ajeet/newsapp/Activities/MainActivity.java
|
UTF-8
| 6,643
| 1.867188
| 2
|
[] |
no_license
|
package com.nickelfox.ajeet.newsapp.Activities;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.nickelfox.ajeet.newsapp.Adapters.ViewPagerAdapter;
import com.nickelfox.ajeet.newsapp.Fragments.EverythingsFragment;
import com.nickelfox.ajeet.newsapp.Fragments.SourcesFragment;
import com.nickelfox.ajeet.newsapp.Fragments.TopHeadLinesFragment;
import com.nickelfox.ajeet.newsapp.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
static ImageView header;
static CoordinatorLayout coordinatorLayout;
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
setSupportActionBar(toolbar);
header=findViewById(R.id.htab_header);
if (getSupportActionBar() != null) getSupportActionBar().setTitle("NickelFox");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
coordinatorLayout=findViewById(R.id.htab_maincontent);
if(!isNetworkConnected()){
showSnackbar("No Internet connection");
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
tabLayout.setupWithViewPager(viewPager);
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);
//Pallrox transition in tabbar...............
try {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.header);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@SuppressWarnings("ResourceType")
@Override
public void onGenerated(Palette palette) {
int vibrantColor = palette.getVibrantColor(R.color.colorPrimary);
int vibrantDarkColor = palette.getDarkVibrantColor(R.color.black_trans80);
collapsingToolbarLayout.setContentScrimColor(vibrantColor);
collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
}
});
} catch (Exception e) {
// if Bitmap fetch fails, fallback to primary colors
Log.e(TAG, "onCreate: failed to create bitmap from background", e.fillInStackTrace());
collapsingToolbarLayout.setContentScrimColor(
ContextCompat.getColor(this, R.color.colorPrimary)
);
collapsingToolbarLayout.setStatusBarScrimColor(
ContextCompat.getColor(this, R.color.black_trans80)
);
}
// on tabselected....................................
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
Log.d(TAG, "onTabSelected: pos: " + tab.getPosition());
switch (tab.getPosition()) {
case 0:
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
// adding fragment in Viewpager.........................
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new TopHeadLinesFragment(
ContextCompat.getColor(this, R.color.cyan_50)), "HeadLines");
adapter.addFrag(new EverythingsFragment(
ContextCompat.getColor(this, R.color.amber_50)), "All News");
adapter.addFrag(new SourcesFragment(
ContextCompat.getColor(this, R.color.purple_50)), "News Sources");
viewPager.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.badge);
menuItem.setIcon( R.drawable.sort_24dp);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.badge:
Intent i=new Intent(this,SourceFilterActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
public static void setParalloxImage(String urlToImage) {
Picasso.get().load(urlToImage).fit().centerCrop().into(header);
}
// connectivity check................
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
public static void showSnackbar(String message){
Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
snackbar.show();
}
}
| true
|
5e62cf59e9ed9118a7be39c8434b333c013d815b
|
Java
|
unlhive/BustersDemise
|
/BustersDemise/src/main/java/com/michaelstark/bustersdemise/FrequencyDataAdapter.java
|
UTF-8
| 434
| 2.21875
| 2
|
[] |
no_license
|
package com.michaelstark.bustersdemise;
import android.*;
import android.R;
import android.content.Context;
import android.widget.ArrayAdapter;
/**
* Created by mstark on 8/7/13.
*/
public class FrequencyDataAdapter extends ArrayAdapter<Integer>
{
public FrequencyDataAdapter(Context context)
{
super(context, R.layout.simple_list_item_1);
this.add(16);
this.add(32);
this.add(64);
}
}
| true
|
13965bda27e6a26bce7f8072d682edb515a0e804
|
Java
|
anhalter42/Minecraft-Bukkit-Building
|
/src/com/mahn42/anhalter42/building/MarkerStorage.java
|
UTF-8
| 1,269
| 2.375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mahn42.anhalter42.building;
import com.mahn42.framework.BlockRect;
import com.mahn42.framework.IMarker;
import com.mahn42.framework.IMarkerStorage;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.World;
/**
*
* @author andre
*/
public class MarkerStorage implements IMarkerStorage{
@Override
public List<IMarker> findMarkers(World aWorld, String aName) {
ArrayList<IMarker> lResult = new ArrayList<IMarker>();
LandmarkDB lDB = BuildingPlugin.plugin.LandmarkDBs.getDB(aWorld);
Landmark lLandmark = lDB.getLandmark(aName);
if (lLandmark != null) {
lResult.add(new MarkerStorageMarker(lLandmark));
}
return lResult;
}
@Override
public List<IMarker> findMarkers(World aWorld, BlockRect aArea) {
ArrayList<IMarker> lResult = new ArrayList<IMarker>();
LandmarkDB lDB = BuildingPlugin.plugin.LandmarkDBs.getDB(aWorld);
ArrayList<Landmark> lLandmarks = lDB.getLandmarks(aArea);
for(Landmark lLandmark : lLandmarks) {
lResult.add(new MarkerStorageMarker(lLandmark));
}
return lResult;
}
}
| true
|
95a530b77481196dcb838b673d5d5b4c20b2525d
|
Java
|
zhaobingcn/LeetCodeL
|
/src/com/company/yushi/Sluation.java
|
UTF-8
| 2,885
| 2.953125
| 3
|
[] |
no_license
|
package com.company.yushi;
/**
* Created by zhzy on 2017/9/28.
*/
public class Sluation {
public static void main(String[] args) {
Sluation sluation = new Sluation();
String test = "my.song.mp3 11b\ngreatSong.flac 1000b\nnot3.txt 5b\nvideo.mp4 200b\ngame.exe 100b\nmov!e.mkv 10000b";
String s = sluation.solution(test);
System.out.println(s);
}
public String solution(String S) {
String music[] = {"mp3","aac", "flac"};
String image[] = {"jpg","bmp","gif"};
String movie[] = {"mp4","avi","mkv"};
String[] cata = {"music", "images", "movies", "other"};
long sum[] = new long[4];
StringBuffer sb = new StringBuffer();
for(String s: S.split("\n")){
String[] line = s.split(" ");
if(isLegal(line[0])){
String numS = line[1].replace("b", "");
int start = line[0].lastIndexOf('.' )+1;
String key = line[0].substring(start);
// System.out.println(key);
int num = Integer.valueOf(numS);
sum[catagory(key, music, image, movie)] += num;
}
}
for(int i=0; i<3; i++){
sb.append(cata[i] + " " + sum[i] + "b" + "\n");
}
sb.append(cata[3] + " " + sum[3] + "b");
return sb.toString();
}
boolean isLegal(String s){
if(s.length() > 30){
return false;
}
// System.out.println(s);
String[] ss =s.split("\\.");
// System.out.println(ss[0]);
for(int i=1; i<ss.length; i++){
for(int j=0; j<ss[i].length(); j++){
char ch = ss[i].charAt(j);
if(!((ch >= 'a' && ch <= 'z') || (ch>='0' && ch<='9'))){
return false;
}
}
}
for(int i=0; i<ss[0].length(); i++){
char ch = ss[0].charAt(i);
if(!((ch >= 'a' && ch <='z') || (ch>='A' && ch <='Z') || (ch>='0' && ch <='9') || contains(ch))) {
return false;
}
}
return true;
}
int catagory(String key, String[] music, String[] image, String[] movie){
for(String s:music){
if(s.equals(key)){
return 0;
}
}
for (String s:image){
if(s.equals(key)){
return 1;
}
}
for (String s: movie){
if(s.equals(key)){
return 2;
}
}
return 3;
}
boolean contains(char a){
char[] s = {'^', '&', '\'','@','{','}','[',']',',','$'
,'=','!','-','#','(',')','%','.','+','~','_'
};
for(int i=0; i<s.length; i++){
if(a == s[i]){
return true;
}
}
return false;
}
}
| true
|
b64c1f84e985e0591af6e8c7c413004c4e188685
|
Java
|
banyanya/JAVA
|
/200607/input_keyboard_data1.java
|
UTF-8
| 885
| 3.203125
| 3
|
[] |
no_license
|
// import java.util.Scanner; // Scanner 사용 시 명시 필수!
// class input_keyboard_data1 {
// public static void main(String[] args) {
// Scanner scanner;
// scanner = new Scanner(System.in);
// while(true) {
// int input = -1;
// input = scanner.nextInt();
// switch(input) {
// case 0 :
// return;
// case 1 :
// System.out.println("입력 : 1");
// break;
// case 2 :
// System.out.println("입력 : 2");
// break;
// case 3 :
// System.out.println("입력 : 3");
// break;
// default :
// break;
// }
// }
// }
// }
| true
|
8d2f7ea5491e02002d2566b11ec055e94b485219
|
Java
|
RegaladoLeonardo/5IV9-Practica
|
/FInalCalculadora/app/src/main/java/com/example/calculadora/Raiz.java
|
UTF-8
| 804
| 2.671875
| 3
|
[] |
no_license
|
package com.example.calculadora;
//import javax.swing.JOptionPane;
public class Raiz extends Calculadora{
private double resultado;
public Raiz() {
}
public Raiz(double can1, double canM, double resultado) {
super(can1, canM);
this.resultado = resultado;
}
public void setResultado(double resultado) {
this.resultado = resultado;
}
public double getResultado() {
return resultado;
}
public double operacionz( ){
//JOptinPane.showMessageDialog(null, getCan1());
System.out.println(getCan1());
//try{
resultado = Math.sqrt(getCan1());
/**}catch (Exception e){
resultado = Double.parseDouble(e.getMessage());
}
**/
return resultado;
}
}
| true
|
d6923a33504628eca71f134da23262d9be6c32c8
|
Java
|
BrunoSilvaATEC/Exercicios_1
|
/src/dificuldade1/Exer11.java
|
ISO-8859-1
| 796
| 3.734375
| 4
|
[] |
no_license
|
package dificuldade1;
import java.util.Scanner;
public class Exer11 {
/*Mdia CursoElabore um mtodo devolve a mdia de um curso de curta durao composto por 5 mdulos.
Certifique-se que o seu programa cumpre os seguintes requisitos
Declara um array do tipo double com a dimenso 5
Pede ao utilizador as 5 notas que lhe foram atribudas
Cada nota armazenada na respectiva posio do array
Mostre na consola a mdia de curso obtida
*/
public Exer11(){
double [] notas = new double [5];
double soma = 0;
Scanner n = new Scanner(System.in);
for (int i=0;i<5;i++)
{
System.out.println("Insira " + (i+1) + " nota: ");
notas[i]=n.nextDouble();
soma+=notas[i];
}
System.out.println("A media " + (soma/5));
}
}
| true
|
3078303af98536006c821098c396e90870042b8f
|
Java
|
mchristensson/ImageIndexer
|
/persistance/src/main/java/org/mac/nasbackup/persistance/mapper/ImageFileCallbackHandler.java
|
UTF-8
| 1,464
| 2.390625
| 2
|
[
"MIT"
] |
permissive
|
package org.mac.nasbackup.persistance.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import org.mac.nasbackup.persistance.model.DeviceType;
import org.mac.nasbackup.persistance.model.ImageEntry;
import org.mac.nasbackup.persistance.model.StorageDevice;
import org.springframework.jdbc.core.RowCallbackHandler;
public class ImageFileCallbackHandler implements RowCallbackHandler {
private Collection<ImageEntry> imageEntries = new ArrayList<ImageEntry>();
@Override
public void processRow(ResultSet rs) throws SQLException {
ImageEntry imageEntry = new ImageEntry();
imageEntry.setId(rs.getLong("FILE_ID"));
imageEntry.setFileName(rs.getString("file_name"));
imageEntry.setFilePath(rs.getString("file_path"));
imageEntry.setSize(rs.getInt("file_size"));
imageEntry.setMake(rs.getString("origin_make"));
imageEntry.setModel(rs.getString("origin_model"));
imageEntry.setSoftware(rs.getString("origin_software"));
StorageDevice storageDevice = new StorageDevice();
storageDevice.setId(rs.getLong("storagedevice_id"));
storageDevice.setPath(rs.getString("file_path"));
storageDevice.setLabel(rs.getString("label"));
storageDevice.setDeviceType(DeviceType.valueOf(rs.getString("devicetype")));
imageEntry.setStorageDevice(storageDevice);
this.imageEntries.add(imageEntry);
}
public Collection<ImageEntry> getImageEntries() {
return imageEntries;
}
}
| true
|
194bead758aad272405cff6b22b19da23254125c
|
Java
|
duygucer/MultiThread
|
/YAZLAB12/src/yazlab12/YazLab12form.java
|
UTF-8
| 33,890
| 2.5
| 2
|
[] |
no_license
|
package yazlab12;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
/**
*
* @author Duygu
*/
//Sub thread nesnesi oluşturmak için gerekli class
class SubThreadsOlustur {
public int ChildThread = 0;
public synchronized int getChildThread() {
return ChildThread;
}
public synchronized void setChildThread(int ChildThread) {
this.ChildThread = ChildThread;
}
}
//JFrame
public class YazLab12form extends javax.swing.JFrame {
ArrayList<Integer> childs = new ArrayList<Integer>();
private int Thistek = 0;
private int Th1istek = 0;
private int Th2istek = 0;
private int Th3istek = 0;
private int Th4istek = 0;
private int istek = 0;
public synchronized int getTh1istek() {
return Th1istek;
}
public synchronized void setTh1istek(int Th1istek) {
this.Th1istek = Th1istek;
}
public synchronized int getTh2istek() {
return Th2istek;
}
public synchronized void setTh2istek(int Th2istek) {
this.Th2istek = Th2istek;
}
public synchronized int getTh3istek() {
return Th3istek;
}
public synchronized void setTh3istek(int Th3istek) {
this.Th3istek = Th3istek;
}
public synchronized int getTh4istek() {
return Th4istek;
}
public synchronized void setTh4istek(int Th4istek) {
this.Th4istek = Th4istek;
}
int zaman = 0;
public YazLab12form() {
initComponents();
}
public synchronized int getIstek() {
return istek;
}
public synchronized void setIstek(int istek) {
this.istek = istek;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jProgressBar5 = new javax.swing.JProgressBar();
MainThreadProgress = new javax.swing.JProgressBar();
SubThread5 = new javax.swing.JProgressBar();
SubThread3 = new javax.swing.JProgressBar();
SubThread1 = new javax.swing.JProgressBar();
SubThread7 = new javax.swing.JProgressBar();
SubThread4 = new javax.swing.JProgressBar();
SubThread6 = new javax.swing.JProgressBar();
SubThread8 = new javax.swing.JProgressBar();
SubThread2 = new javax.swing.JProgressBar();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
SubThread9 = new javax.swing.JProgressBar();
SubThread10 = new javax.swing.JProgressBar();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBounds(new java.awt.Rectangle(600, 300, 0, 0));
setMinimumSize(new java.awt.Dimension(640, 450));
setSize(new java.awt.Dimension(640, 392));
MainThreadProgress.setStringPainted(true);
SubThread5.setStringPainted(true);
SubThread5.setVisible(false);
SubThread3.setStringPainted(true);
SubThread3.setVisible(false);
SubThread1.setStringPainted(true);
SubThread7.setStringPainted(true);
SubThread7.setVisible(false);
SubThread4.setStringPainted(true);
SubThread4.setVisible(false);
SubThread6.setStringPainted(true);
SubThread6.setVisible(false);
SubThread8.setStringPainted(true);
SubThread8.setVisible(false);
SubThread2.setStringPainted(true);
jButton1.setText("Başlat");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Main Thread");
jLabel2.setText("Sub Thread1");
jLabel3.setText("Sub Thread2");
jLabel4.setText("Sub Thread3");
jLabel4.setVisible(false);
jLabel6.setText("Sub Thread5");
jLabel6.setVisible(false);
jLabel5.setText("Sub Thread4");
jLabel5.setVisible(false);
jLabel7.setText("Sub Thread6");
jLabel7.setVisible(false);
jLabel8.setText("Sub Thread7");
jLabel8.setVisible(false);
jLabel9.setText("Sub Thread8");
jLabel9.setVisible(false);
SubThread9.setStringPainted(true);
SubThread9.setVisible(false);
SubThread10.setStringPainted(true);
SubThread10.setVisible(false);
jLabel10.setText("Sub Thread9");
jLabel10.setVisible(false);
jLabel11.setText("Sub Thread10");
jLabel11.setVisible(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(SubThread1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 116, Short.MAX_VALUE)
.addComponent(SubThread2, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(SubThread3, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SubThread4, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(jButton1)
.addGap(43, 43, 43)
.addComponent(MainThreadProgress, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(276, 276, 276)
.addComponent(jLabel1)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(103, 103, 103))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(SubThread5, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SubThread6, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)
.addGap(103, 103, 103))
.addGroup(layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7)
.addGap(103, 103, 103))
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel9)
.addGap(101, 101, 101))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(SubThread7, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SubThread8, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(SubThread9, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SubThread10, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11)
.addGap(100, 100, 100))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(MainThreadProgress, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(SubThread1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SubThread2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addComponent(jLabel4))
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(SubThread3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SubThread4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SubThread5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SubThread6, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SubThread8, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SubThread7, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SubThread9, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SubThread10, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//bütün progressbarların ilerlemesi burada kontrol edilir.
new Thread(new Runnable() {
@Override
public void run() {
while (istek <= 10000) {
// Runs inside of the Swing UI thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int x = (getIstek() / 100);
MainThreadProgress.setValue(x);
if (MainThreadProgress.getValue() > 99) {
System.out.println("10000 istek kapasitesine ulaşıldı.");
}
int y = (getTh1istek() / 50);
SubThread1.setValue(y);
int z = (getTh2istek() / 50);
SubThread2.setValue(z);
if (childs.size() >= 3) {
SubThread3.setVisible(true);
jLabel4.setVisible(true);
SubThread3.setValue(childs.get(2) / 50);
}
if (childs.size() >= 4) {
SubThread4.setVisible(true);
jLabel5.setVisible(true);
SubThread4.setValue(childs.get(3) / 50);
}
if (childs.size() >= 5) {
SubThread5.setVisible(true);
jLabel6.setVisible(true);
SubThread5.setValue(childs.get(4) / 50);
}
if (childs.size() >= 6) {
SubThread6.setVisible(true);
jLabel7.setVisible(true);
SubThread6.setValue(childs.get(5) / 50);
}
if (childs.size() >= 7) {
SubThread7.setVisible(true);
jLabel8.setVisible(true);
SubThread7.setValue(childs.get(6) / 50);
}
if (childs.size() >= 8) {
SubThread8.setVisible(true);
jLabel9.setVisible(true);
SubThread8.setValue(childs.get(7) / 50);
}
if (childs.size() >= 9) {
SubThread9.setVisible(true);
jLabel10.setVisible(true);
SubThread9.setValue(childs.get(8) / 50);
}
if (childs.size() >= 10) {
SubThread10.setVisible(true);
jLabel11.setVisible(true);
SubThread10.setValue(childs.get(9) / 50);
}
//Eğer bir sub thread istek değeri 0'a düşerse burada silinir.
for (int i = 2; i < childs.size(); i++) {
if (childs.get(i) == 0) {
System.out.println((i+1)+". Child silindi!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
childs.remove(i);
System.out.println("Child size: "+childs.size());
if (i == 2 || 2==childs.size()+1 || 2==childs.size()+2) {
SubThread3.setVisible(false);
jLabel4.setVisible(false);
}
if (i == 3 || 3==childs.size()+1 || 3==childs.size()+2) {
SubThread4.setVisible(false);
jLabel5.setVisible(false);
}
if (i == 4 || 4==childs.size()+1 || 4==childs.size()+2) {
SubThread5.setVisible(false);
jLabel6.setVisible(false);
}
if (i == 5 || 5==childs.size()+1 || 5==childs.size()+2) {
SubThread6.setVisible(false);
jLabel7.setVisible(false);
}
if (i == 6 || 6==childs.size()+1 || 6==childs.size()+2) {
SubThread7.setVisible(false);
jLabel8.setVisible(false);
}
if (i == 7 || 7==childs.size()+1 || 7==childs.size()+2) {
SubThread8.setVisible(false);
jLabel9.setVisible(false);
}
if (i == 8 || 8==childs.size()+1 || 8==childs.size()+2) {
SubThread9.setVisible(false);
jLabel10.setVisible(false);
}
if (i == 9 || 9==childs.size()+1 || 9==childs.size()+2) {
SubThread10.setVisible(false);
jLabel11.setVisible(false);
}
}
}
}
});
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YazLab12form.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}).start();
}//GEN-LAST:event_jButton1ActionPerformed
//Main Thread için istek oluşturur.
public void istekOlustur() {
Random r = new Random();
int x = r.nextInt(1001);
if (getIstek() + x < 10000) {
System.out.println("Yeni gelen istek: " + x);
setIstek(getIstek() + x);
} else {
System.out.println("Kuyruk dolu...");
setIstek(10000);
}
}
//Main Thread istek yanıtlar.
public void istekYanıtla() {
if (getIstek() > 0) {
Random r = new Random();
int y = r.nextInt(51);
if (getIstek() > y) {
System.out.println("Yanıtlanan istek: " + y);
setIstek(getIstek() - y);
} else {
System.out.println("Yanıtlanan istek: " + getIstek());
setIstek(0);
}
} else {
System.out.println("Yanıtlanacak istek yok...");
}
}
//Main Thread
public static void main(String args[]) {
YazLab12form mainThread = new YazLab12form();
mainThread.setVisible(true);
mainThread.childs.add(mainThread.getTh1istek());
mainThread.childs.add(mainThread.getTh2istek());
mainThread.CreateSubThread();
mainThread.SubThreads(null);
while (true) {
try {
Thread.sleep(100);
mainThread.zaman += 100;
System.out.println("Geçen zaman: " + mainThread.zaman);
if (mainThread.zaman % 500 == 0) {
mainThread.istekOlustur();
System.out.println("İstek sayısı: " + mainThread.getIstek());
}
if (mainThread.zaman % 200 == 0) {
mainThread.istekYanıtla();
System.out.println("İstek sayısı: " + mainThread.getIstek());
}
} catch (InterruptedException ex) {
Logger.getLogger(YazLab12form.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Sub Threadler için main threadden istek alma
public synchronized int subThreadIstekAl(int x, int ThIstek) {
if (x > getIstek()) {
Thistek = ThIstek + getIstek();
setIstek(0);
} else {
setIstek(getIstek() - x);
Thistek = ThIstek + x;
}
return Thistek;
}
//Sub Thread işlemleri
public void SubThreads(SubThreadsOlustur x) {
childs.set(0, getTh1istek());
childs.set(0, getTh2istek());
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YazLab12form.class.getName()).log(Level.SEVERE, null, ex);
}
if (zaman % 500 == 0) {
Random r = new Random();
int x = r.nextInt(201);
System.out.println("SubThread1, Alınan istek: " + x);
if (getTh1istek() <= 5000) {
setTh1istek(subThreadIstekAl(x, getTh1istek()));
System.out.println("SubThread1 istek sayısı: " + getTh1istek());
childs.set(0, getTh1istek());
} else {
System.out.println("SubThread1 kapasitesi dolu..");
}
}
if (zaman % 300 == 0 && getTh1istek() > 0) {
Random r = new Random();
int y = r.nextInt(31);
if (getTh1istek() - y < 0) {
System.out.println("SubThread1, Yanıtlanan istek: " + (y - getTh1istek()));
setTh1istek(0);
System.out.println("SubThread1 istek sayısı: " + getTh1istek());
childs.set(0, getTh1istek());
} else {
System.out.println("SubThread1, Yanıtlanan istek: " + y);
setTh1istek(getTh1istek() - y);
System.out.println("SubThread1 istek sayısı: " + getTh1istek());
childs.set(0, getTh1istek());
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YazLab12form.class.getName()).log(Level.SEVERE, null, ex);
}
if (zaman % 500 == 0) {
Random r = new Random();
int x = r.nextInt(201);
System.out.println("SubThread2, Alınan istek: " + x);
if (getTh2istek() <= 5000) {
setTh2istek(subThreadIstekAl(x, getTh2istek()));
System.out.println("SubThread2 istek sayısı: " + getTh2istek());
childs.set(1, getTh2istek());
} else {
System.out.println("SubThread2 kapasitesi dolu...");
}
}
if (zaman % 300 == 0 && getTh2istek() > 0) {
Random r = new Random();
int y = r.nextInt(31);
if (getTh2istek() - y < 0) {
System.out.println("SubThread2, Yanıtlanan istek: " + (y - getTh2istek()));
setTh2istek(0);
System.out.println("SubThread2 istek sayısı: " + getTh2istek());
childs.set(1, getTh2istek());
} else {
System.out.println("SubThread2, Yanıtlanan istek: " + y);
setTh2istek(getTh2istek() - y);
System.out.println("SubThread2 istek sayısı: " + getTh2istek());
childs.set(1, getTh2istek());
}
}
}
}
});
//Yeni oluşan sub threadler
if (x != null && x.getChildThread() != 0) {
childs.add(x.getChildThread());
System.out.println("--SubThread sayisi: " + childs.size());
Thread thread5 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YazLab12form.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 2; i < childs.size(); i++) {
if (zaman % 500 == 0) {
Random r = new Random();
int z = r.nextInt(101);
System.out.println("SubThread" + (i + 1) + ", Alınan istek: " + z);
if (childs.get(i) <= 5000) {
childs.set(i, subThreadIstekAl(z, childs.get(i)));
System.out.println("SubThread" + (i + 1) + " istek sayısı: " + childs.get(i));
} else {
System.out.println("SubThread" + (i + 1) + ", kapasitesi dolu...");
}
}
if (zaman % 300 == 0 && getTh2istek() > 0) {
Random r = new Random();
int y = r.nextInt(31);
if (childs.get(i) - y < 0) {
System.out.println("SubThread" + (i + 1) + ", Yanıtlanan istek: " + (y - childs.get(i)));
childs.set(i, 0);
System.out.println("SubThread" + (i + 1) + ", istek sayısı: " + childs.get(i));
} else {
System.out.println("SubThread" + (i + 1) + ", Yanıtlanan istek: " + y);
childs.set(i, childs.get(i) - y);
System.out.println("SubThread" + (i + 1) + ", istek sayısı: " + childs.get(i));
}
}
}
}
}
});
thread5.start();
}
thread1.start();
thread2.start();
}
//Eğer bir sub thread istek değeri %70 üzerine çıkarsa yeni sub thread oluşturulur.
public void CreateSubThread() {
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YazLab12form.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < childs.size(); i++) {
if ((childs.get(i) / 50) >= 70 && childs.size()<10) {
SubThreadsOlustur newchild = new SubThreadsOlustur();
int temp = childs.get(i) / 2;
newchild.setChildThread(temp);
if (i == 0 && getTh1istek() >= 3300) {
setTh1istek(getTh1istek() - temp);
System.out.println("New Th1istek: " + getTh1istek());
childs.set(0, getTh1istek());
}
if (i == 1 && getTh2istek() >= 3300) {
setTh2istek(getTh2istek() - temp);
System.out.println("New Th2istek: " + getTh2istek());
childs.set(1, getTh2istek());
}
if (i != 0 && i != 1) {
childs.set(i, childs.get(i) - temp);
}
System.out.println((childs.size() + 1) + ". Child Oluşturuldu");
SubThreads(newchild);
}
}
}
}
});
thread3.start();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JProgressBar MainThreadProgress;
private javax.swing.JProgressBar SubThread1;
private javax.swing.JProgressBar SubThread10;
private javax.swing.JProgressBar SubThread2;
private javax.swing.JProgressBar SubThread3;
private javax.swing.JProgressBar SubThread4;
private javax.swing.JProgressBar SubThread5;
private javax.swing.JProgressBar SubThread6;
private javax.swing.JProgressBar SubThread7;
private javax.swing.JProgressBar SubThread8;
private javax.swing.JProgressBar SubThread9;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JProgressBar jProgressBar5;
// End of variables declaration//GEN-END:variables
}
| true
|
c65b3cfc33fd07ea78fe6924f663ad79df8ac812
|
Java
|
kamilBrodziak/guestbook
|
/src/main/java/helpers/UserHelper.java
|
UTF-8
| 1,158
| 2.28125
| 2
|
[] |
no_license
|
package helpers;
import com.sun.net.httpserver.HttpExchange;
import controller.CookieController;
import dao.LoginDAO;
import dao.SessionDAO;
import model.Login;
import java.sql.SQLException;
public class UserHelper {
private LoginDAO loginDAO;
private SessionDAO sessionDAO;
private CookieController cookieController;
public UserHelper(LoginDAO loginDAO, SessionDAO sessionDAO, CookieController cookieController) {
this.loginDAO = loginDAO;
this.sessionDAO = sessionDAO;
this.cookieController = cookieController;
}
public boolean isLogged(HttpExchange httpExchange) throws SQLException {
return !cookieController.isNewSession(httpExchange) &&
sessionDAO.getSessionByCookie(
cookieController.getSessionIdCookie(httpExchange).get().getValue()).isPresent();
}
public Login getCurrentLogged(HttpExchange httpExchange) throws SQLException {
return loginDAO.getLoginByID(
sessionDAO.getSessionByCookie(
cookieController.getSessionIdCookie(httpExchange).get().getValue()).get().getLoginID()).get();
}
}
| true
|
e7521566949f884d1cbd8e755bdf24fcaa58ed5e
|
Java
|
Pingviii/Java
|
/src/Lessons/lesson04.java
|
UTF-8
| 770
| 3.484375
| 3
|
[] |
no_license
|
package Lessons;
public class lesson04 {
public static void main(String[] args) {
int i = word("penguin").length();
//System.out.println(i);
//System.out.println(showChar("Oleh",4));
//System.out.println(calculateRetail(5,50));
System.out.println(isPrime(5));
}
public static String word (String word){
return word;
}
public static char showChar (String word, int numb){
char symb = word.charAt(numb-1);
return symb;
}
public static double calculateRetail (double price, double percentage){
return price*(1+percentage/100.00);
}
public static boolean isPrime (int number){
int ost = 0;
for (int i = 2; i < number; i++){
ost = number%i;
if (ost == 0) break;
}
if (ost != 0) return true; else return false;
}
}
| true
|
d291b8cc1a96b57a23d58a14b6a3fae15e120859
|
Java
|
dalyleide/Microservices-Portifolio
|
/consumer-pat/consumer-pat-main/src/main/java/br/com/alelo/consumer/consumerpat/data/model/Card.java
|
UTF-8
| 983
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package br.com.alelo.consumer.consumerpat.data.model;
import br.com.alelo.consumer.consumerpat.util.TypeCardsEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "CARDS")
public class Card implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
@Column(name = "CARD_NUMBER", nullable = false, length = 16)
Long number;
@Column(name = "BALANCE", nullable = false)
BigDecimal balance;
@Column(name = "TYPE_CARD", nullable = false)
TypeCardsEnum type;
@ManyToOne
Consumer consumer;
public Card(Consumer consumer, TypeCardsEnum type, BigDecimal balance, Long number) {
this.balance = balance;
this.consumer = consumer;
this.number = number;
this.type = type;
}
}
| true
|
8669f05abc78e84f347d6bd5bfdbb5a6f237c2dd
|
Java
|
Andyt-Nguyen/java_basics
|
/methodoverloading/src/MethodOverloading.java
|
UTF-8
| 2,220
| 4.1875
| 4
|
[] |
no_license
|
public class MethodOverloading {
/*
* In order to do method overloading is creating multiple of the same method
* names and having each function have different parameters and amount of parameters
*/
public static void main(String[] args) {
calculateScore("Tim", 5); // This function is calling the first method
calculateScore(4); // This function is using the second calcScore method
calculateScore(); // This function is calling the third method
calcFeetAndInchesToCentimeters(13,1);
calcFeetAndInchesToCentimeters(100);
}
public static int calculateScore(String playerName, int score) {
System.out.println("Player " + playerName + " scored " + score + " points");
return score * 1000;
}
public static int calculateScore(int score) {
System.out.println("Unamed Player scored " + score + " points");
return score * 1000;
}
public static int calculateScore() {
System.out.println("No player name or player score");
return 0;
}
// This function coverts ft & inches to cm
public static double calcFeetAndInchesToCentimeters(double feet, double inches) {
if(feet < 0) { // validation check
return -1;
} else if(inches < 0 || inches > 12){ // validation check
return -1;
} else {
// 1ft = 12in
// 1in = 2.54cm
double ftToInches = convertInchesToCm(feet * 12);
double inchesToCm = convertInchesToCm(inches);
double total = ftToInches + inchesToCm;
System.out.println(feet + "ft " + inches + "in = " + total + "cm");
return total;
}
}
// This function takes only inches and transforms to cm
public static double calcFeetAndInchesToCentimeters(double inches) {
if(inches < 0) { // validation check
return -1;
}
double inchesToFt = (int) inches / 12;
double leftOverInches = (int) inches % 12;
return calcFeetAndInchesToCentimeters(inchesToFt, leftOverInches);
}
public static double convertInchesToCm(double inches) {
return inches * 2.54;
}
}
| true
|
689fc201db7c4166c981c503add18772f193037f
|
Java
|
zaomaoer/FootballClub
|
/src/main/java/com/example/footballclub/service/ActivityService.java
|
UTF-8
| 1,536
| 2.15625
| 2
|
[] |
no_license
|
package com.example.footballclub.service;
import com.example.footballclub.model.Activity;
import com.example.footballclub.model.ActivitySignIn;
import com.example.footballclub.model.ActivitySignUp;
import com.example.footballclub.repository.ActivityRepository;
import com.example.footballclub.repository.ActivitySignInRepository;
import com.example.footballclub.repository.ActivitySignUpRepository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Calendar;
import java.util.List;
@Service
public class ActivityService {
@Resource
private ActivityRepository activityRepository;
@Resource
private ActivitySignUpRepository activitySignUpRepository;
@Resource
private ActivitySignInRepository activitySignInRepository;
@Transactional
public List<Activity> findActivitiesByCreateTimeAfter(){
Calendar calendar = Calendar.getInstance();
return activityRepository.findActivitiesByCreateTimeAfter(calendar.get(Calendar.YEAR)+"0000");
}
@Transactional
public Activity saveActivity(Activity activity){
return activityRepository.save(activity);
}
@Transactional
public ActivitySignUp saveActivitySignUp(ActivitySignUp activitySignUp){
return activitySignUpRepository.save(activitySignUp);
}
@Transactional
public ActivitySignIn saveActivitySignIn(ActivitySignIn activitySignIn){
return activitySignInRepository.save(activitySignIn);
}
}
| true
|
c5b63e5c9e58b2418d568b17180849b3bb8e7ef8
|
Java
|
notcorgi/JavaTest
|
/TEST/smalltest/src/exceptionTest/ExceptionTest.java
|
UTF-8
| 851
| 3.3125
| 3
|
[] |
no_license
|
package exceptionTest;
public class
ExceptionTest {
public static void main(String[] args) {
int[] array = null;
try {
choose(array, 2);
} catch (TestException2 e) {
e.printStackTrace();
System.out.println("=========");
System.out.println(e.getMessage());
System.out.println("=========");
System.out.println(e);
}
System.out.println("finish");
}
public static void choose(int[] a, int index) throws TestException2 {
if (a == null) {
throw new TestException2("编译期异常测试");//编译期异常 需要throws或try catch处理
}
if (index < 0 || index >= a.length) {
throw new TestException1("运行期异常测试");//运行期异常,故无需处理
}
}
}
| true
|
00f7caa3c0c92cc380a3762691a1dd1eec842739
|
Java
|
alexandraback/datacollection
|
/solutions_5766201229705216_0/java/starforever/Solution.java
|
UTF-8
| 1,371
| 3.25
| 3
|
[] |
no_license
|
import java.util.Scanner;
import java.util.LinkedList;
public class Solution
{
private int N;
private LinkedList<Integer>[] adj;
public Solution (Scanner sc)
{
N = sc.nextInt();
adj = (LinkedList<Integer>[]) new LinkedList[N];
for (int i = 0; i < N; ++i)
adj[i] = new LinkedList<Integer>();
for (int i = 0; i < N - 1; ++i)
{
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
}
public int solve ()
{
int maxFull = Integer.MIN_VALUE;
for (int i = 0; i < N; ++i)
maxFull = Math.max(maxFull, full(i, -1));
return N - maxFull;
}
private int full (int u, int p)
{
int numChild = adj[u].size();
if (p != -1)
--numChild;
if (numChild < 2)
return 1;
int c1 = Integer.MIN_VALUE, c2 = Integer.MIN_VALUE;
for (int v : adj[u])
{
if (v == p)
continue;
int f = full(v, u);
if (f > c1)
{
c2 = c1;
c1 = f;
}
else if (f > c2)
{
c2 = f;
}
}
return c1 + c2 + 1;
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 1; t <= T; ++t)
{
Solution sol = new Solution(sc);
System.out.format("Case #%d: %d\n", t, sol.solve());
}
sc.close();
}
}
| true
|
88971f4d6ff34ecc9152e2cdc74dc40e634010ef
|
Java
|
GCBaiduMap/GC
|
/app/src/main/java/gc/com/gcmapapp/activity/LoginActivity.java
|
UTF-8
| 5,093
| 2.140625
| 2
|
[] |
no_license
|
package gc.com.gcmapapp.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gc.com.gcmapapp.R;
import gc.com.gcmapapp.application.Constants;
import gc.com.gcmapapp.bean.Login;
import gc.com.gcmapapp.http.Api;
import gc.com.gcmapapp.http.HttpUtil;
import gc.com.gcmapapp.http.ProgressSubscriber;
import gc.com.gcmapapp.http.Url;
import gc.com.gcmapapp.utils.SharePreferenceUtil;
import gc.com.gcmapapp.utils.ToastUtils;
import okhttp3.HttpUrl;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends BaseActivity {
@BindView(R.id.edt_username)
EditText edtUsername;
@BindView(R.id.edt_password)
EditText edtPassword;
@BindView(R.id.layout_login)
FrameLayout login;
@BindView(R.id.rem_selector)
CheckBox rem_checkbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
String rem_userName = (String) SharePreferenceUtil.get(getApplicationContext(), Constants.REM_USERNAME, "");
String rem_passWord = (String) SharePreferenceUtil.get(getApplicationContext(), Constants.REM_PASSWORD, "");
if(!TextUtils.isEmpty(rem_userName)&&!TextUtils.isEmpty(rem_passWord))
{
edtUsername.setText(rem_userName);
edtPassword.setText(rem_passWord);
}
}
@OnClick(R.id.layout_login)
public void login(View view) {
String host = (String) SharePreferenceUtil.get(getApplicationContext(), Constants.HOST, "");
if(TextUtils.isEmpty(host)){
setHost();
return;
}
String userName = edtUsername.getText().toString();
String password = edtPassword.getText().toString();
if (TextUtils.isEmpty(userName)) {
ToastUtils.showMessage(context, "用户名为空");
return;
}
if (TextUtils.isEmpty(password)) {
ToastUtils.showMessage(context, "密码为空");
return;
}
HttpUrl httpUrl = HttpUrl.parse(Url.BASE_URL);
if(httpUrl == null){
ToastUtils.showMessage(context, "服务器地址错误");
return;
}
HttpUtil.getInstance().toSubscribe(Api.getDefault(context).login(userName, password), new ProgressSubscriber<Login>(this) {
@Override
protected void _onNext(Login login) {
SharePreferenceUtil.put(getApplicationContext(), Constants.TOKEN, login.getToken());
SharePreferenceUtil.put(getApplicationContext(), Constants.USERNAME, login.getReal_name());
SharePreferenceUtil.put(getApplicationContext(), Constants.SHOWONCE, "");
if(rem_checkbox.isChecked())
{
SharePreferenceUtil.put(getApplicationContext(), Constants.REM_USERNAME, edtUsername.getText());
SharePreferenceUtil.put(getApplicationContext(), Constants.REM_PASSWORD, edtPassword.getText());
}
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
}
@Override
protected void _onError(String message) {
ToastUtils.showMessage(context, message);
}
}, lifecycleSubject);
}
@OnClick(R.id.linear_setting)
public void setHost(){
final EditText editText = new EditText(context);
editText.setText((String) SharePreferenceUtil.get(getApplicationContext(), Constants.HOST, ""));
new AlertDialog.Builder(context)
.setTitle("请输入服务器地址")
.setView(editText)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String host = editText.getText().toString();
if(TextUtils.isEmpty(host)){
ToastUtils.showMessage(context, "服务器地址不能为空");
return;
}
if(!host.startsWith("http://")){
host = "http://" + host ;
}
SharePreferenceUtil.put(getApplicationContext(), Constants.HOST, host);
Url.BASE_URL = context.getString(R.string.base_url, host);
}
})
.setNegativeButton("取消", null)
.show();
}
}
| true
|
0ab29dd3b529644848dc99015df73d3bf3351921
|
Java
|
cleysonnn/URI-algunsTestes
|
/src/testeWHileANDFOR.java
|
UTF-8
| 544
| 3.265625
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class testeWHileANDFOR {
public static void main(String [] args) {
Scanner info = new Scanner(System.in);
String [] num = info.nextLine().split(" ");
double a = Double.parseDouble(num[0]);
double b = Double.parseDouble(num[1]);
double c = Double.parseDouble(num[2]);
if((b-c) < a && a < (b + c)) {
double perimetro = (a+b+c);
System.out.println("Perimetro = "+perimetro);
}else {
double area = c*(a+b)/2;
System.out.println("Area = "+area);
info.close();
}
}
}
| true
|
554a14e1782dcfa99596b4adda6ed69c7d12fa31
|
Java
|
sjywying/csp
|
/monitorstat-web/src/main/java/com/taobao/monitor/web/vo/HostConfigPo.java
|
UTF-8
| 3,733
| 1.945313
| 2
|
[] |
no_license
|
package com.taobao.monitor.web.vo;
import java.util.Date;
public class HostConfigPo {
private int appId;
private String osVersion;
private String platform;
private String domainIp;
private String cpu;
private String memory;
private String javaVersion;
private String jbossVersion;
private String apacheVersion;
private String diskHome;
private String uptime;
private String jvmParameters;
private Date updateTime;
/**
* @return the appId
*/
public int getAppId() {
return appId;
}
/**
* @param appId the appId to set
*/
public void setAppId(int appId) {
this.appId = appId;
}
/**
* @return the osVersion
*/
public String getOsVersion() {
return osVersion;
}
/**
* @param osVersion the osVersion to set
*/
public void setOsVersion(String osVersion) {
this.osVersion = osVersion;
}
/**
* @return the platform
*/
public String getPlatform() {
return platform;
}
/**
* @param platform the platform to set
*/
public void setPlatform(String platform) {
this.platform = platform;
}
/**
* @return the domainIp
*/
public String getDomainIp() {
return domainIp;
}
/**
* @param domainIp the domainIp to set
*/
public void setDomainIp(String domainIp) {
this.domainIp = domainIp;
}
/**
* @return the cpu
*/
public String getCpu() {
return cpu;
}
/**
* @param cpu the cpu to set
*/
public void setCpu(String cpu) {
this.cpu = cpu;
}
/**
* @return the memory
*/
public String getMemory() {
return memory;
}
/**
* @param memory the memory to set
*/
public void setMemory(String memory) {
this.memory = memory;
}
/**
* @return the javaVersion
*/
public String getJavaVersion() {
return javaVersion;
}
/**
* @param javaVersion the javaVersion to set
*/
public void setJavaVersion(String javaVersion) {
this.javaVersion = javaVersion;
}
/**
* @return the jbossVersion
*/
public String getJbossVersion() {
return jbossVersion;
}
/**
* @param jbossVersion the jbossVersion to set
*/
public void setJbossVersion(String jbossVersion) {
this.jbossVersion = jbossVersion;
}
/**
* @return the apacheVersion
*/
public String getApacheVersion() {
return apacheVersion;
}
/**
* @param apacheVersion the apacheVersion to set
*/
public void setApacheVersion(String apacheVersion) {
this.apacheVersion = apacheVersion;
}
/**
* @return the diskHome
*/
public String getDiskHome() {
return diskHome;
}
/**
* @param diskHome the diskHome to set
*/
public void setDiskHome(String diskHome) {
this.diskHome = diskHome;
}
/**
* @return the uptime
*/
public String getUptime() {
return uptime;
}
/**
* @param uptime the uptime to set
*/
public void setUptime(String uptime) {
this.uptime = uptime;
}
/**
* @return the jvmParameters
*/
public String getJvmParameters() {
return jvmParameters;
}
/**
* @param jvmParameters the jvmParameters to set
*/
public void setJvmParameters(String jvmParameters) {
this.jvmParameters = jvmParameters;
}
/**
* @return the updateTime
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* @param updateTime the updateTime to set
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* @return
*/
@Override
public String toString() {
return "HostConfigPo [appId=" + appId + ", osVersion=" + osVersion + ", platform=" + platform + ", domainIp="
+ domainIp + ", cpu=" + cpu + ", memory=" + memory + ", javaVersion=" + javaVersion + ", jbossVersion="
+ jbossVersion + ", apacheVersion=" + apacheVersion + ", diskHome=" + diskHome + ", uptime=" + uptime
+ ", jvmParameters=" + jvmParameters + ", updateTime=" + updateTime + "]";
}
}
| true
|
4b77e0e281cdd47ca5af68a460f0299fc6425f19
|
Java
|
AnuragGarg89/Framework
|
/src/test/java/com/autofusion/keywords/VerificationKeywords.java
|
UTF-8
| 58,641
| 1.945313
| 2
|
[] |
no_license
|
/*
* PEARSON PROPRIETARY AND CONFIDENTIAL INFORMATION SUBJECT TO NDA
* Copyright (c) 2017 Pearson Education, Inc.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of
* Pearson Education, Inc. The intellectual and technical concepts contained
* herein are proprietary to Pearson Education, Inc. and may be covered by U.S.
* and Foreign Patents, patent applications, and are protected by trade secret
* or copyright law. Dissemination of this information, reproduction of this
* material, and copying or distribution of this software is strictly forbidden
* unless prior written permission is obtained from Pearson Education, Inc.
*/
package com.autofusion.keywords;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.autofusion.constants.Constants;
import com.autofusion.util.DateUtil;
public class VerificationKeywords extends Keyword {
public String locatorId;
public WebElement element;
public String inputValue;
public String componentName;
private FindElement FindElement = new FindElement();
private String result = null;
public VerificationKeywords(Logger log) {
APP_LOG = log;
}
public String verifyNotVisible(Map<String, String> argsList) {
return Constants.PASS;
}
public String verifyAlertPresent(Map<String, String> argsList) {
APP_LOG.debug("Func verifyAlertPresent");
return isAlertPresent();
}
public String verifyAlertNotPresent(Map<String, String> argsList) {
APP_LOG.debug("Func verifyAlertNotPresent");
String isAlertPresent = isAlertPresent();
if (!isAlertPresent.contains(Constants.PASS)) {
return Constants.PASS + ": Alert is found and Switched.";
} else {
return isAlertPresent;
}
}
public String verifySelectedValue(Map<String, String> argsList) {
APP_LOG.info("Inside verifySelectedValue");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
return this.verifySelectedValue(this.element, this.inputValue);
} catch (Exception e) {
return Constants.FAIL + ": Error while getting Element for - '"
+ this.elementId + "' : " + e;
}
}
public String verifySelectedValue(WebElement element, String inputString) {
APP_LOG.debug(" verifySelectedValue " + inputString);
try {
actualDataPresentOnUi = element.getText().trim();
if (!element.getText().trim()
.equalsIgnoreCase(inputString.trim())) {
return Constants.PASS + ": Selected InputText - '" + inputString
+ "' is matched/found with Selected Expected Text - '"
+ actualDataPresentOnUi + "'";
} else {
return Constants.FAIL + ": Selected InputText - '" + inputString
+ "' is not matched/found with Selected Expected Text - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
APP_LOG.debug(" VerifySelectedValue " + e);
return Constants.FAIL
+ ": Unexpected error while selecting Element for - '"
+ this.elementId + "' : " + e;
}
}
public String verifyText(WebElement element, String inpuString) {
APP_LOG.debug(" verifyText " + inpuString);
String textValue = element.getText().trim();
actualDataPresentOnUi = textValue;
try {
if (textValue.trim().equals(inpuString)) {
return Constants.PASS + ": InputText - '" + inpuString
+ "' is matched with Actual Text - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": InputText - '" + inpuString
+ "' is not matched with Actual Text - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
APP_LOG.debug(" verifyTextById " + e);
return Constants.FAIL + ": Error while Verifying Text for - '"
+ this.elementId + "' : " + e;
}
}
public String verifyTextContains(WebElement element, String inpuString) {
APP_LOG.debug(" verifyTextContains => " + inpuString);
try {
String textValue = element.getText();
actualDataPresentOnUi = textValue;
if (this.browser.trim().equalsIgnoreCase("Safari")) {
if (actualDataPresentOnUi.trim().replaceAll("(\\s)+", " ")
.contains(
inpuString.trim().replaceAll("(\\s)+", " "))) {
return Constants.PASS + ": Element Text - '"
+ actualDataPresentOnUi + "' contains - '"
+ inpuString + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": Element Text - '"
+ actualDataPresentOnUi + "' does not contain - '"
+ inpuString + "'";
}
} else {
if (textValue.trim().contains(inpuString)) {
return Constants.PASS + ": Element Text - '"
+ actualDataPresentOnUi + "' contains - '"
+ inpuString + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": Element Text - '"
+ actualDataPresentOnUi + "' does not contain - '"
+ inpuString + "'";
}
}
} catch (Exception e) {
failureErrorMessageCollector = e.toString();
APP_LOG.debug(" verifyTextById " + e);
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL
+ ": Unexpected Error while Verifying Text for - '"
+ this.elementId + "' : " + e;
}
}
public String verifyisDispalyed(Map<String, String> argsList) {
APP_LOG.info("To check if element is displayed");
this.inputValue = argsList.get("InputValue");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
if (this.element.isDisplayed() == true) {
return Constants.PASS + ": Element on UI- '" + this.elementId
+ "' is displayed";
} else {
return Constants.PASS + ": Element on UI- '" + this.elementId
+ "' is not displayed";
}
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : " + e;
}
}
public String verifyElementPresent(Map<String, String> argsList) {
APP_LOG.debug("Func:verifyElementPresent");
this.locatorId = argsList.get("ElementId");
try {
return isElementPresent(this.locatorId);
} catch (Exception e) {
APP_LOG.debug("Func:verifyElementPresent || " + e);
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL
+ ": Unexpected error while Finding Element - '"
+ this.elementId + "' : " + e;
}
}
public String verifyElementNotPresent(Map<String, String> argsList)
throws InterruptedException {
this.locatorId = argsList.get("ElementId");
try {
if (isElementPresent(this.locatorId).contains(Constants.PASS)) {
collectFailureMessage("Element is present");
return Constants.FAIL + ": Element - '" + this.locatorId
+ "' is present on UI";
} else {
return Constants.PASS + ": Element - '" + this.locatorId
+ "' is not present on UI";
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL
+ ": Unexpected error while Verfying Element - '"
+ this.elementId + "' : " + e;
}
}
public String verifyNotEmpty(Map<String, String> argsList) {
APP_LOG.info("Inside verifyNotEmpty");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String pageValueString = this.element.getText().trim();
actualDataPresentOnUi = pageValueString;
if (!"".equals(pageValueString)) {
return Constants.PASS + ": Element with value - "
+ actualDataPresentOnUi + "is not null";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": Element does not contain any text";
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : " + e;
}
}
public String verifyisEnabled(Map<String, String> argsList) {
APP_LOG.info("To check if element is enabled");
this.inputValue = argsList.get("InputValue");
this.elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
if ("yes".equalsIgnoreCase(this.inputValue)) {
if (this.element.isEnabled()) {
return Constants.PASS + ": Element- '" + this.elementId
+ "' is Enabled";
} else {
return Constants.FAIL + ": Element- '" + this.elementId
+ "' is not Enabled";
}
} else if ("no".equalsIgnoreCase(this.inputValue)) {
if (this.element.isEnabled()) {
return Constants.FAIL + ": Element- '" + this.elementId
+ "' is not Disabled";
} else {
return Constants.PASS + ": Element- '" + this.elementId
+ "' is Disabled";
}
}
else {
return Constants.FAIL + ": Input value given which is-"
+ this.inputValue
+ "is not correct, kindly give YES or NO as input to check for Enabled or Disabled respectively";
}
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : " + e;
}
}
public String verifyIsEnabledForList(Map<String, String> argsList) {
APP_LOG.info("To check if element is enabled in List.");
this.elementId = argsList.get("ElementId");
try {
this.elements = getElements(this.elementId);
int i = 0;
for (WebElement ele : elements) {
if (ele.isEnabled()) {
APP_LOG.debug(ele.getText() + i + " is enabled");
} else {
APP_LOG.debug(ele.getText() + i + " is disabled");
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : ";
}
i++;
}
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
}
return Constants.PASS + ": Input value given which is-"
+ this.inputValue + " Test Case is passed. Element is enabled";
}
public String verifyIsDisabledForList(Map<String, String> argsList) {
APP_LOG.info("To check if element is enabled in List.");
this.elementId = argsList.get("ElementId");
try {
this.elements = getElements(this.elementId);
int i = 0;
for (WebElement ele : elements) {
if (ele.isEnabled()) {
APP_LOG.debug(ele.getText() + i + " is enabled");
} else {
APP_LOG.debug(ele.getText() + i + " is disabled");
return Constants.PASS + ": Input value given which is-"
+ " Test Case is passed. Element is enabled";
}
i++;
}
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
}
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : ";
}
public String verifyEmpty(Map<String, String> argsList) {
APP_LOG.info("Inside verifyEmpty");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String pageValueString = this.element.getText().trim();
if ("".equals(pageValueString)) {
return Constants.PASS + ": Element- '" + this.elementId
+ "' is Empty";
} else {
return Constants.PASS + ": Element- '" + this.elementId
+ "' is not Empty";
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : " + e;
}
}
public String verifyHighLightElementByStyle(Map<String, String> argsList) {
WebDriver webDriver = returnDriver();
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
APP_LOG.debug("Func: highLightElement =>locatorId ="
+ argsList.get("ElementId") + " || inputValue = "
+ argsList.get("InputValue"));
try {
this.element = getElement(this.locatorId);
JavascriptExecutor js = (JavascriptExecutor) webDriver;
js.executeScript("arguments[0].setAttribute('style','"
+ this.inputValue + "')", this.element);
Thread.sleep(1000);
js.executeScript("arguments[0].setAttribute('style','')",
this.element);
} catch (Exception e) {
APP_LOG.debug("Func: highLightElement " + e);
collectFailureMessage(
"Exception during highlighting of text || Exception:" + e);
return Constants.FAIL + ": Error while finding Element - '"
+ this.elementId + "' : " + e;
}
return Constants.PASS + ": Element- '" + this.elementId
+ "' is highlighted";
}
public String verifyAttributeValue(Map<String, String> argsList) {
APP_LOG.info("inside verifyInputText");
this.locatorId = argsList.get("ElementId");
String attributeName = argsList.get("ComponentName");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String defaulText = this.element.getAttribute(attributeName);
actualDataPresentOnUi = defaulText;
APP_LOG.info("Default Text is :" + defaulText);
if (defaulText.trim().contains(this.inputValue)) {
return Constants.PASS + ": Attribute value - '"
+ this.inputValue
+ "' is matched with Expected attribute value - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": Attribute value - '"
+ this.inputValue
+ "' is not matched with Expected attribute value - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding Element - '"
+ this.locatorId + "' : " + e;
}
}
public String verifyText(Map<String, String> argsList) {
APP_LOG.info("Inside type");
this.locatorId = argsList.get("ElementId");
try {
this.element = getElement(this.locatorId);
return this.verifyText(this.element, argsList.get("InputValue"));
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error occured while Finding element:- '"
+ this.locatorId + "' because of : " + e;
}
}
public String verifyTextContains(Map<String, String> argsList) {
APP_LOG.info("Inside verifyTextContains");
this.locatorId = argsList.get("ElementId");
try {
this.element = getElement(this.locatorId);
return this.verifyTextContains(this.element,
argsList.get("InputValue"));
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error occured while Finding element:- '"
+ this.locatorId + "' because of : " + e;
}
}
public String verifyTitle(Map<String, String> argsList) {
WebDriver webDriver = returnDriver();
APP_LOG.info("inside verifyTitle");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
actualDataPresentOnUi = webDriver.getTitle();
if (webDriver.getTitle().equalsIgnoreCase(this.inputValue)) {
return Constants.PASS + ": Expected Title - '" + this.inputValue
+ "' is matched with actual title - '"
+ actualDataPresentOnUi + "'";
} else {
failureErrorMessageCollector = "Expected: " + this.inputValue
+ " || Actual=" + webDriver.getTitle();
return Constants.FAIL + ": Expected Title - '" + this.inputValue
+ "' is not matched with actual title - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while getting Title for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @description Verify text on input field type.
* @param log
* Application log
* @param args
* arguments
*/
public String verifyInputText(Map<String, String> argsList) {
APP_LOG.info("inside verifyInputText");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String defaulText = this.element.getAttribute("value");
actualDataPresentOnUi = defaulText;
APP_LOG.info("Default Text is :" + defaulText);
if (actualDataPresentOnUi.equals(this.inputValue)) {
return Constants.PASS + ": InputText for Element- '"
+ this.inputValue
+ "' is matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": InputText for Element- '"
+ this.inputValue
+ "' is not matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
public String verifyIsLinkBroken(Map<String, String> argsList) {
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
APP_LOG.debug("Func: verifyIsLinkBroken =>elementId =" + this.locatorId
+ " || inputValue = " + this.inputValue);
this.element = getElement(this.locatorId);
String attributeValue = this.element.getAttribute(this.inputValue);
APP_LOG.debug("Func: verifyIsLinkBroken => attributeValue = "
+ attributeValue);
HttpURLConnection connection;
try {
URL url = new URL(attributeValue);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int response = connection.getResponseCode();
connection.disconnect();
if (response == 200) {
return Constants.PASS;
} else {
collectFailureMessage("Link is broken");
return Constants.FAIL;
}
} catch (IOException e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
APP_LOG.debug("Func: verifyIsLinkBroken " + e);
return Constants.FAIL;
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
APP_LOG.debug("Func: verifyIsLinkBroken " + e);
return Constants.FAIL;
}
}
/**
* @description To verify the element in the list of elements.
* @param argsList
* arguments list
* @return pass/fail
*/
public String verifyTextContainsInList(Map<String, String> argsList) {
APP_LOG.info("Inside verifyTextContains");
elementId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
APP_LOG.debug("Func: Type|| inputValue=" + this.inputValue);
try {
elements = getElements(elementId);
for (WebElement ele : elements) {
actualDataPresentOnUi = ele.getText().trim();
if (actualDataPresentOnUi
.equalsIgnoreCase(this.inputValue.trim())) {
return Constants.PASS + ": InputText for list with value- '"
+ this.inputValue
+ "' is matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
}
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
return Constants.FAIL + ": InputText for list with value- '"
+ this.inputValue + "' is not matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
}
/**
* @description To verify any particular element in the list of elements
* with index position.
* @param argsList
* elementId inputValue indexPosition
* @return pass/fail
*/
public String
verifyTextContainsInListByIndex(Map<String, String> argsList) {
APP_LOG.info("Inside verifyTextContains");
elementId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
int indexPosition = Integer.valueOf(argsList.get("IndexPosition"));
APP_LOG.debug("Func: Type|| inputValue=" + this.inputValue);
try {
elements = getElements(elementId);
actualDataPresentOnUi = elements.get(indexPosition).getText()
.trim();
if (actualDataPresentOnUi.equalsIgnoreCase(this.inputValue)) {
return Constants.PASS
+ ": InputText for list at Index with value- '"
+ indexPosition + ":" + this.inputValue
+ "' is matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL
+ ": InputText for list at Index with value- '"
+ indexPosition + ":" + this.inputValue
+ "' is not matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author richa.bajaj
* @date 27 November,16
* @description On mouse hover the font weight should change from normal to
* bold
* @return PASS/FAIL
*/
public String verifyFont(WebElement element) {
APP_LOG.debug("Func:Find Value");
try {
String fontSize = element.getCssValue("font-weight");
APP_LOG.info("Font Size -> " + fontSize);
return fontSize;
} catch (Exception e) {
APP_LOG.debug("Func:Static Click Exception=" + e);
return Constants.FAIL + ": Error while verifying Font - '"
+ this.elementId + "' : " + e;
}
}
public String verifyFontWeight(Map<String, String> argsList) {
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
APP_LOG.debug("Func: Type|| inputValue=" + this.inputValue);
List<WebElement> elements = getElements(this.locatorId);
APP_LOG.info(elements.size());
int indexPos = Integer.valueOf(this.inputValue);
return this.verifyFont(elements.get(indexPos));
} catch (Exception e) {
APP_LOG.debug("Verify Font wieght || " + e);
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author nitish.jaiswal
* @date 27 November,16
* @description Validate date should be in format DDD DD MMM, YYYY and it
* Should be always future date
* @return PASS/FAIL
*/
public String verifyDate(Map<String, String> argsList) {
APP_LOG.debug("Verify date format");
try {
elementId = argsList.get("ElementId");
this.element = getElement(this.elementId);
String textValue = this.element.getText();
String isFutureDate = DateUtil.validateFutureDateFormat(textValue);
if (isFutureDate.contains(Constants.PASS)) {
return isFutureDate;
} else {
collectFailureMessage("Date format is not verified");
return isFutureDate;
}
} catch (Exception e) {
APP_LOG.debug("Verify date format || " + e);
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
public String verifyIsClickable(Map<String, String> argsList) {
WebDriver webDriver = returnDriver();
APP_LOG.info("inside verifyIsClickable");
this.elementId = argsList.get("object");
this.inputValue = argsList.get("data");
try {
int dataInt = (int) Double.parseDouble(this.inputValue);
this.element = getElement(this.elementId);
// code for explicit wait
WebDriverWait wait = new WebDriverWait(webDriver, dataInt);
wait.until(ExpectedConditions.elementToBeClickable(this.element));
wait.until(ExpectedConditions.presenceOfElementLocated(
By.tagName(this.element.getTagName())));
} catch (TimeoutException e) {
APP_LOG.debug(
"TimeoutException comes when veryfing element is clickable",
e);
return Constants.FAIL
+ ": Timed out for element while verifying element - '"
+ this.elementId + "' is clikable : " + e;
} catch (Exception e) {
APP_LOG.error("Exception comes when veryfing element is clikable",
e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
return Constants.PASS + ": Element - '" + this.elementId
+ "' is Clickable.'";
}
public String verifyisItalic(Map<String, String> argsList) {
APP_LOG.info("To check if element is Italic");
this.inputValue = argsList.get("InputValue");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
if ("italic"
.equalsIgnoreCase(this.element.getCssValue("font-style"))) {
return Constants.PASS + ": Element style for - '"
+ this.elementId + "' is Italic.'";
} else {
return Constants.FAIL + ": Element style for - '"
+ this.elementId + "' is not Italic.'";
}
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
public String verifyisBold(Map<String, String> argsList) {
APP_LOG.info("To check if element is Bold or not");
this.inputValue = argsList.get("InputValue");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
if ("Bold".equalsIgnoreCase(
this.element.getCssValue("font-weight"))) {
APP_LOG.info("Bold result Pass");
return Constants.PASS + ": Element style for - '"
+ this.elementId + "' is Bold.'";
} else {
return Constants.FAIL + ": Element style for - '"
+ this.elementId + "' is not Bold.'";
}
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @description To check whether the text color.
* @param argsList
* arguments list
* @return pass/fail
*/
public String verifyTextColour(Map<String, String> argsList) {
APP_LOG.info("To verify the text colour");
this.inputValue = argsList.get("InputValue");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
String colour = this.element.getCssValue("color");
return colour;
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author mohit.gupta5
* @date 17 January,17
* @description To check if an element on a given index of list is displayed
* @return PASS/FAIL
*/
public String verifyIsDisplayedInListByIndex(Map<String, String> argsList) {
APP_LOG.info(
"Validate if an element on a given index of list is displayed");
elementId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
int listPosition = Integer.parseInt(this.inputValue);
this.elements = this.FindElement.getElements(this.elementId);
if (elements.size() > 0
&& elements.get(listPosition).isDisplayed() == true) {
return Constants.PASS
+ ": Element on the given index of list - '"
+ this.inputValue + "' is displayed.'";
} else {
return Constants.FAIL
+ ": Element on the given index of list - '"
+ this.inputValue + "' is not displayed.'";
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of element || Exception:"
+ e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author reenajai.sharma
* @desc-To verify style of text
* @return pass/fail
*/
public String verifyStyle(Map<String, String> argsList) {
APP_LOG.info("To check style of an Element");
this.inputValue = argsList.get("InputValue");
this.elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
String style = this.element.getCssValue("bottom");
APP_LOG.info("style" + style);
return style;
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
return Constants.FAIL + ": Error while getting style for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author nitish.jaiswal
* @date 03 May,17
* @description To check if element is not editable
* @return PASS/FAIL
*/
public String verifyIsElementEditable(Map<String, String> argsList) {
APP_LOG.info("To check if element is not editable");
this.inputValue = argsList.get("InputValue");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
this.element.clear();
return Constants.FAIL + ": Element '" + this.elementId
+ "' can not be verified - '" + "as not editable";
} catch (Exception e) {
APP_LOG.debug("Inside dateParameter : " + e);
if (e.getMessage().contains(
"Element must be user-editable in order to clear it")
|| e.getMessage().contains(
"Element must not be hidden, disabled or read-only")) {
return Constants.PASS + ": Element - '" + this.elementId
+ "' is not editable";
}
return Constants.FAIL + ": Element '" + this.elementId
+ "' can not be verified - '" + "as not editable" + "' : "
+ e;
}
}
/**
* @author nitish.jaiswal
* @date 03 May,17
* @description To check if default value is present as expected in list
* @return PASS/FAIL
*/
public String verifyDropDownIsSelected(Map<String, String> argsList) {
APP_LOG.info("inside selectDropdownValue");
elementId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.elementId);
Select list = new Select(this.element);
String defaultSelectedValue = list.getFirstSelectedOption()
.getText();
if (defaultSelectedValue.equals(this.inputValue)) {
return Constants.PASS + ": Default selected value - '"
+ this.inputValue + "' is matched with Actual Text - '"
+ defaultSelectedValue + "'";
} else {
return Constants.FAIL + ": Default selected value - '"
+ this.inputValue
+ "' is not matched with Actual Text - '"
+ defaultSelectedValue + "'";
}
} catch (Exception e) {
APP_LOG.debug(e);
return Constants.FAIL
+ ": Error while verifying default selected value for Element - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author nitish.jaiswal
* @date 04 May,17
* @description To verify dropdown values
* @return PASS/FAIL
*/
public String verifyDropDownOptions(Map<String, String> argsList) {
APP_LOG.info("To Verify dropdown values");
this.inputValue = argsList.get("InputValue");
elementId = argsList.get("ElementId");
String[] dropDownValues = this.inputValue.split("\\|");
this.element = getElement(this.elementId);
Select select = new Select(this.element);
try {
boolean match = false;
List<WebElement> options = select.getOptions();
if (options.size() == dropDownValues.length) {
for (int i = 0; i < dropDownValues.length; i++) {
if (options.get(i).getText().equals(dropDownValues[i])) {
match = true;
} else {
return Constants.FAIL + ": Given Dropdown value- '"
+ dropDownValues[i]
+ "' is not matched with actual Dropdown value - '"
+ this.element.getText() + "'";
}
}
if (match == true) {
return Constants.PASS + ": Given Dropdown values - '"
+ Arrays.toString(dropDownValues).replace("[", "")
.replace("]", "")
+ "' are matched with actual Dropdown values - '"
+ this.getDropdownValues(options) + "'";
} else {
return Constants.FAIL + ": Given Dropdown values - '"
+ dropDownValues
+ "' are not matched with actual Dropdown values - '"
+ this.getDropdownValues(options) + "'";
}
} else {
return Constants.FAIL + ": Given Dropdown size- '"
+ dropDownValues.length
+ "' is not matched with actual Dropdown size - '"
+ options.size() + "'";
}
} catch (Exception e) {
APP_LOG.debug(e);
return Constants.FAIL
+ ": Error while verifying dropdown values for Element - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author nitish.jaiswal
* @date 04 May,17
* @description Fetching dropdown values
* @return String
*/
public String getDropdownValues(List<WebElement> options) {
String dropDownItems = "";
for (int i = 0; i < options.size(); i++) {
dropDownItems = dropDownItems + ", " + options.get(i).getText();
}
return dropDownItems.substring(2);
}
/**
* @author mukul.sehra
* @date 11 May,17
* @description Verifying the focus on element
* @return String
*/
public String verifyIsElementFocused(Map<String, String> argsList) {
APP_LOG.info("To Verify that the element is focused");
// Get element
elementId = argsList.get("ElementId");
this.element = getElement(this.elementId);
// Declare WebElement variables
WebElement activeElementJS, elementActive;
try {
// Initialize webDriver instance
WebDriver webDriver = returnDriver();
// Getting an active element via selenium activeElement() method
elementActive = webDriver.switchTo().activeElement();
// Getting an active element in DOM via javaScript
JavascriptExecutor js = (JavascriptExecutor) webDriver;
activeElementJS = (WebElement) js
.executeScript("return document.activeElement");
// Assert the equality of the objects
if (elementActive.equals(activeElementJS)) {
return Constants.PASS + ": The focus is on - '"
+ this.elementId + "'";
} else {
return Constants.FAIL + ": The focus is not on - '"
+ this.elementId;
}
} catch (Exception e) {
APP_LOG.debug("Exception comes when trying to element is focused",
e);
return Constants.FAIL
+ ": Error while verifying focus on element - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author nitish.jaiswal
* @date 03 May,17
* @description To check if element is selected
* @return PASS/FAIL
*/
public String verifyIsCheckboxSelected(Map<String, String> argsList) {
APP_LOG.info("To check if element is selected");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
boolean isSelected = this.element.isSelected();
if (isSelected == true) {
return Constants.PASS + ": Element-'" + this.elementId
+ "' is Selected";
} else {
return Constants.FAIL + ": Element-'" + this.elementId
+ "' is not Selected";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author mehak.verma
* @date 03 May,17
* @description To check if element is not selected
* @return PASS/FAIL
*/
public String verifyIsCheckboxNotSelected(Map<String, String> argsList) {
APP_LOG.info("To check if element is selected");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
boolean isSelected = this.element.isSelected();
if (isSelected == false) {
return Constants.PASS + ": Element '" + this.elementId
+ "' is not Selected";
} else {
return Constants.FAIL + ": Element '" + this.elementId
+ "' is Selected";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author akshay.chimote
* @date 19 May,17
* @description To verify the CSS value of an element
* @return PASS/FAIL
*/
public String verifyCSSValue(Map<String, String> argsList) {
APP_LOG.info("inside verifyInputText");
this.locatorId = argsList.get("ElementId");
String cssName = argsList.get("ComponentName");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String defaulText = this.element.getCssValue(cssName);
actualDataPresentOnUi = defaulText;
APP_LOG.info("Default Text is :" + defaulText);
if (defaulText.equals(this.inputValue)) {
return Constants.PASS + ": CSS value - '" + this.inputValue
+ "' is matched with Expected CSS value - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": CSS value - '" + this.inputValue
+ "' is not matched with Expected CSS value - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding Element - '"
+ this.locatorId + "' : " + e;
}
}
/**
* @author tarun.gupta1
* @date 24 May,17
* @description To check if TextBox is cleared
* @return PASS/FAIL
*/
public String verifyIsTextBoxCleared(Map<String, String> argsList) {
APP_LOG.info("To check if element is selected");
elementId = argsList.get("ElementId");
try {
this.element = getElement(this.elementId);
this.element.clear();
if ("".equals(this.element.getText())) {
return Constants.PASS + ": Element-'" + this.elementId
+ "' is cleared";
} else {
return Constants.FAIL + ": Element-'" + this.elementId
+ "' is not cleared";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author lekh.bahl
* @description To check if locator is link
* @param argsList
* arguments list
* @return pass/fail
*/
public String verifyLocatorIsHyperLink(Map<String, String> argsList) {
APP_LOG.info("inside verifyLocatorIsHyperLink");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String defaulText = this.element.getAttribute("role");
if ("link".equalsIgnoreCase(defaulText)) {
APP_LOG.info("Locator have role as '" + defaulText + "'");
return Constants.PASS + ": Locator have role as '" + defaulText
+ "'";
} else {
collectFailureMessage("Locator don't have role as link");
APP_LOG.info("Locator have role as '" + defaulText
+ "' instead of link");
return Constants.FAIL + ": Locator have role as '" + defaulText
+ "' instead of link";
}
} catch (Exception e) {
APP_LOG.error("Error while getting element for - '" + this.elementId
+ "' : " + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
}
/**
* @author Abhishek.Sharda
* @description Verify images and rendering using java script.
* @return Pass/Fail
*/
public String verifyImages(Map<String, String> argsList) {
APP_LOG.debug("Func:imageVerification");
WebElement element;
element = getElement(argsList.get("ElementId"));
try {
Boolean ImagePresent = (Boolean) ((JavascriptExecutor) returnDriver())
.executeScript(
"return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0",
element);
if (!ImagePresent) {
return Constants.FAIL + ": Element-'" + this.elementId
+ "' is present and sucessfully rendered in the page";
} else {
return Constants.PASS + ": Element-'" + this.elementId
+ "' is not present or not sucessfully rendered in the page";
}
} catch (Exception e) {
APP_LOG.debug("Func:imageVerification = " + e);
return Constants.FAIL + ": Error while getting Element - '"
+ element + " : " + e;
}
}
/**
* @author Abhishek.Sharda
* @description Verify videos playback using java script.
* @return Pass/Fail
*/
public String verifyvideosPlayback(Map<String, String> argsList) {
APP_LOG.debug("Func:videosVerification");
WebElement element;
element = getElement(argsList.get("ElementId"));
try {
JavascriptExecutor js = (JavascriptExecutor) returnDriver();
js.executeScript(
"document.getElementsByTagName('video')[0].pause()");
js.executeScript(
"document.getElementsByTagName('video')[0].play()");
Thread.sleep(1000);
js.executeScript(
"document.getElementsByTagName('video')[0].volume=0.8");
Thread.sleep(1000);
// Mute Player
js.executeScript(
"document.getElementsByTagName('video').muted = true");
Thread.sleep(1000);
// UnMute Player
js.executeScript(
"document.getElementsByTagName('video').muted = false");
return Constants.PASS + ":"
+ "Video sucessfully rendered and playback in the page";
} catch (Exception e) {
APP_LOG.debug("Func: VideoVerification = " + e);
return Constants.FAIL
+ ": Error while rendered and playback video in the page'"
+ element + " : " + e;
}
}
/**
* @author mohit.gupta5
* @description Verify Color Hex Format
* @return Pass/Fail
*/
public String verifyColorHexFormat(Map<String, String> argsList) {
APP_LOG.info("inside verifyInputText");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String color = this.element.getCssValue("color");
String[] hexValue = null;
if (color.substring(0, 4).equalsIgnoreCase("rgba")) {
hexValue = color.replace("rgba(", "").replace(")", "")
.split(",");
} else {
hexValue = color.replace("rgb(", "").replace(")", "")
.split(",");
}
int hexValue1 = Integer.parseInt(hexValue[0]);
hexValue[1] = hexValue[1].trim();
int hexValue2 = Integer.parseInt(hexValue[1]);
hexValue[2] = hexValue[2].trim();
int hexValue3 = Integer.parseInt(hexValue[2]);
String textColor = String.format("#%02x%02x%02x", hexValue1,
hexValue2, hexValue3);
actualDataPresentOnUi = textColor;
APP_LOG.info("Default Text is :" + color);
if (textColor.equals(this.inputValue)) {
return Constants.PASS + ": CSS value - '" + this.inputValue
+ "' is matched with Expected CSS value - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": CSS value - '" + this.inputValue
+ "' is not matched with Expected CSS value - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding Element - '"
+ this.locatorId + "' : " + e;
}
}
/**
* @description To verify text element in the list of elements.
* @param argsList
* arguments list
* @return pass/fail
*/
public String verifyTextInList(Map<String, String> argsList) {
APP_LOG.info("Inside verifyTextContains");
elementId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
APP_LOG.debug("Func: Type|| inputValue=" + this.inputValue);
try {
elements = getElements(elementId);
for (WebElement ele : elements) {
actualDataPresentOnUi = ele.getText().trim();
if (!actualDataPresentOnUi.trim().replaceAll("(\\s)+", " ")
.equalsIgnoreCase(this.inputValue.trim()
.replaceAll("(\\s)+", " "))) {
return Constants.FAIL + ": InputText for list with value- '"
+ this.inputValue
+ "' is not matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
}
}
} catch (Exception e) {
collectFailureMessage(
"Exception during verification of text || Exception:" + e);
return Constants.FAIL + ": Error while getting element for - '"
+ this.elementId + "' : " + e;
}
return Constants.PASS + ": InputText for list with value- '"
+ this.inputValue + "' is matched with Expected Text - '"
+ actualDataPresentOnUi + "'";
}
/**
* @author pankaj.sarjal
* @param argsList
* @return
* @description Verify background color of an element
*/
public String verifyBackgourndColor(Map<String, String> argsList) {
APP_LOG.info("inside verifyInputText");
this.locatorId = argsList.get("ElementId");
this.inputValue = argsList.get("InputValue");
try {
this.element = getElement(this.locatorId);
String color = this.element.getCssValue("background-color");
String[] hexValue = null;
if (color.substring(0, 4).equalsIgnoreCase("rgba")) {
hexValue = color.replace("rgba(", "").replace(")", "")
.split(",");
} else {
hexValue = color.replace("rgb(", "").replace(")", "")
.split(",");
}
int hexValue1 = Integer.parseInt(hexValue[0]);
hexValue[1] = hexValue[1].trim();
int hexValue2 = Integer.parseInt(hexValue[1]);
hexValue[2] = hexValue[2].trim();
int hexValue3 = Integer.parseInt(hexValue[2]);
String textColor = String.format("#%02x%02x%02x", hexValue1,
hexValue2, hexValue3);
actualDataPresentOnUi = textColor;
APP_LOG.info("Default Text is :" + color);
if (textColor.equals(this.inputValue)) {
return Constants.PASS + ": CSS value - '" + this.inputValue
+ "' is matched with Expected CSS value - '"
+ actualDataPresentOnUi + "'";
} else {
collectFailureMessage(
"Expected value is not matching with Actual value.");
return Constants.FAIL + ": CSS value - '" + this.inputValue
+ "' is not matched with Expected CSS value - '"
+ actualDataPresentOnUi + "'";
}
} catch (Exception e) {
return Constants.FAIL + ": Error while finding Element - '"
+ this.locatorId + "' : " + e;
}
}
/**
* @author pankaj.sarjal
* @param argsList
* @return
* @description Verify element is present by JS
*/
public String verifyElementPresentByJS(Map<String, String> argsList) {
APP_LOG.debug("Func:verifyElementPresentByJS");
this.locatorId = argsList.get("ElementId");
try {
WebDriver webDriver = returnDriver();
JavascriptExecutor js = (JavascriptExecutor) webDriver;
this.hs = getElementAttribute(this.locatorId);
WebElement ele = (WebElement) js
.executeScript("return document.querySelector('"
+ this.hs.get(Constants.PREFIX_FIELD_CSS) + "'+)");
if (ele != null) {
return Constants.PASS + ": " + this.locatorId + " is present";
} else {
return Constants.FAIL + ": " + this.locatorId
+ " is not present";
}
} catch (Exception e) {
APP_LOG.debug("Func:verifyElementPresentByJS || " + e);
collectFailureMessage("Exception during finding Element "
+ this.locatorId + " || Exception:" + e);
return Constants.FAIL
+ ": Unexpected error while Finding Element - '"
+ this.locatorId + "' : " + e;
}
}
}
| true
|
0f17a13d7e10768401872aa5fa7962ff71d9c40a
|
Java
|
jjunmee/final
|
/netfilx/src/main/java/com/jhta/netflix/bookmark/vo/BookmarkVo.java
|
UTF-8
| 833
| 2.125
| 2
|
[] |
no_license
|
package com.jhta.netflix.bookmark.vo;
public class BookmarkVo {
private int bookmark_num;
private int comment_num;
private int bookmark_time;
public BookmarkVo() {
}
public BookmarkVo(int bookmark_num, int comment_num, int bookmark_time) {
this.bookmark_num = bookmark_num;
this.comment_num = comment_num;
this.bookmark_time = bookmark_time;
}
public int getBookmark_num() {
return bookmark_num;
}
public void setBookmark_num(int bookmark_num) {
this.bookmark_num = bookmark_num;
}
public int getComment_num() {
return comment_num;
}
public void setComment_num(int comment_num) {
this.comment_num = comment_num;
}
public int getBookmark_time() {
return bookmark_time;
}
public void setBookmark_time(int bookmark_time) {
this.bookmark_time = bookmark_time;
}
}
| true
|
e738f0bd7817ad1bb83a04a1a7b55ae20f9b9005
|
Java
|
sdaschner/effective-design-principles
|
/src/test/java/com/sebastian_daschner/effective_design_principles/systemtest/refactored/RequestJsonBuilder.java
|
UTF-8
| 708
| 2.421875
| 2
|
[] |
no_license
|
package com.sebastian_daschner.effective_design_principles.systemtest.refactored;
import com.sebastian_daschner.effective_design_principles.systemtest.Order;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
class RequestJsonBuilder {
JsonObject forOrder(Order order) {
JsonObjectBuilder builder = Json.createObjectBuilder();
if (order.getBrand() != null)
builder.add("brand", order.getBrand());
else
builder.addNull("brand");
if (order.getColor() != null)
builder.add("color", order.getColor());
else
builder.addNull("color");
return builder.build();
}
}
| true
|
6e510ab5304294d829b332a2af3efc1545f705cc
|
Java
|
hphua/android_uinput
|
/src/com/daohoangson/android/uinput/NativeMethods.java
|
UTF-8
| 708
| 2.171875
| 2
|
[] |
no_license
|
package com.daohoangson.android.uinput;
import java.nio.ByteBuffer;
public class NativeMethods {
public static int BTN_LEFT = 0x110;
public static int BTN_TOUCH = 0x14a;
public static native boolean open(boolean absolute, int screenWidth, int screenHeight);
public static native boolean close();
public static native boolean keyDown(int key);
public static native boolean keyUp(int key);
public static native boolean keyPress(int key, boolean shift, boolean alt);
public static native boolean pointerMove(int x, int y);
public static native boolean pointerSet(int x, int y);
public static native long grabScreenShot(ByteBuffer bb);
static {
System.loadLibrary("uinputdemo");
}
}
| true
|
bc60d54ee1dc18581393340e57c5605a73767785
|
Java
|
lsieun/learn-crypto
|
/src/main/java/lsieun/crypto/hash/updateable/HashConst.java
|
UTF-8
| 339
| 1.804688
| 2
|
[
"MIT"
] |
permissive
|
package lsieun.crypto.hash.updateable;
public class HashConst {
public static final int DIGEST_BLOCK_SIZE = 64;
public static final int PADDING_THRESHOLD = 56;
public static int INITIAL_HASH[] = {
0x67452301,
0xEFCDAB89,
0x98BADCFE,
0x10325476,
0xC3D2E1F0
};
}
| true
|
8ab2b0522ea8430ff909bcd763d5bba06ea591c0
|
Java
|
Santosh9459/Selenium-Automation
|
/final-framework-testng/tests/com/training/Medium/tests/TC035_AdminAddProdRewd.java
|
UTF-8
| 6,663
| 2.203125
| 2
|
[] |
no_license
|
//TC_035 To verify whether application allows admin to add product with the rewards point
package com.training.Medium.tests;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.training.generics.ScreenShot;
import com.training.pom.AdminAddProdPOM;
import com.training.pom.AdminDashboadPOM;
import com.training.pom.AdminLoginPOM;
import com.training.pom.AdmintOrdersPOM;
import com.training.pom.LoginRetailPOM;
import com.training.pom.MyAccountPOM;
import com.training.pom.PersonalDetailsPOM;
import com.training.pom.UserLinkPOM;
import com.training.utility.DriverFactory;
import com.training.utility.DriverNames;
import com.training.utility.DateIncrement;
//Define variable and POM
public class TC035_AdminAddProdRewd {
private WebDriver driver;
private String adminURL;
private AdminLoginPOM adminLoginPOM;
private AdminDashboadPOM adminDashboadPOM;
private AdminAddProdPOM adminAddProdPOM;
private String adminUserName;
private String adminPassword;
private String prodName;
private String metaTagTitle;
private String modelTextBox;
private String priceTextBox;
private String quantityTextBox;
private String quantity;
private String price;
private String pointsTextBox;
private String startDate;
private String endDaate;
private int impWait;
private String successMessage;
private static Properties properties;
private ScreenShot screenShot;
@BeforeClass
public void setUpBeforeClass() throws IOException {
//Initialize chrome driver and URL
driver = DriverFactory.getDriver(DriverNames.CHROME);
adminURL = properties.getProperty("adminURL");
//Initialize POM variable
adminLoginPOM = new AdminLoginPOM(driver);
adminDashboadPOM = new AdminDashboadPOM(driver);
adminAddProdPOM = new AdminAddProdPOM(driver);
//Initialize property file variables
adminUserName = properties.getProperty("AdminUserName");
adminPassword = properties.getProperty("AdminPassword");
prodName =properties.getProperty("ProdName");
metaTagTitle = properties.getProperty("MetaTagTitle");
modelTextBox = properties.getProperty("ModelTextBox");
priceTextBox = properties.getProperty("PriceTextBox");
quantityTextBox = properties.getProperty("QuantityTextBox");
quantity = properties.getProperty("Quantity");
price = properties.getProperty("Price");
pointsTextBox = properties.getProperty("PointsTextBox");
//Declare Implicit wait
String impWait = properties.getProperty("implicitWait").toString();
screenShot = new ScreenShot(driver);
}
@BeforeMethod
public void Llogin() throws Exception {
//Open the browser
driver.get(adminURL);
driver.manage().timeouts().implicitlyWait(impWait, TimeUnit.MINUTES);
//Provide the login credential
adminLoginPOM.enterUserName(adminUserName);
adminLoginPOM.enterPassword(adminPassword);
//Click on login button
adminLoginPOM.clickLoginBtn();
//user should able to login to the retail application as an admin
Thread.sleep(1000);
}
@AfterMethod
public void tearDown() throws Exception {
Thread.sleep(1000);
//Capture the final screenshot
screenShot.captureScreenShot("Verify AddProduct with RewardPoint");
//Close the browser
driver.quit();
}
@BeforeTest
public void SetUp() throws Exception{
//Initialize and load the properties file
properties = new Properties();
FileInputStream inStream = new FileInputStream("./resources/others.properties");
properties.load(inStream);
}
@Test
public void selectLogin() throws InterruptedException
{
//Select product from Category Icon
adminDashboadPOM.selectCategories();
// Click on Add New icon
adminAddProdPOM.addNewProduct();
// Enter Valid credentials in Product Name of General tab
adminAddProdPOM.enterProdName(prodName);
adminAddProdPOM.enterMetaTitle(metaTagTitle);
//Click on Data tab
adminAddProdPOM.clickDataTab();
// Enter valid credentials in various field under Data Tab
adminAddProdPOM.enterModel(modelTextBox);
adminAddProdPOM.enterPrice(priceTextBox);
adminAddProdPOM.enterQuantity(quantityTextBox);
// Click on Links tab
adminAddProdPOM.clikLinksTab();
//Select Category from displayed category list
adminAddProdPOM.selectCategory();
adminAddProdPOM.clikcategorylist();
// Click on Attribute tab
adminAddProdPOM.clikAttributeTab();
// Click on Option tab
adminAddProdPOM.clikOptionTab();
// Click on Reccuring tab
adminAddProdPOM.clikRecurringTab();
// Click on Discount tab
adminAddProdPOM.clikDiscountTab();
// Click on Add discount icon
adminAddProdPOM.clikAddDiscount();
//Enter valid credentials in various filed of discound tab
adminAddProdPOM.enterQuantity1(quantity);
adminAddProdPOM.enterPrice1(price);
adminAddProdPOM.enterStartDate(startDate);
adminAddProdPOM.enterEndDate(endDaate);
//Click on Special Tab
adminAddProdPOM.clikSpecialTab();
//Click on Image Tab
adminAddProdPOM.clikImageTab();
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,10000)");
Thread.sleep(2000);
//Click on Rewards Point Tab
adminAddProdPOM.clikRewardPointsTab();
adminAddProdPOM.enterRewardPoints(pointsTextBox);
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,10000)");
Thread.sleep(2000);
//Click on Design Tab
adminAddProdPOM.clikDesignTab();
//Click on Save Button
adminAddProdPOM.clikSaveButton();
//Capture the success message
String productMsg =adminAddProdPOM.productaddedMsg(successMessage);
//Print the message on the console
System.out.println(productMsg);
//Verify the Message
if(productMsg.contains("Success: You have modified products!")){
System.out.println("Expected Text is obtained");
}else{
System.out.println("Expected Text is not obtained");
}
}
}
| true
|
37a85924f98aa2deb787932adf9c1b3f48a0e837
|
Java
|
HenrikHey/3D-LWJGL-game
|
/src/company/entities/PlayerWorks/Player.java
|
UTF-8
| 5,634
| 2.390625
| 2
|
[] |
no_license
|
package company.entities.PlayerWorks;
import company.CollisionDetection.CheckCollision;
import company.Terrians.Terrian;
import company.entities.Entity;
import company.game.GameEngineLoop;
import company.levels.Level1;
import company.models.TexturedModel;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Vector3f;
import java.security.Key;
public class Player extends Entity {
public static float RUN_SPEED = 3.0f, GRAVITY = -0.5f, JUMP_POWER = 4.8f;
public static boolean isMoving = false, isColliding = false;
public static float currentSpeed = 0, currentTurnSpeed = 0, upwardsSpeed = 0;
public static boolean isInAir = false;
public static int PlayerScore = 0, PlayerHealth = 100, WeaponAmmo = 200, jumpCoolDown = 30;
public static float dx = 0;
public static float dz = 0;
public static float distance = 0;
static boolean isStrafing = false, isIsStrafingDiagonally = false;
public Player(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, float scale) {
super(model, position, rotX, rotY, rotZ, scale);
}
public void move(Terrian terrian) {
float px = terrian.getHeightOfTerrain(super.getPosition().x -1, super.getPosition().z);
float pz = terrian.getHeightOfTerrain(super.getPosition().x + 1, super.getPosition().z);
if(px-pz >= 3 && px > super.getPosition().y) {
currentSpeed = 0;
jumpCoolDown = 30;
isMoving = false;
isColliding = true;
super.increasePosition(3.5f,-3.5f,0);
}
px = terrian.getHeightOfTerrain(super.getPosition().x +1, super.getPosition().z);
pz = terrian.getHeightOfTerrain(super.getPosition().x - 1, super.getPosition().z);
if(px-pz >= 3 && px > super.getPosition().y) {
currentSpeed = 0;
jumpCoolDown = 30;
isMoving = false;
isColliding = true;
super.increasePosition(-3.5f,-3.5f,0);
}
px = terrian.getHeightOfTerrain(super.getPosition().x, super.getPosition().z-1);
pz = terrian.getHeightOfTerrain(super.getPosition().x, super.getPosition().z+1);
if(px-pz >= 3 && px > super.getPosition().y) {
currentSpeed = 0;
jumpCoolDown = 30;
isMoving = false;
isColliding = true;
super.increasePosition(0,-3.5f,3.5f);
}
px = terrian.getHeightOfTerrain(super.getPosition().x, super.getPosition().z+1);
pz = terrian.getHeightOfTerrain(super.getPosition().x, super.getPosition().z-1);
if(px-pz >= 3 && px > super.getPosition().y) {
currentSpeed = 0;
jumpCoolDown = 30;
isMoving = false;
isColliding = true;
super.increasePosition(0,-3.5f,-3.5f);
}
checkInputs();
super.increaseRotation(0, currentTurnSpeed, 0);
distance = currentSpeed;
if(currentSpeed > 2){
currentSpeed = 2;
}
if (isStrafing) {
dx = (float) (distance * Math.sin(Math.toRadians(super.getRotY() - 90f)));
dz = (float) (distance * Math.cos(Math.toRadians(super.getRotY() - 90f)));
} else{
dx = (float) (distance * Math.sin(Math.toRadians(super.getRotY())));
dz = (float) (distance * Math.cos(Math.toRadians(super.getRotY())));
}
super.increasePosition(dx, 0, dz);
super.increasePosition(0, upwardsSpeed, 0);
float terrainHeight = terrian.getHeightOfTerrain(getPosition().x, getPosition().z);
if (super.getPosition().y < terrainHeight) {
upwardsSpeed = 0;
isInAir = false;
super.getPosition().y = terrainHeight;
}
if(CheckCollision.isOnBridge){
super.getPosition().y = terrainHeight + Level1.bridgeheight;
GRAVITY = 0;
JUMP_POWER = 0;
isInAir = false;
} else {
GRAVITY = -0.5f;
JUMP_POWER = 4.8f;
jumpCoolDown--;
upwardsSpeed += GRAVITY;
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
jump();
}
}
}
private void jump() {
if (!isInAir && jumpCoolDown <= 0) {
this.upwardsSpeed = JUMP_POWER;
isInAir = true;
jumpCoolDown = 30;
}
}
private void checkInputs() {
if(Keyboard.isKeyDown(Keyboard.KEY_W) && !isColliding){
this.currentSpeed = -RUN_SPEED;
isStrafing = false;
isMoving = true;
}else if(Keyboard.isKeyDown(Keyboard.KEY_S) && !isColliding){
this.currentSpeed = RUN_SPEED;
isStrafing = false;
isMoving = true;
}else if(Keyboard.isKeyDown(Keyboard.KEY_D) && !isColliding){
this.currentSpeed = -RUN_SPEED;
isStrafing = true;
isMoving = true;
}else if(Keyboard.isKeyDown(Keyboard.KEY_A) && !isColliding){
this.currentSpeed = RUN_SPEED;
isStrafing = true;
isMoving = true;
}
if (!Keyboard.isKeyDown(Keyboard.KEY_S)&&!Keyboard.isKeyDown(Keyboard.KEY_W)
&&!Keyboard.isKeyDown(Keyboard.KEY_D)&&!Keyboard.isKeyDown(Keyboard.KEY_A)){
this.currentSpeed = 0;
isMoving = false;
}
this.currentTurnSpeed = (float) (Mouse.getDX() * -1);
}
}
| true
|
fe515ff0631d9f1bf57374f03b38fce3192a2eb4
|
Java
|
mrts/vaadin-javaee-clinic-patient-queue-example
|
/vaadin-javaee-clinic-patient-queue-example-ui/src/main/java/com/clinicpatientqueueexample/doctorsoffice/LoginView.java
|
UTF-8
| 2,074
| 2.328125
| 2
|
[
"MIT"
] |
permissive
|
package com.clinicpatientqueueexample.doctorsoffice;
import com.clinicpatientqueueexample.doctors.Doctor;
import com.clinicpatientqueueexample.doctors.DoctorService;
import com.vaadin.cdi.CDIView;
import com.vaadin.cdi.access.JaasAccessControl;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.LoginForm;
import com.vaadin.ui.Notification;
import javax.inject.Inject;
import javax.servlet.ServletException;
import static com.vaadin.ui.Notification.Type.ERROR_MESSAGE;
@CDIView(LoginView.VIEW_NAME)
public class LoginView extends LoginForm implements View {
public static final String VIEW_NAME = "login";
private static final Logger logger = LoggerFactory.getLogger(LoginView.class);
@Inject
private DoctorService doctorService;
@Inject
private UserSessionContext sessionContext;
@Override
public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {
addLoginListener(loginEvent -> onLogin(loginEvent));
}
private void onLogin(LoginEvent loginEvent) {
final String username = loginEvent.getLoginParameter("username");
final String password = loginEvent.getLoginParameter("password");
final Doctor doctor = doctorService.findOne(username);
if (doctor == null) {
final String message = "Unknown doctor: " + username;
Notification.show(message, ERROR_MESSAGE);
logger.warn(message);
return;
}
try {
JaasAccessControl.login(username, password);
Notification.show("Login successful");
sessionContext.setDoctor(doctor);
getUI().getNavigator().navigateTo(DoctorsOfficeViewImpl.VIEW_NAME);
} catch (ServletException e) {
final String message = "User '" + username + "' login failed";
Notification.show(message, ERROR_MESSAGE);
logger.warn(message, e);
}
}
}
| true
|
b94d450a803604f3737c5d08a6638cce9e46a8eb
|
Java
|
Mariela2020/Proyecto_QA_TestCases
|
/src/test/java/TestCases/ProductosTest.java
|
UTF-8
| 3,046
| 1.828125
| 2
|
[] |
no_license
|
package TestCases;
import Pom.*;
import Runners.DriverManagerFactory;
import Runners.DriverType;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;
import java.net.MalformedURLException;
public class ProductosTest {
static WebDriver driver;
String baseUrl = "https://ww2.toctoc.com/gestioncorredor/";
String expected = null;
String actual = null;
WebDriverWait waitElement;
DesiredCapabilities capability= null;
HomePageCorredor homePageCorredor;
ProductosPage productosPage;
LoginPageCorredor loginPageCorredor;
DatosContratosPage datosContratosPage;
DetalleContratoPage detalleContratoPage;
@BeforeTest
//@Parameters({"browser"})
public void setUpTest() throws MalformedURLException {
DriverManagerFactory.getInstance().setDriver(DriverType.FIREFOX);
driver = DriverManagerFactory.getInstance().getDriver();
driver.get(baseUrl);
waitElement = new WebDriverWait(driver, 15);
}
@AfterTest
public void tearDown(){
//driver.quit();
}
//@Test(dataProvider = "SeleccionProducto", dataProviderClass = ProductosPage.class)
@Test
public void Producto() throws Exception {
homePageCorredor = new HomePageCorredor(driver);
productosPage = new ProductosPage(driver);
loginPageCorredor = new LoginPageCorredor(driver);
datosContratosPage= new DatosContratosPage(driver);
detalleContratoPage= new DetalleContratoPage(driver);
Assert.assertTrue(homePageCorredor.homePageIsDisplayed());
homePageCorredor.clickOnProductos();
Assert.assertTrue("No se redirrecciono correctamente a la pagina de Productos", productosPage.isImagenDisplayed());
productosPage.clickOnTarjetaProducto();
Assert.assertTrue(productosPage.isImagenDisplayed2());
productosPage.ClickOnComprar();
loginPageCorredor.isImagenDisplayed3();
Thread.sleep(1000);
loginPageCorredor.typeEmailLocator();
loginPageCorredor.typePasswordLocator();
loginPageCorredor.ClickOnIngresar();
Assert.assertTrue(datosContratosPage.isImagenDisplayed4());
datosContratosPage.typeDatosContratospaso1();
Assert.assertTrue(datosContratosPage.isImagenDisplayed5());
datosContratosPage.typeDatosContratospaso2();
Assert.assertEquals(datosContratosPage.selectDropdownList(), "Metropolitana");
Assert.assertEquals(datosContratosPage.selectDropdownList1(), "Santiago");
datosContratosPage.ClickOncheckaceptaTerminos();
//datosContratosPage.ClickOncheckactulizainfo();
datosContratosPage.ClickOnbtnContinuar();
Assert.assertTrue(detalleContratoPage.istitledetalleDisplayed());
detalleContratoPage.ClickOnbtnPagar();
Assert.assertTrue(detalleContratoPage.istitledetalleDisplayed2());
detalleContratoPage.WriteExcelFile();
}
}
| true
|
36940e6b05f191b872c55f8fe67021cd405315c0
|
Java
|
mohitbmehta/Hand-Calculator
|
/ModelComputation.java
|
UTF-8
| 750
| 3
| 3
|
[] |
no_license
|
public class ModelComputation {
double operand1;
double operand2;
public ModelComputation() {
}
public double getOperand1() {
return operand1;
}
public void setOperand1(double operand1) {
this.operand1 = operand1;
}
public double getOperand2() {
return operand2;
}
public void setOperand2(double operand2) {
this.operand2 = operand2;
}
public ModelComputation(double a, double b) {
operand1=a;
operand2=b;
}
public double addition() {
return operand1 + operand2;
}
public double subtitution() {
return operand1 - operand2;
}
public double division() {
return operand1 / operand2;
}
public double multiplication() {
return operand1 * operand2;
}
}
| true
|
9adb1b4f0e4179c97fdce0da3a3c2e2a01839310
|
Java
|
Ashutosh-bhardwaj879/PEPCODING-LINKED-LIST
|
/mergeSortOfLL16.java
|
UTF-8
| 3,065
| 3.640625
| 4
|
[] |
no_license
|
class main16 {
static class Node {
Node next;
int data;
}
static class LinkedList {
Node head;
Node tail;
int size;
public void addLast(int value) {
Node temp = new Node();
temp.data = value;
temp.next = null;
if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}
size++;
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static LinkedList mergeTwoSortedList(LinkedList l1, LinkedList l2) {
Node one = l1.head;
Node two = l2.head;
LinkedList res = new LinkedList();
while (one != null && two != null) {
if (one.data < two.data) {
res.addLast(one.data);
one = one.next;
} else {
res.addLast(two.data);
two = two.next;
}
}
while (one != null) {
res.addLast(one.data);
one = one.next;
}
while (two != null) {
res.addLast(two.data);
two = two.next;
}
return res;
}
public static Node midNode(Node head, Node tail) {
Node fast = head;
Node slow = head;
while (fast.next != tail && fast != tail) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public static LinkedList mergeSort(Node head, Node tail) {
if (head == tail) {
LinkedList br = new LinkedList();
br.addLast(head.data);
return br;
}
// Node mid = LinkedList.midNode(head, tail);
Node mid = midNode(head, tail);
// LinkedList fsh = LinkedList.mergeSort(head, mid);
LinkedList fsh = mergeSort(head, mid);
LinkedList ssh = mergeSort(mid.next, tail);
LinkedList cl = mergeTwoSortedList(fsh, ssh);
// LinkedList cl = LinkedList.mergeTwoSortedList(fsh, ssh);
return cl;
}
}
public static void main(String[] args) {
LinkedList list1 = new LinkedList();
list1.addLast(-1);
list1.addLast(0);
list1.addLast(23);
list1.addLast(44);
list1.addLast(5);
list1.printList();
Node mid = LinkedList.midNode(list1.head, list1.tail);
System.out.println(mid.data);
LinkedList merged = LinkedList.mergeSort(list1.head, list1.tail);
merged.printList();
Node mid1 = LinkedList.midNode(merged.head, merged.tail);
System.out.println(mid1.data);
}
}
| true
|
86ee8dd7999489ff52ebc4490bd702696282f05b
|
Java
|
stevewen/ihmc-open-robotics-software
|
/ihmc-common-walking-control-modules/src/main/java/us/ihmc/commonWalkingControlModules/momentumBasedController/PlaneContactWrenchProcessor.java
|
UTF-8
| 6,852
| 1.929688
| 2
|
[
"Apache-2.0"
] |
permissive
|
package us.ihmc.commonWalkingControlModules.momentumBasedController;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import us.ihmc.commonWalkingControlModules.controlModules.CenterOfPressureResolver;
import us.ihmc.euclid.referenceFrame.FramePoint2D;
import us.ihmc.euclid.referenceFrame.FramePoint3D;
import us.ihmc.euclid.referenceFrame.FrameVector3D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.graphicsDescription.appearance.YoAppearance;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicPosition;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry;
import us.ihmc.graphicsDescription.yoGraphics.plotting.YoArtifactPosition;
import us.ihmc.humanoidRobotics.model.CenterOfPressureDataHolder;
import us.ihmc.mecano.multiBodySystem.interfaces.RigidBodyBasics;
import us.ihmc.mecano.spatial.Wrench;
import us.ihmc.robotics.contactable.ContactablePlaneBody;
import us.ihmc.yoVariables.registry.YoVariableRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoFramePoint2D;
import us.ihmc.yoVariables.variable.YoFramePoint3D;
/**
* @author twan
* Date: 5/11/13
*/
public class PlaneContactWrenchProcessor
{
private final static boolean VISUALIZE = false;
private final List<? extends ContactablePlaneBody> contactablePlaneBodies;
private final CenterOfPressureResolver centerOfPressureResolver = new CenterOfPressureResolver();
private final YoVariableRegistry registry = new YoVariableRegistry(getClass().getSimpleName());
private final Map<ContactablePlaneBody, YoDouble> normalTorques = new LinkedHashMap<>();
private final Map<ContactablePlaneBody, YoDouble> groundReactionForceMagnitudes = new LinkedHashMap<>();
private final Map<ContactablePlaneBody, YoFramePoint3D> centersOfPressureWorld = new LinkedHashMap<>();
private final Map<ContactablePlaneBody, YoFramePoint2D> centersOfPressure2d = new LinkedHashMap<>();
private final Map<ContactablePlaneBody, YoFramePoint2D> yoCops = new LinkedHashMap<>();
private final Map<ContactablePlaneBody, FramePoint2D> cops = new LinkedHashMap<>();
private final CenterOfPressureDataHolder desiredCenterOfPressureDataHolder;
public PlaneContactWrenchProcessor(List<? extends ContactablePlaneBody> contactablePlaneBodies, YoGraphicsListRegistry yoGraphicsListRegistry,
YoVariableRegistry parentRegistry)
{
Map<RigidBodyBasics, ReferenceFrame> soleFrames = new HashMap<>();
this.contactablePlaneBodies = contactablePlaneBodies;
for (ContactablePlaneBody contactableBody : contactablePlaneBodies)
{
soleFrames.put(contactableBody.getRigidBody(), contactableBody.getSoleFrame());
String name = contactableBody.getSoleFrame().getName();
YoDouble forceMagnitude = new YoDouble(name + "ForceMagnitude", registry);
groundReactionForceMagnitudes.put(contactableBody, forceMagnitude);
YoDouble normalTorque = new YoDouble(name + "NormalTorque", registry);
normalTorques.put(contactableBody, normalTorque);
String copName = name + "CoP";
String listName = getClass().getSimpleName();
YoFramePoint2D cop2d = new YoFramePoint2D(copName + "2d", "", contactableBody.getSoleFrame(), registry);
centersOfPressure2d.put(contactableBody, cop2d);
YoFramePoint3D cop = new YoFramePoint3D(copName, ReferenceFrame.getWorldFrame(), registry);
centersOfPressureWorld.put(contactableBody, cop);
FramePoint2D footCenter2d = new FramePoint2D(contactableBody.getSoleFrame());
footCenter2d.setToNaN();
cops.put(contactableBody, footCenter2d);
YoFramePoint2D yoCop = new YoFramePoint2D(contactableBody.getName() + "CoP", contactableBody.getSoleFrame(), registry);
yoCop.set(footCenter2d);
yoCops.put(contactableBody, yoCop);
if (yoGraphicsListRegistry != null)
{
YoGraphicPosition copViz = new YoGraphicPosition(copName, cop, 0.005, YoAppearance.Navy(), YoGraphicPosition.GraphicType.BALL);
copViz.setVisible(VISUALIZE);
yoGraphicsListRegistry.registerYoGraphic(listName, copViz);
YoArtifactPosition artifact = copViz.createArtifact();
artifact.setVisible(VISUALIZE);
yoGraphicsListRegistry.registerArtifact(listName, artifact);
}
}
desiredCenterOfPressureDataHolder = new CenterOfPressureDataHolder(soleFrames);
parentRegistry.addChild(registry);
}
private final FramePoint3D tempCoP3d = new FramePoint3D();
private final FrameVector3D tempForce = new FrameVector3D();
public void compute(Map<RigidBodyBasics, Wrench> externalWrenches)
{
for (int i = 0; i < contactablePlaneBodies.size(); i++)
{
ContactablePlaneBody contactablePlaneBody = contactablePlaneBodies.get(i);
FramePoint2D cop = cops.get(contactablePlaneBody);
YoFramePoint2D yoCop = yoCops.get(contactablePlaneBody);
cop.set(yoCop);
Wrench wrench = externalWrenches.get(contactablePlaneBody.getRigidBody());
if (wrench != null)
{
tempForce.setIncludingFrame(wrench.getLinearPart());
double normalTorque = centerOfPressureResolver.resolveCenterOfPressureAndNormalTorque(cop, wrench, contactablePlaneBody.getSoleFrame());
centersOfPressure2d.get(contactablePlaneBody).set(cop);
tempCoP3d.setIncludingFrame(cop, 0.0);
centersOfPressureWorld.get(contactablePlaneBody).setMatchingFrame(tempCoP3d);
groundReactionForceMagnitudes.get(contactablePlaneBody).set(tempForce.length());
normalTorques.get(contactablePlaneBody).set(normalTorque);
}
else
{
groundReactionForceMagnitudes.get(contactablePlaneBody).set(0.0);
centersOfPressureWorld.get(contactablePlaneBody).setToNaN();
cop.setToNaN();
}
yoCop.set(cop);
desiredCenterOfPressureDataHolder.setCenterOfPressure(cop, contactablePlaneBody.getRigidBody());
}
}
public void initialize()
{
for (int i = 0; i < contactablePlaneBodies.size(); i++)
{
ContactablePlaneBody contactablePlaneBody = contactablePlaneBodies.get(i);
cops.get(contactablePlaneBody).setToZero((contactablePlaneBody.getSoleFrame()));
}
}
public void getDesiredCenterOfPressure(ContactablePlaneBody contactablePlaneBody, FramePoint2D desiredCoPToPack)
{
YoFramePoint2D yoCop = yoCops.get(contactablePlaneBody);
desiredCoPToPack.setIncludingFrame(yoCop);
}
public CenterOfPressureDataHolder getDesiredCenterOfPressureDataHolder()
{
return desiredCenterOfPressureDataHolder;
}
}
| true
|
9172c1d7a76e0f79fb0cce1e702c9469f3798e92
|
Java
|
ljx728/eyoubika
|
/src/com/eyoubika/user/dao/OpenAccountBriefDao.java
|
UTF-8
| 6,046
| 2.046875
| 2
|
[] |
no_license
|
package com.eyoubika.user.dao;
import java.sql.SQLException;
import java.util.List;
import com.eyoubika.common.BaseDao;
import com.eyoubika.common.YbkException;
import com.eyoubika.user.domain.OpenAccountBriefDomain;
/*==========================================================================================*
* Description: __Description__
* Class: __Class__
* Author: lijiaxuan
* Copyright: CaiDan (c) 2015 jiaxuan.li@eyoubika.com
* History: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*==========================================================================================*/
public class OpenAccountBriefDao extends BaseDao {
String nameSpace = "tu_OpenAccountBrief";
private OpenAccountBriefDomain openAccountBriefDomain; //<<attrNote>>
public OpenAccountBriefDomain getOpenAccountBriefDomain(){
return openAccountBriefDomain;
}
public void setOpenAccountBriefDomain(OpenAccountBriefDomain openAccountBriefDomain){
this.openAccountBriefDomain = openAccountBriefDomain;
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public void addOpenAccountBrief(OpenAccountBriefDomain openAccountBriefDomain){
try {
sqlMapClient.insert(nameSpace +".insertOpenAccountBrief", openAccountBriefDomain);
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public int deleteOpenAccountBrief(String openNo){
try {
return (int)sqlMapClient.delete(nameSpace +".deleteOpenAccountBrief", openNo);
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public int deleteAll(){
try {
return (int)sqlMapClient.delete(nameSpace +".deleteAll");
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public void modifyOpenAccountBrief(OpenAccountBriefDomain openAccountBriefDomain){
try {
sqlMapClient.update(nameSpace +".updateOpenAccountBrief", openAccountBriefDomain);
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public OpenAccountBriefDomain findOpenAccountBrief(String openNo){
try {
return (OpenAccountBriefDomain) sqlMapClient.queryForObject(nameSpace +".selectOpenAccountBrief", openNo);
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public OpenAccountBriefDomain findOpenAccountBriefByDomain(OpenAccountBriefDomain openAccountBriefDomain){
try {
return (OpenAccountBriefDomain) sqlMapClient.queryForObject(nameSpace +".selectOpenAccountBriefByDomain", openAccountBriefDomain);
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public List<OpenAccountBriefDomain> queryOpenAccountBrief(OpenAccountBriefDomain openAccountBriefDomain){
try {
return (List<OpenAccountBriefDomain>) sqlMapClient.queryForList(nameSpace +".selectOpenAccountBriefList", openAccountBriefDomain);
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
}
/*--------------------------------------------------------------------------------------*
* Description: __Description__
* Method: __Method__
* Author: 1.0 created by lijiaxuan at 2015-07-22 20:53:33
*--------------------------------------------------------------------------------------*/
public boolean isExistByDomain(OpenAccountBriefDomain openAccountBriefDomain){
boolean ret = true;
Object ob = new Object();
try {
ob = sqlMapClient.queryForObject(nameSpace +".isExistByDomain", openAccountBriefDomain);
ret = (ob==null) ? false : true;
} catch (SQLException e) {
e.printStackTrace();
throw new YbkException(YbkException.CODE000020, YbkException.DESC000020);
}
return ret;
}
}
| true
|
4d6754abcf629b785186b52207cef006ef3ccb81
|
Java
|
heyimpg/City_project_Spring
|
/city_spring/src/main/java/com/amela/Repository/CityRepository.java
|
UTF-8
| 2,153
| 2.5
| 2
|
[] |
no_license
|
package com.amela.Repository;
import com.amela.Models.City;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.List;
@Transactional
public class CityRepository implements ICityRepository{
@PersistenceContext
EntityManager entityManager;
@Override
public Page<City> findAll(Pageable pageable) {
TypedQuery<City> query = entityManager.createQuery("SELECT c FROM City c", City.class);
List<City> noteList = query.getResultList();
int start = (int)pageable.getOffset();
int end = Math.min((start + pageable.getPageSize()), noteList.size());
Page<City> pageList = new PageImpl<>(noteList.subList(start, end), pageable, noteList.size());
return pageList;
}
@Override
public List<City> findAll() {
TypedQuery<City> query = entityManager.createQuery("SELECT c FROM City c", City.class);
return query.getResultList();
}
@Override
public City findById(int id) {
return entityManager.find(City.class, id);
}
@Override
public void save(City city) {
if (city.getID()!=0)
entityManager.merge(city);
else
entityManager.persist(city);
}
@Override
public void delete(int id) {
entityManager.remove(findById(id));
}
@Override
public Page<City> findByName(String name, Pageable pageable) {
TypedQuery<City> query = entityManager.createQuery("SELECT c FROM City c WHERE c.name like :name", City.class);
query.setParameter("name", "%"+name+"%");
List<City> noteTypeList = query.getResultList();
int start = (int)pageable.getOffset();
int end = Math.min((start + pageable.getPageSize()), noteTypeList.size());
Page<City> pageList = new PageImpl<>(noteTypeList.subList(start, end), pageable, noteTypeList.size());
return pageList;
}
}
| true
|
a4e3ee7ce0a9d32430550b0b0f94b437f06a167e
|
Java
|
Oleiva/myDropBox
|
/src/main/java/io/github/oleiva/myDropBox/controllers/UploadableController.java
|
UTF-8
| 330
| 1.921875
| 2
|
[] |
no_license
|
package io.github.oleiva.myDropBox.controllers;
import io.github.oleiva.myDropBox.files.support.model.FileUploadForm;
import org.springframework.web.bind.annotation.ModelAttribute;
public class UploadableController {
@ModelAttribute("uploadForm")
public FileUploadForm uploadForm() {
return new FileUploadForm();
}
}
| true
|
59abab37f520ec4a836a8b6bc938b74fe95387e5
|
Java
|
mayemonkey/MVPSample
|
/app/src/main/java/com/zc/mvp/mvpsample/ui/activity/LoginActivity.java
|
UTF-8
| 2,093
| 2.359375
| 2
|
[] |
no_license
|
package com.zc.mvp.mvpsample.ui.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.zc.mvp.mvpsample.R;
import com.zc.mvp.mvpsample.presenter.LoginPresenter;
import com.zc.mvp.mvpsample.presenter.LoginPresenterImpl;
import com.zc.mvp.mvpsample.view.LoginView;
public class LoginActivity extends AppCompatActivity implements LoginView, View.OnClickListener {
private ProgressBar progressbar;
private Button submit;
private TextView username;
private TextView password;
private LoginPresenter loginPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponent();
}
private void initComponent() {
username = (TextView) findViewById(R.id.username);
password = (TextView) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submit);
assert submit != null;
submit.setOnClickListener(this);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
loginPresenter = new LoginPresenterImpl(this);
}
@Override
public void progressVisible(boolean visible) {
progressbar.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
}
@Override
public void showError(String index, String error) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.submit:
String username = this.username.getText().toString();
String password = this.password.getText().toString();
loginPresenter.loginCheck(username, password);
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
loginPresenter.destroyView();
}
}
| true
|
fc37512680eb5d045698cd5fe98361cfe424eae1
|
Java
|
mklxiaobai/gmallparent
|
/gmall-api/src/main/java/com/mkl/gmall/pms/service/ProductService.java
|
UTF-8
| 840
| 1.8125
| 2
|
[] |
no_license
|
package com.mkl.gmall.pms.service;
import com.mkl.gmall.pms.entity.Product;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mkl.gmall.to.es.EsProduct;
import com.mkl.gmall.vo.PageInfoVo;
import com.mkl.gmall.vo.product.PmsProductParam;
import com.mkl.gmall.vo.product.PmsProductQueryParam;
import java.util.List;
/**
* <p>
* 商品信息 服务类
* </p>
*
* @author mkl
* @since 2019-11-28
*/
public interface ProductService extends IService<Product> {
// 根据复杂查询条件返回数据
Product productInfo(Long id);
PageInfoVo productPageInfo(PmsProductQueryParam productQueryParam);
void saveProduct(PmsProductParam productParam);
void updatePublishStatus(List<Long> ids, Integer publishStatus);
EsProduct productAllInfo(Long id);
EsProduct produSkuInfo(Long id);
}
| true
|
0b207668e158fe5b7f00525053e60433a67ec61c
|
Java
|
Yashwin12/FAANG
|
/problems/medium/RemoveIslands.java
|
UTF-8
| 1,685
| 3.078125
| 3
|
[] |
no_license
|
import java.util.*;
class Program {
private int totalRow = 0;
private int totalCol = 0;
// Up, Down, Right, Left
private static int[][] DIRECTIONS = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } };
public int[][] removeIslands(int[][] matrix) {
totalRow = matrix.length;
totalCol = matrix[0].length;
int[][] visited = new int[totalRow + 1][totalCol + 1];
for( int row = 0; row < totalRow; row++ ){
for( int col = 0; col < totalCol; col++ ){
boolean rowIsBorder = row == 0 || row == matrix.length - 1;
boolean colIsBorder = col == 0 || col == matrix[0].length - 1;
boolean isBorder = rowIsBorder || colIsBorder;
if( !isBorder || visited[row][col] == 1 || matrix[row][col] == 0 )
continue;
findOnesConnectedWithBorder( matrix, visited, row, col );
}
}
for( int row = 0; row < totalRow; row++ ){
for( int col = 0; col < totalCol; col++ ){
if( visited[row][col] == 0 && matrix[row][col] == 1)
matrix[row][col] = 0;
visited[row][col] = 1;
}
}
return matrix;
}
private void findOnesConnectedWithBorder( int[][] matrix, int[][] visited, int row, int col ){
visited[row][col] = 1;
for( int[] dir: DIRECTIONS ){
int dr = row + dir[0];
int dc = col + dir[1];
if( inBounds( matrix, visited, dr, dc ) && matrix[dr][dc] == 1 ){
findOnesConnectedWithBorder( matrix, visited, dr, dc );
}
}
}
private boolean inBounds( int[][] matrix, int[][] visited, int row, int col ){
if( row >= 0 && row < totalRow && col >= 0 && col < totalCol && visited[row][col] == 0 )
return true;
return false;
}
}
| true
|
1b66ea2e2cbb7a8cd3e2b925c69093b00ee3a3fc
|
Java
|
maicol0915/test
|
/Project/src/main/java/dagachi/service/customer/Customer_Login_ServiceImpl.java
|
UTF-8
| 2,946
| 2.25
| 2
|
[] |
no_license
|
package dagachi.service.customer;
import java.util.HashMap;
import javax.inject.Inject;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import dagachi.dao.customer.Customer_Login_Dao;
import dagachi.dto.customer.Customer_Login_Dto;
import dagachi.dto.customer.Customer_SignUp_Dto;
import lombok.Setter;
@Service
public class Customer_Login_ServiceImpl implements Customer_Login_Service {
@Inject
private Customer_Login_Dao dao;
@Setter
@Autowired
protected JavaMailSender mailSender;
// 회원가입
@Override
public void register(Customer_SignUp_Dto dto) throws Exception {
System.out.println(dto);
dao.insert(dto);
}
public void insert(Customer_SignUp_Dto dto) throws Exception {
dao.insert(dto);
}
@Override
public Customer_Login_Dto login(Customer_Login_Dto dto) throws Exception {
return dao.login(dto);
}
public int ID(String customer_Email) {
int num = dao.ID(customer_Email);
return num;
}
public boolean emailCertification(HttpSession session, String customer_Email, int inputCode) {
try {
int generationCode = (int) session.getAttribute("num" + customer_Email);
System.out.println("입력한 코드 ::" + inputCode);
System.out.println("실제 코드 ::" + generationCode);
if (generationCode == inputCode) {
return true;
} else {
return false;
}
} catch (Exception e) {
throw e;
}
}
public boolean mailSend(dagachi.controller.customer.EmailDTO email) {
try {
MimeMessage msg = mailSender.createMimeMessage();
msg.setSubject(email.getSubject());
// 일반 텍스트만 전송하려는 경우
msg.setText(email.getContent());
msg.setRecipient(RecipientType.TO, new InternetAddress(email.getReceiver()));
mailSender.send(msg);
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
@Override
public void update(HashMap<String, Object> map) {
dao.update(map);
}
}
/*
*
* public boolean isLogin(String id) { boolean isLogin = false;
* Enumeration<String> e = loginUsers.keys(); String key = ""; while
* (e.hasMoreElements()) { key = (String) e.nextElement(); if
* (id.equals(loginUsers.get(key))) isLogin = true; } return isLogin; }
*
* public boolean isUsing(String sessionId) { boolean isUsing = false;
* Enumeration<String> e = loginUsers.keys(); String key = ""; while
* (e.hasMoreElements()) { key = (String) e.nextElement(); if
* (sessionId.equals(loginUsers.get(key))) isUsing = true; } return isUsing; }
*
* public void setSession(HttpSession session, CSignUpDTO dto) {
* loginUsers.put(session.getId(), dto.getId()); session.setAttribute("id",
* dto.getId()); }
*/
| true
|
c91ca81b5487a0d822fda19d968a587279a24dd0
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/20/20_da2c68ba1266b82be3d7fc9d08550f580cd1c643/AwesomePerson/20_da2c68ba1266b82be3d7fc9d08550f580cd1c643_AwesomePerson_t.java
|
UTF-8
| 848
| 2.921875
| 3
|
[] |
no_license
|
package miklos.martin.learningandroid.model;
/**
* Dummy value object for showing results in the sqlite example
*/
public class AwesomePerson {
private int id;
private String name;
private int awesomeness;
public AwesomePerson( int id, String name, int awesomeness ) {
this.id = id;
this.name = name;
this.awesomeness = awesomeness;
}
public int getId () {
return id;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this.name = name;
}
public int getAwesomeness () {
return awesomeness;
}
public void setAwesomeness ( int awesomeness ) {
this.awesomeness = awesomeness;
}
public boolean isAwesome() {
return awesomeness > 10;
}
}
| true
|
69b93875725110fb50e8fc8a8fb2b6b820cbd17a
|
Java
|
chihwei-lin/distributed_system_assignment02
|
/src/view/MainView.java
|
UTF-8
| 19,852
| 2.125
| 2
|
[] |
no_license
|
package view;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import controller.ColorSelector;
import controller.SaveLoad;
import controller.State;
import controller.Tool;
import controller.UndoRedo;
public class MainView{
public JFrame frame;
DrawPanel drawPanel = new DrawPanel();
SaveLoad saveload = new SaveLoad();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//MainView window = new MainView();
//window.frame.setVisible(true);
LoginView login = new LoginView();
login.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
State.Initialize();
frame = new JFrame();
frame.getContentPane().setBackground(new Color(0, 0, 0));
frame.setBounds(100, 100, 828, 615);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{146, 498, 162};
gridBagLayout.rowHeights = new int[] {96, 567, 80, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, 1.0};
gridBagLayout.rowWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JPanel titlePanel = new JPanel();
Color myColor = Color.decode("#114B5F");
Color buttonColor = Color.decode("#456990");
titlePanel.setBackground(myColor);
titlePanel.setLayout(null);
GridBagConstraints gbc_titlePanel = new GridBagConstraints();
gbc_titlePanel.insets = new Insets(0, 0, 5, 0);
gbc_titlePanel.gridwidth = 3;
gbc_titlePanel.fill = GridBagConstraints.BOTH;
gbc_titlePanel.gridx = 0;
gbc_titlePanel.gridy = 0;
frame.getContentPane().add(titlePanel, gbc_titlePanel);
JLabel lblShareWhiteBoard = new JLabel("Shared White Board");
lblShareWhiteBoard.setFont(new Font("Agency FB", Font.PLAIN, 30));
lblShareWhiteBoard.setForeground(new Color(255, 255, 255));
lblShareWhiteBoard.setBounds(10, 10, 228, 41);
lblShareWhiteBoard.setVerticalAlignment(SwingConstants.BOTTOM);
titlePanel.add(lblShareWhiteBoard);
JPanel leftPanel = new JPanel();
Color myColorLeftPanel = Color.decode("#028090");
leftPanel.setBackground(myColorLeftPanel);
GridBagConstraints gbc_leftPanel = new GridBagConstraints();
gbc_leftPanel.anchor = GridBagConstraints.SOUTHEAST;
gbc_leftPanel.fill = GridBagConstraints.BOTH;
gbc_leftPanel.insets = new Insets(0, 0, 5, 5);
gbc_leftPanel.gridx = 0;
gbc_leftPanel.gridy = 1;
frame.getContentPane().add(leftPanel, gbc_leftPanel);
GridBagLayout gbl_leftPanel = new GridBagLayout();
gbl_leftPanel.columnWidths = new int[]{34, 71, 65, 26, 0};
gbl_leftPanel.rowHeights = new int[]{0, 39, 39, 39, 16, 29, 29, 134, 39, 52, 39, 0};
gbl_leftPanel.columnWeights = new double[]{1.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_leftPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
leftPanel.setLayout(gbl_leftPanel);
JLabel label = new JLabel(" ");
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 0;
gbc_label.gridy = 1;
leftPanel.add(label, gbc_label);
JButton btnPencil = new JButton("Pencil");
btnPencil.setBackground(buttonColor);
btnPencil.setForeground(Color.white);
GridBagConstraints gbc_btnPencil = new GridBagConstraints();
gbc_btnPencil.fill = GridBagConstraints.BOTH;
gbc_btnPencil.insets = new Insets(0, 0, 5, 5);
gbc_btnPencil.gridwidth = 2;
gbc_btnPencil.gridx = 1;
gbc_btnPencil.gridy = 1;
leftPanel.add(btnPencil, gbc_btnPencil);
JLabel label_1 = new JLabel(" ");
GridBagConstraints gbc_label_1 = new GridBagConstraints();
gbc_label_1.insets = new Insets(0, 0, 5, 0);
gbc_label_1.gridx = 3;
gbc_label_1.gridy = 1;
leftPanel.add(label_1, gbc_label_1);
JButton btnCircle = new JButton("Circle");
btnCircle.setBackground(buttonColor);
btnCircle.setForeground(Color.white);
GridBagConstraints gbc_btnCircle = new GridBagConstraints();
gbc_btnCircle.fill = GridBagConstraints.BOTH;
gbc_btnCircle.insets = new Insets(0, 0, 5, 5);
gbc_btnCircle.gridx = 1;
gbc_btnCircle.gridy = 2;
leftPanel.add(btnCircle, gbc_btnCircle);
JButton btnOval = new JButton("Oval");
btnOval.setBackground(buttonColor);
btnOval.setForeground(Color.white);
GridBagConstraints gbc_btnOval = new GridBagConstraints();
gbc_btnOval.fill = GridBagConstraints.BOTH;
gbc_btnOval.insets = new Insets(0, 0, 5, 5);
gbc_btnOval.gridx = 2;
gbc_btnOval.gridy = 2;
leftPanel.add(btnOval, gbc_btnOval);
JButton btnLine = new JButton("Line");
btnLine.setBackground(buttonColor);
btnLine.setForeground(Color.white);
GridBagConstraints gbc_btnLine = new GridBagConstraints();
gbc_btnLine.fill = GridBagConstraints.BOTH;
gbc_btnLine.insets = new Insets(0, 0, 5, 5);
gbc_btnLine.gridx = 1;
gbc_btnLine.gridy = 3;
leftPanel.add(btnLine, gbc_btnLine);
JButton btnRectangle = new JButton("Rect");
btnRectangle.setBackground(buttonColor);
btnRectangle.setForeground(Color.white);
GridBagConstraints gbc_btnRectangle = new GridBagConstraints();
gbc_btnRectangle.fill = GridBagConstraints.BOTH;
gbc_btnRectangle.insets = new Insets(0, 0, 5, 5);
gbc_btnRectangle.gridx = 2;
gbc_btnRectangle.gridy = 3;
leftPanel.add(btnRectangle, gbc_btnRectangle);
JLabel lblStrokeSize = new JLabel("Stroke Size: 2");
GridBagConstraints gbc_lblStrokeSize = new GridBagConstraints();
gbc_lblStrokeSize.fill = GridBagConstraints.BOTH;
gbc_lblStrokeSize.insets = new Insets(0, 0, 5, 5);
gbc_lblStrokeSize.gridwidth = 2;
gbc_lblStrokeSize.gridx = 1;
gbc_lblStrokeSize.gridy = 4;
leftPanel.add(lblStrokeSize, gbc_lblStrokeSize);
JSlider sldStrokeSize = new JSlider();
sldStrokeSize.setValue(2);
sldStrokeSize.setMinorTickSpacing(1);
sldStrokeSize.setMaximum(20);
sldStrokeSize.setMinimum(1);
GridBagConstraints gbc_sldStrokeSize = new GridBagConstraints();
gbc_sldStrokeSize.fill = GridBagConstraints.BOTH;
gbc_sldStrokeSize.insets = new Insets(0, 0, 5, 5);
gbc_sldStrokeSize.gridwidth = 2;
gbc_sldStrokeSize.gridx = 1;
gbc_sldStrokeSize.gridy = 5;
leftPanel.add(sldStrokeSize, gbc_sldStrokeSize);
JLabel lblColor = new JLabel("Color");
GridBagConstraints gbc_lblColor = new GridBagConstraints();
gbc_lblColor.anchor = GridBagConstraints.NORTH;
gbc_lblColor.fill = GridBagConstraints.HORIZONTAL;
gbc_lblColor.insets = new Insets(0, 0, 5, 5);
gbc_lblColor.gridx = 1;
gbc_lblColor.gridy = 6;
leftPanel.add(lblColor, gbc_lblColor);
JPanel pnlColorView = new JPanel();
pnlColorView.setBackground(Color.BLACK);
GridBagConstraints gbc_pnlColorView = new GridBagConstraints();
gbc_pnlColorView.fill = GridBagConstraints.BOTH;
gbc_pnlColorView.insets = new Insets(0, 0, 5, 5);
gbc_pnlColorView.gridx = 2;
gbc_pnlColorView.gridy = 6;
leftPanel.add(pnlColorView, gbc_pnlColorView);
JPanel colorPanel = new JPanel();
colorPanel.setBackground(myColorLeftPanel);
colorPanel.setLayout(null);
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.gridwidth = 2;
gbc_panel_1.insets = new Insets(0, 0, 5, 5);
gbc_panel_1.fill = GridBagConstraints.BOTH;
gbc_panel_1.gridx = 1;
gbc_panel_1.gridy = 7;
leftPanel.add(colorPanel, gbc_panel_1);
ColorSelector colorWheel = new ColorSelector();
colorWheel.setBounds(0, 0, 125, 143);
colorPanel.add(colorWheel);
colorWheel.LoadImage();
JButton btnUndo = new JButton("Undo");
GridBagConstraints gbc_btnUndo = new GridBagConstraints();
btnUndo.setBackground(buttonColor);
btnUndo.setForeground(Color.white);
gbc_btnUndo.fill = GridBagConstraints.BOTH;
gbc_btnUndo.insets = new Insets(0, 0, 5, 5);
gbc_btnUndo.gridx = 1;
gbc_btnUndo.gridy = 8;
leftPanel.add(btnUndo, gbc_btnUndo);
JButton btnRedo = new JButton("Redo");
btnRedo.setBackground(buttonColor);
btnRedo.setForeground(Color.white);
GridBagConstraints gbc_btnRedo = new GridBagConstraints();
gbc_btnRedo.fill = GridBagConstraints.BOTH;
gbc_btnRedo.insets = new Insets(0, 0, 5, 5);
gbc_btnRedo.gridx = 2;
gbc_btnRedo.gridy = 8;
leftPanel.add(btnRedo, gbc_btnRedo);
JButton btnEraser = new JButton("Eraser");
btnEraser.setBackground(buttonColor);
btnEraser.setForeground(Color.white);
GridBagConstraints gbc_btnEraser = new GridBagConstraints();
gbc_btnEraser.insets = new Insets(0, 0, 5, 5);
gbc_btnEraser.fill = GridBagConstraints.BOTH;
gbc_btnEraser.gridwidth = 2;
gbc_btnEraser.gridx = 1;
gbc_btnEraser.gridy = 9;
leftPanel.add(btnEraser, gbc_btnEraser);
JLabel label_2 = new JLabel(" ");
GridBagConstraints gbc_label_2 = new GridBagConstraints();
gbc_label_2.fill = GridBagConstraints.HORIZONTAL;
gbc_label_2.insets = new Insets(0, 0, 0, 5);
gbc_label_2.gridx = 1;
gbc_label_2.gridy = 10;
leftPanel.add(label_2, gbc_label_2);
JPanel panel = new JPanel();
panel.setLayout(null);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 5, 5);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 1;
gbc_panel.gridy = 1;
frame.getContentPane().add(panel, gbc_panel);
drawPanel.setBounds(-33, 0, 575, 561);
panel.add(drawPanel);
drawPanel.width = 1200;
drawPanel.height = 1200;
drawPanel.setBackground(Color.WHITE);
drawPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
drawPanel.Initialize(drawPanel.getHeight(), drawPanel.getWidth());
JPanel rightPanel = new JPanel();
rightPanel.setBackground(myColorLeftPanel);
GridBagConstraints gbc_rightPanel = new GridBagConstraints();
gbc_rightPanel.insets = new Insets(0, 0, 5, 0);
gbc_rightPanel.fill = GridBagConstraints.BOTH;
gbc_rightPanel.gridx = 2;
gbc_rightPanel.gridy = 1;
frame.getContentPane().add(rightPanel, gbc_rightPanel);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
JMenuItem mntmLoad = new JMenuItem("Load");
mnFile.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmSaveAs = new JMenuItem("Save As");
mnFile.add(mntmSaveAs);
Color buttonHover = Color.decode("#FF1654");
// ON hover
btnPencil.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnPencil.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnPencil.setBackground(buttonColor);
}
}
);
btnCircle.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnCircle.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnCircle.setBackground(buttonColor);
}
}
);
btnOval.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnOval.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnOval.setBackground(buttonColor);
}
}
);
btnLine.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnLine.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnLine.setBackground(buttonColor);
}
}
);
btnRectangle.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnRectangle.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnRectangle.setBackground(buttonColor);
}
}
);
btnRedo.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnRedo.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnRedo.setBackground(buttonColor);
}
}
);
btnUndo.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnUndo.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnUndo.setBackground(buttonColor);
}
}
);
btnEraser.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnEraser.setBackground(buttonHover);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnEraser.setBackground(buttonColor);
}
}
);
// --------------------------------------------
// Event Handlers
// --------------------------------------------
// Mouse Press / Released
drawPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
MousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
MouseReleased(e);
}
});
// Mouse Dragged
drawPanel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
MouseDragged(e);
}
});
//
// ------------ Tool Box Buttons -------------
//
// Circle Button Click
btnCircle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
State.tool.type = Tool.CIRCLE;
}
});
// Line Button Click
btnLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
State.tool.type = Tool.LINE;
}
});
// Oval Button Click
btnOval.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
State.tool.type = Tool.OVAL;
}
});
// Rectangle Button Click
btnRectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
State.tool.type = Tool.RECTANGLE;
}
});
// Eraser Button Click
btnEraser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
State.tool.type = Tool.ERASER;
}
});
// Pencil Button Click
btnPencil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
State.tool.type = Tool.PENCIL;
}
});
// Stroke Size Slider Changed
sldStrokeSize.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int strokeVal = sldStrokeSize.getValue();
State.tool.width = strokeVal;
lblStrokeSize.setText("Stroke Size: "+strokeVal);
}
});
// Mouse Drag on Color Wheel
colorWheel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
// Added exception because if the user click and drag the mouse
// outside of the panel then it will throw exception
try{Color clr = colorWheel.GetColor(e.getPoint());
State.tool.clr = clr;
pnlColorView.setBackground(clr);}
catch(Exception exp) {return;}
}
});
// Mouse Clicked on Color Wheel
colorWheel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Added exception because if the user click and drag the mouse
// outside of the panel then it will throw exception
try{Color clr = colorWheel.GetColor(e.getPoint());
State.tool.clr = clr;
pnlColorView.setBackground(clr);}
catch(Exception exp) {return;}
}
});
// Mouse Clicked on Undo Button
btnUndo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UndoRedo.Undo(drawPanel);
}
});
// Mouse Clicked on Redo Button
btnRedo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UndoRedo.Redo(drawPanel);
}
});
//
// --------------- Menu Buttons ---------------
//
// Menu New Button Click
mntmNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveload.New(drawPanel, frame);
}
});
// Menu Load Button Click
mntmLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveload.Load(drawPanel, frame);
}
});
// Menu Save Button Click
mntmSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveload.Save(drawPanel.mainImage, frame);
}
});
// Menu Save As Button Click
mntmSaveAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveload.SaveAs(drawPanel.mainImage,frame);
}
});
}
// Mouse Button Pressed on DrawPanel
void MousePressed(MouseEvent e)
{
Point mousePoint = e.getPoint();
State.preMouse = mousePoint;
if(State.tool.type == Tool.PENCIL || State.tool.type == Tool.ERASER)
{
State.preMouse = null;
State.currMouse = mousePoint;
}
UndoRedo.Update(drawPanel.DeepCopyOfMainImage());
}
// Mouse Button Released on DrawPanel
void MouseReleased(MouseEvent e)
{
if(State.preMouse==null) return;
Point mousePoint = e.getPoint();
State.currMouse = mousePoint;
Tool tool = new Tool(State.tool);
tool.AddPoints(State.preMouse, State.currMouse);
drawPanel.Draw(tool,true,false);
}
// Mouse Dragged on DrawPanel
void MouseDragged(MouseEvent e)
{
if(State.tool.IsContinuesTool())
{
Point mousePoint = e.getPoint();
if(State.preMouse!=null)
{
Tool tool = new Tool(State.tool);
tool.AddPoints(State.preMouse, State.currMouse);
drawPanel.Draw(tool,true,false);
}
State.preMouse = State.currMouse;
State.currMouse = mousePoint;
}
else
{
// Animation
// Code same as Mouse Release with Complete of Draw = false
if(State.preMouse==null) return;
Point mousePoint = e.getPoint();
State.currMouse = mousePoint;
Tool tool = new Tool(State.tool);
tool.AddPoints(State.preMouse, State.currMouse);
drawPanel.Draw(tool,false,false);
}
}
}
| true
|
28e6a2efe505004ffa222e4beb3588eae89a9a7f
|
Java
|
Cmrales26/Tienda_binario_lista
|
/src/Metodos/Productos.java
|
UTF-8
| 3,249
| 2.703125
| 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 Metodos;
import Frames.InterfazAdmin;
import Objetos.Producto;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JOptionPane;
/**
*
* @author Camilo && Diana
*/
public class Productos {
public static final String ruta = "./productos.bin";
private Nodo_Productos raiz;
FileOutputStream objeto = null;
ObjectOutputStream ob = null;
FileInputStream is = null;
ObjectInputStream obin = null;
String nombre;
String precio;
String codigo;
public Productos() {
raiz = null;
}
public boolean guardar_nodo_producto(String nombre, String precio, String codigo) {
Nodo_Productos nodo;
nodo = new Nodo_Productos();
Producto pr = new Producto(nombre, precio, codigo);
nodo.productos = pr;
try {
if (!validar_existencia(pr)) {
if (raiz == null) {
nodo.siguiente = null;
} else {
nodo.siguiente = raiz;
}
raiz = nodo;
raiz = nodo;
objeto = new FileOutputStream(ruta);
ob = new ObjectOutputStream(objeto);
ob.writeObject(nodo);
ob.close();
objeto.close();
JOptionPane.showMessageDialog(null, "Se ha guardado el producto");
return true;
} else {
JOptionPane.showMessageDialog(null, "El producto ya se encuentra registrado");
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
public boolean validar_existencia(Producto productos) {
Nodo_Productos nodo;
nodo = raiz;
while (nodo != null) {
if (productos.getCodigo().equals(nodo.productos.getCodigo())) {
return true;
}
nodo = nodo.siguiente;
}
return false;
}
public Nodo_Productos obtener_nodo_productos(){
try {
is = new FileInputStream(ruta);
obin = new ObjectInputStream(is);
Nodo_Productos nodo = (Nodo_Productos) obin.readObject();
is.close();
obin.close();
return nodo;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void obtener_productos(){
Nodo_Productos nodo;
boolean encontrado =false;
nodo = raiz;
while(nodo != null){
nombre = nodo.productos.getProducto();
precio = nodo.productos.getPrecio();
codigo = nodo.productos.getCodigo();
encontrado = true;
nodo = nodo.siguiente;
}
if (encontrado == true) {
InterfazAdmin ia = new InterfazAdmin(nombre, precio, codigo);
}else{
JOptionPane.showMessageDialog(null, "error");
}
}
}
| true
|
9f8e8b51fe40ccc8bc71e16299d932a87d38dd49
|
Java
|
tao-tao/BusinessModuleDesign
|
/avicit.ui.view.navigator/src/avicit/ui/runtime/core/develope/service/ServiceWorkbenchAdapter.java
|
UTF-8
| 1,510
| 2.21875
| 2
|
[] |
no_license
|
package avicit.ui.runtime.core.develope.service;
import avicit.ui.runtime.core.INode;
import avicit.ui.runtime.core.node.GuizeNode;
import avicit.ui.runtime.core.node.GuizeWorkbenchAdapter;
import avicit.ui.view.module.GuizeModelFactory;
import avicit.ui.view.module.IModelFactory;
import avicit.ui.view.module.ModelManagerImpl;
import com.tansun.runtime.resource.adapter.AbstractModelWorkbenchAdapter;
public class ServiceWorkbenchAdapter extends AbstractModelWorkbenchAdapter{
@Override
public boolean hasChildren(Object element) {
return true;
}
public ServiceWorkbenchAdapter()
{
}
public static ServiceWorkbenchAdapter getInstance()
{
return instance;
}
@Override
public Object getParent(Object object) {
return super.getParent(object);
}
public String getLabel(Object object)
{
ServiceNode node = (ServiceNode)object;
return node.getDisplayName();
}
public Object[] getChildren(Object object)
{
INode node = (INode)object;
IModelFactory factory = ModelManagerImpl.getInstance().getModelFactory(/*"tansun.controller", */ServiceModelFactory.TYPE);
// IModelFactory factory = ModelManagerImpl.getInstance().getModelFactory(/*"tansun.controller", */GuizeModelFactory.TYPE);
if(factory != null)
return factory.getModelParser(object, null).getChildren(node);
return new Object[0];
}
private static final ServiceWorkbenchAdapter instance = new ServiceWorkbenchAdapter();
}
| true
|
7f94c67780b7e9d7ef9dcc5e1168250d8f388e0c
|
Java
|
ht1625/java_note_webpage
|
/src/java/data_genel.java
|
UTF-8
| 630
| 2.3125
| 2
|
[] |
no_license
|
public class data_genel {
//böyle bir class a bilgileri xhtml de gösterebilmek için gerekti
private String title;
private String content;
private int note_id;
public int getNote_id() {
return note_id;
}
public void setNote_id(int note_id) {
this.note_id = note_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
data_genel(){}
}
| true
|
488e86d8eca847cbae58fcaba544fa62f2094568
|
Java
|
Ignatoun/WTR-client-server-app
|
/sources/Backend/src/main/java/com/epolsoft/wtr/model/dto/ReportDetailsDTO.java
|
UTF-8
| 1,046
| 1.9375
| 2
|
[] |
no_license
|
package com.epolsoft.wtr.model.dto;
import com.epolsoft.wtr.model.Enums.Status;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.Set;
@ToString
@EqualsAndHashCode
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ReportDetailsDTO {
private Integer reportDetailsId;
@Temporal(TemporalType.DATE)
private Date reportDetailsDate;
@Enumerated(EnumType.STRING)
private Status status;
private Integer factorId;
private Integer locationId;
private Double hours;
private Double workUnits;
private Integer detailedTaskId;
private Integer taskId;
private Integer featureId;
private Integer projectId;
private String comments;
private Set<Integer> usersId;
}
| true
|
37e09b945a4e0a3903be16432f0657d0e02fa434
|
Java
|
zzaoen/code4master
|
/src/imp/designpattern/singleton/SingletonThread.java
|
UTF-8
| 998
| 3.703125
| 4
|
[] |
no_license
|
package imp.designpattern.singleton;
/**
* author : Bruce Zhao
* email : zhzh402@163.com
* date : 2018/4/13 14:01
* desc :
*/
public class SingletonThread extends Thread{
@Override
public void run() {
// System.out.println(HungryObject.getInstance().hashCode()); //一开始就初始化了,所以这个是线程安全的
// System.out.println(LazyObject.getInstance().hashCode()); // 使用的时候才初始化,线程不安全的
// System.out.println(LazyObject.getInstance().hashCode()); //使用synchronized同步方法,线程安全
// System.out.println(StaticInnerClassObject.getInstance().hashCode()); //和懒汉方式差不多,也是线程安全的
// System.out.println(StaticCodeObject.getInstance().hashCode());
System.out.println(EnumObject.enumOne.getInstance().hashCode());
System.out.println(EnumObject.getStaticInstance().hashCode()); //上面的例子中枚举类被暴露了,违反职责单一原则
}
}
| true
|
ccf9f5036f31e3d8f321282917dd711156c4c246
|
Java
|
zhouqwerty/amazon
|
/src/main/java/com/amazon/base/dto/BaseRequestDto.java
|
UTF-8
| 513
| 2.25
| 2
|
[] |
no_license
|
package com.amazon.base.dto;
/**
* @author 岸久
* @version 1.0
* @datetime 2018.7.24 18:58
* @describe 实体类 请求包装类
* */
public class BaseRequestDto<T> {
private Long time;
private T data;
public BaseRequestDto() {
}
public Long getTime() {
return this.time;
}
public void setTime(Long time) {
this.time = time;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
}
| true
|
e7b642254beeefeb3572bf05530b5489b8025a52
|
Java
|
Hogesss/Discrete-Event-Simulation
|
/Simulation.java
|
UTF-8
| 16,500
| 3.140625
| 3
|
[] |
no_license
|
/*
Simulation.java
*Author: Benjamin Hogan
*Student No: c3256846
*Date: 29/05/2017
*Descripion:
* Class that runs the simulation and outputs all the data needed for the production line
*/
import java.util.*;
import java.text.*;
public class Simulation{
private int station, counter;
private Object tempObject;
private double simulationTime = 0, tempProduction;
private Singleton singleton = Singleton.getInstance();
private Random r = new Random();
private boolean finished = false;
private PQ time = new PQ(10);
private Station s0A, s0B, s1, s2, s3A, s3B, s4, s5A, s5B, s6;
private Queue<Object> q01, q12, q23, q34, q45, q56;
// Role: runs the simulation for 10000000 time units and calls updateStages in a while loop.
// Args: int mean, range and max queue value for the simulation
// Return: None
public Simulation(int mean, int range, int max)
{
setup(mean, range, max);
do{
updateStages();
}while(simulationTime < 10000000);
finished = true;
// removes the remainder of the objects caught in the production when time stops
emptyProductionLine();
}
// Role: Sets up the production line with new queues and stations and creates objects in s0a and s0b
// Args: int mean, range and max queue value for the simulation
// Return: None
private void setup(int mean, int range, int qMax)
{
q01 = new Queue<Object>(qMax);
q12 = new Queue<Object>(qMax);
q23 = new Queue<Object>(qMax);
q34 = new Queue<Object>(qMax);
q45 = new Queue<Object>(qMax);
q56 = new Queue<Object>(qMax);
// NEW Queues with max size
s0A = new Station(null, q01, 2*mean, 2*range, 0);
s0B = new Station(null, q01, mean, range, 1);
s1 = new Station(q01, q12, mean, range, 2);
s2 = new Station(q12, q23, mean, range, 3);
s3A = new Station(q23, q34, 2*mean, 2*range, 4);
s3B = new Station(q23, q34, 2*mean, 2*range, 5);
s4 = new Station(q34, q45, mean, range, 6);
s5A = new Station(q45, q56, 2*mean, 2*range, 7);
s5B = new Station(q45, q56, 2*mean, 2*range, 8);
s6 = new Station(q56, null, mean, range, 9);
// NEW STATIONS with next and prev queues.
// create objects in stations for updateStages to start.
createObject(s0A, 0);
createObject(s0B, 1);
// any additional new creation stages for the start process
}
// Role: The production line in the simulation. Removes the object from the top of the time PQ and gets its time, increases the simulation time, then locates which station the object came from. Then completes production on that stage and checks stations either side if they are blocked or starved to continue the flow of the simulation.
// Args: None
// Return: None
private void updateStages()
{
// gets the object next in the PQ and gets the station it originated from
tempObject = time.removeHead(0).getData();
station = tempObject.getID();
// edits the rest of the objects in the time priority queue and increments time.
editTime(tempObject.getTime());
simulationTime += tempObject.getTime();
//S0A and S0B
if(station == 0 || station == 1)
{
try{
q01.append(tempObject, simulationTime);
if(station == 0) // S0A
createObject(s0A, 0);
else // S0B
createObject(s0B, 1);
}catch(NoSuchElementException e)// catches the exception and sets the station as blocked
{
if(station == 0)
setBlocked(s0A, simulationTime);
else
setBlocked(s0B, simulationTime);
}
//checks for starved station 1
checkStarved(s1);
}
// when the time is up, doesn't create more objects
if(finished)
{
try{
if(station == 0) // S0A
finishProduct(s0A);
if(station == 1) // S0B
finishProduct(s0B);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
if(station == 0)
setBlocked(s0A, simulationTime);
if(station == 1)
setBlocked(s0B, simulationTime);
}
//checks for starved station 1
checkStarved(s1);
}
if(station == 2) // S1
{
try{
finishProduct(s1);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s1, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s2);
if(!finished)
{checkBlocked(s0B);
checkBlocked(s0A);}
}
if(station == 3) // S2
{
try{
finishProduct(s2);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s2, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s3A);
checkStarved(s3B);
checkBlocked(s1);
}
if(station == 4) // S3A
{
try{
finishProduct(s3A);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s3A, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s4);
checkBlocked(s2);
}
if(station == 5) // S3B
{
try{
finishProduct(s3B);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s3B, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s4);
checkBlocked(s2);
}
if(station == 6) // S4
{
try{
finishProduct(s4);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s4, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s5A);
checkStarved(s5B);
checkBlocked(s3A);
checkBlocked(s3B);
}
if(station == 7) // S5A
{
try{
finishProduct(s5A);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s5A, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s6);
checkBlocked(s4);
}
if(station == 8) // S5B
{
try{
finishProduct(s5B);
}catch(NoSuchElementException e) // catches the exception and sets the station as blocked
{
setBlocked(s5B, simulationTime);
}
// checks stations either side for blocked or starved
checkStarved(s6);
checkBlocked(s4);
}
if(station == 9) // S6
{
// s6 simply finishes the object and gets rid of it, doesn't get blocked
finishProduct(s6);
// checks stations behind for blocked
checkBlocked(s5A);
checkBlocked(s5B);
}
// checks the amount of items in each queue at each update, used for the avg item statistic
q01.queueItems(); q12.queueItems(); q23.queueItems(); q34.queueItems();
q45.queueItems(); q56.queueItems();
counter++;
}
// Role: Removes time from the other events inside the time queue based on the head of the queue
// Preconditions: The head of time queue has been removed and the difference is the head object production time.
// Args: double time difference to the other times
// Return: None
private void editTime(double difference)
{
time.createIterator();
for(int x = 0; x < time.size(); x++)
{
Object temp = time.nextIter().getData();
if(temp.getTime() != 0)
temp.setTime(temp.getTime() - difference);
}
}
// Role: Stages s0A and s0B create objects with a new id from the singleton object and inserts it into the time PQ
// Args: Station for the object to be created, and int stage type
// Return: None
private void createObject(Station s00, int type)
{
// removes the current product and gets a new production time for the stage
s00.removeProduct();
tempProduction = s00.productionTime(r.nextDouble());
if(type == 0) // S0A
{
tempObject = new Object(singleton.getID()*10, tempProduction);
s00.setProduct(tempObject);
// sets the object to 0 for station S0A
tempObject.setID(0);
}
else // S0B
{
tempObject = new Object(singleton.getID()*10 + 1, tempProduction);
s00.setProduct(tempObject);
// sets the object to 1 for station S0B
tempObject.setID(1);
}
// inserts the new object into the queue
time.insertInOrder(tempObject);
}
// Role: checks if a station is starving by checking if its full then trying to get an object from the previous queue to fill it up
// Args: the Station to check
// Return: None
private void checkStarved(Station stage)
{
if(!stage.isFull()) // if stage is currently empty
{
try{
// gets the object off the previous queue and sets a new production time
tempObject = stage.getPrev().removeHead(simulationTime).getData();
tempObject.setTime(stage.productionTime(r.nextDouble()));
// fills up the stage and sets the id for the PQ
stage.setProduct(tempObject);
stage.setFull(true, simulationTime);
tempObject.setID(stage.getStageID());
// inserts the object into the PQ
time.insertInOrder(tempObject);
}catch(NullPointerException e){ /* If there is a Null Exception from removeHead(), then the station is still starving */ }
}
}
// Role: Finishes the current object in the station and sends it to the next station in the line.
// Args: The station that the object will finish
// Return: None
private void finishProduct(Station stage)
{
if(stage != s6)
stage.getNext().append(tempObject, simulationTime); // sends the finished product onto the next stage
stage.removeProduct();
stage.setFull(false, simulationTime); // station is starving
try{
// trys to get a product from the previous queue and sets a new production time
tempObject = stage.getPrev().removeHead(simulationTime).getData();
tempObject.setTime(stage.productionTime(r.nextDouble()));
// fills up the stage and sets the id for the PQ
stage.setProduct(tempObject);
stage.setFull(true, simulationTime);
tempObject.setID(stage.getStageID());
// inserts the object into the PQ
time.insertInOrder(tempObject);
}catch(NullPointerException e){ /* If there is a Null Exception from removeHead(), then the station is still starving */ }
}
// Role: Sets the stage as blocked and gets the time for blocked statistics
// Args: Station for the blocked stage, and double time
// Return: None
private void setBlocked(Station stage, double time)
{
stage.setBlocked(true, time);
}
// Role: checks if the station is blocked, and sets it to unblocked and puts it back in the PQ since the station infront just finished so there must be a spot on the queue.
// Args: Station that is blocked
// Return: None
private void checkBlocked(Station stage)
{
if(stage.isBlocked())
{
// sets the stage as unblocked
stage.setBlocked(false, simulationTime);
tempObject = stage.getProduct();
// sets the time as 0 and puts it back in the PQ to be quickly updated in the production line
if(tempObject != null)
{tempObject.setTime(0);
tempObject.setID(stage.getStageID());
time.insertInOrder(tempObject);}
}
}
// Role: Runs at the end of the time period to release all the stages and queues of their objects without creating more.
// Args: None
// Return: None
private void emptyProductionLine()
{
do{
updateStages();
}while(time.size()!= 0);
}
// Role: Prints all the program data for the simulation
// Args: None
// Return: None
public void output()
{
NumberFormat form = new DecimalFormat("#0.00");
// Stage data //
System.out.format("%10s%20s%20s%20s\n", "Stage","Production(%)", "Starving Time", "Blocking Time");
System.out.format("%10s%20s%20s%20s\n", "S0A", form.format(s0A.getProduction()), form.format(s0A.getStarvedTime()), form.format(s0A.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S0B", form.format(s0B.getProduction()), form.format(s0B.getStarvedTime()), form.format(s0B.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S1", form.format(s1.getProduction()), form.format(s1.getStarvedTime()), form.format(s1.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S2", form.format(s2.getProduction()), form.format(s2.getStarvedTime()), form.format(s2.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S3A", form.format(s3A.getProduction()), form.format(s3A.getStarvedTime()), form.format(s3A.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S3B", form.format(s3B.getProduction()), form.format(s3B.getStarvedTime()), form.format(s3B.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S4", form.format(s4.getProduction()), form.format(s4.getStarvedTime()), form.format(s4.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S5A", form.format(s5A.getProduction()), form.format(s5A.getStarvedTime()), form.format(s5A.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n", "S5B", form.format(s5B.getProduction()), form.format(s5B.getStarvedTime()), form.format(s5B.getBlockedTime()));
System.out.format("%10s%20s%20s%20s\n\n", "S6", form.format(s6.getProduction()), form.format(s6.getStarvedTime()), form.format(s6.getBlockedTime()));
// Queue data //
System.out.format("%10s%20s%20s\n", "Queue","Avg Time", "Avg Items");
System.out.format("%10s%20s%20s\n", "Q01", form.format(q01.getAvgTime()), form.format(q01.getQueueItems(counter)));
System.out.format("%10s%20s%20s\n", "Q12", form.format(q12.getAvgTime()), form.format(q12.getQueueItems(counter)));
System.out.format("%10s%20s%20s\n", "Q23", form.format(q23.getAvgTime()), form.format(q23.getQueueItems(counter)));
System.out.format("%10s%20s%20s\n", "Q34", form.format(q34.getAvgTime()), form.format(q34.getQueueItems(counter)));
System.out.format("%10s%20s%20s\n", "Q45", form.format(q45.getAvgTime()), form.format(q45.getQueueItems(counter)));
System.out.format("%10s%20s%20s\n", "Q56", form.format(q56.getAvgTime()), form.format(q56.getQueueItems(counter)));
System.out.println("\n S0A created: " + s0A.getProcessed());
System.out.println(" S0B created: " + s0B.getProcessed());
System.out.printf(" Time elapsed: %f\n", simulationTime);
}
}
| true
|
66f5d531b32aea97070a11aae79a11522c8298fc
|
Java
|
TeamworkGuy2/JParseCode
|
/src/twg2/parser/codeParser/extractors/MethodExtractor.java
|
UTF-8
| 8,060
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package twg2.parser.codeParser.extractors;
import java.util.ArrayList;
import java.util.List;
import twg2.ast.interm.annotation.AnnotationSig;
import twg2.ast.interm.block.BlockAst;
import twg2.ast.interm.method.MethodSigSimple;
import twg2.ast.interm.type.TypeSig;
import twg2.parser.codeParser.Keyword;
import twg2.parser.codeParser.BlockType;
import twg2.parser.codeParser.KeywordUtil;
import twg2.parser.codeParser.Operator;
import twg2.parser.codeParser.OperatorUtil;
import twg2.parser.codeParser.tools.NameUtil;
import twg2.parser.fragment.AstFragType;
import twg2.parser.fragment.CodeToken;
import twg2.parser.stateMachine.AstMemberInClassParserReusable;
import twg2.parser.stateMachine.AstParser;
import twg2.parser.stateMachine.Consume;
import twg2.treeLike.simpleTree.SimpleTree;
/**
* @author TeamworkGuy2
* @since 2015-11-24
*/
public class MethodExtractor extends AstMemberInClassParserReusable<MethodExtractor.State, List<MethodSigSimple>> {
static enum State {
INIT,
FINDING_ACCESS_MODIFIERS,
FINDING_TYPE_PARAMS,
FINDING_RETURN_TYPE,
FINDING_NAME,
FINDING_PARAMS,
COMPLETE,
FAILED;
}
KeywordUtil<? extends Keyword> keywordUtil;
OperatorUtil<? extends Operator> operatorUtil;
AstParser<List<AnnotationSig>> annotationParser;
AstParser<List<String>> commentParser;
AstParser<TypeSig.TypeSigSimple> typeParser;
List<TypeSig.TypeSigSimple> typeParameters = new ArrayList<>();
List<Keyword> accessModifiers = new ArrayList<>();
String methodName;
TypeSig.TypeSigSimple returnTypeSig;
List<MethodSigSimple> methods = new ArrayList<>();
/**
* @param parentBlock
* @param annotationParser this annotation parser should be being run external from this instance. When this instance finds a method signature,
* the annotation parser should already contain results (i.e. {@link AstParser#getParserResult()}) for the method's annotations
*/
public MethodExtractor(String langName, KeywordUtil<? extends Keyword> keywordUtil, OperatorUtil<? extends Operator> operatorUtil, BlockAst<? extends BlockType> parentBlock,
AstParser<TypeSig.TypeSigSimple> typeParser, AstParser<List<AnnotationSig>> annotationParser, AstParser<List<String>> commentParser) {
super(langName, "method signature", parentBlock, State.COMPLETE, State.FAILED);
this.keywordUtil = keywordUtil;
this.operatorUtil = operatorUtil;
this.methods = new ArrayList<>();
this.typeParser = typeParser;
this.annotationParser = annotationParser;
this.commentParser = commentParser;
this.state = State.INIT;
}
@Override
public boolean acceptNext(SimpleTree<CodeToken> tokenNode) {
if(state == State.COMPLETE || state == State.FAILED) {
state = State.INIT;
}
Consume res = null;
if(state == State.INIT) {
if(keywordUtil.methodModifiers().is(tokenNode.getData())) {
state = State.FINDING_ACCESS_MODIFIERS;
res = findingAccessModifiers(tokenNode);
if(res.isAccept()) { return true; }
}
if(AstFragType.isBlock(tokenNode.getData(), '<')) {
state = State.FINDING_TYPE_PARAMS;
res = findingTypeParams(tokenNode);
if(res.isAccept()) { return true; }
}
if(TypeExtractor.isPossiblyType(keywordUtil, tokenNode, true)) {
state = State.FINDING_RETURN_TYPE;
res = updateReturnTypeParser(tokenNode);
if(res.isAccept()) { return true; }
}
}
else if(state == State.FINDING_ACCESS_MODIFIERS) {
res = findingAccessModifiers(tokenNode);
if(res.isAccept()) { return true; }
}
else if(state == State.FINDING_TYPE_PARAMS) {
res = findingTypeParams(tokenNode);
if(res.isAccept()) { return true; }
}
else if(state == State.FINDING_RETURN_TYPE) {
res = findingReturnType(tokenNode);
if(res.isAccept()) { return true; }
}
else if(state == State.FINDING_NAME) {
res = findingName(tokenNode);
if(res.isAccept()) { return true; }
}
else if(state == State.FINDING_PARAMS) {
res = findingParams(tokenNode);
if(res.isAccept()) { return true; }
}
return false;
}
private Consume updateReturnTypeParser(SimpleTree<CodeToken> tokenNode) {
boolean res = typeParser.acceptNext(tokenNode);
boolean complete = typeParser.isComplete();
boolean failed = typeParser.isFailed();
if(complete) {
returnTypeSig = typeParser.getParserResult();
typeParser = typeParser.recycle();
state = State.FINDING_NAME;
}
else if(failed) {
typeParser = typeParser.recycle();
typeParameters.clear();
accessModifiers.clear();
state = State.FAILED;
}
return res ? Consume.ACCEPTED : Consume.REJECTED;
}
private Consume findingAccessModifiers(SimpleTree<CodeToken> tokenNode) {
var accessMod = AccessModifierExtractor.parseAccessModifier(keywordUtil, tokenNode);
if(accessMod != null) {
this.accessModifiers.add(accessMod);
return Consume.ACCEPTED;
}
else {
state = State.FINDING_TYPE_PARAMS;
var res2 = findingTypeParams(tokenNode);
if(res2 == Consume.REJECTED) {
accessModifiers.clear();
state = State.FAILED;
}
return res2;
}
}
private Consume findingTypeParams(SimpleTree<CodeToken> tokenNode) {
if(AstFragType.isBlock(tokenNode.getData(), '<')) {
var genericTypes = TypeExtractor.extractGenericTypes(tokenNode.getData().getText(), keywordUtil);
typeParameters.addAll(genericTypes.getParams());
return Consume.ACCEPTED;
}
else {
state = State.FINDING_RETURN_TYPE;
var res2 = findingReturnType(tokenNode);
if(res2 == Consume.REJECTED) {
typeParameters.clear();
accessModifiers.clear();
state = State.FAILED;
}
return res2;
}
}
private Consume findingReturnType(SimpleTree<CodeToken> tokenNode) {
var res = updateReturnTypeParser(tokenNode);
// required because type parser has to look ahead
if(state == State.FINDING_NAME) {
var res2 = findingName(tokenNode);
if(res2.isAccept()) { return res2; }
}
return res;
}
private Consume findingName(SimpleTree<CodeToken> tokenNode) {
if(AstFragType.isIdentifier(tokenNode.getData())) {
methodName = tokenNode.getData().getText();
if(methodName.endsWith(">")) {
var genericTypes = TypeExtractor.extractGenericTypes(methodName, keywordUtil);
methodName = genericTypes.getTypeName();
typeParameters.addAll(genericTypes.getParams());
}
state = State.FINDING_PARAMS;
return Consume.ACCEPTED;
}
typeParameters.clear();
accessModifiers.clear();
state = State.FAILED;
return Consume.REJECTED;
}
private Consume findingParams(SimpleTree<CodeToken> tokenNode) {
if(AstFragType.isBlock(tokenNode.getData(), '(')) {
state = State.COMPLETE;
var annotations = new ArrayList<>(annotationParser.getParserResult());
annotationParser.recycle();
var comments = new ArrayList<>(commentParser.getParserResult());
commentParser.recycle();
var params = MethodParametersParser.extractParamsFromSignature(keywordUtil, operatorUtil, annotationParser, tokenNode);
var typeParams = new ArrayList<>(typeParameters);
var accessMods = new ArrayList<>(accessModifiers);
annotationParser.recycle();
methods.add(new MethodSigSimple(methodName, NameUtil.newFqName(parentBlock.declaration.getFullName(), methodName), params, returnTypeSig, accessMods, typeParams, annotations, comments));
typeParameters.clear();
accessModifiers.clear();
return Consume.ACCEPTED;
}
typeParameters.clear();
accessModifiers.clear();
state = State.FAILED;
return Consume.REJECTED;
}
@Override
public List<MethodSigSimple> getParserResult() {
return methods;
}
@Override
public MethodExtractor recycle() {
reset();
return this;
}
@Override
public MethodExtractor copy() {
return new MethodExtractor(this.langName, this.keywordUtil, this.operatorUtil, this.parentBlock, this.typeParser.copy(), this.annotationParser.copy(), this.commentParser.copy());
}
// package-private
void reset() {
this.methods.clear();
this.typeParameters.clear();
this.accessModifiers.clear();
this.typeParser = typeParser.recycle();
this.annotationParser = annotationParser.recycle();
this.state = State.INIT;
}
}
| true
|
595eb152459c15006e9d38d6515408e716038bc8
|
Java
|
elizadascalu/JavaExercises
|
/Java/Lab2/src/com/company/Language.java
|
UTF-8
| 68
| 1.835938
| 2
|
[] |
no_license
|
package com.company;
public enum Language {
JAVA, PYTHON;
}
| true
|
0b8c020e812eb1387727e801bf034a2c1d3f6af4
|
Java
|
diogorosin/DevelOpenPDV-Android
|
/app/src/main/java/br/com/developen/pdv/room/SaleableModel.java
|
UTF-8
| 4,095
| 2.328125
| 2
|
[] |
no_license
|
package br.com.developen.pdv.room;
import androidx.room.DatabaseView;
import androidx.room.Embedded;
@DatabaseView(viewName = "Saleable", value = "SELECT " +
"Mer.product AS 'identifier', " +
"Cat.identifier AS 'catalog_identifier', " +
"Cat.active AS 'catalog_active', " +
"Cat.position AS 'catalog_position', " +
"Cat.denomination AS 'catalog_denomination', " +
"Mer.position AS 'position', " +
"Mer.reference AS 'reference', " +
"Mer.label AS 'label', " +
"MU.identifier AS 'measureUnit_identifier', " +
"MU.denomination AS 'measureUnit_denomination', " +
"MU.acronym AS 'measureUnit_acronym', " +
"MU.'group' AS 'measureUnit_group', " +
"Mer.price, " +
"0 AS 'type' " +
"FROM Merchandise Mer " +
"INNER JOIN Product Pdt ON Pdt.progeny = Mer.product " +
"INNER JOIN Progeny Pgn ON Pgn.identifier = Pdt.progeny " +
"INNER JOIN Catalog Cat ON Cat.identifier = Mer.catalog " +
"INNER JOIN MeasureUnit MU ON MU.identifier = Pdt.stockUnit " +
"WHERE Cat.active = 1 AND Pgn.active = 1 " +
"UNION ALL " +
"SELECT " +
"Ser.progeny AS 'identifier', " +
"Cat.identifier AS 'catalog_identifier', " +
"Cat.active AS 'catalog_active', " +
"Cat.position AS 'catalog_position', " +
"Cat.denomination AS 'catalog_denomination', " +
"Ser.position AS 'position', " +
"Ser.reference AS 'reference', " +
"Ser.label AS 'label', " +
"MU.identifier AS 'measureUnit_identifier', " +
"MU.denomination AS 'measureUnit_denomination', " +
"MU.acronym AS 'measureUnit_acronym', " +
"MU.'group' AS 'measureUnit_group', " +
"Ser.price, " +
"1 AS 'type' " +
"FROM Service Ser " +
"INNER JOIN Progeny Pgn ON Pgn.identifier = Ser.progeny " +
"INNER JOIN Catalog Cat ON Cat.identifier = Ser.catalog " +
"INNER JOIN MeasureUnit MU ON MU.identifier = Ser.measureUnit " +
"WHERE Cat.active = 1 AND Pgn.active = 1 " +
"ORDER BY 5, 7")
public class SaleableModel {
private Integer identifier;
@Embedded(prefix = "catalog_")
private CatalogModel catalog;
private Integer position;
private Integer reference;
private String label;
@Embedded(prefix = "measureUnit_")
private MeasureUnitModel measureUnit;
private Double price;
private Integer type;
public Integer getIdentifier() {
return identifier;
}
public void setIdentifier(Integer identifier) {
this.identifier = identifier;
}
public CatalogModel getCatalog() {
return catalog;
}
public void setCatalog(CatalogModel catalog) {
this.catalog = catalog;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public Integer getReference() {
return reference;
}
public void setReference(Integer reference) {
this.reference = reference;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public MeasureUnitModel getMeasureUnit() {
return measureUnit;
}
public void setMeasureUnit(MeasureUnitModel measureUnit) {
this.measureUnit = measureUnit;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SaleableModel that = (SaleableModel) o;
return identifier.equals(that.identifier);
}
public int hashCode() {
return identifier.hashCode();
}
}
| true
|
535b989b19161cafeae06ac5771e4431c27f65b5
|
Java
|
shadowjljp/Spring-MVC-design
|
/src/main/java/readshare/util/UnZipEpub.java
|
UTF-8
| 1,514
| 2.78125
| 3
|
[] |
no_license
|
package readshare.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnZipEpub {
// public void unzipfile() throws IOException{
// ZipFile zipFile=new ZipFile("D://Ebook/Java.epub");
// System.out.println("zipFile="+zipFile);
//
// }
public static void main(String[] args) throws IOException {
ZipFile zipFile=new ZipFile("D://Ebook/Java.epub");
System.out.println("zipFile"+zipFile);
String path = "D://unzip/";
Enumeration files = zipFile.entries();
while (files.hasMoreElements()) {
ZipEntry entry = (ZipEntry) files.nextElement();
if (entry.isDirectory()) {
File file = new File(path + entry.getName());
file.mkdir();
System.out.println("Create dir " + entry.getName());
} else {
File f = new File(path + entry.getName());
FileOutputStream fos = new FileOutputStream(f);
InputStream is = zipFile.getInputStream(entry);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
System.out.println("Create File " + entry.getName());
}
}
}
}
| true
|
f6fc20d607cbcc37af63b4a960d70a66462d9128
|
Java
|
SimoneJohnson04/Skipping-Intro
|
/PetTesting.java
|
UTF-8
| 3,286
| 4.28125
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class PetTesting {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Pet bunny;
System.out.println("Which constructor do you want? 1. Default \t2. Custom");
int choice = keyboard.nextInt();
if (choice == 1){
//creates a basic bunny without any special inputs
bunny = new Pet();
}
else{
//allows the user to create their own bunny by entering the name, age, and initial weight of the bunny, then using the Pet class to create the bunny
System.out.println("Enter the name: ");
keyboard.nextLine();
String nameOfBunny = keyboard.nextLine();
System.out.println("Enter the bunny's age:");
int ageOfBunny = keyboard.nextInt();
System.out.println("Enter the bunny's weight:");
double weightOfBunny = keyboard.nextDouble();
bunny = new Pet(nameOfBunny,ageOfBunny,weightOfBunny);
}
boolean gameOn = true;
while(gameOn){
System.out.printf("\n");
System.out.println(bunny.name + " eagerly awaits your attention. Select an action: \n1. Display your bunny's stats\n2. Feed the bunny some carrots(Weight + 0.2*carrots, Happiness + 1)\n3. Give the bunny some water(Weight + 0.2)\n4. Let your bunny hop through hoops(Energy-hops*0.1, Weight-hops*0.05)\n5. Cuddle with the bunny(Happiness + 1)\n6. Let the bunny take a nap(Energy + 0.01*Minutes)\n7. Teach your bunny a new trick(Intelligence + 1, Energy - 1)\n0. Stop playing with the virtual bunny");
choice = keyboard.nextInt();
System.out.printf("\n");
switch(choice){
case 1:
//displays all of the instance variables related to the bunny
bunny.displayStats();
break;
case 2:
//has the bunny eat the users input # of carrots
System.out.println("How many carrots will you give the bunny ?");
int carrots = keyboard.nextInt();
bunny.eat(carrots);
break;
case 3:
//runs the buny drinking method
bunny.drink();
break;
case 4:
//runs the hop method, and inputs the users # of hops
System.out.println("How many times should the bunny hop?");
int hops = keyboard.nextInt();
bunny.hop(hops);
break;
case 5:
//bunny cuddle method, with a void type
bunny.cuddle();
break;
case 6:
//has the bunny take a nap for the inputted amount of minutes
System.out.println("How many minutes should the bunny nap?");
int minutes = keyboard.nextInt();
bunny.nap(minutes);
break;
case 7:
//runs the trick method
bunny.trick();
break;
case 0:
//stops the game
System.out.println("Goodbye.");
gameOn = false;
return;
default:
//if the user enters a number that is not valid (ex. 19, or "s")
System.out.println("Please enter a valid selection.");
break;
}
//if the bunny is taken away, then the return will be false, setting the gameOn boolean to false and stopping the game
gameOn = bunny.bunnyState();
//this method uses a return in order to update the gameOn boolean, and thus is a boolean method rather than a void method
}
}
}
| true
|
200e2e73e6c27aa5504c512cb738ec928d94b92c
|
Java
|
Monil200/treesandmore
|
/treesandmore/src/treessandtrees/CountBattleShips.java
|
UTF-8
| 2,068
| 3.21875
| 3
|
[] |
no_license
|
package treessandtrees;
// similar to count islands, there is DP solution to this.
import java.util.*;
class Point {
int x,y;
Point(int xx, int yy) {
x = xx;
y = yy;
}
}
public class CountBattleShips {
public int getBattleShipCounts(char a[][], int x, int y, boolean visited[][]) {
Queue<Point> q = new LinkedList<Point>();
q.add(new Point(x,y));
while(!q.isEmpty()) {
Point front = q.remove();
visited[front.x][front.y] = true;
if (isValid(a,front.x+1,front.y, visited)) {
q.add(new Point(front.x+1,front.y));
}
if (isValid(a,front.x,front.y+1, visited)) {
q.add(new Point(front.x,front.y+1));
}
if (isValid(a,front.x-1,front.y, visited)) {
q.add(new Point(front.x-1,front.y));
}
if (isValid(a,front.x,front.y-1, visited)) {
q.add(new Point(front.x,front.y-1));
}
}
return 1;
}
public boolean isValid(char a[][], int x, int y, boolean visited[][]) {
if (x <0 || x >= a.length || y < 0 || y >=a[0].length) {
return false;
}
if (visited[x][y] || a[x][y] != 'X')
return false;
return true;
}
public static void main(String[] args) {
CountBattleShips obj = new CountBattleShips();
char a[][] = {
{'X', '.', '.', 'X'},
{'X', '.', '.', 'X'},
{'X', '.', '.', 'X'},
{'X', '.', '.', 'X'}
};
boolean visited[][] = new boolean[a.length][a[0].length];
int result = 0;
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[0].length;j++) {
if (!visited[i][j] && a[i][j] == 'X') {
result += obj.getBattleShipCounts(a,i,j,visited);
}
}
}
System.out.println("Number of battleShips are: " + result);
}
}
| true
|
b8c6a2e6b6956040989fb2cc55e9938c14ea3d6c
|
Java
|
lisaglendenning/zookeeper-lite
|
/zkcore/src/main/java/edu/uw/zookeeper/data/Serializers.java
|
UTF-8
| 9,517
| 2.359375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package edu.uw.zookeeper.data;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public enum Serializers {
REGISTRY;
public static Serializers getInstance() {
return REGISTRY;
}
public static interface ByteSerializer<T> {
byte[] toBytes(T input) throws IOException;
}
public static interface ByteDeserializer<T> {
<U extends T> U fromBytes(byte[] bytes, Class<U> type) throws IOException;
}
public static interface ByteCodec<T> extends ByteSerializer<T>, ByteDeserializer<T> {}
public <I,O> O toClass(I input, Class<O> outputType) {
Class<?> inputType = input.getClass();
Serializer method = find(inputType, outputType);
if (method == null) {
throw new IllegalArgumentException(String.format("Unable to serialize %s to %s", input, outputType));
}
O output = method.invoke(outputType, input);
return output;
}
public static enum ToString implements Function<Object, String> {
TO_STRING;
public static ToString getInstance() {
return TO_STRING;
}
@Override
public String apply(Object input) {
Class<?> inputType = input.getClass();
Serializer serializer = Serializers.getInstance().find(inputType, String.class);
if (serializer != null) {
return serializer.invoke(input);
} else {
return String.valueOf(input);
}
}
}
public static final Set<Class<?>> PRIMITIVE_TYPES = ImmutableSet.<Class<?>>of(String.class, byte[].class);
protected final ConcurrentMap<Class<?>, List<Serializer>> registry;
protected final ConcurrentMap<Class<?>, Set<Serializer>> byType;
private Serializers() {
this.registry = Maps.newConcurrentMap();
this.byType = Maps.newConcurrentMap();
}
public List<Serializer> add(Class<?> type) {
List<Serializer> serializers = registry.get(type);
if (serializers == null) {
serializers = Serializer.discover(type);
registry.put(type, serializers);
if (! serializers.isEmpty()) {
for (Serializer e: serializers) {
Class<?>[] types = { e.inputType(), e.outputType() };
for (Class<?> t: types) {
if (PRIMITIVE_TYPES.contains(t)) {
continue;
}
Set<Serializer> byTypeRegistry = byType.get(t);
if (byTypeRegistry == null) {
byType.putIfAbsent(t, Collections.synchronizedSet(Sets.<Serializer>newHashSet()));
byTypeRegistry = byType.get(t);
}
byTypeRegistry.add(e);
}
}
}
}
return serializers;
}
public List<Serializer> get(Class<?> type) {
return registry.get(type);
}
public Serializer find(Class<?> type,
Class<?> inputType, Class<?> outputType) {
List<Serializer> serializers = add(type);
return Serializer.find(serializers, inputType, outputType);
}
public Serializer find(Class<?> inputType, Class<?> outputType) {
Serializer serializer = null;
Class<?>[] types = { inputType, outputType };
for (Class<?> t: types) {
if (PRIMITIVE_TYPES.contains(t)) {
continue;
}
serializer = find(t, inputType, outputType);
if (serializer != null) {
break;
}
}
if (serializer == null) {
for (Class<?> t: types) {
if (PRIMITIVE_TYPES.contains(t)) {
continue;
}
if (byType.containsKey(t)) {
serializer = Serializer.find(byType.get(t), inputType, outputType);
if (serializer != null) {
break;
}
}
}
}
return serializer;
}
public static class Serializer {
public static List<Serializer> discover(Class<?> type) {
List<Serializer> serializers = Lists.newLinkedList();
for (Method method: type.getDeclaredMethods()) {
Serializes annotation = method.getAnnotation(Serializes.class);
if (annotation == null) {
continue;
}
Class<?> input = annotation.from();
if (input.equals(Void.class)) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 0) {
input = type;
} else if (parameterTypes.length == 1) {
input = parameterTypes[0];
}
}
if (input.equals(Void.class)) {
throw new IllegalArgumentException(String.format("Unable to determine input type from %s", method));
}
Class<?> output = annotation.to();
if (output.equals(Void.class)) {
output = method.getReturnType();
}
if (output.equals(Void.class)) {
throw new IllegalArgumentException(String.format("Unable to determine output type from %s", method));
}
Serializer serializer = new Serializer(method, input, output);
serializers.add(serializer);
}
return serializers;
}
public static Serializer find(Iterable<Serializer> serializers,
Class<?> inputType, Class<?> outputType) {
Serializer bestMatch = null;
for (Serializer serializer: serializers) {
if (serializer.inputType().isAssignableFrom(inputType)
&& outputType.isAssignableFrom(serializer.outputType())) {
if (bestMatch == null
|| ! serializer.inputType().isAssignableFrom(bestMatch.inputType())
|| ! serializer.outputType().isAssignableFrom(bestMatch.outputType())) {
bestMatch = serializer;
}
}
}
return bestMatch;
}
protected final Method method;
protected final Class<?> inputType;
protected final Class<?> outputType;
public Serializer(
Method method,
Class<?> inputType,
Class<?> outputType) {
this.method = method;
this.inputType = inputType;
this.outputType = outputType;
}
public Method method() {
return method;
}
public Class<?> inputType() {
return inputType;
}
public Class<?> outputType() {
return outputType;
}
@SuppressWarnings("unchecked")
public <O> O invoke(Object obj, Object...inputs) {
Object invObj = obj;
Object[] invInputs = inputs;
if (Modifier.isStatic(method().getModifiers()) && (! (obj instanceof Class<?>))) {
invObj = obj.getClass();
invInputs = new Object[inputs.length + 1];
invInputs[0] = obj;
for (int i=0; i<inputs.length; ++i) {
invInputs[i+1] = inputs[i];
}
}
O output;
try {
output = (O) method().invoke(invObj, invInputs);
} catch (Exception e) {
throw new RuntimeException(String.format("Unable to invoke %s on %s %s", method(), invObj, Arrays.toString(invInputs)), e);
}
return output;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("method", method())
.add("inputType", inputType())
.add("outputType", outputType())
.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (! (obj instanceof Serializer)) {
return false;
}
Serializer other = (Serializer)obj;
return Objects.equal(method(), other.method())
&& Objects.equal(inputType(), other.outputType())
&& Objects.equal(outputType(), other.outputType());
}
@Override
public int hashCode() {
return Objects.hashCode(method(), inputType(), outputType());
}
}
}
| true
|
785e7a79f1bd9740c185e1112b7c911a3d893c5d
|
Java
|
FlyingPumba/evolutiz
|
/subjects/are-we-there-yet/Wordpress_394/src/org/wordpress/android/About.java
|
UTF-8
| 1,640
| 2.21875
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package org.wordpress.android;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class About extends Activity {
final String tos_url = "http://en.wordpress.com/tos";
final String automattic_url = "http://automattic.com";
final String privacy_policy_url = "/privacy";
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.about);
TextView version = (TextView) findViewById(R.id.about_version);
PackageManager pm = getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo("org.wordpress.android", 0);
version.setText(getResources().getText(R.string.version) + " "
+ pi.versionName);
} catch (NameNotFoundException e) {
}
Button tos = (Button) findViewById(R.id.about_tos);
tos.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse(tos_url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
Button pp = (Button) findViewById(R.id.about_privacy);
pp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse(automattic_url + privacy_policy_url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
}
public void onClick(View v) {
Uri uri = Uri.parse(automattic_url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
}
| true
|
214e9a39ae30c54ed7dda24b5419f951d71ff5da
|
Java
|
yadorogi/deploygate-android-sdk
|
/sample/src/main/java/com/deploygate/sample/App.java
|
UTF-8
| 1,127
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.deploygate.sample;
import android.app.Application;
import com.deploygate.sdk.DeployGate;
/**
* THIS CLASS IS NOT USED BY DEFAULT. To use this implementation, you have to add on AndroidManifest.xml manually.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
// In most cases you don't have to do this, but if you have multiple processes in your application,
// or you want to customize initialize options, you can install DeployGate manually.
//
// Note that you also need to edit your AndroidManifest.xml to activate customized initializer.
// Refer the comment on AndroidManifest.xml included in this sample.
DeployGate.install(this, null, true);
// If you want to prevent the app distributed by someone else, specify your username on DeployGate
// as a second argument of DeployGate.install, like:
//
// DeployGate.install(this, "YOURUSERNAME");
//
// You can use DeployGate.isAuthorized() later to check the installation is valid or not.
}
}
| true
|
fb04bfd6d7b753201e7c37fac27ccc6b224cfb5b
|
Java
|
lomet1500/Project20201123
|
/Project20201123/src/com/ydm/Address/UnivFriend.java
|
UTF-8
| 748
| 2.828125
| 3
|
[] |
no_license
|
package com.ydm.Address;
public class UnivFriend extends Friend {
private String univ;
private String major;
public UnivFriend(String name, String phone) {
super(name, phone);
// TODO Auto-generated constructor stub
}
public String getUniv() {
return univ;
}
public void setUniv(String univ) {
this.univ = univ;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
@Override // source - override implement...
public void showFriendInfo() {
// TODO Auto-generated method stub
System.out.println("이름: " + super.getName() + ", 연락처: " + super.getPhone() + ", 학교: " + this.univ + ", 전공: " + this.major);
}
}
| true
|
d3763a3f305e38030d2676ef8ee9a98615ba27e3
|
Java
|
dpopkov/learn
|
/ijpds/src/main/java/learn/ijpds/ch12exceptions/exercises/E1219Linking.java
|
UTF-8
| 2,689
| 3.875
| 4
|
[] |
no_license
|
package learn.ijpds.ch12exceptions.exercises;
import learn.csia.utils.CliAppArgs;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Linking two files.
* Write a program that prompts the user to enter the name of an author and the title of one their books.
* It writes the author's name to a sorted file. The book's title is written at the end of Books.txt with
* the line number of the author's name in Authors.txt.
*/
public class E1219Linking {
public static void main(String[] args) {
CliAppArgs in = new CliAppArgs(args, "Enter author", "Enter book title");
String author = in.nextString();
String title = in.nextString();
File authorFile = new File("io/text/Authors.txt");
int position = -1;
try {
position = insert(author, authorFile);
System.out.println("position = " + position);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File titleFile = new File("io/text/Books.txt");
try (FileOutputStream fos = new FileOutputStream(titleFile, true);
PrintWriter out = new PrintWriter(fos)) {
out.println(title + " " + position);
} catch (IOException e) {
e.printStackTrace();
}
}
private static int insert(String author, File file) throws FileNotFoundException {
if (!file.exists()) {
try (PrintWriter out = new PrintWriter(file)) {
out.println(author);
return 0;
}
}
List<String> lines = new ArrayList<>();
int position = -1;
boolean found = false;
boolean inserted = false;
try (Scanner scanner = new Scanner(file)) {
while (!found && scanner.hasNextLine()) {
String current = scanner.nextLine();
if (!inserted) {
position++;
int compare = author.compareTo(current);
if (compare == 0) {
found = true;
} else if (compare < 0) {
lines.add(author);
inserted = true;
}
}
lines.add(current);
}
}
if (!found) {
if (!inserted) {
lines.add(author);
position = lines.size() - 1;
}
try (PrintWriter out = new PrintWriter(file)) {
for (String line : lines) {
out.println(line);
}
}
}
return position;
}
}
| true
|
c6cb814d1c9e457333f3c847d3698a3f6a31be07
|
Java
|
samuelnjri/CBSE_Game
|
/StealMySheep/application/src/test/java/stealmysheep/ApplicationTest.java
|
UTF-8
| 5,921
| 1.898438
| 2
|
[] |
no_license
|
package stealmysheep;
import group12.stealmysheep.GameStates.GameModule;
import group12.stealmysheep.Manager.ModuleManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.nio.file.Files.copy;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import junit.framework.Test;
import org.netbeans.junit.NbModuleSuite;
import org.netbeans.junit.NbTestCase;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import stealmysheep.common.services.IPlugin;
import stealmysheep.common.services.IUpdate;
import stealmysheep.common.services.IWave;
public class ApplicationTest extends NbTestCase {
private static final String UPDATES_XML = "C:/Users/oscar/OneDrive/Skrivebord/Project/Steal My Sheep/StealMySheep/netbeans_site/updates.xml";
private GameModule module;
private Document doc;
public static Test suite() {
return NbModuleSuite.createConfiguration(ApplicationTest.class).
gui(false).
failOnMessage(Level.OFF). // works at least in RELEASE71
failOnException(Level.INFO).
enableClasspathModules(false).
clusters(".*").
suite(); // RELEASE71+, else use NbModuleSuite.create(NbModuleSuite.createConfiguration(...))
}
public ApplicationTest(String n) {
super(n);
}
public void testApplication() throws InterruptedException, IOException {
setupModule();
System.out.println(this.module.getName());
List<IPlugin> plugins = new CopyOnWriteArrayList<>();
List<IUpdate> updates = new CopyOnWriteArrayList<>();
waitForUpdate(plugins, updates);
System.out.println("Testing with all modules");
assertEquals("Regular game plugins", 4, plugins.size());
assertEquals("Regular game updates", 5, updates.size());
System.out.println("Removing one module");
removeModule();
waitForUpdate(plugins, updates);
assertEquals("One module unloaded", 3, plugins.size());
assertEquals("One module unloaded", 4, updates.size());
System.out.println("Testing with all modules again");
addModule();
waitForUpdate(plugins, updates);
assertEquals("Regular game plugins", 4, plugins.size());
assertEquals("Regular game updates", 5, updates.size());
}
public void waitForUpdate(List<IPlugin> iplugins, List<IUpdate> iupdates) throws InterruptedException, IOException {
Thread.sleep(10000);
iplugins.clear();
iplugins.addAll(Lookup.getDefault().lookupAll(IPlugin.class));
iupdates.clear();
iupdates.addAll(Lookup.getDefault().lookupAll(IUpdate.class));
}
private void setupModule() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
this.doc = builder.parse(UPDATES_XML);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//module[@codenamebase=\"stealmysheep.Sheep\"]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println(nl.getLength());
Element e = (Element) nl.item(0);
String name = e.getAttribute("codenamebase");
this.module = new GameModule(name, true, nl.item(0), nl.item(0).getParentNode());
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
Exceptions.printStackTrace(ex);
}
}
private void removeModule() {
Node node = this.module.getNode().cloneNode(true);
this.module.getParent().removeChild(this.module.getNode());
this.module.setNode(node);
refreshFile();
}
private void addModule() {
this.module.setActive(true);
Node node = this.module.getNode();
this.module.getParent().appendChild(node);
refreshFile();
}
private void refreshFile() {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Source source = new DOMSource(doc);
Result result = new StreamResult(new FileOutputStream(UPDATES_XML));
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
Exceptions.printStackTrace(e);
} catch (TransformerException | FileNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
}
}
| true
|
4c98a6c8ad9152fc0d3a0ebe81a5360069f270ec
|
Java
|
peabits/idea-workspace
|
/idea-algorithm/程序员代码面试指南 —IT名企算法与数据结构题目最优解/src/chapter2/issue2/test/Test.java
|
UTF-8
| 767
| 2.90625
| 3
|
[] |
no_license
|
package chapter2.issue2.test;
import chapter2.issue2.solution.RemoveDoubleLinkedListLastKthNode;
import chapter2.issue2.solution.RemoveSingleLinkedListLastKthNode;
public class Test {
private RemoveSingleLinkedListLastKthNode singleLinkedList;
private RemoveDoubleLinkedListLastKthNode doubleLinkedList;
public Test(int[] arr) {
this.singleLinkedList = new RemoveSingleLinkedListLastKthNode(arr);
this.doubleLinkedList = new RemoveDoubleLinkedListLastKthNode(arr);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
Test test = new Test(arr);
test.singleLinkedList.removeSingleLinkedListLastKthNode(3);
test.doubleLinkedList.removeDoubleLinkedListLastKthNode(3);
}
}
| true
|
57c6f78628d41fb0a1fc9c076de013bc10e9c957
|
Java
|
parth-commits/Coronavirus
|
/app/src/main/java/com/example/android/coronavirus/CountryLoader.java
|
UTF-8
| 841
| 2.453125
| 2
|
[] |
no_license
|
package com.example.android.coronavirus;
import android.content.Context;
import android.content.AsyncTaskLoader;
import java.util.List;
public class CountryLoader extends AsyncTaskLoader<List<countryObject>> {
//query url
private String mUrl;
public CountryLoader(Context context, String url){
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
/**
* This is on a background thread.
*/
@Override
public List<countryObject> loadInBackground() {
if (mUrl == null) {
return null;
}
// Perform the network request, parse the response, and extract a list of earthquakes.
List<countryObject> countryObjects = QueryUtils.fetchCovidData(mUrl);
return countryObjects;
}
}
| true
|
7b9da24a79eac2c1fbde29a8284b643127a2c303
|
Java
|
jWinterDay/jwd-srv
|
/src/main/java/com/jwd/service/auth/ILoginService.java
|
UTF-8
| 532
| 2.046875
| 2
|
[] |
no_license
|
package com.jwd.service.auth;
import com.jwd.model.auth.Login;
import com.jwd.model.auth.LoginResponse;
import com.jwd.model.auth.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface ILoginService {
User findByEmail(String email);
int updateRefreshTokenByEmail(String refreshToken, String email);
LoginResponse login(Login loginForm);
String refreshToken(HttpServletRequest request,
HttpServletResponse response);
}
| true
|
02052a70b4bfc7b67cfa2ef9355d8a87d70389c3
|
Java
|
madalinflorin/online_medication_platform
|
/backend/src/main/java/ro/tuc/ds2020/entities/MedicalPlansDetail.java
|
UTF-8
| 2,864
| 2.390625
| 2
|
[] |
no_license
|
package ro.tuc.ds2020.entities;
import org.hibernate.annotations.Type;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Date;
import java.util.UUID;
@Entity
public class MedicalPlansDetail implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Type(type = "uuid-binary")
private UUID id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "dosage", nullable = false)
private float dosage;
@Column(columnDefinition = "date",name = "start_period_tratament", nullable = false)
private Date start_period_tratament;
@Column(columnDefinition = "date",name = "end_period_tratament", nullable = false)
private Date end_period_tratament;
private LocalTime intake_interval_start;
private LocalTime intake_interval_end;
public MedicalPlansDetail(){
}
public MedicalPlansDetail(UUID id, String name, float dosage, Date start_period_tratament, Date end_period_tratament, LocalTime intake_interval_start, LocalTime intake_interval_end) {
this.id = id;
this.name = name;
this.dosage = dosage;
this.start_period_tratament = start_period_tratament;
this.end_period_tratament = end_period_tratament;
this.intake_interval_start = intake_interval_start;
this.intake_interval_end = intake_interval_end;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getDosage() {
return dosage;
}
public void setDosage(float dosage) {
this.dosage = dosage;
}
public Date getStart_period_tratament() {
return start_period_tratament;
}
public void setStart_period_tratament(Date start_period_tratament) {
this.start_period_tratament = start_period_tratament;
}
public Date getEnd_period_tratament() {
return end_period_tratament;
}
public void setEnd_period_tratament(Date end_period_tratament) {
this.end_period_tratament = end_period_tratament;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public LocalTime getIntake_interval_start() {
return intake_interval_start;
}
public void setIntake_interval_start(LocalTime intake_interval_start) {
this.intake_interval_start = intake_interval_start;
}
public LocalTime getIntake_interval_end() {
return intake_interval_end;
}
public void setIntake_interval_end(LocalTime intake_interval_end) {
this.intake_interval_end = intake_interval_end;
}
}
| true
|
2cb94e4a0318d14dd39e1dcfa5d4e4bfa579447f
|
Java
|
benyben83/BloodBath
|
/app/src/main/java/com/example/dell_optilex_3010/bloodbath/charactercreation/Race.java
|
UTF-8
| 1,248
| 2.953125
| 3
|
[] |
no_license
|
package com.example.dell_optilex_3010.bloodbath.charactercreation;
public class Race {
private String name;
private int dexterity;
private int stamina;
private int intelligence;
private int knowledge;
public Race(String name, int dexterity, int stamina, int intelligence, int knowledge) {
this.name = name;
this.dexterity = dexterity;
this.stamina = stamina;
this.intelligence = intelligence;
this.knowledge = knowledge;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDexterity() {
return dexterity;
}
public void setDexterity(int dexterity) {
this.dexterity = dexterity;
}
public int getStamina() {
return stamina;
}
public void setStamina(int stamina) {
this.stamina = stamina;
}
public int getIntelligence() {
return intelligence;
}
public void setIntelligence(int intelligence) {
this.intelligence = intelligence;
}
public int getKnowledge() {
return knowledge;
}
public void setKnowledge(int knowledge) {
this.knowledge = knowledge;
}
}
| true
|
3a96e4f9bd828566cb28c13acd488efeb0dea875
|
Java
|
kdheejb7/2018-Tycoon-game
|
/RandomforSale.java
|
WINDOWS-1252
| 582
| 2.90625
| 3
|
[] |
no_license
|
import java.awt.*;
import javax.swing.*;
class RandomforSale extends JPanel {
Image bg = new ImageIcon("ballon.png").getImage();
RandomforSale() {
int value = (int)(Math.random() * 10);
JLabel jlab = new JLabel("ؾ\n"+ value + " \nּ");
add(jlab);
setOpaque(false);
// setLayout(new BorderLayout(10,10));
//// jlab.setLocation(0,0);
// jlab.setLocation(0,100);
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
}
| true
|
282f462ee84c92765f2a914a90febb82f8e7cee6
|
Java
|
statKim/TIL
|
/Linux/Hadoop/step01_hiveTest/src/step01_hiveTest/Step01.java
|
UHC
| 1,086
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
package step01_hiveTest;
import java.sql.Connection;
import java.sql.DriverManager;
//import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Step01 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//jdbc ϴ ״ ؾ!!(ex-hive or
Connection con = DriverManager.getConnection("jdbc:hive2://127.0.0.1:10000/default","","");
Statement stmt = con.createStatement(); //Statement ü
ResultSet res = stmt.executeQuery("SELECT * FROM person");
// preparedStatement ص (ణ ٸ.. Statement ü ü ..)
// PreparedStatement pstmt = con.prepareStatement("SELECT * FROM person");
// ResultSet res = pstmt.executeQuery();
while (res.next()) {
System.out.println(res.getString(1) + " " + res.getString(2));
}
con.close();
}
}
| true
|
423445fe66b2b8fb0dd7c111de8511339e31fff1
|
Java
|
ComputerArchitectureGroupPWr/JGenerilo
|
/src/test/java/pl/edu/pwr/iiar/zak/thermalKit/placer/ThermalPlacerTest.java
|
UTF-8
| 2,364
| 2.421875
| 2
|
[
"MIT"
] |
permissive
|
package pl.edu.pwr.iiar.zak.thermalKit.placer;
import edu.byu.ece.rapidSmith.design.Net;
import edu.byu.ece.rapidSmith.design.Pin;
import org.junit.Test;
import pl.edu.pwr.iiar.zak.thermalKit.ThermalDesign.ThermalDesign;
/**
* Created by pawel on 22.05.14.
*/
public class ThermalPlacerTest {
public String termometerEnableNet = "InstThermometersLogic/termometrEnable<1>";
@Test
public void testPlaceHeaters() throws Exception {
}
@Test
public void testPlaceThermometers() throws Exception {
}
@Test
public void testAddInternalNets() throws Exception {
}
@Test
public void testConnectHeaterEnableNets() throws Exception {
}
@Test
public void testConnectThermometerEnableNets() throws Exception {
ThermalDesign thermalDesign = new ThermalDesign();
thermalDesign.loadXMLFile("src/test/testData/generilo.xml");
System.out.format("Number of pins after xml parse from factory %d\n", thermalDesign.getThermometerUnits().get(0).getInternalNets().get(0).getPins().size());
ThermalPlacer placer = new ThermalPlacer(thermalDesign);
placer.placeThermometers();
placer.placeHeaters();
for (Net net : thermalDesign.getHeaterUnits().get(0).getInternalNets()) {
System.out.println(net.getName());
System.out.println(net.getPins().size());
for (Pin pin : net.getPins()) {
System.out.print("1");
System.out.println(pin);
}
}
placer.connectThermometerEnableNets();
placer.connectHeaterEnableNets();
Net thermEnable = thermalDesign.getNet(termometerEnableNet);
System.out.println("ENABLE PINS");
for (Pin enablePins : thermEnable.getPins())
System.out.println(enablePins);
System.out.println("Wire pins");
System.out.println(thermalDesign.getThermometerUnits().get(0).getInstances().get(0).getName());
for (Net net : thermalDesign.getThermometerUnits().get(0).getInternalNets()) {
System.out.println(net.getName());
System.out.println(net.getPins().size());
int i = 0;
for (Pin pin : net.getPins()) {
i++;
System.out.print(i);
System.out.println(pin);
}
}
}
}
| true
|