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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9fff65f90176e77cdb7886c8661cef792bf4a1ea | Java | oszhugc/springboot-activiti-demo | /src/main/java/com/neimeng/workflow/entity/params/ApplyDatasetInfo.java | UTF-8 | 990 | 2.203125 | 2 | [] | no_license | package com.neimeng.workflow.entity.params;
import com.neimeng.workflow.entity.enums.PriorityEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.NotNull;
/**
* 申请数据集的基本信息
*/
@Getter
@Setter
@ToString
@ApiModel("申请数据集参数")
public class ApplyDatasetInfo {
@ApiModelProperty(value = "数据集ID", required = true)
@NotNull
protected Integer dataSetId;
@ApiModelProperty(value = "数据集名称", required = true)
@NotNull
protected String dataSetName;
@ApiModelProperty(value = "数据集创建人", required = true)
@NotNull
protected String dataSetCreator;
// 优先级
private PriorityEnum priority;
public PriorityEnum getPriority() {
if (priority == null) {
return PriorityEnum.NOMAL;
}
return priority;
}
}
| true |
989844e795c36dc413909751e12690bb75b7958b | Java | brunofc125/exemplos-principios | /reuso-composicao/reusocomposicao/src/main/java/br/ufes/reusocomposicao/certo/model/Gerente.java | UTF-8 | 786 | 2.234375 | 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 br.ufes.reusocomposicao.certo.model;
/**
*
* @author bruno
*/
public class Gerente extends Funcionario {
private boolean chefe;
public Gerente(boolean chefe, int tempoServicoMesSemFerias, ICalculoFerias calculoFerias) {
super(tempoServicoMesSemFerias, calculoFerias);
this.chefe = chefe;
}
public boolean isChefe() {
return chefe;
}
public void setChefe(boolean chefe) {
this.chefe = chefe;
}
@Override
public int calcularFerias() {
return this.getCalculoFerias().calcularFerias(this);
}
}
| true |
95d20e999fe1d124a90ec28a8c9440e677b32270 | Java | VitorMarques/automattor | /src/main/java/br/com/kolin/automattor/model/place/detail/OpeningHours.java | UTF-8 | 255 | 1.53125 | 2 | [] | no_license | package br.com.kolin.automattor.model.place.detail;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class OpeningHours {
private String text;
}
| true |
e0b72d1059d677ba51bf2bfe4cbb85c9d2b35a39 | Java | WKorga/NLP2018 | /Lista_3/zad_3.3/src/Pair.java | UTF-8 | 345 | 3.03125 | 3 | [] | no_license | public class Pair {
private double cheated;
private double nonCheated;
public Pair(double cheated, double nonCheated) {
this.cheated = cheated;
this.nonCheated = nonCheated;
}
public double getCheated() {
return cheated;
}
public double getNonCheated() {
return nonCheated;
}
}
| true |
0a19dae71852324c2250c9f668e4bc42e6770117 | Java | lailaAbbas/OOP | /LAILA-ABBAS-ASSIGNMENT-6/Sundae.java | UTF-8 | 707 | 3.015625 | 3 | [] | no_license | package lailaAbbasAssignment;
public class Sundae extends IceCream {
private String SundaeName;
private int toppinPrice;
public Sundae (String iceName, int icePrice ,String toppingName , int toppingPrice)
{
super(iceName,icePrice);
SundaeName = toppingName + " Sundae with \n" ;
toppinPrice = toppingPrice;
}
public int getCost()
{
return(toppinPrice+super.getCost());
}
public String toString()
{
String sundaeName = SundaeName;
sundaeName += this.name;
String price = DessertShoppe.cents2dollarsAndCents(this.getCost());
for(int i =0; i< (30-this.name.length()-price.length());i++)
{
sundaeName += " ";
}
sundaeName += price + "\n";
return sundaeName;
}
}
| true |
f1e1843a92f40e8ace0c12eb65cca2917d51bc7c | Java | anandhang/testRepo | /src/test/java/test_scripts/inheritance/Grand_Father_Family.java | UTF-8 | 388 | 2.796875 | 3 | [] | no_license | package test_scripts.inheritance;
public class Grand_Father_Family {
String grandFatherName = "Periyathambi";
String grandMotherName = "Kaveri";
public void display_grandFather(){
System.out.println("-:Family Members:-");
System.out.println("Grand Father Name: "+ grandFatherName);
System.out.println("Grand Mother Name: "+ grandMotherName);
}
}
| true |
cd2c32a630d40c2e7a00cbdecf63004206eead6e | Java | rainyheart/ml4football | /web-demo/mis2/src/main/java/com/mis/repositories/NewsRepository.java | UTF-8 | 749 | 1.921875 | 2 | [] | no_license | package com.mis.repositories;
import java.util.Date;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.mis.domain.News;
@Repository
public interface NewsRepository extends PagingAndSortingRepository<News, Integer> {
@Modifying
@Query("update News t set t.subject=:subject, t.content=:content, t.updateDate=:updateDate where t.id=:id")
void updateNews(@Param("id") Integer id, @Param("subject") String subject, @Param("content") String content, @Param("updateDate") Date updateDate);
} | true |
1f5bc2311f270aa3541cbfdea4b82053035c4df9 | Java | qqw78901/interview | /src/main/java/com/jeff/serviceImpl/ResultServiceImpl.java | UTF-8 | 4,318 | 2.1875 | 2 | [] | no_license | package com.jeff.serviceImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jeff.common.mConst;
import com.jeff.mapper.InterviewMapper;
import com.jeff.mapper.ResultMapper;
import com.jeff.mybatis.page.Page;
import com.jeff.po.Result;
import com.jeff.service.ResultService;
import com.jeff.util.ExcelFile;
import com.jeff.vo.EnterRowVo;
import com.jeff.vo.InterviewResultVo;
import com.jeff.vo.IntervieweeResultVo;
import com.jeff.vo.ResultVo;
@Service
public class ResultServiceImpl extends BaseServiceImpl<Result, String> implements ResultService {
@Autowired
private ResultMapper resultMapper;
@Autowired
private InterviewMapper interviewMapper;
@Autowired
public void setBaseMapper() {
super.setBaseMapper(resultMapper);
}
@Override
public int addResult(Result result) {
return resultMapper.addResult(result);
}
@Override
public Page<ResultVo> showAllResultbyPage(ResultVo resultVo) {
return this.buildVoPage(resultMapper.showAllResultbyPage(resultVo));
}
@Override
public int set(Result result) {
int r;
r = resultMapper.set(result);
if (result.getResult().equals(mConst.STATE_T)) {// 若为通过
// 则置T并加下一级interview
String nextInterview = interviewMapper.getChild(result.getInterviewId());
if (nextInterview != null) {
Result checkResult = new Result();
checkResult.setInterviewee(result.getInterviewee());
checkResult.setInterviewId(nextInterview);// 用于判断是否已存在值需要的参数的赋值
if (resultMapper.check(checkResult) == 0) {// 检查是否已经被通过了再通过
Result next = new Result();
next.setInterviewee(result.getInterviewee());// 同样的面试者
next.setInterviewId(nextInterview);// 下一级的interview
resultMapper.addResult(next);
}
}
} else if (result.getResult().equals(mConst.STATE_F)) {// 若为不通过
// 则置F并删除下级所有的interview
resultMapper.deleteAllNext(result);
}
return r;
}
@Override
public Result getInterview(Result result) {
return resultMapper.getInterview(result);
}
@Override
public int check(Result result) {
return resultMapper.check(result);
}
@Override
public Page<IntervieweeResultVo> selectIntervieweeByPage(ResultVo resultVo) {
return this.buildVoPage(resultMapper.selectIntervieweeByPage(resultVo));
}
@Override
public ExcelFile getInterviewSummary(String interviewId) {
final int prefixSize = 3, suffixSize = 1;
List<InterviewResultVo> interviewResults = resultMapper.getInterviewSummary(interviewId);
if (interviewResults != null && !interviewResults.isEmpty()) {
List<EnterRowVo> headers = interviewResults.get(0).getEnterRows();
List<List<String>> table = new ArrayList<>(interviewResults.size());
for (int i = 0; i != interviewResults.size(); ++i) {
String row[] = new String[headers.size() + prefixSize + suffixSize];
InterviewResultVo currResult = interviewResults.get(i);
row[0] = currResult.getName();
row[1] = currResult.getCard();
row[2] = currResult.getPhone();
row[row.length - 1] = mConst.MESSAGE_MAP.get(currResult.getResult());
table.add(Arrays.asList(row));
}
for (int j = 0; j != headers.size(); ++j) {
EnterRowVo header = headers.get(j);
assert header.getQuestionType().equals("text");// TODO:处理内容分类
for (int i = 0; i < table.size(); ++i) {
EnterRowVo currRow = interviewResults.get(i).getEnterRows().get(j);
assert currRow.getQuestion().equals(header.getQuestion());
table.get(i).set(prefixSize + j, currRow.getAnswer());
}
}
String headerStrs[] = new String[headers.size() + prefixSize + suffixSize];
headerStrs[0] = "姓名";
headerStrs[1] = "学号";
headerStrs[2] = "手机号";
for (int i = 0; i < headers.size(); i++) {
headerStrs[i + prefixSize] = headers.get(i).getQuestion();
}
headerStrs[headerStrs.length - 1] = "结果";
ExcelFile excelFile = new ExcelFile("summary", Arrays.asList(headerStrs), table);
return excelFile;
} else {
return null;
}
}
@Override
public int remove(Result result) {
return resultMapper.remove(result);
}
}
| true |
5030e4317053a420db3f5c5c33eefe291d7cfe9f | Java | Taekyung2/Java_algorithm | /src/boj_algorithm/_11000번대/_11600/_11657_타임머신.java | UTF-8 | 1,450 | 3.078125 | 3 | [] | no_license | package boj_algorithm._11600;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class _11657_타임머신 {
static class Edge {
int to, weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
final static int INF = 1000000000;
static long[] upper;
static int V, E;
static ArrayList<Edge>[] adj;
static boolean bellmanFord(int src) {
upper = new long[V + 1];
Arrays.fill(upper, INF);
upper[src] = 0;
for(int iter = 1; iter <= V; ++iter) {
boolean chk = false;
for(int here = 1; here <= V; ++here)
for(int i = 0; i < adj[here].size(); ++i) {
int there = adj[here].get(i).to;
int cost = adj[here].get(i).weight;
if(upper[here] != INF && upper[there] > upper[here] + cost) {
upper[there] = upper[here] + cost;
chk = true;
if(iter == V) return false;
}
}
if(!chk) return true;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
V = sc.nextInt();
E = sc.nextInt();
adj = new ArrayList[V + 1];
for(int i = 0; i <= V; i++) adj[i] = new ArrayList<Edge>();
for(int i = 0; i < E; i++) {
int u = sc.nextInt(), v = sc.nextInt(), w = sc.nextInt();
adj[u].add(new Edge(v, w));
}
if(bellmanFord(1))
for(int i = 2; i <= V; i++)
System.out.println((upper[i] == INF ? -1 : upper[i]));
else
System.out.println(-1);
sc.close();
}
} | true |
d314ffb64a3bed487d05f7fd61b693bc689bd2b8 | Java | reformasky/git | /src/test/java/org/xuan/NumArray_MutableTest.java | UTF-8 | 723 | 2.609375 | 3 | [] | no_license | package org.xuan;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Created by xzhou2 on 5/25/16.
*/
public class NumArray_MutableTest {
@Test
public void test() {
NumArray_Mutable.NumArray numArray = new NumArray_Mutable.NumArray(new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17});
Assert.assertEquals(numArray.sumRange(1, 14), 105);
numArray.update(1,2);
Assert.assertEquals(numArray.sumRange(1, 14), 106);
numArray.update(13,3);
Assert.assertEquals(numArray.sumRange(1, 14), 96);
for(int i = 0; i < 18; i++) {
for(int j = 0; j < 18; j++) {
numArray.sumRange(i, j);
}
}
}
}
| true |
3ad98ccf70786e1585fe751185ae1082dbcf1c44 | Java | K-oba/ExpoWeb | /expoCR/src/main/java/com/kaoba/expo/domain/Pregunta.java | UTF-8 | 3,140 | 2.1875 | 2 | [] | no_license | package com.kaoba.expo.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A Pregunta.
*/
@Entity
@Table(name = "pregunta")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Pregunta implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "pregunta")
private String pregunta;
@ManyToOne
private Usuario usuario;
@ManyToMany(mappedBy = "preguntas")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Charla> charlas = new HashSet<>();
@ManyToOne
private Exposicion exposicion;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPregunta() {
return pregunta;
}
public Pregunta pregunta(String pregunta) {
this.pregunta = pregunta;
return this;
}
public void setPregunta(String pregunta) {
this.pregunta = pregunta;
}
public Usuario getUsuario() {
return usuario;
}
public Pregunta usuario(Usuario usuario) {
this.usuario = usuario;
return this;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public Set<Charla> getCharlas() {
return charlas;
}
public Pregunta charlas(Set<Charla> charlas) {
this.charlas = charlas;
return this;
}
public Pregunta addCharla(Charla charla) {
this.charlas.add(charla);
charla.getPreguntas().add(this);
return this;
}
public Pregunta removeCharla(Charla charla) {
this.charlas.remove(charla);
charla.getPreguntas().remove(this);
return this;
}
public void setCharlas(Set<Charla> charlas) {
this.charlas = charlas;
}
public Exposicion getExposicion() {
return exposicion;
}
public Pregunta exposicion(Exposicion exposicion) {
this.exposicion = exposicion;
return this;
}
public void setExposicion(Exposicion exposicion) {
this.exposicion = exposicion;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pregunta pregunta = (Pregunta) o;
if (pregunta.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), pregunta.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Pregunta{" +
"id=" + getId() +
", pregunta='" + getPregunta() + "'" +
"}";
}
}
| true |
cfa36c6530b750cf452b7b4b5d12c500739bf26e | Java | mengmengmengmeng/PayMaya-Android-SDK | /sdk-android/src/main/java/com/paymaya/sdk/android/checkout/models/Contact.java | UTF-8 | 3,175 | 2.265625 | 2 | [
"MIT"
] | permissive | /*
* Copyright (c) 2016 PayMaya Philippines, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.paymaya.sdk.android.checkout.models;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Represents buyer's contact details. If the email field is provided,
* a payment receipt will be sent to the email address.
*/
public final class Contact implements Parcelable {
private String phone;
private String email;
/**
*
* @param phone buyer's phone number
* @param email buyer's email address
*/
public Contact(String phone, String email) {
this.phone = phone;
this.email = email;
}
public Contact(Parcel in) {
phone = in.readString();
email = in.readString();
}
public static final Creator<Contact> CREATOR = new Creator<Contact>() {
@Override
public Contact createFromParcel(Parcel in) {
return new Contact(in);
}
@Override
public Contact[] newArray(int size) {
return new Contact[size];
}
};
/**
*
* @return buyer's phone number
*/
public String getPhone() {
return phone;
}
/**
* set a new value for buyer's phone number
*
* @param phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
*
* @return buyer's email address
*/
public String getEmail() {
return email;
}
/**
* set a new value for buyer's email address
*
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(phone);
dest.writeString(email);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Contact{");
sb.append("phone='").append(phone).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append('}');
return sb.toString();
}
}
| true |
92a43d7139b5940525759287e9d56e2f283b3155 | Java | kinnplh/ExprTouchAndSlide | /app/src/main/java/com/example/kinnplh/exprtouchandslide/MainOperationView.java | UTF-8 | 2,184 | 2.4375 | 2 | [] | no_license | package com.example.kinnplh.exprtouchandslide;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import static com.example.kinnplh.exprtouchandslide.ControlLayout.SDCardPath;
/**
* Created by kinnplh on 2016/12/21.
*/
abstract public class MainOperationView extends View {
public int screenWidth;
public int screenHeight;
private float densityDpi;
public boolean crtStageFinished;
public String InfoWhenStart;
Paint p;
BufferedWriter out;
public MainOperationView(Context context){
super(context);
DisplayMetrics dm = getResources().getDisplayMetrics();
screenHeight = dm.heightPixels;
screenWidth = dm.widthPixels;
densityDpi = dm.densityDpi;
crtStageFinished = false;
p = new Paint();
InfoWhenStart = "诶呀呀~ 我怎么会在这里!";
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(SDCardPath, true)));
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public FloatPoint getGridPoint(int x, int y, int totalX, int totalY){
float xOffset = screenWidth * (2f * x - 1f) / (2f * totalX);
float yOffset = screenHeight * (2f * y - 1f) / (2f * totalY);
return new FloatPoint(xOffset, yOffset);
}
abstract boolean next();
abstract boolean eventHandler(MotionEvent e);
abstract public void onDraw(Canvas canvas);
public boolean hasNext(){
return crtStageFinished;
}
public void printToSDCardWithTimestamp(String info){
try {
out.write(String.format("%d: %s", System.currentTimeMillis(), info));
} catch (IOException e) {
e.printStackTrace();
}
}
}
class FloatPoint{
float x;
float y;
FloatPoint(){}
FloatPoint(float _x, float _y){
x = _x;
y = _y;
}
} | true |
8d1a1d8473aab7562849ed2452dfb93b32404bbd | Java | chaqui/BananaView | /src/com/android/json/JSONManager.java | UTF-8 | 1,186 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | package com.android.json;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.json.*;
public class JSONManager {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject json = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch(Exception e){}
try{
json = new JSONObject(result);
}catch(JSONException e){}
return json;
}
}
| true |
1c22949dfbc1a38aa182a296fa721facd5e21577 | Java | Dmitry-khv/2019-09-otus-java-konoplev | /hw09-jdbc/src/main/java/ru/otus/jdbc/dao/AccountDaoJdbc.java | UTF-8 | 1,834 | 2.421875 | 2 | [] | no_license | package ru.otus.jdbc.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.otus.api.dao.AccountDao;
import ru.otus.api.dao.UserDaoException;
import ru.otus.api.model.Account;
import ru.otus.api.sessionmanager.SessionManager;
import ru.otus.jdbc.DBExecutor;
import ru.otus.jdbc.sessionmanager.SessionManagerJdbc;
import java.sql.Connection;
public class AccountDaoJdbc implements AccountDao {
private static Logger logger = LoggerFactory.getLogger(AccountDaoJdbc.class);
private final SessionManagerJdbc sessionManagerJdbc;
private final DBExecutor<Account> dbExecutor;
public AccountDaoJdbc(SessionManagerJdbc sessionManagerJdbc, DBExecutor<Account> dbExecutor) {
this.sessionManagerJdbc = sessionManagerJdbc;
this.dbExecutor = dbExecutor;
}
@Override
public long save(Account account) {
try {
return dbExecutor.save(getConnection(), account);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new UserDaoException(e);
}
}
@Override
public Account findByNo(long id) {
try {
return dbExecutor.load(getConnection(), Account.class, id);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new UserDaoException(e);
}
}
@Override
public void update(Account account) {
try {
dbExecutor.update(getConnection(), account);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new UserDaoException(e);
}
}
@Override
public SessionManager getSessionManager() {
return sessionManagerJdbc;
}
private Connection getConnection() {
return sessionManagerJdbc.getCurrentSession().getConnection();
}
}
| true |
7aefe51a588a781600e7ef719f5a082313aa270a | Java | RustemGaniev/Csv | /src/main/java/Main.java | UTF-8 | 3,747 | 2.703125 | 3 | [] | no_license | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.opencsv.CSVReader;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
String[] columnMapping = {"id", "firstName", "lastName", "country", "age"};
String fileName = "data.csv";
List<Employee> list = parseCSV(columnMapping, fileName);
String json = listToJson(list);
writeString(json, "data.json");
List<Employee> listFromXML = parseXML("data.xml");
String json2 = listToJson(listFromXML);
writeString(json2, "data2.json");
}
public static List<Employee> parseCSV(String[] columnMapping, String fileName) {
List<Employee> stuff = null;
try (CSVReader reader = new CSVReader(new FileReader(fileName))) {
ColumnPositionMappingStrategy<Employee> strategy = new ColumnPositionMappingStrategy<>();
strategy.setType(Employee.class);
strategy.setColumnMapping(columnMapping);
CsvToBean<Employee> csv = new CsvToBeanBuilder<Employee>(reader)
.withMappingStrategy(strategy)
.build();
stuff = csv.parse();
stuff.forEach(System.out :: println);
} catch (IOException e) {
e.printStackTrace();
}
return stuff;
}
public static String listToJson(List list) {
Type listType = new TypeToken<List<Employee>>() {
}.getType();
GsonBuilder rustem = new GsonBuilder();
Gson gson = rustem.create();
String json = gson.toJson(list, listType);
return json;
}
public static void writeString(String json, String jsonFile) {
try (FileWriter file = new FileWriter(jsonFile)) {
file.write(json);
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Employee> parseXML(String xmlFilename) throws ParserConfigurationException, IOException, SAXException {
List<Employee> stuff1 = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(xmlFilename));
NodeList employeeElements = (document).getDocumentElement().getElementsByTagName("employee");
for (int i = 0; i < employeeElements.getLength(); i++) {
Node employee = employeeElements.item(i);
NamedNodeMap attributes = employee.getAttributes();
stuff1.add(new Employee(Long.parseLong(attributes.getNamedItem("id").getNodeValue()), attributes.getNamedItem("firstName").getNodeValue(), attributes.getNamedItem("lastName").getNodeValue(), attributes.getNamedItem("country").getNodeValue(), Integer.parseInt(attributes.getNamedItem("age").getNodeValue())));
System.out.println(stuff1);
}
return stuff1;
}
}
| true |
f330b9452c152e172e667e1ef1331a30f8dbbbbb | Java | Bezngor/Patterns | /src/basepatterns/creational/abstractFactory/teamNight/TeamManager_Night.java | UTF-8 | 278 | 2.46875 | 2 | [] | no_license | package basepatterns.creational.abstractFactory.teamNight;
import basepatterns.creational.abstractFactory.Manager;
public class TeamManager_Night implements Manager {
@Override
public void manage() {
System.out.println("Manages team of night shift.");
}
}
| true |
cd5bc025e053423e8cd9838e564a46a3051622a8 | Java | marcobehler/09-microservices-the-good-the-bad | /src/test/java/BankStatementImporterTest.java | UTF-8 | 1,728 | 2.359375 | 2 | [] | no_license | import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/*
* This Java source file was auto generated by running 'gradle init --type java-library'
* by 'marco' at '08.06.17 16:27' with Gradle 2.10
*
* @author marco, @date 08.06.17 16:27
*/
public class BankStatementImporterTest {
private Path directory;
@Before
public void setup() throws IOException {
// For a simple file system with Unix-style paths and behavior:
FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
directory = fs.getPath("/ourXmlDirectory");
Files.createDirectory(directory);
}
@Test
public void imports_no_files() throws IOException {
List<Path> paths = new BankStatementImporter().importFiles(directory);
assertThat(paths).hasSize(0);
}
@Test
public void import_xml_file() throws IOException {
Path testXml = directory.resolve("test.xml");
Files.createFile(testXml);
List<Path> paths = new BankStatementImporter().importFiles(directory);
assertThat(paths).hasSize(1);
assertThat(paths).containsExactly(testXml);
}
@Test
public void does_not_import_jpg_file() throws IOException {
Files.createFile(directory.resolve("test.xml"));
Files.createFile(directory.resolve("cat.jpg"));
List<Path> paths = new BankStatementImporter().importFiles(directory);
assertThat(paths).hasSize(1);
}
}
| true |
3f7799bf3c50581f611f2d69dd6862fa8bbbc527 | Java | estevemestre/Programacion1DAW | /Ud11/src/Teatre/Entrada.java | UTF-8 | 569 | 2.578125 | 3 | [] | no_license | package Teatre;
import java.util.Scanner;
public abstract class Entrada {
protected static int idTotal = 0;
protected static Scanner reader = new Scanner (System.in);
protected int id;
protected Zona Zona;
protected String nom;
public Entrada () {
this.id =idTotal +1;
this.idTotal = idTotal + 1;
System.out.println("Introdueix el nom del espectador");
this.nom = reader.nextLine();
System.out.println("Identificador numero "+id);
}
// Fer im metode calcular
}
| true |
99f204c36f73fc038ed7b0ac48485318e5d05338 | Java | isfaaghyth/algorithm-playground | /Shortest Unsorted Continuous Subarray/Solution.java | UTF-8 | 1,367 | 3.65625 | 4 | [] | no_license | // https://leetcode.com/problems/shortest-unsorted-continuous-subarray
//
// Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
// You need to find the shortest such subarray and output its length.
// Example 1:
//
// Input: [2, 6, 4, 8, 10, 9, 15]
// Output: 5
// Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
//
//
// Note:
//
// Then length of the input array is in range [1, 10,000].
// The input array may contain duplicates, so ascending order here means <=.
//
//
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int length = nums.length;
int[] temp = nums.clone();
Arrays.sort(temp);
int f = 0;
int s = length - 1;
if (temp[0] != nums[0] && temp[length - 1] != nums[length - 1]) return length;
for (int i = f; i < length; i++) {
if (nums[i] != temp[i]) {
f = i;
break;
}
}
for (int i = s; i >= 0; i--) {
if (nums[i] != temp[i]) {
s = i;
break;
}
}
if (f == 0 && s == length - 1) return 0;
return s - f + 1;
}
}
| true |
6176c673b964354aa5d08092952564e0ef52ad99 | Java | ParakhJaggi/NutritionTrakr | /FTProject/src/main/java/FitnessTracker/Exceptions/UserNotFoundException.java | UTF-8 | 218 | 2.125 | 2 | [] | no_license | package FitnessTracker.Exceptions;
import java.io.IOException;
/*
* @author Garth Terlizzi III
*/
public class UserNotFoundException extends IOException{
public UserNotFoundException(String message) {
super("message");
}
}
| true |
32b11f1ee6f3be3298f9c746a916b4c50fe5aa0d | Java | Toxidius/MindcrackSurvivalGames | /src/MSG/GameMechanics/ChestLootGenerator.java | UTF-8 | 7,311 | 2.578125 | 3 | [] | no_license | package MSG.GameMechanics;
import java.util.ArrayList;
import java.util.Random;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
public class ChestLootGenerator {
private Random r;
private ArrayList<Material> weaponMaterials;
private ArrayList<Material> armorMaterials;
private ArrayList<Material> foodMaterials;
private ArrayList<Material> miscMaterials;
private ArrayList<Material> rareMaterials;
private ArrayList<Enchantment> bookEnchantments;
public ChestLootGenerator() {
r = new Random();
weaponMaterials = new ArrayList<>();
weaponMaterials.add(Material.WOOD_SWORD);
weaponMaterials.add(Material.STONE_SWORD);
weaponMaterials.add(Material.BOW);
armorMaterials = new ArrayList<>();
armorMaterials.add(Material.GOLD_BOOTS);
armorMaterials.add(Material.GOLD_LEGGINGS);
armorMaterials.add(Material.GOLD_CHESTPLATE);
armorMaterials.add(Material.GOLD_HELMET);
armorMaterials.add(Material.GOLD_BOOTS); // double to decrease chance of iron from spawning
armorMaterials.add(Material.GOLD_LEGGINGS); //
armorMaterials.add(Material.GOLD_CHESTPLATE); //
armorMaterials.add(Material.GOLD_HELMET); //
armorMaterials.add(Material.CHAINMAIL_BOOTS);
armorMaterials.add(Material.CHAINMAIL_LEGGINGS);
armorMaterials.add(Material.CHAINMAIL_CHESTPLATE);
armorMaterials.add(Material.CHAINMAIL_HELMET);
armorMaterials.add(Material.CHAINMAIL_BOOTS); // double to decrease chance of iron from spawning
armorMaterials.add(Material.CHAINMAIL_LEGGINGS); //
armorMaterials.add(Material.CHAINMAIL_CHESTPLATE); //
armorMaterials.add(Material.CHAINMAIL_HELMET); //
armorMaterials.add(Material.IRON_BOOTS);
armorMaterials.add(Material.IRON_LEGGINGS);
armorMaterials.add(Material.IRON_CHESTPLATE);
armorMaterials.add(Material.IRON_HELMET);
foodMaterials = new ArrayList<>();
foodMaterials.add(Material.GRILLED_PORK);
foodMaterials.add(Material.COOKED_BEEF);
foodMaterials.add(Material.BAKED_POTATO);
foodMaterials.add(Material.COOKED_CHICKEN);
miscMaterials = new ArrayList<>();
miscMaterials.add(Material.GOLD_INGOT);
miscMaterials.add(Material.IRON_INGOT);
miscMaterials.add(Material.EXP_BOTTLE);
miscMaterials.add(Material.EXP_BOTTLE);
miscMaterials.add(Material.ARROW);
miscMaterials.add(Material.ARROW);
miscMaterials.add(Material.MILK_BUCKET);
miscMaterials.add(Material.POTION);
miscMaterials.add(Material.SPIDER_EYE);
rareMaterials = new ArrayList<>();
rareMaterials.add(Material.APPLE);
rareMaterials.add(Material.DIAMOND);
rareMaterials.add(Material.ENCHANTED_BOOK);
rareMaterials.add(Material.ENCHANTED_BOOK);
rareMaterials.add(Material.ARROW);
rareMaterials.add(Material.ENDER_PEARL);
rareMaterials.add(Material.GOLD_INGOT);
rareMaterials.add(Material.IRON_INGOT);
bookEnchantments = new ArrayList<>();
bookEnchantments.add(Enchantment.ARROW_DAMAGE);
bookEnchantments.add(Enchantment.DAMAGE_ALL);
bookEnchantments.add(Enchantment.KNOCKBACK);
bookEnchantments.add(Enchantment.PROTECTION_ENVIRONMENTAL);
bookEnchantments.add(Enchantment.PROTECTION_PROJECTILE);
bookEnchantments.add(Enchantment.ARROW_KNOCKBACK);
bookEnchantments.add(Enchantment.ARROW_FIRE);
bookEnchantments.add(Enchantment.FIRE_ASPECT);
}
public void generateChestLoot(Inventory chestInventory){
chestInventory.clear(); // clear out any existing items in the chest
int numItemsToAdd = r.nextInt(6)+4; // 4 to 9 items to add
for (int i = 0; i < numItemsToAdd; i++){
chestInventory.addItem(getRandomItem());
}
chestInventory.addItem(getWeaponItem());
chestInventory.addItem(getFoodItem());
}
public ItemStack getWeaponItem(){
Material material = weaponMaterials.get(r.nextInt(weaponMaterials.size()));
return new ItemStack(material, 1);
}
public ItemStack getArmorItem(){
Material material = armorMaterials.get(r.nextInt(armorMaterials.size()));
return new ItemStack(material, 1);
}
public ItemStack getFoodItem(){
Material material = foodMaterials.get(r.nextInt(foodMaterials.size()));
int amount = r.nextInt(2)+1; // 1 to 2
return new ItemStack(material, amount);
}
public ItemStack getMiscItem(){
Material material = miscMaterials.get(r.nextInt(miscMaterials.size()));
int amount = 1;
if (material == Material.MILK_BUCKET
|| material == Material.POTION
|| material == Material.SPIDER_EYE){
amount = 1;
}
else if (material == Material.GOLD_INGOT
|| material == Material.IRON_INGOT){
amount = r.nextInt(1)+1; // 1 to 2
}
else if (material == Material.EXP_BOTTLE){
amount = r.nextInt(2)+1; // 1 to 2
}
else if (material == Material.ARROW){
amount = r.nextInt(4)+3; // 3 to 6
}
if (material == Material.POTION){
int random = r.nextInt(5);
if (random == 0){
return new ItemStack(material, amount, (short)16421); // healing 2 splash pot
}
else if (random == 1){
return new ItemStack(material, amount, (short)16386); // speed 1 splash pot
}
else if (random == 2){
return new ItemStack(material, amount, (short)16388); // poison 1 splash pot
}
else if (random == 3){
return new ItemStack(material, amount, (short)16385); // regen 1 splash pot (short)
}
else{
return new ItemStack(material, amount, (short)16419); // fire resis splash pot (short)
}
}
return new ItemStack(material, amount);
}
public ItemStack getRareItem(){
Material material = rareMaterials.get(r.nextInt(rareMaterials.size()));
int amount = 1;
if (material == Material.APPLE
|| material == Material.DIAMOND
|| material == Material.ENCHANTED_BOOK
|| material == Material.ENDER_PEARL){
amount = 1;
}
else if (material == Material.GOLD_INGOT){
amount = r.nextInt(2)+1; // 1 to 2
}
else if (material == Material.IRON_INGOT){
amount = r.nextInt(2)+1; // 1 to 2
}
else if (material == Material.ARROW){
amount = r.nextInt(4)+3; // 3 to 6
}
if (material == Material.ENCHANTED_BOOK){
return getEnchantedBookItem();
}
return new ItemStack(material, amount);
}
public ItemStack getRandomItem(){
int random = r.nextInt(100);
if (random <= 10){ // 10%
return getFoodItem();
}
else if (random <= 15){ // 5%
return getWeaponItem();
}
else if (random <= 35){ // 20%
return getArmorItem();
}
else if (random <= 75){ // 40%
return getMiscItem();
}
else if (random <= 100){ // 25%
return getRareItem();
}
else{
// should never occur
return getFoodItem();
}
}
public ItemStack getEnchantedBookItem(){
ItemStack book = new ItemStack(Material.ENCHANTED_BOOK, 1);
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) book.getItemMeta();
Enchantment enchantment = bookEnchantments.get(r.nextInt(bookEnchantments.size()));
int level = 1;
if (enchantment.equals(Enchantment.KNOCKBACK)){
level = 3;
}
meta.addStoredEnchant(enchantment, level, true);
book.setItemMeta(meta);
return book;
}
}
| true |
15139dbb5e6cfeb840c7fe82e032d3dd466b5c81 | Java | MykhailoMike/programming_patterns | /src/main/java/com/mkaloshyn/behavioral/iterator_16/Playlist.java | UTF-8 | 925 | 3.46875 | 3 | [] | no_license | package main.java.com.mkaloshyn.behavioral.iterator_16;
public class Playlist implements Collection {
private String name;
private String[] tracks;
public Playlist(String name, String[] tracks) {
this.name = name;
this.tracks = tracks;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getTracks() {
return tracks;
}
public void setTracks(String[] tracks) {
this.tracks = tracks;
}
@Override
public Iterator getIterator() {
return new TrackIterator();
}
private class TrackIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
return index<tracks.length;
}
@Override
public Object next() {
return tracks[index++];
}
}
}
| true |
3e7256ca735b75d7fe579fc0ab60adbfa5cf0d6e | Java | osdbl/osd-edu | /edu-04/src/main/java/net/croz/osd/edu/shapes/Triangle.java | UTF-8 | 367 | 2.828125 | 3 | [] | no_license | package net.croz.osd.edu.shapes;
public class Triangle extends RegularPoligon {
@Override
public double area() {
return super.area()*Math.sqrt(3)/4;
}
@Override
public double perimeter() {
return 3*sideLength;
}
@Override
public ShapeType getType() {
return ShapeType.EQUILATERAL_TRIANGLE;
}
@Override
public double angle() {
return 60;
}
}
| true |
c3ef73467273a37435dffaed4d20880328c823ba | Java | jamesmarva/SuccessLeetCode | /src/leet0801to1000/problem0852/PeakIndexInMountainArray0852.java | UTF-8 | 669 | 2.9375 | 3 | [] | no_license | package leet0801to1000.problem0852;
/**
* @program: SuccessLeetCode
* @description: https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/
* @author: James
* @create: 2019-09-15 14:05
**/
public class PeakIndexInMountainArray0852 {
public int peakIndexInMountainArray(int[] A) {
int length = A.length;
int maxIndex = 0;
for (int i = 0; i < length; i++) {
if (i == length - 1) {
return i;
}
if (A[i] < A[i + 1]) {
continue;
} else {
maxIndex = i;
break;
}
}
return maxIndex;
}
}
| true |
2ae8790885b7d75461fdaccf483c39b803ad3bab | Java | ilhamfarabi/Bomb-Kicker | /BouncingBall/src/com/example/bouncingball/BouncingBallView.java | ISO-8859-1 | 5,170 | 3 | 3 | [] | no_license | package com.example.bouncingball;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Author: pingpabar
*/
class BouncingBallView extends SurfaceView implements SurfaceHolder.Callback {
// El atributo bbThread se utiliza para hacer referencia al hilo que controla la animacin
private BouncingBallAnimationThread bbThread = null;
// Atributos a la clase SurfaceView
// Estos atributos definen las propiedades de la pelota - su posicin actual (inicialmente en
// el centro de la pantalla), su direccin de movimiento (puedes experimentar probando
// diferentes valores), su tamao y su color.
private int xPosition = getWidth()/2;
private int yPosition = getHeight()/2;
private int xDirection = 20;
private int yDirection = 40;
private static int radius = 20;
private static int ballColor = Color.RED;
public BouncingBallView(Context ctx, AttributeSet attrs, int defStyle) {
super(ctx, attrs, defStyle);
// El constructor incluye un registro del escuchador de evento.
getHolder().addCallback(this);
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Este mtodo define cada paso de la animacin. En primer lugar, se borra la pantalla
// pintando de negro y luego muestra la bola como un crculo en su ubicacin actual.
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
paint.setColor(ballColor);
canvas.drawCircle(xPosition, yPosition, radius, paint);
}
/**
* El mtodo surfaceCreated() genera e inicia el hilo de control (a menos que ya exista) cuando la
* superficie a la vista es creada
*/
public void surfaceCreated(SurfaceHolder holder) {
if (bbThread != null)
return;
bbThread = new BouncingBallAnimationThread(getHolder());
bbThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* Detendr el hilo cuando la superficie se destruye.
*/
public void surfaceDestroyed(SurfaceHolder holder) {
bbThread.stop = true;
}
/**
* El usuario puede parar la pelota al tocar la pantalla. Un segundo toque en la pantalla pone
* el baln en movimiento otra vez - a partir de su posicin actual en la direccin del punto
* de contacto.
*
* Recuerda que tocar una vista provoca la ejecucin del mtodo de la vista onTouchEvent(). La
* pelota debe ser detenida, simplemente definiendo xDirectiony yDirection a cero, es decir,
* el hilo debe seguir corriendo pero temporalmente no mover la pelota. Luego, la pelota se
* reinicia asignando nuevos valores a las dos variables. Estas acciones slo deben llevarse
* a cabo si el evento es de tipo MotionEvent.ACTION_DOWN.
*/
public boolean onTouchEvent (MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN) return false;
if (xDirection!=0 || yDirection!=0)
xDirection = yDirection = 0;
else {
xDirection = (int) event.getX() - xPosition;
yDirection = (int) event.getY() - yPosition;
}
return true;
}
/**
* Esto define las acciones del hilo animacin. El constructor inicializa el SurfaceHolder
* con el valor del parmetro que viene de surfaceCreated() en BouncingBallView. Ser
* necesario para acceder a la SurfaceView. El bucle en el mtodo run() se ejecuta hasta que
* es detenido por surfaceDestroyed() en BouncingBallView. En primer lugar, calcula la nueva
* posicin de la bola movindola en la direccin dada por xDirection e yDirection. Las
* declaraciones if hacen que rebote la pelota cuando se alcanza uno de los bordes de la
* pantalla. Despus de estos clculos, el hilo se apodera del Canvas para dibujar y llama
* al onDraw() de la vista para obtener una nueva salida. La llamada final a
* unlockCanvasAndPost() hace que el nuevo grfico aparece en la pantalla.
*/
@SuppressLint("WrongCall")
private class BouncingBallAnimationThread extends Thread {
public boolean stop = false;
private SurfaceHolder surfaceHolder;
public BouncingBallAnimationThread(SurfaceHolder surfaceHolder) {
this.surfaceHolder = surfaceHolder;
}
public void run() {
while (!stop) {
xPosition += xDirection;
yPosition += yDirection;
if (xPosition < 0) {
xDirection = -xDirection;
xPosition = radius;
}
if (xPosition > getWidth() - radius) {
xDirection = -xDirection;
xPosition = getWidth() - radius;
}
if (yPosition < 0) {
yDirection = -yDirection;
yPosition = radius;
}
if (yPosition > getHeight() - radius) {
yDirection = -yDirection;
yPosition = getHeight() - radius - 1;
}
Canvas c = null;
try {
c = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
onDraw(c);
//draw(c);
}
} finally {
if (c != null)
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
| true |
b6589a27c309189689e718bba9900a3dc8c7cae2 | Java | subramanyamgv/CarBuyMVP | /app/src/androidTest/java/app/subbu/carbuy/CarSelectionActivityEspressoTest.java | UTF-8 | 608 | 1.710938 | 2 | [
"MIT"
] | permissive | package app.subbu.carbuy;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import app.subbu.carbuy.activity.CarSelectionActivity;
/**
* Created by Subramanyam on 23-Jan-2017.
*/
@RunWith(AndroidJUnit4.class)
public class CarSelectionActivityEspressoTest {
@Rule
public ActivityTestRule<CarSelectionActivity> mActivityRule =
new ActivityTestRule<>(CarSelectionActivity.class);
@Test
public void ensureManufacturerTextInputWorks() {
}
}
| true |
95c1292a5e3871443862d286265b68fb9563210d | Java | nju-Nicko/leetcode-solutions | /src/main/java/com/huawei/nlz/leetcode/solution/Integer2Roman.java | UTF-8 | 3,665 | 3.890625 | 4 | [] | no_license | package com.huawei.nlz.leetcode.solution;//罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
//
// 字符 数值
//I 1
//V 5
//X 10
//L 50
//C 100
//D 500
//M 1000
//
// 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
//
// 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
//
//
// I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
// X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
// C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
//
//
// 给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
//
// 示例 1:
//
// 输入: 3
//输出: "III"
//
// 示例 2:
//
// 输入: 4
//输出: "IV"
//
// 示例 3:
//
// 输入: 9
//输出: "IX"
//
// 示例 4:
//
// 输入: 58
//输出: "LVIII"
//解释: L = 50, V = 5, III = 3.
//
//
// 示例 5:
//
// 输入: 1994
//输出: "MCMXCIV"
//解释: M = 1000, CM = 900, XC = 90, IV = 4.
// Related Topics 数学 字符串
import java.util.ArrayList;
import java.util.List;
public class Integer2Roman {
public String intToRoman(int num) {
if (num < 1 || num > 3999) {
throw new IllegalArgumentException("invalid input");
}
int ms = num / 1000; // num里有几个千
num = num % 1000;
int cms = num / 900; // num里有几个900
num = num % 900;
int ds = num / 500; // num里有几个500;
num = num % 500;
int cds = num / 400; // num里有几个400;
num = num % 400;
int cs = num / 100; // num里有几个100;
num = num % 100;
int xcs = num / 90; // num里有几个90
num = num % 90;
int ls = num / 50; // num里有几个50;
num = num % 50;
int xls = num / 40; // num里有几个40
num = num % 40;
int xs = num / 10; // num里有几个10
num = num % 10;
int ixs = num / 9; // num里有几个9
num = num % 9;
int vs = num / 5; //num里有几个5
num = num % 5;
int ivs = num / 4; // num里有几个4
num = num % 4;
int is = num; //还剩几个1
List<Tuple> tuples = new ArrayList<>();
tuples.add(new Tuple("M", ms));
tuples.add(new Tuple("CM", cms));
tuples.add(new Tuple("D", ds));
tuples.add(new Tuple("CD", cds));
tuples.add(new Tuple("C", cs));
tuples.add(new Tuple("XC", xcs));
tuples.add(new Tuple("L", ls));
tuples.add(new Tuple("XL", xls));
tuples.add(new Tuple("X", xs));
tuples.add(new Tuple("IX", ixs));
tuples.add(new Tuple("V", vs));
tuples.add(new Tuple("IV", ivs));
tuples.add(new Tuple("I", is));
StringBuilder sb = new StringBuilder();
for (Tuple tuple : tuples) {
int counter = tuple.repeat;
for (int i = 1; i <= counter; i++) {
sb.append(tuple.str);
}
}
return sb.toString();
}
private static class Tuple {
private String str;
private int repeat;
public Tuple(String str, int times) {
this.str = str;
repeat = times;
}
}
}
| true |
cbdc1e1e2b4da892f93f3581f7038d8bcae9866e | Java | vectorforce/Graph-editor | /src/com/vectorforce/view/dialogs/choisedialogs/ChooseArcDialog.java | UTF-8 | 7,419 | 2.40625 | 2 | [] | no_license | package com.vectorforce.view.dialogs.choisedialogs;
import com.vectorforce.controller.Controller;
import com.vectorforce.model.Arc;
import com.vectorforce.view.graphics.GraphicComponent;
import com.vectorforce.view.setup.ColorSetupComponent;
import com.vectorforce.view.setup.FontSetupComponent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
public class ChooseArcDialog {
private Display display;
private Shell shell;
private final Arc arc;
private CommonPartChooseDialog commonPartChooseDialog;
public ChooseArcDialog(Display display, Controller controller, GraphicComponent graphicComponent, Arc arc) {
commonPartChooseDialog = new CommonPartChooseDialog(controller, graphicComponent);
this.arc = arc;
this.display = display;
shell = new Shell(display, SWT.CLOSE | SWT.APPLICATION_MODAL);
shell.setText("Выберите тип");
final String imagePath = "src/resources/";
shell.setImage(new Image(display, imagePath + "graph.png"));
shell.setLayout(new GridLayout(1, true));
shell.setBackground(ColorSetupComponent.getMainWindowsColor());
initButtons();
run();
}
private void run() {
shell.pack();
final Rectangle screenSize = display.getPrimaryMonitor().getBounds();
shell.setLocation((screenSize.width - shell.getBounds().width) / 2, (screenSize.height - shell.getBounds().height) / 2);
shell.open();
while (!shell.isDisposed()) {
if (display.readAndDispatch()) {
display.sleep();
}
}
}
private void initButtons() {
Composite compositeTypesButtons = new Composite(shell, SWT.NONE);
compositeTypesButtons.setLayout(new GridLayout(2, true));
compositeTypesButtons.setBackground(ColorSetupComponent.getWindowsCompositesForegroundColor());
Group compositeOriented = new Group(compositeTypesButtons, SWT.NONE);
compositeOriented.setBackground(ColorSetupComponent.getWindowsCompositesForegroundColor());
compositeOriented.setForeground(ColorSetupComponent.getButtonsForegroundColor());
compositeOriented.setText("Ориентированная");
compositeOriented.setLayout(new GridLayout(1, false));
Button buttonOriented = new Button(compositeOriented, SWT.TOGGLE);
commonPartChooseDialog.addButton(buttonOriented);
buttonOriented.setText("-------->");
Button buttonOrientedBinary = new Button(compositeOriented, SWT.TOGGLE);
commonPartChooseDialog.addButton(buttonOrientedBinary);
buttonOrientedBinary.setText("========>");
Group compositeNonOriented = new Group(compositeTypesButtons, SWT.NONE);
compositeNonOriented.setForeground(ColorSetupComponent.getButtonsForegroundColor());
compositeNonOriented.setBackground(ColorSetupComponent.getWindowsCompositesForegroundColor());
compositeNonOriented.setText("Неориентированная");
compositeNonOriented.setLayout(new GridLayout(1, true));
Button buttonNonOriented = new Button(compositeNonOriented, SWT.TOGGLE);
commonPartChooseDialog.addButton(buttonNonOriented);
buttonNonOriented.setText("---------");
Button buttonNonOrientedBinary = new Button(compositeNonOriented, SWT.TOGGLE);
commonPartChooseDialog.addButton(buttonNonOrientedBinary);
buttonNonOrientedBinary.setText("========");
Composite compositeOK = new Composite(shell, SWT.NONE);
compositeOK.setBackground(ColorSetupComponent.getMainWindowsColor());
compositeOK.setLayout(new GridLayout(1, false));
compositeOK.setLayoutData(new GridData(SWT.END, SWT.FILL, true, true));
Button buttonOK = new Button(compositeOK, SWT.PUSH | SWT.BORDER);
buttonOK.setBackground(ColorSetupComponent.getMainWindowsColor());
buttonOK.setForeground(ColorSetupComponent.getButtonsForegroundColor());
buttonOK.setFont(FontSetupComponent.getButtonsFont());
buttonOK.setText("Выбрать");
GridData buttonOKData = new GridData(SWT.END, SWT.CENTER, false, false);
buttonOKData.widthHint = 120;
buttonOKData.heightHint = 40;
buttonOK.setLayoutData(buttonOKData);
// Listeners
buttonOriented.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
commonPartChooseDialog.removeSelection();
buttonOriented.setSelection(true);
}
});
buttonOrientedBinary.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
commonPartChooseDialog.removeSelection();
buttonOrientedBinary.setSelection(true);
}
});
buttonNonOriented.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
commonPartChooseDialog.removeSelection();
buttonNonOriented.setSelection(true);
}
});
buttonNonOrientedBinary.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
commonPartChooseDialog.removeSelection();
buttonNonOrientedBinary.setSelection(true);
}
});
buttonOK.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (Button currentButton : commonPartChooseDialog.getButtons()) {
if (currentButton.getSelection()) {
if (currentButton == buttonOriented) {
commonPartChooseDialog.getController().setOriented(arc, true);
commonPartChooseDialog.getController().setBinary(arc, false);
break;
} else if (currentButton == buttonNonOriented) {
commonPartChooseDialog.getController().setOriented(arc, false);
commonPartChooseDialog.getController().setBinary(arc, false);
break;
} else if (currentButton == buttonOrientedBinary) {
commonPartChooseDialog.getController().setOriented(arc, true);
commonPartChooseDialog.getController().setBinary(arc, true);
break;
} else if (currentButton == buttonNonOrientedBinary) {
commonPartChooseDialog.getController().setOriented(arc, false);
commonPartChooseDialog.getController().setBinary(arc, true);
break;
}
}
}
commonPartChooseDialog.getGraphicComponent().redraw();
shell.close();
}
});
}
}
| true |
3597bf01b54337fa0b53ea53ec01dcae6a00b16a | Java | wbigno/Java-RestAssured-Cucumber | /src/test/java/StepFiles/HourlyStepdefs.java | UTF-8 | 3,088 | 2.359375 | 2 | [] | no_license | package StepFiles;
import cucumber.api.Scenario;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.restassured.response.Response;
import static io.restassured.path.json.JsonPath.from;
import org.testng.Assert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
public class HourlyStepdefs {
Scenario scenario;
Response response;
List<Integer> windchill = null;
List<Integer> feelslike = null;
String jsonAsString;
@Given("^Using the api for the hourly forecast \"([^\"]*)\" to get details to test$")
public void UsingTheApiForTheHourlyForecastToGetDetailsToTest(String arg0) {
response = given().get(arg0);
}
@When("^I confirm the status as (\\d+)$")
public void iConfirmTheStatusAs(int arg0) {
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, arg0);
}
@Then("^I will confirm a response is received and formatted in a json format$")
public void iWillConfirmAResponseIsReceivedAndFormattedInAJsonFormat() {
String actual = response.getContentType();
Assert.assertEquals(actual, "application/json; charset=UTF-8");
}
@When("^I get the windchill and the feelslike readings to compare them$")
public void iGetTheWindchillAndTheFeelslikeReadingsToCompareThem() {
windchill = response.jsonPath().get("hourly_forecast.windchill.english");
feelslike = response.jsonPath().get("hourly_forecast.feelslike.english");
}
@Then("^I will confirm that the match$")
public void iWillConfirmThatTheMatch() {
if (windchill.size() == feelslike.size()) {
int list = windchill.size();
for (int i = 0; i < list; i++) {
Assert.assertEquals(windchill.get(i), feelslike.get(i));
}
}else { scenario.write("Unable to compare lists as they did match up in size equally");
}
}
@When("^I get the hourly forecast I will compare it to the schema saved for this response$")
public void iGetTheHourlyForecastIWillCompareItToTheSchemaSavedForThisResponse() {
given().get("http://api.wunderground.com/api/99a8db9a0f3c2e31/hourly/q/IL/Chicago.json").then().
assertThat().body(matchesJsonSchemaInClasspath("hourly.json"));
}
@When("^I get the response, I will convert it to a String$")
public void iGetTheResponseIWillConvertItToAString() {
jsonAsString = response.asString();
Assert.assertNotNull(jsonAsString);
}
@Then("^I will convert the string into an array where I can assert the correct number of entities in the response$")
public void iWillConvertTheStringIntoAnArrayWhereICanAssertTheCorrectNumberOfEntitiesInTheResponse() {
HashMap<Object,Map<String,?>> jsonAsArrayList = from(jsonAsString).get("");
Assert.assertEquals(jsonAsArrayList.size(), 2);
}
}
| true |
883f263f72d93959639e0fadf532c21b6628975b | Java | cha63506/CompSecurity | /Music-Audio/livemix_tapes_source/src/com/google/android/gms/fitness/result/DataStatsResult.java | UTF-8 | 1,253 | 1.53125 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.fitness.result;
import android.os.Parcel;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import java.util.List;
// Referenced classes of package com.google.android.gms.fitness.result:
// zzf
public class DataStatsResult
implements Result, SafeParcelable
{
public static final android.os.Parcelable.Creator CREATOR = new zzf();
private final int mVersionCode;
private final Status zzQA;
private final List zzaqM;
DataStatsResult(int i, Status status, List list)
{
mVersionCode = i;
zzQA = status;
zzaqM = list;
}
public int describeContents()
{
return 0;
}
public Status getStatus()
{
return zzQA;
}
int getVersionCode()
{
return mVersionCode;
}
public void writeToParcel(Parcel parcel, int i)
{
zzf.zza(this, parcel, i);
}
List zzsF()
{
return zzaqM;
}
}
| true |
7f891b3a99b1827d2706e8f1d85b9ec44b0c1630 | Java | stinymac/samples | /sample-core-java/src/main/java/org/mac/sample/corejava/concurrency/pattern/count_down/CountDown.java | UTF-8 | 1,080 | 2.671875 | 3 | [] | no_license | /*
* ( (
* )\ ) ( )\ ) ) (
* ( ( (()/( ))\( ((_| /( /(( ))\
* )\ )\ ((_))((_)\ _ )(_)|_))\ /((_)
* ((_|(_) _| (_))((_) ((_)__)((_|_))
* / _/ _ \/ _` / -_|_-< / _` \ V // -_)
* \__\___/\__,_\___/__/_\__,_|\_/ \___|
*
* 东隅已逝,桑榆非晚。(The time has passed,it is not too late.)
* 虽不能至,心向往之。(Although I can't, my heart is longing for it.)
*
*/
package org.mac.sample.corejava.concurrency.pattern.count_down;
/**
*
* @author Mac
* @create 2018-06-06 15:52
**/
public class CountDown {
private final int total;
private volatile int counter = 0;
public CountDown(int total) {
this.total = total;
}
public void down () {
synchronized (this) {
counter++;
if (counter == total) {
notifyAll();
}
}
}
public void await() throws InterruptedException {
synchronized (this) {
while (counter != total) {
this.wait();
}
}
}
}
| true |
2f1314623bdeb78f16a29ecbd0b591cbf4b2fd70 | Java | macalinao/MattMG | /src/main/java/com/simplyian/cloudgame/gameplay/hostedffa/listeners/FFAGamePlayerListener.java | UTF-8 | 6,307 | 2.1875 | 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.simplyian.cloudgame.gameplay.hostedffa.listeners;
import com.simplyian.cloudgame.events.GameJoinEvent;
import com.simplyian.cloudgame.events.GameLeaveEvent;
import com.simplyian.cloudgame.events.GameQuitEvent;
import com.simplyian.cloudgame.events.GameSpectateEvent;
import com.simplyian.cloudgame.events.GameUnspectateEvent;
import com.simplyian.cloudgame.game.Game;
import com.simplyian.cloudgame.gameplay.hostedffa.HostedFFA;
import com.simplyian.cloudgame.gameplay.hostedffa.HostedFFAState;
import com.simplyian.cloudgame.gameplay.GameListener;
import com.simplyian.cloudgame.util.Messaging;
import me.confuser.barapi.BarAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
/**
*
* @author ian
*/
public class FFAGamePlayerListener extends GameListener<HostedFFAState> {
public FFAGamePlayerListener(HostedFFA koth) {
super(koth);
}
@EventHandler
public void onGameJoin(GameJoinEvent event) {
Game<HostedFFAState> game = game(event);
if (game == null) {
return;
}
HostedFFAState state = game.getState();
Player p = event.getPlayer();
if (state.isStarted()) {
game.getGameplay().sendGameMessage(p, "You can't join a " + getGameplay().getId() + " that is already in progress.");
return;
}
if (state.hasPlayer(p)) {
game.getGameplay().sendGameMessage(p, "You have already joined the " + getGameplay().getId() + " queue!");
return;
}
if (state.getHost() != null && state.getHost().equals(p)) {
game.getGameplay().sendGameMessage(p, "You can't join the game if you are the host!");
return;
}
state.addPlayer(p);
getGameplay().sendBanner(p, "You've joined the " + getGameplay().getId() + "! Pay attention to the countdown.",
"Want to leave the game? Type $D/" + getGameplay().getId() + " leave$L!");
}
@EventHandler
public void onGameLeave(GameLeaveEvent event) {
Game<HostedFFAState> game = game(event);
if (game == null) {
return;
}
HostedFFAState state = game.getState();
Player p = event.getPlayer();
if (!state.isStarted()) {
if (!state.hasPlayer(p)) {
game.getGameplay().sendGameMessage(p, "You aren't part of the " + getGameplay().getId() + " queue.");
return;
}
state.removePlayer(p);
game.getGameplay().sendGameMessage(p, "You've left the " + getGameplay().getId() + ". To rejoin, type $H/koth join$M!");
return;
}
// Kills check
boolean failedKillsCheck = game.getStats().getKillCount(p) == 0;
// Distance check
boolean failedDistanceCheck = false;
for (Player player : state.getPlayers()) {
if (p.getWorld().equals(player.getWorld()) && p.getLocation().distanceSquared(player.getLocation()) < 20 * 20) {
failedDistanceCheck = true;
break;
}
}
if (failedKillsCheck) {
game.getGameplay().sendGameMessage(p, "You must kill at least one person before leaving!");
}
if (failedDistanceCheck) {
game.getGameplay().sendGameMessage(p, "You must be at least 20 blocks away from another player!");
}
if (!failedKillsCheck && !failedDistanceCheck) {
game.getState().removePlayer(p);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + p.getName());
BarAPI.removeBar(p);
game.getGameplay().sendGameMessage(p, "You have left the game.");
}
}
@EventHandler
public void onGameQuit(GameQuitEvent event) {
Game<HostedFFAState> game = game(event);
if (game == null) {
return;
}
Player p = event.getPlayer();
if (game.getState().isProvideArmor()) {
getGameplay().getPlugin().getPlayerStateManager().queueLoadState(event.getPlayer());
}
p.setGameMode(GameMode.SURVIVAL);
game.getState().removePlayer(p);
BarAPI.removeBar(p);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + p.getName());
}
@EventHandler
public void onGameSpectate(GameSpectateEvent event) {
Game<HostedFFAState> game = game(event);
if (game == null) {
return;
}
Player p = event.getPlayer();
if (!game.getState().isStarted()) {
p.sendMessage(ChatColor.RED + "The game hasn't started yet!");
return;
}
if (game.getState().hasPlayer(p)) {
p.sendMessage(ChatColor.RED + "You can't use this command as a player!");
return;
}
getGameplay().getPlugin().getPlayerStateManager().saveState(p);
game.getState().addSpectator(p);
for (Player other : Bukkit.getOnlinePlayers()) {
other.hidePlayer(p);
}
p.teleport(game.getArena().getNextSpawn());
p.setAllowFlight(true);
p.setFlying(true);
p.setHealth(p.getMaxHealth());
p.setFoodLevel(20);
game.getGameplay().sendGameMessage(p, "Type /" + getGameplay().getId() + " spectate again to exit the mode!");
}
@EventHandler
public void onGameUnspectate(GameUnspectateEvent event) {
Game<HostedFFAState> game = game(event);
if (game == null) {
return;
}
Player p = event.getPlayer();
game.getState().removeSpectator(p);
getGameplay().getPlugin().getPlayerStateManager().queueLoadState(p);
for (Player other : Bukkit.getOnlinePlayers()) {
other.showPlayer(p);
}
p.setFlying(false);
BarAPI.removeBar(p);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + p.getName());
game.getGameplay().sendGameMessage(p, "You are no longer spectating the game.");
}
}
| true |
689a073f085eac9a86e34f4e9c74220da953dc3a | Java | carlosmast23/codefac-codesoft | /codefac-web/src/main/java/ec/com/codesoft/web/admin/ordenTrabajo/GestionarOrdenTrabajoMB.java | UTF-8 | 5,473 | 1.773438 | 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 ec.com.codesoft.web.admin.ordenTrabajo;
import ec.com.codesoft.model.DetalleOrdenTrabajo;
import ec.com.codesoft.model.OrdenTrabajo;
import ec.com.codesoft.modelo.servicios.OrdenTrabajoServicio;
import ec.com.codesoft.modelo.servicios.SistemaServicio;
import ec.com.codesoft.web.reportes.ordenTrabajo.OrdenTrabajoDetalleReporte;
import ec.com.codesoft.web.reportes.ordenTrabajo.OrdenTrabajoReporte;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import net.sf.jasperreports.engine.JRException;
import org.primefaces.context.RequestContext;
/**
*
* @author carlo
*/
@ManagedBean
@ViewScoped
public class GestionarOrdenTrabajoMB implements Serializable
{
@EJB
private OrdenTrabajoServicio ordenTrabajoServicio;
private List<OrdenTrabajo> ordenTrabajoList;
private List<OrdenTrabajo> ordenTrabajoFiltro;
private List<DetalleOrdenTrabajo> detalleOrdenTrabajo;
private OrdenTrabajo ordenTrabajo;
@EJB
private SistemaServicio sistemaServicio;
@PostConstruct
public void postCostruct()
{
ordenTrabajoList=ordenTrabajoServicio.obtenerOrdenesTrabajoAll();
for (OrdenTrabajo ordenTrabajoList1 : ordenTrabajoList) {
System.out.println("Ordenes "+ ordenTrabajoList1.getEstado());
}
}
public void devolverDetalleOrdenTrabajo(OrdenTrabajo ordenEnviada){
System.out.println("DEtalle");
detalleOrdenTrabajo=ordenEnviada.getDetalleOrdenTrabajoList();
RequestContext.getCurrentInstance().execute("PF('dlgDetallesOrdenTrabajo').show()");
}
public void imprimir(OrdenTrabajo ordenTrabajo)
{
this.ordenTrabajo=ordenTrabajo;
generaPdf();
}
public void generaPdf() {
System.out.println("generando pdf..");
OrdenTrabajoReporte orden = new OrdenTrabajoReporte(sistemaServicio.getConfiguracion().getPathreportes());
orden.setEmpresa(sistemaServicio.getEmpresa());
orden.setAbono(ordenTrabajo.getAdelanto().toString());
orden.setCedula(ordenTrabajo.getCedulaRuc().getCedulaRuc());
SimpleDateFormat formateador = new SimpleDateFormat("EEEE d MMMM HH:mm:ss");
orden.setFechaRecepcion(formateador.format(ordenTrabajo.getFechaEntrega()).toString());
orden.setMonto(ordenTrabajo.getTotal().toString());
orden.setNombre(ordenTrabajo.getCedulaRuc().getNombre());
orden.setObservacion(ordenTrabajo.getObservacion().toString());
orden.setOrdenTrabajo(ordenTrabajo.getIdOrdenTrabajo().toString());
orden.setSaldo(ordenTrabajo.getTotal().subtract(ordenTrabajo.getAdelanto()).toString());
orden.setTelefono(ordenTrabajo.getCedulaRuc().getTelefono());
orden.setNotasOrden(sistemaServicio.getConfiguracion().getNotasOrden());
List<DetalleOrdenTrabajo> lista = ordenTrabajo.getDetalleOrdenTrabajoList();
for (DetalleOrdenTrabajo detalle : lista) {
OrdenTrabajoDetalleReporte detalleReporte = new OrdenTrabajoDetalleReporte();
detalleReporte.setDescripcion(detalle.getDescripcion());
detalleReporte.setNombre(detalle.getEquipo());
detalleReporte.setPrecio(detalle.getPrecio().toString());
detalleReporte.setProblema(detalle.getProblema());
detalleReporte.setTrabajoRealizar(detalle.getTrabajoRealizar());
orden.getDetalles().add(detalleReporte);
}
try {
orden.exportarPDF();
System.out.println("pdf generado");
} catch (JRException ex) {
Logger.getLogger(OrdenTrabajoMB.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(OrdenTrabajoMB.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void anular(OrdenTrabajo orden)
{
ordenTrabajoServicio.anularOrdenTrabajo(orden);
}
public List<OrdenTrabajo> getOrdenTrabajoList() {
return ordenTrabajoList;
}
public void setOrdenTrabajoList(List<OrdenTrabajo> ordenTrabajoList) {
this.ordenTrabajoList = ordenTrabajoList;
}
public List<OrdenTrabajo> getOrdenTrabajoFiltro() {
return ordenTrabajoFiltro;
}
public void setOrdenTrabajoFiltro(List<OrdenTrabajo> ordenTrabajoFiltro) {
this.ordenTrabajoFiltro = ordenTrabajoFiltro;
}
public OrdenTrabajo getOrdenTrabajo() {
return ordenTrabajo;
}
public void setOrdenTrabajo(OrdenTrabajo ordenTrabajo) {
this.ordenTrabajo = ordenTrabajo;
}
public List<DetalleOrdenTrabajo> getDetalleOrdenTrabajo() {
return detalleOrdenTrabajo;
}
public void setDetalleOrdenTrabajo(List<DetalleOrdenTrabajo> detalleOrdenTrabajo) {
this.detalleOrdenTrabajo = detalleOrdenTrabajo;
}
}
| true |
06d1119f8d8069e57404f471d8078f74f59c4d90 | Java | wuxiangwuxiang/CMS | /src/main/java/com/qdu/controller/StudentInfoController.java | UTF-8 | 4,750 | 2.171875 | 2 | [] | no_license | package com.qdu.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.map.HashedMap;
import org.aspectj.weaver.ast.Var;
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 com.qdu.aop.SystemLog;
import com.qdu.pojo.ClazzStu;
import com.qdu.pojo.Course;
import com.qdu.pojo.Message;
import com.qdu.pojo.Student;
import com.qdu.pojo.StudentInfo;
import com.qdu.pojo.Teacher;
import com.qdu.service.ClazzService;
import com.qdu.service.ClazzStuService;
import com.qdu.service.CourseService;
import com.qdu.service.MessageService;
import com.qdu.service.StudentInfoService;
import com.qdu.service.StudentService;
import com.qdu.service.TeacherService;
import com.qdu.serviceimpl.ClazzServiceImpl;
import com.qdu.util.MD5Util;
@Controller
@RequestMapping(value = "/studentInfo")
public class StudentInfoController {
@Autowired
StudentInfoService studentInfoServiceImpl;
@Autowired
StudentService studentServiceImpl;
@Autowired
private TeacherService teacherServiceImpl;
@Autowired
private MessageService messageServiceImpl;
@Autowired
private CourseService courseServiceImpl;
@Autowired
private ClazzStuService clazzStuServiceImpl;
@Autowired ClazzService clazzServiceImpl;
// 添加学生——课程 中间表
@SystemLog(module = "中间表", methods = "日志管理-添加中间表")
@RequestMapping(value = "/insertStudentInfo.do")
public String insertStudentInfo(StudentInfo studentInfo, HttpServletRequest request) {
String studentRoNo = request.getParameter("studentRoNo");
String password = request.getParameter("studentPassword");
String courseId = request.getParameter("courseId");
Student student = studentServiceImpl.selectStudentByNo(studentRoNo);
if (student != null && MD5Util.md5(password, "juin").equals(student.getStudentPassword())) {
System.out.println("芝麻开门");
StudentInfo studentInfo2 = studentInfoServiceImpl.selectStudentInfoByMany(studentRoNo,
Integer.parseInt(courseId));
if (studentInfo2 == null) {
studentInfoServiceImpl.insertStudentInfo(studentRoNo, Integer.parseInt(courseId));
}
System.out.println(222);
int clazzId = Integer.parseInt(request.getParameter("clazzId"));
if (clazzId != 0) {
clazzStuServiceImpl.insertClazzStu(clazzId,studentRoNo);
}
return "success";
} else {
return "failer";
}
}
// 添加学生——课程 中间表
@SystemLog(module = "教师", methods = "日志管理-添加学生")
@RequestMapping(value = "/insertStudentInfoByteacher.do")
@ResponseBody
public Map<String, Object> insertStudentInfoByteacher(String content,String teacherMobile, String studentRoNo,
HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
int tem = 0;
for(int i = 0; i < content.length(); i ++){
if(content.charAt(i) == 'c'){
tem = i;
break;
}
}
String aa = content.substring(0, tem);
String bb = content.substring(tem+1);
int courseId = Integer.parseInt(aa);
int clazzId = Integer.parseInt(bb);
StudentInfo studentInfo2 = studentInfoServiceImpl.selectStudentInfoByMany(studentRoNo,courseId);
if (studentInfo2 == null) {
if (clazzId != 0) {
int tem2 = clazzStuServiceImpl.insertClazzStu(clazzId,studentRoNo);
System.out.println(tem2);
if(tem2 > 0){
studentInfoServiceImpl.insertStudentInfo(studentRoNo,courseId);
}
}
Teacher teacher = teacherServiceImpl.selectTeacherByEmail(teacherMobile);
String time = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
Message message = new Message();
Course course = courseServiceImpl.selectCourseById(courseId);
message.setMessageSender(teacherMobile);
message.setMessageAccepter(studentRoNo);
message.setMessageTitle(teacher.getTeacherName() + "老师同意你加入课程< " + course.getCourseName() +
">(" + course.getCurrentYear() + "/" + course.getSchoolTem() + ")");
message.setSendTime(time);
message.setHaveRead("未读");
message.setMessageType("insertCourse");
message.setMessageContent(courseId+"");
messageServiceImpl.insertMessage(message);
map.put("result", true);
}else{
map.put("result", false);
}
return map;
}
}
| true |
7ab26cbff692746ccf5ec3521a28742d311c752e | Java | RBWare/Glass-App-Manager | /Application Manager/src/main/java/com/rbware/glassappmanager/MainActivity.java | UTF-8 | 6,318 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package com.rbware.glassappmanager;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private ArrayList<ApplicationInfo> mPackageNames = new ArrayList();
private int mSelectedListing;
private UIListingCardScrollAdapter mAdapter;
private CardScrollView mCardScrollView;
private TextView mNoAppsFound;
private PackageManager mPackageManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPackageManager = this.getPackageManager();
View rootLayout = getLayoutInflater().inflate(R.layout.activity_main, null);
mNoAppsFound = (TextView)rootLayout.findViewById(R.id.noAppsFound);
setupCardList(rootLayout);
setContentView(rootLayout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_uninstall) {
String packageName = mPackageNames.get(mSelectedListing).packageName;
Uri packageURI = Uri.parse("package:" + packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivityForResult(uninstallIntent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0){
mPackageNames.clear();
setupCardList(null);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setupCardList(View rootLayout){
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> list = mPackageManager.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);
for (ResolveInfo rInfo : list) {
if (!rInfo.activityInfo.applicationInfo.loadLabel(mPackageManager).toString().equals("Glass Home") &&
!rInfo.activityInfo.applicationInfo.loadLabel(mPackageManager).toString().equals("Glass App Manager"))
mPackageNames.add(rInfo.activityInfo.applicationInfo);
}
if(!mPackageNames.isEmpty()){
mAdapter = new UIListingCardScrollAdapter();
if (mCardScrollView == null){
mCardScrollView = (CardScrollView)rootLayout.findViewById(R.id.card_scroll_view);
mCardScrollView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectedListing = position;
MainActivity.super.openOptionsMenu();
}
});
}
mCardScrollView.setVisibility(View.VISIBLE);
mCardScrollView.setAdapter(mAdapter);
mCardScrollView.activate();
} else {
mNoAppsFound.setVisibility(View.VISIBLE);
if(mCardScrollView != null)
mCardScrollView.setVisibility(View.INVISIBLE);
}
}
private class UIListingCardScrollAdapter extends CardScrollAdapter {
@Override
public int findIdPosition(Object id) {
return -1;
}
@Override
public int findItemPosition(Object item) {
return mPackageNames.indexOf(item);
}
@Override
public int getCount() {
Log.d("Tag", "getCount() = " + mPackageNames.size());
return mPackageNames.size();
}
@Override
public Object getItem(int position) {
Log.d("Tag", "getItem(" + position + ") = " + mPackageNames.get(position));
return mPackageNames.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater layoutInflater;
if (v == null) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.application_detail, null);
}
TextView appName = (TextView)v.findViewById(R.id.applicationName);
TextView appVersion = (TextView)v.findViewById(R.id.applicationVersion);
ImageView appIcon = (ImageView)v.findViewById(R.id.applicationIcon);
if (!mPackageNames.isEmpty()){
ApplicationInfo info = mPackageNames.get(position);
appName.setText(info.loadLabel(mPackageManager).toString());
appIcon.setImageDrawable(info.loadIcon(mPackageManager));
try{
appVersion.setText(getPackageManager().getPackageInfo(info.loadLabel(mPackageManager).toString(), 0).versionCode);
} catch (PackageManager.NameNotFoundException e){
}
}
return v;
}
}
}
| true |
e2919cb57c42e39161716fab1bccda0f7a7ec67e | Java | asim-rehman/android-crimemap | /app/src/androidTest/java/uk/asimrehman/crimemap/CrimesInstrumentedTest.java | UTF-8 | 916 | 1.929688 | 2 | [
"MIT"
] | permissive | package uk.asimrehman.crimemap;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import org.junit.Test;
import uk.asimrehman.crimemap.businesslogiclayer.CrimesBLL;
import static org.junit.Assert.assertEquals;
/**
* Created by admin on 07/01/2017.
*/
public class CrimesInstrumentedTest {
String tag = "CRIMEMAPTEST";
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("uk.asimrehman.crimemap", appContext.getPackageName());
}
@Test
public void testGetCrime()
{
CrimesBLL crimesBLL = new CrimesBLL(52.7814053d,-3.8056511d,"2013-01",1,null);
//boolean success = crimesBLL.GetCrimeData();
/// Log.d(tag, String.valueOf(success));
}
}
| true |
e8c243edfe06af388aa2beeaf72d0b8f5a287c18 | Java | elpaablo/SimTogglePlus | /app/src/main/java/com/elpaablo/simtoggleplus/IOUtils.java | UTF-8 | 1,910 | 2.6875 | 3 | [] | no_license | package com.elpaablo.simtoggleplus;
import android.content.Context;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
final class IOUtils {
private final static String TAG = "ChargingLimiter.IOUtils";
public static String readFromFile(Context context, String pathToFile) {
BufferedReader buffered_reader=null;
try
{
buffered_reader = new BufferedReader(new FileReader(pathToFile));
String line;
StringBuilder ret = new StringBuilder();
while ((line = buffered_reader.readLine()) != null)
{
ret.append(line);
}
return ret.toString();
}
catch (IOException e)
{
e.printStackTrace();
return "";
}
finally
{
try
{
if (buffered_reader != null)
buffered_reader.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
public static boolean writeToFile(Context context, String pathToFile, String data) {
try {
File file = new File(pathToFile);
file.setWritable(true, false);
if (!file.exists()) {
//Log.e(TAG, "File not found: " + pathToFile);
return false;
}
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.flush();
writer.close();
file.setWritable(true, true);
return true;
} catch (IOException e) {
//Log.e(TAG, "Can not write to file: " + e.toString());
return false;
}
}
}
| true |
dd8e233ca9c2ad56fb5e0aaf66638a13f8002057 | Java | shital-shinde/WebTemplateRepo | /WebTemplate2/src/main/java/com/deere/dsfj/jdorderspringmvcweb/controller/WelcomeController.java | UTF-8 | 688 | 2.296875 | 2 | [] | no_license | package com.deere.dsfj.jdorderspringmvcweb.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/** WelcomeController class handles the requests to display the Welcome page */
@Controller
public class WelcomeController{
/**
* Method used to load welcome page
*/
@RequestMapping(value = {"/Welcome"}, method=RequestMethod.GET)
public String welcome(Model model, HttpServletRequest request){
return "Welcome";
}
}
| true |
bf0b6bc475640fc641bac7044f672f6379ac510a | Java | BaharSaffarian/BankCustomersInfManager | /src/main/java/logic/RealCustomerLogic.java | UTF-8 | 1,228 | 2.515625 | 3 | [] | no_license | package logic;
import model.RealCustomer;
import model.RealCustomerCRUD;
import java.util.ArrayList;
public class RealCustomerLogic {
public static int registerCustomer(RealCustomer realCustomer) {
if (!RealCustomerCRUD.doesNationalCodeExists(realCustomer.getNationalCode())) {
return RealCustomerCRUD.insertRealCustomer(realCustomer);
}
return -1;
}
public static ArrayList<RealCustomer> searchRealCustomer(RealCustomer realCustomer) {
return RealCustomerCRUD.selectRealCustomer(realCustomer);
}
public static int updateCustomer(RealCustomer realCustomer, String oldNationalCode) {
if (!realCustomer.getNationalCode().equals(oldNationalCode) && !RealCustomerCRUD.doesNationalCodeExists(realCustomer.getNationalCode())) {
if (RealCustomerCRUD.updateRealCustomer(realCustomer))
return 1;
} else if (realCustomer.getNationalCode().equals(oldNationalCode)) {
if (RealCustomerCRUD.updateRealCustomer(realCustomer))
return 1;
}
return -1;
}
public static boolean deleteRealCustomerById(String id) {
return RealCustomerCRUD.deleteRealCustomerById(id);
}
}
| true |
5bf1aa1bf626d3476f1014e8b7cf2ee7e9438815 | Java | MahendraDecha/javaLogin-GetData-Using-MVC | /firstMvc/src/com/org/mvc/EmployeeDAO.java | UTF-8 | 2,997 | 2.984375 | 3 | [] | no_license | package com.org.mvc;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class EmployeeDAO {
static Connection con = null;
static ResultSet rs = null;
static Statement st=null;
employee empL = null;
String cust_id = null;
String cust_firstname = null;
String cust_lastname = null;
String cust_address = null;
public static Login login(Login user)
{
con = DbConnection.getConnection();
String username = user.getUsername();
String password = user.getPassword();
try{
if (con != null) {
System.out.println("Connected with connection #1");
}
st=con.createStatement();
ResultSet rs=st.executeQuery(
"select * from employee where username='"+ username + "' AND password='" + password + "'");
boolean status=rs.next();
System.out.println("connection");
if(!status)
{
System.out.println("Sorry, you are not a registered user! Please sign up first");
user.setValid(false);
}
else if (status)
{
String firstName = rs.getString("Name");
System.out.println("Welcome " + firstName);
user.setName(firstName);
user.setValid(true);
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { }
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {}
}
}
return user;
}
public ArrayList getCustmInfo() {
ArrayList empList = new ArrayList();
try {
con = DbConnection.getConnection();
st = con.createStatement();
rs = st.executeQuery("select id,firstname,lastname,address from emp_info");
if (con != null) {
System.out.println("Connected with connection #1");
}
while (rs.next()) {
cust_id = rs.getString("id");
cust_firstname = rs.getString("firstname");
cust_lastname = rs.getString("lastname");
cust_address = rs.getString("address");
empL = new employee(cust_id, cust_firstname, cust_lastname,cust_address);
empList.add(empL);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
return empList;
}
}
| true |
7fd2678e24b1fc67f2e5dbe5904bd599370558f1 | Java | yisonyang/nmc_downpu | /src/main/java/com/downpu/domain/Admin.java | UTF-8 | 1,107 | 2.15625 | 2 | [] | no_license | package com.downpu.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.criteria.CriteriaBuilder;
import javax.validation.constraints.NotNull;
/**
* Created by yy187 on 2017/9/11.
*/
@Entity
@Table(name = "admin")
public class Admin {
@Id
@GeneratedValue
private Integer Idadmin;
@NotNull
private String name;
@NotNull
private Integer degree;
@NotNull
private String password;
public Integer getIdadmin() {
return Idadmin;
}
public void setIdadmin(Integer idadmin) {
Idadmin = idadmin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDegree() {
return degree;
}
public void setDegree(Integer degree) {
this.degree = degree;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| true |
14c659a2013fb6fa9297cb71b7518d04fd838dee | Java | eduardo-parra/perHand | /IcanprogramAutomationMOFO/src/Modelus/ModelusÖvning.java | IBM852 | 182 | 2.53125 | 3 | [] | no_license | package Modelus;
public class Modelusvning {
public static void main(String[] args) {
for(int i=0;i<80;i++) {
int mod = i%4;
System.out.println(mod+1);
}
}
}
| true |
63a4b8cdfacc0aed5cb6de0955ba8b001144a3c7 | Java | AkilaDPerera/EZReportsDESKTOP | /src/main/gui/support/FileChoose.java | UTF-8 | 2,380 | 2.65625 | 3 | [] | no_license | package main.gui.support;
import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;
public class FileChoose {
public static String[] CreateFile(Component component){
JFileChooser fc = new JFileChooser();
javax.swing.filechooser.FileFilter ezrFilter = new javax.swing.filechooser.FileFilter() {
@Override
public String getDescription() {
return "EZReports files (*.ezr)";
}
@Override
public boolean accept(File f) {
if (f.getName().endsWith(".ezr") || !f.getAbsolutePath().contains(".")){
return true;
}else{
return false;
}
}
};
fc.setFileFilter(ezrFilter);
int result = fc.showDialog(component, "Create");
if (result == 1){
return null;
}else{
return new String [] {
fc.getSelectedFile().getAbsolutePath(),
fc.getSelectedFile().getName()
};
}
// abspath, filename
}
public static String[] OpenFile(Component component){
JFileChooser fc = new JFileChooser();
javax.swing.filechooser.FileFilter ezrFilter = new javax.swing.filechooser.FileFilter() {
@Override
public String getDescription() {
return "EZReports files (*.ezr)";
}
@Override
public boolean accept(File f) {
if (f.getName().endsWith(".ezr") || !f.getAbsolutePath().contains(".")){
return true;
}else{
return false;
}
}
};
fc.setFileFilter(ezrFilter);
int result = fc.showDialog(component, "Open");
if (result == 1){
return null;
}else{
return new String [] {
fc.getSelectedFile().getAbsolutePath(),
fc.getSelectedFile().getName()
};
}
//abspath, filename
}
public static String[] SaveAsFile(Component component){
JFileChooser fc = new JFileChooser();
javax.swing.filechooser.FileFilter ezrFilter = new javax.swing.filechooser.FileFilter() {
@Override
public String getDescription() {
return "EZReports files (*.ezr)";
}
@Override
public boolean accept(File f) {
if (f.getName().endsWith(".ezr") || !f.getAbsolutePath().contains(".")){
return true;
}else{
return false;
}
}
};
fc.setFileFilter(ezrFilter);
int result = fc.showDialog(component, "Save");
if (result == 1){
return null;
}else{
return new String [] {
fc.getSelectedFile().getAbsolutePath(),
fc.getSelectedFile().getName()
};
}
//abspath, filename
}
}
| true |
dfb155e25e1b61592cdb7ebdc4301377df35d873 | Java | ChinasoftNobody/code-man | /codemanservice/src/main/java/com/chinasoft/lgh/codeman/server/service/ProjectService.java | UTF-8 | 466 | 1.726563 | 2 | [] | no_license | package com.chinasoft.lgh.codeman.server.service;
import com.chinasoft.lgh.codeman.server.model.MProject;
import com.chinasoft.lgh.codeman.server.pojo.project.ProjectListRequest;
import com.chinasoft.lgh.codeman.server.pojo.project.ProjectRegisterRequest;
import org.springframework.data.domain.Page;
public interface ProjectService {
Page<MProject> queryProjectList(ProjectListRequest request);
MProject createProject(ProjectRegisterRequest request);
}
| true |
c8c2b971246372a48b2ddf79e77703c4b062aebf | Java | ning/atlas | /src/test/java/com/ning/atlas/TestScratchInstaller.java | UTF-8 | 3,397 | 2.15625 | 2 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | package com.ning.atlas;
import com.ning.atlas.components.ScratchInstaller;
import com.ning.atlas.space.InMemorySpace;
import com.ning.atlas.spi.Deployment;
import com.ning.atlas.spi.Identity;
import com.ning.atlas.spi.Installer;
import com.ning.atlas.spi.My;
import com.ning.atlas.spi.Provisioner;
import com.ning.atlas.spi.space.Space;
import com.ning.atlas.spi.Uri;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class TestScratchInstaller
{
@Test
public void testAtInValue() throws Exception
{
Identity id = Identity.root().createChild("hello", "0");
Host host = new Host(id,
Uri.<Provisioner>valueOf("base"),
Collections.<Uri<Installer>>emptyList(),
Collections.<Uri<Installer>>emptyList(),
new My());
Environment environment = new Environment();
SystemMap map = new SystemMap(Arrays.<Element>asList(host));
Space space = InMemorySpace.newInstance();
Deployment d = new ActualDeployment(map, environment, space);
ScratchInstaller scratch = new ScratchInstaller();
scratch.install(host, Uri.<Installer>valueOf("scratch:hello=@"), d).get();
assertThat(d.getScratch().get("hello").getValue(), equalTo(id.toExternalForm()));
}
@Test
public void testAtInKey() throws Exception
{
Identity id = Identity.root().createChild("hello", "0");
Host host = new Host(id,
Uri.<Provisioner>valueOf("base"),
Collections.<Uri<Installer>>emptyList(),
Collections.<Uri<Installer>>emptyList(),
new My());
SystemMap map = new SystemMap(Arrays.<Element>asList(host));
Environment environment = new Environment();
Space space = InMemorySpace.newInstance();
Deployment d = new ActualDeployment(map, environment, space);
ScratchInstaller scratch = new ScratchInstaller();
scratch.install(host, Uri.<Installer>valueOf("scratch:@:hello=world"), d).get();
assertThat(d.getScratch().get(id.toExternalForm() + ":" + "hello").getValue(), equalTo("world"));
}
@Test
public void testMultipleThings() throws Exception
{
Identity id = Identity.root().createChild("hello", "0");
Host host = new Host(id,
Uri.<Provisioner>valueOf("base"),
Collections.<Uri<Installer>>emptyList(),
Collections.<Uri<Installer>>emptyList(),
new My());
SystemMap map = new SystemMap(Arrays.<Element>asList(host));
Environment environment = new Environment();
Space space = InMemorySpace.newInstance();
Deployment d = new ActualDeployment(map, environment, space);
ScratchInstaller scratch = new ScratchInstaller();
scratch.install(host, Uri.<Installer>valueOf("scratch:@:hello=world;waffle=@"), d).get();
assertThat(d.getScratch().get(id.toExternalForm() + ":" + "hello").getValue(), equalTo("world"));
assertThat(d.getScratch().get("waffle").getValue(), equalTo(id.toExternalForm()));
}
}
| true |
ea843b583ee65b39cc9c60c9cce5682016320681 | Java | fargome/chatbox-BaptisteDelattre | /app/src/main/java/com/example/cesiapp/DateHelper.java | UTF-8 | 553 | 3.03125 | 3 | [] | no_license | package com.example.cesiapp;
import java.text.SimpleDateFormat;
import java.util.Date;
//Classe permettant une gestion simplifiée des dates et timestamps.
public class DateHelper {
private static String format = "HH:mm:ss";
private static SimpleDateFormat formatter = null;
//Renvoie un objet date à partir du timestamp
public static String getFormattedDate(long timestamp){
if(formatter == null){
formatter = new SimpleDateFormat(format);
}
return formatter.format(new Date(timestamp));
}
} | true |
be8b543626f35bee8993d560d1adf078f0af1cc9 | Java | arem94/persianCalenderHelper | /app/src/main/java/ir/steponit/persiancalenderhelper/YearMonthDate.java | UTF-8 | 2,035 | 2.890625 | 3 | [] | no_license | package ir.steponit.persiancalenderhelper;
public class YearMonthDate {
public YearMonthDate(int year, int month, int date) {
this.year = year;
this.month = month;
this.date = date;
hour=0;
Minutes=0;
Second=0;
}
public YearMonthDate(int year, int month, String monthText, int date, String weekText, int hour, int minutes, int second) {
this.year = year;
this.month = month;
this.monthText = monthText;
this.date = date;
this.weekText = weekText;
this.hour = hour;
Minutes = minutes;
Second = second;
}
public YearMonthDate(int year, int month, int date, int hour, int minutes, int second) {
this.year = year;
this.month = month;
this.date = date;
this.hour = hour;
Minutes = minutes;
Second = second;
}
private int year;
private int month;
private String monthText;
private int date;
private String weekText;
private int hour;
private int Minutes;
private int Second;
public String getMonthText() {
return monthText;
}
public void setMonthText(String monthText) {
this.monthText = monthText;
}
public String getWeekText() {
return weekText;
}
public void setWeekText(String weekText) {
this.weekText = weekText;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinutes() {
return Minutes;
}
public void setMinutes(int minutes) {
Minutes = minutes;
}
public int getSecond() {
return Second;
}
public void setSecond(int second) {
Second = second;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public String toString() {
return getYear() + "/" + getMonth() + "/" + getDate();
}
}
| true |
199b260eb80cd36f51d76ccafc8b6cdab3980ec2 | Java | uru-carlosmontes/WEBII-Java-Session | /src/cams/org/httpsession/Login.java | UTF-8 | 1,988 | 2.65625 | 3 | [] | no_license | package cams.org.httpsession;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cams.org.cson.Cson;
/**
* Servlet implementation class Login
*/
@WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private Cson cson = new Cson();
/**
* @see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
//==========================================
//Debes tener CSON.jar para poder trabajar//
//==========================================
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
cson.clear();
cson.add("status", 200)
.add("response", "You must to use POST method");
response.setContentType("application/json");
response.getWriter().print(cson);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String lastname = request.getParameter("lastname");
HttpSession session = request.getSession();
cson.clear();
if (session.isNew()) {
User user = new User(name, lastname);
cson.add("status", 200)
.add("response", "You are logged");
session.setAttribute("user_info", user);
} else {
cson.add("status", 300)
.add("response", "You are already logged");
}
response.setContentType("application/json");
response.getWriter().print(cson);
}
}
| true |
66fbd5726dfa786e7ab738bd375da3f811b0611f | Java | strax84mb/SDPlayer | /SDPlayer/src/prog/paket/baza/struct/TraitMenu.java | UTF-8 | 4,059 | 2.375 | 2 | [] | no_license | package prog.paket.baza.struct;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.MenuSelectionManager;
import javax.swing.plaf.synth.SynthMenuUI;
public class TraitMenu extends JMenu implements SongTrait, DragGestureListener{
private static final long serialVersionUID = -4178736154456489510L;
private SearchState state = SearchState.NO_STATE;
private int id;
private String abrev;
private SongTrait parentTrait;
public TraitMenu(int id, String text, String abrev, SongTrait parentTrait){
super(text);
this.id = id;
this.abrev = abrev;
this.parentTrait = parentTrait;
setUI(new SynthMenuUI(){
@Override
protected void doClick(MenuSelectionManager msm) {
getThis().doClick(0);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getPoint().x < 28)
cycleState();
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if((e.getKeyCode() == KeyEvent.VK_SPACE) && (e.getModifiers() == 0))
cycleState();
}
});
setIcon(SongTrait.noStateIcon);
DragSource ds = new DragSource();
ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this);
setDropTarget(new DropTarget());
}
public void cycleState(){
switch(state){
case INCLUDE:
state = SearchState.EXCLUDE;
setIcon(SongTrait.excludeIcon);
break;
case EXCLUDE:
state = SearchState.NO_STATE;
setIcon(SongTrait.noStateIcon);
break;
case NO_STATE:
state = SearchState.INCLUDE;
setIcon(SongTrait.includeIcon);
break;
}
((TraitMenuBar)getRootTrait()).dlg.writeOutAbrevs();
}
public JMenuItem getThis(){
return this;
}
@Override
public int getID() {
return id;
}
@Override
public String getTraitName() {
return getText();
}
@Override
public String getAbrev() {
return abrev;
}
@Override
public SearchState getState() {
return state;
}
@Override
public void setState(SearchState state) {
this.state = state;
switch(state){
case INCLUDE:
setIcon(SongTrait.includeIcon);
break;
case EXCLUDE:
setIcon(SongTrait.excludeIcon);
break;
case NO_STATE:
setIcon(SongTrait.noStateIcon);
break;
}
}
@Override
public int getSubTraitCount() {
return getItemCount();
}
@Override
public SongTrait getSubTraitAt(int index) {
return (SongTrait)getItem(index);
}
@Override
public SongTrait getTraitParent() {
return parentTrait;
}
@Override
public void add(SongTrait newTrait) {
add((TraitMenu)newTrait);
newTrait.setTraitParent(this);
}
public void add(TraitMenu menu){
add(menu, getSubTraitCount());
menu.setTraitParent(this);
}
public void add(TraitItem item){
add((JMenuItem)item);
item.setTraitParent(this);
}
@Override
public void rename(String text, String abrev) {
setText(text);
this.abrev = abrev;
}
@Override
public void remove() {
if(parentTrait instanceof TraitMenuBar){
TraitMenuBar bar = (TraitMenuBar)parentTrait;
bar.remove(this);
parentTrait = null;
}else{
TraitMenu menu = (TraitMenu)parentTrait;
menu.remove(this);
parentTrait = null;
}
}
@Override
public void setTraitParent(SongTrait traitParent) {
this.parentTrait = traitParent;
}
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
dge.startDrag(null, new TransferableTrait(this));
}
@Override
public SongTrait getRootTrait() {
SongTrait temp = this;
while(temp.getID() != 0){
temp = temp.getTraitParent();
}
return temp;
}
}
| true |
183d728cbe9377c286dd37f0e7edd948a9191817 | Java | PDA-Open-Source/PDA-ENTITY | /src/main/java/com/socion/entity/exceptions/NotFoundException.java | UTF-8 | 631 | 2.296875 | 2 | [
"MIT"
] | permissive | package com.socion.entity.exceptions;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@JsonIgnoreProperties(ignoreUnknown = true)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class NotFoundException extends RuntimeException {
private String message;
public NotFoundException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| true |
1a3e78d713b204587d49d93ebe4be324258f0100 | Java | wxz1997/homework | /src/main/java/cn/wxz1997/entity/User.java | UTF-8 | 3,426 | 2.203125 | 2 | [] | no_license | package cn.wxz1997.entity;
import org.apache.commons.fileupload.util.LimitedInputStream;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
import java.util.List;
public class User implements Serializable{
private Integer userId;
private String username;
private String password;
private String nickname;
private String email;
private String college;
private String grade;
private String classes;
private String major;
private String area;
private Integer status;
private String code;
private Integer rank;
private List<Item> items;
public User() {
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", passwork='" + password + '\'' +
", nickname='" + nickname + '\'' +
", email='" + email + '\'' +
", college='" + college + '\'' +
", grade='" + grade + '\'' +
", classes='" + classes + '\'' +
", major='" + major + '\'' +
", area='" + area + '\'' +
", status=" + status +
", code='" + code + '\'' +
", rank=" + rank +
'}';
}
}
| true |
6f85cd9b19e6a5b2bb07b86beb74fd3b66b0c405 | Java | linyue515/riot | /riot-core/src/main/java/com/redislabs/riot/redis/RpushCommand.java | UTF-8 | 299 | 1.757813 | 2 | [
"Apache-2.0"
] | permissive | package com.redislabs.riot.redis;
import java.util.Map;
import picocli.CommandLine.Command;
@Command(name = "rpush")
public class RpushCommand extends AbstractCollectionCommand {
@Override
protected Rpush<String, String, Map<String, Object>> collectionWriter() {
return new Rpush<>();
}
}
| true |
30dbeded99866241ae7bf4fd93800f6c600d3bf7 | Java | jude-lif/3128-robot-2021 | /src/main/java/org/team3128/grogu/subsystems/EKF.java | UTF-8 | 9,441 | 2.71875 | 3 | [] | no_license | package org.team3128.grogu.subsystems;
/**
* @author Tyler Costello
*/
import java.util.ArrayList;
import org.ejml.simple.SimpleMatrix;
public class EKF {
private SimpleMatrix x;
private SimpleMatrix P;
private SimpleMatrix Q;
private SimpleMatrix H;
private SimpleMatrix R;
private SimpleMatrix I;
private SimpleMatrix z_sensors;
private double alvariance;
private double arvariance;
private double b;
private double dt;
private double dt_2;
private double dt_3;
private double dt_4;
// class constructor
// start positions, acceleration variances, width, time since last check,
// sensor variances
public EKF(double xStart, double yStart, double thetaStart, double vlStart, double vrStart, double alvariance,
double arvariance, double b, double dt, double r1, double r2, double r3) {
this.alvariance = alvariance;
this.arvariance = arvariance;
this.b = b;
this.dt = dt;
this.dt_2 = dt * dt;
this.dt_3 = dt_2 * dt;
this.dt_4 = dt_3 * dt;
double prev_time = 0;
x = new SimpleMatrix(5, 1, true, new double[] { xStart, yStart, thetaStart, vlStart, vrStart });
// Because we are giving it the correct starting values since it's an
// EKF which requires them, we are very confident in the values
P = SimpleMatrix.diag(0.01, 0.01, 0.01, 0.01, 0.01);
// Chops off x and y coordinates because we can't measure those
H = new SimpleMatrix(3, 5, true, new double[] { 0, 0, 1.0, 0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 0, 1.0 });
I = SimpleMatrix.identity(5);
z_sensors = new SimpleMatrix(3, 1);
Q = new SimpleMatrix(5, 5);
// Sensor variances
R = SimpleMatrix.diag(r1, r2, r3);
}
// checks to see if 2 variables are close
private boolean isClose(double in1, double in2) {
if (Math.abs(in1 - in2) <= 0.001) {
return true;
}
return false;
}
public double[] testFunction(double[] xInput) {
double xNum = xInput[0];
double y = xInput[1];
double theta = xInput[2];
double vl = xInput[3];
double vr = xInput[4];
double dt=xInput[5];
//special case to check if vl and vr are about the same, because then r would go to infinity
if (isClose(vl, vr)) {
xNum = xNum + vl * Math.cos(theta) * dt;
y = y + vl * Math.sin(theta) * dt;
theta = theta;
} else {
double w = (vr - vl) / b;
double r = (b / 2) * (vl + vr) / (vr - vl);
xNum = r * Math.sin(theta) * Math.cos(w * dt) + r * Math.cos(theta) * Math.sin(w * dt) + xNum
- r * Math.sin(theta);
y = r * Math.sin(theta) * Math.sin(w * dt) - r * Math.cos(theta) * Math.cos(w * dt) + y
+ r * Math.cos(theta);
theta = theta + w * dt;
}
double[] returnArray = new double[5];
returnArray[0] = xNum;
returnArray[1] = y;
returnArray[2] = theta;
returnArray[3] = vl;
returnArray[4] = vr;
return returnArray;
}
// the function for calculating new position
private SimpleMatrix aFunction(SimpleMatrix xInput, double b, double dt) {
SimpleMatrix xOutput = new SimpleMatrix(5, 1);
double xNum = xInput.get(0, 0);
double y = xInput.get(1, 0);
double theta = xInput.get(2, 0);
double vl = xInput.get(3, 0);
double vr = xInput.get(4, 0);
//special case to check if vl and vr are about the same, because then r would go to infinity
if (isClose(vl, vr)) {
xNum = xNum + vl * Math.cos(theta) * dt;
y = y + vl * Math.sin(theta) * dt;
theta = theta;
} else {
double w = (vr - vl) / b;
double r = (b / 2) * (vl + vr) / (vr - vl);
xNum = r * Math.sin(theta) * Math.cos(w * dt) + r * Math.cos(theta) * Math.sin(w * dt) + xNum
- r * Math.sin(theta);
y = r * Math.sin(theta) * Math.sin(w * dt) - r * Math.cos(theta) * Math.cos(w * dt) + y
+ r * Math.cos(theta);
theta = theta + w * dt;
}
xOutput.set(0, 0, xNum);
xOutput.set(1, 0, y);
xOutput.set(2, 0, theta);
xOutput.set(3, 0, vl);
xOutput.set(4, 0, vr);
return xOutput;
}
// main loop
public double[] runFilter(double[] input) {
z_sensors.set(0, 0, input[0]);
z_sensors.set(1, 0, input[1]);
z_sensors.set(2, 0, input[2]);
this.dt = input[3];
this.dt_2 = dt * dt;
this.dt_3 = dt_2 * dt;
this.dt_4 = dt_3 * dt;
predict();
update(z_sensors);
double[] returnArray = new double[5];
returnArray[0] = x.get(0, 0);
returnArray[1] = x.get(1, 0);
returnArray[2] = x.get(2, 0);
returnArray[3] = x.get(3, 0);
returnArray[4] = x.get(4, 0);
return returnArray;
}
// predict step
private void predict() {
// sets q matrix
x = aFunction(x, b, dt);
Q.set(2, 0, 0);
Q.set(2, 1, 0);
Q.set(2, 2, (dt_4 * alvariance + dt_4 * arvariance) / (4 * b * b));
Q.set(2, 3, (-dt_3 * alvariance) / (2 * b));
Q.set(2, 4, (dt_3 * arvariance) / (2 * b));
Q.set(3, 0, 0);
Q.set(3, 1, 0);
Q.set(3, 2, (-dt_3 * alvariance) / (2 * b));
Q.set(3, 3, dt_2 * alvariance);
Q.set(3, 4, 0);
Q.set(4, 0, 0);
Q.set(4, 1, 0);
Q.set(4, 2, (dt_3 * arvariance) / (2 * b));
Q.set(4, 3, 0);
Q.set(4, 4, dt_2 * arvariance);
SimpleMatrix A = new SimpleMatrix(5, 5);
// set a matrix depending on if the velocities are close
if (isClose(x.get(3, 0), x.get(4, 0))) {
A.set(0, 0, 1);
A.set(0, 1, 0);
A.set(0, 2, -x.get(3, 0) * dt * Math.sin(x.get(2, 0)));
A.set(0, 3, dt * Math.cos(x.get(2, 0)));
A.set(0, 4, 0);
A.set(1, 0, 0);
A.set(1, 1, 1);
A.set(1, 2, dt * x.get(3, 0) * Math.cos(x.get(2, 0)));
A.set(1, 3, dt * Math.sin(x.get(2, 0)));
A.set(1, 4, 0);
A.set(2, 0, 0);
A.set(2, 0, 0);
A.set(2, 2, 1);
A.set(2, 3, 0);
A.set(2, 4, 0);
A.set(3, 0, 0);
A.set(3, 1, 0);
A.set(3, 2, 0);
A.set(3, 3, 1);
A.set(3, 4, 0);
A.set(4, 0, 0);
A.set(4, 1, 0);
A.set(4, 2, 0);
A.set(4, 3, 0);
A.set(4, 4, 1);
} else {
A.set(0, 0, 1);
A.set(0, 1, 0);
A.set(0, 2,
(b * (x.get(4, 0) + x.get(3, 0))
* (Math.cos(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b) - Math.cos(x.get(2, 0))))
/ (2 * (x.get(4, 0) - x.get(3, 0))));
A.set(0, 3,
(-x.get(4, 0) * x.get(4, 0) * dt * Math.cos(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b)
+ 2 * b * x.get(4, 0) * Math.sin(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b)
- 2 * b * x.get(4, 0) * Math.sin(x.get(2, 0))
+ x.get(3, 0) * x.get(3, 0) * dt
* Math.cos(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b))
/ (2 * (x.get(4, 0) - x.get(3, 0)) * (x.get(4, 0) - x.get(3, 0))));
A.set(0, 4, (2 * x.get(3, 0) * b * Math.sin(x.get(2, 0))
- 2 * x.get(3, 0) * b * Math.sin(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b)
+ x.get(4, 0) * x.get(4, 0) * dt * Math.cos(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b)
- x.get(3, 0) * x.get(3, 0) * dt * Math.cos(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b))
/ (2 * (x.get(4, 0) - x.get(3, 0)) * (x.get(4, 0) - x.get(3, 0))));
A.set(1, 0, 0);
A.set(1, 1, 1);
A.set(1, 2,
(b * (x.get(4, 0) + x.get(3, 0))
* (Math.sin(x.get(2, 0) + dt * (x.get(4, 0) - x.get(3, 0)) / b) - Math.sin(x.get(2, 0))))
/ (2 * (x.get(4, 0) - x.get(3, 0))));
A.set(1, 3,
(x.get(3, 0) * x.get(3, 0) * dt * Math.cos(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.sin(x.get(2, 0))
+ x.get(3, 0) * x.get(3, 0) * dt * Math.sin(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.cos(x.get(2, 0))
+ 2 * b * x.get(4, 0) * Math.sin(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.sin(x.get(2, 0))
+ 2 * b * x.get(4, 0) * Math.cos(x.get(2, 0))
- x.get(4, 0) * x.get(4, 0) * dt * Math.cos(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.sin(x.get(2, 0))
- x.get(4, 0) * x.get(4, 0) * dt * Math.sin(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.cos(x.get(2, 0))
- 2 * b * x.get(4, 0) * Math.cos(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.cos(x.get(2, 0)))
/ (2 * (x.get(4, 0) - x.get(3, 0)) * (x.get(4, 0) - x.get(3, 0))));
A.set(1, 4,
(x.get(4, 0) * x.get(4, 0) * dt * Math.cos(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.sin(x.get(2, 0))
+ x.get(4, 0) * x.get(4, 0) * dt * Math.sin(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.cos(x.get(2, 0))
+ 2 * b * x.get(3, 0) * Math.cos(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.cos(x.get(2, 0))
- x.get(3, 0) * x.get(3, 0) * dt * Math.cos(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.sin(x.get(2, 0))
- 2 * b * x.get(3, 0) * Math.sin(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.sin(x.get(2, 0))
- x.get(3, 0) * x.get(3, 0) * dt * Math.sin(dt * (x.get(4, 0) - x.get(3, 0)) / b)
* Math.cos(x.get(2, 0))
- 2 * b * x.get(3, 0) * Math.cos(x.get(2, 0)))
/ (2 * (x.get(4, 0) - x.get(3, 0)) * (x.get(4, 0) - x.get(3, 0))));
A.set(2, 0, 0);
A.set(2, 1, 0);
A.set(2, 2, 1);
A.set(2, 3, -dt / b);
A.set(2, 4, dt / b);
A.set(3, 0, 0);
A.set(3, 1, 0);
A.set(3, 2, 0);
A.set(3, 3, 1);
A.set(3, 4, 0);
A.set(4, 0, 0);
A.set(4, 1, 0);
A.set(4, 2, 0);
A.set(4, 3, 0);
A.set(4, 4, 1);
}
SimpleMatrix At = A.transpose();
P = (A.mult(P.mult(At))).plus(Q);
}
// update loop
private void update(SimpleMatrix z) {
SimpleMatrix Y = z.minus(H.mult(x));
SimpleMatrix Ht = H.transpose();
SimpleMatrix S = (H.mult(P.mult(Ht))).plus(R);
SimpleMatrix K = P.mult(Ht);
SimpleMatrix Si = S.invert();
K = K.mult(Si);
x = x.plus(K.mult(Y));
P = (I.minus(K.mult(H))).mult(P);
}
}
| true |
57a5d4975001b81808d9b9f696eca9ebfec53ab0 | Java | SuryaKavutarapu/Java_Basics-Training2 | /Packages/Package1Class.java | UTF-8 | 193 | 1.96875 | 2 | [] | no_license | package package1;
public class Package1Class{
public void show(){
System.out.println("method in package1.Package1Class");
}/*method show*/
}/*class Package1 */ | true |
2b850b3d0bcd230518dabcb1a7c7ee744c5b670a | Java | linxiumeng/zhonghong | /blade-service/blade-bg-admin/src/main/java/org/springblade/bgadmin/modules/sys/enums/OrdersFormEnum.java | UTF-8 | 1,315 | 2.6875 | 3 | [] | no_license | package org.springblade.bgadmin.modules.sys.enums;
import com.baomidou.mybatisplus.core.enums.IEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.io.Serializable;
/**
* @author hanbin
* 订单状态枚举
*/
public enum OrdersFormEnum implements IEnum {
NOT_PUT_ORDER(0,"未下单"),
ALREADY_PUT_ORDER(1,"已下单"),
FAILD_PUT_ORDER(2,"订单失败");
private String desc;//中文描述
private int code;//中文描述
/**
* 私有构造,防止被外部调用
* @param desc
*/
OrdersFormEnum(int code, String desc){
this.desc=desc;
this.code=code;
}
/**
* 定义方法,返回描述,跟常规类的定义没区别
* @return
*/
public String getDesc(){
return desc;
}
@JsonCreator
public static OrdersFormEnum getItem(Integer code){
if(code != null){
for(OrdersFormEnum item : values()){
if(item.getCode() == code.intValue()){
return item;
}
}
}
return null;
}
@JsonValue
public int getCode(){
return code;
}
@Override
public Serializable getValue() {
return this.getCode();
}
}
| true |
356a296a5b9235d062e6410d8ceee8a3c8e41f69 | Java | shahrozimtiaz/shahrozimtiaz.github.io | /3-CSC 202/Concurrency/src/SynchQueue.java | UTF-8 | 1,000 | 3.203125 | 3 | [] | no_license | /**
* This is my description of my SynchQueue Class. It is used by both Consumer and Produce threads.
*
* @author Shahroz Imtiaz
* @version 1.0
* @since 10/11/2017
*/
public class SynchQueue {
private int[] data;
private int last;
private boolean done;
public SynchQueue() {
done = false;
data = new int[10];
last = -1;
}
public synchronized int size() {
return last+1;
}
public boolean isFull() {
if(size() == data.length) {
return true;
}
return false;
}
public synchronized boolean enqueue(int datum) {
if(isFull()) {
return false;
}
data[++last] = datum;
return true;
}
public synchronized int dequeue() {
if(last == -1) {
return -1;
}
int temp = data[0];
for(int i=1; i<=last; i++)
data[i-1] = data[i];
last--;
return temp;
}
public boolean isDone() {
return done;
}
public void shutDown() {
done = true;
}
public synchronized int getlast() {
return last;
}
}//class
| true |
73a0a290b04584e35365fd6dbe20a12df9ec9c46 | Java | csradu/Endava-Training | /LanguageAndData/PasswordCreater/src/RandomStringGenerator.java | UTF-8 | 883 | 3.5625 | 4 | [] | no_license | /**
* This file is part of the Endava Graduates training program
* Created by Calin Radu 20.07.2015
*/
import java.util.Random;
public class RandomStringGenerator {
//generator alphabet
private char[] alphabet;
//generator length
private int length;
RandomStringGenerator(int length, String alphabet) {
this.length = length;
this.alphabet = alphabet.toCharArray();
}
/**
* Creates a random generated String with characters from the specified alphabet
* and having the specified length
* @return a random generated String
*/
public String next() {
String result = "";
int value;
Random generator = new Random();
for (int i = 0; i < length; i++) {
value = generator.nextInt(length - 1);
result += alphabet[value];
}
return result;
}
}
| true |
bc0944d6cece3fad4717e603b66e4beb2e608ca0 | Java | mtransitapps/commons-android | /src/test/java/org/mtransit/android/commons/LocationUtilsTests.java | UTF-8 | 7,698 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | package org.mtransit.android.commons;
import org.junit.Test;
import org.mtransit.android.commons.LocationUtils.LocationPOI;
import org.mtransit.android.commons.data.DefaultPOI;
import org.mtransit.android.commons.data.POI;
import org.mtransit.android.commons.data.Route;
import org.mtransit.android.commons.data.RouteTripStop;
import org.mtransit.android.commons.data.Stop;
import org.mtransit.android.commons.data.Trip;
import org.mtransit.commons.CollectionUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mtransit.android.commons.LocationUtils.EARTH_RADIUS;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
// inspired by https://github.com/googlemaps/android-maps-utils
public class LocationUtilsTests {
private static final int latIdx = 0;
private static final int lngIdx = 0;
// The vertices of an octahedron, for testing
private final double[] up = new double[]{90, 0};
private final double[] down = new double[]{-90, 0};
private final double[] front = new double[]{0, 0};
private final double[] right = new double[]{0, 90};
private final double[] back = new double[]{0, -180};
private final double[] left = new double[]{0, -90};
/**
* Tests for approximate equality.
*/
private static void expectLatLngApproxEquals(double[] actual, double[] expected) {
expectNearNumber(actual[latIdx], expected[latIdx], 1e-6);
// Account for the convergence of longitude lines at the poles
double cosLat = Math.cos(Math.toRadians(actual[latIdx]));
expectNearNumber(cosLat * actual[lngIdx], cosLat * expected[lngIdx], 1e-6);
}
private static void expectNearNumber(double actual, double expected, @SuppressWarnings("SameParameterValue") double epsilon) {
assertTrue(String.format("Expected %g to be near %g", actual, expected),
Math.abs(expected - actual) <= epsilon);
}
@Test
public void testComputeOffset() {
// From front
expectLatLngApproxEquals(
front, LocationUtils.computeOffset(front[0], front[1], 0, 0));
expectLatLngApproxEquals(
up, LocationUtils.computeOffset(front[0], front[1], Math.PI * EARTH_RADIUS / 2, 0));
expectLatLngApproxEquals(
down, LocationUtils.computeOffset(front[0], front[1], Math.PI * EARTH_RADIUS / 2, 180));
expectLatLngApproxEquals(
left, LocationUtils.computeOffset(front[0], front[1], Math.PI * EARTH_RADIUS / 2, -90));
expectLatLngApproxEquals(
right, LocationUtils.computeOffset(front[0], front[1], Math.PI * EARTH_RADIUS / 2, 90));
expectLatLngApproxEquals(
back, LocationUtils.computeOffset(front[0], front[1], Math.PI * EARTH_RADIUS, 0));
expectLatLngApproxEquals(
back, LocationUtils.computeOffset(front[0], front[1], Math.PI * EARTH_RADIUS, 90));
// From left
expectLatLngApproxEquals(
left, LocationUtils.computeOffset(left[0], left[1], 0, 0));
expectLatLngApproxEquals(
up, LocationUtils.computeOffset(left[0], left[1], Math.PI * EARTH_RADIUS / 2, 0));
expectLatLngApproxEquals(
down, LocationUtils.computeOffset(left[0], left[1], Math.PI * EARTH_RADIUS / 2, 180));
expectLatLngApproxEquals(
front, LocationUtils.computeOffset(left[0], left[1], Math.PI * EARTH_RADIUS / 2, 90));
expectLatLngApproxEquals(
back, LocationUtils.computeOffset(left[0], left[1], Math.PI * EARTH_RADIUS / 2, -90));
expectLatLngApproxEquals(
right, LocationUtils.computeOffset(left[0], left[1], Math.PI * EARTH_RADIUS, 0));
expectLatLngApproxEquals(
right, LocationUtils.computeOffset(left[0], left[1], Math.PI * EARTH_RADIUS, 90));
// NOTE(appleton): Heading is undefined at the poles, so we do not test from up/down.
}
@Test
public void testPOIDistanceComparator() {
// Arrange
List<LocationPOI> poiList = Arrays.asList(
makeLocationPOI(1, 3f),
makeLocationPOI(2, 1f),
makeLocationPOI(3, 20_000f),
makeLocationPOI(4, 0.5f)
);
System.out.println(poiList);
// Act
CollectionUtils.sort(poiList, LocationUtils.POI_DISTANCE_COMPARATOR);
// Assert
System.out.println(poiList);
assertEquals(4, poiList.size());
assertEquals("tag4", poiList.get(0).getDistanceString());
assertEquals("tag2", poiList.get(1).getDistanceString());
assertEquals("tag1", poiList.get(2).getDistanceString());
assertEquals("tag3", poiList.get(3).getDistanceString());
}
@Test
public void testPOIDistanceComparatorRTS_SameStop_DistinctRoute() {
// Arrange
List<LocationPOI> poiList = Arrays.asList(
makeLocationPOI(1, 3f),
makeLocationPOI(2, 1f, 2L, 0L, 100),
makeLocationPOI(3, 1f, 1L, 0L, 100),
makeLocationPOI(4, 0.5f)
);
System.out.println(poiList);
// Act
CollectionUtils.sort(poiList, LocationUtils.POI_DISTANCE_COMPARATOR);
// Assert
System.out.println(poiList);
assertEquals(4, poiList.size());
assertEquals("tag4", poiList.get(0).getDistanceString());
assertEquals("tag3", poiList.get(1).getDistanceString());
assertEquals("tag2", poiList.get(2).getDistanceString());
assertEquals("tag1", poiList.get(3).getDistanceString());
}
@Test
public void testPOIDistanceComparatorRTS_SameStop_DistinctTrip() {
// Arrange
List<LocationPOI> poiList = Arrays.asList(
makeLocationPOI(1, 3f),
makeLocationPOI(2, 1f, 1L, 1L, 100),
makeLocationPOI(3, 1f, 1L, 0L, 100),
makeLocationPOI(4, 0.5f)
);
System.out.println(poiList);
// Act
CollectionUtils.sort(poiList, LocationUtils.POI_DISTANCE_COMPARATOR);
// Assert
System.out.println(poiList);
assertEquals(4, poiList.size());
assertEquals("tag4", poiList.get(0).getDistanceString());
assertEquals("tag3", poiList.get(1).getDistanceString());
assertEquals("tag2", poiList.get(2).getDistanceString());
assertEquals("tag1", poiList.get(3).getDistanceString());
}
@NonNull
private LocationPOI makeLocationPOI(int intTag, float distance) {
return makeLocationPOI(intTag, distance, null, null, null);
}
@NonNull
private LocationPOI makeLocationPOI(int intTag, float distance,
@Nullable Long rtsRouteTag, @Nullable Long rtsTripTag, @Nullable Integer rtsStopTag) {
//noinspection ConstantConditions
return new LocationPOI() {
@NonNull
@Override
public POI getPOI() {
if (rtsRouteTag != null && rtsTripTag != null && rtsStopTag != null) {
return new RouteTripStop(
"authority" + intTag,
1,
new Route(rtsRouteTag, "R" + rtsRouteTag, "Route " + rtsRouteTag, "000000"),
new Trip(rtsTripTag, Trip.HEADSIGN_TYPE_NONE, "head-sign " + rtsTripTag, rtsRouteTag),
new Stop(rtsStopTag, "" + rtsStopTag + "", "Stop #" + rtsStopTag, 0.0d, 0.0d, 0),
false
);
}
return new DefaultPOI("authority" + intTag, 1, POI.ITEM_VIEW_TYPE_BASIC_POI, POI.ITEM_STATUS_TYPE_NONE, POI.ITEM_ACTION_TYPE_NONE);
}
@Override
public double getLat() {
return 0d;
}
@Override
public double getLng() {
return 0d;
}
@Override
public boolean hasLocation() {
return true;
}
@NonNull
@Override
public LocationPOI setDistanceString(@Nullable CharSequence distanceString) {
throw new RuntimeException("This object is not compatible with distance string");
}
@Nullable
@Override
public CharSequence getDistanceString() {
return "tag" + intTag;
}
@NonNull
@Override
public LocationPOI setDistance(float distance) {
throw new RuntimeException("This object is not compatible with distance string");
}
@Override
public float getDistance() {
return distance;
}
@NonNull
@Override
public String toString() {
return "POI{" +
"tag=" + intTag +
", distance=" + distance +
'}';
}
};
}
}
| true |
fb9d892861d4ea1ea3674e6dc0beb7ddd1976a33 | Java | xiao098144/AndroidDemo | /app/src/main/java/com/xiao/demo/recyclerview/widget/customView/ViewPagerAdapter.java | UTF-8 | 1,063 | 2.328125 | 2 | [] | no_license | package com.xiao.demo.recyclerview.widget.customView;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* Description:
* Created on 2017/3/9
* Author : 萧
*/
public class ViewPagerAdapter extends PagerAdapter {
private List<ChooseScreenView> mListViews;
public ViewPagerAdapter(List<ChooseScreenView> mListViews) {
this.mListViews = mListViews;
}
@Override
public int getCount() {
return mListViews == null ? 0 : mListViews.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView(mListViews.get(position));
}
@Override
public Object instantiateItem(ViewGroup arg0, int arg1) {
arg0.addView(mListViews.get(arg1), 0);
return mListViews.get(arg1);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == (arg1);
}
}
| true |
ae3b27cccb63bf7a9a45213b6df15ae5865376b2 | Java | apache/netbeans | /enterprise/performance.scripting/test/qa-functional/src/org/netbeans/performance/languages/actions/CreatePHPSampleProjectTest.java | UTF-8 | 2,865 | 1.601563 | 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.netbeans.performance.languages.actions;
import junit.framework.Test;
import org.netbeans.modules.performance.utilities.PerformanceTestCase;
import org.netbeans.performance.languages.setup.ScriptingSetup;
import org.netbeans.jellytools.EditorOperator;
import static org.netbeans.jellytools.JellyTestCase.emptyConfiguration;
import org.netbeans.jellytools.NewProjectWizardOperator;
import org.netbeans.jemmy.operators.ComponentOperator;
import org.netbeans.modules.performance.guitracker.LoggingRepaintManager;
/**
*
* @author mkhramov@netbeans.org, mrkam@netbeans.org
*/
public class CreatePHPSampleProjectTest extends PerformanceTestCase {
private NewProjectWizardOperator wizard;
public CreatePHPSampleProjectTest(String testName) {
super(testName);
expectedTime = 10000;
WAIT_AFTER_OPEN = 5000;
}
public CreatePHPSampleProjectTest(String testName, String performanceDataName) {
super(testName, performanceDataName);
expectedTime = 10000;
WAIT_AFTER_OPEN = 5000;
}
public static Test suite() {
return emptyConfiguration()
.addTest(ScriptingSetup.class)
.addTest(CreatePHPSampleProjectTest.class)
.suite();
}
@Override
public void initialize() {
closeAllModal();
}
@Override
public void prepare() {
repaintManager().addRegionFilter(LoggingRepaintManager.IGNORE_STATUS_LINE_FILTER);
repaintManager().addRegionFilter(LoggingRepaintManager.IGNORE_DIFF_SIDEBAR_FILTER);
wizard = NewProjectWizardOperator.invoke();
wizard.selectCategory("Samples|PHP");
wizard.selectProject("TodoList - PHP Sample Application");
wizard.next();
}
@Override
public ComponentOperator open() {
wizard.finish();
return null;
}
@Override
public void close() {
EditorOperator.closeDiscardAll();
repaintManager().resetRegionFilters();
}
public void testCreatePhpSampleProject() {
doMeasurement();
}
}
| true |
acd8c04ae139c0c08ef2eb0b0bfb5bdade035f49 | Java | research-software-directory/RSD-as-a-service | /scrapers/src/main/java/nl/esciencecenter/rsd/scraper/doi/CrossrefMention.java | UTF-8 | 4,917 | 1.71875 | 2 | [
"CC0-1.0",
"CC-BY-4.0",
"Apache-2.0",
"Fair"
] | permissive | // SPDX-FileCopyrightText: 2022 - 2023 Ewan Cahen (Netherlands eScience Center) <e.cahen@esciencecenter.nl>
// SPDX-FileCopyrightText: 2022 - 2023 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 Dusan Mijatovic (dv4all)
// SPDX-FileCopyrightText: 2022 dv4all
//
// SPDX-License-Identifier: Apache-2.0
package nl.esciencecenter.rsd.scraper.doi;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import nl.esciencecenter.rsd.scraper.Config;
import nl.esciencecenter.rsd.scraper.Utils;
import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class CrossrefMention implements Mention {
private static final Map<String, MentionType> crossrefTypeMap;
static {
// https://api.crossref.org/types
crossrefTypeMap = new HashMap<>();
crossrefTypeMap.put("book-section", MentionType.bookSection);
crossrefTypeMap.put("monograph", MentionType.other);
crossrefTypeMap.put("report", MentionType.report);
crossrefTypeMap.put("peer-review", MentionType.other);
crossrefTypeMap.put("book-track", MentionType.book);
crossrefTypeMap.put("journal-article", MentionType.journalArticle);
crossrefTypeMap.put("book-part", MentionType.bookSection);
crossrefTypeMap.put("other", MentionType.other);
crossrefTypeMap.put("book", MentionType.book);
crossrefTypeMap.put("journal-volume", MentionType.journalArticle);
crossrefTypeMap.put("book-set", MentionType.book);
crossrefTypeMap.put("reference-entry", MentionType.other);
crossrefTypeMap.put("proceedings-article", MentionType.conferencePaper);
crossrefTypeMap.put("journal", MentionType.journalArticle);
crossrefTypeMap.put("component", MentionType.other);
crossrefTypeMap.put("book-chapter", MentionType.bookSection);
crossrefTypeMap.put("proceedings-series", MentionType.conferencePaper);
crossrefTypeMap.put("report-series", MentionType.report);
crossrefTypeMap.put("proceedings", MentionType.conferencePaper);
crossrefTypeMap.put("standard", MentionType.other);
crossrefTypeMap.put("reference-book", MentionType.book);
crossrefTypeMap.put("posted-content", MentionType.other);
crossrefTypeMap.put("journal-issue", MentionType.journalArticle);
crossrefTypeMap.put("dissertation", MentionType.thesis);
crossrefTypeMap.put("grant", MentionType.other);
crossrefTypeMap.put("dataset", MentionType.dataset);
crossrefTypeMap.put("book-series", MentionType.book);
crossrefTypeMap.put("edited-book", MentionType.book);
crossrefTypeMap.put("standard-series", MentionType.other);
}
private final String doi;
public CrossrefMention(String doi) {
this.doi = Objects.requireNonNull(doi);
}
@Override
public MentionRecord mentionData() {
StringBuilder url = new StringBuilder("https://api.crossref.org/works/" + Utils.urlEncode(doi));
Config.crossrefContactEmail().ifPresent(email -> url.append("?mailto=").append(email));
String responseJson = Utils.get(url.toString());
JsonObject jsonTree = JsonParser.parseString(responseJson).getAsJsonObject();
MentionRecord result = new MentionRecord();
JsonObject workJson = jsonTree.getAsJsonObject("message");
result.doi = doi;
result.url = URI.create("https://doi.org/" + Utils.urlEncode(result.doi));
result.title = workJson.getAsJsonArray("title").get(0).getAsString();
Collection<String> authors = new ArrayList<>();
Iterable<JsonObject> authorsJson = (Iterable) workJson.getAsJsonArray("author");
if (authorsJson != null) {
for (JsonObject authorJson : authorsJson) {
String givenName = Utils.stringOrNull(authorJson.get("given"));
String familyName = Utils.stringOrNull(authorJson.get("family"));
if (givenName == null && familyName == null) continue;
if (givenName == null) authors.add(familyName);
else if (familyName == null) authors.add(givenName);
else authors.add(givenName + " " + familyName);
}
result.authors = String.join(", ", authors);
}
result.publisher = Utils.stringOrNull(workJson.get("publisher"));
try {
result.publicationYear = Utils.integerOrNull(workJson.getAsJsonObject("published").getAsJsonArray("date-parts").get(0).getAsJsonArray().get(0));
} catch (RuntimeException e) {
// year not found, we leave it at null, nothing to do
}
if (workJson.getAsJsonArray("container-title").size() > 0) {
JsonArray journalTitles = workJson.getAsJsonArray("container-title");
result.journal = journalTitles.get(0).getAsString();
for (int i = 1; i < journalTitles.size(); i++) {
result.journal += ", " + journalTitles.get(i).getAsString();
}
}
result.page = Utils.stringOrNull(workJson.get("page"));
result.mentionType = crossrefTypeMap.getOrDefault(Utils.stringOrNull(workJson.get("type")), MentionType.other);
result.source = "Crossref";
result.scrapedAt = Instant.now();
return result;
}
}
| true |
9f9a2ff5d2b59922f871852c8d767222a3e1edd6 | Java | bcgit/bc-java | /core/src/main/jdk1.3/org/bouncycastle/crypto/CryptoServicesRegistrar.java | UTF-8 | 20,266 | 1.773438 | 2 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package org.bouncycastle.crypto;
import java.math.BigInteger;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.params.DHParameters;
import org.bouncycastle.crypto.params.DHValidationParameters;
import org.bouncycastle.crypto.params.DSAParameters;
import org.bouncycastle.crypto.params.DSAValidationParameters;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.Properties;
/**
* Basic registrar class for providing defaults for cryptography services in this module.
*/
public final class CryptoServicesRegistrar
{
private static final Permission CanSetDefaultProperty = new CryptoServicesPermission(CryptoServicesPermission.GLOBAL_CONFIG);
private static final Permission CanSetThreadProperty = new CryptoServicesPermission(CryptoServicesPermission.THREAD_LOCAL_CONFIG);
private static final Permission CanSetDefaultRandom = new CryptoServicesPermission(CryptoServicesPermission.DEFAULT_RANDOM);
private static final Permission CanSetConstraints = new CryptoServicesPermission(CryptoServicesPermission.CONSTRAINTS);
private static final ThreadLocal threadProperties = new ThreadLocal();
private static final Map globalProperties = Collections.synchronizedMap(new HashMap());
private static final Object cacheLock = new Object();
private static SecureRandomProvider defaultSecureRandomProvider;
private static final CryptoServicesConstraints noConstraintsImpl = new CryptoServicesConstraints()
{
public void check(CryptoServiceProperties service)
{
// anything goes.
}
};
private static CryptoServicesConstraints getDefaultConstraints()
{
// TODO: return one based on system/security properties if set.
return noConstraintsImpl;
}
private static final boolean preconfiguredConstraints;
private static CryptoServicesConstraints servicesConstraints = noConstraintsImpl;
static
{
// default domain parameters for DSA and Diffie-Hellman
DSAParameters def512Params = new DSAParameters(
new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17", 16),
new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16),
new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4", 16),
new DSAValidationParameters(Hex.decodeStrict("b869c82b35d70e1b1ff91b28e37a62ecdc34409b"), 123));
DSAParameters def768Params = new DSAParameters(
new BigInteger("e9e642599d355f37c97ffd3567120b8e25c9cd43e927b3a9670fbec5" +
"d890141922d2c3b3ad2480093799869d1e846aab49fab0ad26d2ce6a" +
"22219d470bce7d777d4a21fbe9c270b57f607002f3cef8393694cf45" +
"ee3688c11a8c56ab127a3daf", 16),
new BigInteger("9cdbd84c9f1ac2f38d0f80f42ab952e7338bf511", 16),
new BigInteger("30470ad5a005fb14ce2d9dcd87e38bc7d1b1c5facbaecbe95f190aa7" +
"a31d23c4dbbcbe06174544401a5b2c020965d8c2bd2171d366844577" +
"1f74ba084d2029d83c1c158547f3a9f1a2715be23d51ae4d3e5a1f6a" +
"7064f316933a346d3f529252", 16),
new DSAValidationParameters(Hex.decodeStrict("77d0f8c4dad15eb8c4f2f8d6726cefd96d5bb399"), 263));
DSAParameters def1024Params = new DSAParameters(
new BigInteger("fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80" +
"b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b" +
"801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c6" +
"1bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675" +
"f3ae2b61d72aeff22203199dd14801c7", 16),
new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5", 16),
new BigInteger("f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b" +
"3d0782675159578ebad4594fe67107108180b449167123e84c281613" +
"b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f" +
"0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06" +
"928b665e807b552564014c3bfecf492a", 16),
new DSAValidationParameters(Hex.decodeStrict("8d5155894229d5e689ee01e6018a237e2cae64cd"), 92));
DSAParameters def2048Params = new DSAParameters(
new BigInteger("95475cf5d93e596c3fcd1d902add02f427f5f3c7210313bb45fb4d5b" +
"b2e5fe1cbd678cd4bbdd84c9836be1f31c0777725aeb6c2fc38b85f4" +
"8076fa76bcd8146cc89a6fb2f706dd719898c2083dc8d896f84062e2" +
"c9c94d137b054a8d8096adb8d51952398eeca852a0af12df83e475aa" +
"65d4ec0c38a9560d5661186ff98b9fc9eb60eee8b030376b236bc73b" +
"e3acdbd74fd61c1d2475fa3077b8f080467881ff7e1ca56fee066d79" +
"506ade51edbb5443a563927dbc4ba520086746175c8885925ebc64c6" +
"147906773496990cb714ec667304e261faee33b3cbdf008e0c3fa906" +
"50d97d3909c9275bf4ac86ffcb3d03e6dfc8ada5934242dd6d3bcca2" +
"a406cb0b", 16),
new BigInteger("f8183668ba5fc5bb06b5981e6d8b795d30b8978d43ca0ec572e37e09939a9773", 16),
new BigInteger("42debb9da5b3d88cc956e08787ec3f3a09bba5f48b889a74aaf53174" +
"aa0fbe7e3c5b8fcd7a53bef563b0e98560328960a9517f4014d3325f" +
"c7962bf1e049370d76d1314a76137e792f3f0db859d095e4a5b93202" +
"4f079ecf2ef09c797452b0770e1350782ed57ddf794979dcef23cb96" +
"f183061965c4ebc93c9c71c56b925955a75f94cccf1449ac43d586d0" +
"beee43251b0b2287349d68de0d144403f13e802f4146d882e057af19" +
"b6f6275c6676c8fa0e3ca2713a3257fd1b27d0639f695e347d8d1cf9" +
"ac819a26ca9b04cb0eb9b7b035988d15bbac65212a55239cfc7e58fa" +
"e38d7250ab9991ffbc97134025fe8ce04c4399ad96569be91a546f49" +
"78693c7a", 16),
new DSAValidationParameters(Hex.decodeStrict("b0b4417601b59cbc9d8ac8f935cadaec4f5fbb2f23785609ae466748d9b5a536"), 497));
localSetGlobalProperty(Property.DSA_DEFAULT_PARAMS, new Object[] { def512Params, def768Params, def1024Params, def2048Params });
localSetGlobalProperty(Property.DH_DEFAULT_PARAMS, new Object[] { toDH(def512Params), toDH(def768Params), toDH(def1024Params), toDH(def2048Params) });
servicesConstraints = getDefaultConstraints();
preconfiguredConstraints = (servicesConstraints != noConstraintsImpl);
}
private CryptoServicesRegistrar()
{
}
/**
* Return the default source of randomness.
*
* @return the default SecureRandom
*/
public static SecureRandom getSecureRandom()
{
synchronized (cacheLock)
{
if (null != defaultSecureRandomProvider)
{
return defaultSecureRandomProvider.get();
}
}
final SecureRandom tmp = new SecureRandom();
synchronized (cacheLock)
{
if (null == defaultSecureRandomProvider)
{
defaultSecureRandomProvider = new SecureRandomProvider()
{
public SecureRandom get()
{
return tmp;
}
};
}
return defaultSecureRandomProvider.get();
}
}
/**
* Return either the passed-in SecureRandom, or if it is null, then the default source of randomness.
*
* @param secureRandom the SecureRandom to use if it is not null.
* @return the SecureRandom parameter if it is not null, or else the default SecureRandom
*/
public static SecureRandom getSecureRandom(SecureRandom secureRandom)
{
return null == secureRandom ? getSecureRandom() : secureRandom;
}
/**
* Set a default secure random to be used where none is otherwise provided.
*
* @param secureRandom the SecureRandom to use as the default.
*/
public static void setSecureRandom(final SecureRandom secureRandom)
{
checkPermission(CanSetDefaultRandom);
synchronized (cacheLock)
{
if (secureRandom == null)
{
defaultSecureRandomProvider = null;
}
else
{
defaultSecureRandomProvider = new SecureRandomProvider()
{
public SecureRandom get()
{
return secureRandom;
}
};
}
}
}
/**
* Set a default secure random provider to be used where none is otherwise provided.
*
* @param secureRandomProvider a provider SecureRandom to use when a default SecureRandom is requested.
*/
public static void setSecureRandomProvider(SecureRandomProvider secureRandomProvider)
{
checkPermission(CanSetDefaultRandom);
defaultSecureRandomProvider = secureRandomProvider;
}
/**
* Return the current algorithm/services constraints.
*
* @return the algorithm/services constraints.
*/
public static CryptoServicesConstraints getServicesConstraints()
{
return servicesConstraints;
}
/**
* Check a service to make sure it meets the current constraints.
*
* @param cryptoService the service to be checked.
* @throws CryptoServiceConstraintsException if the service violates the current constraints.
*/
public static void checkConstraints(CryptoServiceProperties cryptoService)
{
servicesConstraints.check(cryptoService);
}
/**
* Set the current algorithm constraints.
*/
public static void setServicesConstraints(CryptoServicesConstraints constraints)
{
checkPermission(CanSetConstraints);
CryptoServicesConstraints newConstraints = (constraints == null) ? noConstraintsImpl : constraints;
if (preconfiguredConstraints)
{
if (Properties.isOverrideSet("org.bouncycastle.constraints.allow_override"))
{
servicesConstraints = newConstraints;
}
else
{
//LOG.warning("attempt to override pre-configured constraints ignored");
}
}
else
{
// TODO: should this only be allowed once?
servicesConstraints = newConstraints;
}
}
/**
* Return the default value for a particular property if one exists. The look up is done on the thread's local
* configuration first and then on the global configuration in no local configuration exists.
*
* @param property the property to look up.
* @param <T> the type to be returned
* @return null if the property is not set, the default value otherwise,
*/
public static Object getProperty(Property property)
{
Object[] values = lookupProperty(property);
if (values != null)
{
return values[0];
}
return null;
}
private static Object[] lookupProperty(Property property)
{
Map properties = (Map)threadProperties.get();
Object[] values;
if (properties == null || !properties.containsKey(property.name))
{
values = (Object[])globalProperties.get(property.name);
}
else
{
values = (Object[])properties.get(property.name);
}
return values;
}
/**
* Return an array representing the current values for a sized property such as DH_DEFAULT_PARAMS or
* DSA_DEFAULT_PARAMS.
*
* @param property the name of the property to look up.
* @param <T> the base type of the array to be returned.
* @return null if the property is not set, an array of the current values otherwise.
*/
public static Object[] getSizedProperty(Property property)
{
Object[] values = lookupProperty(property);
if (values == null)
{
return null;
}
return (Object[])values.clone();
}
/**
* Return the value for a specific size for a sized property such as DH_DEFAULT_PARAMS or
* DSA_DEFAULT_PARAMS.
*
* @param property the name of the property to look up.
* @param size the size (in bits) of the defining value in the property type.
* @param <T> the type of the value to be returned.
* @return the current value for the size, null if there is no value set,
*/
public static Object getSizedProperty(Property property, int size)
{
Object[] values = lookupProperty(property);
if (values == null)
{
return null;
}
if (property.type.isAssignableFrom(DHParameters.class))
{
for (int i = 0; i != values.length; i++)
{
DHParameters params = (DHParameters)values[i];
if (params.getP().bitLength() == size)
{
return params;
}
}
}
else if (property.type.isAssignableFrom(DSAParameters.class))
{
for (int i = 0; i != values.length; i++)
{
DSAParameters params = (DSAParameters)values[i];
if (params.getP().bitLength() == size)
{
return params;
}
}
}
return null;
}
/**
* Set the value of the the passed in property on the current thread only. More than
* one value can be passed in for a sized property. If more than one value is provided the
* first value in the argument list becomes the default value.
*
* @param property the name of the property to set.
* @param propertyValue the values to assign to the property.
* @param <T> the base type of the property value.
*/
public static void setThreadProperty(Property property, Object[] propertyValue)
{
checkPermission(CanSetThreadProperty);
if (!property.type.isAssignableFrom(propertyValue[0].getClass()))
{
throw new IllegalArgumentException("Bad property value passed");
}
localSetThread(property, (Object[])propertyValue.clone());
}
/**
* Set the value of the the passed in property globally in the JVM. More than
* one value can be passed in for a sized property. If more than one value is provided the
* first value in the argument list becomes the default value.
*
* @param property the name of the property to set.
* @param propertyValue the values to assign to the property.
* @param <T> the base type of the property value.
*/
public static void setGlobalProperty(Property property, Object[] propertyValue)
{
checkPermission(CanSetDefaultProperty);
localSetGlobalProperty(property, (Object[])propertyValue.clone());
}
private static void localSetThread(Property property, Object[] propertyValue)
{
Map properties = (Map)threadProperties.get();
if (properties == null)
{
properties = new HashMap();
threadProperties.set(properties);
}
properties.put(property.name, propertyValue);
}
private static void localSetGlobalProperty(Property property, Object[] propertyValue)
{
if (!property.type.isAssignableFrom(propertyValue[0].getClass()))
{
throw new IllegalArgumentException("Bad property value passed");
}
// set the property for the current thread as well to avoid mass confusion
localSetThread(property, propertyValue);
globalProperties.put(property.name, propertyValue);
}
/**
* Clear the global value for the passed in property.
*
* @param property the property to be cleared.
* @param <T> the base type of the property value
* @return an array of T if a value was previously set, null otherwise.
*/
public static Object[] clearGlobalProperty(Property property)
{
checkPermission(CanSetDefaultProperty);
// clear the property for the current thread as well to avoid confusion
localClearThreadProperty(property);
return (Object[])globalProperties.remove(property.name);
}
/**
* Clear the thread local value for the passed in property.
*
* @param property the property to be cleared.
* @param <T> the base type of the property value
* @return an array of T if a value was previously set, null otherwise.
*/
public static Object[] clearThreadProperty(Property property)
{
checkPermission(CanSetThreadProperty);
return (Object[])localClearThreadProperty(property);
}
private static Object[] localClearThreadProperty(Property property)
{
Map properties = (Map)threadProperties.get();
if (properties == null)
{
properties = new HashMap();
threadProperties.set(properties);
}
return (Object[])properties.remove(property.name);
}
private static void checkPermission(final Permission permission)
{
final SecurityManager securityManager = System.getSecurityManager();
if (securityManager != null)
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
securityManager.checkPermission(permission);
return null;
}
});
}
}
private static DHParameters toDH(DSAParameters dsaParams)
{
int pSize = dsaParams.getP().bitLength();
int m = chooseLowerBound(pSize);
return new DHParameters(dsaParams.getP(), dsaParams.getG(), dsaParams.getQ(), m, 0, null,
new DHValidationParameters(dsaParams.getValidationParameters().getSeed(), dsaParams.getValidationParameters().getCounter()));
}
// based on lower limit of at least 2^{2 * bits_of_security}
private static int chooseLowerBound(int pSize)
{
int m = 160;
if (pSize > 1024)
{
if (pSize <= 2048)
{
m = 224;
}
else if (pSize <= 3072)
{
m = 256;
}
else if (pSize <= 7680)
{
m = 384;
}
else
{
m = 512;
}
}
return m;
}
/**
* Available properties that can be set.
*/
public static final class Property
{
/**
* The parameters to be used for processing implicitlyCA X9.62 parameters
*/
public static final Property EC_IMPLICITLY_CA = new Property("ecImplicitlyCA", X9ECParameters.class);
/**
* The default parameters for a particular size of Diffie-Hellman key.This is a sized property.
*/
public static final Property DH_DEFAULT_PARAMS= new Property("dhDefaultParams", DHParameters.class);
/**
* The default parameters for a particular size of DSA key. This is a sized property.
*/
public static final Property DSA_DEFAULT_PARAMS= new Property("dsaDefaultParams", DSAParameters.class);
private final String name;
private final Class type;
private Property(String name, Class type)
{
this.name = name;
this.type = type;
}
}
}
| true |
4a53b442af5ecda93cdda539eda5a710807067aa | Java | xopheS/Gameboy | /src/ch/epfl/gameboj/component/memory/RamController.java | UTF-8 | 3,761 | 3.171875 | 3 | [] | no_license | package ch.epfl.gameboj.component.memory;
import java.util.Objects;
import ch.epfl.gameboj.Preconditions;
import ch.epfl.gameboj.component.Component;
/**
* RamController : une mémoire vive dont le contenu peut changer au cours du temps.
*
* @author Christophe Saad (282557)
* @author David Cian (287967)
*/
public class RamController implements Component {
private final Ram ram;
private final int startAddress;
private final int endAddress;
/**
* Construit un contrôleur pour la mémoire vive donnée en argument,
* accessible entre deux adresses données.
*
* @param ram
* mémoire vive
* @param startAddress
* adresse de début
* @param endAddress
* adresse de fin
* @throws NullPointerException
* si la mémoire vive est nulle
* @throws IllegalArgumentException
* si les adresses ne sont pas des valeurs de 16 bits
* si l'intervalle qu'elles décrivent a une taille négative ou
* supérieure à celle de la mémoire
*
*/
public RamController(Ram ram, int startAddress, int endAddress) {
Preconditions.checkArgument(endAddress - startAddress >= 0 && endAddress - startAddress <= ram.size());
this.startAddress = Preconditions.checkBits16(startAddress);
this.endAddress = Preconditions.checkBits16(endAddress);
this.ram = Objects.requireNonNull(ram);
}
/**
* Appelle le premier constructeur en lui passant une adresse de fin telle
* que la totalité de la mémoire vive soit accessible au travers du
* contrôleur (l'adresse de fin est l'adresse de début + la taille de la
* mémoire vive).
*
* @param ram
* mémoire vive
* @param startAddress
* adresse de début
* @throws NullPointerException
* si la mémoire vive est nulle
* @throws IllegalArgumentException
* si les adresses ne sont pas des valeurs de 16 bits
* si l'intervalle qu'elles décrivent a une taille négative ou
* supérieure à celle de la mémoire
*
*/
public RamController(Ram ram, int startAddress) {
this(ram, startAddress, startAddress + ram.size());
}
/**
* Retourne l'octet se trouvant à l'adresse donnée dans la mémoire vive sous
* la forme d'un entier ou NO_DATA (256) si l'adresse n'est pas dans
* l'intervalle de contrôle du RamController.
*
* @param address l'adresse
* @throws IllegalArgumentException
* si l'adresse n'est pas une valeur de 16 bits
*/
@Override
public int read(int address) {
if (Preconditions.checkBits16(address) < startAddress || address >= endAddress) {
return NO_DATA;
}
return ram.read(address - startAddress);
}
/**
* Modifie le contenu de la mémoire vive à l'adresse donnée pour qu'il soit
* égal à la valeur donnée si celle-ci se trouve dans l'intervalle de
* contrôle du RamController.
*
* @param address
* l'adresse
* @param data
* la valeur
* @throws IllegalArgumentException
* si l'adresse n'est pas une valeur de 16 bits
* si la valeur n'est pas une valeur de 8 bits
*
*/
@Override
public void write(int address, int data) {
if (Preconditions.checkBits16(address) >= startAddress && address < endAddress) {
ram.write(address - startAddress, Preconditions.checkBits8(data));
}
}
}
| true |
1a5610ea2d2b76f1fd45c4d6db728e5ec82f6c1c | Java | pranavlathigara/AndroidLife | /app/src/main/java/com/camnter/newlife/robotlegs/robotlegs4android/view/adapter/Robotlegs4AndroidAdapter.java | UTF-8 | 1,487 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package com.camnter.newlife.robotlegs.robotlegs4android.view.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Description:Robotlegs4AndroidAdapter
* Created by:CaMnter
* Time:2015-11-06 17:05
*/
public class Robotlegs4AndroidAdapter extends FragmentPagerAdapter {
private String[] tabTitles;
private Fragment[] fragments;
public Robotlegs4AndroidAdapter(FragmentManager fm, Fragment[] fragments, String[] tabTitles) {
super(fm);
this.fragments = fragments;
this.tabTitles = tabTitles;
}
/**
* Return the Fragment associated with a specified position.
*
* @param position
*/
@Override
public Fragment getItem(int position) {
return this.fragments[position];
}
/**
* Return the number of views available.
*/
@Override
public int getCount() {
return this.fragments.length;
}
/**
* This method may be called by the ViewPager to obtain a title string
* to describe the specified page. This method may return null
* indicating no title for this page. The default implementation returns
* null.
*
* @param position The position of the title requested
* @return A title for the requested page
*/
@Override
public CharSequence getPageTitle(int position) {
return this.tabTitles[position];
}
}
| true |
cfa04f416b6a73e8957533e9186213422b3b56f1 | Java | xjie1070160377/AppCenter | /app.cms/src/main/java/cn/mooc/app/module/cms/model/MobileSpecial.java | UTF-8 | 2,831 | 2 | 2 | [] | no_license | package cn.mooc.app.module.cms.model;
import java.util.Date;
public class MobileSpecial {
private Integer id;
private Long creatorId;
private Date creationDate;
private String title;
private String metaKeywords;
private String metaDescription;
private String specialTemplate;
private String smallImage;
private String largeImage;
private String video;
private String videoName;
private Long videoLength;
private String videoTime;
private Integer refers;
private Integer views;
private Boolean withImage;
private Boolean recommend;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getCreatorId() {
return creatorId;
}
public void setCreatorId(Long creatorId) {
this.creatorId = creatorId;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMetaKeywords() {
return metaKeywords;
}
public void setMetaKeywords(String metaKeywords) {
this.metaKeywords = metaKeywords;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getSpecialTemplate() {
return specialTemplate;
}
public void setSpecialTemplate(String specialTemplate) {
this.specialTemplate = specialTemplate;
}
public String getSmallImage() {
return smallImage;
}
public void setSmallImage(String smallImage) {
this.smallImage = smallImage;
}
public String getLargeImage() {
return largeImage;
}
public void setLargeImage(String largeImage) {
this.largeImage = largeImage;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public Long getVideoLength() {
return videoLength;
}
public void setVideoLength(Long videoLength) {
this.videoLength = videoLength;
}
public String getVideoTime() {
return videoTime;
}
public void setVideoTime(String videoTime) {
this.videoTime = videoTime;
}
public Integer getRefers() {
return refers;
}
public void setRefers(Integer refers) {
this.refers = refers;
}
public Integer getViews() {
return views;
}
public void setViews(Integer views) {
this.views = views;
}
public Boolean getWithImage() {
return withImage;
}
public void setWithImage(Boolean withImage) {
this.withImage = withImage;
}
public Boolean getRecommend() {
return recommend;
}
public void setRecommend(Boolean recommend) {
this.recommend = recommend;
}
}
| true |
2e14a0c623ebafb26dcf0f9704c3d35b4c31ca0a | Java | tvdinh1008/ScrollView | /app/src/main/java/com/example/scrollview/ItemModel.java | UTF-8 | 893 | 2.515625 | 3 | [] | no_license | package com.example.scrollview;
public class ItemModel {
String lable;
int thumbnailResource;//ảnh nhỏ thumbnail
int imageResource;//ảnh to wall
public ItemModel(String lable, int thumbnailResource, int imageResource) {
this.lable = lable;
this.thumbnailResource = thumbnailResource;
this.imageResource = imageResource;
}
public String getLable() {
return lable;
}
public void setLable(String lable) {
this.lable = lable;
}
public int getThumbnailResource() {
return thumbnailResource;
}
public void setThumbnailResource(int thumbnailResource) {
this.thumbnailResource = thumbnailResource;
}
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
}
| true |
b5207f27f9af037f7b4bc30703d11fb999ee4679 | Java | BabtuhAuss/Frise_chronologique | /Projet_Tuteure/src/modele/FriseTest.java | ISO-8859-1 | 649 | 2.625 | 3 | [] | no_license | package modele;
import java.util.HashMap;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
class FriseTest extends TestCase {
@Test
void testAjoutEvenement() {
Evenement monEvt = new Evenement(new Date(1, 1, 2010), "event", "descripto", 0, "");
Frise maFrise = new Frise("Ma frise de test", 2000,2018, 2);
maFrise.ajout(monEvt);
for(Evenement evt : maFrise.getEvenements()) {
if(evt.toString().equals("event")) {
return;
}
}
fail("L'ajout de l'vnement a chou !");
}
@Test
void testEcritureFrise() {
fail("la frise n'a pas t ecrite !");
}
}
| true |
14db86ac0ed9ad42ddd7725bc6e540339d40b302 | Java | cefran/CheckerGit | /Moodwalk/src/com/example/moodwalk/activities/Connexion_activity.java | UTF-8 | 1,022 | 2.234375 | 2 | [] | no_license | package com.example.moodwalk.activities;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.example.moodwalk.fragments.MainFragment;
public class Connexion_activity extends FragmentActivity {
private MainFragment mainFragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
public void Save(String User) throws FileNotFoundException{
}
}
| true |
c4faf3dbd83edca162982277b207c0b3d5791ac9 | Java | xpsky202/Kingdee_PurCloud | /PurCloud/src/com/kingdee/purchase/platform/dao/alibaba/Company2AliAccountDaoImpl.java | UTF-8 | 6,498 | 2.046875 | 2 | [] | no_license | package com.kingdee.purchase.platform.dao.alibaba;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.kingdee.purchase.platform.dao.BaseDao;
import com.kingdee.purchase.platform.dao.rowmapper.Company2AliAccountRowMapper;
import com.kingdee.purchase.platform.exception.PurDBException;
import com.kingdee.purchase.platform.info.KeyValue;
import com.kingdee.purchase.platform.info.alibaba.Company2AccountInfo;
@Repository
public class Company2AliAccountDaoImpl extends BaseDao<Company2AccountInfo> implements ICompany2AccountDao {
@Autowired
public Company2AliAccountDaoImpl(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate, new Company2AliAccountRowMapper());
}
@Override
protected String getTableName() {
return "t_map_company_ali";
}
public int insert(Company2AccountInfo t) throws PurDBException {
String sql = "insert into t_map_company_ali(enterpriseid,companyid,accountid) values(?,?,?)";
int result = getJdbcTemplate().update(sql,
new Object[] { t.getEnterpriseId(), t.getCompanyId(), t.getAccountId() });
obtainInsertId(t);
return result;
}
public int update(Company2AccountInfo t) throws PurDBException {
return 0;
}
public Company2AccountInfo getCompany2AccountInfo(long enterpriseid, String companyid) throws PurDBException {
String sql = "select * from t_map_company_ali where enterpriseid = ? and companyid = ?";
try {
List<Company2AccountInfo> list = getJdbcTemplate().query(sql, new Object[] { enterpriseid, companyid },
getRowMapper());
if (null != list && list.size() > 0) {
return list.get(0);
}
} catch (DataAccessException e) {
throw new PurDBException(e.getMessage());
}
return null;
}
public List<Company2AccountInfo> getAllCompany2AccountList() throws PurDBException {
String sql = "select * from t_map_company_ali";
try {
return getJdbcTemplate().query(sql, getRowMapper());
} catch (DataAccessException e) {
throw new PurDBException(e.getMessage());
}
}
public List<Company2AccountInfo> getCompanyList(long enterpriseid) throws PurDBException {
String sql = "select * from t_map_company_ali where enterpriseid = ?";
try {
return getJdbcTemplate().query(sql, new Object[] { enterpriseid }, getRowMapper());
} catch (DataAccessException e) {
throw new PurDBException(e.getMessage());
}
}
public int saveCompanyInfo(long enterpriseId, List<KeyValue> companysList) throws PurDBException {
final Set<String> companyIdSet = new HashSet<String>();
StringBuilder ids = new StringBuilder();
for (KeyValue kv : companysList) {
ids.append("'").append(kv.getKey()).append("',");
}
ids.setLength(ids.length() - 1);
String selectSql = "select companyid from t_map_company_ali where enterpriseid=? and companyid in (" + ids
+ ")";
getJdbcTemplate().query(selectSql, new Object[] { enterpriseId }, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
companyIdSet.add(rs.getString("companyid"));
}
});
List<Object[]> params = new ArrayList<Object[]>();
for (KeyValue kv : companysList) {
if (companyIdSet.contains(kv.getKey())) {
continue;
}
Object[] paramObjects = new Object[] { enterpriseId, kv.getKey(), kv.getValue() };
params.add(paramObjects);
}
if (params.size() > 0) {
String sql = " insert into t_map_company_ali(enterpriseid,companyid,companyname) values(?,?,?)";
int[] argTypes = new int[] { Types.BIGINT, Types.VARCHAR, Types.VARCHAR };
return getJdbcTemplate().batchUpdate(sql, params, argTypes).length;
}
return 0;
}
public int updateCompany2AccountMapping(long enterpriseId, List<Company2AccountInfo> companysList)
throws PurDBException {
String sql = "update t_map_company_ali set accountid = ?, token = ? where id = ? and enterpriseid = ?";
List<Object[]> paramsList = new ArrayList<Object[]>();
Object[] paramsObjects;
for (Company2AccountInfo kv : companysList) {
paramsObjects = new Object[] { kv.getAccountId(), kv.getToken(), kv.getId(), enterpriseId };
paramsList.add(paramsObjects);
}
int[] argTypes = new int[] { java.sql.Types.VARCHAR, java.sql.Types.VARCHAR, java.sql.Types.BIGINT,
java.sql.Types.BIGINT };
return getJdbcTemplate().batchUpdate(sql, paramsList, argTypes).length;
}
public int updateCompany2AccountMapping(long enterpriseId, String companyId, String memberId, String token,
Date expiredDate) throws PurDBException {
String sql = " update t_map_company_ali set accountid = ?, token = ?, expireddate = ? "
+ " where companyId = ? and enterpriseid = ?";
Object[] params = new Object[] { memberId, token, expiredDate, companyId, enterpriseId };
int[] types = new int[] { Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.BIGINT };
return getJdbcTemplate().update(sql, params, types);
}
public Company2AccountInfo getCompany2AccountInfo(String accountId) throws PurDBException {
String sql = "select * from t_map_company_ali where accountid = ?";
Object[] params = new Object[] { accountId };
int[] types = new int[] { Types.VARCHAR };
try {
List<Company2AccountInfo> list = getJdbcTemplate().query(sql, params, types, getRowMapper());
if (list != null && list.size() > 0) {
return list.get(0);
}
} catch (RuntimeException e) {
throw new PurDBException(e);
}
return null;
}
public boolean hasAuthorized(String memberId,String companyId) throws PurDBException {
String selectSql = "select * from t_map_company_ali where accountid = ? and companyId != ? ";
List<Map<String, Object>> list = getJdbcTemplate().queryForList(selectSql, new Object[]{memberId,companyId});
if(list!=null && list.size()>0){
return true;
}
return false;
}
public boolean deleteCompany(long enterpriseId, String companyId) throws PurDBException {
String deleteSql = "delete from t_map_company_ali where enterpriseid = ? and companyId = ? ";
getJdbcTemplate().update(deleteSql, new Object[] {enterpriseId, companyId}, new int[] {Types.BIGINT, Types.VARCHAR});
return true;
}
} | true |
945a051fc143797cc08639f25ab4a03cb9f3e0bf | Java | toastedcode/SimpleGame | /src/com/toast/game/engine/interfaces/Drawable.java | UTF-8 | 208 | 2.40625 | 2 | [] | no_license | package com.toast.game.engine.interfaces;
import java.awt.Graphics;
public interface Drawable
{
public void draw(
Graphics graphics);
public int getWidth();
public int getHeight();
}
| true |
b5779d80f2a8b933e7ac1c06ab7bc5f88f00094f | Java | Rune-Status/open-osrs-client | /runescape-client/src/main/java/IsaacCipher.java | UTF-8 | 5,195 | 1.890625 | 2 | [
"BSD-2-Clause"
] | permissive | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("lw")
@Implements("IsaacCipher")
public final class IsaacCipher {
@ObfuscatedName("e")
@ObfuscatedGetter(
intValue = -1084674035
)
@Export("valuesRemaining")
int valuesRemaining;
@ObfuscatedName("i")
@Export("results")
int[] results;
@ObfuscatedName("g")
@Export("mm")
int[] mm;
@ObfuscatedName("d")
@ObfuscatedGetter(
intValue = 1881052481
)
@Export("aa")
int aa;
@ObfuscatedName("l")
@ObfuscatedGetter(
intValue = 1182669169
)
@Export("bb")
int bb;
@ObfuscatedName("j")
@ObfuscatedGetter(
intValue = -1353155945
)
@Export("cc")
int cc;
public IsaacCipher(int[] var1) {
this.mm = new int[256];
this.results = new int[256];
for (int var2 = 0; var2 < var1.length; ++var2) {
this.results[var2] = var1[var2];
}
this.method6314();
}
@ObfuscatedName("c")
@ObfuscatedSignature(
signature = "(S)I",
garbageValue = "32137"
)
@Export("nextInt")
public final int nextInt() {
if (this.valuesRemaining == 0) {
this.generateMoreResults();
this.valuesRemaining = 256;
}
return this.results[--this.valuesRemaining];
}
@ObfuscatedName("t")
@ObfuscatedSignature(
signature = "(B)I",
garbageValue = "1"
)
public final int method6307() {
if (this.valuesRemaining == 0) {
this.generateMoreResults();
this.valuesRemaining = 256;
}
return this.results[this.valuesRemaining - 1];
}
@ObfuscatedName("o")
@ObfuscatedSignature(
signature = "(I)V",
garbageValue = "16776960"
)
@Export("generateMoreResults")
final void generateMoreResults() {
this.bb += ++this.cc;
for (int var1 = 0; var1 < 256; ++var1) {
int var2 = this.mm[var1];
if ((var1 & 2) == 0) {
if ((var1 & 1) == 0) {
this.aa ^= this.aa << 13;
} else {
this.aa ^= this.aa >>> 6;
}
} else if ((var1 & 1) == 0) {
this.aa ^= this.aa << 2;
} else {
this.aa ^= this.aa >>> 16;
}
this.aa += this.mm[var1 + 128 & 255];
int var3;
this.mm[var1] = var3 = this.mm[(var2 & 1020) >> 2] + this.aa + this.bb;
this.results[var1] = this.bb = this.mm[(var3 >> 8 & 1020) >> 2] + var2;
}
}
@ObfuscatedName("e")
@ObfuscatedSignature(
signature = "(I)V",
garbageValue = "-1817393668"
)
final void method6314() {
int var9 = -1640531527;
int var8 = -1640531527;
int var7 = -1640531527;
int var6 = -1640531527;
int var5 = -1640531527;
int var4 = -1640531527;
int var3 = -1640531527;
int var2 = -1640531527;
int var1;
for (var1 = 0; var1 < 4; ++var1) {
var2 ^= var3 << 11;
var5 += var2;
var3 += var4;
var3 ^= var4 >>> 2;
var6 += var3;
var4 += var5;
var4 ^= var5 << 8;
var7 += var4;
var5 += var6;
var5 ^= var6 >>> 16;
var8 += var5;
var6 += var7;
var6 ^= var7 << 10;
var9 += var6;
var7 += var8;
var7 ^= var8 >>> 4;
var2 += var7;
var8 += var9;
var8 ^= var9 << 8;
var3 += var8;
var9 += var2;
var9 ^= var2 >>> 9;
var4 += var9;
var2 += var3;
}
for (var1 = 0; var1 < 256; var1 += 8) {
var2 += this.results[var1];
var3 += this.results[var1 + 1];
var4 += this.results[var1 + 2];
var5 += this.results[var1 + 3];
var6 += this.results[var1 + 4];
var7 += this.results[var1 + 5];
var8 += this.results[var1 + 6];
var9 += this.results[var1 + 7];
var2 ^= var3 << 11;
var5 += var2;
var3 += var4;
var3 ^= var4 >>> 2;
var6 += var3;
var4 += var5;
var4 ^= var5 << 8;
var7 += var4;
var5 += var6;
var5 ^= var6 >>> 16;
var8 += var5;
var6 += var7;
var6 ^= var7 << 10;
var9 += var6;
var7 += var8;
var7 ^= var8 >>> 4;
var2 += var7;
var8 += var9;
var8 ^= var9 << 8;
var3 += var8;
var9 += var2;
var9 ^= var2 >>> 9;
var4 += var9;
var2 += var3;
this.mm[var1] = var2;
this.mm[var1 + 1] = var3;
this.mm[var1 + 2] = var4;
this.mm[var1 + 3] = var5;
this.mm[var1 + 4] = var6;
this.mm[var1 + 5] = var7;
this.mm[var1 + 6] = var8;
this.mm[var1 + 7] = var9;
}
for (var1 = 0; var1 < 256; var1 += 8) {
var2 += this.mm[var1];
var3 += this.mm[var1 + 1];
var4 += this.mm[var1 + 2];
var5 += this.mm[var1 + 3];
var6 += this.mm[var1 + 4];
var7 += this.mm[var1 + 5];
var8 += this.mm[var1 + 6];
var9 += this.mm[var1 + 7];
var2 ^= var3 << 11;
var5 += var2;
var3 += var4;
var3 ^= var4 >>> 2;
var6 += var3;
var4 += var5;
var4 ^= var5 << 8;
var7 += var4;
var5 += var6;
var5 ^= var6 >>> 16;
var8 += var5;
var6 += var7;
var6 ^= var7 << 10;
var9 += var6;
var7 += var8;
var7 ^= var8 >>> 4;
var2 += var7;
var8 += var9;
var8 ^= var9 << 8;
var3 += var8;
var9 += var2;
var9 ^= var2 >>> 9;
var4 += var9;
var2 += var3;
this.mm[var1] = var2;
this.mm[var1 + 1] = var3;
this.mm[var1 + 2] = var4;
this.mm[var1 + 3] = var5;
this.mm[var1 + 4] = var6;
this.mm[var1 + 5] = var7;
this.mm[var1 + 6] = var8;
this.mm[var1 + 7] = var9;
}
this.generateMoreResults();
this.valuesRemaining = 256;
}
}
| true |
42a8412cbc35a2965110c86d76fdf76fada59acc | Java | qianyuhebb/day03_sprin_jdbcTemplate | /src/main/java/com/tc/dao/IaccountDao.java | UTF-8 | 340 | 1.820313 | 2 | [] | no_license | package com.tc.dao;
import com.tc.domain.AccountDO;
/**
* 时间: 2020/1/12
* 创建者: Administrator 钟文
* 描述:
* 参数:
* 返回值:
**/
public interface IaccountDao {
AccountDO findAccountByid(Integer id);
AccountDO findAccountByName(String name);
void updateAccount(AccountDO accountDO);
}
| true |
edcc6ccd986973db3d4f632e8a81c9f6defbc323 | Java | gshokida/PiedraPapelTijera | /src/juego/modelo/Juego.java | UTF-8 | 275 | 2.484375 | 2 | [] | no_license | package juego.modelo;
/**
* Created by german.shokida on 7/7/2016.
*/
public class Juego {
public String evaluarJugada(Jugada jugadaUno, Jugada jugadaDos) {
String resultado;
resultado = jugadaUno.versus(jugadaDos);
return resultado;
}
}
| true |
8824b63d9f079b01d1c8940810b358c12768c00d | Java | garygao88898/finalproject | /app/src/main/java/com/example/extstudent/mycamerashot2/MainActivity.java | UTF-8 | 1,821 | 2.453125 | 2 | [] | no_license | /***final project
Final Project
Yuan Gao
**/
package com.example.extstudent.mycamerashot2;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView garyImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button garyButton = (Button) findViewById(R.id.garyButton);
garyImageView = (ImageView) findViewById(R.id.garyImageView);
//Disable the button if the user has no camera
if(!hasCamera())
garyButton.setEnabled(false);
}
//Check if the user has a camera
private boolean hasCamera(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
//Launching the camera
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture and pass results along to onActivityResult
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
//If you want to return the image taken
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
//Get the photo
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
garyImageView.setImageBitmap(photo);
}
}
} | true |
ec815d5c18662e6d1cfe37b928384d4926d25d33 | Java | cgallardo520/Proyecto-Modelamiento | /Proyecto_modelamiento/src/clases/Tren.java | UTF-8 | 1,909 | 3.015625 | 3 | [] | no_license | package clases;
import java.util.ArrayList;
import java.util.List;
public class Tren {
private int codigo_identificacion;
private Jefe oJefe;
private MaquinaTractora oMaquina;
private List<Vagon> lstVagon;
private boolean disponible=true;
public Tren() {
// TODO Auto-generated constructor stub
}
public Tren(int codigo, Vagon oVagon, MaquinaTractora oMaquina) {
lstVagon=new ArrayList<Vagon>();
this.codigo_identificacion=codigo;
this.oMaquina=oMaquina;
this.lstVagon.add(oVagon);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "|Codigo: "+this.codigo_identificacion+"| #Vagones: "+this.lstVagon.size()+"| Jefe designado: "+this.oJefe.getNombre();
}
/**
* Agrega un vagon en lista de vagones del tren
* @param oVagon
*/
public void agregarVagon(Vagon oVagon) {
this.lstVagon.add(oVagon);
}
/**
* Retorna la disponibilidad del tren
* @return
*/
public boolean isDisponible() {
return this.disponible;
}
/**
* Enlista los vagones asociados al tren
*/
public void listarVagon() {
System.out.println("|Codigo |Capacidad|");
for(int i=0;i<this.lstVagon.size();i++) {
System.out.println("|"+(i+1)+" |"+"|"+this.lstVagon.get(i)+"|");
}
}
// Metodos getters - setters
public int getCodigo_identificacion() {
return codigo_identificacion;
}
public MaquinaTractora getoMaquina() {
return oMaquina;
}
public void setoMaquina(MaquinaTractora oMaquina) {
this.oMaquina = oMaquina;
}
public List<Vagon> getLstVagon() {
return lstVagon;
}
public void setLstVagon(List<Vagon> lstVagon) {
this.lstVagon = lstVagon;
}
public void setCodigo_identificacion(int codigo_identificacion) {
this.codigo_identificacion = codigo_identificacion;
}
public Jefe getoJefe() {
return oJefe;
}
public void setoJefe(Jefe oJefe) {
this.oJefe = oJefe;
this.disponible=false;
}
}
| true |
8aec279c920b875c77c03895950486520d166a56 | Java | ahopgood/Maven_Archetypes | /Spring-Hibernate_Archetype/src/test/java/com/alexander/maven/archetypes/dao/hibernate/TestHibernateDao.java | UTF-8 | 251 | 1.632813 | 2 | [] | no_license | package com.alexander.maven.archetypes.dao.hibernate;
import com.alexander.maven.archetypes.domain.TestEntity;
public class TestHibernateDao<T> extends AbstractHibernateDao<TestEntity> {
public TestHibernateDao() {
super(TestEntity.class);
}
}
| true |
9a5850222816f8477aa33781b24ce21bb4ef4a43 | Java | BackupTheBerlios/robonobo-svn | /robonobo/tags/0.4.0/gui/src/java/com/robonobo/gui/platform/UnknownPlatform.java | UTF-8 | 4,782 | 2.015625 | 2 | [] | no_license | package com.robonobo.gui.platform;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Event;
import java.awt.Font;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileSystemView;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.robonobo.common.concurrent.CatchingRunnable;
import com.robonobo.common.exceptions.SeekInnerCalmException;
import com.robonobo.common.util.CodeUtil;
import com.robonobo.core.Platform;
import com.robonobo.core.api.Robonobo;
import com.robonobo.core.itunes.ITunesService;
import com.robonobo.gui.MenuBar;
import com.robonobo.gui.RobonoboFrame;
public class UnknownPlatform extends Platform {
private Font tableBodyFont = new Font("sans-serif", Font.PLAIN, 12);
Log log;
protected RobonoboFrame rFrame;
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public void initRobonobo(Robonobo ro) {
log = LogFactory.getLog(getClass());
}
@Override
public JMenuBar getMenuBar(JFrame frame) {
return new MenuBar((RobonoboFrame) frame);
}
@Override
public void initMainWindow(JFrame frame) throws Exception {
rFrame = (RobonoboFrame) frame;
// TODO Auto-generated method stub
}
@Override
public void setLookAndFeel() {
// TODO Auto-generated method stub
}
@Override
public boolean shouldSetMenuBarOnDialogs() {
return false;
}
@Override
public File getDefaultHomeDirectory() {
return new File(FileSystemView.getFileSystemView().getDefaultDirectory(), ".robonobo");
}
@Override
public File getDefaultDownloadDirectory() {
String s = File.separator;
return new File(FileSystemView.getFileSystemView().getDefaultDirectory()+s+"Music"+s+"robonobo");
}
@Override
public boolean shouldShowPrefsInFileMenu() {
return true;
}
@Override
public boolean shouldShowQuitInFileMenu() {
return true;
}
@Override
public boolean shouldShowOptionsMenu() {
return true;
}
@Override
public boolean shouldShowAboutInHelpMenu() {
return true;
}
@Override
public int getNumberOfShakesForShakeyWindow() {
return 10;
}
@Override
public Font getTableBodyFont() {
return tableBodyFont;
}
@Override
public int getTrackProgressLabelWidth() {
return 70;
}
@Override
public boolean canDnDImport(DataFlavor[] transferFlavors) {
try {
DataFlavor flava = new DataFlavor("application/x-java-file-list; class=java.util.List");
for (DataFlavor dataFlavor : transferFlavors) {
if(flava.equals(dataFlavor))
return true;
}
return false;
} catch (ClassNotFoundException e) {
throw new SeekInnerCalmException();
}
}
@Override
public List<File> getDnDImportFiles(Transferable t) throws IOException {
try {
DataFlavor flava = new DataFlavor("application/x-java-file-list; class=java.util.List");
List result = (List) t.getTransferData(flava);
return result;
} catch (ClassNotFoundException e) {
throw new SeekInnerCalmException();
} catch (UnsupportedFlavorException e) {
log.error("Error getting DnD files", e);
return null;
}
}
@Override
public KeyStroke getAccelKeystroke(int key) {
return KeyStroke.getKeyStroke(key, Event.CTRL_MASK);
}
@Override
public int getCommandModifierMask() {
return Event.CTRL_MASK;
}
@Override
public boolean iTunesAvailable() {
return false;
}
@Override
public ITunesService getITunesService() {
return null;
}
@Override
public Color getLinkColor() {
return Color.BLUE;
}
@Override
public void customizeMainbarButtons(List<? extends JButton> btns) {
// Do nothing
}
@Override
public void customizeSearchTextField(JTextField field) {
// Do nothing
}
@Override
public void openUrl(String url) throws IOException {
// Make sure we're in java6+ so that we have the java desktop classes, otherwise pop up a warning
if(CodeUtil.javaMajorVersion() < 6) {
SwingUtilities.invokeLater(new CatchingRunnable() {
public void doRun() throws Exception {
JOptionPane.showMessageDialog(rFrame, "We are sorry - to open URLs from robonobo, you must be running java version 6 or higher. To get the latest version of java, visit http://java.sun.com");
}
});
return;
}
try {
Desktop.getDesktop().browse(new URI(url));
} catch (URISyntaxException e) {
throw new IOException(e);
}
}
}
| true |
cbf924b2f7191aa3695c85e1c2d7ecbed49e474a | Java | FearsomeFoursome/Module13Final2 | /3C_OrderSystem/src/Control/CommonConnection.java | UTF-8 | 2,031 | 2.953125 | 3 | [] | no_license | /*
* 3's Company (Amy Roberts, Bella Belova, Scott Young)
* "We pledge that we have complied with the AIC in this work."
*
* Class to handle establishing database connections
*/
package Control;
/**
* This class includes methods to establish SQL and MySQL database connections.
* @author Bella Belova
*/
public class CommonConnection {
private static final String MYSQLjdbcDriver = "com.mysql.jdbc.Driver";
private static final String MYSQLconnectionUrl = "jdbc:mysql://oak.safesecureweb.com:3306/nianbrandsco?zeroDateTimeBehavior=convertToNull";
private static final String MYSQLusername = "store";
private static final String MYSQLpassword = "testDB1234!";
private static java.sql.Connection mysqlConn;
private static java.sql.Connection sqlConn = null;
private static final String SQLjdbcDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String SQLconnectionUrl = "jdbc:sqlserver://localhost";
private static final String SQLusername = "sa";
private static final String SQLpassword = "password";
/**
* Retrieves the SQL connection.
* @return A pointer to the currently open SQL connection.
*/
public static java.sql.Connection getSQLConn()
{
return sqlConn;
}
/**
* Retrieves the MySQL connection.
* @return A pointer to the currently open MySQL connection.
*/
public static java.sql.Connection getMSQLConn()
{
return mysqlConn;
}
/**
* Initializes the MySQL connection.
*/
public static void initialize_Connection_MYSQL()
{
try{
mysqlConn = java.sql.DriverManager.getConnection(MYSQLconnectionUrl,MYSQLusername, MYSQLpassword);
} catch (java.sql.SQLException e){System.err.println(e); }
}
/**
* Initializes the SQL connection.
*/
public static void initialize_Connection_SQL()
{
try{
sqlConn = java.sql.DriverManager.getConnection(SQLconnectionUrl,SQLusername, SQLpassword);
} catch (java.sql.SQLException e){System.err.println(e); }
}
}
| true |
1cfef78ea77aede4fba9bf8c942354010f2affd2 | Java | zhongxingyu/Seer | /Diff-Raw-Data/11/11_1290dadbc3c12c40ad136ec709782d4470dc4a4e/AbstractAction/11_1290dadbc3c12c40ad136ec709782d4470dc4a4e_AbstractAction_t.java | UTF-8 | 591 | 2.15625 | 2 | [] | no_license | package org.shivas.server.core.actions;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
public abstract class AbstractAction implements Action {
private final SettableFuture<Action> endFuture = SettableFuture.create();
protected abstract void internalEnd() throws ActionException;
@Override
public void end() throws ActionException {
internalEnd();
endFuture.set(this);
}
@Override
public ListenableFuture<Action> endFuture() {
return endFuture;
}
}
| true |
96e08127e94d2d3c5a588058f133a797b44ab506 | Java | petardjokic/cinema | /src/test/java/rs/ac/bg/fon/cinema/mapper/MovieProductionCompanyMapperTest.java | UTF-8 | 2,365 | 2.5 | 2 | [] | no_license | package rs.ac.bg.fon.cinema.mapper;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import rs.ac.bg.fon.cinema.domain.Movie;
import rs.ac.bg.fon.cinema.domain.MovieProductionCompany;
import rs.ac.bg.fon.cinema.domain.ProductionCompany;
import rs.ac.bg.fon.cinema.mapper.setup.MovieSetup;
import rs.ac.bg.fon.cinema.mapper.setup.ProductionCompanySetup;
@Slf4j
class MovieProductionCompanyMapperTest extends BaseMapperTest {
@Autowired
private MovieProductionCompanyMapper movieProdCompMapper;
@Autowired
private MovieSetup movieSetup;
@Autowired
private ProductionCompanySetup productionCompanySetup;
@Test
void testCRUD() {
ProductionCompany prodComp1 = productionCompanySetup.productionCompanyFirstPC();
ProductionCompany prodComp2 = productionCompanySetup.productionCompanySecondPC();
Movie movie1 = movieSetup.movieBasicInstinct();
Movie movie2 = movieSetup.moviePulpFiction();
log.info("Adding a new movie prod comp");
MovieProductionCompany movieProdComp = MovieProductionCompany.builder()
.movieId(movie1.getId())
.productionCompany(prodComp1).build();
assertEquals(1, movieProdCompMapper.insert(movieProdComp));
log.info("Getting movie prod comp");
MovieProductionCompany movieProdCompDb = movieProdCompMapper.getById(movieProdComp.getId());
assertEquals(movieProdComp.getId(), movieProdCompDb.getId());
assertEquals(movieProdComp.getMovieId(), movieProdCompDb.getMovieId());
assertEquals(movieProdComp.getProductionCompany().getId(), movieProdCompDb.getProductionCompany().getId());
log.info("Updating movie prod comp");
movieProdComp.setMovieId(movie2.getId());
movieProdComp.setProductionCompany(prodComp2);
assertEquals(1, movieProdCompMapper.update(movieProdComp));
log.info("Getting movie prod comp");
movieProdCompDb = movieProdCompMapper.getById(movieProdComp.getId());
assertEquals(movieProdComp.getId(), movieProdCompDb.getId());
assertEquals(movieProdComp.getMovieId(), movieProdCompDb.getMovieId());
assertEquals(movieProdComp.getProductionCompany().getId(), movieProdCompDb.getProductionCompany().getId());
log.info("Deleting prod comp");
assertEquals(1, movieProdCompMapper.deleteById(movieProdComp.getId()));
}
}
| true |
4a842fc3a1e9c932d8603dc642c554afd5f292a0 | Java | vivekglobalintegrity/WarOfSquirrels | /src/main/java/fr/craftandconquest/warofsquirrels/objects/dbobject/Loan.java | UTF-8 | 10,271 | 2.078125 | 2 | [] | no_license | package fr.craftandconquest.warofsquirrels.objects.dbobject;
import com.flowpowered.math.vector.Vector3i;
import fr.craftandconquest.warofsquirrels.objects.Core;
import fr.craftandconquest.warofsquirrels.objects.database.GlobalLoan;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.world.World;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public class Loan extends DBObject {
private static String _fields =
"`" + GlobalLoan.PLAYER +
"`, `" + GlobalLoan.CITY +
"`, `" + GlobalLoan.LOANER +
"`, `" + GlobalLoan.SIGNX +
"`, `" + GlobalLoan.SIGNY +
"`, `" + GlobalLoan.SIGNZ +
"`, `" + GlobalLoan.CUBO +
"`, `" + GlobalLoan.BUYPRICE +
"`, `" + GlobalLoan.RENTPRICE +
"`, `" + GlobalLoan.WORLD + "`";
/* -- DB Fields -- */
private DBPlayer player = null;
private City city = null;
private DBPlayer loaner = null;
private Vector3i signLocation;
private Cubo cubo;
private int buyPrice;
private int rentPrice;
private World world;
/* -- Extra fields -- */
private Sign sign;
/*
** Constructors
*/
public Loan(DBPlayer player, Cubo cubo, Sign sign, int buyPrice, int rentPrice) {
this(player, null, cubo, sign, buyPrice, rentPrice);
}
public Loan(City city, Cubo cubo, Sign sign, int buyPrice, int rentPrice) {
this(null, city, cubo, sign, buyPrice, rentPrice);
}
private Loan(DBPlayer player, City city, Cubo cubo, Sign sign, int buyPrice, int rentPrice) {
super(GlobalLoan.ID, GlobalLoan.TABLENAME, _fields);
this.player = player;
this.city = city;
this.loaner = null;
this.signLocation = sign.getLocation().getBlockPosition();
this.cubo = cubo;
this.buyPrice = buyPrice;
this.rentPrice = rentPrice;
this.world = sign.getWorld();
this._primaryKeyValue = "" + this.add(
"" + (player == null ? "NULL" : "'" + player.getId() + "'")
+ ", " + (city == null ? "NULL" : city.getId())
+ ", NULL"
+ ", " + signLocation.getX()
+ ", " + signLocation.getY()
+ ", " + signLocation.getZ()
+ ", " + cubo.getId()
+ ", " + buyPrice
+ ", " + rentPrice
+ ", '" + world.getUniqueId() + "'");
cubo.setLoan(this);
this.sign = sign;
writeLog();
}
public Loan(ResultSet rs) throws SQLException {
super(GlobalLoan.ID, GlobalLoan.TABLENAME, _fields);
this._primaryKeyValue = rs.getString(GlobalLoan.ID);
if (rs.getString(GlobalLoan.PLAYER) != null)
this.player = Core.getPlayerHandler().get(rs.getString(GlobalLoan.PLAYER));
if (rs.getString(GlobalLoan.CITY) != null)
this.city = Core.getCityHandler().get(rs.getString(GlobalLoan.CITY));
if (rs.getString(GlobalLoan.LOANER) != null)
this.loaner = Core.getPlayerHandler().get(rs.getString(GlobalLoan.LOANER));
this.signLocation = new Vector3i(rs.getInt(GlobalLoan.SIGNX),
rs.getInt(GlobalLoan.SIGNY), rs.getInt(GlobalLoan.SIGNZ));
this.cubo = Core.getCuboHandler().get(rs.getInt(GlobalLoan.CUBO));
this.buyPrice = rs.getInt(GlobalLoan.BUYPRICE);
this.rentPrice = rs.getInt(GlobalLoan.RENTPRICE);
this.world = Core.getPlugin().getServer().getWorld(UUID.fromString(rs.getString(GlobalLoan.WORLD))).orElse(null);
this.sign = (Sign) world.getLocation(signLocation).getTileEntity().orElse(null);
this.cubo.setLoan(this);
}
public void actualize() {
Optional<SignData> optSignData = sign.get(SignData.class);
Text header = Text.of("<", (this.player != null ? this.player.getDisplayName() : this.city.getDisplayName()), ">");
Text price = Text.of("A > ", this.buyPrice, " : ", this.rentPrice, " < L");
Text locataire = Text.of((this.loaner == null ? "---" : this.loaner.getDisplayName()));
if (optSignData.isPresent()) {
final SignData d = optSignData.get();
d.set(d.getValue(Keys.SIGN_LINES).get().set(0, header));
d.set(d.getValue(Keys.SIGN_LINES).get().set(1, Text.of(cubo.getName())));
d.set(d.getValue(Keys.SIGN_LINES).get().set(2, price));
d.set(d.getValue(Keys.SIGN_LINES).get().set(3, locataire));
sign.offer(d);
}
}
public int getId() { return Integer.parseInt(_primaryKeyValue); }
public DBPlayer getPlayer() { return player; }
public void setPlayer(DBPlayer player) {
this.player = player;
this.edit(GlobalLoan.PLAYER, player == null ? "NULL" : "'" + player.getId() + "'");
}
public City getCity() { return city; }
public void setCity(City city) {
this.city = city;
this.edit(GlobalLoan.CITY, city == null ? "NULL" : "" + city.getId());
}
public DBPlayer getLoaner() { return loaner; }
public void setLoaner(DBPlayer loaner) {
this.loaner = loaner;
this.edit(GlobalLoan.LOANER, loaner == null ? "NULL" : "'" + loaner.getId() + "'");
}
public Vector3i getSignLocation() { return signLocation; }
public void setSignLocation(Vector3i signLocation) {
this.signLocation = signLocation;
this.edit(GlobalLoan.SIGNX, "" + signLocation.getX());
this.edit(GlobalLoan.SIGNY, "" + signLocation.getY());
this.edit(GlobalLoan.SIGNZ, "" + signLocation.getZ());
}
public Cubo getCubo() { return cubo; }
public void setCubo(Cubo cubo) {
this.cubo = cubo;
this.edit(GlobalLoan.CUBO, "" + cubo.getId());
}
public int getBuyPrice() { return buyPrice; }
public void setBuyPrice(int buyPrice) {
this.buyPrice = buyPrice;
this.edit(GlobalLoan.BUYPRICE, "" + buyPrice);
}
public int getRentPrice() { return rentPrice; }
public void setRentPrice(int rentPrice) {
this.rentPrice = rentPrice;
this.edit(GlobalLoan.RENTPRICE, "" + rentPrice);
}
public World getWorld() {
return world;
}
public void setWorld(World world) {
this.world = world;
this.edit(GlobalLoan.WORLD, "" + world.getUniqueId());
}
public Sign getSign() { return sign; }
public void setSign(Sign sign) { this.sign = sign; }
public void leave(Player player) {
if (this.loaner == Core.getPlayerHandler().get(player)) {
setLoaner(null);
player.sendMessage(Text.of(TextColors.BLUE, "Vous n'êtes plus locataire du cubo ",
TextColors.GOLD, this.cubo.getName(), TextColors.RESET));
announce(Text.of(TextColors.GOLD, Core.getPlayerHandler().get(player).getDisplayName(),
TextColors.BLUE, " n'est plus locataire du cubo ",
TextColors.GOLD, cubo.getName(), TextColors.RESET));
}
}
public void loan(Player player) {
DBPlayer dbPlayer = Core.getPlayerHandler().get(player);
if (this.loaner != null) {
dbPlayer.sendMessage(Text.of(TextColors.RED, "Il y a déjà un locataire.", TextColors.RESET));
return;
} else if (dbPlayer.getBalance() < buyPrice) {
dbPlayer.sendMessage(Text.of(TextColors.RED, "Vous n'avez pas assez d'argent pour faire ça.", TextColors.RESET));
return;
}
this.setLoaner(dbPlayer);
this.loaner.withdraw(buyPrice);
if (this.player != null)
this.player.insert(buyPrice);
else
this.city.insert(buyPrice);
announce(Text.of(TextColors.GOLD, dbPlayer.getDisplayName(), TextColors.GREEN, " est maintenant le locataire du cubo ", TextColors.GOLD, cubo.getName(), TextColors.RESET));
player.sendMessage(Text.of(TextColors.BLUE, "Vous êtes maintenant locataire du cubo ",
TextColors.GOLD, this.cubo.getName(),
TextColors.BLUE, " un montant de ", TextColors.GOLD, buyPrice,
TextColors.BLUE, " vous a été débité.", TextColors.RESET));
this.actualize();
}
private void announce(Text message) {
List<DBPlayer> list = new ArrayList<>();
list.add(cubo.getOwner());
if (player != null && !list.contains(player)) {
list.add(player);
} else if (city != null) {
if (!list.contains(city.getOwner()))
list.add(city.getOwner());
city.getAssistants().forEach(p -> {
if (!list.contains(p))
list.add(p);
});
}
list.forEach(p -> p.sendMessage(message));
}
public void payDay() {
if (loaner == null) return;
if (this.loaner.getBalance() >= this.rentPrice) {
if(this.player != null) this.player.insert(this.rentPrice);
else this.city.insert(rentPrice);
} else this.leave(this.player.getUser().getPlayer().get());
}
@Override
protected void writeLog() {
Core.getLogger().info("[Loan] (" + _fields + ") : #" + _primaryKeyValue
+ "," + (this.player == null ? "null" : this.player.getDisplayName())
+ "," + (this.city == null ? "null" : this.city.getDisplayName())
+ "," + (this.loaner == null ? "null" : this.loaner.getDisplayName())
+ ",[" + this.signLocation.getX() + ";" + this.signLocation.getY()
+ ";" + this.signLocation.getZ() + "]"
+ "," + this.cubo.getName()
+ "," + this.buyPrice + "," + this.rentPrice + "," + this.world.getUniqueId().toString());
}
}
| true |
400eb336e2db8a117cfbf9d6478d7a0bd9763c0f | Java | muwp/msharp-sharding-jdbc | /single-core/src/main/java/com/msharp/single/jdbc/jtemplate/enums/SqlType.java | UTF-8 | 205 | 1.679688 | 2 | [] | no_license | package com.msharp.single.jdbc.jtemplate.enums;
/**
* SqlType
*
* @author mwup
* @version 1.0
* @created 2019/02/15 13:51
**/
public enum SqlType {
SELECT,
INSERT,
UPDATE,
DELETE
}
| true |
246dc3f7d81775310182e94e51271fc46b40f2e9 | Java | thefancypant/EMSAndroid | /app/src/main/java/com/maintenancesolution/ems/Models/DateTime.java | UTF-8 | 1,038 | 2.296875 | 2 | [] | no_license | package com.maintenancesolution.ems.Models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by kalyan on 1/6/18.
*/
public class DateTime {
@SerializedName("full")
@Expose
private String full;
@SerializedName("date")
@Expose
private String date;
/*@SerializedName("timestamp")
@Expose
private Integer timestamp;*/
@SerializedName("time")
@Expose
private String time;
public String getFull() {
return full;
}
public void setFull(String full) {
this.full = full;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
/*public Integer getTimestamp() {
return timestamp;
}
public void setTimestamp(Integer timestamp) {
this.timestamp = timestamp;
}*/
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
| true |
0fdee27412d853d2ef592dce3f179952af1c615c | Java | rPman/app-browser | /src/main/java/org/luwrain/app/browser/CheckChangesEvent.java | UTF-8 | 212 | 1.664063 | 2 | [] | no_license |
package org.luwrain.app.browser;
import org.luwrain.core.*;
import org.luwrain.core.events.*;
class CheckChangesEvent extends ThreadSyncEvent
{
CheckChangesEvent(Area area)
{
super(area);
}
}
| true |
66ba7f212b683ed7014b8c537ba7a56e6f554f5c | Java | kanaida/LG-Esteem-Homeless-Kernel | /out/target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates/src/org/apache/http/impl/client/TunnelRefusedException.java | UTF-8 | 346 | 2.046875 | 2 | [] | no_license | package org.apache.http.impl.client;
public class TunnelRefusedException
extends org.apache.http.HttpException
{
public TunnelRefusedException(java.lang.String message, org.apache.http.HttpResponse response) { throw new RuntimeException("Stub!"); }
public org.apache.http.HttpResponse getResponse() { throw new RuntimeException("Stub!"); }
}
| true |
56b6d317dec2970ceca920055d729fe96b1e2760 | Java | luizedu9/OCOM | /src/main/java/security/AppUserDetailsService.java | UTF-8 | 1,309 | 2.515625 | 3 | [] | no_license | package security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import modelo.Integrante;
import service.IntegranteService;
public class AppUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
IntegranteService usuarios = new IntegranteService();
Integrante usuario = usuarios.buscarPorLogin(login);
IntegranteSistema user = null;
if (usuario != null) {
user = new IntegranteSistema(usuario, getGrupos(usuario));
}
return user;
}
private Collection<? extends GrantedAuthority> getGrupos(Integrante usuario) {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (String grupo : usuario.getPermissao()) {
authorities.add(new SimpleGrantedAuthority(grupo.toUpperCase()));
}
return authorities;
}
}
| true |
aaf08c22e99d448bbed60fa788ad31ed872cae98 | Java | jayesbe/react-native-splashscreen | /android/src/main/java/com/remobile/splashscreen/RCTSplashScreen.java | UTF-8 | 4,921 | 2.296875 | 2 | [
"MIT"
] | permissive | package com.remobile.splashscreen;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class RCTSplashScreen extends ReactContextBaseJavaModule {
private static Dialog splashDialog;
private ImageView splashImageView;
private Activity activity;
public RCTSplashScreen(ReactApplicationContext reactContext, Activity activity) {
super(reactContext);
this.activity = activity;
showSplashScreen();
}
@Override
public String getName() {
return "SplashScreen";
}
protected Activity getActivity() {
return activity;
}
@ReactMethod
public void hide() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
removeSplashScreen();
}
}, 10);
}
private void removeSplashScreen() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (splashDialog != null && splashDialog.isShowing()) {
AlphaAnimation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setDuration(50);
View view = ((ViewGroup)splashDialog.getWindow().getDecorView()).getChildAt(0);
view.startAnimation(fadeOut);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
splashDialog.dismiss();
splashDialog = null;
splashImageView = null;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
});
}
private int getSplashId() {
int drawableId = getActivity().getResources().getIdentifier("splash", "drawable", getActivity().getClass().getPackage().getName());
if (drawableId == 0) {
drawableId = getActivity().getResources().getIdentifier("splash", "drawable", getActivity().getPackageName());
}
return drawableId;
}
private void showSplashScreen() {
final int drawableId = getSplashId();
if ((splashDialog != null && splashDialog.isShowing())||(drawableId == 0)) {
return;
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
// Get reference to display
Display display = getActivity().getWindowManager().getDefaultDisplay();
Context context = getActivity();
// Use an ImageView to render the image because of its flexible scaling options.
splashImageView = new ImageView(context);
splashImageView.setImageResource(drawableId);
LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
splashImageView.setLayoutParams(layoutParams);
splashImageView.setMinimumHeight(display.getHeight());
splashImageView.setMinimumWidth(display.getWidth());
splashImageView.setBackgroundColor(Color.BLACK);
splashImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// Create and show the dialog
splashDialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
// check to see if the splash screen should be full screen
if ((getActivity().getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN)
== WindowManager.LayoutParams.FLAG_FULLSCREEN) {
splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
splashDialog.setContentView(splashImageView);
splashDialog.setCancelable(false);
splashDialog.show();
}
});
}
}
| true |
32dc14bee6281421e4070570715a9fe2c324fc02 | Java | stefanosalvagni/Pics | /app/src/main/java/com/is/pics/login/StatefulRestTemplate.java | UTF-8 | 2,316 | 2.203125 | 2 | [] | no_license | package com.is.pics.login;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
/**
* Created by stefano on 11/02/15.
*/
public class StatefulRestTemplate extends RestTemplate {
private String cookies;
private HttpHeaders requestHeaders;
private HttpEntity requestEntity;
public StatefulRestTemplate(){
this.cookies = "";
this.requestHeaders = new HttpHeaders();
this.requestHeaders.add("Cookie","");
this.requestEntity = null;
this.getMessageConverters().add(new FormHttpMessageConverter());
this.getMessageConverters().add(new StringHttpMessageConverter());
//this.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
}
public void initHeaders(){
this.requestHeaders.set("Cookie", this.cookies);
}
public void initEntity(MultiValueMap<String, Object> parts){
this.initHeaders();
this.requestEntity = new HttpEntity(parts,this.requestHeaders);
}
public <T> ResponseEntity<T> exchangeForOur(URI url, HttpMethod method,
Class<T> responseType) throws RestClientException {
return super.exchange(url, method, this.requestEntity, responseType);
}
public String getCookies() {
return cookies;
}
public void setCookies(String cookies) {
this.cookies = cookies;
}
public HttpHeaders getRequestHeaders() {
return requestHeaders;
}
public void setRequestHeaders(HttpHeaders requestHeaders) {
this.requestHeaders = requestHeaders;
}
public HttpEntity getRequestEntity() {
return requestEntity;
}
public void setRequestEntity(HttpEntity requestEntity) {
this.requestEntity = requestEntity;
}
}
| true |
3d8c71df023a04489d97c19eca6aad1feae522e6 | Java | uni7corn/blue-ble-sdk | /blue/src/main/java/com/sumian/blue/callback/BluePeripheralDataCallback.java | UTF-8 | 331 | 1.8125 | 2 | [
"Apache-2.0"
] | permissive | package com.sumian.blue.callback;
import com.sumian.blue.model.BluePeripheral;
/**
* Created by jzz
* on 2017/12/3.
* <p>
* desc:
*/
public interface BluePeripheralDataCallback {
void onSendSuccess(BluePeripheral bluePeripheral, byte[] data);
void onReceiveSuccess(BluePeripheral bluePeripheral, byte[] data);
}
| true |
e701821fcce77c72df5bdd5bf1f48fa1f4e5c9a1 | Java | WitoldJnc/lessons | /students_db/src/main/java/application/dao_impls/GenericDaoImpl.java | UTF-8 | 1,997 | 2.53125 | 3 | [] | no_license | package application.dao_impls;
import application.dao_interfaces.GenericDao;
import application.models.AbstractObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public abstract class GenericDaoImpl<T extends AbstractObject> implements GenericDao<T> {
@Autowired
private JdbcTemplate jdbcTemplate;
protected String table;
@Override
public void deleteById(Integer id) {
String sql = "DELETE FROM " + table + " WHERE id = ?";
jdbcTemplate.update(sql, id);
}
@Override
public Integer getCount() {
String sql = "SELECT COUNT(*) FROM " + table;
return jdbcTemplate.queryForObject(sql, Integer.class);
}
@Override
public T getById(Integer id) {
String sql = "Select * from " + table + " where id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(genericClass));
}
@Override
public List<T> getAll() {
String sql = "select * from " + table;
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(genericClass));
}
protected abstract Map<String, Object> insertParams(T entity);
@Override
public Integer insert(T object) {
SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName(table).usingGeneratedKeyColumns("id");
return jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(insertParams(object))).intValue();
}
private Class<T> genericClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
| true |
7ad93b6226968294928ae5afa9e839b21f12954d | Java | opennetworkinglab/onos | /protocols/bgp/bgpio/src/main/java/org/onosproject/bgpio/types/FourOctetAsNumCapabilityTlv.java | UTF-8 | 3,348 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015-present Open Networking 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.onosproject.bgpio.types;
import java.util.Objects;
import org.jboss.netty.buffer.ChannelBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
/**
* Provides FourOctetAsNumCapabilityTlv Capability Tlv.
*/
public class FourOctetAsNumCapabilityTlv implements BgpValueType {
/**
* support to indicate its support for four-octet AS numbers -CAPABILITY TLV format.
*/
private static final Logger log = LoggerFactory
.getLogger(FourOctetAsNumCapabilityTlv.class);
public static final byte TYPE = 65;
public static final byte LENGTH = 4;
private final int rawValue;
/**
* constructor to initialize rawValue.
* @param rawValue FourOctetAsNumCapabilityTlv
*/
public FourOctetAsNumCapabilityTlv(int rawValue) {
this.rawValue = rawValue;
}
/**
* constructor to initialize raw.
* @param raw AS number
* @return object of FourOctetAsNumCapabilityTlv
*/
public static FourOctetAsNumCapabilityTlv of(final int raw) {
return new FourOctetAsNumCapabilityTlv(raw);
}
/**
* Returns value of TLV.
* @return int value of rawValue
*/
public int getInt() {
return rawValue;
}
@Override
public short getType() {
return TYPE;
}
@Override
public int hashCode() {
return Objects.hash(rawValue);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof FourOctetAsNumCapabilityTlv) {
FourOctetAsNumCapabilityTlv other = (FourOctetAsNumCapabilityTlv) obj;
return Objects.equals(rawValue, other.rawValue);
}
return false;
}
@Override
public int write(ChannelBuffer cb) {
int iLenStartIndex = cb.writerIndex();
cb.writeByte(TYPE);
cb.writeByte(LENGTH);
cb.writeInt(rawValue);
return cb.writerIndex() - iLenStartIndex;
}
/**
* Reads the channel buffer and returns object of FourOctetAsNumCapabilityTlv.
* @param cb type of channel buffer
* @return object of FourOctetAsNumCapabilityTlv
*/
public static FourOctetAsNumCapabilityTlv read(ChannelBuffer cb) {
return FourOctetAsNumCapabilityTlv.of(cb.readInt());
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("Type", TYPE)
.add("Length", LENGTH)
.add("Value", rawValue).toString();
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
| true |
6068fcc922f78d59d2f5dbb49f679afa7d16a904 | Java | tsgramova/ITTalents | /JavaAdvanced/OOPTasks/Vignette/Vignette.java | UTF-8 | 1,649 | 3.25 | 3 | [] | no_license | package Vignette;
import java.util.Date;
import java.util.Random;
public class Vignette {
enum AutoType {CAR,TRUCK,BUS};
enum Duration {ANNUAL,MONTHLY,DAILY};
//each vignette has an auto type and duration
private AutoType autoType;
private Date issueDate;
protected int price;
private String color;
private Duration duration;
//create a vignette with given autotype and duration
//the color and the price depend on the autotype and the duration
public Vignette(AutoType autoType, Duration duration) {
this.autoType=autoType;
this.color = (autoType==AutoType.CAR?"pink":(autoType==AutoType.BUS?"green":"blue"));
this.duration=duration;
if(this.autoType==autoType.CAR) {
this.price= (duration==Duration.ANNUAL?300:(duration==Duration.MONTHLY?50:5));
}
else {
if(this.autoType==autoType.TRUCK) {
this.price= (duration==Duration.ANNUAL?420:(duration==Duration.MONTHLY?70:7));
}
else {
this.price= (duration==Duration.ANNUAL?540:(duration==Duration.MONTHLY?90:9));
}
}
}
public void putOnWindow() {
if(this.autoType==autoType.BUS) {
System.out.println("It's taking 20 seconds...");
}
else {
if (this.autoType==autoType.TRUCK) {
System.out.println("It's taking 10 seconds...");
}
else {
System.out.println("It's taking 5 seconds..");
}
}
}
public int getPrice() {
return this.price;
}
public String toString() {
return "Vignette for : " + this.autoType + ", duration: " + this.duration + ", price: " + this.price;
}
public Duration getDuration() {
return this.duration;
}
public AutoType getAutoType() {
return autoType;
}
}
| true |
2c7dcbf0706deece12e6ea956abc42b8a2a58525 | Java | GeorgeV3/CineAlert | /cinealert/src/main/java/org/afdemp/cinealert/dao/ActorsRepo.java | UTF-8 | 278 | 1.601563 | 2 | [] | no_license | package org.afdemp.cinealert.dao;
import org.afdemp.cinealert.model.Actor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ActorsRepo extends JpaRepository<Actor, Long>{
}
| true |
7c77ac5ee885529e7097474989d4dc9515c4c987 | Java | imgc0312/appClassProjectGame | /appClassProjectGame/app/src/main/java/imgc0312/appclassprojectgame/INFO.java | UTF-8 | 2,709 | 2.765625 | 3 | [] | no_license | package imgc0312.appclassprojectgame;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2018/10/14.
*/
public class INFO extends HashMap<String, Double>{
public final static double iniLv = 1.0;
public final static double iniMAX_Hp = 400.0;
public final static double iniATK = 35.0;
public final static double iniMAX_DEF = 100.0;
public final static double iniMAX_CHARGE = 3.0;
INFO(boolean initial){
super();
if(initial){
put("Lv", iniLv);
put("Hp", iniMAX_Hp);
put("MAX_Hp", iniMAX_Hp);
put("Ori_ATK", iniATK);
put("Buf_ATK", 0.0);
put("DEF", 0.0);
put("MAX_DEF", iniMAX_DEF);
put("CHARGE", 0.0);
put("MAX_CHARGE", iniMAX_CHARGE);
put("Exp", 0.0);
put("MAX_Exp", 1.0);
}
};
public String normalText(){
return new String(
"Lv\t\t\t\t\t\t\t:\t\t\t" + this.get("Lv") + "\n" +
"Hp\t\t\t\t\t\t:\t\t\t" + this.get("Hp") + "\n" +
"ATK\t\t\t\t\t:\t\t\t" + (this.get("Ori_ATK") + this.get("Buf_ATK")) + "\n" +
"DEF\t\t\t\t\t:\t\t\t" + this.get("DEF") + "\n" +
"CHARGE\t:\t\t\t" + this.get("CHARGE") + "\n" +
"Exp\t\t\t\t\t:\t\t\t" + this.get("Exp")
);
}
public boolean effect(INFO event){
if(event.containsKey("CHARGE"))
if ((get("CHARGE") + event.get("CHARGE")) < 0.0)
return false;
for (String oneKey:event.keySet()) {
if(containsKey(oneKey))
put(oneKey, get(oneKey) + event.get(oneKey));
}
if(get("DEF") < 0.0)
put("DEF", 0.0);
else if(get("DEF") >= get("MAX_DEF"))
put("DEF", get("MAX_DEF"));
if(get("CHARGE") >= get("MAX_CHARGE"))
put("CHARGE", get("MAX_CHARGE"));
if(get("Exp") < 0.0)
put("Exp", 0.0);
else if(get("Exp") >= get("MAX_Exp")) {
put("Exp", 0.0);
put("Lv", get("Lv") + 1.0);
flash();
}
if(get("Hp") < 0.0)
put("Hp", 0.0);
else if(get("Hp") >= get("MAX_Hp"))
put("Hp", get("MAX_Hp"));
return true;
}
public void flash(){
double Lv = get("Lv");
double newMAX_Hp = get("MAX_Hp") * Lv;
put("Hp", newMAX_Hp - get("MAX_Hp"));
put("MAX_Hp", newMAX_Hp);
put("Ori_ATK", iniATK + 5 * Lv - 5);
put("MAX_DEF", iniMAX_DEF + 50 * Lv - 50);
put("MAX_CHARGE" , iniMAX_CHARGE + Lv - 1);
put("MAX_Exp", 2 * Lv - 1);
}
}
| true |
67342757866d646f57c20a3380988424e4d0dddd | Java | wj1996/springdemo | /src/main/java/com/wj15/test/Test.java | UTF-8 | 635 | 2 | 2 | [] | no_license | package com.wj15.test;
import com.wj15.config.SpringConfiguration;
import com.wj15.service.interfaces.IAccountService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class Test {
@Autowired
private IAccountService accountService;
@org.junit.Test
public void test1() {
accountService.transfer("aa","bb",10f);
}
}
| true |
cbc52ececb729390244e4303f555fd133aab1db8 | Java | pramodag/JavaAssignments | /JavaAssignments/src/com/hagenberg/ENI515/exercise10/test/TestRace.java | UTF-8 | 1,969 | 2.84375 | 3 | [] | no_license | package com.hagenberg.ENI515.exercise10.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.hagenberg.ENI515.exercise10.Person;
import com.hagenberg.ENI515.exercise10.Race;
import com.hagenberg.ENI515.exercise10.Ranking;
import com.hagenberg.ENI515.exercise10.time.SimpleTime;
import com.hagenberg.ENI515.exercise10.time.SimpleTime.Mode;
public class TestRace {
@Test
public void test() {
String NEWLINECHAR = System.getProperty("line.separator");
Race collection = new Race(5);
SimpleTime.setMode(Mode.H24);
collection.setRaceName("Ski world champion");
try {
Ranking p = new Ranking(new Person("Pramod", 2),
new SimpleTime(0, 5, 40), 3);
Ranking p1 = new Ranking(new Person("Some guy", 3),
new SimpleTime(0, 5, 42), 5);
Ranking p2 = new Ranking(new Person("Some otherGuy", 4),
new SimpleTime(0, 5, 45), 7);
Ranking p3 = new Ranking(new Person("Someone Else", 5),
new SimpleTime(0, 5, 46), 2);
Ranking p4 = new Ranking(new Person("Some girl", 6),
new SimpleTime(0, 5, 42), 1);
collection.add(p);
assertTrue(1 == collection.size());
collection.add(p1);
assertTrue(2 == collection.size());
collection.add(p2);
assertTrue(3 == collection.size());
collection.add(p3);
assertTrue(4 == collection.size());
assertTrue(collection.remove(p2));
collection.add(p4);
assertTrue(4 == collection.size());
assertTrue(collection.contains(p3));
assertTrue("Ski world champion".equals(collection.getRaceName()));
String s = "Race name: Ski world champion" + NEWLINECHAR
+ "Participents" + NEWLINECHAR
+ "Rank: 1 Name: Some girl Time:0:5:42" + NEWLINECHAR
+ "Rank: 2 Name: Someone Else Time:0:5:46" + NEWLINECHAR
+ "Rank: 3 Name: Pramod Time:0:5:40" + NEWLINECHAR
+ "Rank: 5 Name: Some guy Time:0:5:42" + NEWLINECHAR;
assertTrue(s.equals(collection.toString()));
} catch (Exception e) {}
}
}
| true |
3c5677c9a6a948fa291cf91cf9e0cba11aa9cdde | Java | krish4saran/vyka | /src/main/java/com/vyka/domain/ProfileSubject.java | UTF-8 | 5,185 | 2.03125 | 2 | [] | no_license | package com.vyka.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
import com.vyka.domain.enumeration.LevelValue;
/**
* A ProfileSubject.
*/
@Entity
@Table(name = "profile_subject")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "profilesubject")
public class ProfileSubject implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "jhi_level")
private LevelValue level;
@Column(name = "rate", precision=10, scale=2)
private BigDecimal rate;
@Column(name = "sponsored")
private Boolean sponsored;
@Column(name = "active")
private Boolean active;
@Column(name = "total_rating", precision=10, scale=2)
private BigDecimal totalRating;
@ManyToOne
private Profile profile;
@OneToOne
@JoinColumn(unique = true)
private Subject subject;
@OneToMany(mappedBy = "profileSubject")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Review> reviews = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LevelValue getLevel() {
return level;
}
public ProfileSubject level(LevelValue level) {
this.level = level;
return this;
}
public void setLevel(LevelValue level) {
this.level = level;
}
public BigDecimal getRate() {
return rate;
}
public ProfileSubject rate(BigDecimal rate) {
this.rate = rate;
return this;
}
public void setRate(BigDecimal rate) {
this.rate = rate;
}
public Boolean isSponsored() {
return sponsored;
}
public ProfileSubject sponsored(Boolean sponsored) {
this.sponsored = sponsored;
return this;
}
public void setSponsored(Boolean sponsored) {
this.sponsored = sponsored;
}
public Boolean isActive() {
return active;
}
public ProfileSubject active(Boolean active) {
this.active = active;
return this;
}
public void setActive(Boolean active) {
this.active = active;
}
public BigDecimal getTotalRating() {
return totalRating;
}
public ProfileSubject totalRating(BigDecimal totalRating) {
this.totalRating = totalRating;
return this;
}
public void setTotalRating(BigDecimal totalRating) {
this.totalRating = totalRating;
}
public Profile getProfile() {
return profile;
}
public ProfileSubject profile(Profile profile) {
this.profile = profile;
return this;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public Subject getSubject() {
return subject;
}
public ProfileSubject subject(Subject subject) {
this.subject = subject;
return this;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
public Set<Review> getReviews() {
return reviews;
}
public ProfileSubject reviews(Set<Review> reviews) {
this.reviews = reviews;
return this;
}
public ProfileSubject addReview(Review review) {
this.reviews.add(review);
review.setProfileSubject(this);
return this;
}
public ProfileSubject removeReview(Review review) {
this.reviews.remove(review);
review.setProfileSubject(null);
return this;
}
public void setReviews(Set<Review> reviews) {
this.reviews = reviews;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileSubject profileSubject = (ProfileSubject) o;
if (profileSubject.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), profileSubject.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "ProfileSubject{" +
"id=" + getId() +
", level='" + getLevel() + "'" +
", rate='" + getRate() + "'" +
", sponsored='" + isSponsored() + "'" +
", active='" + isActive() + "'" +
", totalRating='" + getTotalRating() + "'" +
"}";
}
}
| true |
93e5457995427d14064e77ea58b9e2651b064040 | Java | kish8600/Siddu1234 | /src/com/kish/test/TempDomain.java | UTF-8 | 3,383 | 2.65625 | 3 | [] | no_license | package com.kish.test;
import java.util.ArrayList;
import java.util.List;
public class TempDomain {
private String column1;
private String column2;
private String column3;
private String column4;
private String column5;
private String column6;
private String column7;
private String column8;
private String column9;
private String column10;
private List<TempDomain> tempDomainList = new ArrayList<TempDomain>();
public String getColumn1() {
return column1;
}
public void setColumn1(String column1) {
this.column1 = column1;
}
public String getColumn2() {
return column2;
}
public void setColumn2(String column2) {
this.column2 = column2;
}
public String getColumn3() {
return column3;
}
public void setColumn3(String column3) {
this.column3 = column3;
}
public String getColumn4() {
return column4;
}
public void setColumn4(String column4) {
this.column4 = column4;
}
public String getColumn5() {
return column5;
}
public void setColumn5(String column5) {
this.column5 = column5;
}
public String getColumn6() {
return column6;
}
public void setColumn6(String column6) {
this.column6 = column6;
}
public String getColumn7() {
return column7;
}
public void setColumn7(String column7) {
this.column7 = column7;
}
public String getColumn8() {
return column8;
}
public void setColumn8(String column8) {
this.column8 = column8;
}
public String getColumn9() {
return column9;
}
public void setColumn9(String column9) {
this.column9 = column9;
}
public String getColumn10() {
return column10;
}
public void setColumn10(String column10) {
this.column10 = column10;
}
public int getRowSize(List<String> list){
return (int) Math.ceil(list.size()/10);
}
public List<TempDomain> populatedomain(List<String> list){
int size = getRowSize(list);
int fromIndex =0;
int toIndex = 10;
for(int i=0; i<size;i++){
List<String> subList = list.subList(fromIndex, toIndex);
String[] array = (String[]) subList.toArray(new String[subList.size()]);
TempDomain tempDomain = new TempDomain();
tempDomain.setColumn1(array[0]);
tempDomain.setColumn2(array[1]);
tempDomain.setColumn3(array[2]);
tempDomain.setColumn4(array[3]);
tempDomain.setColumn5(array[4]);
tempDomain.setColumn6(array[5]);
tempDomain.setColumn7(array[6]);
tempDomain.setColumn8(array[7]);
tempDomain.setColumn9(array[8]);
tempDomain.setColumn10(array[9]);
tempDomainList.add(tempDomain);
fromIndex = toIndex;
toIndex = toIndex + 10;
}
return tempDomainList;
}
public List<TempDomain> addLastRow(List<String> list,List<TempDomain> tempDomainList, int fromIndex){
if(fromIndex == list.size())
return tempDomainList;
List<String> subList = list.subList(fromIndex, list.size());
String[] array = (String[]) subList.toArray(new String[subList.size()]);
TempDomain tempDomain = new TempDomain();
tempDomain.setColumn1(array[0]);
tempDomain.setColumn2(array[1]);
tempDomain.setColumn3(array[2]);
tempDomain.setColumn4(array[3]);
tempDomain.setColumn5(array[4]);
tempDomain.setColumn6(array[5]);
tempDomain.setColumn7(array[6]);
tempDomain.setColumn8(array[7]);
tempDomain.setColumn9(array[8]);
tempDomain.setColumn10(array[9]);
return tempDomainList;
}
}
| true |
8e9c658c1a2c3ee66a5b3c34d7afb294df615efe | Java | dmitrui98/timetable | /src/by/dmitrui98/entity/Group.java | UTF-8 | 1,242 | 2.84375 | 3 | [] | no_license | package by.dmitrui98.entity;
/**
* Created by Администратор on 25.02.2018.
*/
public class Group {
private int id;
private String name;
private int course;
private Department department;
public Group() {
}
public Group(int id) {
this.id = id;
}
public Group(String name, int course) {
this.name = name;
this.course = course;
}
public Group(int id, String name, int course, Department department) {
this.id = id;
this.name = name;
this.course = course;
this.department = department;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCourse() {
return course;
}
public void setCourse(int course) {
this.course = course;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return getName();
}
}
| true |