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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24972ef88e5048e3b71e696ebde20a86b415bc72
|
Java
|
blitzik/game
|
/Enums/MessageType.java
|
UTF-8
| 114
| 1.914063
| 2
|
[] |
no_license
|
package game.Enums;
/**
*
* @author aleš tichava
*/
public enum MessageType {
BONUS, WARRNING, BAD;
}
| true
|
1da22322d0bb3175d7b681757b308ed3c14e1038
|
Java
|
fsmflying/fsmflying
|
/fsmflying-spring/src/main/java/com/fsmflying/spring/controller/UserInterfaceController.java
|
UTF-8
| 5,139
| 1.8125
| 2
|
[] |
no_license
|
package com.fsmflying.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/ui")
public class UserInterfaceController {
@RequestMapping("/account/login")
public String goToLoginPage01()
{
return "login";
}
@RequestMapping("/user/login")
public String goToLoginPage02()
{
return "login";
}
@RequestMapping("/sysadmin/user/add")
public String goToAddPageOfSysUser()
{
return "sysadmin/userAdd";
}
@RequestMapping("/sysadmin/user/edit")
public String goToEditPageOfSysUser()
{
return "sysadmin/userEdit";
}
@RequestMapping("/sysadmin/user/list")
public String goToListPageOfSysUser()
{
return "sysadmin/userList";
}
@RequestMapping("/sysadmin/company/add")
public String goToAddPageOfSysCompany()
{
return "sysadmin/companyAdd";
}
@RequestMapping("/sysadmin/company/edit")
public String goToEditPageOfSysCompany()
{
return "sysadmin/companyEdit";
}
@RequestMapping("/sysadmin/company/list")
public String goToListPageOfSysCompany()
{
return "sysadmin/companyList";
}
@RequestMapping("/sysadmin/department/add")
public String goToAddPageOfSysDepartment()
{
return "sysadmin/departmentAdd";
}
@RequestMapping("/sysadmin/department/edit")
public String goToEditPageOfSysDepartment()
{
return "sysadmin/departmentEdit";
}
@RequestMapping("/sysadmin/department/list")
public String goToListPageOfSysDepartment()
{
return "sysadmin/departmentList";
}
@RequestMapping("/sysadmin/role/add")
public String goToAddPageOfSysRole()
{
return "sysadmin/roleAdd";
}
@RequestMapping("/sysadmin/role/edit")
public String goToEditPageOfSysRole()
{
return "sysadmin/roleEdit";
}
@RequestMapping("/sysadmin/role/list")
public String goToListPageOfSysRole()
{
return "sysadmin/roleList";
}
@RequestMapping("/sysadmin/tab/add")
public String goToAddPageOfSysTab()
{
return "sysadmin/tabAdd";
}
@RequestMapping("/sysadmin/tab/edit")
public String goToEditPageOfSysTab()
{
return "sysadmin/tabEdit";
}
@RequestMapping("/sysadmin/tab/list")
public String goToListPageOfSysTab()
{
return "sysadmin/tabList";
}
@RequestMapping("/sysadmin/menu/add")
public String goToAddPageOfSysMenu()
{
return "sysadmin/menuAdd";
}
@RequestMapping("/sysadmin/menu/edit")
public String goToEditPageOfSysMenu()
{
return "sysadmin/menuEdit";
}
@RequestMapping("/sysadmin/menu/list")
public String goToListPageOfSysMenu()
{
return "sysadmin/menuList";
}
@RequestMapping("/sysadmin/funcPoint/add")
public String goToAddPageOfSysFuncPoint()
{
return "sysadmin/funcPointAdd";
}
@RequestMapping("/sysadmin/funcPoint/edit")
public String goToEditPageOfSysFuncPoint()
{
return "sysadmin/funcPointEdit";
}
@RequestMapping("/sysadmin/funcPoint/list")
public String goToListPageOfFuncPoint()
{
return "sysadmin/funcPointList";
}
@RequestMapping("/sysadmin/dataAuth/add")
public String goToAddPageOfSysDataAuth()
{
return "sysadmin/dataAuthAdd";
}
@RequestMapping("/sysadmin/dataAuth/edit")
public String goToEditPageOfSysDataAuth()
{
return "sysadmin/dataAuthEdit";
}
@RequestMapping("/sysadmin/dataAuth/list")
public String goToListPageOfSysDataAuth()
{
return "sysadmin/dataAuthList";
}
@RequestMapping("/sysadmin/dataAuthItem/add")
public String goToAddPageOfSysDataAuthItem()
{
return "sysadmin/dataAuthItemAdd";
}
@RequestMapping("/sysadmin/dataAuthItem/edit")
public String goToEditPageOfSysDataAuthItem()
{
return "sysadmin/dataAuthItemEdit";
}
@RequestMapping("/sysadmin/dataAuthItem/list")
public String goToListPageOfSysDataAuthItem()
{
return "sysadmin/dataAuthItemList";
}
@RequestMapping("/sysadmin/dictDir/add")
public String goToAddPageOfSysDictDir()
{
return "sysadmin/dictDirAdd";
}
@RequestMapping("/sysadmin/dictDir/edit")
public String goToEditPageOfSysDictDir()
{
return "sysadmin/dictDirEdit";
}
@RequestMapping("/sysadmin/dictDir/list")
public String goToListPageOfSysDictDir()
{
return "sysadmin/dictDirList";
}
@RequestMapping("/sysadmin/dictItem/add")
public String goToAddPageOfSysDictItem()
{
return "sysadmin/dictItemAdd";
}
@RequestMapping("/sysadmin/dictItem/edit")
public String goToEditPageOfSysDictItem()
{
return "sysadmin/dictItemEdit";
}
@RequestMapping("/sysadmin/dictItem/list")
public String goToListPageOfSysDictItem()
{
return "sysadmin/dictItemList";
}
@RequestMapping("/sysadmin/config/add")
public String goToAddPageOfSysConfig()
{
return "sysadmin/configAdd";
}
@RequestMapping("/sysadmin/config/edit")
public String goToEditPageOfSysConfig()
{
return "sysadmin/configEdit";
}
@RequestMapping("/sysadmin/config/list")
public String goToListPageOfSysConfig()
{
return "sysadmin/configList";
}
}
| true
|
f8c617d5fe37b8f4b84695a4d477ec767b940980
|
Java
|
bilalsay/TCP_Game_Homework
|
/controller/MainController.java
|
UTF-8
| 1,408
| 2.25
| 2
|
[] |
no_license
|
package sample.controller;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import sample.*;
import sample.services.Game;
import java.io.IOException;
public class MainController extends Controller {
@FXML
private TextField serverName;
@FXML
public VBox serverContainer;
private Game game;
public void createServer() throws IOException {
FXMLLoader mainLoader = new FXMLLoader();
mainLoader.setLocation(Main.class.getResource("/sample/resources/gameBoard.fxml"));
main.mainLayout.setCenter(mainLoader.load());
BoardController boardController = (BoardController) mainLoader.getController();
boardController.setMain(main);
game = new Game(boardController, true, 20, 2, 5);
game.setServerName(serverName.getText());
}
public void listInvet() throws IOException {
FXMLLoader mainLoader = new FXMLLoader();
mainLoader.setLocation(Main.class.getResource("/sample/resources/gameBoard.fxml"));
main.mainLayout.setCenter(mainLoader.load());
BoardController boardController = (BoardController) mainLoader.getController();
boardController.setMain(main);
game = new Game(boardController, false,20, 2, 5);
game.start();
game.getBoardController().okButton.setVisible(false);
}
}
| true
|
00db91cefd2157a785f4f383be94664959772d1a
|
Java
|
EvgeniyShipov/threads
|
/src/main/java/ru/sbt/threads/Exercise1/CallableException.java
|
UTF-8
| 261
| 2.421875
| 2
|
[] |
no_license
|
package ru.sbt.threads.Exercise1;
public class CallableException extends RuntimeException {
public CallableException(Exception e) {
super(e);
System.out.println("Произошла ошибка. Попробуйте позже.");
}
}
| true
|
ddbf72c406fdc73943042dc767290efce9df2e96
|
Java
|
sdibona/ocapi
|
/src/main/java/org/akaza/openclinica/domain/dao/EventDefinitionCrfDao.java
|
UTF-8
| 2,272
| 2.015625
| 2
|
[] |
no_license
|
package org.akaza.openclinica.domain.dao;
import java.util.List;
import org.akaza.openclinica.domain.datamap.EventDefinitionCrf;
import org.springframework.stereotype.Service;
@Service
public class EventDefinitionCrfDao extends AbstractDomainDao<EventDefinitionCrf> {
@Override
Class<EventDefinitionCrf> domainClass() {
// TODO Auto-generated method stub
return EventDefinitionCrf.class;
}
@SuppressWarnings("unchecked")
public List<EventDefinitionCrf> findByStudyEventDefinitionId(int studyEventDefinitionId) {
String query = "from "
+ getDomainClassName()
+ " event_definition_crf where event_definition_crf.studyEventDefinition.studyEventDefinitionId = :studyeventdefinitionid";
org.hibernate.Query q = getCurrentSession().createQuery(query);
q.setInteger("studyeventdefinitionid", studyEventDefinitionId);
return (List<EventDefinitionCrf>) q.list();
}
@SuppressWarnings("unchecked")
public List<EventDefinitionCrf> findAvailableByStudyEventDefStudy(Integer studyEventDefinitionId, Integer studyId) {
String query = "from " + getDomainClassName() + " do where do.studyEventDefinition.studyEventDefinitionId = :studyeventdefid " +
" and do.study.studyId = :studyid and do.statusId = 1";
org.hibernate.Query q = getCurrentSession().createQuery(query);
q.setInteger("studyeventdefid", studyEventDefinitionId);
q.setInteger("studyid", studyId);
return (List<EventDefinitionCrf>) q.list();
}
@SuppressWarnings("unchecked")
public List<EventDefinitionCrf> findSiteHiddenByStudyEventDefStudy(Integer studyEventDefinitionId, Integer studyId) {
String query = "from " + getDomainClassName() + " do where do.studyEventDefinition.studyEventDefinitionId = :studyeventdefid " +
" and do.study.studyId = :studyid and do.statusId = 1 and do.hideCrf = true";
org.hibernate.Query q = getCurrentSession().createQuery(query);
q.setInteger("studyeventdefid", studyEventDefinitionId);
q.setInteger("studyid", studyId);
return (List<EventDefinitionCrf>) q.list();
}
}
| true
|
80f901f3818ca1899e2315952156c63c02322940
|
Java
|
icarus94/StruDvoriste
|
/src/linearnestrukture/dinamicke/dslista/CvorDSListe.java
|
UTF-8
| 1,558
| 3.765625
| 4
|
[] |
no_license
|
package linearnestrukture.dinamicke.dslista;
/**
* Cvor dvostruko spregnute liste. Svaki cvor liste u sebi cuva podatak (kod
* ovog cvora to je ceo broj) i pokazivace na prethodni i sledeci cvor.
*
* @author Dejan Stojimirovic, Strukture podataka i algoritmi, FON, 2014
*
*/
public class CvorDSListe {
// podatak koji se cuva u cvoru.
// Ako cvor treba da cuva neki drugi tip elementa, ovde to treba promeniti
public int podatak;
// "pokazivac" na prethodni cvor u listi
public CvorDSListe prethodni;
// "pokazivac" na sledeci cvor u listi
public CvorDSListe sledeci;
/**
* Konstruktor. Prihvata i postavlja sve elemente cvora.
*
* @param p Podatak koji se cuva u cvoru.
* @param pret Pokazivac na prethodni element liste
* @param sled Pokazivac na sledeći element za cvor koji se kreira
*
*/
public CvorDSListe(int p, CvorDSListe pret, CvorDSListe sled) {
podatak = p;
prethodni = pret;
sledeci = sled;
}
public int getPodatak() {
return podatak;
}
public void setPodatak(int podatak) {
this.podatak = podatak;
}
public CvorDSListe getPrethodni() {
return prethodni;
}
public void setPrethodni(CvorDSListe prethodni) {
this.prethodni = prethodni;
}
public CvorDSListe getSledeci() {
return sledeci;
}
public String toString() {
return "podatak "+this.podatak ;//+" sledeci "+this.sledeci.podatak+" predhodni "+this.prethodni.podatak;
}
public void setSledeci(CvorDSListe sledeci) {
this.sledeci = sledeci;
}
}
| true
|
3a70a3ff1715eae2c1bfb99341151d6fe7f84532
|
Java
|
lyq0604/spring-cloud-demo
|
/spring-cloud-auth/src/main/java/com/blade/springcloudauth/entity/User.java
|
UTF-8
| 2,957
| 2.234375
| 2
|
[] |
no_license
|
package com.blade.springcloudauth.entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Table(name = "base_user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private String name;
@NotNull
private String username;
@NotNull
private String password;
private String sex;
private String QQ;
private String phone;
private String address;
private String remark;
private String state;
private static final long serialVersionUID = 1L;
/**
* @return id
*/
public String getId() {
return id;
}
/**
* @param id
*/
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* @return username
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
/**
* @return password
*/
public String getPassword() {
return password;
}
/**
* @param password
*/
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getQQ() {
return QQ;
}
public void setQQ(String QQ) {
this.QQ = QQ;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", qq='" + QQ + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
", remark='" + remark + '\'' +
", state='" + state + '\'' +
'}';
}
}
| true
|
a39ac35924f174abb9b8da97320a2dcc6c0e61f3
|
Java
|
rafa-gao/dbook
|
/dbook-member/src/main/java/com/rafagao/dbook/member/controller/MemberController.java
|
UTF-8
| 2,013
| 2.28125
| 2
|
[] |
no_license
|
package com.rafagao.dbook.member.controller;
import com.rafagao.dbook.common.api.CommonResult;
import com.rafagao.dbook.common.exception.DBookUserException;
import com.rafagao.dbook.domain.DbookMember;
import com.rafagao.dbook.member.dto.MemberInfo;
import com.rafagao.dbook.member.dto.param.MemberRegisterParam;
import com.rafagao.dbook.member.dto.param.UserLoginParam;
import com.rafagao.dbook.member.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author rafa gao
*/
@RestController
@RequestMapping("/user")
public class MemberController {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private MemberService memberService;
/**
* 用户登录接口
*
* @return
*/
@PostMapping("/login")
public CommonResult login(@RequestBody UserLoginParam userLoginParam){
try {
// 拿到数据
DbookMember member = memberService.login(userLoginParam.getUsername(), userLoginParam.getPassword());
Map<String,String> dataMap=new HashMap<>();
dataMap.put("username",member.getUsername());
dataMap.put("icon", member.getIcon());
dataMap.put("personalizedSignature",member.getPersonalizedSignature());
return CommonResult.success(dataMap);
}catch (DBookUserException e){
return new CommonResult(null,e.getMessage(),e.getCode());
}
}
/**
* 用户注册接口
*
* @param
* @return
*/
@PostMapping("/register")
@CrossOrigin(origins = "*", maxAge = 3600)
public CommonResult register(@RequestBody MemberRegisterParam memberRegisterParam){
MemberInfo register = memberService.register(memberRegisterParam);
return CommonResult.success(register.getUsername());
}
}
| true
|
b4b802f27a5a7c5b7acf02ac08de62c9cf046d4a
|
Java
|
haoyuehong/push
|
/huaweipush/com/huawei/push/model/Importance.java
|
UTF-8
| 343
| 2.015625
| 2
|
[] |
no_license
|
//
// Decompiled by Procyon v0.5.36
//
package com.huawei.push.model;
public enum Importance
{
LOW("LOW"),
NORMAL("NORMAL"),
HIGH("HIGH");
private String value;
private Importance(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
| true
|
12ebfe228977d23c3ddf8b0aa0f8d4ba7abb33eb
|
Java
|
shouzhangbo/tesppent
|
/paypal/src/main/java/com/my/paypal/ctrl/TestCtrl.java
|
UTF-8
| 955
| 2.03125
| 2
|
[] |
no_license
|
package com.my.paypal.ctrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.my.paypal.mapper.TestMapper;
@Controller
public class TestCtrl {
private static final Log log = LogFactory.getLog(TestCtrl.class);
@Autowired
private TestMapper testMapper;
@RequestMapping("/test")
@ResponseBody
public String test(String name){
log.info("info级别的日志输出:into test controller!!");
log.error("error级别的日志输出:into test controller!!");
log.debug("debug级别的日志输出:into test controller!!");
// System.out.println(testMapper.getTest().size());
return null==name?"this is a test!":name;
}
}
| true
|
55f6ae489b4dfa274a35472dd9f0006a62487be0
|
Java
|
julienvillegas/libgdx.info-particleEffect
|
/core/src/com/mygdx/game/MyGdxGame.java
|
UTF-8
| 797
| 2.234375
| 2
|
[] |
no_license
|
package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.mygdx.game.Screens.TitleScreen;
public class MyGdxGame extends Game {
static public Skin skin;
static public TextureAtlas textureAtlas;
@Override
public void create () {
skin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
textureAtlas = new TextureAtlas();
textureAtlas.addRegion("note",new TextureRegion(new Texture("note.png")));
this.setScreen(new TitleScreen(this));
}
@Override
public void render () {
super.render();
}
public void dispose () {
skin.dispose();
}
}
| true
|
250ec4d0ce37fcc0a7d906b687e76e2284edf6d5
|
Java
|
aayushibaghel/Demo_QA
|
/demoqa/RegistrationForm.java
|
UTF-8
| 3,205
| 2.21875
| 2
|
[] |
no_license
|
package demoqa;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import BrowserFactory.BrowserPage;
import readExcel.ReadExcelSheet;
import registration.ClickOnRegistration;
public class RegistrationForm {
WebDriver driver;
public void Form(String current_url,WebDriver driver)
{
ReadExcelSheet rd= new ReadExcelSheet("C:\\Aayushi\\Selenium\\ExcelData\\TestData1.xlsx");
String td1= rd.getData(0, 0, 0);
String td2= rd.getData(0, 0, 1);
String td3= rd.getData(0, 0, 2);
String td4= rd.getData(0, 0, 3);
String td5= rd.getData(0, 0, 4);
String td6= rd.getData(0, 0, 5);
String td7= rd.getData(0, 0, 6);
String td8= rd.getData(0, 0, 7);
String td9= rd.getData(0, 0, 8);
String td10= rd.getData(0, 0, 9);
String td11= rd.getData(0, 0, 10);
String td12= rd.getData(0, 0, 11);
String td13= rd.getData(0, 0, 12);
String td14= rd.getData(0, 0, 13);
String td15= rd.getData(0, 0, 14);
/*System.out.println("reched");
//ClickOnRegistration cl= new ClickOnRegistration();
//driver=cl.getDriverValue();
// System.out.println("fetched driver is "+ driver);
//driver.get(current_url);
System.out.println("Fetched url is ");*/
driver.findElement(By.xpath("//*[@id='name_3_firstname']")).sendKeys(td1);
driver.findElement(By.xpath("//*[@id='name_3_lastname']")).sendKeys(td2);
List <WebElement> radio= driver.findElements(By.xpath("//input[@type='radio' and @name='radio_4[]']"));
for(int i=0;i<radio.size();i++)
{
WebElement loc_rad= radio.get(i);
String val= loc_rad.getAttribute("value");
if(val.equalsIgnoreCase(td3))
{
loc_rad.click();
}
}
List<WebElement> chkbox= driver.findElements(By.xpath("//input[@type='checkbox' and @name='checkbox_5[]']"));
for(int i=0;i<chkbox.size();i++)
{
WebElement loc_chk= chkbox.get(i);
String sval= loc_chk.getAttribute("value");
if(sval.equalsIgnoreCase(td4))
{
loc_chk.click();
}
else if(sval.equalsIgnoreCase(td5))
{
loc_chk.click();
}
}
WebElement drpdwn_country= driver.findElement(By.id("dropdown_7"));
Select val= new Select(drpdwn_country);
val.selectByVisibleText(td6);
WebElement drpdwn_dob1= driver.findElement(By.id("mm_date_8"));
Select dob_month= new Select(drpdwn_dob1);
dob_month.selectByVisibleText(td7);
WebElement drpdwn_dob2= driver.findElement(By.id("dd_date_8"));
Select dob_day= new Select(drpdwn_dob2);
dob_day.selectByVisibleText(td8);
WebElement drpdwn_dob3= driver.findElement(By.id("yy_date_8"));
Select dob_year= new Select(drpdwn_dob3);
dob_year.selectByVisibleText(td9);
driver.findElement(By.id("phone_9")).sendKeys(td10);
driver.findElement(By.id("username")).sendKeys(td11);
driver.findElement(By.id("email_1")).sendKeys(td12);
driver.findElement(By.id("description")).sendKeys(td13);
driver.findElement(By.id("password_2")).sendKeys(td14);
driver.findElement(By.id("confirm_password_password_2")).sendKeys(td15);
driver.findElement(By.name("pie_submit")).click();
}
}
| true
|
5c9f5989e04b887a80f55517f8e5b18b41511380
|
Java
|
AndersonESilva/mvpsamplejava
|
/app/src/main/java/com/zup/bank/service/AsyncService.java
|
UTF-8
| 687
| 2.234375
| 2
|
[] |
no_license
|
package com.zup.bank.service;
import android.os.AsyncTask;
import com.zup.bank.Db.DbConnection;
public class AsyncService extends AsyncTask<String, Void, String> {
private int opcao;
public AsyncService(int opcao){
this.opcao = opcao;
}
@Override
protected String doInBackground(String... strings) {
switch (opcao){
case 0:{
String result = new DbConnection().autenticacao(strings[0],strings[1]);
return result;
}
case 1:{
String result = new DbConnection().getStatements();
return result;
}
}
return null;
}
}
| true
|
6a82d14b90fbd7a43f3822b049553ea98cd21c78
|
Java
|
whytekieran/MultithreadCypherBreaker
|
/src/ie/gmit/sw/Resultable.java
|
UTF-8
| 493
| 2.671875
| 3
|
[] |
no_license
|
package ie.gmit.sw;
/**
* An interface for all Resultable's that are used in Multithread cyphers. Contains the basic methods you should be
* able to do with a Result object.
* @author Ciaran Whyte
* @version 1.0
*/
public interface Resultable
{
public abstract String getPlainText();
public abstract void setPlainText(String plainText);
public abstract int getKey();
public abstract void setKey(int key);
public abstract int getScore();
public abstract void setScore(int score);
}
| true
|
f5db31137bf62a0dfb850225f9044a1b819e70c0
|
Java
|
testUserDX/CIManager
|
/src/main/java/com/model/Org.java
|
UTF-8
| 3,468
| 2.046875
| 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.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author new
*/
@Entity
@Table(name = "org")
@XmlRootElement
public class Org implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;
@Basic(optional = false)
@Column(name = "orgLink")
private String orgLink;
@Basic(optional = false)
@Column(name = "login")
private String login;
@Basic(optional = false)
@Column(name = "password")
private String password;
@Column(name = "isProduction")
private Boolean isProduction;
@Basic(optional = false)
@Column(name = "branch_name")
private String branchName;
@ManyToMany
@JoinTable(name = "user_has_org", joinColumns = {
@JoinColumn(name = "Org_id", referencedColumnName = "id")}, inverseJoinColumns = {
@JoinColumn(name = "User_id", referencedColumnName = "id")})
private List<User> userList= new ArrayList<>();
@JoinColumn(name = "project_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Project projectId;
public Org() {
}
public Org(Long id) {
this.id = id;
}
public Org(Long id, String login, String password, String branchName) {
this.id = id;
this.login = login;
this.password = password;
this.branchName = branchName;
}
public Org(String login, String password, String branchName, String orgLink, Project projectId) {
this.login = login;
this.password = password;
this.branchName = branchName;
this.projectId = projectId;
this.orgLink = orgLink;
}
public String getOrgLink() {
return orgLink;
}
public void setOrgLink(String orgLink) {
this.orgLink = orgLink;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getIsProduction() {
return isProduction;
}
public void setIsProduction(Boolean isProduction) {
this.isProduction = isProduction;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
@XmlTransient
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public Project getProjectId() {
return projectId;
}
public void setProjectId(Project projectId) {
this.projectId = projectId;
}
@Override
public String toString() {
return "com.model.Org[ id=" + id + " ]";
}
}
| true
|
1527a1ce29f2875fddf4e8d3ff41bbe9177101e9
|
Java
|
AVAtric/wsode3
|
/src/RateMal.java
|
UTF-8
| 898
| 3.84375
| 4
|
[] |
no_license
|
/**
* RateMal dient zur veranschaulichung der Benutzung der Math-Klasse.
*
* @author Adnan Vatric
* @version v 1.0
*/
public class RateMal {
/**
* Eine Zahl muss über die Konsole eingegeben Werden und diese wird mit
* einer zufällig generierten Zahl verglichen.
*
* @param args Es werde keine Parameter verwendet.
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
int zahl = (int) (1 + Math.random() * 9); // Zufällige Zahl zwischen 1 und 9 erstellen
// User gibt eine Zahl ein
System.out.println("Welche Zahl denke ich mir zwischen 1 und 9?");
int raten = new java.util.Scanner(System.in).nextInt();
// Zahl prüfen
if (zahl == raten)
System.out.println("Glück gehabt!");
else
System.out.printf("Sorry, ich habe mir die %s ausgedacht!", zahl);
}
}
| true
|
850efcf65eeac239363b0476c97cb23d1bdeb33d
|
Java
|
wolodey/zertifizierung_oracle
|
/src/ZertifizierungsProgramm/Test_Level3/v8_2_984/v8_2_1090/TestClass.java
|
UTF-8
| 397
| 2.671875
| 3
|
[] |
no_license
|
package ZertifizierungsProgramm.Test_Level3.v8_2_984.v8_2_1090;
/**
* Created by WSteinle on 02.02.2017.
*/
public class TestClass {
public static void main(String[] args) {
int sum = 0;
for (int i = 0, j = 10; sum < 20; ++i, --j) {
sum = sum + i + j;
}
System.out.println(sum);
char x = 'a';
System.out.println(""+ x);
}
}
| true
|
5b97e07ebed2d36d817b8ef86dc779174f0c0a82
|
Java
|
kharkovstiger/serverForBB
|
/src/main/java/serverForBB/repository/PlayerRepository.java
|
UTF-8
| 367
| 1.96875
| 2
|
[] |
no_license
|
package serverForBB.repository;
import serverForBB.model.Player;
import java.util.List;
public interface PlayerRepository {
Player save(Player player);
Player findOne(String id);
List<Player> getAllFromCountry(String country);
List<Player> getAllFromCountryMinGames(String country);
List<Player> getAllMinGames(boolean u21);
}
| true
|
11a59cbfdb838eb78ac0a184d54f83bd948a3783
|
Java
|
fgregg/cm
|
/2.7.x/choicemaker-cm/choicemaker-modeling/com.choicemaker.cm.matching.cfg/src/main/java/com/choicemaker/cm/matching/cfg/ContextFreeGrammar.java
|
UTF-8
| 11,035
| 2.359375
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2001, 2009 ChoiceMaker Technologies, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License
* v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ChoiceMaker Technologies, Inc. - initial API and implementation
*/
package com.choicemaker.cm.matching.cfg;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.choicemaker.cm.matching.cfg.tokentype.InlineTokenType;
/**
* Represents a context-free grammar.
*
* CFG's are immutable, i.e. Rules and StartSymbol cannot be changed
* after initialization.
*
* @author Adam Winkel
* @version $Revision: 1.1.1.1 $ $Date: 2009/05/03 16:02:59 $
*/
public class ContextFreeGrammar {
/** the start Variable for this CFG */
protected Variable startVariable;
/** the Variables used by this CFG */
protected HashSet variables = new HashSet();
/**
* A hash of collections from LHS symbol to a collection of rules
* that have that symbol as the LHS.
*/
protected Map lhsBuckets = new HashMap();
/**
* Default constructor for subclasses like CnfGrammar.
*/
protected ContextFreeGrammar() { }
/**
* Create a new ContextFreeGrammar with the specified start variable
* and rules.
*
* @param startVariable the start variable
* @param rules the rules in this
*/
public ContextFreeGrammar(Variable startVariable, Collection rules) {
this.startVariable = startVariable;
addAllRules(rules);
}
/**
* Add all the rules in <code>rules</code> to this CFG's set of rules.
*
* @throws IllegalArgumentException if <code>rules</code> contains a
* "leaf rule" with a TokenType on the LHS and a Token on the RHS.
*/
public void addAllRules(Collection rules) {
Iterator elements = rules.iterator();
while (elements.hasNext()) {
addRule((Rule) elements.next());
}
}
/**
* Add <code>rule</code> to this CFG's set of rules.
*
* @throws IllegalArgumentException if <code>rule</code> is a
* "leaf rule"
*/
public void addRule(Rule rule) {
// check the validity of the RHS.
int rhsSize = rule.getRhsSize();
for (int i = 0; i < rhsSize; i++) {
if (rule.getRhsSymbol(i) instanceof Token) {
throw new IllegalArgumentException(
"Cannot add rules with Tokens on RHS to a CFG's set of rules.");
}
}
Variable lhs = rule.getLhs();
CfgRuleBucket bucket = getLhsBucket(lhs);
if (bucket == null) {
bucket = new CfgRuleBucket(lhs);
lhsBuckets.put(lhs, bucket);
}
bucket.addRule(rule);
variables.add(rule.getLhs());
variables.addAll(rule.getRhs());
}
/**
* Removes the specified rule from this CFG
*/
public boolean removeRule(Rule rule) {
CfgRuleBucket bucket = getLhsBucket(rule.getLhs());
if (bucket == null) {
return false;
} else {
return bucket.removeRule(rule);
}
}
/**
* Returns the start variable.
*/
public Variable getStartVariable() {
return startVariable;
}
protected void setStartVariable(Variable v) {
this.startVariable = v;
}
public List getVariables() {
return new ArrayList(variables);
}
public List getInlineTokenTypes() {
List vList = getVariables();
List inline = new ArrayList();
for (int i = 0; i < vList.size(); i++) {
Variable v = (Variable) vList.get(i);
if (v instanceof InlineTokenType) {
inline.add(v);
}
}
return inline;
}
public int getNumRules() {
int num = 0;
Iterator it = lhsBuckets.values().iterator();
while (it.hasNext()) {
CfgRuleBucket bucket = (CfgRuleBucket) it.next();
num += bucket.getNumRules();
}
return num;
}
public boolean hasRule(Rule r) {
return hasRule(r.getLhs(), r.getRhs());
}
public boolean hasRule(Variable lhs, List rhs) {
CfgRuleBucket bucket = getLhsBucket(lhs);
if (bucket == null) {
return false;
}
return bucket.hasRule(lhs, rhs);
}
public Rule getRule(Variable lhs, List rhs) {
if (!hasRule(lhs, rhs)) {
StringBuffer buff = new StringBuffer();
buff.append(lhs.toString());
buff.append(" -->");
for (int i = 0; i < rhs.size(); i++) {
buff.append(" " + rhs.get(i).toString());
}
throw new IllegalArgumentException("Specified rule does not exist: " + buff.toString());
}
return getLhsBucket(lhs).getRule(lhs, rhs);
}
public List getRules(Variable lhs) {
CfgRuleBucket bucket = getLhsBucket(lhs);
if (bucket == null) {
return new ArrayList();
}
return bucket.getRules();
}
public List getRules() {
ArrayList list = new ArrayList();
Iterator it = lhsBuckets.values().iterator();
while (it.hasNext()) {
CfgRuleBucket bucket = (CfgRuleBucket)it.next();
list.addAll(bucket.getRules());
}
return list;
}
protected CfgRuleBucket getLhsBucket(Variable lhs) {
return (CfgRuleBucket) lhsBuckets.get(lhs);
}
/**
* Each bucket must have a sum probability of at least .999999, but
* less than 1.000001.
*
* This relaxation of the requirement that probabilities sum to 1
* compensates for rounding error.
*
* @return true iff this PCFG's probabilities are consistent.
*/
public boolean areRuleProbabilitiesConsistent() {
boolean consistent = true;
Iterator itVars = getVariables().iterator();
while (itVars.hasNext()) {
Variable v = (Variable)itVars.next();
Iterator itRules = getRules(v).iterator();
if (!itRules.hasNext()) {
continue;
}
double sum = 0;
while (itRules.hasNext()) {
Rule r = (Rule) itRules.next();
sum += r.getProbability();
}
consistent &= (sum > .999999 && sum < 1.000001);
}
return consistent;
}
/**
* Returns true if this grammar has any dangling non-token type variables.
*
* That is, if the grammar has at least one rule of the form
* A --> B
* where A is any variable and B is a non-token-type variable, but no rules
* of the form
* B --> C
* where C is any variable.
*
* In general, this is indicative of programmer error, e.g. an undeclared token type
* in a grammar.
*/
public boolean hasDanglingNonTokenTypes() {
Set lhsVariables = new HashSet();
Set rhsNonTokenTypes = new HashSet();
List rules = getRules();
for (int i = 0; i < rules.size(); i++) {
Rule r = (Rule) rules.get(i);
lhsVariables.add(r.getLhs());
List rhs = r.getRhs();
for (int j = 0; j < rhs.size(); j++) {
Variable v = (Variable) rhs.get(j);
if (!(v instanceof TokenType)) {
rhsNonTokenTypes.add(v);
}
}
}
return !lhsVariables.containsAll(rhsNonTokenTypes);
}
/**
* Returns true if this grammar has at least one useless rule.
*
* That is, if this grammar has at least one rule of the form<br>
* A --> B<br>
* where A is not the start variable and B is any variable, but no rules of the form<br>
* C --> A
*
* <p>
* Note that "islands" of rules which are unreachable from the start variable
* are also useless. However, the algorithms in hasUselessRules() and removeUselessRules()
* do not find or remove such circularities.
*
* <p>
* This can happen either as a result of programmer error, or as a result of
* converting a grammar to Nearly Chomsky Normal Form.
*/
public boolean hasUselessRules() {
return getUselessRules().size() != 0;
}
/**
* Removes all the useless rules in this grammar. Note that this is done
* recursively, as removal of one useless rule may make other rules useless.
*/
public void removeUselessRules() {
while (true) {
List useless = getUselessRules();
if (useless.size() == 0) {
return;
}
for (int i = 0; i < useless.size(); i++) {
Rule r = (Rule) useless.get(i);
removeRule(r);
}
}
}
/**
* Returns the first useless rule encountered in this grammar, or null if none
* exists.
*/
protected List getUselessRules() {
List rules = getRules();
Set rhsVars = new HashSet();
for (int i = 0; i < rules.size(); i++) {
Rule r = (Rule) rules.get(i);
rhsVars.addAll(r.getRhs());
}
Variable sv = getStartVariable();
List useless = new ArrayList();
for (int i = 0; i < rules.size(); i++) {
Rule r = (Rule) rules.get(i);
Variable lhs = r.getLhs();
if (!lhs.equals(sv) && !rhsVars.contains(lhs)) {
useless.add(r);
}
}
return useless;
}
/**
* Creates and returns a String representing this CFG.
* The returned value should be suitable for parsing by
* readFromFile(). The rules for the start symbol are
* the first rules in the string, and other rules are
* grouped together by LHS.
*/
public String toString() {
String s = "";
List inlineTokenTypes = getInlineTokenTypes();
for (int i = 0; i < inlineTokenTypes.size(); i++) {
InlineTokenType tt = (InlineTokenType) inlineTokenTypes.get(i);
s += tt.getDefinitionString() + "\n";
}
Iterator rules = getRules(startVariable).iterator();
while (rules.hasNext()) {
s += rules.next() + "\n";
}
Iterator keys = lhsBuckets.keySet().iterator();
while (keys.hasNext()) {
Variable lhs = (Variable) keys.next();
if (lhs.equals(startVariable)) {
continue;
}
rules = getRules(lhs).iterator();
while (rules.hasNext()) {
s += rules.next() + "\n";
}
}
return s;
}
//
// Inner class
//
/**
* A CfgRuleBucket contains all the rules which have the specified variable as the LHS.
*/
private static class CfgRuleBucket {
Variable lhs;
HashMap rules = new HashMap();
List ruleList = new ArrayList(4);
List unmodifiableRuleList = Collections.unmodifiableList(ruleList);
public CfgRuleBucket(Variable lhs) {
this.lhs = lhs;
}
public void addRule(Rule r) {
List rhs = r.getRhs();
if (rules.containsKey(rhs)) {
throw new IllegalArgumentException("Attempt to add duplicate rule to CFG: " + r);
}
rules.put(rhs, r);
ruleList.add(r);
}
public boolean hasRule(Variable lhs, List rhs) {
if (!this.lhs.equals(lhs)) {
throw new IllegalStateException("Specified LHS different than bucket LHS!");
}
return rules.containsKey(rhs);
}
public Rule getRule(Variable lhs, List rhs) {
if (!hasRule(lhs, rhs)) {
throw new IllegalArgumentException("Rule does not exist!");
}
return (Rule)rules.get(rhs);
}
public int getNumRules() {
return rules.size();
}
public List getRules() {
return unmodifiableRuleList;
}
public boolean removeRule(Rule r) {
if (!this.lhs.equals(r.getLhs())) {
throw new IllegalStateException("Rule has LHS different than bucket LHS!");
}
List rhs = r.getRhs();
Object fromHash = rules.remove(rhs);
ruleList.remove(r);
return fromHash != null;
}
}
}
| true
|
c8c353b53e1459b3a83f6cdad0f7fb47efe4ae4c
|
Java
|
aygol/JavaProject
|
/src/array_practice/Array_warm_uP.java
|
UTF-8
| 1,244
| 3.5625
| 4
|
[] |
no_license
|
package array_practice;
public class Array_warm_uP {
public static void main(String[] args) {
// find create an arra of 7 items
//assign a value prinit out in reserve order
//2 store last item in a variable called LastItem
//print it out speraitly
int[] nums = {1, 3, 4, 5, 8, 9, 4};
for (int i = nums.length - 1; i >= 0; i--) {
System.out.print("reverse order " + nums[i]);
System.out.print("->");
}
System.out.println("****");
int lastItem = nums[nums.length - 1];
System.out.println("Last Item value " + lastItem);
System.out.println("middle item index value=" + nums[nums.length / 2]);
int sum = 0;
for (int x = 0; x < nums.length; x++) {
sum = sum + nums[x];
}
System.out.println("sum= " + sum);
int max =nums[0];
for (int eachnums : nums) {
if(eachnums>max){
max=eachnums;
}
}
System.out.println("max value = "+max);
int min=nums[0];
for(int eachnums:nums){
if(eachnums<min){
min=eachnums;
}
}
System.out.println("min = "+min);
}
}
| true
|
6ff393a883ccbb1cea907a01fdc3010c2f7c4b08
|
Java
|
olisaJohnnyChukwu/PersonalCryptoManager
|
/src/main/java/com/ojc/Service/cryptoService.java
|
UTF-8
| 2,267
| 2.125
| 2
|
[] |
no_license
|
package com.ojc.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ojc.model.crypto;
@Service
public class cryptoService implements ICryptoservice{
@Autowired
com.ojc.repository.cryptoRepository cryptoRepository;
private static final String url="https://coinmarketcap.com/";
@Override
@PostConstruct
public void scrapWeb() {
// TODO Auto-generated method stub
//System.setProperty("webdriver.chrome.driver", "/Users/olisajohnnychukwu/Downloads/chromedriver");
System.setProperty("webdriver.chrome.driver", "/Users/olisajohnnychukwu/Downloads/chromedriver");
ChromeDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.navigate().to(url);
WebElement word=driver.findElement(By.cssSelector("#__next > div.bywovg-1.sXmSU > div.main-content > div.sc-57oli2-0.comDeo.cmc-body-wrapper > div > div > div.h7vnx2-1.bFzXgL > table"));
List<WebElement> price=driver.findElements(By.cssSelector("td:nth-of-type(4)"));
List<WebElement> name=driver.findElements(By.cssSelector("td:nth-of-type(3)"));
//List<WebElement> marketcap=driver.findElements(By.cssSelector("td:nth-of-type(7)"));
//List<WebElement> w2=driver.findElements(By.cssSelector(".coin-item-symbol.gGIpIK.sc-1eb5slv-0"));
//w.stream().forEach(ww->System.out.println(ww.getText()));
List<crypto> cryptos=cryptoRepository.findAll();
for(int i=0;i<name.size();i++) {
crypto crypto=new crypto();
crypto.setName(name.get(i).getText());
crypto.setPrice(Double.parseDouble(price.get(i).getText().substring(1).replace(",", "")));
cryptoRepository.save(crypto);
cryptos.add(crypto);
}
cryptos.stream().forEach(c->{
cryptoRepository.updatePrice(c.getName(),c.getPrice());
});
}
public List<crypto> getAll() {
return cryptoRepository.findAll();
}
}
| true
|
625114c9a90a27e971ffcb8286c3ab6c1db539a1
|
Java
|
llddoo/SpringBoot_Mybatis_Thymeleaf_Security
|
/src/main/java/com/iu/s1/member/MemberController.java
|
UTF-8
| 1,814
| 2.078125
| 2
|
[] |
no_license
|
package com.iu.s1.member;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/member/**")
public class MemberController {
@Autowired
private MemberService memberService;
@GetMapping("login")
public String getLogin()throws Exception{
return "member/memberLogin";
}
@PostMapping("login")
public String getLogin(MemberVO memberVO, HttpSession session)throws Exception{
memberVO = memberService.getLogin(memberVO);
//session.setAttribute("member", memberVO);
if(memberVO != null) {
session.setAttribute("member", memberVO);
}
return "redirect:/";
}
@GetMapping("logout")
public String logout(HttpSession session)throws Exception{
session.invalidate();
return "redirect:../";
}
@GetMapping("join")
public String setJoin(@ModelAttribute MemberVO memberVO)throws Exception{
return "member/memberJoin";
}
@PostMapping("join")
public String setJoin(@Valid MemberVO memberVO, Errors errors ,MultipartFile avatar)throws Exception{
System.out.println("Join Process" + memberVO.getName().length());
// if(errors.hasErrors()) {
// return "member/memberJoin";
// }
if(memberService.memberError(memberVO, errors)) {
return "member/memberJoin";
}
//int result = memberService.setJoin(memberVO, avatar);
return "redirect:../";
}
}
| true
|
b353da27a050e7c31c28302ecf9ae6c070087082
|
Java
|
IdelsTak/dpml-svn
|
/snapshot/planet/facilities/reflector/impl/src/main/org/apache/metro/facilities/reflector/impl/ReflectionHandler.java
|
UTF-8
| 20,330
| 1.820313
| 2
|
[] |
no_license
|
/*
* Copyright 2004 Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.metro.facilities.reflector.impl;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.avalon.framework.activity.Startable;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.LogEnabled;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.http.HttpContextService;
import org.apache.metro.facilities.reflector.ReflectionException;
import org.apache.metro.facilities.reflector.ReflectorService;
import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpHandler;
import org.mortbay.http.HttpRequest;
import org.mortbay.http.HttpResponse;
/**
* @avalon.component name="reflector-http-handler" lifestyle="singleton"
* @avalon.service type="org.mortbay.http.HttpHandler"
*/
public class ReflectionHandler
implements Startable, Parameterizable, LogEnabled,
Serviceable, Contextualizable, HttpHandler
{
private String m_Name;
private Logger m_Logger;
private HttpContextService m_ContextService;
private HttpContext m_Context;
private int m_Index;
private boolean m_Started;
private ReflectorService m_Reflector;
private String m_ContextPath;
private String m_Encoding;
private Vector m_Reserved;
public ReflectionHandler()
{
m_Started = false;
m_Reserved = new Vector();
m_Reserved.addElement("debug");
m_Reserved.addElement("app");
m_Reserved.addElement("");
}
/**
* Enable the logging system.
*
* @avalon.logger name="http"
*/
public void enableLogging( Logger logger )
{
m_Logger = logger;
}
public Logger getLogger()
{
return m_Logger;
}
/**
* Contextulaization of the Handler.
*
* @param ctx the supplied listener context
*
* @exception ContextException if a contextualization error occurs
*
* @avalon.entry key="urn:avalon:name"
* type="java.lang.String"
*/
public void contextualize( Context ctx )
throws ContextException
{
m_Name = (String) ctx.get( "urn:avalon:name" );
}
public void parameterize( Parameters params )
throws ParameterException
{
m_Index = params.getParameterAsInteger( "handler-index", -1 );
m_ContextPath = params.getParameter( "context-path" );
m_Encoding = params.getParameter( "encoding", "ISO-8859-1" );
}
/**
* @avalon.dependency type="org.apache.avalon.http.HttpContextService"
* key="http-context"
* @avalon.dependency type="org.apache.metro.facilities.reflector.ReflectorService"
* key="reflector"
*/
public void service( ServiceManager man )
throws ServiceException
{
m_ContextService = (HttpContextService) man.lookup( "http-context" );
m_Reflector = (ReflectorService) man.lookup( "reflector" );
}
public void initialize( HttpContext context )
{
if( m_Logger.isDebugEnabled() )
m_Logger.debug( "Initializing ReflectorHandler: " + context );
m_Context = context;
}
public String getName()
{
return m_Name;
}
public void setName( String name )
{
m_Name = name;
}
public HttpContext getHttpContext()
{
return m_Context;
}
public void start()
throws Exception
{
m_Started = true;
if( m_Index >= 0 )
m_ContextService.addHandler( m_Index, this );
else
m_ContextService.addHandler( this );
if( m_Logger.isDebugEnabled() )
m_Logger.debug( "Starting ReflectorHandler: " + this );
}
public boolean isStarted()
{
return m_Started;
}
public void stop()
throws InterruptedException
{
m_Started = false;
if( m_Logger.isDebugEnabled() )
m_Logger.debug( "Stopping ReflectorHandler: " + this );
m_ContextService.removeHandler( this );
}
public void handle( String pathInContext, String pathParams,
HttpRequest request, HttpResponse response )
throws IOException
{
m_Logger.info( "Request: " + pathInContext );
if( ! pathInContext.startsWith( m_ContextPath ) )
return;
pathInContext = pathInContext.substring( m_ContextPath.length() );
response.setContentType("text/html");
RequestContext ctx = new RequestContext( pathInContext, request, response, m_Encoding );
try
{
String method = request.getMethod();
if( method.equals( "GET" ) )
doGet( ctx );
if( method.equals( "POST" ) )
doPost( ctx );
} catch( Exception e )
{
ctx.out.println( "<html><body><h1>Exception occurred in service.</h1><hr><pre>" );
e.printStackTrace( ctx.out );
ctx.out.println( "</pre></body></html>" );
} finally
{
ctx.dispose();
}
}
private void doGet( RequestContext ctx )
throws IOException, ReflectionException
{
if( m_Logger.isDebugEnabled() )
{
String s1 = "Reflector get:[" + ctx.req.getRemoteAddr() + ":" + ctx.req.getUserPrincipal() + "] --> " + ctx.req.getRequestURL() + "?" + ctx.req.getQuery();
m_Logger.debug(s1);
}
ctx.out.println( "<html>" );
formatGet( ctx );
formatDebug(ctx);
ctx.out.println( "</body></html>" );
}
private void doPost( RequestContext ctx )
throws IOException
{
if( m_Logger.isDebugEnabled() )
{
String s1 = "Reflector set:[" + ctx.req.getRemoteAddr() + ":" + ctx.req.getUserPrincipal() + "] --> " + ctx.req.getRequestURL() + "?" + ctx.req.getQuery();
m_Logger.debug( s1 );
}
ctx.out.println( "<html><head>" );
ctx.out.println( "</head><body>" );
ctx.out.println( "<h3>Changes made:</h3><hr>" );
ctx.out.println( "<table border=1 cellspacing=0 cellpadding=2 width=\"100%\">" );
ctx.out.println( "<tr><td><b><u>Member</b></u></td><td><b><u>Changed to</b></u></td></tr>" );
Iterator names = ctx.req.getParameterNames().iterator();
while( names.hasNext() )
{
String name = (String) names.next();
if( ! isReserved(name) )
{
List values = ctx.req.getParameterValues( name );
for( int i=0 ; i < values.size() ; i++ )
{
String value = (String) values.get(i);
if( value != null )
{
if( ! value.equals("") )try
{
ctx.out.print( "<tr><td>" );
ctx.out.print( name );
ctx.out.print( "</td><td>" );
m_Reflector.set( name, value );
ctx.out.print( value );
} catch( Exception e )
{
e.printStackTrace( ctx.out );
}
ctx.out.print( "</td></tr>" );
}
}
}
}
ctx.out.println( "</table>" );
if( ctx.debug )
ctx.out.println("<hr>Execution Time:" + (System.currentTimeMillis()-ctx.start) + " ms" );
ctx.out.println( "</body></html>" );
}
private void formatGet( RequestContext ctx )
throws IOException, ReflectionException
{
// then get the writer and write the response data
String title = null;
if( ctx.objectname == null || ctx.objectname.equals("") )
title = "Application Root Names";
else
title = ctx.objectname;
PrintWriter out = ctx.out;
out.println( "<head><title>" );
out.println( title );
out.println( "</title></head><body>" );
out.println( "<h1>" );
out.println( title );
out.println( "</h1>" );
if( ctx.objectname == null || ctx.objectname.equals("") )
out.println( "<hr>" );
else
{
String container = m_Reflector.getContainer( ctx.objectname );
String member = m_Reflector.getMember( ctx.objectname );
if( container == null || "".equals(container) )
{
out.print( "<A href=" );
out.print( "\"/bali/debug/" );
out.print( "\">Application Root</A><hr>" );
}
else
{
out.print( "<A href=" );
formatURL( ctx, container );
out.println( "\">" );
out.println( container );
out.println( "</A><hr>" );
}
}
out.print( "<FORM Method=\"POST\" Action=\"modify" );
if( ctx.debug )
out.print( "?debug=true" );
out.print( "\">" );
boolean error = false;
if( ctx.objectname != null )
{
if( ! ctx.objectname.equals("") )
{
Class cls = m_Reflector.getClass(ctx.objectname);
if( cls == null )
{
formatNotFound(ctx);
error = true;
}
else if( cls.isArray() ||
Collection.class.isAssignableFrom(cls) ||
Map.class.isAssignableFrom(cls) ||
Dictionary.class.isAssignableFrom(cls)
)
formatArray( ctx );
else
formatObject(ctx);
}
else
formatObject(ctx);
}
else
formatObject(ctx);
if( ! error )
formatButton( ctx );
out.println( "</FORM>" );
}
private void formatNotFound( RequestContext ctx )
{
ctx.out.println( "<h2>Object not found.</h2>" );
}
private void formatObject( RequestContext ctx)
throws ReflectionException
{
String[] names = m_Reflector.getNames( ctx.objectname );
formatTableHeader(ctx);
for( int i=0; i<names.length ; i++ )
{
ctx.out.print( "<tr>" );
formatMember( ctx, names[i] );
ctx.out.println( "</tr>" );
}
ctx.out.println( "</table>" ) ;
}
private void formatMember( RequestContext ctx, String member)
{
int columncount = 0;
long then = System.currentTimeMillis();
ctx.out.print( "<td><A href=" );
columncount++;
String str = "";
if( ctx.objectname != null && ! "".equals(ctx.objectname) )
str = ctx.objectname + ".";
str = str + member;
formatURL(ctx, str );
ctx.out.print ( ">" );
ctx.out.print( member );
ctx.out.print( "</A></td><td>" );
columncount++;
try
{
String value;
String membername;
if( ctx.objectname == null || "".equals(ctx.objectname) )
membername = member;
else
membername = ctx.objectname + "." + member;
String obj = m_Reflector.get( membername );
if( obj == null )
value = "<null>";
else
value = obj;
ctx.out.print( value );
if( m_Reflector.isSettable(membername) )
{
ctx.out.print( "</td><td><INPUT Name=\"" );
ctx.out.print( str );
ctx.out.print( "\" TYPE=\"TEXT\" SIZE=\"15\" MAXLENGTH=\"300\" >" );
}
else
{
ctx.out.print( "</td><td><br>" );
}
columncount++;
ctx.out.print( "</td><td>" );
columncount++;
String name = m_Reflector.getClassName( membername );
if( name == null )
ctx.out.print( "" );
else
ctx.out.print( name );
}
catch( Exception e )
{
m_Logger.error( e.toString() );
ctx.out.print( "<pre>" );
ctx.out.print( e.toString() );
e.printStackTrace( ctx.out );
ctx.out.print( "</pre>" );
for( ; columncount < 4 ; columncount++ )
ctx.out.print( "</td><td><br>" );
}
ctx.out.print( "</td>" );
long now = System.currentTimeMillis();
if( ctx.debug )
ctx.out.print( "<td>" + (now-then) + " ms</td>" );
}
private void formatArrayMember( RequestContext ctx, String membername)
{
long then = System.currentTimeMillis();
int columncount = 0;
ctx.out.print( "<td><A href=" );
columncount++;
formatURL( ctx, ctx.objectname + membername );
ctx.out.print ( ">" );
ctx.out.print( membername );
ctx.out.print( "</A></td><td>" );
columncount++;
try
{
String value = m_Reflector.get(ctx.objectname + membername);
Class cls = m_Reflector.getClass(ctx.objectname + membername);
ctx.out.print( value );
if( m_Reflector.isSettable(ctx.objectname + membername) )
{
ctx.out.print( "</td><td><INPUT Name=\"" );
ctx.out.print( ctx.objectname + membername );
ctx.out.print( "\" TYPE=\"TEXT\" SIZE=\"10\" MAXLENGTH=\"30\" >" );
}
else
{
ctx.out.print( "</td><td><br>" );
}
columncount++;
ctx.out.print( "</td><td>" );
columncount++;
if( cls == null )
ctx.out.print( "<unknown>" );
else
ctx.out.print( cls.getName() );
}
catch( Exception e )
{
m_Logger.error( e.getMessage(), e );
ctx.out.print( "<pre>" );
ctx.out.print( e.toString() );
e.printStackTrace( ctx.out );
ctx.out.print( "</pre>" );
for( ; columncount < 4 ; columncount++ )
ctx.out.print( "</td><td>" );
}
ctx.out.println( "</td>" );
long now = System.currentTimeMillis();
if( ctx.debug )
ctx.out.print( "<td>" + (now-then) + " ms</td>" );
}
private void formatMapMember( RequestContext ctx, Object key, Object value)
{
long then = System.currentTimeMillis();
int columncount = 0;
ctx.out.print( "<td><A href=" );
columncount++;
formatURL( ctx, ctx.objectname + "['" + key + "']" );
ctx.out.print ( ">" );
ctx.out.print( "[\"" + key + "\"]" );
ctx.out.print( "</A></td><td>" );
columncount++;
try
{
ctx.out.print( value );
Class cls = key.getClass();
ctx.out.print( "</td><td>" );
if( isPrimitive( cls ) )
{
ctx.out.print( "<INPUT Name=\"" );
ctx.out.print( ctx.objectname + "[\"" + key + "\"]" );
ctx.out.print( "\" TYPE=\"TEXT\" SIZE=\"10\" MAXLENGTH=\"30\" >" );
}
columncount++;
ctx.out.print( "</td><td>" );
columncount++;
ctx.out.print( cls.getName() );
}
catch( Exception e )
{
m_Logger.error( e.getMessage(), e );
ctx.out.print( "<pre>" );
ctx.out.print( e.toString() );
e.printStackTrace( ctx.out );
ctx.out.print( "</pre>" );
for( ; columncount < 4 ; columncount++ )
ctx.out.print( "</td><td>" );
}
ctx.out.println( "</td>" );
long now = System.currentTimeMillis();
if( ctx.debug )
ctx.out.print( "<td>" + (now-then) + " ms</td>" );
}
private void formatArray( RequestContext ctx )
throws ReflectionException
{
formatTableHeader(ctx);
String[] names = m_Reflector.getNames(ctx.objectname);
for( int i=0; i < names.length ; i++ )
{
ctx.out.print( "<tr>" );
formatArrayMember( ctx, "[\'" + names[i] + "\']" );
ctx.out.println( "</tr>" );
}
ctx.out.println( "</table>" ) ;
}
private void formatButton( RequestContext ctx )
{
ctx.out.print( "<p><center><INPUT TYPE=\"SUBMIT\" VALUE=\"Change\"></center></p>" );
}
private void formatDebug( RequestContext ctx )
{
if( ctx.debug )
{
long i = System.currentTimeMillis() - ctx.start;
ctx.out.println( "<hr>Execution time:" + i + " ms" );
}
}
private boolean isPrimitive( Class cls )
{
if( cls.isPrimitive() )
return true;
if( cls.equals( Boolean.class ) )
return true;
if( cls.equals( Number.class ) )
return true;
else if( cls.equals(Character.class) )
return true;
else if( cls.equals(Void.class) )
return true;
else if( cls.equals(String.class) )
return true;
else
return false;
}
private void formatURL( RequestContext ctx, String objectname )
{
ctx.out.print( "\"" );
ctx.out.print( encode( objectname ) );
if( ctx.debug )
ctx.out.print( "?debug=true" );
ctx.out.print( "\"" );
}
private String encode( String text )
{
StringBuffer buf = new StringBuffer();
for( int i=0 ; i < text.length() ; i++ )
{
char ch = text.charAt(i);
if( (ch >= 'A' && ch <= 'z') || (ch >= '(' && ch <= '9') &&
( ch != '/' )
)
{
buf.append( ch );
}
else
{
buf.append( '{' );
buf.append( "" + ((int) ch) );
buf.append( '}' );
}
}
return buf.toString();
}
private void formatTableHeader( RequestContext ctx )
{
ctx.out.println( "<table border=1 cellspacing=0 cellpadding=2 width=\"100%\">" );
ctx.out.println( "<tr><td><b><u>Member</b></u></td><td><b><u>Value</b></u></td><td><b><u>Change</b></u></td><td><b><u>Class/Type</b></u></td></tr>" );
}
private boolean isReserved( String text )
{
return m_Reserved.contains(text);
}
}
| true
|
48d24d98d69c1269426385f031497c91b67dfa6f
|
Java
|
pwm-project/pwm
|
/server/src/main/java/password/pwm/util/cli/commands/ImportLocalDBCommand.java
|
UTF-8
| 2,588
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2021 The PWM Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package password.pwm.util.cli.commands;
import password.pwm.error.PwmOperationalException;
import password.pwm.util.cli.CliParameters;
import password.pwm.util.localdb.LocalDB;
import password.pwm.util.localdb.LocalDBUtility;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
public class ImportLocalDBCommand extends AbstractCliCommand
{
@Override
void doCommand( )
throws IOException
{
final LocalDB localDB = cliEnvironment.getLocalDB();
final String msg = "Proceeding with this operation will clear ALL data from the LocalDB." + "\n"
+ "Please consider backing up the LocalDB before proceeding. " + "\n"
+ "\n"
+ "The application must be stopped for this operation to succeed.";
if ( !promptForContinue( msg ) )
{
out( "exiting..." );
return;
}
final LocalDBUtility pwmDBUtility = new LocalDBUtility( localDB );
final Path inputFile = ( Path ) cliEnvironment.getOptions().get( CliParameters.REQUIRED_EXISTING_INPUT_FILE.getName() );
try
{
pwmDBUtility.importLocalDB( inputFile, System.out );
}
catch ( final PwmOperationalException e )
{
out( "error during import: " + e.getMessage() );
}
}
@Override
public CliParameters getCliParameters( )
{
final CliParameters cliParameters = new CliParameters();
cliParameters.commandName = "ImportLocalDB";
cliParameters.description = "Import the entire LocalDB contents from a backup file";
cliParameters.options = Collections.singletonList( CliParameters.REQUIRED_EXISTING_INPUT_FILE );
cliParameters.needsLocalDB = true;
cliParameters.readOnly = false;
return cliParameters;
}
}
| true
|
49457fe088cbf5f37373919653d02352013a8abb
|
Java
|
delepoulle/LRjava
|
/src/lr/format/wavefront/NormalAnalyzer.java
|
UTF-8
| 816
| 2.71875
| 3
|
[] |
no_license
|
package lr.format.wavefront;
import lr.Vecteur;
import java.io.IOException;
import java.io.StreamTokenizer;
public class NormalAnalyzer extends AbstractWavefrontAnalyzer {
public NormalAnalyzer(WavefrontFormat format) {
super(format);
}
@Override
public String getNom() {
return "vn";
}
@Override
public void analyser(StreamTokenizer tokenizer) throws IOException {
tokenizer.eolIsSignificant(false);
tokenizer.nextToken();
float x = (float) tokenizer.nval;
tokenizer.nextToken();
float y = (float) tokenizer.nval;
tokenizer.nextToken();
float z = (float) tokenizer.nval;
this.format.add(new Vecteur(x, y, z));
System.out.println("Vertex Normal described as " + new Vecteur(x, y, z));
}
}
| true
|
874cd822c4ad92c9ed1215049414fe42e56316a9
|
Java
|
GoncaloLeitao/aula-dml
|
/src/main/java/pt/ulisboa/tecnico/softeng/bank/domain/Account.java
|
UTF-8
| 586
| 2.78125
| 3
|
[] |
no_license
|
package pt.ulisboa.tecnico.softeng.bank.domain;
public class Account extends Account_Base{
public Account(int iban, int balance, Bank bank) {
this.setIban(iban);
this.setBalance(balance);
this.setBank(bank);
bank.addAccount(this);
}
public void delete() {
this.setBank(null);
deleteDomainObject();
}
public boolean withdraw(int amount) {
if ((this.getBalance() - amount ) > 0) {
this.setBalance(this.getBalance() - amount);
return true;
}
return false;
}
public void deposit(int amount) {
this.setBalance(this.getBalance() + amount);
}
}
| true
|
cd270a74f367b351f77c34e6560e6a4c3cd7b1a9
|
Java
|
IvanBelyaev/ibelyaev
|
/chapter_002/src/test/java/ru/job4j/profession/DoctorTest.java
|
UTF-8
| 1,128
| 3.046875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package ru.job4j.profession;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* DoctorTest.
* @author Ivan Belyaev
* @since 12.09.2017
* @version 1.0
*/
public class DoctorTest {
/**
* Test for the treat method.
*/
@Test
public void whenTreatThenIvanTreatKatya() {
Doctor doctor = new Doctor("Иван", "ТГМА", 5, "1-я ГорБольница");
Person person = new Person("Катя");
String methodReturns = doctor.treat(person);
String expected = "Доктор Иван лечит Катя.";
assertThat(methodReturns, is(expected));
}
/**
* Test for the diagnose method.
*/
@Test
public void whenDiagnoseThenOlgaDiagnoseRoma() {
Doctor doctor = new Doctor("Оля", "ТГМА", 5, "1-я ГорБольница");
Person person = new Person("Рома");
String methodReturns = doctor.diagnose(person);
String expected = "Доктор Оля ставит диагноз Рома.";
assertThat(methodReturns, is(expected));
}
}
| true
|
1366acf41979f39c36bb1f8598ae0951ab5b8900
|
Java
|
alus-it/GPSreceiver
|
/src/it/alus/GPSreceiver/serialPort/SerialDriver.java
|
UTF-8
| 10,443
| 2.53125
| 3
|
[] |
no_license
|
//============================================================================
// This file is part of GPSreceiver: a Java demo program that parses NMEA
// sentences from a serial GPS receiver and displays live the received data.
// Author : Alberto Realis-Luc <alberto.realisluc@gmail.com>
// Since : July 2010
// Web : http://www.alus.it/airnavigator/gpsreceiver/
// Git repository : https://github.com/alus-it/GPSreceiver.git
// Version : 0.1
// Copyright : © 2010-2018 Alberto Realis-Luc
// License : GPL
//============================================================================
/*
== Physical protocol layer ==
The NMEA specification requires a physical-level protocol compatible
with RS422 at 4800bps, 8N1 or 7N2. It is RS422 rather than RS232
because NMEA expects many navigational devices to feed a common serial
bus. The darta encoding is ASCII with the high data bit not used and zeroed.
Consumer-grade GPS sensors normally report over an RS232 port or a USB
port emulating an RS232 serial device. Baud rate is variable, with
9600 probably the most common. Most deviveces use 8N1; there are
rare exceptions that use 7N2 (San Jose Navigation) or even 8O1 (Trimble).
== NMEA Encoding Conventions ==
An NMEA sentence consists of a start delimiter, followed by a
comma-separated sequence of fields, followed by the character '\*'
(ASCII 42), followed by a CRC32 checksum expressed as two hexadecimal
digits, followed by an end-of-line marker.
The start delimiter is normally '$' (ASCII 36). Packets of AIVDM/AIVDO
data, which are otherwise formatted like NMEA, use '!'. It is
possible that recent revisions of NMEA may allow other exceptions;
we do not know.
*/
package it.alus.GPSreceiver.serialPort;
import it.alus.GPSreceiver.SentenceReceiver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Queue;
import java.util.TooManyListenersException;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
public class SerialDriver extends Thread implements SerialPortEventListener {
private static InputStream inputStream;
private static OutputStream outputStream;
protected static SerialPort port;
private static final int READBUFFER_SIZE = 4096;
private static final int TIMEOUT_MAX = 5000;
private static final int TIMEOUT_MILLIS = 2000;
private static boolean receiving,trasmitting;
private static Queue<byte[]> outgoingQueue;
private static boolean isUARTmanagerActive;
private static boolean lineFeedExpected;
private static byte[] sentence;
private static int rcvdBytesOfSentence;
private static long timestamp;
public SerialDriver(CommPortIdentifier comPortId) throws IOException {
isUARTmanagerActive=false;
receiving=false;
trasmitting=false;
sentence=new byte[READBUFFER_SIZE];
rcvdBytesOfSentence=0;
lineFeedExpected=false;
outgoingQueue = new LinkedList<byte []>();
if(!openSerialPort(comPortId)) {
System.out.println("Can't operate on port "+comPortId.getName()+" closing SerialDriver...");
System.gc();
}
}
private synchronized boolean openSerialPort(CommPortIdentifier portId) {
if(portId.getPortType()!=CommPortIdentifier.PORT_SERIAL) {
System.out.println("Error: port: "+portId.getName()+" is not a serial port!");
return false;
}
try {
port=(SerialPort)portId.open("GPSreceiver",TIMEOUT_MAX);
} catch (PortInUseException e) {
System.out.println("Warning: The port "+portId.getName()+" was already in use by: "+ e.currentOwner);
return false;
}
catch (RuntimeException e) {
System.out.println("Error: Runtime Exception while opening port "+portId.getName());
return false;
}
if(port==null) {
System.out.println("Error: port request timed out");
return false;
}
try {
port.enableReceiveTimeout(TIMEOUT_MILLIS);
} catch (UnsupportedCommOperationException e) {
System.out.println("ERROR: Impossibile settare il timeout sulla seriale.");
e.printStackTrace();
}
try {
inputStream = port.getInputStream();
} catch (IOException e1) {
System.out.println("Error while opening the input stream to serial port "+portId.getName());
e1.printStackTrace();
port.close();
return false;
}
try {
outputStream = port.getOutputStream();
} catch (IOException e1) {
System.out.println("Error while opening the output stream to serial port "+portId.getName());
e1.printStackTrace();
port.close();
try {
inputStream.close();
} catch (IOException e) {
System.out.println("Error while reclosing input stream to serial port "+portId.getName());
e.printStackTrace();
}
return false;
}
try {
port.addEventListener(this); //c'è un this quindi questo metodo non può essere static
} catch (TooManyListenersException e) {
System.out.println("Too many listeners on port "+portId.getName()+": "+e.getMessage());
try {
inputStream.close();
outputStream.close();
} catch (IOException e1) {
System.out.println("Error while reclosing IO streams on serial port "+portId.getName());
e1.printStackTrace();
}
port.close();
return false;
}
port.notifyOnDataAvailable(true);
try {
port.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException e) {
System.out.println("Operation not supported on port "+portId.getName()+": "+e.getMessage());
port.close();
try {
inputStream.close();
outputStream.close();
} catch (IOException e1) {
System.out.println("Error while reclosing IO streams on serial port "+portId.getName());
e1.printStackTrace();
}
return false;
}
this.start();
isUARTmanagerActive=true;
return true;
}
private static int getCRCintValue() {
if(rcvdBytesOfSentence<9) return -1;
try {
int checksum=Integer.parseInt(""+((char)sentence[rcvdBytesOfSentence-2])+((char)sentence[rcvdBytesOfSentence-1]),16);
return checksum;
} catch (NumberFormatException e) {
return -1;
}
}
public synchronized void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI: //Break Interrupt
case SerialPortEvent.OE: //Overrun Error
case SerialPortEvent.FE: //Framing Error
case SerialPortEvent.PE: //Parity Error
case SerialPortEvent.CD: //Carrier Detect
case SerialPortEvent.DSR: //Data Sent Ready
case SerialPortEvent.RI: //Ring Indicator
case SerialPortEvent.OUTPUT_BUFFER_EMPTY: //Dati trasmessi output buffer vuoto
case SerialPortEvent.CTS: break; //Clear To Send
case SerialPortEvent.DATA_AVAILABLE: //Dati ricevuti nel buffer da leggere
receiving=true;
timestamp=System.currentTimeMillis();
byte[] readBuffer = new byte[READBUFFER_SIZE];
int redBytes=0,i; // number of bytes read from serial port
try { // states machine implementation
while(inputStream.available()>0) {
redBytes=inputStream.read(readBuffer); //leggo il buffer
for(i=0;i<redBytes;i++) switch(readBuffer[i]) {
case '$': if(rcvdBytesOfSentence==0) sentence[rcvdBytesOfSentence++]='$'; break;
case '\r': if(rcvdBytesOfSentence>0) lineFeedExpected=true; break;
case '\n': if(lineFeedExpected) {
if(rcvdBytesOfSentence>3) { //to avoid overflow errors
if(sentence[rcvdBytesOfSentence-3]=='*') { //verifica CRC
int checksum=0;
for(int j=1;j<rcvdBytesOfSentence-3;j++) checksum=checksum^sentence[j];
if(getCRCintValue()==checksum) SentenceReceiver.receiveSentence(new String(sentence,0,rcvdBytesOfSentence,"ASCII"),timestamp);
} else SentenceReceiver.receiveMessage(new String(sentence,0,rcvdBytesOfSentence,"ASCII"),timestamp); //line without checksum
}
rcvdBytesOfSentence=0;
lineFeedExpected=false;
}
break;
default: if(rcvdBytesOfSentence>0)
if(rcvdBytesOfSentence<READBUFFER_SIZE) sentence[rcvdBytesOfSentence++]=readBuffer[i];
else { //to avoid buffer overflow
rcvdBytesOfSentence=0;
lineFeedExpected=false;
}
} //end of or each byte of just received sequence
} // end of the 'while' loop
} catch (Exception e) { //catch, warn, ignore better to catch ANY exception to avoid ANY kind of error
e.printStackTrace();
System.out.println(e.getClass().getName()+" caugth in the source: "+e.getMessage());
}
receiving=false;
goAhead();
break; //end of data available
} // end of switch
}
private static synchronized void sendDataToUARTnow(byte[] dataToSend) { //invia immediatamente
trasmitting=true;
try {
//System.out.println("Data to UART: "+Converter.Vector2HexString(dataToSend));
outputStream.write(dataToSend);
} catch (IOException e) {
e.printStackTrace();
}
trasmitting=false;
}
public static void sendDataToUART(byte[] dataToSend) { //mette in coda per inviare
if(!trasmitting && !receiving && isUARTmanagerActive) {
System.out.println("####senData trasm:"+trasmitting+" rec:"+receiving+" isActive:"+isUARTmanagerActive);
if(!outgoingQueue.isEmpty()) {
//System.out.println("Data to QUEUE: "+Converter.Vector2HexString(dataToSend));
outgoingQueue.add(dataToSend);
} else sendDataToUARTnow(dataToSend);
}
else {
//System.out.println("Data to QUEUE: "+Converter.Vector2HexString(dataToSend));
outgoingQueue.add(dataToSend);
}
}
public static void goAhead() {
if(!trasmitting && !receiving && isUARTmanagerActive)
if(!outgoingQueue.isEmpty()) {
System.out.println("####GOAHEAD!! trasm:"+trasmitting+" rec:"+receiving+" isActive:"+isUARTmanagerActive+" queueEmpty:"+outgoingQueue.isEmpty());
sendDataToUARTnow(outgoingQueue.poll());
}
}
public static synchronized void Stop() {
if(isUARTmanagerActive) {
isUARTmanagerActive=false;
outgoingQueue.clear();
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
System.out.println("Error while reclosing IO streams on serial port.");
e.printStackTrace();
}
trasmitting=false;
receiving=false;
rcvdBytesOfSentence=0;
lineFeedExpected=false;
port.close();
}
}
public static boolean isActive() {
return isUARTmanagerActive;
}
}
| true
|
e25eb3dd5005da074f89da15d1f4036b6818d22d
|
Java
|
JorgeDirkx/Fundamentals
|
/src/com/jorgedirkx/arrayofstrings/App.java
|
UTF-8
| 488
| 3.703125
| 4
|
[] |
no_license
|
package com.jorgedirkx.arrayofstrings;
public class App {
public static void main(String[] args) {
//standard empty ref. text
String text = null;
String[]fruits = {"apple", "banana", "kiwi"};
String[]vegetables= {"paprika", "carrot"};
//for each loop
for(String fruit: fruits){
System.out.println(fruit);
}
for(String vegetable: vegetables){
System.out.println(vegetable);
}
}
}
| true
|
f4fee1c61d2063a55a738b4bd899e73d2b7cde69
|
Java
|
lionani07/Sistema_Pedidos
|
/src/main/java/com/br/stefanini/pedidos/model/Usuario.java
|
UTF-8
| 2,514
| 2.484375
| 2
|
[] |
no_license
|
package com.br.stefanini.pedidos.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import com.br.stefanini.pedidos.model.enums.EstadoUsuario;
import com.br.stefanini.pedidos.model.enums.Rol;
@Entity
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message="People é obrigatório")
private String people;
private String senha;
@NotBlank(message="Nome é obrigatório")
private String nome;
@NotBlank(message="Email é obrigatório")
@Email(message="Formato de email incorreto")
private String email;
@NotNull(message="Rol e obrigatório")
@Enumerated(EnumType.STRING)
private Rol rol;
@Enumerated(EnumType.STRING)
private EstadoUsuario estado;
public Usuario(){
this.estado = EstadoUsuario.ACTIVO;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPeople() {
return people;
}
public void setPeople(String people) {
this.people = people;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
public EstadoUsuario getEstado() {
return estado;
}
public void setEstado(EstadoUsuario estado) {
this.estado = estado;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Usuario other = (Usuario) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| true
|
5311cddc68fa544807d85ed075adadd7f45ac0c8
|
Java
|
yaokantv/YKCenterDemo-Android
|
/src/com/ykan/sdk/example/AirControlActivity.java
|
UTF-8
| 7,214
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
package com.ykan.sdk.example;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.yaokan.sdk.api.JsonParser;
import com.yaokan.sdk.model.AirConCatogery;
import com.yaokan.sdk.model.AirEvent;
import com.yaokan.sdk.model.AirStatus;
import com.yaokan.sdk.model.AirV1Command;
import com.yaokan.sdk.model.AirV3Command;
import com.yaokan.sdk.model.DeviceDataStatus;
import com.yaokan.sdk.model.KeyCode;
import com.yaokan.sdk.model.RemoteControl;
import com.yaokan.sdk.utils.Logger;
import com.yaokan.sdk.utils.Utility;
import com.yaokan.sdk.wifi.DeviceController;
import com.yaokan.sdk.wifi.listener.IDeviceControllerListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AirControlActivity extends BaseActivity implements IDeviceControllerListener, View.OnClickListener{
protected static final String TAG = AirControlActivity.class.getSimpleName();
/** The tv MAC */
private TextView tvMAC,tv_show;
/** The GizWifiDevice device */
private GizWifiDevice device;
private HashMap<String,KeyCode> codeDatas = new HashMap<String,KeyCode>();
private DeviceController driverControl = null;
private JsonParser jsonParser = new JsonParser();
private Button mode_btn,wspeed_btn,tbspeed_btn,lrwspped_btn,power_btn,temp_add_btn,temp_rdc_btn;
private static final int V3=3;
private int airVerSion=V3;
private AirEvent airEvent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.air_control);
initDevice();
initView();
setOnClickListener();
}
private void initDevice() {
Intent intent = getIntent();
device = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice");
driverControl = new DeviceController(getApplicationContext(),device,this);
//获取设备硬件相关信息
driverControl.getDevice().getHardwareInfo();
//修改设备显示名称
driverControl.getDevice().setCustomInfo("alias", "遥控中心产品");
RemoteControl remoteControl = jsonParser.parseObjecta(intent.getStringExtra("remoteControl"), RemoteControl.class);
if (!Utility.isEmpty(remoteControl)) {
airVerSion =remoteControl.getVersion();
codeDatas=remoteControl.getRcCommand();
airEvent=getAirEvent(codeDatas);
}
}
private void initView() {
tvMAC = (TextView) findViewById(R.id.tvMAC);
tv_show= (TextView) findViewById(R.id.tv_show);
mode_btn = (Button) findViewById(R.id.mode_btn);
wspeed_btn = (Button) findViewById(R.id.wspeed_btn);
tbspeed_btn = (Button) findViewById(R.id.tbspeed_btn);
lrwspped_btn = (Button) findViewById(R.id.lrwspped_btn);
power_btn = (Button) findViewById(R.id.power_btn);
temp_add_btn = (Button) findViewById(R.id.temp_add_btn);
temp_rdc_btn = (Button) findViewById(R.id.temp_rdc_btn);
//v1没有左右扫风,上下扫风,风量
if (airVerSion!=V3) {
wspeed_btn.setVisibility(View.GONE);
tbspeed_btn.setVisibility(View.GONE);
lrwspped_btn.setVisibility(View.GONE);
}
if (null != device) {
tvMAC.setText("MAC: " + device.getMacAddress().toString());
}
}
private void setOnClickListener() {
mode_btn.setOnClickListener(this);
wspeed_btn.setOnClickListener(this);
tbspeed_btn.setOnClickListener(this);
lrwspped_btn.setOnClickListener(this);
power_btn.setOnClickListener(this);
temp_add_btn.setOnClickListener(this);
temp_rdc_btn.setOnClickListener(this);
}
private AirEvent getAirEvent(HashMap<String,KeyCode> codeDatas) {
AirEvent airEvent = null;
if (!Utility.isEmpty(codeDatas)) {
if (airVerSion==V3) {
airEvent = new AirV3Command(codeDatas);
}else{
airEvent = new AirV1Command(codeDatas);
}
}
return airEvent;
}
@Override
public void onClick(View v) {
if (Utility.isEmpty(airEvent)) {
toast("airEvent is null");
return;
}
//空调必须先打开,才能操作其他按键
if (airEvent.isOff()&& !(v.getId() == R.id.power_btn)) {
toast("请先打开空调");
return;
}
KeyCode mKeyCode=null;
switch (v.getId()) {
case R.id.power_btn:
mKeyCode = airEvent.getNextValueByCatogery(AirConCatogery.Power);
break;
case R.id.mode_btn:
mKeyCode = airEvent.getNextValueByCatogery(AirConCatogery.Mode);
break;
case R.id.wspeed_btn:
mKeyCode = airEvent.getNextValueByCatogery(AirConCatogery.Speed);
break;
case R.id.tbspeed_btn:
mKeyCode = airEvent.getNextValueByCatogery(AirConCatogery.WindUp);
break;
case R.id.lrwspped_btn:
mKeyCode = airEvent.getNextValueByCatogery(AirConCatogery.WindLeft);
break;
case R.id.temp_add_btn:
if (airEvent.modeHasTemp()) {
mKeyCode = airEvent.getNextValueByCatogery(AirConCatogery.Temp);
}
break;
case R.id.temp_rdc_btn:
if (airEvent.modeHasTemp()) {
mKeyCode = airEvent.getForwardValueByCatogery(AirConCatogery.Temp);
}
break;
default:
break;
}
if (!Utility.isEmpty(mKeyCode)) {
driverControl.sendCMD(mKeyCode.getSrcCode());
onRefreshUI(airEvent.getCurrStatus());
}
}
private void onRefreshUI(AirStatus airStatus) {
if (Utility.isEmpty(airStatus)) {
return ;
}
String content="";
if (airEvent.isOff()){
content="空调已关闭";
}else {
content=getContent(airStatus);
}
tv_show.setText(content);
}
//
private String getContent(AirStatus airStatus){
String content="";
if (airVerSion==1) {
content="模式:"+airStatus.getMode().getName()
+"\n温度:"+airStatus.getTemp().getName();
}else {
content="模式:"+airStatus.getMode().getName()
+"\n风量:"+airStatus.getSpeed().getName()
+"\n左右扫风:"+airStatus.getWindLeft().getName()
+"\n上下扫风:"+airStatus.getWindUp().getName()
+"\n温度:"+airStatus.getTemp().getName();
}
return content;
}
@Override
public void didGetHardwareInfo(GizWifiErrorCode result,GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {
Logger.d(TAG, "获取设备信息 :");
if (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) {
Logger.d(TAG, "获取设备信息 : hardwareInfo :" + hardwareInfo);
} else {
}
}
@Override
public void didReceiveData(DeviceDataStatus arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {
Logger.d(TAG, "自定义设备信息回调");
if (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) {
Logger.d(TAG, "自定义设备信息成功");
}
}
@Override
public void didUpdateNetStatus(GizWifiDevice device,GizWifiDeviceNetStatus netStatus) {
switch (device.getNetStatus()) {
case GizDeviceOffline:
Logger.d(TAG, "设备下线");
break;
case GizDeviceOnline:
Logger.d(TAG, "设备上线");
break;
default:
break;
}
}
}
| true
|
3c2169e3f6b77e692c6f036471e59137b580c33c
|
Java
|
CordonaCodeCraft/limeburgerapp
|
/limeburger/src/main/java/com/limeburger/domain/allergen/model/AllergenCustomerDto.java
|
UTF-8
| 704
| 2.28125
| 2
|
[] |
no_license
|
package com.limeburger.domain.allergen.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@ApiModel(value = "DTO for displaying an allergen with attributes, tailored for a customer user")
@Data
public class AllergenCustomerDto {
@ApiModelProperty(value = "Allergen's name", required = true)
private String name;
@ApiModelProperty(value = "Allergen's name", required = true)
private String description;
@ApiModelProperty(value = "Allergen's danger index", required = true)
private String dangerIndex;
@ApiModelProperty(value = "URL string pointing at image of the allergen", required = true)
private String imageUrl;
}
| true
|
0863bcc775bae0756f94b5306601631419c0ea82
|
Java
|
Ignotus/torcsnet
|
/src/main/java/storage/MLPSetup.java
|
UTF-8
| 2,534
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
package storage;
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import java.io.*;
public class MLPSetup {
public RealMatrix W1;
public RealMatrix W2;
public Normalization norm = new Normalization();
public MLPSetup(RealMatrix W1, RealMatrix W2, Normalization norm) {
this.W1 = W1;
this.W2 = W2;
this.norm = norm;
}
public int getNumInputs() {
return W1.getColumnDimension() - 1; // skip bias neuron
}
public int getNumHiddens() {
return W1.getRowDimension() - 1;
}
public int getNumOutputs() {
return W2.getRowDimension() - 1;
}
public MLPSetup() {}
/* I/O methods */
/* Read NN weights and normalization */
public static MLPSetup readSetup(String filename) throws IOException, ClassNotFoundException {
System.out.println("Loading weights " + MLPSetup.class.getResource(filename).getFile());
MLPSetup setup = new MLPSetup();
InputStream fis = MLPSetup.class.getResourceAsStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
MatrixUtils.deserializeRealMatrix(setup, "W1", ois);
MatrixUtils.deserializeRealMatrix(setup, "W2", ois);
MatrixUtils.deserializeRealVector(setup.norm, "inputMin", ois);
MatrixUtils.deserializeRealVector(setup.norm, "inputMax", ois);
MatrixUtils.deserializeRealVector(setup.norm, "targetMin", ois);
MatrixUtils.deserializeRealVector(setup.norm, "targetMax", ois);
ois.close();
return setup;
}
public static MLPSetup[] readSetups(String[] filenames) throws IOException, ClassNotFoundException {
MLPSetup[] setups = new MLPSetup[filenames.length];
for (int i = 0; i < filenames.length; i++) {
setups[i] = readSetup(filenames[i]);
}
return setups;
}
public void writeSetup(String filename, MLPSetup setup) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
MatrixUtils.serializeRealMatrix(setup.W1, oos);
MatrixUtils.serializeRealMatrix(setup.W2, oos);
MatrixUtils.serializeRealVector(setup.norm.inputMin, oos);
MatrixUtils.serializeRealVector(setup.norm.inputMax, oos);
MatrixUtils.serializeRealVector(setup.norm.targetMin, oos);
MatrixUtils.serializeRealVector(setup.norm.targetMax, oos);
oos.close();
}
}
| true
|
983c8b2ab5301c0b4b6809d84a85668a38d3547d
|
Java
|
genghaihua/user_click
|
/src/cn/clickwise/net/http/SegClient.java
|
UTF-8
| 703
| 2.296875
| 2
|
[] |
no_license
|
package cn.clickwise.net.http;
import java.net.URLDecoder;
import java.net.URLEncoder;
import cn.clickwise.liqi.str.edcode.UrlCode;
public class SegClient {
public String url="http://192.168.110.182:7000/seg?s=";
public HttpClientTool hct=new HttpClientTool();
public String seg(String text)
{
String encode_text=URLEncoder.encode(text);
encode_text=encode_text.replaceAll("\\s+", "");
String req_url=url+encode_text;
return hct.postUrl(req_url);
}
public static void main(String[] args)
{
SegClient sc=new SegClient();
String s="9111秋装2013新款女韩版包臀短裙弹力蕾丝半身裙职业中裙大码裙子";
System.out.println(URLDecoder.decode(sc.seg(s)));
}
}
| true
|
b91abbac0b1bf3b6726672c1b3939dc16a9df80c
|
Java
|
rizkyabdillah/sistem-kasbon-mobile
|
/app/src/main/java/com/android/kasbon/sistem/adapter/TransaksiPembeliAdapter.java
|
UTF-8
| 2,019
| 2.078125
| 2
|
[] |
no_license
|
package com.android.kasbon.sistem.adapter;
import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.android.kasbon.sistem.R;
import com.android.kasbon.sistem.databinding.ItemTransaksiPembeliBinding;
import com.android.kasbon.sistem.databinding.ItemTransaksiPenjualBinding;
import com.android.kasbon.sistem.model.OperationTransaksiModel;
import com.android.kasbon.sistem.model.TransaksiModel;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
public class TransaksiPembeliAdapter extends RecyclerView.Adapter<TransaksiPembeliAdapter.ViewHolder> {
private ItemTransaksiPembeliBinding bindingPembeli;
private List<OperationTransaksiModel> list;
private Boolean isLimit = false;
public TransaksiPembeliAdapter(List<OperationTransaksiModel> list, Boolean isLimit) {
this.list = list;
this.isLimit = isLimit;
}
@NonNull
@Override
public TransaksiPembeliAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
bindingPembeli = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_transaksi_pembeli,parent,false);
return new ViewHolder(bindingPembeli);
}
@SuppressLint("ResourceAsColor")
@Override
public void onBindViewHolder(@NonNull TransaksiPembeliAdapter.ViewHolder holder, int position) {
bindingPembeli.setOperation(list.get(position));
}
@Override
public int getItemCount() {
return isLimit ? (Math.min(list.size(), 5)) : list.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(ItemTransaksiPembeliBinding binding) {
super(binding.getRoot());
}
}
}
| true
|
6266f513bfa11e20e5a7ace53e39809fe1b3634b
|
Java
|
rsandhu1/grid-services-test
|
/src/main/java/org/ogce/grid/services/listener/JobSubmissionListener.java
|
UTF-8
| 3,033
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.ogce.grid.services.listener;
import org.globus.gram.GramJob;
import org.globus.gram.GramJobListener;
import org.ogce.grid.security.ApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JobSubmissionListener implements GramJobListener {
private boolean finished;
private int error;
private int status;
private GramJob job;
private static final Logger log = LoggerFactory.getLogger(JobSubmissionListener.class);
public JobSubmissionListener(GramJob job) {
this.job = job;
}
// waits for DONE or FAILED status
public void waitFor() throws Exception {
while (!finished) {
int proxyExpTime = job.getCredentials().getRemainingLifetime();
if (proxyExpTime < 900) {
log.info("Job proxy expired. Trying to renew proxy");
ApplicationContext context = new ApplicationContext();
context.login();
job.renew(context.getGssCredential());
}
// job status is changed but method isn't invoked
if (status != 0) {
if (job.getStatus() != status) {
log.info("invoke method manually");
statusChanged(job);
} else {
log.info("job " + job.getIDAsString() + " have same status: " + GramJob.getStatusAsString(status));
}
} else {
log.info("Status is zero");
}
synchronized (this) {
wait(120 * 1000l);
}
}
}
public synchronized void statusChanged(GramJob job) {
log.debug("Listener: statusChanged triggered");
int jobStatus = job.getStatus();
String jobId = job.getIDAsString();
String statusString = job.getStatusAsString();
log.info("Job Status: " + statusString + "(" + jobStatus + ")");
System.out.println("Job Status: " + statusString + "(" + jobStatus + ")");
status = jobStatus;
if (jobStatus == GramJob.STATUS_DONE) {
finished = true;
} else if (jobStatus == GramJob.STATUS_FAILED) {
finished = true;
error = job.getError();
log.info("Job Error Code: " + error);
}
// notify wait thread to wake up if done
if (finished) {
notify();
}
}
public int getError() {
return error;
}
public int getStatus() {
return status;
}
public void wakeup() {
try {
notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
a2135970cf72dd92eb758187709ee7dddda9f921
|
Java
|
TymJanek/testing_junit
|
/src/JUnitClass2.java
|
UTF-8
| 894
| 3.28125
| 3
|
[] |
no_license
|
//class that checks if sequence is a geometric sequence (test for exercise 2)
import org.junit.Test;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class JUnitClass2 {
@Test
public void checkGeometricSequence() throws IOException {
GeometricSequence gs = new GeometricSequence();
Reader reader = new FileReader("geoSequence.txt"); //content in geoSequence.txt file right now is 1,2,4,8,16,32,64 - so the result should be true
gs.loadData(reader);
//printing all numbers from file, this is not necessary
/*
List list = gs.inputData();
for(int i=0; i<list.size(); i++){
System.out.print(list.get(i) + " ");
}
System.out.println();
*/
Double result = gs.calcQ(0.0); //q value
System.out.println(result);
}
}
| true
|
f6b97cdd682c346d14f727974afab68a906a0728
|
Java
|
sri-ts2012/PractiseJava
|
/src/streams/PaginationStreams.java
|
UTF-8
| 1,277
| 2.828125
| 3
|
[] |
no_license
|
package streams;
import java.util.List;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class PaginationStreams {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "\\src\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/offers");
//sorting webtable
//1.click on column
driver.findElement(By.xpath("//tr/th[1]")).click();
//2. capture all webelements into a list
List<String> price;
do{
List<WebElement> veglist= driver.findElements(By.xpath("//tr/td[1]"));
price=veglist.stream().filter(s->s.getText().contains("Rice")).map(s->getPriceItem(s)).collect(Collectors.toList());
price.forEach(a->System.out.println(a));
if(price.size()<1)
{
driver.findElement(By.cssSelector("[aria-label='Next']")).click();
}
}while(price.size()<1);
}
private static String getPriceItem(WebElement s)
{
String priceValue=s.findElement(By.xpath("following-sibling::td[1]")).getText();
return priceValue;
}
}
| true
|
a5d44288b76da38f434fa19ca981a3bfafe14b27
|
Java
|
lujina/spring-web
|
/src/main/java/com/demo/spring_web/messaging/MessageSender.java
|
UTF-8
| 1,357
| 2.328125
| 2
|
[] |
no_license
|
package com.demo.spring_web.messaging;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import com.demo.spring_web.model.InventoryResponse;
import com.demo.spring_web.model.Order;
@Component
public class MessageSender {
@Autowired
JmsTemplate jmsTemplate;
private static final String ORDER_RESPONSE_QUEUE = "order-response-queue";
private static final String ORDER_QUEUE = "order-queue";
//新增一个订单
public void sendMessage(final Order order){
jmsTemplate.send(ORDER_QUEUE,new MessageCreator(){
@Override
public Message createMessage(Session session) throws JMSException {
// TODO Auto-generated method stub
return session.createObjectMessage(order);
}
});
}
//仓库处理完一个订单
public void sendMessage2(final InventoryResponse inventoryResponse){
jmsTemplate.send(ORDER_RESPONSE_QUEUE,new MessageCreator(){
@Override
public Message createMessage(Session session) throws JMSException {
// TODO Auto-generated method stub
return session.createObjectMessage(inventoryResponse);
}
});
}
}
| true
|
93a5794882a63499b7c9ad5c23f62d02b2693d68
|
Java
|
BajkaFCI/Sudoku2
|
/src/sudoku2/Sudoku2.java
|
WINDOWS-1250
| 3,676
| 2.9375
| 3
|
[] |
no_license
|
package sudoku2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class Sudoku2 extends JFrame{
private static final long serialVersionUID = 1L; //????????????????????
public JTextField[][] plansza;
static Border outerBorder = BorderFactory.createLineBorder(Color.black, 2);
static Border innerBorder = BorderFactory.createLineBorder(Color.gray, 2);
public static void main(String[] args) throws Exception{
JFrame frame = new JFrame("SUDOKU - Pascal van der Sluis 2019");
frame.setSize(1200,1000);
JButton solutionBtn = new JButton("rozwi");
solutionBtn.setSize(new Dimension(150, 40));
BufferedImage logo = ImageIO.read(new File("E:\\eclipse-workspace\\Sudoku2\\src\\images\\javalogo.png"));
JLabel logoLabel = new JLabel(new ImageIcon(logo));
GridLayout thegrid = new GridLayout(9,9);
JPanel gridpanel = new JPanel(thegrid);
FlowLayout theflow = new FlowLayout(FlowLayout.LEFT,200,10);
JPanel flowlayout1 = new JPanel(theflow);
flowlayout1.add(solutionBtn);
flowlayout1.add(logoLabel);
BorderLayout borderlayout = new BorderLayout();
JPanel mainPanel = new JPanel(borderlayout);
borderlayout.setHgap(50);
borderlayout.setVgap(50);
JLabel topLabel = new JLabel("HERE IS SOME HEADER");
BufferedImage sudokulogo = ImageIO.read(new File("E:\\eclipse-workspace\\Sudoku2\\src\\images\\sudoku.png"));
JLabel sudokuLabel = new JLabel(new ImageIcon(sudokulogo));
JLabel sudokuLabel2 = new JLabel(new ImageIcon(sudokulogo));
mainPanel.add(topLabel, BorderLayout.NORTH);
mainPanel.add(sudokuLabel, BorderLayout.EAST);
mainPanel.add(sudokuLabel2, BorderLayout.WEST);
mainPanel.add(gridpanel,BorderLayout.CENTER);
mainPanel.add(flowlayout1,BorderLayout.SOUTH);
frame.add(mainPanel);
frame.setVisible(true);
//kolory planszy
Color[] col = {Color.blue,Color.white,Color.blue,Color.white,Color.blue,Color.white,
Color.blue,Color.white,Color.blue};
JTextField[][] plansza = new JTextField[9][9];
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
plansza[i][j] = new JTextField();
plansza[i][j].setBounds(25+j*20, 25+i*20, 10, 10);
plansza[i][j].setBorder(innerBorder);
plansza[i][j].setBackground(col[(i/3)*3+(j/3)]);
gridpanel.add(plansza[i][j]);
gridpanel.setBorder(outerBorder);
}
}
solutionBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
//Start method present in background_code.java
// MAGIC.start();
}
}
);
}
//Method to return the element present in particular box if not return 0
int get_element(int i,int j)
{
String txt = plansza[i][j].getText();
if(txt.isEmpty())
return 0;
return Integer.parseInt(txt.trim());
}
//Method to set element in particular box
void set_element(int i,int j,int val)
{
plansza[i][j].setText(String.valueOf(val));
}
//Method to clear the box
void clear()
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
plansza[i][j].setText("");
}
}
}
}
| true
|
b936558d2b3c8015f2b40a78d2b7281e836dc2d3
|
Java
|
hxxy2003/dyninfo
|
/m3.opinion-webchat/.svn/pristine/e5/e505353116067d0a46342825d71efc242b0a0ee3.svn-base
|
UTF-8
| 4,429
| 1.96875
| 2
|
[] |
no_license
|
/*
*
* Copyright (c) 2009-2015 SHENZHEN Eternal Dynasty Technology Co.,Ltd.
* All rights reserved.
*
* This file contains valuable properties of SHENZHEN Eternal Dynasty
* Technology Co.,Ltd., embodying substantial creative efforts and
* confidential information, ideas and expressions. No part of this
* file may be reproduced or distributed in any form or by any means,
* or stored in a data base or a retrieval system, without the prior
* written permission of SHENZHEN Eternal Dynasty Technology Co.,Ltd.
*
*/
package cn.com.dyninfo.opinion.webchat.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.dyninfo.opinion.webchat.dao.QueryDao;
import cn.com.dyninfo.opinion.webchat.domain.EnumItemDomain;
import cn.com.dyninfo.opinion.webchat.domain.RepresentCriteria;
import cn.com.dyninfo.opinion.webchat.domain.RepresentDomain;
import cn.com.dyninfo.opinion.webchat.domain.StaffDomain;
import cn.com.dyninfo.opinion.webchat.domain.UserIdentityDomain;
import cn.com.dyninfo.opinion.webchat.mapper.MemberModelMapper;
import cn.com.dyninfo.opinion.webchat.model.MemberModel;
import cn.com.dyninfo.opinion.webchat.model.MemberModelCriteriaBuilder;
import cn.com.dyninfo.opinion.webchat.utils.CommonUtils;
/**
* Description:
*
*
*
* @Author : andy.du
* @Date : 2015年9月23日 下午10:09:20
* @Version: 1.0.0-SNAPSHOT
*/
@Service
public class QueryService {
@Autowired
private QueryDao queryDao;
@Autowired
private MemberModelMapper memberModelMapper;
private static final String OPINION_SERIAL_CODE = "OPINION_APPLY_SERIAL" ;
public String getOpinionSerialNo(){
Map<String,String> params = new HashMap<String,String>();
params.put("i_code", OPINION_SERIAL_CODE);
queryDao.genSerialNo(params);
return MapUtils.getString(params,"o_serial_no","");
}
public StaffDomain getStationStaffByOpenId(String wxOpenId){
MemberModelCriteriaBuilder builder = new MemberModelCriteriaBuilder();
builder.createCriteria().andWxOpenIdEqualTo(wxOpenId).andTypeEqualTo(0);
MemberModel member = CommonUtils.getFirstObjectOfList(memberModelMapper.select(builder));
if(member != null && StringUtils.isNotBlank(member.getPersonalId())){
return queryDao.getStationStaff(member.getPersonalId(), null);
}
return null;
}
public StaffDomain getStationStaffByMobile(String mobile){
return queryDao.getStationStaff(null, mobile);
}
public List<RepresentDomain> getRepresentByOpenId(String openId){
MemberModelCriteriaBuilder builder = new MemberModelCriteriaBuilder();
builder.createCriteria().andWxOpenIdEqualTo(openId)
.andTypeEqualTo(1);
MemberModel member = CommonUtils.getFirstObjectOfList(memberModelMapper.select(builder));
if(member != null && StringUtils.isNotBlank(member.getPersonalId())){
RepresentCriteria criteria = new RepresentCriteria();
criteria.setPersonalId(member.getPersonalId());
return queryDao.selectRepresent(criteria);
}
return new ArrayList<RepresentDomain>(1);
}
public List<RepresentDomain> getAllRepresent(){
RepresentCriteria criteria = new RepresentCriteria();
return queryDao.selectRepresent(criteria);
}
public RepresentDomain getRepresentByMobile(String mobile){
mobile = StringUtils.defaultString(mobile);
if(mobile.length()!=11){
return null;
}
RepresentCriteria criteria = new RepresentCriteria();
criteria.setMobile("%"+mobile+"%");
return CommonUtils.getFirstObjectOfList(queryDao.selectRepresent(criteria));
}
public List<EnumItemDomain> getEnumitemByCode(String enumTypeCode){
return queryDao.getEnumitemByCode(enumTypeCode);
}
public Map<String,EnumItemDomain> getEnumitemInMapByCode(String enumTypeCode){
Map<String,EnumItemDomain> map = new HashMap<String,EnumItemDomain>();
List<EnumItemDomain> list = queryDao.getEnumitemByCode(enumTypeCode);
for(EnumItemDomain item : list){
map.put(item.getEnumValue(),item);
}
return map;
}
public List<UserIdentityDomain> selectUserIdenityByMobile(String mobile){
return queryDao.selectUserIdenityByMobile(mobile);
}
}
| true
|
b8b1c7791381c69204a26af259827c0c45ced8ca
|
Java
|
kuke0932/kehaoduo
|
/wechat/src/main/java/com/htcs/kehaoduo/wechat/handler/impl/LogHandler.java
|
UTF-8
| 843
| 1.945313
| 2
|
[] |
no_license
|
package com.htcs.kehaoduo.wechat.handler.impl;
import com.htcs.kehaoduo.wechat.handler.AbstractLogHandler;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* Created by zhaokaiyuan on 17-7-10.
*/
@Component
public class LogHandler extends AbstractLogHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxCpXmlMessage, Map<String, Object> map, WxMpService wxCpService, WxSessionManager wxSessionManager) throws WxErrorException {
logger.debug("logger {}", wxCpXmlMessage);
return null;
}
}
| true
|
3fda1e00f6255979de081b0773f1431a16be7692
|
Java
|
amjekula/ElectronicHealthRecord_BackEnd
|
/src/main/java/mjeks/athenkosi/service/internal_generics/LabTestService.java
|
UTF-8
| 271
| 1.757813
| 2
|
[] |
no_license
|
package mjeks.athenkosi.service.internal_generics;
import mjeks.athenkosi.entity.internal_generics.LabTest;
import mjeks.athenkosi.service.IService;
import java.util.Set;
public interface LabTestService extends IService<LabTest, String> {
Set<LabTest> getAll();
}
| true
|
b83b546439359c8aca28ece8dd6553b467d07e1c
|
Java
|
isaacsecops/c
|
/cli/src/main/java/com/checkmarx/cxconsole/commands/GenerateTokenCommand.java
|
UTF-8
| 2,570
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.checkmarx.cxconsole.commands;
import com.checkmarx.cxconsole.commands.constants.Commands;
import com.checkmarx.cxconsole.commands.exceptions.CLICommandException;
import com.checkmarx.cxconsole.commands.exceptions.CLICommandParameterValidatorException;
import com.checkmarx.cxconsole.commands.job.CxGenerateTokenJob;
import com.checkmarx.cxconsole.commands.utils.CommandParametersValidator;
import com.checkmarx.cxconsole.parameters.CLIScanParametersSingleton;
import org.apache.log4j.Logger;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Created by nirli on 31/10/2017.
*/
class GenerateTokenCommand extends CLICommand {
private static final Logger log = Logger.getLogger(GenerateTokenCommand.class);
GenerateTokenCommand(CLIScanParametersSingleton params) {
super(params);
this.commandName = Commands.GENERATE_TOKEN.value();
}
@Override
protected int executeCommand() throws CLICommandException {
CxGenerateTokenJob job = new CxGenerateTokenJob(params);
Future<Integer> future = executor.submit(job);
try {
if (timeoutInSeconds != null) {
exitCode = future.get(timeoutInSeconds, TimeUnit.SECONDS);
} else {
exitCode = future.get();
}
} catch (Exception e) {
String errorMessage = e.getCause().getMessage();
log.error("Error executing GenerateToken command, due to: " + errorMessage);
throw new CLICommandException("Error executing GenerateToken command, due to: " + errorMessage);
}
return exitCode;
}
@Override
public void checkParameters() throws CLICommandParameterValidatorException {
CommandParametersValidator.validateGenerateTokenParams(params);
}
@Override
public String getCommandName() {
return commandName;
}
@Override
public String getUsageExamples() {
return "runCxConsole.cmd GenerateToken -CxServer http://localhost -cxuser admin@company -cxpassword admin -v";
}
@Override
public void printHelp() {
String helpHeader = "\nThe \"GenerateToken\" command allows to generate login token, to be used instead of username and password.";
String helpFooter = "\nUsage example: " + getUsageExamples() + "\n\n(c) 2017 CheckMarx.com LTD, All Rights Reserved\n";
helpFormatter.printHelp(120, getCommandName(), helpHeader, params.getCliMandatoryParameters().getGenerateTokenMandatoryParamsOptionGroup(), helpFooter, true);
}
}
| true
|
18baac0ce6793f16d10306d66e1a7faa19d073cb
|
Java
|
wojtekblack/miss2015
|
/src/pl/edu/agh/miss/chart/ScatterChart.java
|
UTF-8
| 2,976
| 2.875
| 3
|
[] |
no_license
|
package pl.edu.agh.miss.chart;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Shape;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.LogAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.Title;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.util.ShapeUtilities;
public class ScatterChart extends Chart<List<Point>>{
private Map<String, List<Point>> data;
public ScatterChart(){
data = new HashMap<String, List<Point>>();
}
@Override
public Chart<List<Point>> addSeries(String name, List<Point> values) {
data.put(name, values);
return this;
}
@Override
protected void save(File file) throws IOException {
//create series
XYSeriesCollection dataset = new XYSeriesCollection();
for(String key : data.keySet()){
XYSeries series = new XYSeries(key);
XYSeries deviationSeriesUp = new XYSeries(key + "_deviation1");
XYSeries deviationSeriesDown = new XYSeries(key + "_deviation2");
for(Point point : data.get(key)){
series.add(point.x, point.y);
deviationSeriesUp.add(point.x, point.y + point.deviation);
deviationSeriesDown.add(point.x, point.y - point.deviation);
}
dataset.addSeries(series);
if(standardDeviation) dataset.addSeries(deviationSeriesUp);
if(standardDeviation) dataset.addSeries(deviationSeriesDown);
}
JFreeChart chart = ChartFactory.createScatterPlot(title, xTitle, yTitle, dataset);
if(subtitles != null) {
for(Title subtitle : subtitles)
chart.addSubtitle(subtitle);
}
if(logScale){
XYPlot plot = (XYPlot) chart.getPlot();
LogAxis logAxis = new LogAxis(yTitle);
plot.setRangeAxis(logAxis);
}
if(standardDeviation){
Color [] colors = new Color[]{Color.RED, Color.BLUE, Color.GREEN, Color.PINK, Color.YELLOW};
XYPlot plot = (XYPlot) chart.getPlot();
XYItemRenderer renderer = plot.getRenderer();
int cnt = data.size() * 3;
for(int i = 0; i < cnt; i += 3){
if(i / 3 < colors.length) {
Paint paint = colors[i / 3];
Paint semiTransparentPaint = new Color(colors[i / 3].getRed(), colors[i / 3].getGreen(), colors[i / 3].getBlue(), colors[i / 3].getAlpha() / 10);
renderer.setSeriesPaint(i, paint);
renderer.setSeriesPaint(i + 1, semiTransparentPaint);
renderer.setSeriesPaint(i + 2, semiTransparentPaint);
}
renderer.setSeriesVisibleInLegend(i + 1, false);
renderer.setSeriesVisibleInLegend(i + 2, false);
Shape shape = ShapeUtilities.createDiamond(1);
renderer.setSeriesShape(i + 1, shape);
renderer.setSeriesShape(i + 2, shape);
}
}
ChartUtilities.saveChartAsJPEG(file, chart, size[0], size[1]);
}
}
| true
|
611daeb0d2c7b6d7f7690d30b2270255a912caf3
|
Java
|
alexstarr8155/AlphaBetaChess
|
/CapstoneProject7/src/controller/ChessBoard.java
|
UTF-8
| 7,921
| 2.78125
| 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 controller;
import model.Board;
import model.Coordinate;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.*;
import model.MoveThread;
import model.OpponentPlayer;
import model.Player;
public class ChessBoard {
private final JPanel gui = new JPanel(new BorderLayout(3, 3));
private final ChessBoardSquares chessBoardSquares = new ChessBoardSquares();
private JPanel chessBoard;
private MoveThread mt;
public boolean moveAllowed = true;
public static boolean twoPlayer;
public boolean whiteTurn = true;
public ChessBoard(int level) {
mt = new MoveThread(this, level);
twoPlayer = false;
OpponentPlayer.pieces = OpponentPlayer.initialState();
Player.pieces = Player.initialState();
setUpBoard();
}
public ChessBoard(int level, boolean twoPlayer) {
this(level);
this.twoPlayer = twoPlayer;
}
public final void setUpBoard() {
chessBoard = new JPanel(new GridLayout(0, 8));
chessBoard.setBorder(new LineBorder(Color.BLACK));
gui.add(chessBoard);
for (int i = 0; i < chessBoardSquares.board.length; i++) {
for (int j = 0; j < chessBoardSquares.board[i].length; j++) {
JButton b = new JButton();
if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.LIGHT_GRAY);
}
chessBoardSquares.board[j][i] = b;
}
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
// if (j == 0) {
//
// chessBoard.add(new JLabel("" + (i + 1), SwingConstants.CENTER));
//
// }
chessBoard.add(chessBoardSquares.board[j][i]);
}
}
update();
setUpButtons();
}
public void setUpButtons() {
for (int i = 0; i < chessBoardSquares.board.length; i++) {
for (int j = 0; j < chessBoardSquares.board[i].length; j++) {
JButton b = chessBoardSquares.board[i][j];
int numi = i;
int numj = j;
ActionListener boardListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//update();
if (twoPlayer) {
runGame(numi, numj, whiteTurn);
} else {
runGame(numi, numj);
}
}
};
b.addActionListener(boardListener);
}
}
}
public void runGame(int numi, int numj, boolean white) {
if (white) {
if (!new Coordinate(numi, numj).containsPiece(Board.BLACK)) {
boolean successful = false;
try {
successful = Player.selectedPiece.move(new Coordinate(numi, numj));
if (successful) {
Player.selectedPiece = null;
}
} catch (NullPointerException n) {
};
if (successful) {
whiteTurn = !whiteTurn;
}
} else if (Player.containsPiece(new Coordinate(numi, numj))) {
Player.selectedPiece = Player.pieceAt(new Coordinate(numi, numj));
}
} else {
if (!new Coordinate(numi, numj).containsPiece(Board.WHITE)) {
boolean successful = false;
try {
successful = Player.selectedPiece.move(new Coordinate(numi, numj));
if (successful) {
Player.selectedPiece = null;
}
} catch (NullPointerException n) {
}
if (successful) {
whiteTurn = !whiteTurn;
}
} else if (OpponentPlayer.containsPiece(new Coordinate(numi, numj))) {
Player.selectedPiece = OpponentPlayer.pieceAt(new Coordinate(numi, numj));
}
}
update();
}
public void runGame(int numi, int numj) {
boolean moveSuccessful = false;
if (Player.pieceAt(new Coordinate(numi, numj)) == null && moveAllowed) {
moveSuccessful = Player.selectedPiece.move(new Coordinate(numi, numj));
//update();
} else if (moveAllowed) {
Player.selectedPiece = Player.pieceAt(new Coordinate(numi, numj));
}
update();
if (moveSuccessful) {
moveAllowed = false;
new Thread(mt).start();
}
update();
}
public void update() {
//System.out.println(gui.getHeight());
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
chessBoardSquares.board[i][j].setIcon(new ImageIcon("blank.png"));
chessBoardSquares.board[i][j].setBackground(Color.WHITE);
//chessBoardSquares.board[i][j].setOpaque(false);
} else {
chessBoardSquares.board[i][j].setIcon(new ImageIcon("blank.png"));
chessBoardSquares.board[i][j].setBackground(Color.LIGHT_GRAY);
//chessBoardSquares.board[i][j].setOpaque(false);
}
if (Player.pieceAt(new Coordinate(i, j)) != null) {
chessBoardSquares.board[i][j].setIcon(Player.pieceAt(new Coordinate(i, j)).toImage());
}
if (OpponentPlayer.pieceAt(new Coordinate(i, j)) != null) {
chessBoardSquares.board[i][j].setIcon(OpponentPlayer.pieceAt(new Coordinate(i, j)).toImage());
}
}
}
}
public void lightPossibleMoves() {
if (Player.selectedPiece != null) {
for (Coordinate c : Player.selectedPiece.possibleMoves()) {
int i = c.getX();
int j = c.getY();
chessBoardSquares.board[i][j].setBackground(Color.CYAN);
//chessBoardSquares.board[i][j].setIcon(new ImageIcon("blank.png"));
}
} else {
setGridColours();
}
}
public void setGridColours() {
for (int i = 0; i < chessBoardSquares.board.length; i++) {
for (int j = 0; j < chessBoardSquares.board[i].length; j++) {
JButton b = new JButton();
if (Player.pieceAt(new Coordinate(i, j)) == null) {
if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.LIGHT_GRAY);
}
chessBoardSquares.board[j][i] = b;
}
}
}
}
// public void play() {
//
// if (!whiteTurn) {
// OpponentPlayer.makeMove();
// whiteTurn = true;
// }
//
// update();
//
// }
public JPanel returnFrame() {
return gui;
}
}
| true
|
695fc7201a602b2d52ea84e6207857ac662711ab
|
Java
|
daoo/polhemthegame
|
/src/main/java/loader/data/json/types/ProjectileData.java
|
UTF-8
| 456
| 1.742188
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Zlib"
] |
permissive
|
/*
* Copyright (c) 2009-2012 Daniel Oom, see license.txt for more info.
*/
package loader.data.json.types;
@SuppressWarnings("InstanceVariableNamingConvention")
public class ProjectileData {
public boolean collides;
public boolean gravity;
public Size hitbox;
public AOEData aoe;
public float damage;
public int targets;
public int duration;
public int range;
public float speed;
public SpriteData sprite;
public String texture;
}
| true
|
deef407a80ee19422c67b90f2fba88cde1490d74
|
Java
|
ImgBotApp/primefaces
|
/src/main/java/org/primefaces/util/ComponentTraversalUtils.java
|
UTF-8
| 5,447
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2009-2017 PrimeTek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.component.ContextCallback;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.UniqueIdVendor;
import javax.faces.context.FacesContext;
public class ComponentTraversalUtils {
public static <T> T closest(Class<T> type, UIComponent base) {
UIComponent parent = base.getParent();
while (parent != null) {
if (type.isAssignableFrom(parent.getClass())) {
return (T) parent;
}
parent = parent.getParent();
}
return null;
}
public static <T> T first(Class<T> type, UIComponent base) {
T result = null;
Iterator<UIComponent> kids = base.getFacetsAndChildren();
while (kids.hasNext() && (result == null)) {
UIComponent kid = (UIComponent) kids.next();
if (type.isAssignableFrom(kid.getClass())) {
result = (T) kid;
break;
}
result = first(type, kid);
if (result != null) {
break;
}
}
return result;
}
public static <T> ArrayList<T> children(Class<T> type, UIComponent base) {
ArrayList<T> result = new ArrayList<T>();
Iterator<UIComponent> kids = base.getFacetsAndChildren();
while (kids.hasNext()) {
UIComponent kid = (UIComponent) kids.next();
if (type.isAssignableFrom(kid.getClass())) {
result.add((T) kid);
}
}
return result;
}
public static void withId(String id, UIComponent base, List<UIComponent> components) {
if (id.equals(base.getId())) {
components.add(base);
}
if (base.getFacetCount() > 0) {
for (UIComponent facet : base.getFacets().values()) {
withId(id, facet, components);
}
}
if (base.getChildCount() > 0) {
for (int i = 0, childCount = base.getChildCount(); i < childCount; i++) {
UIComponent child = base.getChildren().get(i);
withId(id, child, components);
}
}
}
/**
* Finds the first component with the given id (NOT clientId!).
*
* @param id The id.
* @param base The base component to start the traversal.
* @return The component or null.
*/
public static UIComponent firstWithId(String id, UIComponent base) {
if (id.equals(base.getId())) {
return base;
}
UIComponent result = null;
Iterator<UIComponent> kids = base.getFacetsAndChildren();
while (kids.hasNext() && (result == null)) {
UIComponent kid = (UIComponent) kids.next();
if (id.equals(kid.getId())) {
result = kid;
break;
}
result = firstWithId(id, kid);
if (result != null) {
break;
}
}
return result;
}
/**
* Finds the first component by the given id expression or client id.
*
* @param id The id.
* @param base The base component to start the traversal.
* @param separatorString The seperatorString (e.g. :).
* @param context The FacesContext.
* @param callback the callback for the found component
*/
public static void firstById(String id, UIComponent base, String separatorString, FacesContext context, ContextCallback callback) {
// try #findComponent first
UIComponent component = base.findComponent(id);
// try #invokeOnComponent
// it's required to support e.g. a full client id for a component which is placed inside UIData components
if (component == null) {
// #invokeOnComponent doesn't support the leading seperator char
String tempExpression = id;
if (tempExpression.startsWith(separatorString)) {
tempExpression = tempExpression.substring(1);
}
context.getViewRoot().invokeOnComponent(context, tempExpression, callback);
}
else {
callback.invokeContextCallback(context, component);
}
}
public static UIForm closestForm(FacesContext context, UIComponent component) {
return closest(UIForm.class, component);
}
public static UniqueIdVendor closestUniqueIdVendor(UIComponent component) {
return (UniqueIdVendor) closest(UniqueIdVendor.class, component);
}
public static UIComponent closestNamingContainer(UIComponent component) {
return (UIComponent) closest(NamingContainer.class, component);
}
}
| true
|
3c0f357651a179e3375a7c0ce1bc7994d48c999d
|
Java
|
xh2321020/apiPlan
|
/src/main/java/com/cnnp/social/onPlan/repository/dao/OnPlanModifyInfoDao.java
|
UTF-8
| 851
| 2
| 2
|
[] |
no_license
|
package com.cnnp.social.onPlan.repository.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import com.cnnp.social.onPlan.repository.entity.PlanModifyInfo;
@Transactional
public interface OnPlanModifyInfoDao extends CrudRepository<PlanModifyInfo, String> ,JpaSpecificationExecutor<PlanModifyInfo>{
@Query("select count(*) from PlanModifyInfo ")
public long countPlan();
@Query("select count(*) from PlanModifyInfo planmi where planmi.id = ?1")
public long countPlan(Long id);
@Query("select planmi from PlanModifyInfo planmi where planmi.planid = ?1 ")
public List<PlanModifyInfo> findforme(String id);
}
| true
|
4a75d1210302643d67b58d2eec80fe3922e18651
|
Java
|
Poissonfish/iPat
|
/src/main/java/Enum_FileType.java
|
UTF-8
| 315
| 2.28125
| 2
|
[] |
no_license
|
public enum Enum_FileType {
NA("NA"), Phenotype("Phenotype"), Genotype("Genotype"), Map("Map"),
FAM("FAM"), BIM("BIM"), Covariate("Covariate"), Kinship("Kinship");
String name;
Enum_FileType(String name) {
this.name = name;
}
boolean isNA () {
return this == NA;
}
}
| true
|
a7487a2f60062f7585df84ac7aa813b602854f0a
|
Java
|
aliyun/aliyun-openapi-java-sdk
|
/aliyun-java-sdk-sas/src/main/java/com/aliyuncs/sas/transform/v20181203/DescribeModuleConfigResponseUnmarshaller.java
|
UTF-8
| 3,204
| 1.820313
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.sas.transform.v20181203;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.sas.model.v20181203.DescribeModuleConfigResponse;
import com.aliyuncs.sas.model.v20181203.DescribeModuleConfigResponse.ModuleConfig;
import com.aliyuncs.sas.model.v20181203.DescribeModuleConfigResponse.ModuleConfig.Item;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeModuleConfigResponseUnmarshaller {
public static DescribeModuleConfigResponse unmarshall(DescribeModuleConfigResponse describeModuleConfigResponse, UnmarshallerContext _ctx) {
describeModuleConfigResponse.setRequestId(_ctx.stringValue("DescribeModuleConfigResponse.RequestId"));
describeModuleConfigResponse.setHttpStatusCode(_ctx.integerValue("DescribeModuleConfigResponse.HttpStatusCode"));
describeModuleConfigResponse.setSuccess(_ctx.booleanValue("DescribeModuleConfigResponse.Success"));
describeModuleConfigResponse.setCount(_ctx.integerValue("DescribeModuleConfigResponse.Count"));
List<ModuleConfig> moduleConfigList = new ArrayList<ModuleConfig>();
for (int i = 0; i < _ctx.lengthValue("DescribeModuleConfigResponse.ModuleConfigList.Length"); i++) {
ModuleConfig moduleConfig = new ModuleConfig();
moduleConfig.setModuleName(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].ModuleName"));
moduleConfig.setConfigName(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].ConfigName"));
List<Item> items = new ArrayList<Item>();
for (int j = 0; j < _ctx.lengthValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items.Length"); j++) {
Item item = new Item();
item.setUuid(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items["+ j +"].Uuid"));
item.setGroupId(_ctx.integerValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items["+ j +"].GroupId"));
item.setInstanceName(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items["+ j +"].InstanceName"));
item.setRegion(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items["+ j +"].Region"));
item.setIp(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items["+ j +"].Ip"));
item.setInstanceId(_ctx.stringValue("DescribeModuleConfigResponse.ModuleConfigList["+ i +"].Items["+ j +"].InstanceId"));
items.add(item);
}
moduleConfig.setItems(items);
moduleConfigList.add(moduleConfig);
}
describeModuleConfigResponse.setModuleConfigList(moduleConfigList);
return describeModuleConfigResponse;
}
}
| true
|
539c9d0ae48c86d06a653f723d598af6c00cb144
|
Java
|
Daniel-BG/Maze-Generator-Solver
|
/src/com/marp/travellers/solving/TremauxTraveller.java
|
UTF-8
| 3,878
| 3.546875
| 4
|
[] |
no_license
|
package com.marp.travellers.solving;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
import com.marp.maze.Maze;
import com.marp.maze.MazeData;
import com.marp.travellers.MazeTraveller;
/**
* El algoritmo de Trèmaux funciona de la siguiente manera: Toma un punto inicial,
* y muévete aleatoriamente hacia uno adyacente. Sigue haciendo esto desde la nueva
* posición sin volver por el mismo camino. Hay dos casos en los que habrá que volver
* sobre los pasos dados:
* -Si te cruzas con algún tramo que ya habías recorrido
* -Si no puedes avanzar
* En cualquiera de esos dos casos, se vuelve hacia atrás por el camino dado hasta
* que se encuentre una intersección con un camino no tomado aún, y se toma.
* Finalmente se encontrará la salida, o se volverá a la casilla de inicio. En el segundo
* caso, el laberinto no tiene solución desde la casilla desde la que se empezó.
*
* @author Dani
*
*/
public class TremauxTraveller extends MazeTraveller {
//current path within the maze
private Stack<Point> curPath = new Stack<Point>();
//additional data for the algorithm
private boolean[][] TremauxData;
private ArrayList<Integer> dirs = new ArrayList<Integer>();
//CONSTRUCTOR
public TremauxTraveller(Maze m) {
super(m);
dirs.add(0);
dirs.add(1);
dirs.add(2);
dirs.add(3);
}
@Override
protected void doReset() {
this.map.initData();
this.TremauxData = new boolean[this.map.getWidth()][this.map.getHeight()];
}
@Override
protected void step() {
int cx = this.pos.x;
int cy = this.pos.y;
if (this.pos.equals(target)) { //terminamos por llegar al final
this.nextStepOnPath(cx, cy);
this.hasFinished = true;
return;
}
boolean hasMoved = false;
Collections.shuffle(dirs,rnd);
for (int i = 0; i < dirs.size() && !hasMoved; i++)
hasMoved |= move(dirs.get(i),cx,cy);
if (hasMoved)
return;
this.map.setColorAt(cx, cy, MazeData.COLOR_NOVALID);
this.TremauxData[cx][cy] = true;
if (this.curPath.isEmpty()) { //terminamos por no haber encontrado el final
this.hasFinished = true;
return;
}
this.pos = this.curPath.pop();
}
/**
* Tries to move in the specified direction (0 north, 1 east...)
* @param dir
* @param cx
* @param cy
* @return true if it moved, false otherwise
*/
private boolean move(int dir,int cx, int cy) {
//intenta hacia la izqda
if (dir == 0 && cx > 0 && !this.map.getValueAt(cx-1, cy) && !this.TremauxData[cx-1][cy]) {
this.nextStepOnPath(cx, cy);
this.pos.x = cx-1;
return true;
}
//intenta hacia la derecha
if (dir == 1 && cx < this.map.getWidth()-1 && !this.map.getValueAt(cx+1, cy) && !this.TremauxData[cx+1][cy]) {
this.nextStepOnPath(cx, cy);
this.pos.x = cx+1;
return true;
}
//intenta hacia arriba
if (dir == 2 && cy > 0 && !this.map.getValueAt(cx, cy-1) && !this.TremauxData[cx][cy-1]) {
this.nextStepOnPath(cx, cy);
this.pos.y = cy-1;
return true;
}
//intenta hacia abajo
if (dir == 3 &&cy < this.map.getHeight()-1 && !this.map.getValueAt(cx, cy+1) && !this.TremauxData[cx][cy+1]) {
this.nextStepOnPath(cx, cy);
this.pos.y = cy+1;
return true;
}
return false;
}
/**
* Puts the info of a new step being taken from (x,y) into the data of the maze
* @param x
* @param y
*/
private void nextStepOnPath(int x, int y) {
this.curPath.push(new Point(x,y));
this.map.setColorAt(x, y, MazeData.COLOR_CURPATH);
this.TremauxData[x][y] = true;
}
@Override
public String getCurrentExecutionInfo() {
return super.getCurrentExecutionInfo() +
"Stack size: " + this.curPath.size() + "\n" +
"Current position: (" + this.pos.x + "," + this.pos.y + ")\n";
}
}
| true
|
65fa90e29bf9d2b5ab9e9b41573d13f7351da1a4
|
Java
|
arunav-b/dsalgo
|
/13-advancedgraphs/src/main/java/com/arunav/dsalgo/advancedgraphs/representation/Vertex.java
|
UTF-8
| 462
| 3.078125
| 3
|
[] |
no_license
|
package com.arunav.dsalgo.advancedgraphs.representation;
public class Vertex<T> {
private int id;
private T vertex;
public Vertex(int id, T vertex) {
this.id = id;
this.vertex = vertex;
}
public int getId() {
return id;
}
public T getVertex() {
return vertex;
}
@Override
public String toString() {
return "Vertex{" +
"id=" + id +
'}';
}
}
| true
|
964edb424fe037bf9ee64eae38ecfb2a49dcb504
|
Java
|
sgholamian/log-aware-clone-detection
|
/NLPCCd/HBase/3620_1.java
|
UTF-8
| 984
| 1.882813
| 2
|
[
"MIT"
] |
permissive
|
//,temp,sample_742.java,2,16,temp,sample_743.java,2,16
//,2
public class xxx {
public void dummy_method(){
HRegionInfo parent = new HRegionInfo(td.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("eee"));
HRegionInfo splita = new HRegionInfo(td.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("ccc"));
HRegionInfo splitb = new HRegionInfo(td.getTableName(), Bytes.toBytes("ccc"), Bytes.toBytes("eee"));
Result parentMetaRow = createResult(parent, splita, splitb);
FileSystem fs = FileSystem.get(HTU.getConfiguration());
Path rootdir = this.masterServices.getMasterFileSystem().getRootDir();
FSUtils.setRootDir(fs.getConf(), rootdir);
Path tabledir = FSUtils.getTableDir(rootdir, td.getTableName());
Path storedir = HStore.getStoreHomedir(tabledir, parent, td.getColumnFamilies()[0].getName());
Path storeArchive = HFileArchiveUtil.getStoreArchivePath(this.masterServices.getConfiguration(), parent, tabledir, td.getColumnFamilies()[0].getName());
log.info("table dir");
}
};
| true
|
04eacdca1dfdf310eb3a912f8756bcd8aa03006c
|
Java
|
magenta-aps/datafordeler
|
/core/src/main/java/dk/magenta/datafordeler/core/exception/InvalidServiceOwnerDefinitionException.java
|
UTF-8
| 612
| 2.328125
| 2
|
[] |
permissive
|
package dk.magenta.datafordeler.core.exception;
import dk.magenta.datafordeler.core.plugin.Plugin;
import java.util.regex.Pattern;
public class InvalidServiceOwnerDefinitionException extends InvalidPluginDefinitionException {
public InvalidServiceOwnerDefinitionException(Plugin plugin, String ownerDefinition, Pattern validationRegex) {
super(plugin, "\"" + ownerDefinition + "\" is not a valid owner definition, must conform to regex /" + validationRegex.pattern() + "/");
}
@Override
public String getCode() {
return "datafordeler.plugin.invalid_owner_definition";
}
}
| true
|
32ac14fd3f192aa8f86adf34d09cbdb823c50f08
|
Java
|
hiejulia/batch
|
/src/main/java/com/project/batch/writer/transaction/CustomerStatementItemStreamItemWriter.java
|
UTF-8
| 1,849
| 2.28125
| 2
|
[] |
no_license
|
package com.project.batch.writer.transaction;
import java.util.List;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.file.ResourceAwareItemWriterItemStream;
import org.springframework.core.io.Resource;
import com.apress.springbatch.statement.domain.Customer;
import com.apress.springbatch.statement.domain.Transaction;
// Customer Statement Item stream item writer
public class CustomerStatementItemStreamItemWriter implements
ResourceAwareItemWriterItemStream<Customer> {
private ResourceAwareItemWriterItemStream<Customer> bodyWriter;
private ResourceAwareItemWriterItemStream<Transaction> detailWriter;
public void close() throws ItemStreamException {
bodyWriter.close();
detailWriter.close();
}
public void open(ExecutionContext executionContext) throws ItemStreamException {
bodyWriter.open(executionContext);
detailWriter.open(executionContext);
}
public void update(ExecutionContext executionContext) throws ItemStreamException {
bodyWriter.update(executionContext);
detailWriter.update(executionContext);
}
public void write(List<? extends Customer> customers) throws Exception {
bodyWriter.write(customers);
detailWriter.write(customers.get(0).getAccount().getTransactions());
}
public void setResource(Resource resource) {
bodyWriter.setResource(resource);
detailWriter.setResource(resource);
}
public void setBodyWriter(ResourceAwareItemWriterItemStream<Customer> bodyWriter) {
this.bodyWriter = bodyWriter;
}
public void setDetailWriter(
ResourceAwareItemWriterItemStream<Transaction> detailWriter) {
this.detailWriter = detailWriter;
}
}
| true
|
a6f96d7b64445b11fad967f6b09835068806fb3c
|
Java
|
sinooceanland/OnePush
|
/one-push-huawei/src/main/java/com/peng/one/push/huawei/hmsagents/NotificationClickActivity.java
|
UTF-8
| 1,608
| 1.992188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.peng.one.push.huawei.hmsagents;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.peng.one.push.OneRepeater;
import com.peng.one.push.utils.JsonUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* Created by pyt on 2017/5/15.
*/
public class NotificationClickActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
if (uri != null) {
Log.i(NotificationClickActivity.class.getSimpleName(), "URL:" + uri.toString());
String title = uri.getQueryParameter("title");
String content = uri.getQueryParameter("content");
// String keyValue = uri.getQueryParameter("keyValue"); //因为华为通道两次转码的问题,使用新的keyValue1
String keyValue1 = uri.getQueryParameter("keyValue1");
try {
Log.i(NotificationClickActivity.class.getSimpleName(), "keyValue:" + URLDecoder.decode(keyValue1, "utf-8"));
OneRepeater.transmitNotificationClick(getApplicationContext(), -1, title, content, null, JsonUtils.toMap(new JSONObject(URLDecoder.decode(keyValue1, "utf-8"))));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
finish();
}
}
| true
|
a0c8a3f8fc51cd33865d8a4f54d465b6edd88297
|
Java
|
UserWeronikaGarbarz/weronika-garbarz-kodilla-java
|
/kodilla-stream/src/main/java/com/kodilla/stream/world/World.java
|
UTF-8
| 613
| 2.96875
| 3
|
[] |
no_license
|
package com.kodilla.stream.world;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class World {
private List<Continent> continents = new ArrayList<>();
public void addContinent(Continent continent) {
continents.add(continent);
}
public List<Continent> getContinents() {
return continents;
}
public BigDecimal getPeopleQuantity() {
return continents.stream().flatMap(continent -> Stream.of(continent.getPeopleQuantity()))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
| true
|
59dda216a8c5fdae09b03054ca55ed91bdb447a9
|
Java
|
tiborh/java
|
/points_and_lines/Point.java
|
UTF-8
| 603
| 3.609375
| 4
|
[] |
no_license
|
/**
* Point class to study a task of week 4 quiz
*
* @author University of Madrid
* @version 0.01
* @since 2015-06-06
*/
public class Point
{
/**
* Coordinates
*/
private double x = 0;
private double y = 0;
/**
* Constructor
*/
public Point(int a, int b)
{
x = a;
y = b;
}
/**
* getting coordinates
*/
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public String toString()
{
return "(" + x + "," + y + ")";
}
}
| true
|
8720818a920669c4dcf9952f4a3f0a0c5ad23a3d
|
Java
|
lkemin/travel.b2b
|
/src/main/java/com/zb/app/web/tools/WebUserTools.java
|
UTF-8
| 3,280
| 2
| 2
|
[] |
no_license
|
/*
* Copyright 2011-2016 ZuoBian.com All right reserved. This software is the confidential and proprietary information of
* ZuoBian.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
* in accordance with the terms of the license agreement you entered into with ZuoBian.com.
*/
package com.zb.app.web.tools;
import org.apache.commons.lang.StringUtils;
import com.zb.app.biz.cons.CompanyTypeEnum;
import com.zb.app.biz.cons.MemberTypeEnum;
import com.zb.app.common.authority.Right;
import com.zb.app.common.core.lang.Argument;
import com.zb.app.common.util.DateViewTools;
import com.zb.app.web.webuser.ZuobianWebUser;
/**
* @author zxc Jul 8, 2014 11:17:48 AM
*/
public class WebUserTools {
public static ZuobianWebUser current() {
return ZuobianWebUser.getCurrentUser();
}
public static String getNick() {
return current() == null ? null : current().getUserName();
}
public static String getCompanyName() {
return current() == null ? null : current().getCompanyName();
}
public static CompanyTypeEnum getCompanyType() {
return current() == null ? null : current().getType();
}
public static MemberTypeEnum getMemberType() {
return current() == null ? null : current().getmType();
}
public static Long getCid() {
return current() == null ? null : current().getcId();
}
public static Long getMid() {
return current() == null ? null : current().getmId();
}
public static Long getSiteId() {
return current() == null ? null : current().getSiteId();
}
public static String getSiteName() {
return current() == null ? StringUtils.EMPTY : current().getSiteName();
}
public static Long getChugangId() {
return current() == null ? null : current().getChugangId();
}
public static String getChugangName() {
return current() == null ? StringUtils.EMPTY : current().getChugangName();
}
public static String getLastLogin() {
return current() == null ? null : DateViewTools.format(current().getLastLogin(), "yyyy-MM-dd HH:mm");
}
public static boolean hasLogin() {
return current() == null ? false : current().hasLogin();
}
public static boolean hasPermission(String right) {
if (StringUtils.isEmpty(right)) {
return false;
}
if (current() == null) {
return false;
}
if (MemberTypeEnum.isSupper(current().getmType())) {
return true;
}
return current().getRightSet().contains(Right.getAction(right));
}
public static boolean hasPermission(Integer right) {
if (Argument.isNotPositive(right)) {
return false;
}
if (current() == null) {
return false;
}
if (MemberTypeEnum.isSupper(current().getmType())) {
return true;
}
return current().getRightSet().contains(Right.getAction(right));
}
public static Object getPermissionValue(String value) {
return null;
}
@Override
public String toString() {
return current() == null ? StringUtils.EMPTY : current().toString();
}
}
| true
|
fb26ffdbd2eb7703e5c482980165c9cc006c18ff
|
Java
|
rickymartingou/RowanMartini
|
/src/ViewProfileForm.java
|
UTF-8
| 8,496
| 2.40625
| 2
|
[] |
no_license
|
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.*;
import javax.swing.*;
public class ViewProfileForm extends JInternalFrame implements ActionListener,WindowListener {
Connect con;
MainForm mainForm;
JPanel finalMainPanel,mainPanel,mainPanel2,panelContain,panelTitle,panelUsername,panelPhone,panelGender,panelButton;
JPanel panelTxtPhone,panelTxtGender,panelTxtUsername;
JLabel lblUsername,lblPhone,lblGender,lblTitle;
JTextField txtUsername,txtPhone,txtGender;
JButton btnSubmit,btnUpdate,btnCancel;
JRadioButton radioMale,radioFemale;
ButtonGroup radioGroup;
String radio,userPhone,userGender,userName;
public void setButtonState(boolean state)
{
btnUpdate.setEnabled(!state);
btnCancel.setEnabled(state);
btnSubmit.setEnabled(state);
}
public void init()
{
finalMainPanel = new JPanel();
mainPanel = new JPanel(new GridLayout(3,2));
mainPanel2 = new JPanel();
panelTitle = new JPanel();
panelUsername = new JPanel();
panelPhone = new JPanel();
panelGender = new JPanel();
panelContain = new JPanel();
panelTxtUsername = new JPanel();
panelTxtPhone = new JPanel();
panelTxtGender = new JPanel();
panelButton = new JPanel();
lblUsername = new JLabel("Username",SwingConstants.CENTER);
lblPhone = new JLabel("Phone Number",SwingConstants.CENTER);
lblGender = new JLabel("Gender",SwingConstants.CENTER);
lblTitle = new JLabel("Profile",SwingConstants.CENTER);
lblTitle.setFont(new Font("",Font.BOLD,15));
btnSubmit = new JButton("Update");
btnUpdate = new JButton("Edit");
btnCancel = new JButton("Cancel");
txtUsername = new JTextField();
txtUsername.setPreferredSize(new Dimension(120, 25));
txtUsername.setEnabled(false);
txtPhone = new JTextField();
txtPhone.setPreferredSize(new Dimension(120, 25));
txtPhone.setEnabled(false);
radioMale = new JRadioButton("Male");
radioFemale = new JRadioButton("Female");
radioMale.setEnabled(false);
radioFemale.setEnabled(false);
radioGroup = new ButtonGroup();
radioGroup.add(radioMale);
radioGroup.add(radioFemale);
panelUsername.add(lblUsername);
panelUsername.setLayout(new FlowLayout(FlowLayout.LEFT,10,2));
panelTxtUsername.add(txtUsername);
panelTxtUsername.setLayout(new FlowLayout(FlowLayout.LEFT,10,2));
panelPhone.add(lblPhone);
panelPhone.setLayout(new FlowLayout(FlowLayout.LEFT,10,2));
panelTxtPhone.add(txtPhone);
panelTxtPhone.setLayout(new FlowLayout(FlowLayout.LEFT,10,2));
panelGender.add(lblGender);
panelGender.setLayout(new FlowLayout(FlowLayout.LEFT,10,2));
panelTxtGender.add(radioMale);
panelTxtGender.add(radioFemale);
panelTxtGender.setLayout(new FlowLayout(FlowLayout.LEFT,10,2));
panelButton.add(btnUpdate);
panelButton.add(btnSubmit);
panelButton.add(btnCancel);
panelButton.setLayout(new FlowLayout(FlowLayout.CENTER));
mainPanel.add(panelUsername);
mainPanel.add(panelTxtUsername);
mainPanel.add(panelPhone);
mainPanel.add(panelTxtPhone);
mainPanel.add(panelGender);
mainPanel.add(panelTxtGender);
panelTitle.add(lblTitle);
panelTitle.setLayout(new FlowLayout(FlowLayout.CENTER,10,2));
panelContain.add(mainPanel);
panelContain.setLayout(new FlowLayout());
mainPanel2.setLayout(new BoxLayout(mainPanel2,BoxLayout.Y_AXIS));
mainPanel2.add(panelTitle);
mainPanel2.add(panelContain);
finalMainPanel.add(mainPanel2);
finalMainPanel.add(panelButton);
add(finalMainPanel);
btnUpdate.addActionListener(this);
btnSubmit.addActionListener(this);
btnCancel.addActionListener(this);
setButtonState(false);
txtUsername.setText(userName);
txtUsername.setEnabled(false);
txtPhone.setText(userPhone);
if(userGender.equals("Male"))
{
radioMale.setSelected(true);
}
else if(userGender.equals("Female"))
{
radioFemale.setSelected(true);
}
}
private void getUserData()
{
con.rs = con.executeQuery("SELECT username,phone,gender FROM users WHERE id = "+Integer.parseInt(mainForm.loginForm.tempID));
try {
con.rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
userName = con.rs.getString("username");
userPhone = con.rs.getString("phone");
userGender = con.rs.getString("gender");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initFrame()
{
setSize(320,210);
setLocation(mainForm.getWidth() / 2 - getWidth() / 2, mainForm.getHeight() / 2 - getHeight() / 2);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public ViewProfileForm(MainForm mainForm, Connect con)
{
super("MyProfile",true,true,false);
this.mainForm=mainForm;
this.con = con;
getUserData();
init();
initFrame();
setVisible(true);
}
private boolean numericChecker(String test){
int digit = 0;
for(int i=0;i<test.length();i++){
if(Character.isDigit(test.charAt(i))){
digit++;
}
}
if(digit == test.length())
return true;
else
return false;
}
@Override
public void actionPerformed(ActionEvent src) {
// TODO Auto-generated method stub
if(src.getSource()==btnUpdate)
{
txtPhone.setEnabled(true);
radioMale.setEnabled(true);
radioFemale.setEnabled(true);
setButtonState(true);
}
else if(src.getSource()==btnSubmit)
{
txtPhone.setEnabled(false);
radioMale.setEnabled(false);
radioFemale.setEnabled(false);
if(radioMale.isSelected())
{
radio = "Male";
}
else if(radioFemale.isSelected())
{
radio = "Female";
}
if(txtPhone.getText().equals(""))
{
txtPhone.setText(userPhone);
if(userGender.equals("Male"))
{
radioMale.setSelected(true);
}
else if(userGender.equals("Female"))
{
radioFemale.setSelected(true);
}
JOptionPane.showMessageDialog(null,"Phone number must be filled", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(numericChecker(txtPhone.getText().toString()) == false)
{
txtPhone.setText(userPhone);
if(userGender.equals("Male"))
{
radioMale.setSelected(true);
}
else if(userGender.equals("Female"))
{
radioFemale.setSelected(true);
}
JOptionPane.showMessageDialog(null,"Phone Number must be numeric", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(txtPhone.getText().length() != 11)
{
txtPhone.setText(userPhone);
if(userGender.equals("Male"))
{
radioMale.setSelected(true);
}
else if(userGender.equals("Female"))
{
radioFemale.setSelected(true);
}
JOptionPane.showMessageDialog(null, "Phone Number must be 11 digits", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(!radioMale.isSelected()&&!radioFemale.isSelected())
{
txtPhone.setText(userPhone);
if(userGender.equals("Male"))
{
radioMale.setSelected(true);
}
else if(userGender.equals("Female"))
{
radioFemale.setSelected(true);
}
JOptionPane.showMessageDialog(null,"Gender must be selected", "Error", JOptionPane.ERROR_MESSAGE);
}
else
{
con.executeUpdateProfileToUsers(txtPhone.getText().toString(),radio,Integer.parseInt(mainForm.loginForm.tempID));
JOptionPane.showMessageDialog(null,"Update Success !");
}
setButtonState(false);
}
else if(src.getSource()==btnCancel)
{
txtPhone.setEnabled(false);
radioMale.setEnabled(false);
radioFemale.setEnabled(false);
setButtonState(false);
}
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
mainForm.enableMenu(false);
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
mainForm.enableMenu(false);
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
}
| true
|
22f6365d9d91d0a7080028410fcbe4f4e902dab5
|
Java
|
yugansan/SecuriteInformatique
|
/projet_SI/Cesar.java
|
UTF-8
| 1,573
| 3.203125
| 3
|
[] |
no_license
|
public class Cesar implements Chiffrement<String,Integer,Character>{
@Override
public char chiffrer_caract(Character car, Integer clef) {
car=Character.toLowerCase(car);
if(96<car && car<123){
int carInt=((int)car)-97;
char code=(char)(((carInt+clef)%26)+97);
return (code);
}/*}else if(64<car && car<91){
int carInt=((int)car)-65;
char code=(char)(((carInt+clef)%26)+65);
return (code);
}
*/
return car;
}
@Override
public String chiffrer_str(String str, Integer clef) {
String msgChiffrer="";
for (int i=0;i<str.length();i++) {
msgChiffrer+=chiffrer_caract(str.charAt(i),clef);
}
return msgChiffrer;
}
@Override
public char dechiffrer_caract(Character car, Integer clef) {
car=Character.toLowerCase(car);
if(96<car && car<123){
int carInt=((int)car)-97;
if(carInt<clef){
int reste=((carInt+97)-clef)%26;
char code=(char) (123-reste);
return (code);
}
char code=(char)(((carInt-clef)%26)+97);
return (code);
}
/*else if(64<car && car<91){
int clefInt=((int)clef)-65;
int carInt=((int)car)-65;
if(carInt<clef){
int reste=clef-carInt;
char code=(char) (91-reste);
return (code);
}
char code=(char)(((carInt-clef)%26)+65);
return (code);
}
*/
return car;
}
@Override
public String dechiffrer_str(String str, Integer clef) {
String msgDechiffrer="";
for (int i=0;i<str.length();i++) {
msgDechiffrer+=dechiffrer_caract(str.charAt(i),clef);
}
return msgDechiffrer;
}
}
| true
|
58cae56dc1679508c854a92f42b2f52817c940b2
|
Java
|
Matheus1206/SeleniumJavaTest
|
/src/test/java/configuration/Config.java
|
UTF-8
| 1,159
| 2.484375
| 2
|
[] |
no_license
|
package configuration;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Config {
private WebDriver driver;
private final String URL = "olapodcasts";
public WebDriver iniciaDriver(){
String soNome = System.getProperty("os.name");
if(soNome.startsWith("W")){
System.setProperty("webdriver.chrome.driver","drivers/windows.exe");
driver = new ChromeDriver();
}else if(soNome.startsWith("M")){
System.setProperty("webdriver.chrome.driver","drivers/mac");
driver = new ChromeDriver();
} else if(soNome.startsWith("U") || soNome.startsWith("L")) {
System.setProperty("webdriver.chrome.driver", "drivers/linux");
driver = new ChromeDriver();
}
return driver;
}
public WebDriver acessaUrlDoOla(){
WebDriver driver = iniciaDriver();
driver.get("https://"+URL+".com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
return driver;
}
}
| true
|
a26e526c987b789799798e6df50d7db3f854c0f3
|
Java
|
srinnix1395/kindergaten
|
/app/src/main/java/com/srinnix/kindergarten/request/model/LoginResponse.java
|
UTF-8
| 826
| 1.984375
| 2
|
[] |
no_license
|
package com.srinnix.kindergarten.request.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.srinnix.kindergarten.model.Child;
import com.srinnix.kindergarten.model.Contact;
import com.srinnix.kindergarten.model.User;
import java.util.ArrayList;
/**
* Created by anhtu on 2/23/2017.
*/
public class LoginResponse {
@SerializedName("info")
@Expose
private User user;
@SerializedName("children")
@Expose
private ArrayList<Child> children;
@SerializedName("contact")
@Expose
private ArrayList<Contact> contacts;
public User getUser() {
return user;
}
public ArrayList<Child> getChildren() {
return children;
}
public ArrayList<Contact> getContacts() {
return contacts;
}
}
| true
|
3a1a4859f62732432fb4775961727b008fc565ac
|
Java
|
abarraco/imis-cbms
|
/src/org/vmasc/cbms/client/bindings/generated/cbml_1_0/RailcarTypeCategoryCode.java
|
UTF-8
| 4,272
| 1.84375
| 2
|
[] |
no_license
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.11.04 at 01:32:24 PM EDT
//
package org.vmasc.cbms.client.bindings.generated.cbml_1_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RailcarTypeCategoryCode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="RailcarTypeCategoryCode">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="LCMTVE"/>
* <enumeration value="NKN"/>
* <enumeration value="NOS"/>
* <enumeration value="RLDEQP"/>
* <enumeration value="RLLSTK"/>
* <enumeration value="TRAIN"/>
* <enumeration value="TRAM"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "RailcarTypeCategoryCode", namespace = "urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2")
@XmlEnum
public enum RailcarTypeCategoryCode {
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">A detachable, wheeled engine used for pulling trains.</Definition>
* </pre>
*
*
*
*/
LCMTVE,
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">It is not possible to determine which value is most applicable.</Definition>
* </pre>
*
*
*
*/
NKN,
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">The appropriate value is not in the set of specified values.</Definition>
* </pre>
*
*
*
*/
NOS,
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">Mobile equipment that uses rails to move on, for example, dockyard cranes.</Definition>
* </pre>
*
*
*
*/
RLDEQP,
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">Generic term for wagons, either passenger, freight or specialised that are used to form a train.</Definition>
* </pre>
*
*
*
*/
RLLSTK,
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">A self-propelled passenger carrying vehicle that runs on rails.</Definition>
* </pre>
*
*
*
*/
TRAIN,
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Definition xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jc3iedm="urn:int:nato:standard:mip:jc3iedm:3.0.2:oo:2.2" xml:lang="en">A passenger carrying vehicle that runs on rails normally along roads, with minimal earthworks, typically powered by electricity from overhead power cables via a pantograph.</Definition>
* </pre>
*
*
*
*/
TRAM;
public String value() {
return name();
}
public static RailcarTypeCategoryCode fromValue(String v) {
return valueOf(v);
}
}
| true
|
b9c3681c7ba4e8b991472c4ec2efb11d68a34734
|
Java
|
trustnature/Spring_Hibernate
|
/src/xyz/tuny/jx/util/HibernateUtil.java
|
UTF-8
| 933
| 2.296875
| 2
|
[] |
no_license
|
package xyz.tuny.jx.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private final static SessionFactory FACTORY = buildSessionFactroy();
private static SessionFactory buildSessionFactroy() {
Configuration cfg = new Configuration().configure();
StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
StandardServiceRegistry sr = srb.build();
SessionFactory sf = cfg.buildSessionFactory(sr);
return sf;
}
public static SessionFactory getSessionFactroy(){
return FACTORY;
}
public static Session openSession(){
return FACTORY.openSession();
}
public static void close(Session session){
if(session != null) session.close();
}
}
| true
|
520ae29c790963f2c2f0d9dfd80397493fa3a414
|
Java
|
iangowland/JavaPractice
|
/Week 5/NestedPractice/src/NestedLoops.java
|
UTF-8
| 433
| 3.25
| 3
|
[] |
no_license
|
public class NestedLoops
{
public static void main(String[] args)
{
for (int rowNum = 1; rowNum < 5; rowNum++)
{
System.out.print(rowNum);
System.out.print(" : ");
for (int colNum = 1; colNum< 5; colNum++)
{
System.out.print(colNum);
System.out.print(" ");
}
System.out.println();
}
}
}
| true
|
5f901e7456b2e365c859e7f4e9d1949e23be4d5d
|
Java
|
GislaineMartins/Agenda_JavaWeb
|
/src/java/teste.java
|
UTF-8
| 911
| 2.34375
| 2
|
[] |
no_license
|
import Utilitarios.Conexao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author gimcj
*/
public class teste {
public static void main(String[] args) {
Conexao Con = new Conexao();
try {
PreparedStatement stm = Con.getConnection().prepareStatement("SELECT * FROM `contato` ");
ResultSet rs = stm.executeQuery();
rs.next();
System.out.println(rs.getString("Nome"));
} catch (SQLException ex) {
Logger.getLogger(teste.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true
|
1afb72057d07049e9031a301c0ea8975838b94f3
|
Java
|
Shrey-Sachdeva/Project5_ss77335_kmo785
|
/src/assignment5/Critter1.java
|
UTF-8
| 2,810
| 3.3125
| 3
|
[] |
no_license
|
package assignment5;
/* CRITTERS Critter1.java
* EE422C Project 4 submission by
* Shrey Sachdeva
* ss77335
* 15455
* Kylar Osborne
* kmo785
* 15455
* Slip days used: <0>
* Spring 2018
*/
/**
* Critter1 - The Buffalo
* Ecological Niche: Nomadic grazing animal, forms herds with its own kind and eats algae as it traverses the world
* This unique Critter has the special property of only being able to move in one direction - right.
* At first one may consider this a boring characteristic, however any more-than-casual observer will find
* that from this characteristic emerges the phenomena of only traveling in groups which resemble herds.
* The Critter1 is a very ecologically sustainable animal. As the herd travels to the right it consumes all Algae
* in its path. However, the newly open space is quickly replenished over time as the herd takes its time to come
* back around the torus world and eat even more dense algae.
*/
public class Critter1 extends Critter {
private int direction;
public Critter1() {
direction = 0;
}
@Override
public String toString() {
return "1";
}
@Override
public void doTimeStep() {
lookDuringTimeStep = true;
String occupant = look(direction, true); // ??
run(direction);
lookDuringTimeStep = false;
Critter1 offspring = new Critter1();
reproduce(offspring, getRandomInt(8));
}
@Override
public boolean fight(String opponent) {
if(opponent.equals("@")) {// buffalo eat grass
return true;
}
else {
tryingToFlee = true;
String occupant = look(4, true); // ??
walk(4);//move back in the herd
return false;
}
}
public static String runStats(java.util.List<Critter> ones) { //
if(ones.size() == 0) {
//System.out.println("0 total Critter1s, how sad");
return "0 total Critter1s, how sad";
}
int averageEnergy = 0;
for(Object o : ones) {
Critter1 one = (Critter1) o;
averageEnergy += one.getEnergy();
}
averageEnergy /= ones.size();
//System.out.println(ones.size() + " total Critter1s running to the right with average energy: " + averageEnergy);
return (ones.size() + " total Critter1s running to the right with average energy: " + averageEnergy);
}
@Override
public CritterShape viewShape() {
// TODO Auto-generated method stub
return CritterShape.TRIANGLE;
}
public javafx.scene.paint.Color viewFillColor() { return javafx.scene.paint.Color.YELLOW; }
public javafx.scene.paint.Color viewOutlineColor() { return javafx.scene.paint.Color.BLUE; }
}
| true
|
95512837c018051772a3359fa39bdab9d1e2fd2a
|
Java
|
JohnLeek/ssmProject
|
/shop-sso/src/main/java/com/taotao/sso/service/LoginService.java
|
UTF-8
| 400
| 1.757813
| 2
|
[] |
no_license
|
package com.taotao.sso.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.taotao.common.pojo.TaotaoResult;
public interface LoginService {
TaotaoResult login(String username, String password, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse);
TaotaoResult getUserByToken(String token);
}
| true
|
e80d5112f337373c4a704c971e19b4de5121fa8e
|
Java
|
HughesLou/lintcode
|
/src/main/java/com/hughes/lou/lintcode/easy/ClosestBinarySearchTreeValue900.java
|
UTF-8
| 1,056
| 3.359375
| 3
|
[] |
no_license
|
package com.hughes.lou.lintcode.easy;
import com.hughes.lou.lintcode.level.Easy;
import com.hughes.lou.lintcode.model.TreeNode;
/**
* @author HughesLou
* Created on 2022-04-05
*/
public class ClosestBinarySearchTreeValue900 implements Easy {
/**
* @param root: the given BST
* @param target: the given target
* @return: the value in the BST that is closest to the target
*/
public int closestValue(TreeNode root, double target) {
if (root == null) {
return 0;
}
TreeNode upper = root;
TreeNode lower = root;
while (root != null) {
if (root.val > target) {
upper = root;
root = root.left;
} else if (root.val < target) {
lower = root;
root = root.right;
} else {
return root.val;
}
}
if (Math.abs(upper.val - target) > Math.abs(target - lower.val)) {
return lower.val;
}
return upper.val;
}
}
| true
|
d6f2ef5a2e3cdf005b86ab2bfc9cd94c45ebb2c0
|
Java
|
Den22/javaServerSpring
|
/src/main/java/com/example/Hotel.java
|
UTF-8
| 174
| 1.679688
| 2
|
[] |
no_license
|
package com.example;
import lombok.Data;
@Data
class Hotel {
private String url;
private String name;
private String description;
private String owner;
}
| true
|
a9478ea7b2e1017135e162b7299a13efee647ee9
|
Java
|
thanesh56/springboot-crud-jpa-oracle-oauth2-demo
|
/src/main/java/com/gl/springbootcrudjpaoracledemo/dao/impl/ClientDaoImpl.java
|
UTF-8
| 939
| 2.265625
| 2
|
[] |
no_license
|
package com.gl.springbootcrudjpaoracledemo.dao.impl;
import com.gl.springbootcrudjpaoracledemo.dao.ClientDao;
import com.gl.springbootcrudjpaoracledemo.model.Client;
import com.gl.springbootcrudjpaoracledemo.repository.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class ClientDaoImpl implements ClientDao {
@Autowired
ClientRepository clientRepository;
@Autowired
PasswordEncoder passwordEncoder;
@Override
public void saveClient(Client client) {
client.setPassword(passwordEncoder.encode(client.getPassword()));
clientRepository.save(client);
}
@Override
public Optional<Client> getClientByName(String clientName) {
return clientRepository.findByUsername(clientName);
}
}
| true
|
e9ade7aa1443d2534a8a48c3ffc232e94b1cfb5c
|
Java
|
Gmdeng/gzz
|
/gzz-mybatis/src/main/java/com/gzz/mybatis/action/IndexAction.java
|
UTF-8
| 889
| 2.0625
| 2
|
[] |
no_license
|
package com.gzz.mybatis.action;
import com.gzz.mybatis.pojo.MiMember;
import com.gzz.mybatis.service.MiMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*
*/
@RestController
public class IndexAction {
@Value("${spring.data.user.age}")
private String age;
@Autowired
private MiMemberService memberService;
@RequestMapping("/helloWord")
public String index(String name){
return "Hello Ricky age:" + age + " name:" + name;
}
@RequestMapping("/getMemberInfo")
public Object getMember(String memberNo){
MiMember member = memberService.getMiMember(memberNo);
return member;
}
}
| true
|
3b9b1c805f1d69c4317543bdc2b724b96bad2607
|
Java
|
javers/javers
|
/javers-core/src/main/java/org/javers/java8support/LocalDateTimeTypeAdapter.java
|
UTF-8
| 714
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.javers.java8support;
import org.javers.core.json.BasicStringTypeAdapter;
import org.javers.core.json.typeadapter.util.UtilTypeCoreAdapters;
import java.time.LocalDateTime;
/**
* @author bartosz.walacik
*/
class LocalDateTimeTypeAdapter extends BasicStringTypeAdapter<LocalDateTime> {
@Override
public String serialize(LocalDateTime sourceValue) {
return UtilTypeCoreAdapters.serialize(sourceValue);
}
@Override
public LocalDateTime deserialize(String serializedValue) {
return LocalDateTime.from(UtilTypeCoreAdapters.deserializeLocalDateTime(serializedValue));
}
@Override
public Class getValueType() {
return LocalDateTime.class;
}
}
| true
|
b322d2aee0f8869eda9508cf32e361e4273609b0
|
Java
|
anna-chepiga/GoJavaEnterprise
|
/module5.1/src/main/java/ua/goit/lib/operations/OperationSquareRoot.java
|
UTF-8
| 161
| 1.640625
| 2
|
[] |
no_license
|
package ua.goit.lib.operations;
public interface OperationSquareRoot extends Operation {
String operationSymbol = "sqrt";
int correctInputLength = 2;
}
| true
|
88574cacde6ca175d2b3a5704de8e5aae1b2ed4d
|
Java
|
jmotionsoft/weplace
|
/api-server/src/main/java/towntalk/controller/BoardController.java
|
UTF-8
| 1,150
| 2.1875
| 2
|
[] |
no_license
|
package towntalk.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import towntalk.model.Board;
import towntalk.model.Group;
import towntalk.service.BoardService;
import towntalk.util.HttpReturn;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dooseon on 2016. 6. 6..
*/
@RestController
public class BoardController {
static final Logger logger = LoggerFactory.getLogger(BoardController.class);
@Autowired
private BoardService boardService;
@RequestMapping("/board")
public ResponseEntity<?> getBoardList(){
List<Group> groupList = boardService.getGroupList();
List<Board> boardList = boardService.getBoardList();
Map resultMap = new LinkedHashMap();
resultMap.put("groupList", groupList);
resultMap.put("boardList", boardList);
return HttpReturn.OK(resultMap);
}
}
| true
|
70ae4e7585b80a58ebabba3985b50af28cfe85dc
|
Java
|
amulyack/employeeManagement
|
/src/main/java/com/mindtree/controller/EmployeeManagementController.java
|
UTF-8
| 2,748
| 2.296875
| 2
|
[] |
no_license
|
package com.mindtree.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mindtree.entity.Employee;
import com.mindtree.exceptions.InvalidRequestException;
import com.mindtree.service.EmployeeManagementService;
@RestController
public class EmployeeManagementController {
@Autowired
private EmployeeManagementService service;
@RequestMapping("/EmpMgt")
public ResponseEntity<String> startPage() {
return new ResponseEntity<String>("Welcome to Employee Management", HttpStatus.OK);
}
@RequestMapping(value = "/EmpMgt/addEmp", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDetail> addEmployee(@RequestBody Employee employee) throws Exception {
ResponseDetail response = service.addEmployee(employee);
return new ResponseEntity<ResponseDetail>(response, HttpStatus.OK);
}
@RequestMapping(value = "/EmpMgt/deleteEmp/{empId}", method = RequestMethod.DELETE)
public ResponseEntity<ResponseDetail> deleteEmployee(@PathVariable String empId) throws Exception {
ResponseDetail response = service.deleteEmployee(empId);
return new ResponseEntity<ResponseDetail>(response, HttpStatus.OK);
}
@RequestMapping(value = "/EmpMgt/getAllEmpDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDetail> getAllEmployees() {
ResponseDetail response = service.getAllEmployees();
return new ResponseEntity<ResponseDetail>(response, HttpStatus.OK);
}
@RequestMapping(value = "/EmpMgt/getByEmpId/{empId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDetail> getEmployee(@PathVariable String empId) {
ResponseDetail response = service.getEmployee(empId);
return new ResponseEntity<ResponseDetail>(response, HttpStatus.OK);
}
@RequestMapping(value = "/EmpMgt/checkLogin", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDetail> checkLogin(@RequestBody LoginDetails loginDetails) {
ResponseDetail response = service.authenticateUser(loginDetails.getUsername(), loginDetails.getPassword());
return new ResponseEntity<ResponseDetail>(response, HttpStatus.OK);
}
}
| true
|
31bc610c7ffa9f7a258bf32d80b810b91671393e
|
Java
|
spektion/segooro
|
/src/segooro/Tsveiculo.java
|
UTF-8
| 690
| 2.609375
| 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 segooro;
import java.io.Serializable;
/**
*
* @author a
*/
public class Tsveiculo extends Seguro implements Serializable{ //Declaração de class
private boolean acidentes=false; //Já teve acidentes?
private tveiculo veiculo; //Tipo de veiculo
public Tsveiculo(double p,tveiculo v, boolean a){ //Construtor
super(p,tseguro.Veiculo); //Construtor da superclass
this.veiculo=v; //Tipo de veiculo
this.acidentes=a; //Já teve acidentes
}
}
| true
|
f0bb4c5a14d721e27683e945d489c9daadb27623
|
Java
|
Blackdogman/jwxt
|
/src/main/java/com/jwxt/controller/ydj/YdjLoginController.java
|
UTF-8
| 3,927
| 2.171875
| 2
|
[] |
no_license
|
package com.jwxt.controller.ydj;
import com.jwxt.model.ydj.YdjClassInfo;
import com.jwxt.model.ydj.YdjStudent;
import com.jwxt.model.ydj.YdjUser;
import com.jwxt.service.ydj.YdjClassInfoService;
import com.jwxt.service.ydj.YdjStudentService;
import com.jwxt.service.ydj.YdjUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/loginControllerNAAAAAAAAAA")
public class YdjLoginController {
/** */
@Autowired
private YdjUserService userService;
// @Autowired
// private YdjMenuService menuService;
@Autowired
private YdjStudentService studentService;
@Autowired
private YdjClassInfoService classInfoService;
@RequestMapping("/login.do")
public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model,
YdjUser user) {
// 1.收集数据
// 3.调用相关业务
System.out.println("前台传入" + user);
YdjUser u = userService.queryUserByLogiNameAndPassword(user);
System.out.println("+++////++++////+++/////++" + u);
if (u != null) {
model.addAttribute("loginSuccess", "登录成功");
session.setAttribute("USER", u);
YdjStudent s = studentService.queryStudentByuserLoginName(user.getUserLoginName());
String id = s.getStudentId();
System.out.println("学生表中的班级ID:" + s);
session.setAttribute("STUDENTid", id);
session.setAttribute("CLASSID", s);
YdjClassInfo c = classInfoService.queryClassById(s.getStudentClassId());
// YdjClassInfo c = classInfoService.queryClassById(s.getStudentClassId());
System.out.println("班级表中的班级名字:" + c);
model.addAttribute("classId", "所属班级");
session.setAttribute("CLA", c);
///////////////////
// List<Menu> menuSelectedList = menuService.queryAllMenuXZByUserId(u.getUserId());
// model.addAttribute("menuSelectedList", menuSelectedList);
// for (Menu menu2 : menuSelectedList) {
// System.out.println("+++++++++++++++++++++++" + menu2);
// }
////////////////////
return "view/frame/main";
} else {
model.addAttribute("loginError", "用户名或密码错误");
// 2.跳转页面
return "view/frame/login";
}
}
// @RequestMapping("/queryAnthortySon.do")
// public String queryAnthortySon(HttpServletRequest request, HttpServletResponse response, HttpSession session,
// Model model, YdjUser user, Menu menu, String menuId) {
// YdjUser u = (YdjUser) session.getAttribute("USER");
// // 把用户信息保存到session
// session.setAttribute("USER", u);
// if (u != null) {
// model.addAttribute("loginSuccess", "登录成功!");
//
// List<Menu> menuSelectedListSon = menuService.queryMenuSelectedSonByMenuId(menuId);
// for (Menu menu2 : menuSelectedListSon) {
// System.out.println("===========================-----" + menu2);
// }
// model.addAttribute("menuSelectedListSon", menuSelectedListSon);
//
// ////////////////////
// List<Menu> menuSelectedList = menuService.queryAllMenuXZByUserId(u.getUserId());
// model.addAttribute("menuSelectedList", menuSelectedList);
// ////////////////////
//
// return "frame/main";
// } else {
// model.addAttribute("loginError", "用户名或密码错误,请重新输入!");
// return "main/login";
// }
//
// }
}
| true
|
3cb3ee5dc6323d4c3647c7037d0f1520c5e717f3
|
Java
|
kimtc/SO
|
/so-virtualobject/src/main/java/com/pineone/icbms/so/virtualobject/DefaultVirtualObject.java
|
UTF-8
| 647
| 2.5625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
package com.pineone.icbms.so.virtualobject;
/**
* Virtual Object default class.<BR/>
* Created by uni4love on 2016. 11. 16..
*/
public class DefaultVirtualObject extends AGenericVirtualObject {
/**
* constructor
*/
public DefaultVirtualObject() {
}
/**
* constructor<BR/>
*
* @param id id
* @param name name
*/
public DefaultVirtualObject(String id, String name) {
super(id, name);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[").append(super.toString()).append("]");
return sb.toString();
}
}
| true
|
10bf08335bdee363fa15a2c1df3ade35e2ec6f15
|
Java
|
moussacamara7/TESTPARSER
|
/src/parser/parserTerrain/ParserGare.java
|
UTF-8
| 1,006
| 2.921875
| 3
|
[] |
no_license
|
package parser.parserTerrain;
import application.ui.UIPlateau;
import exception.ParserManquantException;
import parser.Parser;
import terrain.Gare;
public class ParserGare extends Parser {
/**
* Constructeur permettant de parser suivant
* @param suivant parser suivant
*/
public ParserGare(Parser suivant) {
super(suivant);
}
/**
* Methode permettant de traiter la ligne
* @param values la ligne a traiter
* @param plateau le plateau
* @throws ParserManquantException en cas de parser manquant
*/
@Override
public void parser(String[] values, UIPlateau plateau) throws ParserManquantException {
Gare T = new Gare(Integer.parseInt(values[0]), values[2], 400);
plateau.ajouterCasesP(T);
}
/**
* @param values la ligne a segmenter
* @return vrai si la ligne peut etre parser
*/
@Override
public boolean saitParser(String[] values) {
return values[1].matches("GARE");
}
}
| true
|
6a0f30f4e9e4671b32917acf20cc951250be2474
|
Java
|
Shantanu28/EventManager
|
/src/main/java/com/cultur/eventmanager/services/EventManagerService.java
|
UTF-8
| 434
| 1.820313
| 2
|
[] |
no_license
|
package com.cultur.eventmanager.services;
import com.cultur.eventmanager.dtos.request.EventPublishRequest;
import com.cultur.eventmanager.dtos.response.EventPublishResponse;
import org.springframework.stereotype.Service;
/**
* Created by shantanu on 29/4/17.
*/
@Service
public class EventManagerService {
public EventPublishResponse startBackgroundJob(EventPublishRequest eventPublishRequest) {
return null;
}
}
| true
|
01a8679314fb39167735af506eda642078820400
|
Java
|
edu-go/java-bootcamp
|
/TopicFINALPROJECT/src/main/java/com/bootcamp/shoppingcart/service/ShoppingCartRepository.java
|
UTF-8
| 308
| 1.578125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.bootcamp.shoppingcart.service;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.bootcamp.shoppingcart.entity.ShoppingCart;
@Repository
public interface ShoppingCartRepository extends CrudRepository<ShoppingCart, Long>{
}
| true
|
8358a00151a511b912db1bb0e939b3ba898e2d82
|
Java
|
782231139/uyun
|
/app/src/main/java/com/uyun/hummer/fragment/ContactsFragment.java
|
UTF-8
| 6,116
| 1.734375
| 2
|
[] |
no_license
|
package com.uyun.hummer.fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.uyun.hummer.MainActivity;
import com.uyun.hummer.R;
import com.uyun.hummer.base.fragment.BaseFragment;
import com.uyun.hummer.httputils.CookieManager;
import com.uyun.hummer.javaScriptInterface.AllJavaScriptInterface;
import com.uyun.hummer.model.bean.UserBean;
import com.uyun.hummer.utils.SystemUtils;
import com.uyun.hummer.utils.WebViewUtils;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
/**
* Created by Liyun on 2017/3/15.
*/
public class ContactsFragment extends BaseFragment {
private String url = null;
private static String CONTACTS = "#/contacts/home";
private boolean isViewCreated;
private boolean isLoad= false;
//private int isCollect = 1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//if (getUserVisibleHint()) {
//loadWebView();
//}
//getRefreshLayout().setOnRefreshListener(this);
EventBus.getDefault().register(this);
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void initWebview(Context context){
loadWebView();
isViewCreated = true;
Log.i("ttt", "Webview------- LabelFragment");
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void refreshCookiesForView(UserBean bean){
Log.i("ttt","refreshCookiesForView ContactsFragment");
CookieManager.getInstance(getActivity()).syncCookie(url);
getWebView().loadUrl(url);
}
@Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getDefault().unregister(this);
if(getWebView()!=null){
WebViewUtils.destroy(getWebView());
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isViewCreated ) {
Log.i("ttt", "setUserVisibleHint------------------------------getLabelData()");
loadWebView();
isViewCreated = true;
}
}
@Override
public void onResume() {
super.onResume();
CookieManager.getInstance(getActivity()).syncCookie(url);
}
public void loadWebView(){
//if(getUserVisibleHint()) {
getWebView().addJavascriptInterface(new AllJavaScriptInterface(getActivity(),null), "Android");
//CustomPrograssDialog.getInstance().createLoadingDialog(getActivity(),getString(R.string.loading)).show();
url = SystemUtils.getUrlWithName(CONTACTS, realHost);
if(isLoad){
getWebView().reload();
}else {
//getWebView().loadUrl(url);
getWebView().loadUrl(url);
isLoad = true;
}
setText(getString(R.string.collect));
getWebView().setWebViewClient(new WebViewClient() {
/*@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
view.clearHistory();
}*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//CustomPrograssDialog.getInstance().disMissDialog();
String cookies = android.webkit.CookieManager.getInstance().getCookie(url);
Log.i("yunli","onPageFinished cookies = " + cookies);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
WebResourceResponse response = WebViewUtils.getInstance(getContext()).shouldOverrideInterceptRequest(mFileUtilsMethod,view, request.getUrl().toString());
if (response != null) {
return response;
} else {
return super.shouldInterceptRequest(view, request);
}
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
WebResourceResponse response = WebViewUtils.getInstance(getContext()).shouldOverrideInterceptRequest(mFileUtilsMethod,view, url);
if (response != null) {
return response;
} else {
return super.shouldInterceptRequest(view, url);
}
}
});
//}
}
public class JsInteration {
@JavascriptInterface
public void changeMsgpage(final String url){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
((MainActivity) getActivity()).changeMsgpage();
Log.d("showToast", "changeMsgpage--------"+url);
//getWebView().loadUrl("javascript:contactsGetChatInfo('" + url + "')");
EventBus.getDefault().post(url);
}
});
}
}
}
| true
|
f802bb7ea34ccff28f5a4b9db5ce3f9b2c61a0e9
|
Java
|
hexi007/JVM
|
/src/classloader/ClassModifier.java
|
UTF-8
| 2,596
| 3.109375
| 3
|
[] |
no_license
|
package classloader;
/**
* @author 27771
* @description 将java.lang.System替换为我们自己定义的HackSystem类,暂时只提供修改常量池的功能
* @create 2020-10-12 21:06
**/
public class ClassModifier {
/**
* CONSTANT_POOL_COUNT_INDEX Class: 文件中常量池的起始偏移,8个字节
*/
private static final int CONSTANT_POOL_COUNT_INDEX = 8;
/**
* CONSTANT_Utf8_info: 常量的tag标志
*/
private static final int CONSTANT_UTF8_INFO = 1;
/**
* CONSTANT_ITEM_LENGTH: 常量池11种变量所占长度,CONSTANT_UTF8_INFO除外,因为它不定长
*/
private static final int[] CONSTANT_ITEM_LENGTH = {-1, -1, -1, 5, 5, 9, 9 , 3, 3 ,5, 5, 5 ,5};
/**
* U1表示占一个字节,U1表示占两个字节
*/
private static final int U1 = 1;
private static final int U2 = 2;
/**
* classByte: 字节数组
*/
private byte[] classByte;
public ClassModifier(byte[] classByte) {
this.classByte = classByte;
}
/**
* @Description 修改常量池中CONSTANT_UTF8_INFO常量的内容
* @Param oldString 修改前的字符串
* @Param newString 修改后的字符串
* @return 修改结果
*/
public byte[] modifyUTF8Constant (String oldStr, String newStr){
int cpc = getConstantPoolCount();
int offset = CONSTANT_POOL_COUNT_INDEX + U2;
for(int i = 0; i < cpc; i++){
int tag = ByteUtils.bytes2Int(classByte, offset , U1);
if(tag == CONSTANT_UTF8_INFO) {
int len = ByteUtils.bytes2Int(classByte, offset + U1 , U2);
offset += (U1 + U2);
String str = ByteUtils.bytes2String(classByte, offset, len);
if(str.equalsIgnoreCase(oldStr)){
byte[] strBytes = ByteUtils.string2Bytes(newStr);
byte[] strLen = ByteUtils.int2Bytes(newStr.length(), U2);
classByte = ByteUtils.bytesReplace(classByte, offset - U2, U2, strLen);
classByte = ByteUtils.bytesReplace(classByte, offset, len, strBytes);
return classByte;
} else {
offset += len;
}
} else {
offset += CONSTANT_ITEM_LENGTH[tag];
}
}
return classByte;
}
/**
* 获取常量池中常量的数量
* @return 常量池数量
*/
private int getConstantPoolCount() {
return ByteUtils.bytes2Int(classByte, CONSTANT_POOL_COUNT_INDEX, U2);
}
}
| true
|
d1ef90e5979519744ef8ce89c1c7e1772b792f78
|
Java
|
github4n/cloud
|
/aggregation/smart-home/src/main/java/com/iot/widget/exception/UserWidgetExceptionEnum.java
|
UTF-8
| 1,554
| 2.328125
| 2
|
[] |
no_license
|
package com.iot.widget.exception;
import com.iot.common.exception.IBusinessException;
/**
* 项目名称: IOT云平台
* 模块名称:
* 功能描述:
* 创建人: yuChangXing
* 创建时间: 2019/1/7 10:51
* 修改人:
* 修改时间:
*/
public enum UserWidgetExceptionEnum implements IBusinessException {
// ***** 设备相关
// 设备离线
DEVICE_OFFLINE(10101, "DEVICE_OFFLINE"),
// 设备开关状态为 关
DEVICE_TURNED_OFF(10102, "DEVICE_TURNED_OFF"),
DEVICE_NOT_FOUND(10103, "DEVICE_NOT_FOUND"),
// ***** scene
SCENE_NOT_FOUND(10201, "SCENE_NOT_FOUND"),
// scene内容为空
SCENE_EMPTY(10202, "SCENE_EMPTY"),
// ***** 安防
UNBOUND_GATEWAY(10301, "UNBOUND_GATEWAY"),
// ***** 其它
// 不支持 协议/参数
NOT_SUPPORTED(30601, "NOT_SUPPORTED"),
// 参数错误
PARAMETER_ERROR(30602, "PARAMETER_ERROR"),
// request timeout.
TIMEOUT(30603, "TIMEOUT"),
// 内部报错
INTERNAL_ERROR(30604, "INTERNAL_ERROR"),
// 未知错误
UN_KNOWN_ERROR(30615, "UN_KNOWN_ERROR");
private int code;
private String messageKey;
UserWidgetExceptionEnum(String messageKey) {
this.code = 400;
this.messageKey = messageKey;
}
UserWidgetExceptionEnum(int code, String messageKey) {
this.code = code;
this.messageKey = messageKey;
}
@Override
public int getCode() {
return code;
}
@Override
public String getMessageKey() {
return messageKey;
}
}
| true
|
301cb758eb896d191662d97951c4220d01fb0a60
|
Java
|
thisisbaozi/reaver
|
/src/main/java/io/messaginglabs/reaver/com/LocalServer.java
|
UTF-8
| 1,663
| 2.453125
| 2
|
[] |
no_license
|
package io.messaginglabs.reaver.com;
import io.messaginglabs.reaver.com.msg.Message;
import io.netty.util.AbstractReferenceCounted;
import io.netty.util.ReferenceCounted;
import java.util.Objects;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
public class LocalServer extends AbstractReferenceCounted implements Server {
private final Consumer<Message> consumer;
private final long localId;
private final String address;
public LocalServer(long localId, String address, Consumer<Message> consumer) {
this.consumer = consumer;
this.localId = localId;
this.address = address;
}
@Override
public void send(Message msg) {
if (consumer != null) {
consumer.accept(msg);
}
}
@Override
public void send(Message msg, long timeout) throws TimeoutException, InterruptedException {
send(msg);
}
@Override
public boolean connect(long timeout) throws InterruptedException {
return true;
}
@Override
public String address() {
return address;
}
@Override
public long nodeId() {
return localId;
}
@Override
public void connect() {
// do nothing
}
@Override
public void areYouOk() {
// do nothing
}
@Override
public boolean isActive() {
return true;
}
@Override
protected void deallocate() {
// do nothing
}
@Override
public ReferenceCounted touch(Object hint) {
return this;
}
@Override
public void close() throws Exception {
// do nothing
}
}
| true
|
bddd0d9d7964a0332e8d41415567180ab99bb734
|
Java
|
i3mainz/kiwi-postgis
|
/src/org/openrdf/query/algebra/evaluation/function/postgis/geometry/exporter/AsX3D.java
|
UTF-8
| 1,420
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.openrdf.query.algebra.evaluation.function.postgis.geometry.exporter;
import org.openrdf.model.vocabulary.POSTGIS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.openrdf.query.algebra.evaluation.function.postgis.geometry.base.GeometricStringExportFunction;
public class AsX3D extends GeometricStringExportFunction {
@Override
public String operation(Geometry geom) {
StringBuilder builder=new StringBuilder();
builder.append("<IndexedFaceSet coordIndex=\"");
Integer index=0;
for(Coordinate coord:geom.getCoordinates()) {
builder.append(index.toString());
index++;
}
builder.append("</IndexedFaceSet>");
builder.append("<Coordinate point=\"");
for(Coordinate coord:geom.getCoordinates()) {
builder.append(coord.getX()+" "+coord.getY()+" "+coord.getZ()+" ");
}
builder.append("\"/>");
return header+builder.toString()+footer;
}
String header="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.2//EN\""+
"http://www.web3d.org/specifications/x3d-3.2.dtd\"><Scene><Shape>";
String footer="</Shape></Scene></X3D>";
@Override
public String getURI() {
// TODO Auto-generated method stub
return POSTGIS.ST_ASX3D.stringValue();
}
}
| true
|
7ddd068f5f2009a986db553b60683b42e4d3cbb1
|
Java
|
hungwen0425/cloudmall
|
/cloudmall-order/src/main/java/com/hungwen/cloudmall/order/service/PaymentInfoService.java
|
UTF-8
| 460
| 1.640625
| 2
|
[] |
no_license
|
package com.hungwen.cloudmall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hungwen.common.utils.PageUtils;
import com.hungwen.cloudmall.order.entity.PaymentInfoEntity;
import java.util.Map;
/**
* 支付資料表
*
* @author Hungwen Tseng
* @email hungwen.tseng@gmail.com
* @date 2020-08-25 14:57:51
*/
public interface PaymentInfoService extends IService<PaymentInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| true
|
51900bdeaae442f0d7b7a1ff6455e3e986b9024f
|
Java
|
aguilaj10/ProEscRec
|
/proescrec-model/target/generated-sources/annotations/com/jsm/proescrec/model/CatTipoEstructura_.java
|
UTF-8
| 724
| 1.515625
| 2
|
[] |
no_license
|
package com.jsm.proescrec.model;
import com.jsm.proescrec.model.EstructuraPlanteles;
import javax.annotation.Generated;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-11-20T13:52:21")
@StaticMetamodel(CatTipoEstructura.class)
public class CatTipoEstructura_ {
public static volatile ListAttribute<CatTipoEstructura, EstructuraPlanteles> estructuraPlantelesList;
public static volatile SingularAttribute<CatTipoEstructura, String> tipoEstructura;
public static volatile SingularAttribute<CatTipoEstructura, Integer> cveTipoEstructura;
}
| true
|
c6f3aef9be74a5b1d72240cf796408033c4b4074
|
Java
|
SandeepAshmar/MonetFirstVersion
|
/app/src/main/java/com/monet_android/modle/register/RegisterResponse.java
|
UTF-8
| 2,527
| 2.125
| 2
|
[] |
no_license
|
package com.monet_android.modle.register;
public class RegisterResponse {
private String user_gender;
private String user_country;
private String user_lname;
private String user_phone;
private String api_token;
private String user_password;
private String user_id;
private String user_email;
private String user_dob;
private String user_fname;
public String getUser_gender ()
{
return user_gender;
}
public void setUser_gender (String user_gender)
{
this.user_gender = user_gender;
}
public String getUser_country ()
{
return user_country;
}
public void setUser_country (String user_country)
{
this.user_country = user_country;
}
public String getUser_lname ()
{
return user_lname;
}
public void setUser_lname (String user_lname)
{
this.user_lname = user_lname;
}
public String getUser_phone ()
{
return user_phone;
}
public void setUser_phone (String user_phone)
{
this.user_phone = user_phone;
}
public String getApi_token ()
{
return api_token;
}
public void setApi_token (String api_token)
{
this.api_token = api_token;
}
public String getUser_password ()
{
return user_password;
}
public void setUser_password (String user_password)
{
this.user_password = user_password;
}
public String getUser_id ()
{
return user_id;
}
public void setUser_id (String user_id)
{
this.user_id = user_id;
}
public String getUser_email ()
{
return user_email;
}
public void setUser_email (String user_email)
{
this.user_email = user_email;
}
public String getUser_dob ()
{
return user_dob;
}
public void setUser_dob (String user_dob)
{
this.user_dob = user_dob;
}
public String getUser_fname ()
{
return user_fname;
}
public void setUser_fname (String user_fname)
{
this.user_fname = user_fname;
}
@Override
public String toString()
{
return "ClassPojo [user_gender = "+user_gender+", user_country = "+user_country+", user_lname = "+user_lname+", user_phone = "+user_phone+", api_token = "+api_token+", user_password = "+user_password+", user_id = "+user_id+", user_email = "+user_email+", user_dob = "+user_dob+", user_fname = "+user_fname+"]";
}
}
| true
|
7cebe947af886c5a5d63a46fb43baba0f93a8155
|
Java
|
Intrinsarc/intrinsarc-evolve
|
/Jazz-1.3/edu/umd/cs/jazz/event/ZSelectionResizeHandler.java
|
UTF-8
| 46,159
| 2.59375
| 3
|
[] |
no_license
|
package edu.umd.cs.jazz.event;
/**
* Copyright (C) 1998-2000 by University of Maryland, College Park, MD 20742, USA
* All rights reserved.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.io.*;
import javax.swing.event.*;
import edu.umd.cs.jazz.*;
import edu.umd.cs.jazz.util.*;
import edu.umd.cs.jazz.component.ZRectangle;
/**
* <b>ZSelectionResizeHandler</b> is a selection handler for use with
* <b>ZSelectionManager</b>. <code>ZSelectionResizeHandler</code> renders
* resize "handles" over the current selection, and allows the user to
* resize the selection by dragging these handles.
* <P>
* Resizing works as expected from drawing applications such as PowerPoint.
* Dragging a resize handle allows for unconstrained scaling while shift-drag
* allows constrained proportion scaling.
* <P>
* <b>Warning:</b> Serialized and ZSerialized objects of this class will not be
* compatible with future Jazz releases. The current serialization support is
* appropriate for short term storage or RMI between applications running the
* same version of Jazz. A future release of Jazz will provide support for long
* term persistence.
*
* @see ZSelectionManager
* @see ZSelectionModifyHandler
* @see ZSelectionMoveHandler
* @see ZSelectionDeleteHandler
* @see ZSelectionScaleHandler
* @author Antony Courtney, Yale University
* @author Lance Good, University of Maryland
* @author Benjamin Bederson, University of Maryland
*/
public class ZSelectionResizeHandler implements ZEventHandler, ZGroupListener, Serializable {
/** The default highlight color */
private static final Color DEFAULT_HIGHLIGHT_COLOR = Color.red.darker();
/** The resize handle size */
protected static double RESIZE_HANDLE_SIZE = 6.0;
/** true when event handler is active */
private boolean active = false;
/** rrue if this event handler is globally active rather than per-camera */
private boolean globallyActive = false;
/** node this event handler attaches to */
private ZNode node = null;
/** The active camera if this is a per-camera event handler */
private ZCamera activeCamera = null;
/** camera found in latest interaction */
private ZCamera interactionCamera = null;
/** highlight color for highlighted nodes */
private Color highLightColor = DEFAULT_HIGHLIGHT_COLOR;
/** active resize handles. Maps from ZNode -> ResizeHandle */
protected transient HashMap activeHandles;
/** registered event listeners */
protected transient EventListenerList listenerList;
/** the current resizer - handles the actual resizing */
private ResizeListener defaultResizeListener;
private int allButton1ButShiftMask = (MouseEvent.BUTTON1_MASK |
MouseEvent.ALT_GRAPH_MASK |
MouseEvent.CTRL_MASK);
/**
* Interface that a class must implement to handle the resizing
* of the selected nodes for a given ZSelectionResizeHandler.
* A default resizer is provided by ZSelectionResizeHandler so
* applications need not implement their own for the default behavior.
*
* @see ZSelectionResizeHandler.ResizeEvent
*/
public interface ResizeListener extends EventListener {
/**
* Fired when a node is resized by the current resize handler
* @param re The resize event for the current resize
*/
public void nodeResized(ResizeEvent re);
/**
* Signals the end of a resize for a group of nodes
*/
public void resizeComplete();
}
/**
* An event to signal that a node has been resized by this event handler.
* This event provides several scale values to allow for various resizing
* behaviors other than the default.
* <p>
* The boolean value <code>constrained</code> signals that this resize
* was considered constrained by the default standard, namely that the
* shift key was depressed during the resize.
* <p>
* The values returned by <code>getScaleX</code> and <code>getScaleY<code>
* represent the default scale values based on the value of
* <code>constrained</code>. The constrained values are provided by
* the <code>getConstrainScaleX</code> and <code>getConstrainScaleY<code>.
* <p>
* The scale values for no flip scaling are also provided. The term
* "no flip" does not indicate that the values will always be positive
* but rather indicates that the point from which the scale is computed
* remains constant. For example, if the bottom right resize handle is
* grabbed, the new size will always be computed from the upper right
* hand corner. In the previous case (ie. when flipping is employed) when
* the scale becomes negative, it is necessary to change the point from
* which the new width is computed. This is necessary for resizing in
* which flipping occurs because of the representation of rectangles.
* Rectangles can not have negative width or height, hence when the
* object's scale becomes negative the point from which the new width
* or height is computed must change, eg. from the x point to the
* x point plus the width.
*/
public static class ResizeEvent {
/**
* The resized node
*/
ZNode node;
/**
* The mouse event that caused the resize
*/
ZMouseEvent mouseEvent;
/**
* The default X scale
*/
double xScale;
/**
* The default Y scale
*/
double yScale;
/**
* The alternate X scale - eg. a constrained scale if the default
* scale was unconstrained
*/
double constrainXScale;
/**
* The alternate Y scale - eg. a constrained scale if the default
* scale was unconstrained
*/
double constrainYScale;
/**
* The default X scale in which the point from which the scale is
* computed doesn't change
*/
double noFlipXScale;
/**
* The default Y scale in which the point from which the scale is
* computed doesn't change
*/
double noFlipYScale;
/**
* The alternate X scale in which the point from which the scale is
* computed doesn't change
*/
double constrainNoFlipXScale;
/**
* The alternate Y scale in which the point from which the scale is
* computed doesn't change
*/
double constrainNoFlipYScale;
/**
* The X coordinate around which the resizing occurs
*/
double x;
/**
* The Y coordinate around which the resizing occurs
*/
double y;
/**
* @param node The node that is being resized
* @param mouseEvent The mouse event that caused the resize
* @param xScale The percentage of the current width
* @param yScale The percentage of the current height
* @param constrainXScale The constrained x scale percentage
* @param constrainYScale The constrained y scale percentage
* @param noFlipXScale The non-flipping x scale percentage
* @param noFlipYScale The non-flipping y scale percentage
* @param constrainNoFlipXScale The constrained non-flip x scale
* @param constrainNoFlipYScale The constrained non-flip y scale
* @param x The x point around which resizing occurs
* @param y The y point around which resizing occurs
*/
public ResizeEvent(ZNode node, ZMouseEvent mouseEvent,
double xScale, double yScale,
double constrainXScale, double constrainYScale,
double noFlipXScale, double noFlipYScale,
double constrainNoFlipXScale, double constrainNoFlipYScale,
double x, double y) {
this.node = node;
this.mouseEvent = mouseEvent;
this.xScale = xScale;
this.yScale = yScale;
this.constrainXScale = constrainXScale;
this.constrainYScale = constrainYScale;
this.noFlipXScale = noFlipXScale;
this.noFlipYScale = noFlipYScale;
this.constrainNoFlipXScale = constrainNoFlipXScale;
this.constrainNoFlipYScale = constrainNoFlipYScale;
this.x = x;
this.y = y;
}
/**
* @return The node that was resized
*/
public ZNode getNode() {
return node;
}
/**
* @return The mouse event that cause the resize
*/
public ZMouseEvent getMouseEvent() {
return mouseEvent;
}
/**
* @return The default x scale
*/
public double getScaleX() {
return xScale;
}
/**
* @return The default y scale
*/
public double getScaleY() {
return yScale;
}
/**
* @return The constrained x scale
*/
public double getConstrainScaleX() {
return constrainXScale;
}
/**
* @return The constrained y scale
*/
public double getConstrainScaleY() {
return constrainYScale;
}
/**
* @return The default no-flip x scale
*/
public double getNoFlipScaleX() {
return noFlipXScale;
}
/**
* @return The default no-flip y scale
*/
public double getNoFlipScaleY() {
return noFlipYScale;
}
/**
* @return The constrained no-flip x scale
*/
public double getNoFlipConstrainScaleX() {
return constrainNoFlipXScale;
}
/**
* @return The constrained no-flip y scale
*/
public double getNoFlipConstrainScaleY() {
return constrainNoFlipYScale;
}
/**
* @return The x coordinate around which the object is resized
*/
public double getX() {
return x;
}
/**
* @return The y coordinate around which the object is resized
*/
public double getY() {
return y;
}
}
/**
* Inner class used to render resize handles over a single component.
* <P>
* Terminology: A "compass position" is a pair of integers (x,y) drawn
* from the set {-1,0,1} that identifies a particular resize handle
* relative to a 3x3 square whose origin is the center.
* The upper-left resize handle is identified as (-1,-1), upper-right
* as (1,-1), etc.
*/
protected class ResizeHandles extends ZVisualComponent implements ZMouseListener, ZMouseMotionListener {
/** Default pen color */
public final Color penColor_DEFAULT = ZSelectionGroup.penColor_DEFAULT;
// The set of PROTECTED variables which might be generally useful
/** Pen color for rendering of selection */
protected Color penColor = penColor_DEFAULT;
/** actual rectangles rendered for the handles */
protected Rectangle2D[] handles = null;
/** location of most recent mouse press on a resize handle,
* in global coordinates. */
protected Point2D pressPt;
/** the node that was pressed */
protected ZNode pressNode = null;
/** relative compass location of resize handle of last press */
protected Point pressHandle;
/** the handle to highlight */
protected Point highLightHandle;
/** location of most recent drag, in global coordinates */
protected Point2D dragPt;
/** The current selected list */
protected ArrayList selection = null;
// The set of PRIVATE variables which are more dependent on this
// particular implementation
/** have we rendered the handles yet? */
private boolean rendered = false;
/** The width of the selected object at mouse press */
private double pressWidth;
/** The height of the selected object at mouse press */
private double pressHeight;
/** The x scale of the selected object at mouse press */
private double pressScaleX;
/** The y scale of the selected object at mouse press */
private double pressScaleY;
/** The x scale of the selected object at previous drag */
private double prevScaleX;
/** The y scale of the selected object at previous drag */
private double prevScaleY;
/** The x constrained scale on the previous drag */
private double prevConstrainScaleX;
/** The y constrained scale on the previous drag */
private double prevConstrainScaleY;
/** The x scale of the selected object at previous drag */
private double prevNoFlipScaleX;
/** The y scale of the selected object at previous drag */
private double prevNoFlipScaleY;
/** The x constrained scale on the previous drag */
private double prevNoFlipConstrainScaleX;
/** The y constrained scale on the previous drag */
private double prevNoFlipConstrainScaleY;
/**
* A list of boolean objects to indicate whether each of
* the selected objects have negative x scale
*/
private ArrayList selectedInverseX = new ArrayList();
/**
* A list of boolean objects to indicate whether each of
* the selected objects have negative y scale
*/
private ArrayList selectedInverseY = new ArrayList();
/** true if we are performing a drag operation */
private boolean dragging = false;
/** A temporary storage point */
private Point2D tmpPoint = new Point2D.Double();
/**
* Default constructor
*/
public ResizeHandles() {
super();
handles = new Rectangle2D[9];
pressPt = new Point2D.Double();
dragPt = new Point2D.Double();
}
/**
* Compute index of resize handle from relative compass position.
*/
private final int mapIndex(int i,int j) {
return (j+1)*3+(i+1);
}
/**
* Compute compass position of resize handle from an index.
*/
private final Point unMapIndex(int index) {
Point cp = new Point((index % 3) - 1,(index / 3) - 1);
return cp;
}
/**
* Indicates a pick in case the underlying visual components
* aren't picked
*/
public boolean pick(Rectangle2D pickRect, ZSceneGraphPath path) {
return contains(pickRect);
}
/**
* Render a single resize handle, centered at the given x,y position.
* @return the newly allocated rectangle that represents the geometry
* of the handle.
*/
protected Rectangle2D getHandle(double cx,
double cy,
double xLen,
double yLen) {
Rectangle2D r = new Rectangle2D.Double(cx - (xLen/2),
cy - (yLen/2),
xLen,
yLen);
return r;
}
/**
* Renders the given ResizeHandles
* @param ctx The current render context
*/
public void render(ZRenderContext ctx) {
Graphics2D g2 = ctx.getGraphics2D();
AffineTransform transform = g2.getTransform();
double xScale = Math.abs(transform.getScaleX());
double yScale = Math.abs(transform.getScaleY());
double xSz = 1.0 / xScale;
double ySz = 1.0 / yScale;
double xLen = RESIZE_HANDLE_SIZE*xSz;
double yLen = RESIZE_HANDLE_SIZE*ySz;
ZNode p = getParents()[0];
if (p instanceof ZSelectionGroup) {
ZSelectionGroup g = (ZSelectionGroup)p;
Rectangle2D r = g.getBounds();
double x = r.getX();
double y = r.getY();
double w = r.getWidth();
double h = r.getHeight();
// don't draw very small selection objects
if (w < 3.0*xLen ||
h < 3.0*yLen) {
rendered = false;
return;
}
double cx = x + (w/2);
double cy = y + (h/2);
w -= xLen + 2*xSz;
h -= yLen + 2*ySz;
g2.setColor(penColor);
Rectangle2D handle;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if ((i != 0) || (j != 0)) {
handle = getHandle(cx+i*(w/2),
cy+j*(h/2),
xLen,
yLen);
if (highLightHandle != null &&
((int)highLightHandle.getX()) == i &&
((int)highLightHandle.getY()) == j) {
g2.setColor(highLightColor);
handles[mapIndex(i,j)] = handle;
g2.fill(handle);
g2.setColor(penColor);
}
else {
handles[mapIndex(i,j)] = handle;
g2.fill(handle);
}
}
}
}
rendered = true;
}
}
/**
* The resize handles don't have logical bounds
*/
protected void computeBounds() {
}
/**
* Used by ZSelectionResizeHandler to determine whether or not
* the mouse is over a resize handle. Tests the given (x,y)
* position to determine if it is over a resize handle. If so,
* sets <code>cp</code> to the compass position of the handle,
* and returns <code>true</code>. Otherwise returns false.
*
* @param x x position, in local coordinates
* @param y y position, in local coordinates
* @return cp out parameter: compass point of handle, if found.
*/
public Point contains(double x,double y) {
if (!rendered) {
return null;
}
for (int i=0; i < 9; i++) {
Rectangle2D r = handles[i];
if (r != null && r.contains(x,y)) {
return unMapIndex(i);
}
}
return null;
}
/**
* Used by ZSelectionResizeHandler to determine whether or not
* the mouse is over a resize handle. Tests the given rectangle
* to determine if it is contained by a resize handle.
*
* @param x x position, in local coordinates
* @param y y position, in local coordinates
* @return True if one of the handles contains the point
*/
public boolean contains(Rectangle2D rect) {
if (!rendered) {
return false;
}
for (int i=0; i < 9; i++) {
Rectangle2D r = handles[i];
if (r != null && r.contains(rect.getX()+rect.getWidth()/2.0,
rect.getY()+rect.getHeight()/2.0)) {
return true;
}
}
return false;
}
/**
* @param bounds The current global bounds of the scaled node
* @param oldPt The press pt from which the old dimensions are computed
* @param newPt The drag pt from which the new dimensions are computed
*/
private void scaleSelection(ZBounds bounds,
Point2D oldPt,
Point2D newPt,
ZMouseEvent mouseEvent) {
Point2D scalePoint = new Point2D.Double();
double scaleX;
double scaleY;
double noFlipScaleX;
double noFlipScaleY;
double baseX;
double baseY;
double noFlipBaseX;
double noFlipBaseY;
double oldWidth, oldHeight;
double newWidth, newHeight;
double oldNoFlipWidth, oldNoFlipHeight;
double newNoFlipWidth, newNoFlipHeight;
double offX, offY;
double noFlipOffX, noFlipOffY;
// ***************************************************
// Compute the base point from which the width and height
// will be computed. This depends on the previous scale
// and the handle pressed.
// Compute the base X
if (pressHandle.getX() >= 0) {
if (prevScaleX >= 0) {
baseX = bounds.getX();
}
else {
baseX = bounds.getX()+bounds.getWidth();
}
noFlipBaseX = bounds.getX();
}
else {
if (prevScaleX >= 0) {
baseX = bounds.getX()+bounds.getWidth();
}
else {
baseX = bounds.getX();
}
noFlipBaseX = bounds.getX()+bounds.getWidth();
}
// Compute the base Y
if (pressHandle.getY() >= 0) {
if (prevScaleY >= 0) {
baseY = bounds.getY();
}
else {
baseY = bounds.getY()+bounds.getHeight();
}
noFlipBaseY = bounds.getY();
}
else {
if (prevScaleY >= 0) {
baseY = bounds.getY()+bounds.getHeight();
}
else {
baseY = bounds.getY();
}
noFlipBaseY = bounds.getY()+bounds.getHeight();
}
// ***************************************************
// ***************************************************
// Now compute the old and new widths and heights to
// later compute X and Y scales
oldWidth = Math.abs(oldPt.getX()-baseX);
oldHeight = Math.abs(oldPt.getY()-baseY);
oldNoFlipWidth = Math.abs(oldPt.getX()-noFlipBaseX);
oldNoFlipHeight = Math.abs(oldPt.getY()-noFlipBaseY);
offX = pressWidth-oldWidth;
offY = pressHeight-oldHeight;
noFlipOffX = pressWidth-oldNoFlipWidth;
noFlipOffY = pressHeight-oldNoFlipHeight;
if (pressHandle.getX() >= 0) {
newWidth = newPt.getX()-baseX;
newNoFlipWidth = newPt.getX()-noFlipBaseX;
}
else {
newWidth = baseX-newPt.getX();
newNoFlipWidth = noFlipBaseX-newPt.getX();
}
if (pressHandle.getY() >= 0) {
newHeight = newPt.getY()-baseY;
newNoFlipHeight = newPt.getY()-noFlipBaseY;
}
else {
newHeight = baseY-newPt.getY();
newNoFlipHeight = noFlipBaseY-newPt.getY();
}
// Adjust the new width based on the pressed offset
// from the handle edge
if (newWidth > 0.0) {
newWidth += offX;
}
else {
newWidth -= offX;
}
// Adjust the new no flip width based on the pressed
// offset from the handle edge
if (newNoFlipWidth > 0.0) {
newNoFlipWidth += noFlipOffX;
}
else {
newNoFlipWidth -= noFlipOffX;
}
// Adjust the new height based on the pressed offset
// from the handle edge
if (newHeight > 0.0) {
newHeight += offY;
}
else {
newHeight -= offY;
}
// Adjust the new no flip height based on the pressed
// offset from the handle edge
if (newNoFlipHeight > 0.0) {
newNoFlipHeight += noFlipOffY;
}
else {
newNoFlipHeight -= noFlipOffY;
}
// ***************************************************
// ***************************************************
// Compute the X and Y scales
// Compute the X scale
if (pressHandle.getX() != 0) {
if (oldWidth == 0.0 || newWidth == 0.0) {
scaleX = 1.0;
}
else {
scaleX = newWidth/pressWidth;
}
if (oldNoFlipWidth == 0.0 || newNoFlipWidth == 0.0) {
noFlipScaleX = 1.0;
}
else {
noFlipScaleX = newNoFlipWidth/pressWidth;
}
}
else {
scaleX = 1.0;
noFlipScaleX = 1.0;
}
// Compute the Y scale
if (pressHandle.getY() != 0) {
if (oldHeight == 0.0 || newHeight == 0.0) {
scaleY = 1.0;
}
else {
scaleY = newHeight/pressHeight;
}
if (oldNoFlipHeight == 0.0 || newNoFlipHeight == 0.0) {
noFlipScaleY = 1.0;
}
else {
noFlipScaleY = newNoFlipHeight/pressHeight;
}
}
else {
scaleY = 1.0;
noFlipScaleY = 1.0;
}
// ***************************************************
// ***************************************************
// Now scale each of the selected nodes around a specific point
double xSign = (scaleX)*Math.abs(scaleX) / Math.pow(scaleX,2);
double ySign = (scaleY)*Math.abs(scaleY) / Math.pow(scaleY,2);
double scale = 1.0;
double noFlipXSign = (noFlipScaleX)*Math.abs(noFlipScaleX) / Math.pow(noFlipScaleX,2);
double noFlipYSign = (noFlipScaleY)*Math.abs(noFlipScaleY) / Math.pow(noFlipScaleY,2);
double noFlipScale = 1.0;
if (pressHandle.getX() != 0 && pressHandle.getY() != 0) {
scale = Math.max(Math.abs(scaleX),Math.abs(scaleY));
noFlipScale = Math.max(Math.abs(noFlipScaleX),Math.abs(noFlipScaleY));
}
else if (pressHandle.getX() == 0) {
scale = Math.abs(scaleY);
noFlipScale = Math.abs(noFlipScaleY);
}
else if (pressHandle.getY() == 0) {
scale = Math.abs(scaleX);
noFlipScale = Math.abs(noFlipScaleX);
}
for (int i=0; i<selection.size(); i++) {
ZNode selNode = (ZNode)selection.get(i);
bounds = selNode.getBounds();
boolean inverseX = ((Boolean)selectedInverseX.get(i)).booleanValue();
boolean inverseY = ((Boolean)selectedInverseY.get(i)).booleanValue();
// First set the x scale coordinate
if (inverseX) {
if (pressHandle.getX() > 0) {
scalePoint.setLocation(bounds.getX()+bounds.getWidth(),
bounds.getY()+bounds.getHeight());
}
else if (pressHandle.getX() == 0) {
scalePoint.setLocation(bounds.getX()+bounds.getWidth()/2.0,
scalePoint.getY());
}
else {
scalePoint.setLocation(bounds.getX(),
scalePoint.getY());
}
}
else {
if (pressHandle.getX() > 0) {
scalePoint.setLocation(bounds.getX(),
scalePoint.getY());
}
else if (pressHandle.getX() == 0) {
scalePoint.setLocation(bounds.getX()+bounds.getWidth()/2.0,
scalePoint.getY());
}
else {
scalePoint.setLocation(bounds.getX()+bounds.getWidth(),
bounds.getY()+bounds.getHeight());
}
}
// Now set the y scale coordinate
if (inverseY) {
if (pressHandle.getY() > 0) {
scalePoint.setLocation(scalePoint.getX(),
bounds.getY()+bounds.getHeight());
}
else if (pressHandle.getY() == 0) {
scalePoint.setLocation(scalePoint.getX(),
bounds.getY()+bounds.getHeight()/2.0);
}
else {
scalePoint.setLocation(scalePoint.getX(),
bounds.getY());
}
}
else {
if (pressHandle.getY() > 0) {
scalePoint.setLocation(scalePoint.getX(),
bounds.getY());
}
else if (pressHandle.getY() == 0) {
scalePoint.setLocation(scalePoint.getX(),
bounds.getY()+bounds.getHeight()/2.0);
}
else {
scalePoint.setLocation(scalePoint.getX(),
bounds.getY()+bounds.getHeight());
}
}
ResizeEvent re = new ResizeEvent(selNode, mouseEvent,
xSign*Math.abs(scaleX)/prevScaleX,
ySign*Math.abs(scaleY)/prevScaleY,
xSign*scale/prevConstrainScaleX,
ySign*scale/prevConstrainScaleY,
noFlipXSign*Math.abs(noFlipScaleX)/prevNoFlipScaleX,
noFlipYSign*Math.abs(noFlipScaleY)/prevNoFlipScaleY,
noFlipXSign*noFlipScale/prevNoFlipConstrainScaleX,
noFlipYSign*noFlipScale/prevNoFlipConstrainScaleY,
scalePoint.getX(),
scalePoint.getY());
fireResizeEvent(re);
}
prevScaleX = scaleX;
prevScaleY = scaleY;
prevConstrainScaleX = xSign*scale;
prevConstrainScaleY = ySign*scale;
prevNoFlipScaleX = noFlipScaleX;
prevNoFlipScaleY = noFlipScaleY;
prevNoFlipConstrainScaleX = noFlipXSign*noFlipScale;
prevNoFlipConstrainScaleY = noFlipYSign*noFlipScale;
}
/**
* Mouse press event handler
* @param <code>e</code> The event.
*/
public void mousePressed(ZMouseEvent e) {
if (((e.getModifiers() & allButton1ButShiftMask) == MouseEvent.BUTTON1_MASK)) {
ZSceneGraphPath path = e.getPath();
if (globallyActive) {
interactionCamera = path.getCamera();
}
else {
interactionCamera = activeCamera;
}
// If the node isn't accessible through the specified camera
// then just return - this means we likely pressed on an
// empty region in an internal camera
Point2D testPt = new Point2D.Double(e.getX(),e.getY());
try {
path.screenToCamera(testPt,interactionCamera);
interactionCamera.cameraToLocal(testPt,path.getNode());
}
catch (ZNodeNotFoundException znnfe) {
return;
}
pressPt.setLocation(e.getX(), e.getY());
path.screenToCamera(pressPt,interactionCamera);
interactionCamera.cameraToLocal(pressPt,null);
pressHandle = contains(testPt.getX(),testPt.getY());
if (pressHandle != null) {
// consume this event so no other handler sees it...
e.consume();
pressNode = path.getNode();
ZBounds pressBounds = pressNode.getGlobalBounds();
pressWidth = pressBounds.getWidth();
pressHeight = pressBounds.getHeight();
AffineTransform globalToLocal = pressNode.getGlobalToLocalTransform();
if (globalToLocal.getScaleX() < 0.0) {
pressHandle.setLocation(-pressHandle.getX(),pressHandle.getY());
}
if (globalToLocal.getScaleY() < 0.0) {
pressHandle.setLocation(pressHandle.getX(),-pressHandle.getY());
}
selection = ZSelectionManager.getSelectedNodes(interactionCamera);
selectedInverseX.clear();
selectedInverseY.clear();
for (int i=0; i<selection.size(); i++) {
ZNode selNode = (ZNode)selection.get(i);
globalToLocal = selNode.getGlobalToLocalTransform();
if (globalToLocal.getScaleX() < 0.0) {
selectedInverseX.add(new Boolean(true));
}
else {
selectedInverseX.add(new Boolean(false));
}
if (globalToLocal.getScaleY() < 0.0) {
selectedInverseY.add(new Boolean(true));
}
else {
selectedInverseY.add(new Boolean(false));
}
}
prevScaleX = 1.0;
prevScaleY = 1.0;
prevConstrainScaleX = 1.0;
prevConstrainScaleY = 1.0;
prevNoFlipScaleX = 1.0;
prevNoFlipScaleY = 1.0;
prevNoFlipConstrainScaleX = 1.0;
prevNoFlipConstrainScaleY = 1.0;
dragging = true;
}
}
}
/**
* Mouse drag event handler
* @param <code>e</code> The event.
*/
public void mouseDragged(ZMouseEvent e) {
if (((e.getModifiers() & allButton1ButShiftMask) == MouseEvent.BUTTON1_MASK) && dragging) { // left button only:
if (interactionCamera != null) {
ZSceneGraphPath path = e.getPath();
dragPt.setLocation(e.getX(), e.getY());
path.screenToCamera(dragPt,interactionCamera);
interactionCamera.cameraToLocal(dragPt,null);
scaleSelection(pressNode.getGlobalBounds(),
pressPt,
dragPt,
e);
// finally: consume the event:
e.consume();
}
}
}
/**
* Mouse release event handler
* @param <code>e</code> The event.
*/
public void mouseReleased(ZMouseEvent e) {
if (((e.getModifiers() & allButton1ButShiftMask) == MouseEvent.BUTTON1_MASK)) {
if (dragging) {
mouseMoved(e);
fireResizeEvent(null);
}
}
dragging = false;
}
/**
* Invoked when the mouse enters a component.
*/
public void mouseEntered(ZMouseEvent e) {
}
/**
* Invoked when the mouse exits a component.
*/
public void mouseExited(ZMouseEvent e) {
if (highLightHandle != null && !dragging) {
highLightHandle = null;
repaint();
}
}
/**
* Invoked when the mouse has been clicked on a component.
*/
public void mouseClicked(ZMouseEvent e) {
}
/**
* Invoked when the mouse button has been moved on a node
* (with no buttons no down).
*/
public void mouseMoved(ZMouseEvent e) {
ZSceneGraphPath path = e.getPath();
ZCamera camera;
if (globallyActive) {
camera = path.getCamera();
}
else {
camera = activeCamera;
}
// If the node isn't accessible through the specified camera
// then just return - this means we likely moused over an
// empty region in an internal camera
Point2D testPt = new Point2D.Double(e.getX(),e.getY());
try {
path.screenToCamera(testPt,camera);
camera.cameraToLocal(testPt,path.getNode());
}
catch (ZNodeNotFoundException znnfe) {
return;
}
Point newHighLightHandle = contains(testPt.getX(),testPt.getY());
if ((highLightHandle == null && newHighLightHandle != null) ||
(highLightHandle != null && newHighLightHandle == null)) {
highLightHandle = newHighLightHandle;
repaint();
}
else if (highLightHandle != null && newHighLightHandle != null &&
(highLightHandle.getX() != newHighLightHandle.getX() ||
highLightHandle.getY() != newHighLightHandle.getY())) {
highLightHandle = newHighLightHandle;
repaint();
}
}
}
/**
* Construct a new ZSelectionResizeHandler which will be active across
* all cameras
* @param node The node to which this handler attaches
*/
public ZSelectionResizeHandler(ZNode node) {
this.node = node;
globallyActive = true;
init();
}
/**
* Construct a new ZSelectionResizeHandler.
* @param node The node to which this handler attaches
* @param camera The camera to which this handler attaches
*/
public ZSelectionResizeHandler(ZNode node, ZCamera camera) {
this.node = node;
this.activeCamera = camera;
init();
}
/**
* Add a ResizeListener, registered for nodeResized events.
* @param l The resize listener to register
*/
public void addResizeListener(ResizeListener l) {
listenerList.add(ResizeListener.class, l);
}
/**
* Remove a ResizeListener, registered for nodeResized events.
* @param l The resize listener to un-register
*/
public void removeResizeListener(ResizeListener l) {
listenerList.remove(ResizeListener.class, l);
}
/**
* Creates the default resizer which just allows unconstrained
* scale resizing.
*/
protected ResizeListener createResizeListener() {
return new ResizeListener() {
public void nodeResized(ResizeEvent re) {
if (re.getMouseEvent().isShiftDown()) {
scale(re.getNode().editor().getTransformGroup(),
re.getConstrainScaleX(),re.getConstrainScaleY(),re.getX(),re.getY());
}
else {
scale(re.getNode().editor().getTransformGroup(),
re.getScaleX(),re.getScaleY(),re.getX(),re.getY());
}
}
public void resizeComplete() {
}
};
}
/**
* render the resize handles on a selected node
*/
protected ResizeHandles createResizeHandles() {
return new ResizeHandles();
}
/**
* Fires the resize event on the appropriate listeners
* @param re The resize event to be fired
*/
protected void fireResizeEvent(ResizeEvent re) {
if (listenerList == null) {
return;
}
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ResizeListener.class) {
if (re == null) {
((ResizeListener)listeners[i+1]).resizeComplete();
}
else {
((ResizeListener)listeners[i+1]).nodeResized(re);
}
}
}
}
/**
* Gets the current highlight color
* @return The current highlight color
*/
public Color getHighLightColor() {
return highLightColor;
}
/**
* Initializes this event handler
*/
protected void init() {
listenerList = new EventListenerList();
defaultResizeListener = createResizeListener();
addResizeListener(defaultResizeListener);
activeHandles = new HashMap();
}
/**
* Determines if this event handler is active.
* @return True if active
*/
public boolean isActive() {
return active;
}
/**
* required method of ZGroupListener:
*/
public void nodeAdded(ZGroupEvent e) {
ZNode node = e.getChild();
ZSceneGraphEditor editor = node.editor();
ResizeHandles rh = createResizeHandles();
editor.getNode().addMouseListener(rh);
editor.getNode().addMouseMotionListener(rh);
editor.getSelectionGroup().addAuxiliaryVisualComponent(rh);
activeHandles.put(node,rh);
}
/**
* required method of ZGroupListener:
*/
public void nodeRemoved(ZGroupEvent e) {
ZNode node = e.getChild();
ZSceneGraphEditor editor = node.editor();
ResizeHandles handles = (ResizeHandles)activeHandles.get(node);
if (handles != null) {
editor.getNode().removeMouseListener(handles);
editor.getNode().removeMouseMotionListener(handles);
}
activeHandles.remove(node);
}
/**
* Scales the given ZTransformGroup by the given (unconstrained)
* scale factors around the specified point
* @param zTransform The transform group to scale
* @param dxz The x scale
* @param dyz The y scale
* @param x The x coordinate around which to scale
* @param y The y coordinate around which to scale
*/
protected void scale(ZTransformGroup zTransform,
double dxz,
double dyz,
double x,
double y) {
AffineTransform transform = zTransform.getTransform();
transform.translate(x,y);
transform.scale(dxz,dyz);
transform.translate(-x,-y);
zTransform.setTransform(transform);
}
/**
* Specifies whether this event handler is active
* @param active True to make this event handler active
*/
public void setActive(boolean active) {
if (this.active && !active) {
// turn off this handler
this.active = false;
// un-register as a group listener for notification of changes to
// the selection:
if (globallyActive) {
ZSelectionManager.removeGroupListener(this);
}
else {
ZSelectionManager.removeGroupListener(this,activeCamera);
}
} else if (!this.active && active) {
// turn on handler:
this.active = true;
// register as a group listener for notification of changes to the
// selection:
if (globallyActive) {
ZSelectionManager.addGroupListener(this);
}
else {
ZSelectionManager.addGroupListener(this,activeCamera);
}
}
}
/**
* Remove the default resize listener
*/
public void setDefaultResizeListenerActive(boolean active) {
if (active && defaultResizeListener == null) {
defaultResizeListener = createResizeListener();
addResizeListener(defaultResizeListener);
}
else if (!active && defaultResizeListener != null) {
removeResizeListener(defaultResizeListener);
defaultResizeListener = null;
}
}
/**
* Sets the highlight color for this resize handler.
* @param color The new highlight color
*/
public void setHighLightColor(Color color) {
highLightColor = color;
}
}
| true
|
9a525737e8566a808d73973aa0ee88e29c3e6a95
|
Java
|
saydar31/java_lab
|
/course 2/2.JavaLabMessageQueue/src/main/java/ru/itis/javalabmessagequeue/service/SubscribeService.java
|
UTF-8
| 448
| 1.789063
| 2
|
[] |
no_license
|
package ru.itis.javalabmessagequeue.service;
import org.springframework.web.socket.WebSocketSession;
import ru.itis.javalabmessagequeue.dto.JlmqReceiveMessage;
import ru.itis.javalabmessagequeue.dto.JlmqSubscribeMessage;
import java.util.List;
public interface SubscribeService {
List<JlmqReceiveMessage> doService(JlmqSubscribeMessage subscribeMessage, WebSocketSession session);
List<JlmqReceiveMessage> doService(String queueName);
}
| true
|
789190b06d95cb68600e9347997fcc3727720c0b
|
Java
|
m172371621/qx_mgr
|
/src/com/brilliantreform/sc/circle/po/CircleFriend.java
|
UTF-8
| 2,516
| 2.171875
| 2
|
[] |
no_license
|
package com.brilliantreform.sc.circle.po;
import java.sql.Timestamp;
public class CircleFriend {
private Integer me_id; // int(11) NOT NULL,
private Integer user_id; // int(11) NOT NULL,
private Integer status; // int(11) DEFAULT '1',
private Timestamp createTime; // timestamp NULL DEFAULT NULL,
private String user_name;
private String user_pic;
private String user_sex; //F M
private String user_sign;
private String user_community;
private Integer relation_type; // int(11) DEFAULT '1',
public Integer getRelation_type() {
return relation_type;
}
public void setRelation_type(Integer relationType) {
relation_type = relationType;
}
public Integer getMe_id() {
return me_id;
}
public void setMe_id(Integer meId) {
me_id = meId;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer userId) {
user_id = userId;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String userName) {
user_name = userName;
}
public String getUser_pic() {
return user_pic;
}
public void setUser_pic(String userPic) {
user_pic = userPic;
}
public String getUser_sex() {
return user_sex;
}
public void setUser_sex(String userSex) {
user_sex = userSex;
}
public String getUser_sign() {
return user_sign;
}
public void setUser_sign(String userSign) {
user_sign = userSign;
}
public String getUser_community() {
return user_community;
}
public void setUser_community(String userCommunity) {
user_community = userCommunity;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CircleFried [createTime=");
builder.append(createTime);
builder.append(", me_id=");
builder.append(me_id);
builder.append(", status=");
builder.append(status);
builder.append(", user_community=");
builder.append(user_community);
builder.append(", user_id=");
builder.append(user_id);
builder.append(", user_name=");
builder.append(user_name);
builder.append(", user_pic=");
builder.append(user_pic);
builder.append(", user_sex=");
builder.append(user_sex);
builder.append(", user_sign=");
builder.append(user_sign);
builder.append("]");
return builder.toString();
}
}
| true
|
0260fdfd0f78b02cf4941db9154544b095113a88
|
Java
|
deep-mm/FamFood
|
/App/app/src/main/java/com/canteenautomation/famfood/Activity/SearchActivity.java
|
UTF-8
| 4,548
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package com.canteenautomation.famfood.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.canteenautomation.famfood.Adapter.MenuItemAdapter;
import com.canteenautomation.famfood.Entities.ItemCategoryEntity;
import com.canteenautomation.famfood.Entities.ItemEntity;
import com.canteenautomation.famfood.Listener.OnItemQuantityChange;
import com.canteenautomation.famfood.R;
import com.canteenautomation.famfood.Utilities.Helper;
import com.canteenautomation.famfood.Utilities.SharedData;
import java.util.ArrayList;
import java.util.List;
public class SearchActivity extends AppCompatActivity {
private ArrayList<ItemEntity> itemEntityArrayList = new ArrayList<>();
private List<ItemCategoryEntity> itemCategoryEntities;
private RecyclerView mRecyclerView;
private MenuItemAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private SharedData sharedData;
private ImageView backButton;
private Helper helper;
private TextView page_title;
private EditText searchBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initialize();
itemCategoryEntities = sharedData.getItemCategoryEntity();
for(int i=0;i<itemCategoryEntities.size();i++){
ItemCategoryEntity itemCategoryEntity = itemCategoryEntities.get(i);
itemEntityArrayList.addAll(itemCategoryEntity.getItemEntities());
}
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mRecyclerView.setItemAnimator( new DefaultItemAnimator());
mAdapter = new MenuItemAdapter("",itemEntityArrayList, getApplicationContext(), new OnItemQuantityChange() {
@Override
public void onQuantityChange() {
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SearchActivity.super.onBackPressed();
}
});
mRecyclerView.setAdapter(mAdapter);
searchBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filter(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
}
private void filter(String text) {
ArrayList<ItemEntity> filteredList = new ArrayList<>();
for(ItemCategoryEntity item: itemCategoryEntities){
if(item.getCategoryName().toLowerCase().contains(text.toLowerCase())){
filteredList.addAll(item.getItemEntities());
}
}
for (ItemEntity item : itemEntityArrayList) {
if (item.getItemName().toLowerCase().contains(text.toLowerCase())) {
if(!filteredList.contains(item))
filteredList.add(item);
}
}
mAdapter = new MenuItemAdapter("",filteredList, getApplicationContext(), new OnItemQuantityChange() {
@Override
public void onQuantityChange() {
}
});
mRecyclerView.setAdapter(mAdapter);
}
public void initialize(){
mRecyclerView= findViewById(R.id.search_recycler);
sharedData = new SharedData(getApplicationContext());
backButton = (ImageButton) findViewById(R.id.back_button);
page_title = (TextView) findViewById(R.id.search_title);
helper = new Helper(getApplicationContext());
searchBox = findViewById(R.id.search_edit_text);
assignFonts();
}
public void assignFonts(){
page_title.setTypeface(helper.cambriaBold);
searchBox.setTypeface(helper.comic);
}
@Override
public void onBackPressed(){
super.onBackPressed();
}
}
| true
|
440a4ea748f57672acd2b7f7ea60e0c6acaf952e
|
Java
|
david-d25/programming-lab8
|
/src/ru/david/room/server/HubFriendly.java
|
UTF-8
| 998
| 2.625
| 3
|
[] |
no_license
|
package ru.david.room.server;
/**
* Интерфейс для тех, кто дружит с {@link Hub}
*/
public interface HubFriendly {
/**
* Вызывается, когда экземпляр {@link Hub} создан и этот объект к нему подключён.
* В этом методе экземпляр следует сохранить, однако работать
* с хабом нельзя, так как он ещё не не готов.
*
* @param hub хаб, к которому будет подключен этот экземпляр класса
*/
void onHubConnected(Hub hub);
/**
* Вызывается, когда хаб готов к взаимодействию.
* В этом методе можно начать работать с хабом, который
* рвнее передавался через вызов метода {@link #onHubConnected(Hub)}.
*/
void onHubReady();
}
| true
|
2e22bf9960122be163fb1c168079440c5b761a3c
|
Java
|
bsc-renewit/d2.2
|
/powerModelling/prototype/src/main/java/es/bsc/autonomic/powermodeller/configuration/CoreConfiguration.java
|
UTF-8
| 10,082
| 1.53125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2015 Barcelona Supercomputing Center
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package es.bsc.autonomic.powermodeller.configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.*;
import static java.nio.file.Files.setPosixFilePermissions;
public class CoreConfiguration {
public static char CSV_DELIMITER;
public static String INDEPENDENT;
public static String TEMPDIR ="temp-" + Calendar.getInstance().getTimeInMillis();
public static List<String> TRAINING_CPU;
public static List<String> TRAINING_MEMORY;
public static List<String> TRAINING_DISK;
public static List<String> TRAINING_NETWORK;
public static List<String> TRAINING_GLOBAL;
public static List<String> VALIDATION;
public static boolean PREPROCESS_DATASET;
public static boolean SCALE_DATA;
public static int MOVING_AVG_WINDOW;
public static String FILTER_TYPE;
public static double POWER_IDLE;
public static String CLASSIFIER;
public static String MODEL_PATH;
public static boolean NEW_MODEL;
//public static boolean STEP2_NEW_MODEL;
public static String STEP_2_CLASSIFIER;
//public static String STEP_2_MODEL_PATH;
public static String POWER_IDLE_VALIDATION;
public static String MODEL_TYPE;
public static String MODEL_RESOURCES_LEVEL;
public static final String P_PCPU = "P-Pcpu";
public static final String P_PCPU_PMEM = "P-Pcpu-Pmem";
public static final String P_PCPU_PMEM_PDISK = "P-Pcpu-Pmem-Pdisk";
public static final String PIDLE_LABEL = "Pidle";
public static final String PCPU_LABEL = "Pcpu";
public static final String PMEM_LABEL = "Pmem";
public static final String PDISK_LABEL = "Pdisk";
public static final String PNET_LABEL = "Pnet";
public static final String PACTUAL_LABEL = "Pactual";
public static final String PPREDICTED_LABEL = "Ppredicted";
// Configuration files
private static String PMG_HOME = System.getenv("PMG_HOME");
private final static String PMG_HOME_DEFAULT = "/opt/PowerModelGenerator";
private static final String CONF_GLOBAL = "/conf/configuration.properties";
private static final String CONF_DATASETS = "/conf/datasets.properties";
public static final String CONF_MODEL_CPU = "/conf/model-cpu.properties";
public static final String CONF_MODEL_MEMORY = "/conf/model-memory.properties";
public static final String CONF_MODEL_DISK = "/conf/model-disk.properties";
public static final String CONF_MODEL_NETWORK = "/conf/model-network.properties";
public static final String CONF_MODEL_GLOBAL = "/conf/model-global.properties";
public static final String R_SCRIPT_ESTIMATION = "/conf/estimation.r";
public static final String R_SCRIPT_GENERATE_SCALING = "/conf/scaling_data_training.r";
public static final String R_SCRIPT_APPLY_SCALING = "/conf/scaling_data_validation.r";
public static final String R_SCRIPT_MOVING_AVERAGE = "/conf/movingAverage.r";
// Model types:
public final static String RESOURCES_MODEL = "resources";
public final static String GLOBAL_MODEL = "global";
public final static String COMBINED_MODEL = "combined";
// Subtypes of resources model:
public final static String RESOURCES_MODEL_TYPE_CPU = "cpu";
public final static String RESOURCES_MODEL_TYPE_MEM = "cpu+mem";
public final static String RESOURCES_MODEL_TYPE_DISK = "cpu+mem+disk";
public final static String RESOURCES_MODEL_TYPE_NET = "cpu+mem+disk+net";
public final static String RESOURCES_MODEL_TYPE_ALL = "all";
private final static Logger logger = Logger.getLogger(CoreConfiguration.class);
// WARNING: this attribute must be the last to be declared in this class. NEVER MODIFY IT.
private static final CoreConfiguration CONF_INSTANCE = new CoreConfiguration();
/**
* Private constructor
*/
private CoreConfiguration() {
//General configuration
PropertiesConfiguration config = getPropertiesConfiguration(CoreConfiguration.CONF_GLOBAL);
CSV_DELIMITER = config.getString("csv-delimiter").charAt(0);
INDEPENDENT = config.getString("independent");
PREPROCESS_DATASET = config.getBoolean("preprocess-dataset");
SCALE_DATA = config.getBoolean("scale-data");
FILTER_TYPE = config.getString("filter-type");
MOVING_AVG_WINDOW = config.getInt("moving-average-window");
POWER_IDLE = config.getDouble("power-idle-training");
CLASSIFIER = config.getString("classifier");
NEW_MODEL = config.getBoolean("new-model");
MODEL_TYPE = config.getString("model-type");
MODEL_RESOURCES_LEVEL = config.getString("model-resources-level");
MODEL_PATH = config.getString("model-path");
//STEP2_NEW_MODEL = config.getBoolean("step2-new-model");
STEP_2_CLASSIFIER = config.getString("step2-classifier");
//STEP_2_MODEL_PATH = config.getString("step2-model-path");
POWER_IDLE_VALIDATION = config.getString("power-idle-validation");
//Training dataset configuration
PropertiesConfiguration datasets = getPropertiesConfiguration(CoreConfiguration.CONF_DATASETS);
TRAINING_CPU = Arrays.asList(datasets.getStringArray("trainingCPU"));
TRAINING_MEMORY = Arrays.asList(datasets.getStringArray("trainingMemory"));
TRAINING_DISK = Arrays.asList(datasets.getStringArray("trainingDisk"));
TRAINING_NETWORK = Arrays.asList(datasets.getStringArray("trainingNetwork"));
VALIDATION = Arrays.asList(datasets.getStringArray("validation"));
TRAINING_GLOBAL = Arrays.asList(datasets.getStringArray("trainingGlobal"));
//Temporal working directory creation
File fileDir = new File(TEMPDIR);
if (!fileDir.exists()) {
logger.debug("Creating directory: " + fileDir);
boolean result = false;
try{
fileDir.mkdir();
result = true;
} catch(SecurityException se){
//handle it
}
if(result) {
TEMPDIR = fileDir.getAbsolutePath();
logger.info("Temporary directory " + TEMPDIR + " created");
}
}
}
public static PropertiesConfiguration getPropertiesConfiguration(String configFile) {
String filePath = null;
PropertiesConfiguration config = null;
try {
filePath = getFilePath(configFile);
config = new PropertiesConfiguration(filePath);
} catch (ConfigurationException ex) {
logger.error("Error reading " + filePath + " configuration file: " + ex.getMessage());
logger.error(ex.getMessage());
}
return config;
}
public static String getFilePath(String configFile) {
String pmgHome = PMG_HOME;
if (pmgHome == null) {
pmgHome = PMG_HOME_DEFAULT;
PMG_HOME = pmgHome;
logger.warn("Please set environment variable PMG_HOME. Using default " + pmgHome);
}
File fileObject = new File(pmgHome.concat(configFile));
if (!fileObject.exists()) {
try {
createDefaultConfigFile(fileObject);
} catch (Exception ex) {
logger.error("Error reading " + pmgHome.concat(configFile) + " configuration file: ", ex);
}
}
return pmgHome.concat(configFile);
}
private static void createDefaultConfigFile(File fileObject) throws Exception {
logger.debug("File " + fileObject.getAbsolutePath() + " didn't exist. Creating one with default values...");
//Create parent directories.
logger.debug("Creating parent directories.");
new File(fileObject.getParent()).mkdirs();
//Create an empty file to copy the contents of the default file.
logger.debug("Creating empty file.");
new File(fileObject.getAbsolutePath()).createNewFile();
//Copy file.
logger.debug("Copying file " + fileObject.getName());
InputStream streamIn = CoreConfiguration.class.getResourceAsStream("/" + fileObject.getName());
FileOutputStream streamOut = new FileOutputStream(fileObject.getAbsolutePath());
byte[] buf = new byte[8192];
while (true) {
int length = streamIn.read(buf);
if (length < 0) {
break;
}
streamOut.write(buf, 0, length);
}
//Close streams after copying.
try {
streamIn.close();
} catch (IOException ex) {
logger.error("Couldn't close input stream");
logger.error(ex.getMessage());
}
try {
streamOut.close();
} catch (IOException ex) {
logger.error("Couldn't close file output stream");
logger.error(ex.getMessage());
}
setPosixFilePermissions(fileObject.toPath(), PosixFilePermissions.fromString("rwxr-xr-x"));
}
public static String getNewCSVFileName() {
return TEMPDIR + "/" + UUID.randomUUID().toString() + ".csv";
}
public static String getNewSerializedFileName() {
return TEMPDIR + "/" + UUID.randomUUID().toString() + ".ser";
}
}
| true
|
ae22b1f8fe3b9c5261e6a387fac76efc02e0a341
|
Java
|
elKevin24/KOKOS
|
/src/java/controlador/BeanInventario.java
|
UTF-8
| 2,892
| 1.929688
| 2
|
[] |
no_license
|
package controlador;
public class BeanInventario {
public String getId_inventario() {
return id_inventario;
}
public void setId_inventario(String id_inventario) {
this.id_inventario = id_inventario;
}
public String getPrenda() {
return prenda;
}
public void setPrenda(String prenda) {
this.prenda = prenda;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getTalla() {
return talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getPrecio_costo() {
return precio_costo;
}
public void setPrecio_costo(String precio_costo) {
this.precio_costo = precio_costo;
}
public String getPrecio_venta() {
return precio_venta;
}
public void setPrecio_venta(String precio_venta) {
this.precio_venta = precio_venta;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getUsuario_id() {
return usuario_id;
}
public void setUsuario_id(String usuario_id) {
this.usuario_id = usuario_id;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getNumero_Prenda() {
return Numero_Prenda;
}
public void setNumero_Prenda(String Numero_Prenda) {
this.Numero_Prenda = Numero_Prenda;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public BeanInventario(String prenda, String marca,
String talla, String precio_costo, String precio_venta, String codigo, String usuario_id, String Numero_Prenda, String descripcion) {
this.prenda = prenda;
this.marca = marca;
this.talla = talla;
this.precio_costo = precio_costo;
this.precio_venta = precio_venta;
this.codigo = codigo;
this.usuario_id = usuario_id;
this.Numero_Prenda = Numero_Prenda;
this.descripcion = descripcion;
}
private String id_inventario;
private String prenda;
private String marca;
private String talla;
private String precio_costo;
private String precio_venta;
private String codigo;
private String usuario_id;
private String fecha;
private String status;
private String Numero_Prenda;
private String descripcion;
public BeanInventario() {
}
}
| true
|
f24f1336c12a1e7ff721f3c332f5609f7cb627e3
|
Java
|
leedongyoen/cafein
|
/cafein/src/main/java/co/yedam/cafein/customer/login/CustomerLoginDAO.java
|
UTF-8
| 1,856
| 2.15625
| 2
|
[] |
no_license
|
package co.yedam.cafein.customer.login;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import co.yedam.cafein.vo.CustomerVO;
@Repository
public class CustomerLoginDAO {
@Autowired
private SqlSessionTemplate mybatis;
public CustomerVO getCustomer(CustomerVO vo) {
return mybatis.selectOne("customerLoginDAO.getCustomer",vo);
}
public CustomerVO getKakaoCustomer(CustomerVO vo) {
return mybatis.selectOne("customerLoginDAO.getKakaoCustomer",vo);
}
public CustomerVO getNaverCustomer(CustomerVO vo) {
return mybatis.selectOne("customerLoginDAO.getNaverCustomer",vo);
}
// 로그인 시 DB에 있는 id, password 와 일치하는지 확인하기위한 select
public List<CustomerVO> getCustomerList(CustomerVO vo) {
System.out.println("-- -- -- Customer Login -- -- --");
return mybatis.selectList("customerLoginDAO.getCustomerList", vo);
}
// kakao 로그인 시 DB에 정보가 없으면 insert
public int insertCustomerKakao(CustomerVO vo) {
System.out.println("-- -- -- Customer Kakao_Info Insert -- -- --");
return mybatis.insert("customerLoginDAO.insertCustomerKakao", vo);
}
// naver 로그인 시 정보가 없으면 insert
public int insertCustomerNaver(CustomerVO vo) {
System.out.println("-- -- -- Customer Naver_Info Insert -- -- --");
return mybatis.insert("customerLoginDAO.insertCustomerNaver", vo);
}
//아이디 찾기 폼
public CustomerVO idFind(CustomerVO vo) {
System.out.println(" - - - - id - - - -");
return mybatis.selectOne("customerLoginDAO.idFind", vo);
}
//비밀번호 찾기 폼
public void pwFind(CustomerVO vo) {
mybatis.update("customerLoginDAO.pwFind", vo);
}
}
| true
|