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
6f126315dc393a2d170416e6f11c0783f108f3d7
Java
WCYu/HuanPet
/app/src/main/java/com/example/huanpet/view/know/KnowActivity.java
UTF-8
1,484
1.976563
2
[]
no_license
package com.example.huanpet.view.know; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.huanpet.R; import com.example.huanpet.app.BaseActivity; import com.example.huanpet.utils.CustomTool; import com.example.huanpet.utils.OkhttpUtil; import java.io.IOException; import java.util.HashMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okio.BufferedSink; public class KnowActivity extends BaseActivity { private CustomTool know_custom; private TextView tx; @Override public int initLayoutID() { return R.layout.activity_know; } @Override public void initView() { know_custom = findViewById(R.id.know_custom); tx = findViewById(R.id.tx); } @Override public void initAdapter() { } @Override public void initData() { know_custom.initViewsVisible(true, true, false, false); know_custom.setAppTitle("寄养须知"); know_custom.setReturnBtn(" "); } @Override public void initListener() { know_custom.setOnLeftButtonClickListener(new CustomTool.OnLeftButtonClickListener() { @Override public void onLeftButtonClick(View v) { finish(); } }); } @Override public void setMyAppTitle() { } }
true
b34f15bf352df19e36381280bf187b39c94f8d1c
Java
lbyjwwyqt147/background-security
/src/main/java/pers/ljy/background/model/SysLogsEntity.java
UTF-8
6,488
2.296875
2
[]
no_license
package pers.ljy.background.model; import java.io.Serializable; import java.util.Date; /*** * 日志纪录 * @author ljy * */ public class SysLogsEntity implements Serializable { /** * id */ private Long id; /** * 用户ID */ private Integer userId; /** * 日志类型:1001:正常 1002:异常 */ private String logsType; /** * 请求url */ private String url; /** * 请求IP */ private String ip; /** * 请求类路径 */ private String classPath; /** * 请求方法 */ private String askMethod; /** * 请求方法全路径 */ private String methodPath; /** * 请求方式 */ private String requestMethod; /** * 描述 */ private String description; /** * 异常代码 */ private String errorCode; /** * 创建时间 */ private Date createDate; /** * 请求参数 */ private String params; /** * 异常信息 */ private String errorMsg; /** * 请求方法返回值 */ private String methodResultValue; /** * 方法执行消耗时间转换值 */ private String wasteTimeMsg; /** * 方法消耗时间(秒为单位) */ private Long wasteTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table sys_logs * * @mbggenerated */ private static final long serialVersionUID = 1L; /** * id * @return id_ */ public Long getId() { return id; } /** * id * @param id */ public void setId(Long id) { this.id = id; } /** * 用户ID * @return user_id_ */ public Integer getUserId() { return userId; } /** * 用户ID * @param userId */ public void setUserId(Integer userId) { this.userId = userId; } /** * 日志类型:1001:正常 1002:异常 * @return logs_type_ */ public String getLogsType() { return logsType; } /** * 日志类型:1001:正常 1002:异常 * @param logsType */ public void setLogsType(String logsType) { this.logsType = logsType == null ? null : logsType.trim(); } /** * 请求url * @return url_ */ public String getUrl() { return url; } /** * 请求url * @param url */ public void setUrl(String url) { this.url = url == null ? null : url.trim(); } /** * 请求IP * @return ip_ */ public String getIp() { return ip; } /** * 请求IP * @param ip */ public void setIp(String ip) { this.ip = ip == null ? null : ip.trim(); } /** * 请求类路径 * @return class_path_ */ public String getClassPath() { return classPath; } /** * 请求类路径 * @param classPath */ public void setClassPath(String classPath) { this.classPath = classPath == null ? null : classPath.trim(); } /** * 请求方法 * @return ask_method_ */ public String getAskMethod() { return askMethod; } /** * 请求方法 * @param askMethod */ public void setAskMethod(String askMethod) { this.askMethod = askMethod == null ? null : askMethod.trim(); } /** * 请求方法全路径 * @return method_path_ */ public String getMethodPath() { return methodPath; } /** * 请求方法全路径 * @param methodPath */ public void setMethodPath(String methodPath) { this.methodPath = methodPath == null ? null : methodPath.trim(); } /** * 请求方式 * @return request_method_ */ public String getRequestMethod() { return requestMethod; } /** * 请求方式 * @param requestMethod */ public void setRequestMethod(String requestMethod) { this.requestMethod = requestMethod == null ? null : requestMethod.trim(); } /** * 描述 * @return description_ */ public String getDescription() { return description; } /** * 描述 * @param description */ public void setDescription(String description) { this.description = description == null ? null : description.trim(); } /** * 异常代码 * @return error_code_ */ public String getErrorCode() { return errorCode; } /** * 异常代码 * @param errorCode */ public void setErrorCode(String errorCode) { this.errorCode = errorCode == null ? null : errorCode.trim(); } /** * 创建时间 * @return create_date_ */ public Date getCreateDate() { return createDate; } /** * 创建时间 * @param createDate */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * 请求参数 * @return params_ */ public String getParams() { return params; } /** * 请求参数 * @param params */ public void setParams(String params) { this.params = params == null ? null : params.trim(); } /** * 异常信息 * @return error_msg_ */ public String getErrorMsg() { return errorMsg; } /** * 异常信息 * @param errorMsg */ public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg == null ? null : errorMsg.trim(); } /** * 请求方法返回值 * @return method_result_value_ */ public String getMethodResultValue() { return methodResultValue; } /** * 请求方法返回值 * @param methodResultValue */ public void setMethodResultValue(String methodResultValue) { this.methodResultValue = methodResultValue == null ? null : methodResultValue.trim(); } public String getWasteTimeMsg() { return wasteTimeMsg; } public void setWasteTimeMsg(String wasteTimeMsg) { this.wasteTimeMsg = wasteTimeMsg; } public Long getWasteTime() { return wasteTime; } public void setWasteTime(Long wasteTime) { this.wasteTime = wasteTime; } }
true
fd2db3592cd822b3d8f271fd6c4278ca09a54a17
Java
Demelphy/CursoSpring
/concesionarioRest/Interfaces/src/main/java/com/atsistemas/concesionario/interfaces/servicios/FacturaServicio.java
UTF-8
226
1.75
2
[]
no_license
package com.atsistemas.concesionario.interfaces.servicios; public interface FacturaServicio { /** * Cobra la factura y entrega el pedido (cambia su estado e entregado) */ public long CobroDeFacturas(long idFactura); }
true
ef1359ee073baa6e6ffd8e5967b99b18d9a17b11
Java
teknoraver/ryanair
/src/net/teknoraver/ryanair/Select.java
UTF-8
6,595
2.078125
2
[]
no_license
package net.teknoraver.ryanair; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.TableRow; public class Select extends Activity implements OnItemClickListener, OnClickListener, OnDateSetListener { private static final Pattern patt = Pattern.compile(".*\\(([A-Z]{3})\\)$"); private AutoCompleteTextView from, to; private Button db1, db2; private Date d1, d2; static Date now; private String codef, codet; private RadioButton roundradio; private boolean isRound; private Button settingDate; private TableRow roundgroup; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.select); GregorianCalendar justnow = new GregorianCalendar(); now = d1 = d2 = new GregorianCalendar(justnow.get(Calendar.YEAR), justnow.get(Calendar.MONTH), justnow.get(Calendar.DAY_OF_MONTH)).getTime(); from = (AutoCompleteTextView)findViewById(R.id.from); to = (AutoCompleteTextView)findViewById(R.id.to); ImageButton invert = (ImageButton)findViewById(R.id.invert); invert.setOnClickListener(this); db1 = (Button)findViewById(R.id.date1); db1.setText(Results.dfmt.format(d1)); db1.setOnClickListener(this); db2 = (Button)findViewById(R.id.date2); db2.setText(Results.dfmt.format(d2)); db2.setOnClickListener(this); RadioButton r1 = (RadioButton)findViewById(R.id.one); r1.setOnClickListener(this); roundradio = (RadioButton)findViewById(R.id.round); roundradio.setOnClickListener(this); roundgroup = (TableRow)findViewById(R.id.roundgroup); // from.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, Routes.names)); from.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Routes.names)); from.setOnItemClickListener(this); ((Button)findViewById(R.id.search)).setOnClickListener(this); } @Override public void onResume() { super.onResume(); isRound = roundradio.isChecked(); if(isRound) roundgroup.setVisibility(View.VISIBLE); else roundgroup.setVisibility(View.GONE); } @Override public void onClick(View view) { switch(view.getId()) { case R.id.search: search(); break; case R.id.invert: invert(); break; case R.id.date1: case R.id.date2: GregorianCalendar calendar = new GregorianCalendar(); if(view.getId() == R.id.date1) calendar.setTime(d1); else calendar.setTime(d2); settingDate = (Button)view; new DatePickerDialog(this, this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show(); break; case R.id.one: isRound = false; roundgroup.setVisibility(View.GONE); break; case R.id.round: isRound = true; roundgroup.setVisibility(View.VISIBLE); break; } } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Date date = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime(); if(date.before(now)) { new AlertDialog.Builder(this) .setTitle(R.string.app_name) .setMessage("The date " + Results.dfmt.format(date) + " is in the past") .setIcon(android.R.drawable.ic_dialog_alert) .show(); return; } if(settingDate == db1) { d1 = date; if(d1.after(d2)) { d2 = date; db2.setText(Results.dfmt.format(date)); } } else d2 = date; settingDate.setText(Results.dfmt.format(date)); } private void search() { if(isRound && d1.after(d2)) { new AlertDialog.Builder(this) .setTitle(R.string.error) .setMessage(R.string.baddate) .setIcon(android.R.drawable.ic_dialog_alert) .show(); return; } String f = from.getText().toString(); String t = to.getText().toString(); boolean valid = false; // grep for a matching pattern Matcher matcher = patt.matcher(f); if(matcher.find() && Routes.names.indexOf(f) != -1) { codef = matcher.group(1); matcher = patt.matcher(t); if(matcher.find() && Routes.names.indexOf(t) != -1) { // get the destinations from the departure codet = matcher.group(1); List<String> dests = Routes.getDestinations(f); if(dests != null && dests.indexOf(t) != -1) valid = true; } } if(!valid) { new AlertDialog.Builder(this) .setTitle(R.string.selectt) .setMessage(R.string.selectm) .setIcon(android.R.drawable.ic_dialog_alert) .show(); return; } f = f.substring(0, f.length() - 6); t = t.substring(0, t.length() - 6); Intent intent; if(isRound) intent = new Intent(this, Tab.class).putExtra(Results.DATE2, d2); else intent = new Intent(this, Results.class); startActivity(intent .putExtra(Results.TITLE, f + " to " + t) .putExtra(Results.FROM, codef) .putExtra(Results.TO, codet) .putExtra(Results.DATE, d1)); } private void invert() { String tmp = from.getText().toString(); from.setText(to.getText().toString()); List<String> destinations = Routes.getDestinations(from.getText().toString()); if(destinations != null) to.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, destinations)); // to.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, destinations)); to.setText(tmp); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { List<String> destinations = Routes.getDestinations(from.getText().toString()); if(destinations != null) to.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, destinations)); // to.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, destinations)); else { new AlertDialog.Builder(this) .setTitle(R.string.app_name) .setMessage(R.string.noflight) .setIcon(android.R.drawable.ic_dialog_info) .show(); from.setText(""); to.setText(""); } } }
true
884f9628ff47e4445a88d55da0f8965a0f1fa63d
Java
konovaliuk/Servlet_Kalchenko_CashRegister_4
/src/main/java/dao/IUserDAO.java
UTF-8
586
2.25
2
[]
no_license
package dao; import entity.User; public interface IUserDAO<T> extends IDAO<T> { /** * Найти пользователя по логину и паролю * @param login логин пользователя * @param password пароль пользователя * @return user пользователь */ public User findUser(String login, String password); /** * Найти пользователя по логину * @param login логин пользователя * @return user пользователь */ public User findUserByLogin(String login); }
true
20a8a4cc09c8987c12d41e05f398661ff83a1558
Java
trity1993/xpuzzle
/xpuzzle/app/src/main/java/cc/trity/xpuzzle/utils/ComBindingAdapter.java
UTF-8
328
1.820313
2
[]
no_license
package cc.trity.xpuzzle.utils; import android.databinding.BindingAdapter; import android.widget.ImageView; /** * Created by trity on 28/6/16. */ public class ComBindingAdapter { @BindingAdapter("bind:src") public static void setImageDrawable(ImageView img,int resInt){ img.setImageResource(resInt); } }
true
c7171117cf30fbd6cdbd31be7d8e71fd2de5154a
Java
MyhreAndersen/Simula15Loom
/Simula15Loom/src/simulaTestPrograms/CallProcedureFormal$$callFP.java
UTF-8
2,478
2.515625
3
[]
no_license
package simulaTestPrograms; // Simula-1.0 Compiled at Thu Aug 15 21:46:43 CEST 2019 import simula.runtime.*; @SuppressWarnings("unchecked") public final class CallProcedureFormal$$callFP extends PROC$ { // ProcedureDeclaration: BlockKind=Procedure, BlockLevel=2, firstLine=3, lastLine=10, hasLocalClasses=false, System=false // Declare parameters as attributes public PRCQNT$ p$F; // Declare locals as attributes // JavaLine 10 <== SourceLine 5 float r=0.0f; int i=0; // Parameter Transmission in case of Formal/Virtual Procedure Call public CallProcedureFormal$$callFP setPar(Object param) { //Util.BREAK("CALL CallProcedureFormal$$callFP.setPar: param="+param+", qual="+param.getClass().getSimpleName()+", npar="+$nParLeft+", staticLink="+SL$); try { switch($nParLeft--) { case 1: p$F=procValue(param); break; default: throw new RuntimeException("Too many parameters"); } } catch(ClassCastException e) { throw new RuntimeException("Wrong type of parameter: "+param,e);} return(this); } // Constructor in case of Formal/Virtual Procedure Call public CallProcedureFormal$$callFP(RTObject$ SL$) { super(SL$,1); // Expecting 1 parameters } // Normal Constructor public CallProcedureFormal$$callFP(RTObject$ SL$,PRCQNT$ sp$F) { super(SL$); // Parameter assignment to locals this.p$F = sp$F; BBLK(); // Declaration Code STM$(); } // Procedure Statements public CallProcedureFormal$$callFP STM$() { // JavaLine 40 <== SourceLine 6 r=((float)(intValue(p$F.CPF() .setPar(new NAME$<Integer>(){ public Integer get() { return(7); } }) .setPar(new NAME$<Integer>(){ public Integer get() { return(9); } }) .ENT$().RESULT$()))); // JavaLine 42 <== SourceLine 7 i=intValue(p$F.CPF().setPar(new NAME$<Integer>(){ public Integer get() { return(7); } }).setPar(new NAME$<Integer>(){ public Integer get() { return(9); } }).ENT$().RESULT$()); // JavaLine 44 <== SourceLine 9 i=intValue(p$F.CPF().setPar(new NAME$<Integer>(){ public Integer get() { return(9); } }).ENT$().RESULT$()); EBLK(); return(this); } // End of Procedure BODY public static PROGINFO$ INFO$=new PROGINFO$("CallProcedureFormal.sim","Procedure callFP",10,5,40,6,42,7,44,9,48,10); } // End of Procedure
true
81afc0ea4ef07a4314ad70e23cb54f56e334bfbf
Java
owel09/JavaPractice
/src/main/java/Fundamentals/Lambda/ListIteratorEnumInterface.java
UTF-8
1,536
3.90625
4
[]
no_license
package Fundamentals.Lambda;/* *Created by owel on 02/11/2019 8:38 AM Vector vs ArrayList https://www.youtube.com/watch?v=4BWmtZQSedU Demo kung paano gamitin yung ListIterator na may reverse direction si Iterator kasi forward direction lang siya */ import java.util.Enumeration; import java.util.ListIterator; import java.util.Vector; public class ListIteratorEnumInterface { public static void main(String[] args) { Vector <Integer> vector = new Vector<Integer>(); vector.add(1); vector.add(2); vector.add(3); ListIterator lit = vector.listIterator(); System.out.println("In Forward direction"); while (lit.hasNext()){ System.out.print(lit.next() + " "); } /* Output: In Forward direction 1 2 3 kapag wala yung .next() mag-iinfinite loop */ System.out.println("\nIn Backward direction"); while (lit.hasPrevious()){ System.out.print(lit.previous() + " "); } System.out.println("\nEnumeration Interface"); Enumeration enumeration = vector.elements(); while (enumeration.hasMoreElements()){ System.out.print(enumeration.nextElement() + " "); /* Output: Enumeration Interface 1 2 3 Iterator can remove elements na wala sa Enumeration. Parang wala syang masyadong use kasi one by one yun pagretrive ng element */ } } }
true
7b2591482d8cc6f8b268fe89d59cea16a0edbbce
Java
zxp0505/Mes2
/workstation/src/main/java/workstation/zjyk/workstation/modle/bean/WSProductProcedureConcernMaterielVO.java
UTF-8
870
2.015625
2
[]
no_license
package workstation.zjyk.workstation.modle.bean; import java.io.Serializable; import java.util.List; public class WSProductProcedureConcernMaterielVO implements Serializable { private static final long serialVersionUID = 1L; private String productId; private String procedureId; private List<WSConcernMaterielVO> concernMaterielList; public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProcedureId() { return procedureId; } public void setProcedureId(String procedureId) { this.procedureId = procedureId; } public List<WSConcernMaterielVO> getConcernMaterielList() { return concernMaterielList; } public void setConcernMaterielList(List<WSConcernMaterielVO> concernMaterielList) { this.concernMaterielList = concernMaterielList; } }
true
ea77117a1857f7e7e7125c3612401bbe013e9c5f
Java
siren-HLL/JavaWebLearning
/Shopping/src/com/sybinal/shop/utils/Page.java
UTF-8
413
2.375
2
[ "Apache-2.0" ]
permissive
package com.sybinal.shop.utils; public class Page { // 当前页 private int nowPage = 1; public int getNowPage() { return nowPage; } public void setNowPage(int nowPage) { this.nowPage = nowPage; } public static long confirmPage(long count, int pageNumber) { if (count % pageNumber == 0) { return count / pageNumber; } else { return count / pageNumber + 1; } } }
true
4f8900de8d79ed12e44e2beae99a222cad9b16db
Java
prathapc/AlgoDs
/src/com/practice/B_algo_ps/I_dp/P91_DecodeWays.java
UTF-8
1,795
3.515625
4
[]
no_license
package com.practice.B_algo_ps.I_dp; import java.util.HashMap; import java.util.Map; /** * Created by Prathap on 02 Dec, 2019 * * https://leetcode.com/problems/decode-ways/ * * Input: "12" * Output: 2 * Explanation: It could be decoded as "AB" (1 2) or "L" (12). */ public class P91_DecodeWays { public static void main(String args[]) { String s = "123"; System.out.println(decodeWays_topDownDp(s, 0)); System.out.println(decodeWays_bottomUpDp(s)); } static Map<Integer, Integer> memo = new HashMap<>(); private static int decodeWays_topDownDp(String s, int index) { if (memo.containsKey(index)) return memo.get(index); if (index == s.length()) return 1; if (s.charAt(index) == '0') return 0; if (index == s.length()-1) return 1; int ans = decodeWays_topDownDp(s, index+1); if (Integer.parseInt(s.substring(index, index+2)) <= 26) { ans += decodeWays_topDownDp(s, index+2); } memo.put(index, ans); return ans; } private static int decodeWays_bottomUpDp(String s) { int dp[] = new int[s.length() + 1]; dp[0] = 1; //just a base case: for empty string only one way of decoding by doing nothing dp[1] = s.charAt(0) == '0' ? 0 : 1; //for single char input for (int i=2; i<=s.length(); i++) { int oneDigit = Integer.parseInt(s.substring(i-1, i)); int twoDigits = Integer.parseInt(s.substring(i-2, i)); if (oneDigit >= 1) { dp[i] = dp[i-1]; //beats 89% where if you put dp[i] = dp[i-1]; it beats only 20% } if (twoDigits >= 10 && twoDigits <= 26) { dp[i] += dp[i-2]; } } return dp[s.length()]; } }
true
7f9b8aac7993ae364f42e15b73f1a5ae28301584
Java
Pinelo/triggerGame
/src/main/Character.java
UTF-8
2,322
2.546875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package main; import java.awt.Image; import java.util.LinkedList; import javax.swing.ImageIcon; /** * * @author Casa */ public class Character extends Base{ public int ID; public int maxHp; public int hp; public int speed; public int dir; public Boolean isPlayable; public LinkedList inventory; public Boolean isAlive; public Animacion aniAnimacion; public Character(int x, int y, Image img, Animacion ani ,int id, int maxhp, int hp, int speed, int dir, Boolean isplayable, LinkedList invent, Boolean isalive) { super(x, y, img); ID = id; aniAnimacion = ani; maxHp = maxhp; this.hp = hp; this.speed = speed; this.dir = dir; isPlayable = isplayable; inventory = invent; isAlive = isalive; } public int getId() { return ID; } public int getMaxHp() { return maxHp; } public int getHp() { return hp; } public int getSpeed() { return speed; } public int getDir() { return dir; } public Boolean getIsPlayable() { return isPlayable; } public LinkedList getInventory() { return inventory; } public Boolean getIsAlive() { return isAlive; } public void setId(int id) { ID = id; } public void setMaxHp(int max) { maxHp = max; } public void getHp(int hp) { this.hp = hp; } public void setSpeed(int speed) { this.speed = speed; } public void setDir(int dir) { this.dir = dir; } public void setIsPlayable(Boolean isP) { isPlayable = isP; } public void setInventory(LinkedList inv) { inventory = inv; } public void setIsAlive(Boolean isalive) { isAlive = isalive; } public void setAnimacion(Animacion ani) { aniAnimacion = ani; } public Animacion getAnimacion() { return aniAnimacion; } }
true
807c8e778155c9d6b1fc8095328c5a721350433d
Java
tuxbear/ktxtemplate001
/core/src/com.tuxbear.dinos/ui/dialogs/LoadingDialog.java
UTF-8
1,060
2.171875
2
[]
no_license
package com.tuxbear.dinos.ui.dialogs; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable; import com.tuxbear.dinos.services.ResourceContainer; /** * Created with IntelliJ IDEA. User: tuxbear Date: 06/01/14 Time: 15:39 To change this template use File | Settings | File * Templates. */ public class LoadingDialog extends Dialog { public LoadingDialog(Skin skin, String message) { super("", skin); Label messageLabel = new Label(message, new Label.LabelStyle(ResourceContainer.largeFont, Color.FIREBRICK)); getContentTable().setBackground(new SpriteDrawable(new Sprite(new Texture(Gdx.files.internal("ui/loading.jpg"))))); setWidth(Gdx.graphics.getWidth()); setHeight(Gdx.graphics.getHeight()); this.getContentTable().add(messageLabel).center(); } // dinos making smoke signals ? }
true
655e0546c44e1393bde8fb8f5c84074688a4bbcb
Java
songszs/android_comm
/mytest/app/src/main/java/com/zs/test/thread/ThreadPoolTest.java
UTF-8
1,601
3.0625
3
[]
no_license
package com.zs.test.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author: zang song * @version: V1.0 * @date: 2020-02-22 16:21 * @email: [email protected] * @description: description */ public class ThreadPoolTest { //https://juejin.im/post/5d1882b1f265da1ba84aa676#heading-38 public void testThreadPool(){ //单个线程 顺序执行。提交任务,如果有线程创建,添加任务到LinkedBlockingQueue阻塞队列。没有则创建线程。始终只有一个线程在工作。 //LinkedBlockingQueue ExecutorService service1 = Executors.newSingleThreadExecutor(); //可以创建无限个线程。如果提交任务速度大于处理任务速度,会创建过多到线程导致资源耗尽。 //没有核心线程,所以任务直接加到SynchronousQueue队列 //提交任务,如果有空闲线程则使用空闲线程执行。没有则创建线程执行。线程执行完会等待60s,过后被终止。 //SynchronousQueue ExecutorService service2 = Executors.newCachedThreadPool(); //提交任务 //如果线程数少于核心线程,创建核心线程执行任务 //如果线程数等于核心线程,把任务添加到LinkedBlockingQueue阻塞队列 //如果线程执行完任务,去阻塞队列取任务,继续执行 ExecutorService service3 = Executors.newFixedThreadPool(5); //单个线程 顺序执行 DelayedWorkQueue ExecutorService service4 = Executors.newScheduledThreadPool(5); } }
true
267e6de2eab262e1dd2de6adec4e4d20721b6262
Java
njbhorn/TDDMoney
/DemoMoneyExercise/src/qa/tdd/money/iteration0/DollarTest.java
UTF-8
627
2.515625
3
[]
no_license
package qa.tdd.money.iteration0; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class DollarTest { @BeforeEach void setUp() throws Exception { } @Test void test() { // Assign Dollar dollar = new Dollar ( 5 ) ; int expected = 10 ; // Act int actual = dollar.timesBy ( 2 ) ; // Assert assertThat ( "$5 * 2 Failed", actual , is ( equalTo ( expected ))) ; } }
true
dd1f9bb59c4fc8f1490caa41ebcb630b1dcacb01
Java
matiramos/proglab3-18
/guia-objetos-i/src/com/utn/ejercicio1/Rectangulo.java
UTF-8
685
3.359375
3
[ "MIT" ]
permissive
package com.utn.ejercicio1; public class Rectangulo { private double ancho = 1.0; private double alto = 1.0; public Rectangulo() { } public Rectangulo(double ancho, double alto) { this.ancho = ancho; this.alto = alto; } public double getAncho() { return ancho; } public void setAncho(double ancho) { this.ancho = ancho; } public double getAlto() { return alto; } public void setAlto(double alto) { this.alto = alto; } public double calcularArea() { return ancho * alto; } public double calcularPerimetro() { return 2 * (ancho + alto); } }
true
2a93112494fafdd70370c5fad47d1d05871f3a9b
Java
waynefong0401/duke
/src/main/java/duke/memo/parser/InputParser.java
UTF-8
3,426
3.015625
3
[]
no_license
package duke.memo.parser; import duke.memo.command.AddCommand; import duke.memo.command.Command; import duke.memo.command.DeleteCommand; import duke.memo.command.DoneCommand; import duke.memo.command.ExitCommand; import duke.memo.command.ExpenseCommand; import duke.memo.command.FindCommand; import duke.memo.command.ListCommand; import duke.memo.exception.DukeException; import duke.memo.exception.NoDescriptionException; import duke.memo.exception.TaskTypeError; import duke.memo.record.Record; import duke.memo.record.expense.Expense; import duke.memo.record.task.Deadline; import duke.memo.record.task.Event; import duke.memo.record.task.ToDo; public class InputParser { private static final String BYE_CMD = "bye"; private static final String LIST_CMD = "list"; private static final String FIND_CMD = "find"; private static final String DONE_CMD = "done"; private static final String DELETE_CMD = "delete"; private static final String EXPENSE_CMD = "expense"; private static final String SPLIT_REGEX = " "; public static final int SPLIT_NO = 2; /** * Static method parse for Parser. * To parse the log into a command. * * @param cmd Full command in log file. * @return parsed command * @throws DukeException Throw if there is a problem in the command. */ public static Command parse(String cmd) throws DukeException { if (cmd.equalsIgnoreCase(BYE_CMD)) { return new ExitCommand(); } else if (cmd.equalsIgnoreCase(LIST_CMD)) { return new ListCommand(); } else if (cmd.startsWith(FIND_CMD)) { examineCmd(cmd, FIND_CMD); return new FindCommand(cmd.substring(FIND_CMD.length() + SPLIT_REGEX.length())); } else if (cmd.startsWith(DONE_CMD)) { examineCmd(cmd, DONE_CMD); return new DoneCommand(cmd.substring(DONE_CMD.length() + SPLIT_REGEX.length()).trim()); } else if (cmd.startsWith(DELETE_CMD)) { examineCmd(cmd, DELETE_CMD); return new DeleteCommand(cmd.substring(DELETE_CMD.length() + SPLIT_REGEX.length()).trim()); } else if (cmd.startsWith(EXPENSE_CMD)) { examineCmd(cmd,EXPENSE_CMD); return new ExpenseCommand(cmd.substring(EXPENSE_CMD.length() + SPLIT_REGEX.length()).trim()); } else { return new AddCommand(cmd); } } private static void examineCmd(String cmd, String targetCmd) throws DukeException { if (cmd.trim().equalsIgnoreCase(targetCmd)) { throw new NoDescriptionException(targetCmd); } else if (!cmd.split(SPLIT_REGEX, SPLIT_NO)[0].equalsIgnoreCase(targetCmd)) { throw new TaskTypeError(); } } /** * Convert raw log string to a task object. * * @param log Raw log. * @return Task return the parsed log * @throws DukeException Throw if there is a problem in the log. */ public static Record parseLog(String log) throws DukeException { String[] taskDetails = log.split(" \\| ",4); switch (taskDetails[0]) { case "T": return new ToDo(taskDetails); case "E": return new Event(taskDetails); case "D": return new Deadline(taskDetails); case "EX": return new Expense(taskDetails); default: return null; } } }
true
66b4689fa2cdab6e06a25333290fe33151b80da2
Java
myMenuApp/myMenuApp
/src/main/java/com/HandCrest/myMenuApp/RestaurantRepository.java
UTF-8
243
1.914063
2
[]
no_license
package com.HandCrest.myMenuApp; import org.springframework.data.repository.CrudRepository; public interface RestaurantRepository extends CrudRepository<Restaurant,Long>{ Restaurant findByRestaurantName(String restaurantName); }
true
d1435bc1673e7190c2cf1d9c145dd493b29cac19
Java
aymenlaadhari/GuideTouristique
/src/adapter/MonumentListAdapter.java
UTF-8
1,412
2.359375
2
[]
no_license
package adapter; import java.util.List; import model.Monument; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.navigation.R; public class MonumentListAdapter extends BaseAdapter { private List<Monument> monuments; private Context context; public MonumentListAdapter(Context context, List<Monument> monuments) { this.monuments = monuments; this.context = context; } @Override public int getCount() { return monuments.size(); } @Override public Object getItem(int index) { return monuments.get(index); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate( R.layout.list_item_title_navigation, null); } ImageWebView imgIcon = (ImageWebView) convertView .findViewById(R.id.imgIcon); TextView txtTitle = (TextView) convertView.findViewById(R.id.txtTitle); imgIcon.loadImage(monuments.get(position).getImage()); txtTitle.setText(monuments.get(position).getNomM()); return convertView; } }
true
01ba87480b79a114ce4c82e9b5676741446887bd
Java
Sagebits/uts-rest-api
/src/main/java/net/sagebits/tmp/isaac/rest/api1/data/mapping/RestMappingItemComputedDisplayField.java
UTF-8
3,599
1.789063
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 VetsEZ Inc, Sagebits LLC * * 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. * * Contributions from 2015-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works */ package net.sagebits.tmp.isaac.rest.api1.data.mapping; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import net.sagebits.tmp.isaac.rest.api.exceptions.RestException; import net.sagebits.tmp.isaac.rest.api1.data.enumerations.MapSetItemComponent; import sh.isaac.api.identity.IdentifiedObject; /** * * {@link RestMappingItemComputedDisplayField} * * This, combined with {@link RestMappingSetDisplayFieldBase} returns a subset of information about fields, on an map set item level. * This class only carries enough information to link this computed field back to the full display field order specification provided * in the MapSet itself - the linkage is by the id field from this class, to the id field in {@link RestMappingSetDisplayField} * * This class is only returned within item level object, and is only returned for COMPUTED fields. The value calulated by the computation * is returned in the value attribute. * * @author <a href="mailto:[email protected]">Joel Kniaz</a> */ @XmlRootElement @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, defaultImpl = RestMappingItemComputedDisplayField.class) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public class RestMappingItemComputedDisplayField extends RestMappingSetDisplayFieldBase { /** * In cases where this field represents a text description value for a calculated item such as source, target, or equivalence type, * this will contain the value to display. This field should always be populated. This entire object will only be returned * for computed fields that have a value. */ @XmlElement public String value; // for Jaxb protected RestMappingItemComputedDisplayField() { super(); } public RestMappingItemComputedDisplayField(IdentifiedObject id, MapSetItemComponent component, String value) throws RestException { super(id, component); this.value = value; } /** * {@inheritDoc} */ @Override public String toString() { return "RestMappingSetDisplayField [id=" + id + ", componentType=" + componentType + ", value=" + value + "]"; } }
true
462197186d6fc4e25fba823b10c731ca26a09c3b
Java
stonegu/bizislife-depreciated
/bizislife_v2/src/main/java/com/bizislife/core/service/UserDetailService.java
UTF-8
1,119
2.203125
2
[]
no_license
package com.bizislife.core.service; import java.util.ArrayList; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.bizislife.core.hibernate.pojo.Role; @Service("userDetailService") @Transactional public class UserDetailService { public List<GrantedAuthority> getGrantedAuthorities(List<Role> roles) { final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); if (roles!=null) { for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } } return authorities; } public List<GrantedAuthority> getGrantedAuthorities(Role role) { final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); if (role!=null) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } }
true
9312a8401461db48d0a36fa598b414dd0e53e2f4
Java
socrammol/MenssagensParaUsuarios
/Mensssagem/src/Model/FactoryNovoAssinante.java
UTF-8
847
2.4375
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 Model; import java.text.ParseException; import javafx.scene.input.KeyCode; import static javafx.scene.input.KeyCode.V; /** * * @author mmol */ public class FactoryNovoAssinante{ public Assinante novoAssinante(int id , String nome, String tipo, int qtdMensagem, long data) throws ParseException{ if (tipo.equals ("Free")) return new Assinante_Free(id ,nome, qtdMensagem); if (tipo.equals("Premium")) return new Assinante_Premium(id ,nome, qtdMensagem); if (tipo.equals("VIP")) return new Assinante_Vip(id ,nome, qtdMensagem, data); return null; } }
true
6f8dd7e0411582709f90a560039cc61f99c4ebc5
Java
kostadinlambov/Java-Advanced
/01. 2. Intro-To-Java-Exercises/src/p07_Character_Multiplier.java
UTF-8
1,008
3.71875
4
[ "MIT" ]
permissive
import java.util.Scanner; public class p07_Character_Multiplier { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] inputString = scanner.nextLine().split("\\s+"); int sum = calculateSumOfCharMultiplier(inputString[0], inputString[1]); System.out.println(sum); } private static int calculateSumOfCharMultiplier(String s, String s1) { String shorterString = ""; String longerString = ""; if(s.length() <= s1.length()){ shorterString = s; longerString = s1; }else{ shorterString = s1; longerString = s; } int sum = 0; for (int i = 0; i < shorterString.length(); i++) { sum += shorterString.charAt(i) * longerString.charAt(i); } for (int i = shorterString.length(); i < longerString.length() ; i++) { sum += longerString.charAt(i); } return sum; } }
true
8fd39452c283adb91d769579ce236f8f2ad50ac8
Java
ivansimplicio/LABS-MAP
/Lab05-Fachada/src/setor/infraEstrutura/Sala.java
UTF-8
517
2.984375
3
[ "MIT" ]
permissive
package setor.infraEstrutura; public class Sala { private String sala; private String bloco; public Sala(String sala, String bloco) { setSala(sala); setBloco(bloco); } public String getSala() { return sala; } public void setSala(String sala) { this.sala = sala; } public String getBloco() { return bloco; } public void setBloco(String bloco) { this.bloco = bloco; } @Override public String toString() { return String.format("Sala: %s - Bloco: %s\n", getSala(), getBloco()); } }
true
f164505f912150f9fcebbbc14cbf9921dbb286e2
Java
CDE20/MFPE_Projects
/POD-6/Audit-Management-Authentication/Audit-Severity/src/test/java/com/cts/AuditSeverity/pojo/AuditTypeTest.java
UTF-8
1,500
2.421875
2
[]
no_license
package com.cts.AuditSeverity.pojo; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.cts.AuditSeverity.pojo.AuditType; import lombok.extern.slf4j.Slf4j; /** * * Test class to test AuditType * */ @RunWith(SpringRunner.class) @ContextConfiguration @Slf4j public class AuditTypeTest { AuditType auditType = new AuditType(); @Mock Environment env; /** * to test the all param constructor of AuditType */ @Test public void testAuditTypeAllConstructor() { log.info(env.getProperty("string.start")); AuditType type = new AuditType("abc"); assertEquals(type.getAuditType(), "abc"); log.info(env.getProperty("string.end")); } /** * to test the getter setter of AuditType */ @Test public void testGetAuditType() { log.info(env.getProperty("string.start")); auditType.setAuditType("abc"); assertEquals(auditType.getAuditType(), "abc"); log.info(env.getProperty("string.end")); } /** * to test the getter setter of toString() */ @Test public void testoString() { log.info(env.getProperty("string.start")); String string = auditType.toString(); assertEquals(auditType.toString(), string); log.info(env.getProperty("string.end")); } }
true
9260f043cfe02c42c4aa864bb6ce1268161be9f3
Java
zedaav/hw2mqtt
/org.zedaav.hw2mqtt/src/org/zedaav/hw2mqtt/hal/tranform/HalPayloadTransformOkLowToInt.java
UTF-8
460
2.703125
3
[]
no_license
package org.zedaav.hw2mqtt.hal.tranform; import org.zedaav.hw2mqtt.misc.Hw2MqttConstants; public class HalPayloadTransformOkLowToInt implements HalPayloadTransform { @Override public String transform(String originalPayload) { // Simple Ok -> 100 / Low -> 10 transformation if (originalPayload.equals(Hw2MqttConstants.OK)) { return "100"; } if (originalPayload.equals(Hw2MqttConstants.LOW)) { return "10"; } return originalPayload; } }
true
2922c0f9fb68ec64c2988832d9f3a81157966835
Java
NourhanGehad/TravisitBusiness
/app/src/main/java/com/travisit/travisitbusiness/vvm/destination/AuthenticationFragment.java
UTF-8
7,038
1.898438
2
[]
no_license
package com.travisit.travisitbusiness.vvm.destination; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.NavDirections; import androidx.navigation.Navigation; import android.text.Editable; import android.text.Html; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.TextView; import com.google.gson.Gson; import com.travisit.travisitbusiness.data.Client; import com.travisit.travisitbusiness.databinding.FragmentAuthenticationBinding; import com.travisit.travisitbusiness.databinding.FragmentSplashBinding; import com.travisit.travisitbusiness.model.Business; import com.travisit.travisitbusiness.utils.SharedPrefManager; import com.travisit.travisitbusiness.vvm.AppActivity; import com.travisit.travisitbusiness.vvm.vm.AuthenticationVM; import com.travisit.travisitbusiness.R; public class AuthenticationFragment extends Fragment { private AuthenticationVM vm; private FragmentAuthenticationBinding binding; public SharedPrefManager preferences; private final TextWatcher watcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (getFieldText("email").length() == 0 || getFieldText("password").length() < 6 ){ binding.fAuthBtnSignIn.setEnabled(false); } else { binding.fAuthBtnSignIn.setEnabled(true); } } }; private Business user; public static AuthenticationFragment newInstance() { return new AuthenticationFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ((AppActivity)getActivity()).changeBottomNavVisibility(View.GONE,false); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); binding = FragmentAuthenticationBinding.inflate(inflater, container, false); View view = binding.getRoot(); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); preferences = new SharedPrefManager(getActivity()); vm = ViewModelProviders.of(this).get(AuthenticationVM.class); user = CompleteProfileFragmentArgs.fromBundle(getArguments()).getUser(); if (user != null) { NavDirections action = AuthenticationFragmentDirections.actionFromAuthToCompleteProfile().setUser(user); Navigation.findNavController(view).navigate(action); } String gotToSignUpText = getResources().getString(R.string.go_to_sign_up); binding.fAuthTvGoToSignup.setText(Html.fromHtml(gotToSignUpText)); handleUserInteractions(view); } private void handleUserInteractions(final View view) { binding.fAuthTvGoToSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Navigation.findNavController(view).navigate(R.id.action_from_auth_to_reg); } }); binding.fAuthTvForgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Navigation.findNavController(view).navigate(R.id.action_from_auth_to_forgot_password); } }); binding.fAuthBtnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("PVMError","ssssss"); vm.signInBusiness(getFieldText("email"), getFieldText("password")); vm.businessMutableLiveData.observe(getActivity(), new Observer<Business>() { @Override public void onChanged(Business business) { if (business!=null){ preferences.saveUser(business); Client.reinstantiateClient(business.getToken()); //Navigation.findNavController(view).navigate(R.id.action_from_auth_to_home); if (business.getApprovementStatus() != null) { if (business.getApprovementStatus().contains("inComplete")) { NavDirections action = AuthenticationFragmentDirections.actionFromAuthToCompleteProfile().setUser(business); Navigation.findNavController(view).navigate(action); } else if (business.getApprovementStatus().contains("pending")) { NavDirections action = AuthenticationFragmentDirections.actionFromAuthToShowAccountStatus().setIsVerified(false); Navigation.findNavController(view).navigate(action); } else { if (business.getBranchesCount() == null || business.getBranchesCount() < 1) { NavDirections action = AuthenticationFragmentDirections.actionFromAuthToShowAccountStatus().setIsVerified(true); Navigation.findNavController(view).navigate(action); } else { Navigation.findNavController(view).navigate(R.id.action_from_auth_to_home); } } } else { Navigation.findNavController(view).navigate(R.id.action_from_auth_to_home); } }else {/*You Need to register*/} } }); } }); binding.fAuthTietEmailAddress.addTextChangedListener(watcher); binding.fAuthTietPassword.addTextChangedListener(watcher); } private String getFieldText(String fieldName){ switch (fieldName){ case "email": return binding.fAuthTietEmailAddress.getText().toString(); case "password": return binding.fAuthTietPassword.getText().toString(); default: return "invalid"; } } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }
true
0f630531d6d8f8b0d727a6d611abbeda8fd2e9c7
Java
davideyoga/OOSD-Project
/src/gamingplatform/controller/Add.java
UTF-8
4,005
2.546875
3
[]
no_license
package gamingplatform.controller; import gamingplatform.dao.exception.DaoException; import gamingplatform.dao.implementation.*; import gamingplatform.dao.interfaces.*; import gamingplatform.model.DBTableStructure; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static gamingplatform.controller.utils.SecurityLayer.checkAuth; import static gamingplatform.controller.utils.SecurityLayer.redirect; import static gamingplatform.controller.utils.SessionManager.*; import static gamingplatform.controller.utils.Utils.getLastBitFromUrl; import static gamingplatform.view.FreemarkerHelper.process; /** * classe Servlet che si occupa di presentare l'interfaccia di aggiunta elementi al db */ public class Add extends HttpServlet { @Resource(name = "jdbc/gamingplatform") private static DataSource ds; //container dati che sarà processato da freemarker private Map<String, Object> data = new HashMap<>(); /** * gestisce richieste GET, nello specifico mostra la form di inserimento per un data entità * @param request richiesta servlet * @param response risposta servlet * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //pop dell'eventuale messaggio in sessione //nel dettaglio inserisco un elemento "message" dentro la Map che andrà a processare freemarker //prendendolo dalla sessione tramite SessionManager.pop che appunto ritorna il messaggio in sessione, se c'è //oppure null data.put("message", popMessage(request)); //carico l'user nella Map prelevandolo dalla sessione se verificata data.put("user", getUser(request)); //carico i servizi data.put("services", getServices(request)); //carico la "modalità" (edit) data.put("mode", "add"); //carico la tabella in cui si vuole aggiungere la tupla (la url è della forma /add/tabella String item = getLastBitFromUrl(request.getRequestURI()); data.put("table", item); //controllo quì se l'utente è loggato e ha acesso al report di quella determinata tabella if (!checkAuth(request, item)) { //se l'ultimo elemento dopo lo "/" (ovvero il servizio a cui si sta provando ad accedere) //non è un servizio a cui l'utente ha accesso redirect("/index", "KO-unauthorized", response, request); return; } try { //prelevo la struttura della tabella sul db DBTableStructureDao dbsDao = new DBTableStructureDaoImpl(ds); dbsDao.init(item); DBTableStructure dbs = dbsDao.getDBTableStructure(); dbs = dbsDao.getTableStructure(); dbsDao.destroy(); //carico i dati della struttura della tabella nella map di freemarker //così poi da freemarker posso generare la form in modo generale a prescindere //dalla tabella del db in esame data.put("fields", dbs.getFields()); data.put("keys", dbs.getKeys()); data.put("nulls", dbs.getNulls()); data.put("types", dbs.getTypes()); data.put("defaults", dbs.getDefaults()); data.put("extras", dbs.getExtras()); data.put("arity", dbs.getArity()); } catch (DaoException e) { Logger.getAnonymousLogger().log(Level.WARNING, "[Add: item = " + item + "] " + e.getMessage()); } //processo template process("crudForm.ftl", data, response, getServletContext()); } }
true
946821590cee30a97b220a12ea157c1501eface9
Java
techthirsts/AndroidLocationTracker
/LocationBasedService/src/com/example/locationbasedservice/tracklist.java
UTF-8
4,479
2.125
2
[]
no_license
package com.example.locationbasedservice; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TableRow.LayoutParams; import android.widget.TextView; import android.widget.Toast; public class tracklist extends Activity implements View.OnClickListener{ TableLayout table_layout; //LinearLayout linear_layout,parent; int cols = 7; String name; //Date sch_from,sch_to,time_from, time_to,d,t; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tracklist); name = getIntent().getStringExtra("username"); final trackcontroller t_db = new trackcontroller(this); // parent = (LinearLayout) findViewById(R.id.linearlayout1); table_layout = (TableLayout) findViewById(R.id.tableLayout1); //linear_layout = (LinearLayout) findViewById(R.id.linearlayout2); int rows = t_db.getDatasCount(); Toast.makeText(this,"Row count "+rows+" "+name,Toast.LENGTH_SHORT).show(); // outer for loop t_db.openDB(); Cursor c1=t_db.getData(); String[] Fields=new String[]{ "Trackname","FromDate","ToDate","FromTime","ToTime","Repeat" }; //c1 = t_db.getString(null); c1.moveToFirst(); TableRow row = new TableRow(this); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); for (int j =0; j <6; j++) { TextView tv = new TextView(this); tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setBackgroundColor(Color.LTGRAY); tv.setGravity(Gravity.CENTER); tv.setTextSize(18); tv.setPadding(0, 0, 0, 0); tv.setTextColor(Color.RED); tv.setText(Fields[j]); row.addView(tv); } table_layout.addView(row); // outer for loop for (int i = 0; i < rows; i++) { row = new TableRow(this); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); for (int j = 2; j <= cols; j++) { TextView tv = new TextView(this); tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); tv.setBackgroundColor(Color.TRANSPARENT); tv.setGravity(Gravity.CENTER); tv.setTextSize(18); tv.setPadding(0, 0, 0, 0); tv.setText(c1.getString(j)); final String trackname=c1.getString(1); final String repeat=c1.getString(7); final Cursor cur=c1; row.addView(tv); tv.setOnClickListener(new OnClickListener(){ public void onClick(View v) { Intent main = new Intent(tracklist.this,Load.class); main.putExtra("username", name); main.putExtra("trackname", trackname); startActivity(main); /*if(repeat.equals("Yes")) { repeat(cur.getString(1),cur.getString(2),cur.getString(3),cur.getString(4),cur.getString(5),cur.getString(6)); }*/ } }); } c1.moveToNext(); table_layout.addView(row); } row = new TableRow(this); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); Button b = new Button(this); b.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); b.setText("Add"); row.addView(b); table_layout.addView(row); b.setOnClickListener(this); t_db.close(); } public void onClick(View v) { Intent main = new Intent(tracklist.this,track.class); main.putExtra("username", name); //main.putExtra("trackname", name.toString()); startActivity(main); } }
true
9f9a49154a3f0c91d58bcf0846667cec57275f0e
Java
freedom541/cclTest
/ccl-spring-jetty-jersey-mybatis/src/main/java/com/ccl/main/Main.java
UTF-8
1,375
2.25
2
[]
no_license
package com.ccl.main; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.glassfish.jersey.servlet.ServletContainer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.request.RequestContextListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; public class Main { public static void main(String[] args) throws Exception { ApplicationConfig applicationConfig = new ApplicationConfig(); ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(applicationConfig)); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(jerseyServlet, "/rest/*"); context.addEventListener(new ContextLoaderListener()); context.addEventListener(new RequestContextListener()); context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); context.setInitParameter("contextConfigLocation", SpringJavaConfiguration.class.getName()); int port=8080; if(args.length==1){ port=Integer.parseInt(args[0]); } Server server = new Server(port); server.setHandler(context); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } } }
true
a43bcc82b20278a346fe531d3fff47ebd7b41ea8
Java
treejames/Breeze_android
/TWP/src/com/twp/activity/model/VendorList.java
UTF-8
1,620
2.078125
2
[]
no_license
package com.twp.activity.model; import java.util.ArrayList; import android.content.Context; import com.twp.database.TWPDataManager; import com.twp.database.TWPDatabaseFinder; import com.twp.im.R; import com.twp.model.Vendor; import com.twp.networking.TWPOrderManager; public class VendorList { private static VendorList _instance; private Context _Context; private VendorList() { } public static VendorList getInstance() { if (_instance == null) { _instance = new VendorList(); } return _instance; } public ArrayList<BaseItem> getArrayList() { int currentVendorID = TWPOrderManager.getInstance().getCurrentVendorID(); if(currentVendorID == -1){ return getEmptyList(); } else{ return getCurrentList(currentVendorID); } } public void setConext(Context context){ this._Context = context; } public ArrayList<BaseItem> getCurrentList(int id) { ArrayList<BaseItem> resultList = new ArrayList<BaseItem>(); if(id>=1){ Vendor vendor = TWPDatabaseFinder.findVendorById(id); BaseItem itm = new BaseItem( vendor.getId(), vendor.getName(), null, null, false); resultList.add(itm); } else{ resultList = getEmptyList(); } return resultList; } public ArrayList<BaseItem> getEmptyList() { ArrayList<BaseItem> resultList = new ArrayList<BaseItem>(); BaseItem itm; itm = new BaseItem( 0, this._Context.getString(R.string.txt_order_summary_select_vendor), null, null, false); resultList.add(itm); return resultList; }; }
true
80e411d2c88c7c2f3221972c53e6cec0f96d2dc4
Java
Qwe1999/heroku_backend
/src/main/java/com/softserve/academy/event/service/db/EmailService.java
UTF-8
236
1.65625
2
[]
no_license
package com.softserve.academy.event.service.db; public interface EmailService { void sendMail(String recipientAddress, String subject, String message); void sendEmailForUser(String idUser, String idSurvey, String[] anEmail); }
true
1df721e68d6845238b73c283ea6b442ff1482f02
Java
MeFisto94/Monake
/src/main/java/com/jmonkeyengine/monake/net/client/SharedObjectUpdater.java
UTF-8
7,356
1.960938
2
[ "BSD-3-Clause" ]
permissive
/* * $Id$ * * Copyright (c) 2016, Simsilica, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jmonkeyengine.monake.net.client; import java.util.*; import com.jme3.network.service.AbstractClientService; import com.jme3.network.service.ClientServiceManager; import com.jmonkeyengine.monake.es.BodyPosition; import com.simsilica.es.*; import com.simsilica.es.client.EntityDataClientService; import com.simsilica.ethereal.EtherealClient; import com.simsilica.ethereal.SharedObject; import com.simsilica.ethereal.SharedObjectListener; import org.slf4j.*; /** * Updates the entities local position from network state. * Requires that the entity have the BodyPosition component * to accumulate state history for some backlog. Updates to * entities without a BodyPosition will be ignored... the alternative * would be to cache a BodyPosition in advance until we finally * see the entity. This will be necessary if strict starting visibility * is ever a requirement as the message that updates the entity's component * may come some time after we've been recieving valid updates. Enough that * we'll be missing some history. (For com.jmonkeyengine.monake.example, a missile might look like * it starts a bit down its path.) * * @author Paul Speed */ public class SharedObjectUpdater extends AbstractClientService implements SharedObjectListener { static Logger log = LoggerFactory.getLogger(SharedObjectUpdater.class); private EntityData ed; private EntitySet entities; private long frameTime; public SharedObjectUpdater() { } @Override protected void onInitialize(ClientServiceManager s) { log.info("onInitialize()"); this.ed = getService(EntityDataClientService.class).getEntityData(); } @Override public void start() { log.info("start()"); entities = ed.getEntities(BodyPosition.class); this.frameTime = -1; getService(EtherealClient.class).addObjectListener(this); } @Override public void stop() { log.info("stop()"); getService(EtherealClient.class).removeObjectListener(this); entities.release(); } @Override public void beginFrame( long time ) { if( log.isTraceEnabled() ) { log.trace("** beginFrame(" + time + ")"); } this.frameTime = time; if( entities.applyChanges() ) { // Make sure the added/updated entities have been initialized initializeBodyPosition(entities.getAddedEntities()); initializeBodyPosition(entities.getChangedEntities()); } } protected void initializeBodyPosition( Set<Entity> set ) { for( Entity e : set ) { BodyPosition pos = e.get(BodyPosition.class); // BodyPosition requires special management to make // sure all instances of BodyPosition are sharing the same // thread-safe history buffer pos.initialize(e.getId(), 12); } } @Override public void objectUpdated( SharedObject obj ) { if( log.isTraceEnabled() ) { log.trace("****** Object moved[t=" + frameTime + "]:" + obj.getEntityId() + " pos:" + obj.getWorldPosition() + " removed:" + obj.isMarkedRemoved()); } EntityId id = new EntityId(obj.getEntityId()); Entity entity = entities.getEntity(id); if( entity == null ) { if( log.isDebugEnabled() ) { log.debug("No entity yet for:" + obj.getEntityId()); } return; } BodyPosition pos = entity.get(BodyPosition.class); if( pos == null ) { // normal as it may take longer for that update to get here if( log.isDebugEnabled() ) { log.debug("Object doesn't have a BodyPosition yet for:" + obj.getEntityId()); } } else { // Update our position buffer pos.addFrame(frameTime, obj.getWorldPosition().toVector3f(), obj.getWorldRotation().toQuaternion(), true); } } @Override public void objectRemoved( SharedObject obj ) { if( log.isDebugEnabled() ) { log.debug("****** Object removed[t=" + frameTime + "]:" + obj.getEntityId()); } EntityId id = new EntityId(obj.getEntityId()); Entity entity = entities.getEntity(id); if( entity == null ) { if( log.isDebugEnabled() ) { log.debug("No entity for removed object for:" + obj.getEntityId()); } return; } BodyPosition pos = entity.get(BodyPosition.class); if( pos == null ) { // normal as it may take longer for that update to get here if( log.isDebugEnabled() ) { log.debug("Removed object doesn't have a BodyPosition yet for:" + obj.getEntityId()); } } else { if( log.isDebugEnabled() ) { log.debug("Setting entity to invisible for:" + obj.getEntityId()); } pos.addFrame(frameTime, obj.getWorldPosition().toVector3f(), obj.getWorldRotation().toQuaternion(), false); } } @Override public void endFrame() { log.trace("** endFrame()"); this.frameTime = -1; } }
true
33d75d75b16ef6fd4ff931231116c650d9d6156b
Java
vivdalal/java-swing-apps
/Assignment_3/Assignment-3-Travel-Application/src/Interface/ManageAirlines/ManageAirlinesJPanel.java
UTF-8
5,892
2.296875
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 Interface.ManageAirlines; import Business.Airline.AirlineDirectory; import javax.swing.JPanel; /** * * @author vivekdalal */ public class ManageAirlinesJPanel extends javax.swing.JPanel { private AirlineDirectory airlineDirectory; private JPanel cardSequenceJPanel; /** * Creates new form ManageAirlinesJPanel */ public ManageAirlinesJPanel(JPanel cardSequenceJPanel, AirlineDirectory airlineDirectory) { initComponents(); this.cardSequenceJPanel = cardSequenceJPanel; this.airlineDirectory = airlineDirectory; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); addAirlineBtn = new javax.swing.JButton(); viewAirlineBtn = new javax.swing.JButton(); searchAirlineBtn = new javax.swing.JButton(); searchTxtFld = new javax.swing.JTextField(); updateAirlineBtn = new javax.swing.JButton(); setMaximumSize(new java.awt.Dimension(800, 600)); setMinimumSize(new java.awt.Dimension(800, 600)); setPreferredSize(new java.awt.Dimension(800, 600)); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Lucida Grande", 3, 12)); // NOI18N jLabel1.setText("Manage Airlines"); add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(14, 6, 140, 30)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 40, 600, 160)); addAirlineBtn.setText("Add Airline"); addAirlineBtn.setMaximumSize(new java.awt.Dimension(120, 30)); addAirlineBtn.setMinimumSize(new java.awt.Dimension(120, 30)); addAirlineBtn.setPreferredSize(new java.awt.Dimension(120, 30)); addAirlineBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addAirlineBtnActionPerformed(evt); } }); add(addAirlineBtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 270, 130, -1)); viewAirlineBtn.setText("View Airline"); viewAirlineBtn.setMaximumSize(new java.awt.Dimension(120, 30)); viewAirlineBtn.setMinimumSize(new java.awt.Dimension(120, 30)); viewAirlineBtn.setPreferredSize(new java.awt.Dimension(120, 30)); add(viewAirlineBtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 310, 130, -1)); searchAirlineBtn.setText("Search Airline"); searchAirlineBtn.setMaximumSize(new java.awt.Dimension(120, 30)); searchAirlineBtn.setMinimumSize(new java.awt.Dimension(120, 30)); searchAirlineBtn.setPreferredSize(new java.awt.Dimension(120, 30)); add(searchAirlineBtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 350, 130, -1)); searchTxtFld.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchTxtFldActionPerformed(evt); } }); add(searchTxtFld, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 350, 190, -1)); updateAirlineBtn.setText("Update Airline"); updateAirlineBtn.setMaximumSize(new java.awt.Dimension(120, 30)); updateAirlineBtn.setMinimumSize(new java.awt.Dimension(120, 30)); updateAirlineBtn.setPreferredSize(new java.awt.Dimension(120, 30)); add(updateAirlineBtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 390, 130, -1)); }// </editor-fold>//GEN-END:initComponents private void searchTxtFldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTxtFldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_searchTxtFldActionPerformed private void addAirlineBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAirlineBtnActionPerformed // Manage Airline button action code goes here. // AddNewAirlineJPanel addNewAirlineJPanel = new AddNewAirlineJPanel(cardSequenceJPanel, airline); // cardSequenceJPanel.add("AddNewAirlineJPanel", addNewAirlineJPanel); // CardLayout cardLayout = (CardLayout) cardSequenceJPanel.getLayout(); // cardLayout.next(cardSequenceJPanel); }//GEN-LAST:event_addAirlineBtnActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addAirlineBtn; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JButton searchAirlineBtn; private javax.swing.JTextField searchTxtFld; private javax.swing.JButton updateAirlineBtn; private javax.swing.JButton viewAirlineBtn; // End of variables declaration//GEN-END:variables }
true
cc7ac44a18c0049c56cc7bde6b9abab888d3f867
Java
NikolayNS/user-storage
/src/main/java/com/dmitrenko/userstorage/mapper/Mapper.java
UTF-8
320
2.390625
2
[]
no_license
package com.dmitrenko.userstorage.mapper; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public interface Mapper<T, S> { T from(S source); default List<T> from(Collection<S> sources) { return sources .stream() .map(this::from) .collect(Collectors.toList()); } }
true
08c5be7c70e125a5e29626826fd411bfc0dd9759
Java
luthfihariz/jalan-android-app
/app/src/main/java/com/luthfihariz/jalan/contract/NearbyContract.java
UTF-8
396
1.828125
2
[]
no_license
package com.luthfihariz.jalan.contract; import com.luthfihariz.jalan.BasePresenter; import com.luthfihariz.jalan.BaseView; /** * Created by luthfihariz on 11/6/16. */ public class NearbyContract { public interface Presenter extends BasePresenter<View> { void loadNearby(); } public interface View extends BaseView<Presenter> { void updateNearbyList(); } }
true
5b95c046e1cab172338562c12d74f067f229222e
Java
StevenS125/jdbc.database-console
/src/main/java/com/github/perschola/MyObject.java
UTF-8
4,123
3.171875
3
[]
no_license
package com.github.perschola; import java.sql.*; import com.mysql.cj.jdbc.Driver; import java.util.StringJoiner; public class MyObject implements Runnable { public void run() { registerJDBCDriver(); Connection mysqlDbConnection = getConnection("mysql"); executeStatement(mysqlDbConnection, "DROP DATABASE IF EXISTS databaseName;"); executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS databaseName;"); executeStatement(mysqlDbConnection, "USE databaseName;"); executeStatement(mysqlDbConnection, new StringBuilder() .append("CREATE TABLE IF NOT EXISTS databaseName.pokemonTable(") .append("id int auto_increment primary key,") .append("name text not null,") .append("primary_type int not null,") .append("secondary_type int null);").toString()); executeStatement(mysqlDbConnection, new StringBuilder() .append("INSERT INTO databaseName.pokemonTable ") .append("(id, name, primary_type, secondary_type)") .append(" VALUES (12, 'Ivysaur', 3, 7);").toString()); executeStatement(mysqlDbConnection, new StringBuilder() .append("INSERT INTO databaseName.pokemonTable ") .append("(id, name, primary_type, secondary_type)") .append(" VALUES (13, 'Charmander', 4, 8);").toString()); String query = "SELECT * FROM databaseName.pokemonTable;"; ResultSet resultSet = executeQuery(mysqlDbConnection, query); printResults(resultSet); } void registerJDBCDriver() { // Attempt to register JDBC Driver try { DriverManager.registerDriver(Driver.class.newInstance()); } catch (InstantiationException | IllegalAccessException | SQLException e1) { throw new Error(e1); } } public Connection getConnection(String dbVendor) { String username = "root"; String password = "root"; String url = "jdbc:" + dbVendor + "://localhost:8889?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; try { return DriverManager.getConnection(url, username, password); } catch (SQLException e) { throw new Error(e); } } public Statement getScrollableStatement(Connection connection) { int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE; int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY; try { return connection.createStatement(resultSetType, resultSetConcurrency); } catch (SQLException e) { throw new Error(e); } } public void printResults(ResultSet resultSet) { try { for (Integer rowNumber = 0; resultSet.next(); rowNumber++) { String firstColumnData = resultSet.getString(1); String secondColumnData = resultSet.getString(2); String thirdColumnData = resultSet.getString(3); System.out.println(new StringJoiner("\n") .add("Row number = " + rowNumber.toString()) .add("First Column = " + firstColumnData) .add("Second Column = " + secondColumnData) .add("Third column = " + thirdColumnData) .toString()); } } catch (SQLException e) { throw new Error(e); } } void executeStatement(Connection connection, String sqlStatement) { try { Statement statement = getScrollableStatement(connection); statement.execute(sqlStatement); } catch (SQLException e) { throw new Error(e); } } ResultSet executeQuery(Connection connection, String sqlQuery) { try { Statement statement = getScrollableStatement(connection); return statement.executeQuery(sqlQuery); } catch (SQLException e) { throw new Error(e); } } }
true
4d00592c6467830073b5fa7f6c38653748d30fe8
Java
adi100989/OraclePGX_FinalReport
/diameter/test/ApproximateDiameter.java
UTF-8
4,671
2.453125
2
[]
no_license
import oracle.pgx.api.CompiledProgram; import oracle.pgx.api.Pgx; import oracle.pgx.api.PgxGraph; import oracle.pgx.api.PgxVertex; import oracle.pgx.api.PgxSession; import oracle.pgx.api.internal.AnalysisResult; import oracle.pgx.api.VertexProperty; import oracle.pgx.common.types.PropertyType; import oracle.pgx.common.util.vector.Vect; import oracle.pgx.api.PgxVect; import java.lang.*; import java.util.*; import java.io.PrintWriter; import java.io.FileOutputStream; public class ApproximateDiameter { public static final int RAND_MAX = 32767; public static final int BITMASK_LENGTH = 64; public static Random rand = new Random(); public static float my_rand(){ float res = (float) ( rand.nextInt(RAND_MAX) / (RAND_MAX + 1.0) ); return res; } public static int hash_value(){ int ret = 0; while(my_rand() < 0.5){ ret ++; } return ret; } public static Integer[] create_bitmask(){ Integer[] bit_mask = new Integer[BITMASK_LENGTH]; for(int i = 0; i < BITMASK_LENGTH; i++) { bit_mask[i] = Integer.valueOf(0); } int hash = hash_value(); bit_mask[hash] = Integer.valueOf(1); return bit_mask; } public static void main(String[] args) throws Exception { PgxSession session = Pgx.createSession("my-session"); CompiledProgram approximate_diameter = session.compileProgram("/var/services/homes/adisingh/github/OraclePGX_FinalReport/diameter/test/approximate_diameter.gm"); PgxGraph graph = session.readGraphWithProperties("/var/services/homes/adisingh/github/OraclePGX_FinalReport/Link_Prediction/facebook.json"); VertexProperty<Integer,Integer> id = graph.getVertexProperty("nodeID"); System.out.println("Number of nodes:"+(int)id.size()); double n = (double)id.size(); int maxIter = 256; int K =1; int log_n = (int) Math.log(n); VertexProperty<Integer,Integer> radius = graph.createVertexProperty(PropertyType.INTEGER, "radius"); VertexProperty<Integer,PgxVect<Integer>> bit_string = graph.createVertexVectorProperty(PropertyType.INTEGER, BITMASK_LENGTH, "bit_string"); PrintWriter writer = new PrintWriter(new FileOutputStream("../github/OraclePGX_FinalReport/diameter/test/bitmasks.txt", false)); VertexProperty<Integer,PgxVect<Integer>> bit_mask = graph.createVertexVectorProperty(PropertyType.INTEGER, BITMASK_LENGTH, "bit_mask"); Iterable<Map.Entry<PgxVertex<Integer>,Integer>> id_iterator = id.getValues(); // Display elements int i = 0; for(Map.Entry me : id_iterator) { Integer[] bitmask = create_bitmask() ; PgxVect<Integer> bm = new PgxVect(bitmask, PropertyType.INTEGER ) ; System.out.println(i++); //System.out.println(bm); bit_mask.set((PgxVertex<Integer>)me.getKey(), bm); writer.print((PgxVertex<Integer>)me.getKey() + " : " ); writer.println(bit_mask.get((PgxVertex<Integer>)me.getKey())); //writer.println(me.getValue()); } System.out.println("Done"); writer.close(); AnalysisResult<Integer> result = approximate_diameter.run(graph, BITMASK_LENGTH, maxIter, K, bit_mask, bit_string , radius ); // AnalysisResult<Integer> result = approximate_diameter.run(graph, BITMASK_LENGTH, maxIter, K, bit_mask, bit_string, radius ); writer = new PrintWriter(new FileOutputStream("../github/OraclePGX_FinalReport/diameter/test/radius_results.txt", false)); Iterable<Map.Entry<PgxVertex<Integer>,Integer>> radius_iterator = radius.getValues(); // Display elements for(Map.Entry me : radius_iterator) { //Map.Entry me = (Map.Entry)radius_iterator.next(); writer.print(me.getKey() + ": "); writer.println(me.getValue()); //System.out.print(me.getKey() + ": "); //System.out.println(me.getValue()); } writer.close(); writer = new PrintWriter(new FileOutputStream("../github/OraclePGX_FinalReport/diameter/test/bitmask_results.txt", false)); //Iterable<Map.Entry<PgxVertex<Integer>,PgxVect<Integer>>> bm_iterator = bit_mask.getValues(); Iterable<Map.Entry<PgxVertex<Integer>,PgxVect<Integer>>> bm_iterator = bit_string.getValues(); // Display elements for(Map.Entry me : bm_iterator) { //Map.Entry me = (Map.Entry)radius_iterator.next(); writer.print(me.getKey() + ": "); writer.println(me.getValue()); //System.out.print(me.getKey() + ": "); //System.out.println(me.getValue()); } writer.close(); System.out.println("Result = " + result.getReturnValue() + " (took " + result.getExecutionTimeMs() + "ms)"); } }
true
93342ca9d6ad6d0a43cb259e35bdeaaa02205085
Java
fudai/algorithm
/src/test/java/com/leet/code/ArrayTest.java
UTF-8
480
2.390625
2
[]
no_license
package com.leet.code; import org.junit.Test; import static org.junit.Assert.*; /** * @className: ArrayTest * @description: * @author: fudai * @date: 2021-10-25 21:29 */ public class ArrayTest { @Test public void reverse() { int[] array = new int[]{2,2,2,0,1}; System.out.println(Array.reverse(array)); } @Test public void search() { int[] array = new int[]{3,4,5,1,2}; System.out.println(Array.search(array)); } }
true
52dc81eff1c7ae040d22b61a8dc710c63fec986c
Java
vishmango117/traffic-simulator-app
/src/trafficsimulator/Straight.java
UTF-8
496
2.796875
3
[]
no_license
package trafficsimulator; public class Straight extends Intersection { private trafficsimulator.Road next_road; public Straight(trafficsimulator.Road int_road, trafficsimulator.Road next_road) { super(int_road); this.next_road = next_road; } public Straight() { super(); } public trafficsimulator.Road getNext_road() { return next_road; } public void setNext_road(Road next_road) { this.next_road = next_road; } }
true
050b90c6c133a6b917265e4eaaf61489065c9ea6
Java
Frostcast/Kingdoms
/src/main/java/me/leothepro555/kingdoms/main/NexusBlockManager.java
UTF-8
54,297
2.140625
2
[]
no_license
package me.leothepro555.kingdoms.main; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class NexusBlockManager implements Listener{ private Kingdoms plugin; private Inventory nexusgui; private Inventory kchest; private Inventory dumpgui; private Inventory champions; private int rpi = 10; public NexusBlockManager(Kingdoms plugin){ this.plugin = plugin; if(plugin.getConfig().get("items-needed-for-one-resource-point") != null){ this.rpi = plugin.getConfig().getInt("items-needed-for-one-resource-point"); } } @EventHandler public void onPlayerClick(PlayerInteractEvent event){ Player p = event.getPlayer(); if(event.getAction() == Action.RIGHT_CLICK_BLOCK){ if(event.getClickedBlock().getType() == Material.BEACON){ if(event.getClickedBlock().hasMetadata("nexusblock")){ event.setCancelled(true); if(!plugin.getChunkKingdom(event.getClickedBlock().getLocation().getChunk()).equals(plugin.getKingdom(p))){ if(!plugin.isAlly(plugin.getChunkKingdom(event.getClickedBlock().getLocation().getChunk()),p)){ p.sendMessage(ChatColor.RED + "You can't use a nexus that doesn't belong to your kingdom!"); }else{ dumpgui = Bukkit.createInventory(null, 54, ChatColor.DARK_BLUE + "Donate to " + ChatColor.DARK_GREEN + plugin.getChunkKingdom(event.getClickedBlock().getLocation().getChunk())); p.openInventory(dumpgui); } if(plugin.isKAlly(plugin.getKingdom(p), plugin.getChunkKingdom(event.getClickedBlock().getLocation().getChunk()))){ p.sendMessage(ChatColor.RED + "You marked " + plugin.getChunkKingdom(event.getClickedBlock().getLocation().getChunk()) + " as an ally, but they did not mark your kingdom as their ally"); } }else if(plugin.getChunkKingdom(event.getClickedBlock().getLocation().getChunk()).equals(plugin.getKingdom(p))){ openNexusGui(p); } } } } } @EventHandler public void onInventoryMove(InventoryClickEvent event){ Player p = (Player) event.getWhoClicked(); if(event.getInventory().getName().endsWith(ChatColor.AQUA + plugin.getKingdom(p) + "'s nexus")){ event.setCancelled(true); if(event.getCurrentItem() != null){ if(event.getCurrentItem().getItemMeta() != null){ if(event.getCurrentItem().getItemMeta().getDisplayName() != null){ if(event.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.AQUA + "Kingdom Chest")){ openKingdomChest(p); } if(event.getCurrentItem().getItemMeta().getLore() != null){ if(event.getCurrentItem().getItemMeta().getLore().contains(ChatColor.LIGHT_PURPLE + "Nexus Upgrade")){ int cost = 0; int max = 1; event.setCancelled(true); ItemStack item = event.getCurrentItem(); int rp = plugin.kingdoms.getInt(plugin.getKingdom(p) + ".resourcepoints"); if(plugin.isMod(plugin.getKingdom(p), p) || plugin.isKing(p)){ if(item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.AQUA + "Damage Reduction")){ cost = plugin.getConfig().getInt("cost.nexusupgrades.dmg-reduc"); max = plugin.getConfig().getInt("max.nexusupgrades.dmg-reduc"); if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), cost)){ if(plugin.powerups.getInt(plugin.getKingdom(p) + ".dmg-reduction") < max){ plugin.rpm.minusRP(plugin.getKingdom(p), cost); upgradePowerup(plugin.getKingdom(p), "dmg-reduction", 1); p.sendMessage(ChatColor.GREEN + "Damage reduction upgraded! Total: " + plugin.powerups.getInt(plugin.getKingdom(p) + ".dmg-reduction")); p.closeInventory(); openNexusGui(p); }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level!"); } }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } } if(item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.AQUA + "Regeneration Boost")){ cost = plugin.getConfig().getInt("cost.nexusupgrades.regen-boost"); max = plugin.getConfig().getInt("max.nexusupgrades.regen-boost"); if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), cost)){ if(plugin.powerups.getInt(plugin.getKingdom(p) + ".regen-boost") < max){ plugin.rpm.minusRP(plugin.getKingdom(p), cost); upgradePowerup(plugin.getKingdom(p), "regen-boost", 5); p.sendMessage(ChatColor.GREEN + "Regeneration boost upgraded! Total: " + plugin.powerups.getInt(plugin.getKingdom(p) + ".regen-boost")); p.closeInventory(); openNexusGui(p); }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level!"); } }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } } if(item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.AQUA + "Damage Boost")){ cost = plugin.getConfig().getInt("cost.nexusupgrades.dmg-boost"); max = plugin.getConfig().getInt("max.nexusupgrades.dmg-boost"); if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), cost)){ if(plugin.powerups.getInt(plugin.getKingdom(p) + ".dmg-boost") < max){ plugin.rpm.minusRP(plugin.getKingdom(p), cost); upgradePowerup(plugin.getKingdom(p), "dmg-boost", 1); p.sendMessage(ChatColor.GREEN + "Damage boost upgraded! Total: " + plugin.powerups.getInt(plugin.getKingdom(p) + ".dmg-boost")); p.closeInventory(); openNexusGui(p); }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level!"); } }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } } if(item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.AQUA + "Increase Kingdom Chest Size")){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 30)){ if(plugin.kingdoms.getInt(plugin.getKingdom(p) + ".chestsize") < 27){ plugin.rpm.minusRP(plugin.getKingdom(p), 30); plugin.kingdoms.set(plugin.getKingdom(p) + ".chestsize", plugin.kingdoms.getInt(plugin.getKingdom(p) + ".chestsize") + 9); plugin.saveKingdoms(); p.sendMessage(ChatColor.GREEN + "Chest Size upgraded! Total: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".chestsize")); p.closeInventory(); openNexusGui(p); }else{ p.sendMessage(ChatColor.RED + "Maximum level reached."); } }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } } }else{ p.sendMessage(ChatColor.RED + "Only kingdom kings and mods can upgrade bonuses"); } }else if(event.getCurrentItem().getItemMeta().getLore().contains(ChatColor.LIGHT_PURPLE + "Nexus Option")){ event.setCancelled(true); ItemStack item = event.getCurrentItem(); if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Convert items to resource points")){ dumpgui = Bukkit.createInventory(null, 54, ChatColor.DARK_BLUE + "Close inventory to confirm."); p.openInventory(dumpgui); } }else if(event.getCurrentItem().getItemMeta().getLore().contains(ChatColor.LIGHT_PURPLE + "Click to open Champion upgrades")){ if(plugin.isMod(plugin.getKingdom(p), p) || plugin.isKing(p)){ event.setCancelled(true); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "Only kingdom kings and mods can upgrade bonuses"); p.closeInventory(); } }else if(event.getCurrentItem().getItemMeta().getLore().contains(ChatColor.LIGHT_PURPLE + "Click to open Miscellaneous upgrades")){ if(plugin.isMod(plugin.getKingdom(p), p) || plugin.isKing(p)){ event.setCancelled(true); openMisMenu(p); }else{ p.sendMessage(ChatColor.RED + "Only kingdom kings and mods can upgrade bonuses"); p.closeInventory(); } }else if(event.getCurrentItem().getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Turrets")){ if(plugin.isMod(plugin.getKingdom(p), p) || plugin.isKing(p)){ event.setCancelled(true); openTurretShop(p); }else{ p.sendMessage(ChatColor.RED + "Only kingdom kings and mods can buy turrets"); p.closeInventory(); } }else if(event.getCurrentItem().getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Survivability")){ if(plugin.isMod(plugin.getKingdom(p), p) || plugin.isKing(p)){ event.setCancelled(true); openSurvivabilityShop(p); }else{ p.sendMessage(ChatColor.RED + "Only kingdom kings and mods can upgrade bonuses"); p.closeInventory(); } }else if(event.getCurrentItem().getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Structures")){ if(plugin.isMod(plugin.getKingdom(p), p) || plugin.isKing(p)){ event.setCancelled(true); openStructureShop(p); }else{ p.sendMessage(ChatColor.RED + "Only kingdom kings and mods can upgrade bonuses"); p.closeInventory(); } } } } } } }else if(event.getInventory().getName().equals(ChatColor.AQUA + plugin.getKingdom(p) + "'s Champion")){ event.setCancelled(true); ItemStack item = event.getCurrentItem(); if(event.getCurrentItem().getItemMeta().getDisplayName().equals(ChatColor.RED + "Return to main menu")){ p.closeInventory(); openNexusGui(p); } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Champion Weapon")){ if(getChampionUpgrade(plugin.getKingdom(p), "weapon") < 4){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 10)){ plugin.rpm.minusRP(plugin.getKingdom(p), 10); upgradeChampion(plugin.getKingdom(p), "weapon", 1); p.sendMessage(ChatColor.GREEN + "Champion Weapon upgraded! Total: " + getChampionUpgrade(plugin.getKingdom(p), "weapon")); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level."); } } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Champion Resistance")){ if(getChampionUpgrade(plugin.getKingdom(p), "resist") < 100){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 5)){ plugin.rpm.minusRP(plugin.getKingdom(p), 5); upgradeChampion(plugin.getKingdom(p), "resist", 20); p.sendMessage(ChatColor.GREEN + "Champion Resistance upgraded! Total: " + getChampionUpgrade(plugin.getKingdom(p), "resist")); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level."); } } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Champion Speed")){ if(getChampionUpgrade(plugin.getKingdom(p), "speed") < 3){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 20)){ plugin.rpm.minusRP(plugin.getKingdom(p), 20); upgradeChampion(plugin.getKingdom(p), "speed", 1); p.sendMessage(ChatColor.GREEN + "Champion Speed upgraded! Total: " + getChampionUpgrade(plugin.getKingdom(p), "speed")); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level."); } } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Champion Health")){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 2)){ plugin.rpm.minusRP(plugin.getKingdom(p), 2); upgradeChampion(plugin.getKingdom(p), "health", 2); p.sendMessage(ChatColor.GREEN + "Champion Health upgraded! Total: " + getChampionUpgrade(plugin.getKingdom(p), "health")); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Drag")){ if(plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.drag") == 0){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 30)){ plugin.rpm.minusRP(plugin.getKingdom(p), 30); upgradeChampion(plugin.getKingdom(p), "drag", 1); p.sendMessage(ChatColor.GREEN + "Drag Enabled!"); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } }else{ p.sendMessage(ChatColor.RED + "This upgrade is at its maximum level"); } } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Mock")){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 10)){ plugin.rpm.minusRP(plugin.getKingdom(p), 10); upgradeChampion(plugin.getKingdom(p), "mock", 1); p.sendMessage(ChatColor.GREEN + "Mock upgraded! Total: " + getChampionUpgrade(plugin.getKingdom(p), "mock")); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Death Duel")){ if(plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.duel") == 0){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 100)){ plugin.rpm.minusRP(plugin.getKingdom(p), 100); upgradeChampion(plugin.getKingdom(p), "duel", 1); p.sendMessage(ChatColor.GREEN + "Death Duel enabled!"); p.closeInventory(); openChampionMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this upgrade!"); } }else{ p.sendMessage(ChatColor.RED + "You have reached the maximum level for this upgrade"); } } }else if(event.getInventory().getName().equals(ChatColor.AQUA + "Extra Upgrades")){ event.setCancelled(true); if(event.getCurrentItem().getItemMeta().getDisplayName().equals(ChatColor.RED + "Return to main menu")){ p.closeInventory(); openNexusGui(p); } ItemStack item = event.getCurrentItem(); if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Anti-Creeper")){ this.upgradeMis(p, "anticreeper"); } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Anti-Trample")){ this.upgradeMis(p, "antitrample"); } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Nexus Guard")){ this.upgradeMis(p, "nexusguard"); } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Glory")){ this.upgradeMis(p, "glory"); } if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Bomb Expertise")){ this.upgradeMis(p, "bombshards"); } }else if(event.getInventory().getName().equals(ChatColor.AQUA + "Turret Shop")){ event.setCancelled(true); ItemStack item = event.getCurrentItem(); if(item.getItemMeta() != null){ if(item.getItemMeta().getLore().contains(ChatColor.LIGHT_PURPLE + "Turret")){ if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Nexus Turret")){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 300)){ p.sendMessage(ChatColor.GREEN + "Right click while holding " + ChatColor.AQUA + "Nexus Turret " + ChatColor.GREEN + "to place it"); plugin.rpm.minusRP(plugin.getKingdom(p), 300); ItemStack i2 = new ItemStack(Material.RECORD_10); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Nexus Tower"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "Zaps all enemies in range with the"); i2l.add(ChatColor.GREEN + "power of lightning"); i2l.add(ChatColor.RED+ "Can only be placed in the nexus chunk"); i2l.add(ChatColor.BLUE + "Range: 5 blocks"); i2l.add(ChatColor.BLUE + "Damage: 3 hearts/shot"); i2l.add(ChatColor.BLUE + "Attack Speed: 1/sec"); i2l.add(ChatColor.BLUE + "Targets: All targets in range"); i2l.add(ChatColor.LIGHT_PURPLE + "Turret"); i2m.setLore(i2l); i2.setItemMeta(i2m); p.getInventory().addItem(i2); p.updateInventory(); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this turret!"); } }else if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Arrow Turret")){ if(p.getInventory().firstEmpty() == -1){ p.sendMessage(ChatColor.RED + "Cannot craft with full inventory!"); return; } if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 100)){ p.sendMessage(ChatColor.GREEN + "Right click while holding " + ChatColor.AQUA + "Arrow Turret " + ChatColor.GREEN + "to place it"); plugin.rpm.minusRP(plugin.getKingdom(p), 100); ItemStack i1 = new ItemStack(Material.RECORD_9); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Arrow Turret"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Rapidly fires at anything other than"); i1l.add(ChatColor.GREEN + "kingdom members. One target at a time."); i1l.add(ChatColor.BLUE + "Range: 5 blocks"); i1l.add(ChatColor.BLUE + "Damage: 4 hearts/shot"); i1l.add(ChatColor.BLUE + "Attack Speed: 1/sec"); i1l.add(ChatColor.BLUE + "Targets: One random target in range"); i1l.add(ChatColor.LIGHT_PURPLE + "Turret"); i1m.setLore(i1l); i1.setItemMeta(i1m); p.getInventory().addItem(i1); p.updateInventory(); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this turret!"); } }else if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Flame Turret")){ if(p.getInventory().firstEmpty() == -1){ p.sendMessage(ChatColor.RED + "Cannot craft with full inventory!"); return; } if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 150)){ p.sendMessage(ChatColor.GREEN + "Right click while holding " + ChatColor.AQUA + "Flame Turret " + ChatColor.GREEN + "to place it"); plugin.rpm.minusRP(plugin.getKingdom(p), 150); ItemStack i1 = new ItemStack(Material.RECORD_9); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Flame Turret"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Fast-firing turret that sets targets on"); i1l.add(ChatColor.GREEN + "fire"); i1l.add(ChatColor.GREEN + "Works best on a flat space"); i1l.add(ChatColor.BLUE + "Range: 5 blocks"); i1l.add(ChatColor.BLUE + "Damage: 2 hearts/shot"); i1l.add(ChatColor.BLUE + "Attack Speed: 2/sec"); i1l.add(ChatColor.BLUE + "Targets: One random target in range"); i1m.setLore(i1l); i1.setItemMeta(i1m); p.getInventory().addItem(i1); p.updateInventory(); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this turret!"); } }else if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Pressure Mine")){ if(p.getInventory().firstEmpty() == -1){ p.sendMessage(ChatColor.RED + "Cannot craft with full inventory!"); return; } if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 10)){ p.sendMessage(ChatColor.GREEN + "Right click on a floor while holding " + ChatColor.AQUA + "Pressure Mine " + ChatColor.GREEN + "to place it"); plugin.rpm.minusRP(plugin.getKingdom(p), 10); ItemStack i1 = new ItemStack(Material.RECORD_9); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Pressure Mine"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "A placable pressure plate, when stepped"); i1l.add(ChatColor.GREEN + "on by non-allies, will explode, dealing "); i1l.add(ChatColor.GREEN + "damage. Does not damage blocks"); i1l.add(ChatColor.BLUE + "Range: 3 blocks"); i1l.add(ChatColor.BLUE + "Damage: 4 hearts (Depending on location)"); i1l.add(ChatColor.BLUE + "Attack Speed: one use"); i1l.add(ChatColor.BLUE + "Targets: All targets in blast range"); i1m.setLore(i1l); i1.setItemMeta(i1m); p.getInventory().addItem(i1); p.updateInventory(); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this turret!"); } } } } }else if(event.getInventory().getName().equals(ChatColor.AQUA + "Structure Shop")){ event.setCancelled(true); if(p.getInventory().firstEmpty() == -1){ p.sendMessage(ChatColor.RED + "Cannot craft with full inventory!"); return; } ItemStack item = event.getCurrentItem(); if(item.getItemMeta() != null){ if(item.getItemMeta().getLore() != null && item.getItemMeta().getDisplayName() != null){ if(item.getItemMeta().getLore().contains(ChatColor.LIGHT_PURPLE + "Placable Structure")){ if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Power Cell")){ if(plugin.rpm.hasAmtRp(plugin.getKingdom(p), 50)){ p.sendMessage(ChatColor.GREEN + "Right click while holding " + ChatColor.AQUA + "Power Cell " + ChatColor.GREEN + "to place it"); plugin.rpm.minusRP(plugin.getKingdom(p), 50); ItemStack i1 = new ItemStack(Material.MAGMA_CREAM); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName("Power Cell"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Chunks next to the chunk with a power cell"); i1l.add(ChatColor.GREEN + "cannot be invaded without invading the power"); i1l.add(ChatColor.GREEN + "cell first. Does not work on other power cell land"); i1l.add(ChatColor.RED+ "Can't be placed on power cell chunks"); i1m.setLore(i1l); i1.setItemMeta(i1m); p.getInventory().addItem(i1); p.updateInventory(); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points for this turret!"); } }else if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Arrow Turret")){ }else if(item.getItemMeta().getDisplayName().equals(ChatColor.AQUA + "Flame Turret")){ } } } } } } public int getChampionUpgrade(String kingdom, String powerup){ return plugin.kingdoms.getInt(kingdom + ".champion." + powerup); } public void upgradeChampion(String kingdom, String powerup, int amount){ plugin.kingdoms.set(kingdom + ".champion." + powerup, plugin.kingdoms.getInt(kingdom + ".champion." + powerup) + amount); plugin.saveKingdoms(); } public void upgradePowerup(String kingdom, String powerup, int amount){ plugin.powerups.set(kingdom + "." + powerup, plugin.powerups.getInt(kingdom + "." + powerup) + amount); plugin.savePowerups(); } @EventHandler public void onInventoryClose(InventoryCloseEvent event){ Player p = (Player) event.getPlayer(); if(event.getInventory().getName().equals(ChatColor.DARK_BLUE + "Close inventory to confirm.")){ int donatedamt = donateItems(event.getInventory().getContents(), plugin.getKingdom(p),p); ((Player) event.getPlayer()).sendMessage(ChatColor.GREEN + "Your kingdom gained " + donatedamt + " resource points"); }else if(event.getInventory().getName().startsWith(ChatColor.DARK_BLUE + "Donate to " + ChatColor.DARK_GREEN)){ String[] nsplit = event.getInventory().getName().split(" "); String kingdom = ChatColor.stripColor(nsplit[nsplit.length - 1]); if(event.getInventory().getContents().length > 0){ int donatedamt = donateItems(event.getInventory().getContents(), kingdom,p); ((Player) event.getPlayer()).sendMessage(ChatColor.GREEN + kingdom + " has gained " + donatedamt + " resource points. Thank you for your donation!"); plugin.messageKingdomPlayers(kingdom, ChatColor.GREEN + event.getPlayer().getName() + " has donated " + donatedamt + " resource points"); }else{ ((Player) event.getPlayer()).sendMessage(ChatColor.GREEN + kingdom + " has gained 0 resource points."); } }else if(event.getInventory().getName().equals(ChatColor.AQUA + "Kingdom Chest")){ ArrayList<ItemStack> kchestcontents = new ArrayList<ItemStack>(); for(ItemStack item: event.getInventory().getContents()){ if(item != null){ kchestcontents.add(item); } } plugin.chest.set(plugin.getKingdom(p), kchestcontents); plugin.saveChests(); } } public int donateItems(ItemStack[] items, String kingdom, Player p){ int rpdonated = 0; for(ItemStack item:items){ if(item != null){ if(!plugin.blacklistitems.contains(item.getType())){ if(!plugin.usewhitelist){ int amt = item.getAmount(); if(!plugin.specialcaseitems.containsKey(item.getType())){ rpdonated = rpdonated + amt; }else{ amt = amt * plugin.specialcaseitems.get(item.getType()); rpdonated = rpdonated + amt; } }else{ int amt = item.getAmount(); if(!plugin.whitelistitems.containsKey(item.getType())){ p.sendMessage(ChatColor.RED + item.getType().name() + " cannot be traded for resource points. Do /k tradable to see allowed trades"); p.getWorld().dropItemNaturally(p.getLocation(), item); }else{ amt = amt * plugin.whitelistitems.get(item.getType()); rpdonated = rpdonated + amt; } } }else{ if(p != null){ p.sendMessage(ChatColor.RED + item.getType().name() + " cannot be traded for resource points. Do /k tradable to see allowed trades"); p.getWorld().dropItemNaturally(p.getLocation(), item); } } } } float i = rpdonated/rpi; String newint = Float.toString(i); String[] split = newint.split("\\."); plugin.rpm.addRP(kingdom, Integer.parseInt(split[0])); plugin.saveKingdoms(); return Integer.parseInt(split[0]); } public void openNexusGui(Player p){ nexusgui = Bukkit.createInventory(null, 27, ChatColor.AQUA + plugin.getKingdom(p) + "'s nexus"); ItemStack i1 = new ItemStack(Material.WHEAT); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Convert items to resource points"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "1 resourcepoint per " + rpi + " items"); i1l.add(ChatColor.LIGHT_PURPLE + "Nexus Option"); i1m.setLore(i1l); i1.setItemMeta(i1m); ItemStack i2 = new ItemStack(Material.IRON_CHESTPLATE); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Damage Reduction"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "Each upgrade reduces damage taken by another 1%"); i2l.add(ChatColor.RED + "Current Damage Reduction: " + plugin.powerups.getInt(plugin.getKingdom(p) + ".dmg-reduction") + "%"); i2l.add(ChatColor.RED + "Cost: " + plugin.getConfig().getInt("cost.nexusupgrades.dmg-reduc") +" resource points"); i2l.add(ChatColor.RED + "Max Level: " + plugin.getConfig().getInt("max.nexusupgrades.dmg-reduc")); i2l.add(ChatColor.LIGHT_PURPLE + "Nexus Upgrade"); i2m.setLore(i2l); i2.setItemMeta(i2m); ItemStack i3 = new ItemStack(Material.RED_ROSE); ItemMeta i3m = i3.getItemMeta(); i3m.setDisplayName(ChatColor.AQUA + "Regeneration Boost"); ArrayList<String> i3l = new ArrayList<String>(); i3l.add(ChatColor.GREEN + "While in your own land, boost your health regeneration"); i3l.add(ChatColor.GREEN + "by 5% more."); i3l.add(ChatColor.RED + "Current Regeneration Boost: " + plugin.powerups.getInt(plugin.getKingdom(p) + ".regen-boost") + "%"); i3l.add(ChatColor.RED + "Cost: " + plugin.getConfig().getInt("cost.nexusupgrades.regen-boost") +" resource points"); i3l.add(ChatColor.RED + "Max Level: " + plugin.getConfig().getInt("max.nexusupgrades.regen-boost")); i3l.add(ChatColor.LIGHT_PURPLE + "Nexus Upgrade"); i3m.setLore(i3l); i3.setItemMeta(i3m); ItemStack i4 = new ItemStack(Material.IRON_SWORD); ItemMeta i4m = i4.getItemMeta(); i4m.setDisplayName(ChatColor.AQUA + "Damage Boost"); ArrayList<String> i4l = new ArrayList<String>(); i4l.add(ChatColor.GREEN + "Increase your damage by 1% more"); i4l.add(ChatColor.RED + "Current Damage Boost: " + plugin.powerups.getInt(plugin.getKingdom(p) + ".dmg-boost") + "%"); i4l.add(ChatColor.RED + "Cost: " + plugin.getConfig().getInt("cost.nexusupgrades.dmg-boost") +" resource points"); i4l.add(ChatColor.RED + "Max Level: " + plugin.getConfig().getInt("max.nexusupgrades.dmg-boost")); i4l.add(ChatColor.LIGHT_PURPLE + "Nexus Upgrade"); i4m.setLore(i4l); i4.setItemMeta(i4m); ItemStack i5 = new ItemStack(Material.BLAZE_ROD); ItemMeta i5m = i5.getItemMeta(); i5m.setDisplayName(ChatColor.AQUA + "Champion Upgrades"); ArrayList<String> i5l = new ArrayList<String>(); i5l.add(ChatColor.GREEN + "Improve your defenses by upgrading"); i5l.add(ChatColor.GREEN + "your kingdom's champion!"); i5l.add(ChatColor.LIGHT_PURPLE + "Click to open Champion upgrades"); i5m.setLore(i5l); i5.setItemMeta(i5m); ItemStack i6 = new ItemStack(Material.MONSTER_EGG); ItemMeta i6m = i6.getItemMeta(); i6m.setDisplayName(ChatColor.AQUA + "Extra Upgrades"); ArrayList<String> i6l = new ArrayList<String>(); i6l.add(ChatColor.GREEN + "Miscellaneous Upgrades."); i6l.add(ChatColor.LIGHT_PURPLE + "Click to open Miscellaneous upgrades"); i6m.setLore(i6l); i6.setItemMeta(i6m); ItemStack i7 = new ItemStack(Material.ENDER_PORTAL_FRAME); ItemMeta i7m = i7.getItemMeta(); i7m.setDisplayName(ChatColor.AQUA + "Increase Kingdom Chest Size"); ArrayList<String> i7l = new ArrayList<String>(); i7l.add(ChatColor.RED + "Current Chest Size: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".chestsize") + " slots"); i7l.add(ChatColor.GREEN + "Allows more loot for the champion to capture with"); i7l.add(ChatColor.GREEN + "the loot champion upgrade, and increases the kingdom"); i7l.add(ChatColor.GREEN + "chest size."); i7l.add(ChatColor.RED + "Cost: 30 resource points for 9 more slots"); i7l.add(ChatColor.LIGHT_PURPLE + "Nexus Upgrade"); i7m.setLore(i7l); i7.setItemMeta(i7m); ItemStack i8 = new ItemStack(Material.DISPENSER); ItemMeta i8m = i8.getItemMeta(); i8m.setDisplayName(ChatColor.AQUA + "Turrets"); ArrayList<String> i8l = new ArrayList<String>(); i8l.add(ChatColor.LIGHT_PURPLE + "Click to open turrets shop. Build"); i8l.add(ChatColor.LIGHT_PURPLE + "turrets with resource points"); i8m.setLore(i8l); i8.setItemMeta(i8m); ItemStack i9 = new ItemStack(Material.OBSIDIAN); ItemMeta i9m = i9.getItemMeta(); i9m.setDisplayName(ChatColor.AQUA + "Survivability"); ArrayList<String> i9l = new ArrayList<String>(); i9l.add(ChatColor.LIGHT_PURPLE + "Click to open Survivability shop."); i9l.add(ChatColor.LIGHT_PURPLE + "Contains upgrades to improve the"); i9l.add(ChatColor.LIGHT_PURPLE + "survivability of your kingdom"); i9m.setLore(i9l); i9.setItemMeta(i9m); ItemStack i10 = new ItemStack(Material.BEACON); ItemMeta i10m = i10.getItemMeta(); i10m.setDisplayName(ChatColor.AQUA + "Structures"); ArrayList<String> i10l = new ArrayList<String>(); i10l.add(ChatColor.LIGHT_PURPLE + "Click to open Structures shop."); i10l.add(ChatColor.LIGHT_PURPLE + "Structures have different functions"); i10m.setLore(i10l); i10.setItemMeta(i10m); ItemStack chest = new ItemStack(Material.CHEST); ItemMeta chestm = chest.getItemMeta(); chestm.setDisplayName(ChatColor.AQUA + "Kingdom Chest"); ArrayList<String> chestl = new ArrayList<String>(); chestl.add(ChatColor.GREEN + "A kingdom chest to store items! Space can be upgraded."); chestl.add(ChatColor.LIGHT_PURPLE + "Click to open Kingdom Chest"); chestm.setLore(chestl); chest.setItemMeta(chestm); ItemStack r = new ItemStack(Material.HAY_BLOCK); ItemMeta rm = r.getItemMeta(); rm.setDisplayName(ChatColor.AQUA + "Resource Points"); ArrayList<String> rl = new ArrayList<String>(); rl.add(ChatColor.GREEN + "Your kingdom currently has"); rl.add(ChatColor.DARK_AQUA + "" + plugin.rpm.getRp(plugin.getKingdom(p)) + ChatColor.GREEN + " Resource Points"); rm.setLore(rl); r.setItemMeta(rm); nexusgui.setItem(0, i1); nexusgui.setItem(9, i2); nexusgui.setItem(10, i3); nexusgui.setItem(11, i4); nexusgui.setItem(12, i7); nexusgui.setItem(13, i10); nexusgui.setItem(20, i8); nexusgui.setItem(18, i5); nexusgui.setItem(19, i6); nexusgui.setItem(17, r); nexusgui.setItem(26, chest); p.openInventory(nexusgui); } public void openStructureShop(Player p){ champions = Bukkit.createInventory(null, 27, ChatColor.AQUA + "Structure Shop"); ItemStack i1 = new ItemStack(Material.MAGMA_CREAM); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Power Cell"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Chunks next to the chunk with a power cell"); i1l.add(ChatColor.GREEN + "cannot be invaded without invading the power"); i1l.add(ChatColor.GREEN + "cell first. Does not work on other power cell land"); i1l.add(ChatColor.RED+ "Cost: 50 resource points"); i1l.add(ChatColor.RED+ "Can't be placed on power cell chunks"); i1l.add(ChatColor.LIGHT_PURPLE + "Placable Structure"); i1m.setLore(i1l); i1.setItemMeta(i1m); ItemStack i2 = new ItemStack(Material.WHEAT); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Mystic Harvester"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "A block that creates resource points"); i2l.add(ChatColor.GREEN + "from nearby growing wheat. Stops functioning"); i2l.add(ChatColor.GREEN + "when the wheat nearby is fully grown."); i2l.add(ChatColor.GREEN + "Only wheat around it in a one block"); i2l.add(ChatColor.GREEN + "radius will allow resource point harvesting"); i2l.add(ChatColor.RED+ "Cost: 50 resource points"); i2l.add(ChatColor.RED+ "Must be placed on nexus chunks"); i2l.add(ChatColor.LIGHT_PURPLE + "Placable Structure"); i2m.setLore(i2l); i2.setItemMeta(i2m); ItemStack r = new ItemStack(Material.HAY_BLOCK); ItemMeta rm = r.getItemMeta(); rm.setDisplayName(ChatColor.AQUA + "Resource Points"); ArrayList<String> rl = new ArrayList<String>(); rl.add(ChatColor.GREEN + "Your kingdom currently has"); rl.add(ChatColor.DARK_AQUA + "" + plugin.rpm.getRp(plugin.getKingdom(p)) + ChatColor.GREEN + " Resource Points"); rm.setLore(rl); r.setItemMeta(rm); ItemStack backbtn = new ItemStack(Material.REDSTONE_BLOCK); ItemMeta backbtnmeta = backbtn.getItemMeta(); backbtnmeta.setDisplayName(ChatColor.RED + "Return to main menu"); backbtn.setItemMeta(backbtnmeta); champions.setItem(17, r); champions.setItem(26, backbtn); champions.addItem(i1); p.openInventory(champions); } public void openSurvivabilityShop(Player p){ champions = Bukkit.createInventory(null, 27, ChatColor.AQUA + "Survivability Shop"); ItemStack i1 = new ItemStack(Material.BED); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Belonging"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Be able to use your kingdom home, even if"); i1l.add(ChatColor.GREEN + "your home's land is no longer your land."); i1l.add(ChatColor.RED + "Cost: 100 resource points"); i1l.add(ChatColor.LIGHT_PURPLE + "Survivability Upgrade"); i1m.setLore(i1l); i1.setItemMeta(i1m); ItemStack i2 = new ItemStack(Material.MAGMA_CREAM); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Nexus Tower"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "Converts the nexus into a powerful"); i2l.add(ChatColor.GREEN + "area turret. Strikes nearby targets"); i2l.add(ChatColor.GREEN + "with the power of lightning"); i2l.add(ChatColor.RED+ "Cost: 100 resource points"); i2l.add(ChatColor.LIGHT_PURPLE + "Survivability Upgrade"); i2m.setLore(i2l); i2.setItemMeta(i2m); ItemStack i3 = new ItemStack(Material.EYE_OF_ENDER); ItemMeta i3m = i3.getItemMeta(); i3m.setDisplayName(ChatColor.AQUA + "Detector"); ArrayList<String> i3l = new ArrayList<String>(); i3l.add(ChatColor.GREEN + "Invisibility users in the nexus"); i3l.add(ChatColor.GREEN + "chunk will have their invisibility"); i3l.add(ChatColor.GREEN + "removed."); i3l.add(ChatColor.RED + "Cost: 100 resource points"); i3l.add(ChatColor.LIGHT_PURPLE + "Survivability Upgrade"); i3m.setLore(i3l); i3.setItemMeta(i3m); ItemStack r = new ItemStack(Material.HAY_BLOCK); ItemMeta rm = r.getItemMeta(); rm.setDisplayName(ChatColor.AQUA + "Resource Points"); ArrayList<String> rl = new ArrayList<String>(); rl.add(ChatColor.GREEN + "Your kingdom currently has"); rl.add(ChatColor.DARK_AQUA + "" + plugin.rpm.getRp(plugin.getKingdom(p)) + ChatColor.GREEN + " Resource Points"); rm.setLore(rl); r.setItemMeta(rm); ItemStack backbtn = new ItemStack(Material.REDSTONE_BLOCK); ItemMeta backbtnmeta = backbtn.getItemMeta(); backbtnmeta.setDisplayName(ChatColor.RED + "Return to main menu"); backbtn.setItemMeta(backbtnmeta); champions.addItem(i1); champions.setItem(15, r); champions.setItem(26, backbtn); p.openInventory(champions); } public void openTurretShop(Player p){ champions = Bukkit.createInventory(null, 27, ChatColor.AQUA + "Turret Shop"); ItemStack i1 = new ItemStack(Material.BOW); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Arrow Turret"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Rapidly fires at anything other than"); i1l.add(ChatColor.GREEN + "kingdom members. One target at a time."); i1l.add(ChatColor.BLUE + "Range: 5 blocks"); i1l.add(ChatColor.BLUE + "Damage: 4 hearts/shot"); i1l.add(ChatColor.BLUE + "Attack Speed: 1/sec"); i1l.add(ChatColor.BLUE + "Targets: One random target in range"); i1l.add(ChatColor.RED + "Cost: 100 resource points"); i1l.add(ChatColor.LIGHT_PURPLE + "Turret"); i1m.setLore(i1l); i1.setItemMeta(i1m); ItemStack i2 = new ItemStack(Material.BEACON); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Nexus Tower"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "Zaps all enemies in range with the"); i2l.add(ChatColor.GREEN + "power of lightning"); i2l.add(ChatColor.RED+ "Can only be placed in the nexus chunk"); i2l.add(ChatColor.BLUE + "Range: 5 blocks"); i2l.add(ChatColor.BLUE + "Damage: 2 hearts/shot"); i2l.add(ChatColor.BLUE + "Attack Speed: 1/sec"); i2l.add(ChatColor.BLUE + "Targets: All targets in range"); i2l.add(ChatColor.RED + "Cost: 300 resource points"); i2l.add(ChatColor.LIGHT_PURPLE + "Turret"); i2m.setLore(i2l); i2.setItemMeta(i2m); ItemStack i3 = new ItemStack(Material.FIREBALL); ItemMeta i3m = i3.getItemMeta(); i3m.setDisplayName(ChatColor.AQUA + "Flame Turret"); ArrayList<String> i3l = new ArrayList<String>(); i3l.add(ChatColor.GREEN + "Fast-firing turret that sets targets on"); i3l.add(ChatColor.GREEN + "fire"); i3l.add(ChatColor.GREEN + "Works best on a flat space"); i3l.add(ChatColor.BLUE + "Range: 5 blocks"); i3l.add(ChatColor.BLUE + "Damage: 2 hearts/shot"); i3l.add(ChatColor.BLUE + "Attack Speed: 2/sec"); i3l.add(ChatColor.BLUE + "Targets: One random target in range"); i3l.add(ChatColor.RED + "Cost: 150 resource points"); i3l.add(ChatColor.LIGHT_PURPLE + "Turret"); i3m.setLore(i3l); i3.setItemMeta(i3m); ItemStack i4 = new ItemStack(Material.TNT); ItemMeta i4m = i4.getItemMeta(); i4m.setDisplayName(ChatColor.AQUA + "Pressure Mine"); ArrayList<String> i4l = new ArrayList<String>(); i4l.add(ChatColor.GREEN + "A placable pressure plate, when stepped"); i4l.add(ChatColor.GREEN + "on by non-allies, will explode, dealing "); i4l.add(ChatColor.GREEN + "damage. Does not damage blocks"); i4l.add(ChatColor.BLUE + "Range: 3 blocks"); i4l.add(ChatColor.BLUE + "Damage: 4 hearts"); i4l.add(ChatColor.BLUE + "Attack Speed: one use"); i4l.add(ChatColor.BLUE + "Targets: All targets in blast range"); i4l.add(ChatColor.RED + "Cost: 10 resource points"); i4l.add(ChatColor.LIGHT_PURPLE + "Turret"); i4m.setLore(i4l); i4.setItemMeta(i4m); champions.addItem(i1); champions.addItem(i3); champions.addItem(i4); p.openInventory(champions); } public void openChampionMenu(Player p){ champions = Bukkit.createInventory(null, 27, ChatColor.AQUA + plugin.getKingdom(p) + "'s Champion"); ItemStack i1 = new ItemStack(Material.DIAMOND_SWORD); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Champion Weapon"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "Provides your champion with a better weapon"); i1l.add(ChatColor.GREEN + "each upgrade. Max level is 4"); i1l.add(ChatColor.DARK_PURPLE + "Current Champion Weapon Level: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.weapon")); i1l.add(ChatColor.RED + "Cost: 10 resource points"); i1l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i1m.setLore(i1l); i1.setItemMeta(i1m); ItemStack i2 = new ItemStack(Material.DIAMOND_CHESTPLATE); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Champion Health"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "Each upgrade increases champion health"); i2l.add(ChatColor.GREEN + "by 2"); i2l.add(ChatColor.DARK_PURPLE + "Current Champion Health: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.health")); i2l.add(ChatColor.RED + "Cost: 2 resource points"); i2l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i2m.setLore(i2l); i2.setItemMeta(i2m); ItemStack i3 = new ItemStack(Material.BRICK); ItemMeta i3m = i3.getItemMeta(); i3m.setDisplayName(ChatColor.AQUA + "Champion Resistance"); ArrayList<String> i3l = new ArrayList<String>(); i3l.add(ChatColor.GREEN + "Increase Champion's resistance, with a"); i3l.add(ChatColor.GREEN + "chance to prevent knockback. 20% each"); i3l.add(ChatColor.GREEN + "upgrade. Max: 100%"); i3l.add(ChatColor.RED + "Current Resistance: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.resist") + "%"); i3l.add(ChatColor.RED + "Cost: 5 resource points"); i3l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i3m.setLore(i3l); i3.setItemMeta(i3m); ItemStack i4 = new ItemStack(Material.QUARTZ); ItemMeta i4m = i4.getItemMeta(); i4m.setDisplayName(ChatColor.AQUA + "Champion Speed"); ArrayList<String> i4l = new ArrayList<String>(); i4l.add(ChatColor.GREEN + "Increases Champion Speed. 30% more"); i4l.add(ChatColor.GREEN + "per upgrade. Max level is 3."); i4l.add(ChatColor.RED + "Current Champion Speed Level: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.speed")); i4l.add(ChatColor.RED + "Cost: 20 resource points"); i4l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i4m.setLore(i4l); i4.setItemMeta(i4m); ItemStack i5 = new ItemStack(Material.ENDER_PEARL); ItemMeta i5m = i5.getItemMeta(); i5m.setDisplayName(ChatColor.AQUA + "Drag"); ArrayList<String> i5l = new ArrayList<String>(); i5l.add(ChatColor.GREEN + "When the player is more than 5 blocks"); i5l.add(ChatColor.GREEN + "away, the champion pulls the player"); i5l.add(ChatColor.GREEN + "to the champion's location."); i5l.add(ChatColor.RED + "Enabled: " + (plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.drag") > 0)); i5l.add(ChatColor.RED + "Cost: 30 resource points"); i5l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i5m.setLore(i5l); i5.setItemMeta(i5m); ItemStack i6 = new ItemStack(Material.FEATHER); ItemMeta i6m = i6.getItemMeta(); i6m.setDisplayName(ChatColor.AQUA + "Mock"); ArrayList<String> i6l = new ArrayList<String>(); i6l.add(ChatColor.GREEN + "While dueling the champion, the invader"); i6l.add(ChatColor.GREEN + "cannot place or break blocks in a range"); i6l.add(ChatColor.GREEN + "of the champion."); i6l.add(ChatColor.RED + "Current Mock Range: " + plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.mock") + " blocks"); i6l.add(ChatColor.RED + "Cost: 10 resource points"); i6l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i6m.setLore(i6l); i6.setItemMeta(i6m); ItemStack i7 = new ItemStack(Material.GOLD_SWORD); ItemMeta i7m = i7.getItemMeta(); i7m.setDisplayName(ChatColor.AQUA + "Death Duel"); ArrayList<String> i7l = new ArrayList<String>(); i7l.add(ChatColor.GREEN + "Only the invader can damage the champion"); i7l.add(ChatColor.GREEN + "and the champion will only savagely"); i7l.add(ChatColor.GREEN + "target the invader"); i7l.add(ChatColor.RED + "Enabled: " + (plugin.kingdoms.getInt(plugin.getKingdom(p) + ".champion.duel") > 0)); i7l.add(ChatColor.RED + "Cost: 100 resource points"); i7l.add(ChatColor.LIGHT_PURPLE + "Champion Upgrade"); i7m.setLore(i7l); i7.setItemMeta(i7m); ItemStack r = new ItemStack(Material.HAY_BLOCK); ItemMeta rm = r.getItemMeta(); rm.setDisplayName(ChatColor.AQUA + "Resource Points"); ArrayList<String> rl = new ArrayList<String>(); rl.add(ChatColor.GREEN + "Your kingdom currently has"); rl.add(ChatColor.DARK_AQUA + "" + plugin.rpm.getRp(plugin.getKingdom(p)) + ChatColor.GREEN + " Resource Points"); rm.setLore(rl); r.setItemMeta(rm); ItemStack backbtn = new ItemStack(Material.REDSTONE_BLOCK); ItemMeta backbtnmeta = backbtn.getItemMeta(); backbtnmeta.setDisplayName(ChatColor.RED + "Return to main menu"); backbtn.setItemMeta(backbtnmeta); champions.setItem(0, i1); champions.setItem(1, i2); champions.setItem(2, i3); champions.setItem(3, i4); champions.setItem(4, i5); champions.setItem(5, i6); champions.setItem(6, i7); champions.setItem(17, r); champions.setItem(26, backbtn); p.openInventory(champions); } public void openMisMenu(Player p){ champions = Bukkit.createInventory(null, 27, ChatColor.AQUA + "Extra Upgrades"); ItemStack i1 = new ItemStack(Material.SULPHUR); ItemMeta i1m = i1.getItemMeta(); i1m.setDisplayName(ChatColor.AQUA + "Anti-Creeper"); ArrayList<String> i1l = new ArrayList<String>(); i1l.add(ChatColor.GREEN + "When a creeper explodes in your "); i1l.add(ChatColor.GREEN + "territory, it will do no block damage"); i1l.add(ChatColor.GREEN + "or damage your members."); if(hasMisUpgrade(plugin.getKingdom(p), "anticreeper")){ i1l.add(ChatColor.DARK_PURPLE + "Enabled!"); }else{ i1l.add(ChatColor.RED + "Cost: 50 resource points"); } i1l.add(ChatColor.LIGHT_PURPLE + "Mis Upgrade"); i1m.setLore(i1l); i1.setItemMeta(i1m); ItemStack i2 = new ItemStack(Material.SEEDS); ItemMeta i2m = i2.getItemMeta(); i2m.setDisplayName(ChatColor.AQUA + "Anti-Trample"); ArrayList<String> i2l = new ArrayList<String>(); i2l.add(ChatColor.GREEN + "Your farms can't be trampled"); i2l.add(ChatColor.GREEN + "by mobs or players."); if(hasMisUpgrade(plugin.getKingdom(p), "antitrample")){ i2l.add(ChatColor.DARK_PURPLE + "Enabled!"); }else{ i2l.add(ChatColor.RED + "Cost: 10 resource points"); } i2l.add(ChatColor.LIGHT_PURPLE + "Mis Upgrade"); i2m.setLore(i2l); i2.setItemMeta(i2m); ItemStack i3 = new ItemStack(Material.IRON_AXE); ItemMeta i3m = i3.getItemMeta(); i3m.setDisplayName(ChatColor.AQUA + "Nexus Guard"); ArrayList<String> i3l = new ArrayList<String>(); i3l.add(ChatColor.GREEN + "When an enemy mines your nexus,"); i3l.add(ChatColor.GREEN + "a nexus guard will spawn to try"); i3l.add(ChatColor.GREEN + "and defend it. Nexus guards"); i3l.add(ChatColor.GREEN + "have 30 health and the weapon of"); i3l.add(ChatColor.GREEN + "your champion."); if(hasMisUpgrade(plugin.getKingdom(p), "nexusguard")){ i3l.add(ChatColor.DARK_PURPLE + "Enabled!"); }else{ i3l.add(ChatColor.RED + "Cost: 100 resource points"); } i3l.add(ChatColor.LIGHT_PURPLE + "Mis Upgrade"); i3m.setLore(i3l); i3.setItemMeta(i3m); ItemStack i4 = new ItemStack(Material.NETHER_STAR); ItemMeta i4m = i4.getItemMeta(); i4m.setDisplayName(ChatColor.AQUA + "Glory"); ArrayList<String> i4l = new ArrayList<String>(); i4l.add(ChatColor.GREEN + "When you kill something in your"); i4l.add(ChatColor.GREEN + "land, gain three times the xp"); i4l.add(ChatColor.GREEN + "from the mob."); if(hasMisUpgrade(plugin.getKingdom(p), "glory")){ i4l.add(ChatColor.DARK_PURPLE + "Enabled!"); }else{ i4l.add(ChatColor.RED + "Cost: 60 resource points"); } i4l.add(ChatColor.LIGHT_PURPLE + "Mis Upgrade"); i4m.setLore(i4l); i4.setItemMeta(i4m); ItemStack i5 = new ItemStack(Material.TNT); ItemMeta i5m = i5.getItemMeta(); i5m.setDisplayName(ChatColor.AQUA + "Bomb Expertise"); ArrayList<String> i5l = new ArrayList<String>(); i5l.add(ChatColor.GREEN + "When an explosion goes off in your"); i5l.add(ChatColor.GREEN + "land, the blocks regenerate after"); i5l.add(ChatColor.GREEN + "some time. In the explosion,"); i5l.add(ChatColor.GREEN + "nearby non-members are smited."); if(hasMisUpgrade(plugin.getKingdom(p), "bombshards")){ i5l.add(ChatColor.DARK_PURPLE + "Enabled!"); }else{ i5l.add(ChatColor.RED + "Cost: 100 resource points"); } i5l.add(ChatColor.LIGHT_PURPLE + "Mis Upgrade"); i5m.setLore(i5l); i5.setItemMeta(i5m); ItemStack r = new ItemStack(Material.HAY_BLOCK); ItemMeta rm = r.getItemMeta(); rm.setDisplayName(ChatColor.AQUA + "Resource Points"); ArrayList<String> rl = new ArrayList<String>(); rl.add(ChatColor.GREEN + "Your kingdom currently has"); rl.add(ChatColor.DARK_AQUA + "" + plugin.rpm.getRp(plugin.getKingdom(p)) + ChatColor.GREEN + " Resource Points"); rm.setLore(rl); r.setItemMeta(rm); ItemStack backbtn = new ItemStack(Material.REDSTONE_BLOCK); ItemMeta backbtnmeta = backbtn.getItemMeta(); backbtnmeta.setDisplayName(ChatColor.RED + "Return to main menu"); backbtn.setItemMeta(backbtnmeta); champions.setItem(0, i1); champions.setItem(1, i2); champions.setItem(2, i3); champions.setItem(3, i4); champions.setItem(4, i5); champions.setItem(17, r); champions.setItem(26, backbtn); p.openInventory(champions); } public boolean hasMisUpgrade(String kingdom, String upgrade){ boolean boo = plugin.misupgrades.getBoolean(kingdom + "." + upgrade); return boo; } public void upgradeMis(Player p, String upgrade){ int cost = 0; String kingdom = plugin.getKingdom(p); if(plugin.isKing(p) || plugin.isMod(plugin.getKingdom(p), p)){ if(!hasMisUpgrade(kingdom, upgrade)){ if(upgrade.equalsIgnoreCase("anticreeper")){ cost = 50; if(plugin.rpm.hasAmtRp(kingdom, cost)){ plugin.rpm.minusRP(kingdom, cost); plugin.misupgrades.set(kingdom + "." + upgrade, true); plugin.saveMisupgrades(); p.sendMessage(ChatColor.GREEN + "Anti-Creeper upgrade acquired!"); p.closeInventory(); openMisMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points."); } }else if(upgrade.equalsIgnoreCase("antitrample")){ cost = 10; if(plugin.rpm.hasAmtRp(kingdom, cost)){ plugin.rpm.minusRP(kingdom, cost); plugin.misupgrades.set(kingdom + "." + upgrade, true); plugin.saveMisupgrades(); p.sendMessage(ChatColor.GREEN + "Anti-Trample upgrade acquired!"); p.closeInventory(); openMisMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points."); } }else if(upgrade.equalsIgnoreCase("nexusguard")){ cost = 100; if(plugin.rpm.hasAmtRp(kingdom, cost)){ plugin.rpm.minusRP(kingdom, cost); plugin.misupgrades.set(kingdom + "." + upgrade, true); plugin.saveMisupgrades(); p.sendMessage(ChatColor.GREEN + "Nexus Guard upgrade acquired!"); p.closeInventory(); openMisMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points."); } }else if(upgrade.equalsIgnoreCase("glory")){ cost = 60; if(plugin.rpm.hasAmtRp(kingdom, cost)){ plugin.rpm.minusRP(kingdom, cost); plugin.misupgrades.set(kingdom + "." + upgrade, true); plugin.saveMisupgrades(); p.sendMessage(ChatColor.GREEN + "Glory upgrade acquired!"); p.closeInventory(); openMisMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points."); } }else if(upgrade.equalsIgnoreCase("bombshards")){ cost = 100; if(plugin.rpm.hasAmtRp(kingdom, cost)){ plugin.rpm.minusRP(kingdom, cost); plugin.misupgrades.set(kingdom + "." + upgrade, true); plugin.saveMisupgrades(); p.sendMessage(ChatColor.GREEN + "Bomb Expertise upgrade acquired!"); p.closeInventory(); openMisMenu(p); }else{ p.sendMessage(ChatColor.RED + "You don't have enough resource points."); } } }else{ p.sendMessage(ChatColor.RED + "This upgrade is already enabled!"); } } } public void openKingdomChest(Player p){ if(plugin.hasKingdom(p)){ int chestlevel = plugin.kingdoms.getInt(plugin.getKingdom(p) + ".chestsize"); this.kchest = Bukkit.createInventory(null, chestlevel, ChatColor.AQUA + "Kingdom Chest"); if(plugin.chest.getList(plugin.getKingdom(p)) == null){ plugin.chest.set(plugin.getKingdom(p), new ArrayList<String>()); plugin.saveChests(); } for(Object obj : plugin.chest.getList(plugin.getKingdom(p))){ if(obj instanceof ItemStack){ kchest.addItem((ItemStack) obj); } } p.closeInventory(); p.openInventory(kchest); } } }
true
1550ae7c41a09cd81610873ff30b5325dd682fd2
Java
ymhelloword/nyg
/src/main/java/com/nyg/ssm/entity/OrderMaster.java
UTF-8
721
1.640625
2
[]
no_license
package com.nyg.ssm.entity; import java.util.Date; public class OrderMaster { private int orderId; private int orderSn; private int customerId; private String shippingUser; private int province; private int city; private int district; private String address; private int paymentMethod; private double orderMoney; private double districtMoney; private double shippingMoney; private double paymentMoney; private String shippingCompName; private String shippingSn; private Date createTime; private Date shippingTime; private Date payTime; private Date receiveTime; private Date orderStatus; private Date orderPoint; private String invoiceTime; private Date modifiedTime; }
true
a5ff557f921b1e02d18a3642f86fe63caabb7096
Java
tommwq/jet
/src/main/java/com/tommwq/jet/database/SQLiteDataTypeTranslator.java
UTF-8
1,731
2.703125
3
[]
no_license
package com.tommwq.jet.database; import java.util.HashMap; import java.util.Map; public class SQLiteDataTypeTranslator implements SqlDataTypeTranslator { private static final Map<String, Class> dataTypeTable = new HashMap<>(); private static final Map<Class, String> javaTypeTable = new HashMap<>(); static { dataTypeTable.put("BLOB", Object.class); dataTypeTable.put("TEXT", String.class); dataTypeTable.put("REAL", Double.class); dataTypeTable.put("INTEGER", Long.class); } static { javaTypeTable.put(Boolean.class, "INTEGER"); javaTypeTable.put(Byte.class, "INTEGER"); javaTypeTable.put(Character.class, "INTEGER"); javaTypeTable.put(Double.class, "REAL"); javaTypeTable.put(Float.class, "REAL"); javaTypeTable.put(Integer.class, "INTEGER"); javaTypeTable.put(Long.class, "INTEGER"); javaTypeTable.put(Short.class, "INTEGER"); javaTypeTable.put(String.class, "TEXT"); javaTypeTable.put(boolean.class, "INTEGER"); javaTypeTable.put(byte.class, "INTEGER"); javaTypeTable.put(char.class, "INTEGER"); javaTypeTable.put(double.class, "REAL"); javaTypeTable.put(float.class, "REAL"); javaTypeTable.put(int.class, "INTEGER"); javaTypeTable.put(long.class, "INTEGER"); javaTypeTable.put(short.class, "INTEGER"); } @Override public Class toJavaType(String dataType) { if (dataTypeTable.containsKey(dataType)) { return dataTypeTable.get(dataType); } return Object.class; } public String toSqlType(Class clazz) { Class type = clazz; if (clazz.isEnum()) { type = int.class; } if (javaTypeTable.containsKey(type)) { return javaTypeTable.get(type); } return "BLOB"; } }
true
f2016c328eed2132e6a8a62951fbe4eb93d05eda
Java
tracyhenryduck2/SerialPortApp
/seriallibrary/src/main/java/com/siterwell/seriallibrary/usbserial/Modbus/ModbusService.java
UTF-8
9,292
2.328125
2
[]
no_license
package com.siterwell.seriallibrary.usbserial.Modbus; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; import com.siterwell.seriallibrary.usbserial.driver.UsbSerialDriver; import com.siterwell.seriallibrary.usbserial.event.InitSerialEvent; import com.siterwell.seriallibrary.usbserial.event.PacketEndEvent; import com.siterwell.seriallibrary.usbserial.event.SerialReceiveEvent; import com.siterwell.seriallibrary.usbserial.event.SerialSendEvent; import com.siterwell.seriallibrary.usbserial.util.HexDump; import com.siterwell.seriallibrary.usbserial.util.SerialInputOutputManager; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.io.IOException; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by TracyHenry on 2018/1/9. */ public class ModbusService extends Service implements SerialInputOutputManager.Listener{ private static ArrayList<Byte> receive_data; private Timer timer; private MyTimerTask myTimerTask; private Timer timer_read; private ModbusReadTimerTask modbusReadTimerTask; private final String TAG = ModbusService.class.getName(); private final ExecutorService mExecutor = Executors.newSingleThreadExecutor(); private SerialInputOutputManager mSerialIoManager; private int count; //用来做接收数据的分包标识 private int count_data; //用来做分包发送线圈和寄存器命令; private AtomicBoolean flag_timer; private final int MaX_INTERVAL = 100; //最大时间间隔为500ms 表示500ms没收到数据则认为缓冲数据为一个完整的包 @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); flag_timer = new AtomicBoolean(false); receive_data = new ArrayList<Byte>(); timer = new Timer(); timer_read=new Timer(); myTimerTask = new MyTimerTask(); modbusReadTimerTask = new ModbusReadTimerTask(); timer.schedule(myTimerTask,0l,1l); timer_read.schedule(modbusReadTimerTask,20000l,20000l); } @Override public int onStartCommand(Intent intent, int flags, int startId) { EventBus.getDefault().register(this); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); receive_data= null; EventBus.getDefault().unregister(this); stopIoManager(); if(timer!=null){ timer.cancel(); timer = null; } if(myTimerTask!=null){ myTimerTask = null; } if(handler!=null){ handler.removeCallbacks(null); } } @Override public void onNewData(byte[] data) { synchronized (data){ Log.i(TAG,"收到的数据为:"+ HexDump.dumpHexString(data)); for(int i=0;i<data.length;i++){ Byte ds2 = new Byte(String.valueOf(data[i])); receive_data.add(ds2); } SerialReceiveEvent serialReceiveEvent = new SerialReceiveEvent(); serialReceiveEvent.setReceive_data(data); EventBus.getDefault().post(serialReceiveEvent); flag_timer.set(true); } } @Override public void onRunError(Exception e) { e.printStackTrace(); } private void stopIoManager() { if (mSerialIoManager != null) { Log.i(TAG, "Stopping io manager .."); mSerialIoManager.stop(); mSerialIoManager = null; } } private void startIoManager() { if (ModbusResolve.getInstance().sDriver != null) { Log.i(TAG, "Starting io manager .."); mSerialIoManager = new SerialInputOutputManager(ModbusResolve.getInstance().sDriver, this); mExecutor.submit(mSerialIoManager); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(InitSerialEvent event) { if (event.getUsbSerialDriver() == null) { Log.i(TAG,"No serial device."); } else { try { ModbusResolve.getInstance().sDriver = event.getUsbSerialDriver(); Log.d(TAG, "sDriver=" + ModbusResolve.getInstance().sDriver); ModbusResolve.getInstance().sDriver.open(); ModbusResolve.getInstance().sDriver.setParameters(9600, 8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE); } catch (IOException e) { Log.e(TAG, "Error setting up device: " + e.getMessage(), e); try { ModbusResolve.getInstance().sDriver.close(); } catch (IOException e2) { e2.printStackTrace(); } ModbusResolve.getInstance().sDriver = null; } Log.i(TAG,"Serial device: " + ModbusResolve.getInstance().sDriver.getClass().getSimpleName()); stopIoManager(); startIoManager(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(SerialSendEvent event) { byte[] ds = event.getContent(); if(mSerialIoManager!=null){ mSerialIoManager.writeAsync(ds); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(PacketEndEvent event) { Byte[] ds = (Byte[])receive_data.toArray(); byte ds2[] = new byte[ds.length]; for(int i=0;i<ds.length;i++){ ds2[i] = ds[i]; } Toast.makeText(this,"收到数据包:"+HexDump.toHexString(ds2),Toast.LENGTH_LONG).show(); receive_data.clear(); flag_timer.set(false); } private class MyTimerTask extends TimerTask{ @Override public void run() { if(flag_timer.get()){ count ++; if(count>=MaX_INTERVAL){ count = 0; handler.sendEmptyMessage(1); } } } } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: if(receive_data.size()>0){ byte ds2[] = new byte[receive_data.size()]; for(int i=0;i<receive_data.size();i++){ ds2[i] = receive_data.get(i).byteValue(); } Toast.makeText(ModbusService.this,"收到数据包:"+HexDump.toHexString(ds2),Toast.LENGTH_LONG).show(); receive_data.clear(); flag_timer.set(false); if(count_data%2==1){ ModbusErrcode modbusErrcode = ModbusResolve.getInstance().checkReceiveReadCoil(ds2); if(ModbusResolve.getInstance().getSendModbusCommand()!=null){ ModbusResolve.getInstance().getSendModbusCommand().ErrorReadCoil(modbusErrcode); } }else{ } } break; case 2: if(ModbusResolve.getInstance().listcoil!=null && ModbusResolve.getInstance().listcoil.size()>0){ byte[] data_coil = ModbusResolve.getInstance().sendReadcoil(ModbusResolve.DEVICE_ADDRESS,ModbusResolve.getInstance().listcoil.get(0).getAddress(),ModbusResolve.getInstance().listcoil.size()); SerialSendEvent serialSendEvent = new SerialSendEvent(); serialSendEvent.setContent(data_coil); EventBus.getDefault().post(serialSendEvent); } break; case 3: if(ModbusResolve.getInstance().listregister!=null && ModbusResolve.getInstance().listregister.size()>0) { byte[] data_register = ModbusResolve.getInstance().sendCommandOfReadRegister(ModbusResolve.DEVICE_ADDRESS, ModbusResolve.getInstance().listregister.get(0).getAddress(), ModbusResolve.getInstance().listregister.size()); SerialSendEvent serialSendEvent = new SerialSendEvent(); serialSendEvent.setContent(data_register); EventBus.getDefault().post(serialSendEvent); } break; } } }; private class ModbusReadTimerTask extends TimerTask{ @Override public void run() { count_data ++; if(count_data%2==1){ handler.sendEmptyMessage(2); }else{ handler.sendEmptyMessage(3); } } } }
true
022e188accb46856a69e590b4ecba18943cc7143
Java
Oceanysh/Demo
/src/Demo02If.java
UTF-8
351
3.09375
3
[]
no_license
public class Demo02If { public static void main(String[] args) { System.out.println("网吧"); int age=18; if(age>=18){ System.out.println("进入网吧"); System.out.println("打游戏"); System.out.println("打完回家"); } System.out.println("直接回家"); } }
true
d994a9a82cdfc7ff85bf714082699b8a76714a9d
Java
chou120/DaHan
/javaseThread/src/main/java/com/banyuan/club/implThread5/TestMyThread.java
UTF-8
508
2.875
3
[]
no_license
package com.banyuan.club.implThread5; /** * @author sanye * @version 1.0 * @date 2020/3/26 4:24 下午 */ public class TestMyThread { public static void main(String[] args) { MyThread myThread=new MyThread(); //只有一个对象 Thread t1=new Thread(myThread,"线程A"); Thread t2=new Thread(myThread,"线程B"); Thread t3=new Thread(myThread,"线程C"); Thread t4=new Thread(myThread,"线程D"); t1.start(); t2.start(); t3.start(); t4.start(); } }
true
d3726578af4b61afaa1a354ae8569b1e99f6da09
Java
bsreddy125/wissen-nexwave
/4-JPA/JPA-CRUD/src/main/java/com/Delete_Product.java
UTF-8
804
2.515625
3
[]
no_license
package com; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.model.Product; /* * * in JAP , we can select entities in 4 ways * * -> by primary key * -> by JPQL * -> by Criteria API * -> by Native SQL * */ public class Delete_Product { public static void main(String[] args) { // using JPA API // ---------------------------------------- EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Product product = em.find(Product.class, 111); em.remove(product); em.getTransaction().commit(); em.close(); emf.close(); // ---------------------------------------- } }
true
5c8b83d8dd9545edbf00dfd1c956d3ffb9a0271a
Java
deanwyns/Android
/app/src/main/java/hogent/hogentprojecteniii_groep10/models/Gebruiker.java
UTF-8
2,944
2.890625
3
[]
no_license
package hogent.hogentprojecteniii_groep10.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; /** * De klasse die een Gebruiker voorstelt in de applicatie. * Is Parcelable om doorgave mogelijk te maken tussen activities. */ public class Gebruiker implements Parcelable{ @SerializedName("email") private String emailadres; @SerializedName("password") private String password; @SerializedName("phone_number") private String telNr; @SerializedName("first_name_mother") private String naam; @SerializedName("last_name_mother") private String voornaam; public Gebruiker(String emailadres, String password, String telNr, String naam, String voornaam) { this.emailadres = emailadres; this.password = password; this.telNr = telNr; this.naam = naam; this.voornaam = voornaam; } public String getNaam() { return naam; } public String getVoornaam() { return voornaam; } public String getTelNr() { return telNr; } public String getEmailadres() { return emailadres; } public String getPassword() { return password; } @Override public String toString() { return this.voornaam + " " + this.naam; } /** * Constructor voor gebruiker die als parameter een parcel object meekrijgt * en die het parcel object uitleest om een gebruiker aan te maken * @param in de parcel die meegegeven wordt en die de gegevens van de gebruiker bevat */ protected Gebruiker(Parcel in) { emailadres = in.readString(); password = in.readString(); telNr = in.readString(); naam = in.readString(); voornaam = in.readString(); } /** * Nodig voor elke parcellable. In 99% van de gevallen is return 0 goed. * @return */ @Override public int describeContents() { return 0; } /** * Maakt het mogelijk om gebruiker in een parcel te steken * @param dest is de parcel waarin de gebruiker terechtkomt * @param flags */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(emailadres); dest.writeString(password); dest.writeString(telNr); dest.writeString(naam); dest.writeString(voornaam); } /** * Maakt het lezen van een gebruiker uit een parcel mogelijk * Gebruikt een constructor van gebruiker die als parameter een parcel object meekrijgt */ public static final Parcelable.Creator<Gebruiker> CREATOR = new Parcelable.Creator<Gebruiker>() { @Override public Gebruiker createFromParcel(Parcel in) { return new Gebruiker(in); } @Override public Gebruiker[] newArray(int size) { return new Gebruiker[size]; } }; }
true
48e2e41e58460384bc9bb9ab82d23eaf6f27bc88
Java
chhh/batmass
/GUI/src/umich/ms/batmass/gui/examples/actions/CookieBasedAction.java
UTF-8
2,749
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Dmitry Avtonomov. * * 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 umich.ms.batmass.gui.examples.actions; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.nodes.Node; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.util.NbBundle.Messages; import org.openide.util.actions.CookieAction; import umich.ms.datatypes.LCMSData; /** * * @author Dmitry Avtonomov */ //@ActionID( // category = "LCMSFileDesc/View", // id = "umich.ms.batmass.gui.lcmsfileactions.CookieBasedAction") //@ActionRegistration( // displayName = "#CTL_CookieBasedAction", //// iconBase = "umich/ms/batmass/gui/lcmsfileactions/view_chromatogram_icon.png", // lazy = false //) //@ActionReference( // path = "LCMSFileDesc/View", // position=200, // separatorBefore = 199, // separatorAfter = 201) @Messages("CTL_CookieBasedAction=Cookie based Action!") public class CookieBasedAction extends CookieAction { @Override protected int mode() { return CookieAction.MODE_EXACTLY_ONE; } @Override protected Class<?>[] cookieClasses() { return new Class<?>[]{LCMSData.class}; } @Override protected void performAction(Node[] activatedNodes) { String msg = "I'm the cookie action!"; NotifyDescriptor d = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(d); } @Override public String getName() { return NbBundle.getMessage(this.getClass(), "CTL_CookieBasedAction"); } @Override public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } @Override protected void initialize() { super.initialize(); // see org.openide.util.actions.SystemAction.iconResource() Javadoc for more details putValue("noIconInMenu", true); } @Override protected boolean asynchronous() { return false; } @Override protected String iconResource() { return "umich/ms/batmass/gui/lcmsfileactions/view_chromatogram_icon.png"; } // @Override // protected boolean enable(Node[] activatedNodes) { // // } }
true
366a330c38d606d98e42e8d4f98207c7872bdc6d
Java
MMMirka/palvelinohjelmointi
/src/main/java/MirkaM/TaskList/TaskListApplication.java
UTF-8
1,734
2.359375
2
[]
no_license
package MirkaM.TaskList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import MirkaM.TaskList.domain.Task; import MirkaM.TaskList.domain.TaskRepository; import MirkaM.TaskList.domain.Priority; import MirkaM.TaskList.domain.PriorityRepository; import MirkaM.TaskList.domain.User; import MirkaM.TaskList.domain.UserRepository; @SpringBootApplication public class TaskListApplication { private static final Logger log = LoggerFactory.getLogger(TaskListApplication.class); public static void main(String[] args) { SpringApplication.run(TaskListApplication.class, args); } @Bean public CommandLineRunner demo(TaskRepository repository, PriorityRepository prepository, UserRepository urepository) { return (args) -> { prepository.deleteAll(); prepository.save(new Priority("High")); prepository.save(new Priority("Medium")); prepository.save(new Priority("Low")); Task task1 = new Task ("Projektiraportti", urepository.findByUsername("admin"),"1.5.2021", prepository.findByName("Low").get(0)); repository.save(task1); urepository.deleteAll(); User user1 = new User("user", "$2a$06$3jYRJrg0ghaaypjZ/.g4SethoeA51ph3UD4kZi9oPkeMTpjKU5uo6", "USER", "sposti1"); User user2 = new User("admin", "$2a$10$0MMwY.IQqpsVc1jC8u7IJ.2rT8b0Cd3b3sfIBGV2zfgnPGtT4r0.C", "ADMIN","sposti2"); urepository.save(user1); urepository.save(user2); log.info("fetch all tasks"); for (Task task : repository.findAll()) { log.info(task.toString()); } }; } }
true
47ec60038a04a56483f041e02f5224c21ceb5c22
Java
tranric/Java-2018-stuff
/lab2 solution prog36859/src/lab2soln.java
UTF-8
5,713
3.65625
4
[]
no_license
import java.util.ArrayList; import java.util.Collections; public class lab2soln { public static void main(String args[]){ ArrayList<Integer> myList1 = new ArrayList<Integer>(); ArrayList<Integer> myList2 = new ArrayList<Integer>(); // ArrayList<String> myList1 = new ArrayList<String>(); // ArrayList<String> myList2 = new ArrayList<String>(); // ArrayList<String> myList3 = new ArrayList<String>(); // int listSize = 10; int listSize1 = (int)(Math.random()*15); int listSize2 = (int)(Math.random()*15); for(int i = 0; i < listSize1; i++){ myList1.add((int)(Math.random()*10)); } for(int i = 0; i < listSize2; i++){ myList2.add((int)(Math.random()*10)); } // myList1.add("Sheridan"); // myList1.add("College"); // myList2.add("Seneca"); // myList2.add("College"); // myList3.add("Hello"); // myList3.add("World!"); // //(Answer to i) System.out.println("Answer to (i)"); System.out.print("The List 1 = "); System.out.println(myList1); System.out.print("The List 2 = "); System.out.println(myList2); addLists(myList1, myList2); System.out.println(); //Answer to ii System.out.println("Answer to (ii)"); System.out.println("List 1 after removing common items: " + removeFromList(myList1, myList2)); System.out.println(); //Answer to iii System.out.println("Answer to (iii)"); ArrayList<Integer> countArray = countOccurrences(myList1, myList2); if (countArray.isEmpty()) System.out.println("The first list is empty."); else for (int i = 0; i<myList1.size(); i++){ System.out.println(myList1.get(i).toString() + " of the 1st list occurs " + countArray.get(i) + " times in the 2nd list"); } System.out.println(); //Answer to iv System.out.println("Answer to (iv)"); System.out.println("Merged sorted lists: " + mergeSortedLists(myList1, myList2)); System.out.println(); //Bonus System.out.println("The Bonus part "); Student s1 = new Student(22, "Bob", "Security"); Student s2 = new Student(20, "Jill", "Networking"); Student s3 = new Student (25, "Alice", "DB"); ArrayList<Student> allStudents = new ArrayList(){ {add(s1); add(s2); add(s3);}}; System.out.println(findMax(allStudents).getName() + " has the highest ID of: " + findMax(allStudents).getId()); // System.out.println(findMax(allStudents).getId()); // findMax(allStudents); } // Add one list to the end of other public static <E> void addLists (ArrayList<E> list1, ArrayList<E> list2){ ArrayList<E> tempList = new ArrayList<E>(); tempList = (ArrayList<E>)list1.clone(); for(E obj: list2){ tempList.add(obj); } System.out.println("Both lists together: " + tempList); } // Sort and merge two lists public static <E extends Comparable<E>> ArrayList<E> mergeSortedLists (ArrayList<E> list1, ArrayList<E> list2){ ArrayList<E> tempList1 = (ArrayList<E>)list1.clone(); ArrayList<E> tempList2 = (ArrayList<E>)list2.clone(); Collections.sort(tempList1); Collections.sort(tempList2); System.out.println("Sorted List1: " + tempList1); System.out.println("Sorted List2: " + tempList2); ArrayList<E> mergedSortedList = new ArrayList<E>(); int current1 = 0; // Current index in tempList1 int current2 = 0; // Current index in tempList2 while (current1 < tempList1.size() && current2 < tempList2.size()) { if (tempList1.get(current1).compareTo(tempList2.get(current2))< 0 ) mergedSortedList.add(tempList1.get(current1++)); else mergedSortedList.add(tempList2.get(current2++)); } while (current1 < tempList1.size()) mergedSortedList.add(tempList1.get(current1++)); while (current2 < tempList2.size()) mergedSortedList.add(tempList2.get(current2++)); return mergedSortedList; } // Remove common elements from the first list public static <E> ArrayList<E> removeFromList(ArrayList<E> list1, ArrayList<E> list2){ ArrayList<E> tempArray = (ArrayList<E>)list1.clone(); for(E object: list2){ if(tempArray.contains(object)) tempArray.remove(object); } return tempArray; } // Count the occurrence public static <E extends Comparable<E>> ArrayList<Integer> countOccurrences(ArrayList<E> list1, ArrayList<E> list2){ ArrayList<Integer> tempArray = new ArrayList<Integer>(); for(int i = 0; i < list1.size(); i++){ int count = 0; for(int j = 0; j < list2.size(); j++) if(list1.get(i).toString().equals(list2.get(j).toString())){ count++; } tempArray.add(count); } return tempArray; } public static <E extends Comparable<E>> E findMax (ArrayList<E> temp){ E max = temp.get(0); for (E s : temp){ if (max.compareTo(s) < 0) max = s; } return max; } // }
true
ca983050efdf2d6a4d5ef7c6f7a7079d3a4f045a
Java
StartZYP/Hero-Forge
/src/main/java/com/qq44920040/miecarft/hero/Heros/next/Shooter.java
UTF-8
2,862
2.3125
2
[]
no_license
/* * Decompiled with CFR 0.138. * * Could not load the following classes: * org.bukkit.Location * org.bukkit.entity.Arrow * org.bukkit.entity.Player * org.bukkit.entity.Projectile * org.bukkit.util.Vector */ package com.qq44920040.miecarft.hero.Heros.next; import java.util.Map; import java.util.UUID; import com.qq44920040.miecarft.hero.util.Util; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Arrow; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import com.qq44920040.miecarft.hero.Data; import com.qq44920040.miecarft.hero.Heros.Event.ShooterEvent; import com.qq44920040.miecarft.hero.Heros.Hero; public class Shooter extends Hero { private static final PotionEffect JUMP_EFFECT; private static final PotionEffect SPEED_EFFECT; private static final PotionEffect NIGHT_VISION; public Shooter() { super(HeroType.SHOOTER, Data.shooter_title); this.addSkill("crit", Data.shooter_crit_maybe, (long)Data.shooter_crit_wait); this.addSkill("arrows", Data.shooter_arrows_maybe, (long)Data.shooter_arrows_wait); } public double Skill_crit(Player player, double damage) { if (this.isUseSkill("crit", player)) { player.sendMessage(Data.title + Data.shooter_crit); return damage * 2.0D; } else { return damage; } } public void Skill_arrows(Player player, double damage) { if (this.isUseSkill("arrows", player)) { player.addPotionEffect(JUMP_EFFECT); player.addPotionEffect(SPEED_EFFECT); player.addPotionEffect(NIGHT_VISION); int number = (int)(Math.random() * 10.0D) + 5; for(int i = 0; i < number; ++i) { Arrow arrow = player.launchProjectile(Arrow.class); Vector vector = player.getLocation().getDirection().multiply(5); vector.setX(vector.getX() + Math.random() * 4.0D - Math.random() * 4.0D); vector.setY(vector.getY() + Math.random() * 2.0D - Math.random() * 1.0D); vector.setZ(vector.getZ() + Math.random() * 4.0D - Math.random() * 4.0D); arrow.setVelocity(vector); ShooterEvent.map.put(arrow.getUniqueId(), damage); } Util.particleCreate(player.getLocation(), 4.0D, Effect.valueOf("INSTANT_SPELL")); player.sendMessage(Data.title + Data.shooter_arrows); } } static { JUMP_EFFECT = new PotionEffect(PotionEffectType.JUMP, 2147483647, 2); SPEED_EFFECT = new PotionEffect(PotionEffectType.SPEED, 2147483647, 3); NIGHT_VISION = new PotionEffect(PotionEffectType.NIGHT_VISION, 2147483647, 1); } }
true
db194f73bc31cee4f0e057daa619ec1461aafa1a
Java
Archatom/FRC-Java
/src/main/java/frc/robot/subsystems/AirCompressor.java
UTF-8
1,305
2.125
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants.PortID; public class AirCompressor extends SubsystemBase { private Compressor air_compressor; private Solenoid s1; private boolean Triggered; public AirCompressor() { air_compressor = new Compressor(); s1 = new Solenoid(PortID.compressor_port.value); Triggered = false; air_compressor.start(); } @Override public void periodic() { // This method will be called once per scheduler run s1.set(Triggered); } public void Control_Update() { Triggered = !Triggered; } public void CompressStop() { Triggered = false; s1.set(false); } }
true
c1e3c121c0f2869487f4606b55f8700152118e4e
Java
bewasp/MedicineProject
/MedicineProject/BackendSpring/src/main/java/pl/edu/pwsztar/controller/AcceptCureApiController.java
UTF-8
1,600
2.109375
2
[]
no_license
package pl.edu.pwsztar.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import pl.edu.pwsztar.domain.dto.ResponseDto; import pl.edu.pwsztar.domain.dto.cure.ClientInfo; import pl.edu.pwsztar.domain.dto.cure.CureDto; import pl.edu.pwsztar.service.AcceptingDoseService; @Controller @RequestMapping(value = "/api/accept") public class AcceptCureApiController { private final AcceptingDoseService acceptingDoseService; @Autowired public AcceptCureApiController(AcceptingDoseService acceptingDoseService){ this.acceptingDoseService=acceptingDoseService; } @CrossOrigin @PostMapping(value = "/{userId}/apply-accept", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<ResponseDto<Void>> accepting(@PathVariable Long userId, @RequestBody CureDto cure) { ResponseDto<Void> result; result = acceptingDoseService.acceptingCure(userId, cure); return new ResponseEntity<>(result , HttpStatus.CREATED); } @CrossOrigin @GetMapping(value = "/{userId}/get-stats", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<ClientInfo> stats(@PathVariable Long userId) { ClientInfo result = null; result = acceptingDoseService.makeStats(userId); return new ResponseEntity<>(result , HttpStatus.CREATED); } }
true
2781fb3128e1ba62f1a244768abfbc69888640fe
Java
dujiajia1995/study_java
/src/main/java/study/designpattern/builderpattern/ordered/FatPersonBuildImpl.java
UTF-8
645
2.921875
3
[ "Apache-2.0" ]
permissive
package study.designpattern.builderpattern.ordered; /** * @Author 杜佳佳 * @Date 2021/5/18-10:50 * @@Version 1.0 */ public class FatPersonBuildImpl implements PersonBuilder { @Override public void drawHead() { System.out.println("小头"); } @Override public void drawNeck() { System.out.println("大粗脖子"); } @Override public void drawBody() { System.out.println("大胖身体"); } @Override public void drawArm() { System.out.println("大胖胳膊"); } @Override public void drawLeg() { System.out.println("大胖腿"); } }
true
e333dc3c421ee7b6284bae8d7374a3b0bc64f8b9
Java
ZaraD-Hu-b/JavaClasses
/src/com/class34/Student.java
UTF-8
1,051
4.3125
4
[]
no_license
package com.class34; import java.util.Iterator; import java.util.LinkedList; /*Create a Set collection that will hold Objects of Student Type. In this set we do not care about the insertion order. Each student object should have name and studentID. Display name of each student. */ class Student { String studentName; int id; Student(String studentName, int id) { this.studentName = studentName; this.id = id; } public void display() { System.out.println(id + " " + studentName); } public static void main(String[] args) { Student s1 = new Student("Nick", 101); Student s2 = new Student("Sandra", 102); Student s3 = new Student("Melissa", 103); Student s4 = new Student("Ted", 104); Student s5 = new Student("Taisia", 105); LinkedList<Student> studlist = new LinkedList<Student>(); studlist.add(s1); studlist.add(s2); studlist.add(s3); studlist.add(s4); studlist.add(s5); Iterator<Student> it = studlist.iterator(); while (it.hasNext()) { Student s = (Student) it.next(); s.display(); } } }
true
15e2027f9fb4c07db47ad305d691ccaba7d8c034
Java
liuyaoCS/ChinasoHomeView
/app/src/main/java/com/chinaso/test/MyPullToRefreshScrollView.java
UTF-8
2,667
2.15625
2
[]
no_license
package com.chinaso.test; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; /** * Created by Administrator on 2016/6/30 0030. */ public class MyPullToRefreshScrollView extends PullToRefreshScrollView { private static final String TAG ="MyPTRScrollView" ; public MyPullToRefreshScrollView(Context context) { super(context); } public MyPullToRefreshScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public MyPullToRefreshScrollView(Context context, Mode mode) { super(context, mode); } public MyPullToRefreshScrollView(Context context, Mode mode, AnimationStyle style) { super(context, mode, style); } private boolean mIsDisable; public void setDisable(boolean flag){ mIsDisable =flag; } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: Log.i(TAG, "onTouchEvent action:ACTION_DOWN"); break; case MotionEvent.ACTION_MOVE: Log.i(TAG, "onTouchEvent action:ACTION_MOVE"); break; case MotionEvent.ACTION_UP: Log.i(TAG, "onTouchEvent action:ACTION_UP"); break; case MotionEvent.ACTION_CANCEL: Log.i(TAG, "onTouchEvent action:ACTION_CANCEL"); break; } if(!mIsDisable){ return super.onTouchEvent(event); }else{ return false; } } @Override public boolean onInterceptTouchEvent(MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: Log.i(TAG, "onInterceptTouchEvent action:ACTION_DOWN"); // return true; break; case MotionEvent.ACTION_MOVE: Log.i(TAG, "onInterceptTouchEvent action:ACTION_MOVE"); //return true; break; case MotionEvent.ACTION_UP: Log.i(TAG, "onInterceptTouchEvent action:ACTION_UP"); //return true; break; case MotionEvent.ACTION_CANCEL: Log.i(TAG, "onInterceptTouchEvent action:ACTION_CANCEL"); break; } if(!mIsDisable){ return super.onInterceptTouchEvent(event); }else{ return false; } } }
true
e6a8738a113eeabfb1dd17ba71a0ebb960eae0ce
Java
tfurukawa33/restTrainContainer
/rest-service/src/main/java/com/example/restservice/repository/Category.java
UTF-8
1,537
2.109375
2
[]
no_license
package com.example.restservice.repository; import java.util.List; // import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; // import com.example.restservice.filter.FilmCategory; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; @Entity @Table(name = "category") @Data public class Category { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "category_id", unique = true, nullable = false, updatable = false) private int id; @Column(name = "name", nullable = false) @NotNull private String name; // @OneToMany(fetch = FetchType.EAGER) // @JoinColumn(name = "category_id", insertable = false, updatable = false) // private Set<FilmCategory> filmCategories; @OneToMany(fetch = FetchType.LAZY) @JoinTable( name = "film_category", joinColumns = { @JoinColumn(name = "category_id", referencedColumnName = "category_id") }, inverseJoinColumns = { @JoinColumn(name = "film_id", referencedColumnName = "film_id", unique = true) } ) @JsonIgnoreProperties("categories") private List<Film> films; }
true
9752d8a254306e0ec286b6668873e5c8b9e6db88
Java
OrgSmells/codehaus-mule-git
/tags/mule-2.0.0-RC2/transports/http/src/test/java/org/mule/transport/http/HttpRequestMessageAdapterTestCase.java
UTF-8
3,740
2.0625
2
[]
no_license
/* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.transport.http; import org.mule.api.MessagingException; import org.mule.api.transport.MessageAdapter; import org.mule.tck.providers.AbstractMessageAdapterTestCase; import org.mule.transport.http.servlet.HttpRequestMessageAdapter; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; public class HttpRequestMessageAdapterTestCase extends AbstractMessageAdapterTestCase { public Object getValidMessage() throws Exception { return getMockRequest("test message"); } public MessageAdapter createAdapter(Object payload) throws MessagingException { return new HttpRequestMessageAdapter(payload); } public static HttpServletRequest getMockRequest(final String message) { Object proxy = Proxy.newProxyInstance(ServletConnectorTestCase.class.getClassLoader(), new Class[]{HttpServletRequest.class}, new InvocationHandler() { private String payload = message; private Map props = new HashMap(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getInputStream".equals(method.getName())) { ServletInputStream s = new ServletInputStream() { ByteArrayInputStream is = new ByteArrayInputStream(payload.getBytes()); public int read() throws IOException { return is.read(); } }; return s; } else if ("getAttribute".equals(method.getName())) { return props.get(args[0]); } else if ("setAttribute".equals(method.getName())) { props.put(args[0], args[1]); } else if ("equals".equals(method.getName())) { return Boolean.valueOf(payload.equals(args[0].toString())); } else if ("toString".equals(method.getName())) { return payload; } else if ("getReader".equals(method.getName())) { return new BufferedReader(new StringReader(payload.toString())); } else if ("getAttributeNames".equals(method.getName())) { return new Hashtable().elements(); } else if ("getHeaderNames".equals(method.getName())) { return new Hashtable().elements(); } return null; } }); return (HttpServletRequest)proxy; } }
true
b3559394a8c96fdbf451bcc444597f18d5471a07
Java
robopoo/devweb_metricas_sgpf
/src/main/java/br/com/banestes/metrica/core/enumeration/TipoRelatorioEnum.java
UTF-8
285
2.265625
2
[]
no_license
package br.com.sgpf.metrica.core.enumeration; public enum TipoRelatorioEnum { PDF("PDF"), XLS("XLS"), DOC("DOC"); private String descricao; private TipoRelatorioEnum(String descricao) { this.descricao = descricao; } public String getDescricao() { return descricao; } }
true
0632d1cbe0419236535405a91e60991a7ec1a716
Java
gnehil/DataLink
/dl-worker/dl-worker-writer-kudu/src/main/java/com/ucar/datalink/writer/kudu/util/KuduRowUtils.java
UTF-8
3,395
2.4375
2
[ "CDDL-1.1", "Apache-2.0", "CDDL-1.0" ]
permissive
package com.ucar.datalink.writer.kudu.util; import com.ucar.datalink.common.errors.DatalinkException; import org.apache.kudu.ColumnSchema; import org.apache.kudu.Type; import org.apache.kudu.client.PartialRow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; public class KuduRowUtils { private static final Logger LOG = LoggerFactory.getLogger(KuduRowUtils.class); public static void setValue(PartialRow partialRow, Object value, ColumnSchema columnSchema) throws Exception { Object writeValue; String columnName = columnSchema.getName(); Type type = columnSchema.getType(); if (type == Type.STRING) { writeValue = value == null ? "" : value; partialRow.addString(columnName, writeValue.toString()); return; } else if (type == Type.BINARY) { writeValue = value == null ? "" : value; partialRow.addBinary(columnName, writeValue.toString().getBytes()); return; } writeValue = (value == null || value.toString().trim().equals("") || value.toString().equalsIgnoreCase("null")) ? 0 : value; try { if (type == Type.INT16) { partialRow.addShort(columnName, Short.parseShort(writeValue.toString())); return; } else if (type == Type.INT8) { partialRow.addByte(columnName, Byte.parseByte(writeValue.toString())); return; } else if (type == Type.INT32) { partialRow.addInt(columnName, Integer.parseInt(writeValue.toString())); return; } else if (type == Type.INT64) { partialRow.addLong(columnName, Long.parseLong(writeValue.toString())); return; } else if (type == Type.BOOL) { partialRow.addBoolean(columnName, Boolean.parseBoolean(writeValue.toString())); return; } else if (type == Type.FLOAT) { partialRow.addFloat(columnName, Float.parseFloat(writeValue.toString())); return; } else if (type == Type.DOUBLE) { partialRow.addDouble(columnName, Double.parseDouble(writeValue.toString())); return; } } catch (NumberFormatException e) { String msg = String.format("column[%s] value[%s] convert type[%s] errror!", columnName, value, type.toString()); LOG.error(msg, e); throw new DatalinkException(msg, e); } if (type == Type.DECIMAL) { int scale = columnSchema.getTypeAttributes().getScale(); BigDecimal formatValue = null; try { formatValue = new BigDecimal(String.valueOf(writeValue)).setScale(scale, BigDecimal.ROUND_HALF_UP); partialRow.addDecimal(columnName, formatValue); return; } catch (Exception e) { String msg = String.format("column[%s] value[%s] convert type[%s] value[%s] errror!", columnName, writeValue, type.toString(), formatValue == null ? "" : formatValue.toString()); LOG.error(msg, e); throw new DatalinkException(msg, e); } } throw new Exception(String.format("column[%s] type[%s] not support!", columnName, type.toString())); } }
true
df5d978eb08e4b55969a92087c9259dd3ac1a1a7
Java
WeiduoS/SpringCore
/SpringAOP/src/main/java/com/web/springaop/Sleepable.java
UTF-8
138
2.09375
2
[]
no_license
package com.web.springaop; /** * @author Weiduo * @date 2020/5/7 - 2:03 AM */ public interface Sleepable { public void sleep(); }
true
bb615e496c23b23542a7b56591646d461ab1ca18
Java
termMed/rf2-to-json-conversion-2
/src/main/java/org/ihtsdo/json/model/Description.java
UTF-8
2,387
2.078125
2
[ "Apache-2.0" ]
permissive
/* * 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 org.ihtsdo.json.model; import java.util.List; /** * * @author Alejandro Rodriguez */ public class Description extends Component { String descriptionId; String conceptId; LightConceptDescriptor type; String languageCode; String term; Integer length; LightConceptDescriptor caseSignificance; List<LangMembership> acceptability; List<RefsetMembership> refsetMemberships; private List<String> words; public Description() { } public String getDescriptionId() { return descriptionId; } public void setDescriptionId(String descriptionId) { this.descriptionId = descriptionId; } public String getConceptId() { return conceptId; } public void setConceptId(String conceptId) { this.conceptId = conceptId; } public LightConceptDescriptor getType() { return type; } public void setType(LightConceptDescriptor type) { this.type = type; } public String getTerm() { return term; } public void setTerm(String term) { this.term = term; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public List<LangMembership> getLangMemberships() { return acceptability; } public void setLangMemberships(List<LangMembership> langMemberships) { this.acceptability = langMemberships; } public List<RefsetMembership> getRefsetMemberships() { return refsetMemberships; } public void setRefsetMemberships(List<RefsetMembership> refsetMemberships) { this.refsetMemberships = refsetMemberships; } public List<String> getWords() { return words; } public void setWords(List<String> words) { this.words = words; } public String getLanguageCode() { return languageCode; } public void setLanguageCode(String languageCode) { this.languageCode = languageCode; } public LightConceptDescriptor getCaseSignificance() { return caseSignificance; } public void setCaseSignificance(LightConceptDescriptor caseSignificance) { this.caseSignificance = caseSignificance; } }
true
a38d27dee0aa9d2f60fe1e05a3f225489f18b6f8
Java
luckyluke1994/RSS_MVP
/RssMvp/app/src/main/java/com/example/maidaidien/rssmvp/Constant.java
UTF-8
658
1.734375
2
[]
no_license
package com.example.maidaidien.rssmvp; /** * Created by mai.dai.dien on 29/03/2017. */ public class Constant { public static final String LINK_EXTRA = "link"; public static final String URI_EXTRA = "uri"; public static final String NEWS_EXTRA = "news"; public static final int AllNewsLoaderId = 0; public static final int FootballNewsLoaderId = 1; // index when query public static final int COL_ID = 0; public static final int COL_TITLE = 1; public static final int COL_DESCRIPTION = 2; public static final int COL_DATE = 3; public static final int COL_IMAGE = 4; public static final int COL_LINK = 5; }
true
9140043eaae0f80cdfe1683777f426980f687a77
Java
hunoFox/lib.base
/src/main/java/com/hunofox/baseFramework/okHttp/utils/OkHttpUtils.java
UTF-8
4,637
2.296875
2
[]
no_license
package com.hunofox.baseFramework.okHttp.utils; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.hunofox.baseFramework.okHttp.callback.BaseCallback; import com.hunofox.baseFramework.okHttp.cookie.SimpleCookieJar; import com.hunofox.baseFramework.okHttp.request.RequestCall; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Response; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.io.InputStream; public class OkHttpUtils { private static OkHttpUtils mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private OkHttpUtils() { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); okHttpClientBuilder.cookieJar(new SimpleCookieJar()); mDelivery = new Handler(Looper.getMainLooper()); okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); mOkHttpClient = okHttpClientBuilder.build(); } public static OkHttpUtils getInstance() { if (mInstance == null) { synchronized (OkHttpUtils.class) { if (mInstance == null) { mInstance = new OkHttpUtils(); } } } return mInstance; } public Handler getDelivery() { return mDelivery; } public OkHttpClient getOkHttpClient() { return mOkHttpClient; } /** * 异步执行 */ public void execute(final RequestCall requestCall, BaseCallback callback, final String flag) { if (callback == null) return; final BaseCallback finalCallback = callback; final Call call = requestCall.getCall(); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { sendFailResultCallback(call, -1, e, finalCallback, flag); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.code() != 200) { try { sendFailResultCallback(call, response.code(), new RuntimeException(response.body().string()), finalCallback, flag); } catch (IOException e) { e.printStackTrace(); } return; } try { Object o = finalCallback.parseNetworkResponse(response); sendSuccessResultCallback(o, finalCallback, flag); } catch (Exception e) { sendFailResultCallback(call, response.code(), e, finalCallback, flag); } } }); } public void sendFailResultCallback(final Call call, final int responseCode, final Exception e, final BaseCallback callback, final String flag) { if (callback == null) return; mDelivery.post(new Runnable() { @Override public void run() { callback.onError(call, responseCode, e, flag); callback.onAfter(flag); } }); } public void sendSuccessResultCallback(final Object object, final BaseCallback callback, final String flag) { if (callback == null) return; mDelivery.post(new Runnable() { @Override public void run() { callback.onResponse(object, flag); callback.onAfter(flag); } }); } public void setCertificates(X509TrustManager trustManager, InputStream... certificates) { mOkHttpClient = getOkHttpClient().newBuilder() .sslSocketFactory(HttpsUtils.getSslSocketFactory(certificates, null, null), trustManager) .build(); } public void cancelTag(Object tag) { if (tag == null) { mOkHttpClient.dispatcher().cancelAll(); return; } for (Call call : mOkHttpClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag()) || tag == call.request().tag()) { call.cancel(); } } for (Call call : mOkHttpClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag()) || tag == call.request().tag()) { call.cancel(); } } } }
true
ba47d778ae178e650fa62929819e18e85ca76159
Java
carlosmata1/Sistema-de-expediente-clinico
/Proyecto TOO/src/java/entity/Municipio.java
UTF-8
2,648
2.09375
2
[]
no_license
package entity; // Generated 10-22-2016 08:37:44 AM by Hibernate Tools 4.3.1 import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Municipio generated by hbm2java */ @Entity @Table(name="MUNICIPIO" ,schema="SYSTEM" ) public class Municipio implements java.io.Serializable { private BigDecimal codMunicipio; private Departamento departamento; private String nombre; private Set<Persona> personas = new HashSet<Persona>(0); private Set<Clinica> clinicas = new HashSet<Clinica>(0); public Municipio() { } public Municipio(BigDecimal codMunicipio, Departamento departamento, String nombre) { this.codMunicipio = codMunicipio; this.departamento = departamento; this.nombre = nombre; } public Municipio(BigDecimal codMunicipio, Departamento departamento, String nombre, Set<Persona> personas, Set<Clinica> clinicas) { this.codMunicipio = codMunicipio; this.departamento = departamento; this.nombre = nombre; this.personas = personas; this.clinicas = clinicas; } @Id @Column(name="COD_MUNICIPIO", unique=true, nullable=false, precision=22, scale=0) public BigDecimal getCodMunicipio() { return this.codMunicipio; } public void setCodMunicipio(BigDecimal codMunicipio) { this.codMunicipio = codMunicipio; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="COD_DEPARTAMENTO", nullable=false) public Departamento getDepartamento() { return this.departamento; } public void setDepartamento(Departamento departamento) { this.departamento = departamento; } @Column(name="NOMBRE", nullable=false, length=30) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @OneToMany(fetch=FetchType.LAZY, mappedBy="municipio") public Set<Persona> getPersonas() { return this.personas; } public void setPersonas(Set<Persona> personas) { this.personas = personas; } @OneToMany(fetch=FetchType.LAZY, mappedBy="municipio") public Set<Clinica> getClinicas() { return this.clinicas; } public void setClinicas(Set<Clinica> clinicas) { this.clinicas = clinicas; } }
true
1b5fc3329aef3ee9b34c8012ac67d8a0e79fa320
Java
barunsw/parking
/VPPServer/src/main/java/com/hyundai_mnsoft/vpp/vo/ParkingLotUseSearchVo.java
UTF-8
606
1.882813
2
[]
no_license
package com.hyundai_mnsoft.vpp.vo; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; public class ParkingLotUseSearchVo implements Serializable { private String plId; private String rlId; public String getPlId() { return plId; } public void setPlId(String plId) { this.plId = plId; } public String getRlId() { return rlId; } public void setRlId(String rlId) { this.rlId = rlId; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
true
1f2136e89b37e02098221c38b08e06de65002cc8
Java
Patrick-Batenburg/java-android-student-meals-app-exam
/maaltijdapp/app/src/main/java/com/patrick/maaltijdapp/controller/callbacks/LoginControllerCallback.java
UTF-8
631
2.609375
3
[ "MIT" ]
permissive
package com.patrick.maaltijdapp.controller.callbacks; /** * Created by Patrick on 16/01/2018. */ /** * Occurs after a student has logged in successfully or unsuccessfully. */ public interface LoginControllerCallback { /** * Occurs after a student has logged in successfully or unsuccessfully. * * @param response The result value of this callback. */ void onLoginComplete(String response); /** * Occurs after a student has logged in successfully. */ void onLoginSuccess(); /** * Occurs after a student has logged in unsuccessfully. */ void onLoginFailed(); }
true
10840d150166c3f4519d2f56af1b481ad52fa55d
Java
sethgreen23/DataStructresAndAlgorithms
/6.Hash Table/5.Exercice1/src/Concordance.java
UTF-8
2,648
3.375
3
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; public class Concordance { private static Map<String, String> map = new TreeMap<>(); private static Set<String> words = new TreeSet<>(); public Concordance(String source, String filter) { //reading and storing the filter strings File filterFile=null ; File sourceFile=null; Scanner input=null; int lineCount=0; try { filterFile = new File(filter); System.out.println("Filter file opened !"); input = new Scanner(filterFile); while(input.hasNext()) { String[] line = input.nextLine().split(" "); // System.out.println(Arrays.toString(line)); for(int i=0;i<line.length;i++) { String inputWord = line[i].toUpperCase(); words.add(inputWord); } } // System.out.println(words); System.out.println("Filter file closed!"); System.out.println("Source file opened!"); sourceFile = new File(source); input = new Scanner(sourceFile); while(input.hasNext()) { lineCount++; String[] line = input.nextLine().split("[\\s',;:!?.-]+"); // System.out.println(Arrays.toString(line)); for(int i=0;i<line.length;i++) { String listing = line[i].toUpperCase(); //we filter out the element that we grab from the source file //the one that are included in the filter file we dont include them in the destination file if(words.contains(listing)) continue; String exist = map.get(listing); if(exist !=null) { exist = map.get(listing)+", "+lineCount; }else { exist = ""+lineCount; } map.put(listing, exist); } } // System.out.println(map); System.out.println("Source file closed!"); input.close(); }catch (FileNotFoundException e) { e.printStackTrace(); }finally { input.close(); } } public void printInFile(String destination) { //writing the element from the map to destination file PrintWriter write = null; try { File destinationFile = new File(destination); System.out.println("Print on destination start!"); write = new PrintWriter("destination.txt"); for(Map.Entry<String, String> entery : map.entrySet()) { write.println(entery); } System.out.println("Print on destination ended!"); }catch(FileNotFoundException e) { e.printStackTrace(); }finally { write.close(); } } public static void main(String[] args) { Concordance c = new Concordance("shakespear.txt","words.txt"); c.printInFile("destination.txt"); } }
true
7c65b98552df72a3572d8f641c828203d2ca2573
Java
harsgit/repositryjava
/DonorApplication/src/com/cg/donor/util/DbConnection.java
UTF-8
974
2.359375
2
[]
no_license
package com.cg.donor.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DbConnection { public static Connection getConnection() throws IOException, SQLException, ClassNotFoundException { try { FileInputStream fis=new FileInputStream("resources/MyProp.Properties"); Properties p=new Properties(); p.load(fis); String driver1=p.getProperty("driver"); String url=p.getProperty("url"); String username=p.getProperty("username"); String password=p.getProperty("password"); Class.forName(driver1); Connection conn = DriverManager.getConnection(url,username,password); return conn; } catch (FileNotFoundException e) { System.out.println(e); } //return null; return null; } }
true
070f4c7ad46542938d3c07cf46b78c9852031b6a
Java
amicafm/ArquiteturaClean
/produtos/produtos/src/main/java/com/crud/produtos/usercases/ProdutoServiceImpl.java
UTF-8
1,419
2.171875
2
[]
no_license
package com.crud.produtos.usercases; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import com.crud.produtos.entities.Produto; import com.crud.produtos.viewmodels.ProdutoRepository; import com.crud.produtos.viewmodels.ProdutoService; @Service public class ProdutoServiceImpl implements ProdutoService{ @Autowired private ProdutoRepository repository; @Override public Produto createProduto(Produto produto) { return repository.saveAndFlush(produto); } @Override public Produto findProdutoById(Integer id) { return repository.getOne(id); } @Override public List<Produto> findAllProdutos() { return repository.findAll(); } @Override public Produto updateProduto(Produto produto) { repository.save(produto); return repository.findById(produto.getId()).get(); } @Override public List<Produto> deleteProdutoById(Integer id) { repository.deleteById(id); return repository.findAll(); } @Override public List<Produto> deleteProduto(Produto produto) { repository.delete(produto); return repository.findAll(); } }
true
499361163312ae7a29744ff194bced81867f14f4
Java
Elvil/eurockv2
/TP4_VI/src/main/sarl/fr/utbm/info/vi51/project/environment/MouseTarget.java
UTF-8
2,585
2.390625
2
[]
no_license
/* * $Id$ * * Copyright (c) 2011-15 Stephane GALLAND <[email protected]>. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * This program is free software; you can redistribute it and/or modify */ package fr.utbm.info.vi51.project.environment; import java.util.UUID; import fr.utbm.info.vi51.framework.environment.AbstractMobileObject; import fr.utbm.info.vi51.framework.math.Circle2f; import fr.utbm.info.vi51.framework.math.MathUtil; import fr.utbm.info.vi51.framework.math.Point2f; import fr.utbm.info.vi51.framework.math.Vector2f; /** * Situated object representing the mouse position. * * @author St&eacute;phane GALLAND &lt;[email protected]&gt; * @version $Name$ $Revision$ $Date$ */ public final class MouseTarget extends AbstractMobileObject { private static final long serialVersionUID = 4893719355660004451L; /** * @param x * @param y */ public MouseTarget(float x, float y) { super( UUID.randomUUID(), new Circle2f(0, 0, 5f), Float.MAX_VALUE, Float.MAX_VALUE, x, y); setName("Mouse Target"); setType("TARGET"); } /** Change the position of the mouse target. * * @param newPosition * @param simulationDuration is the time during which the motion is applied. * @param worldWidth is the width of the world. * @param worldHeight is the height of the world. */ void setMousePosition(Point2f newPosition, float simulationDuration, float worldWidth, float worldHeight) { Point2f oldPosition = getPosition(); Vector2f oldDirection = getDirection(); Vector2f motion = newPosition.operator_minus(oldPosition); float rotation; if (motion.epsilonNul(MathUtil.EPSILON)) { rotation = 0f; } else { rotation = oldDirection.signedAngle(motion); } move(motion.getX(), motion.getY(), simulationDuration, worldWidth, worldHeight); rotate(rotation, simulationDuration); } @Override public String toString() { return "TARGET @ " + getPosition(); } }
true
9e4b87bd54071646b0c54f02408903492f41fb41
Java
lfeschuk/jetpack_full
/restoraunt/app_manager/src/main/java/Objects/DeliveryGuyWorkTime.java
UTF-8
2,458
2.640625
3
[]
no_license
package Objects; import android.util.Log; import java.util.ArrayList; public class DeliveryGuyWorkTime { //assume same index as DeliveryGuy // private long index; private String indexString; private String name; private Boolean in_time ; private String time; private String date; // private ArrayList<DeliveryGuytimeByDate> working_dates = new ArrayList<>(); public static final String TAG = "DeliveryGuyWorkTime"; public DeliveryGuyWorkTime ( ) { } public DeliveryGuyWorkTime (DeliveryGuyWorkTime d ) { this.indexString = d.getIndexString(); this.name = d.getName(); this.in_time = d.getIn_time(); this.time = d.getTime(); this.date = d.getDate(); } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Boolean getIn_time() { return in_time; } public void setIn_time(Boolean in_time) { this.in_time = in_time; } // public long getIndex() { // return index; // } // // public void setIndex(long index) { // this.index = index; // } // public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getIndexString() { return indexString; } // public void setIndexString(String indexString) { this.indexString = indexString; } // public String getName() { return name; } // public void setName(String name) { this.name = name; } // // public ArrayList<DeliveryGuytimeByDate> getWorking_dates() { // return working_dates; // } // // public void setWorking_dates(ArrayList<DeliveryGuytimeByDate> working_dates) { // this.working_dates = working_dates; // } // public void add_times_to_date (String time,Boolean in_time,String date) // { // Log.d(TAG,"ffffffff"); // // Boolean found = false; // for( DeliveryGuytimeByDate d : working_dates) // { // if (d.getDate().equals(date)) // { // d.add_time(time,in_time); // return; // } // } // //assume didnt find // DeliveryGuytimeByDate d = new DeliveryGuytimeByDate(); // d.setDate(date); // d.add_time(time,in_time); // working_dates.add(d); // } }
true
f0aad5204e86380dd5e7a10f5d2602c9df532441
Java
mengyunzhi/core
/src/main/java/com/mengyunzhi/core/entity/YunzhiEntity.java
UTF-8
416
2.078125
2
[]
no_license
package com.mengyunzhi.core.entity; import com.mengyunzhi.core.service.CommonService; public interface YunzhiEntity<ID> { ID getId(); Boolean getDeleted(); /** * 将所有的字段设置为null * 该方法使用反射,效率低。 * 建议时间上有条件的重写该方法。 */ default void setAllFieldsToNull() { CommonService.setAllFieldsToNull(this); } }
true
e23961a664e4df3dbf69ce1e9bc697ac68da9316
Java
ConceptEngine/UniversalRestaurantManagementSystem
/ManagementSystem/src/AdminMenuView.java
UTF-8
2,230
2.671875
3
[]
no_license
import javafx.geometry.Insets; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.stage.Screen; import javafx.stage.Stage; /** * Created by kasdi on 24.05.2016. */ public class AdminMenuView { GridPane grid; //constructor - empty public AdminMenuView(){ } public void start(Stage primaryStage, DatabaseAccessObject dbo){ //getting sxcreen real estate Rectangle2D screenSize = Screen.getPrimary().getVisualBounds(); //creating layout and grid BorderPane layout = new BorderPane(); grid = new GridPane(); //padding for layout layout.setPadding(new Insets(10, 10, 10, 10)); //create buttons Button addTables = new Button("Add Tables"); Button editItems = new Button("Edit items"); Button endButton = new Button("END"); //color style for end button endButton.setStyle("-fx-background-color: red"); //set button sizes addTables.setPrefSize(screenSize.getWidth()/3, screenSize.getHeight()/8); editItems.setPrefSize(screenSize.getWidth()/3, screenSize.getHeight()/8); endButton.setPrefSize(screenSize.getWidth()/3, screenSize.getHeight()/8); //set buttons on action addTables.setOnAction(event -> { //Create add table pop up window }); editItems.setOnAction(event -> { //Go to edit item view }); endButton.setOnAction(event -> { TableLayoutView tableLayout = new TableLayoutView(); tableLayout.start(primaryStage, dbo); }); //add butttons to the grid grid.add(addTables, 0, 0); grid.add(editItems, 0, 1); grid.add(endButton, 0, 2); //later set it to bottom right corner on the grid //set grid to align in center layout.setCenter(grid); //set the primary view Scene scene = new Scene(layout, screenSize.getWidth(), screenSize.getHeight() - 32); primaryStage.setTitle("Table Layout"); primaryStage.setScene(scene); primaryStage.show(); } }
true
06a044064eb340a673664b104f99d2cd6c283379
Java
wilson32190/tis
/tsearcher-dumpcenter/src/main/java/com/qlangtech/tis/hdfs/client/context/impl/TSearcherDumpContextImpl.java
UTF-8
7,886
1.5625
2
[ "MIT" ]
permissive
/* * The MIT License * * Copyright (c) 2018-2022, qinglangtech Ltd * * 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.qlangtech.tis.hdfs.client.context.impl; import java.util.Collections; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileSystem; import org.springframework.beans.factory.InitializingBean; import com.qlangtech.tis.hdfs.TISHdfsUtils; import com.qlangtech.tis.common.config.IServiceConfig; import com.qlangtech.tis.common.zk.TerminatorZkClient; import com.qlangtech.tis.exception.TimeManageException; import com.qlangtech.tis.hdfs.client.context.TSearcherDumpContext; import com.qlangtech.tis.hdfs.client.context.TSearcherQueryContext; import com.qlangtech.tis.hdfs.client.context.impl.TSearcherQueryContextImpl.ServiceConfigChangeListener; import com.qlangtech.tis.hdfs.client.process.BatchDataProcessor; import com.qlangtech.tis.hdfs.client.router.GroupRouter; import com.qlangtech.tis.hdfs.client.status.SolrCoreStatusHolder; import com.qlangtech.tis.hdfs.client.time.FileTimeProvider; import com.qlangtech.tis.hdfs.util.ServiceNameAware; /* * 数据DUMP上下文实现,(无状态) * * @author 百岁([email protected]) * @date 2019年1月17日 */ public class TSearcherDumpContextImpl implements TSearcherDumpContext, ServiceNameAware, InitializingBean { private static final String FS_DEFAULT_NAME = "fs.default.name"; protected static final Log logger = LogFactory.getLog(TSearcherDumpContextImpl.class); protected String fsName; private TSearcherQueryContext queryContext; private int triggerPort = 0; public int getTriggerPort() { return triggerPort; } public void setTriggerPort(int triggerPort) { this.triggerPort = triggerPort; } // 执行dump逻辑的时候,是否需要判断本节点是否抢夺到了锁 private boolean triggerLock; @Override public void fireServiceConfigChange() { queryContext.fireServiceConfigChange(); } @Override public void afterPropertiesSet() throws Exception { this.initDistributedSystemTaskLock(); } public void addCoreConfigChangeListener(ServiceConfigChangeListener listener) { queryContext.addCoreConfigChangeListener(listener); } // @Override private void initDistributedSystemTaskLock() { logger.warn("【注意】初始化集群系统分布式锁、HDFS任务阀值锁<<"); // HdfsJobLock hdfsLock = // new HdfsJobLock(getZkClient()); } public IServiceConfig getServiceConfig() { return queryContext.getServiceConfig(); } public GroupRouter getGroupRouter() { return queryContext.getGroupRouter(); } public SolrCoreStatusHolder getHostStatusHolder() { return queryContext.getHostStatusHolder(); } public String getServiceName() { return queryContext.getServiceName(); } public TerminatorZkClient getZkClient() { return queryContext.getZkClient(); } public void setFsName(String fsName) { this.fsName = fsName; } public TSearcherDumpContextImpl() { super(); // this.logger = new WrapperLogger( // LogFactory.getLog(HdfsTerminatorBean.class), this); } // protected static FileSystem fileSystem; public static FileSystem getHdfsFileSystem() { // return fileSystem; return TISHdfsUtils.getFileSystem(); } @Override public FileSystem getDistributeFileSystem() { return getHdfsFileSystem(); // if (fileSystem == null) { // synchronized (TSearcherDumpContextImpl.class) { // if (fileSystem == null) { // // Configuration configuration = new Configuration(); // FileSystem fileSys = null; // if (StringUtils.isEmpty(this.fsName)) { // throw new IllegalStateException( // "hdfsHost can not be null"); // } // logger.info("hdfsAddress:" + this.fsName); // try { // configuration.set("fs.default.name", this.fsName); // // configuration.addResource("core-site.xml"); // configuration.addResource("mapred-site.xml"); // // fileSys = FileSystem.get(configuration); // // } catch (Exception e) { // throw new RuntimeException(e); // } // fileSystem = fileSys; // // } // } // } // return fileSystem; } @Override public Set<String> getGroupNameSet() { return Collections.emptySet(); } @Override public Boolean getIncrOrNot() { throw new UnsupportedOperationException(); } @Override public String getLocalTimeFilePath() { return this.localTimeFilePath; } private String localTimeFilePath; public void setLocalTimeFilePath(String localTimeFilePath) { this.localTimeFilePath = localTimeFilePath; } // @Override // public Integer getNumSplits() { // //return getConfiguration().getInt("import.split.size", 4); // return 4; // } private String currentUserName = null; protected FileTimeProvider fileTimeProvider; public FileTimeProvider getFileTimeProvider() { return fileTimeProvider; } public void setFileTimeProvider(FileTimeProvider fileTimeProvider) { this.fileTimeProvider = fileTimeProvider; } // private boolean shallInitializeHdfs = true; // // public boolean isShallInitializeHdfs() { // return shallInitializeHdfs; // } // @Override public FileTimeProvider getTimeProvider() { if (fileTimeProvider == null) { try { if (localTimeFilePath != null) // fileTimeProvider = new FileTimeProvider(localTimeFilePath); else // 本地存储 // HDFS存储 fileTimeProvider = new FileTimeProvider(this, getCurrentUserName()); } catch (TimeManageException e) { logger.error("[错误]生成时间记录生成器出现错误,将不能正常启动", e); throw new RuntimeException("[错误]生成时间记录生成器出现错误,将不能正常启动", e); } } return fileTimeProvider; } @Override public String getFSName() { return this.fsName; } @Override public int getWirteHdfsThreadCount() { return this.writeHdfsThreadCount; } public String getCurrentUserName() { return StringUtils.defaultIfEmpty(currentUserName, System.getProperty("user.name")); } private int writeHdfsThreadCount = 10; public int getWriteHdfsThreadCount() { return writeHdfsThreadCount; } public void setWriteHdfsThreadCount(int writeHdfsThreadCount) { this.writeHdfsThreadCount = writeHdfsThreadCount; } public void setQueryContext(TSearcherQueryContext queryContext) { this.queryContext = queryContext; } @SuppressWarnings("all") private BatchDataProcessor dataprocessor; @SuppressWarnings("all") @Override public BatchDataProcessor getDataProcessor() { return this.dataprocessor; } @SuppressWarnings("all") public void setDataprocessor(BatchDataProcessor dataprocessor) { this.dataprocessor = dataprocessor; } public boolean isTriggerLock() { return triggerLock; } public void setTriggerLock(boolean triggerLock) { this.triggerLock = triggerLock; } }
true
df7f7977309cd938aff60249736b81a0d0320580
Java
Itisha2987/TCP-IP_Protocol
/datacomm/Dto.java
UTF-8
3,624
2.953125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package datacomm; import java.lang.Math; import java.util.Random; /** * * @author itisha */ public class Dto { public static String stringToBinary(String str){ String bString=""; int i; for(i=0;i<str.length();i++){ int acode=str.charAt(i); // System.out.print(acode); String temp=Integer.toBinaryString(str.charAt(i)); while(temp.length()<8){ temp= "0"+temp; } bString+=temp; } return bString; } private static int binaryToInt(String str){ char[] numbers = str.toCharArray(); int result = 0; for(int i=numbers.length - 1; i>=0; i--) if(numbers[i]=='1') result += Math.pow(2, (numbers.length-i - 1)); return result; } public static String binaryToString(String str){ String msg=""; for(int i=0;i<str.length();i=i+8){ String temp=str.substring(i, i+8); int acode = binaryToInt(temp); char c=(char)acode; msg+=Character.toString(c); } return msg; } //generates error of one bit public static String errorGenerator(String str){ String modified_string=""; Random rand = new Random(); int rand_int = rand.nextInt(str.length()); //System.out.println(rand_int); for(int i=0;i<str.length();i++) { if(i==rand_int) { if(str.charAt(i)=='0') modified_string += "1"; else modified_string += "0"; } else { modified_string += str.charAt(i); } } return modified_string; } public static String headGenerator(String str){ Random r = new Random(); int n = r.nextInt(16); String s = Integer.toBinaryString(n); while(s.length()<4) s = "0"+s; String ans=""; for(int i=0;i<str.length();i+=20) { ans += s + str.substring(i,Math.min(i+20, str.length())); } return ans; } public static String removeHead(String str){ String refined_msg=""; int n=1; System.out.println("The data received from the clients with data-link layer head in packets is: "); for(int i=0;i<str.length();i+=24) { String temp = str.substring(i,Math.min(i+24,str.length())); System.out.println("Packet "+n+" is "+temp + " "); refined_msg += str.substring(i+4,Math.min(i+24,str.length())); n++; //msg = msg.substring(4); } return refined_msg; } public static String Manchester(String str){ String final_msg=""; for(int i=0;i<str.length();i++) { if(str.charAt(i)=='0') final_msg += "-11"; else final_msg += "1-1"; } return final_msg; } public static String ManchesterDecoder(String str){ String final_str=""; for(int i=0;i<str.length();i+=3) { String sub = str.substring(i,i+3); if(sub.equals("-11")) final_str+="0"; else final_str+="1"; } return final_str; } }
true
be2493fd0d5543bae144b11c52cfa06be382b66f
Java
Amitercse/RestService
/RestServices/src/com/amit/dao/MessageDao.java
UTF-8
673
2.140625
2
[]
no_license
package com.amit.dao; import java.sql.SQLException; import java.util.List; import com.amit.model.MessageResource; /** * @author amit * Dao interface for message. */ public interface MessageDao { public List<MessageResource> getMessages(String url) throws SQLException; public MessageResource getMessage(int id) throws SQLException; public void addMessage(MessageResource messageResource) throws SQLException; public void updateMessage(int id, MessageResource messageResource) throws SQLException; public void deleteMessage(int messageId) throws SQLException; public List<MessageResource> getMessages(String author, String url) throws SQLException; }
true
4ccfa4050300bdda8daf45ea98f3235494ceeb86
Java
wsydt/java
/src/test/java/com/example/wsy/redis/pubsub/SubscribeBySpring.java
UTF-8
1,273
2.203125
2
[]
no_license
package com.example.wsy.redis.pubsub; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.stereotype.Component; @Component @Profile("pubsub") public class SubscribeBySpring { @Bean public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory redisConnectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); MessageListener messageListener = new MessageListener(){ @Override public void onMessage(Message message, byte[] bytes) { System.out.println("use spring ioc container accept message : " + message); } }; container.addMessageListener(messageListener, new ChannelTopic("__keyevent@0__:del")); return container; } }
true
72416b86224a75c00778d9b8a8db23538bc724e4
Java
wocloud/workOrder-frontend
/src/main/java/com/wocloud/common/util/http/APIHttpClient.java
UTF-8
2,817
2.40625
2
[]
no_license
package com.wocloud.common.util.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import com.alibaba.fastjson.JSONObject; public class APIHttpClient { static Log logger = LogFactory.getLog(APIHttpClient.class); static String url = "http://172.20.2.172:8080/commonCloud/pr/getMenu" ; // 通用调用 public static JSONObject commCall(Map params) { logger.debug(params); StringBuilder sb = new StringBuilder(""); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(dealURL(url, params)); /* * getRequest.addHeader("accept", "application/json;charset=UTF-8"); * getRequest.addHeader("content-type", * "application/json;charset=UTF-8"); */ logger.info("开始调用:" + getRequest.getURI()); HttpResponse response = httpClient.execute(getRequest); logger.info("结束调用:" + getRequest.getURI()); if (response.getStatusLine().getStatusCode() != 200) { } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()), "UTF-8")); String output = ""; logger.debug("Output from Server .... \n"); while ((output = br.readLine()) != null) { logger.debug(output); sb.append(output); } logger.debug("结果:" + sb.toString()); httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return JSONObject.parseObject(sb.toString()); } public static String dealURL(String url, Map params) { if (params.isEmpty()) return url; StringBuilder sb = new StringBuilder(url); sb.append("?"); Set keyset = params.keySet(); Iterator it = keyset.iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = new String(); if (params.get(key) instanceof String) { value = (String) params.get(key); } else if (params.get(key) instanceof Integer) { value = Integer.toString((Integer) params.get(key)); } else { } sb.append("&").append(key).append("=").append(value); } String ret = sb.toString().replaceAll(" ", "%20"); logger.info("拼装后的URL:" + ret); // TestExam.setHttpurl(ret); return ret; } public static void main(String[] args){ HashMap map = new HashMap(); map.put("userName", "alladmin"); APIHttpClient.commCall(map); } }
true
4da25ae60b9510853b155cdd1f6aa725f216fd2e
Java
Mujib517/devops-java
/src/Main.java
UTF-8
197
2.25
2
[]
no_license
// TFS // SVN // GIT // Concept // Repository public class Main { public static void main(String[] args) { int res = new MyMath().add(10, 20); System.out.println(res); } }
true
0d862803cc1bf5996ab39d7bb87ab7c8b8a81c0d
Java
41407/GPong
/Gpong/src/logic/Gameplay.java
UTF-8
3,888
3.125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package logic; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import ui.PongFrame; /** * * @author 41407 */ public class Gameplay { private HashSet<Ball> balls; private Paddle leftPaddle; private Paddle rightPaddle; private Stage stage; private int player1score = 0; private int player2score = 0; private PongFrame frame; private HashSet<Ball> ballsToAdd; public Gameplay(int x, int y) { this.balls = new HashSet(); this.ballsToAdd = new HashSet(); this.stage = new Stage(x, y); this.leftPaddle = new Paddle(50, (int) y / 2, 32, 150); this.rightPaddle = new Paddle(x - 50, (int) y / 2, 32, 150); System.out.println(x + " y: " + y); } public void loop() { Random r = new Random(); while (true) { player1score = balls.size(); if (balls.isEmpty()) { double xSpeed = 5 * Math.pow(-1, r.nextInt(2)); double ySpeed = 2 * Math.pow(-1, r.nextInt(2)); addABall(stage.getHeight() / 2, stage.getHeight() / 2, xSpeed, ySpeed, false); } addBalls(); handleCollisions(); rightPaddle.update(stage); leftPaddle.update(stage); frame.updatePanel(); try { Thread.currentThread().sleep(16); } catch (InterruptedException ex) { System.out.println("Perse!"); } } } private void handleCollisions() { for (Iterator<Ball> it = balls.iterator(); it.hasNext();) { Ball b = it.next(); double x = b.update(stage); if (x < leftPaddle.getX() + leftPaddle.getWidth()) { if (b.xCollide(leftPaddle)) { addABall(leftPaddle.getX() + leftPaddle.getWidth() + 10, b.getY(), Math.abs(b.getxSpeed()), b.getySpeed(), true); } } if (x < 0) { it.remove(); } else if (x > rightPaddle.getX()) { if (b.xCollide(rightPaddle)) { addABall(rightPaddle.getX() - 10, b.getY(), -Math.abs(b.getxSpeed()), b.getySpeed(), true); } } if (x > stage.getWidth()) { it.remove(); } } } public HashSet<Ball> getBalls() { return balls; } public Paddle getLeftPaddle() { return leftPaddle; } public Paddle getRightPaddle() { return rightPaddle; } public Stage getStage() { return stage; } public int getPlayer1score() { return player1score; } public int getPlayer2score() { return player2score; } public void setFrame(PongFrame frame) { this.frame = frame; } public PongFrame getFrame() { return frame; } private void addABall(double x, double y, double xSpeed, double ySpeed, boolean random) { Random r = new Random(); if (random) { ySpeed += (r.nextDouble() - 0.5)*1.4; xSpeed += r.nextDouble() - 0.5; } Ball b = new Ball(x, y, xSpeed, ySpeed, calculateSize()); ballsToAdd.add(b); } private void addBalls() { if (!ballsToAdd.isEmpty()) { for (Ball b : ballsToAdd) { balls.add(b); } } ballsToAdd.clear(); } private double calculateSize() { return Math.max(1, 20 - (balls.size() / 500)); } }
true
b52c7f1a75c4f5819264e9f716a65d7aeb493aea
Java
tom91136/Akatsuki
/akatsuki-api/src/main/java/com/sora/util/akatsuki/TypeConstraint.java
UTF-8
2,267
2.34375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 WEI CHEN LIN * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sora.util.akatsuki; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Defines a constraint for type matching */ @Target(ElementType.ANNOTATION_TYPE) @Retention(RetentionPolicy.CLASS) public @interface TypeConstraint { /** * Matching class for this constraint. Annotated class are also supported, * simply supply the annotation class instead of the type. */ Class<?>type(); /** * Bounds for class type matching. (When used on an annotation class, the * bound applies to the annotated element, see fields in * {@link com.sora.util.akatsuki.TypeConstraint.Bound} for more details). * <p> * If different bounds are required for different types, you can use * multiple {@link TypeConstraint}s together * */ Bound bound() default Bound.EXACTLY; /** * Class matching bounds */ enum Bound { /** * Has the same meaning of {@code A.class.equals(B.class)}. If used on * annotations,the bound matches classes that is being annotated * directly. */ EXACTLY, /** * Has the same meaning of {@code A.class.isAssignableFrom(B.class)}. If * used on annotations, the bound matches classes that inherits from a * class that contains the annotation. */ EXTENDS, /** * Has the same meaning of * {@code A.class.equals(B.class.getSuperclass())} where the inheritance * hierarchy is transversed and checked for equality all the way up to * {@link Object}. If used on annotations, the bound matches classes * that inherits from a class that contains the annotation. */ SUPER } }
true
2f3d842a2052b2d47ea8f921e9c201c4d6c6274b
Java
arnabs542/leetcode-48
/src/important/backtrack/Compute_sum_of_digits_in_all_numbers_from1ton.java
UTF-8
6,154
4.21875
4
[]
no_license
package important.backtrack; /** * Compute sum of digits in all numbers from 1 to n Given a number x, find sum of digits in all numbers from 1 to n.
Examples: Input: n = 5 Output: Sum of digits in numbers from 1 to 5 = 15 Input: n = 12 Output: Sum of digits in numbers from 1 to 12 = 51 Input: n = 328 Output: Sum of digits in numbers from 1 to 328 = 3241 Naive Solution:
A naive solution is to go through every number x from 1 to n, and compute sum in x by traversing all digits of x. Below is C++ implementation of this idea. // A Simple C++ program to compute sum of digits in numbers from 1 to n #include<iostream> using namespace std;   int sumOfDigits(int );   // Returns sum of all digits in numbers from 1 to n int sumOfDigitsFrom1ToN(int n) {     int result = 0; // initialize result       // One by one compute sum of digits in every number from     // 1 to n     for (int x=1; x<=n; x++)         result += sumOfDigits(x);       return result; }   // A utility function to compute sum of digits in a // given number x int sumOfDigits(int x) {     int sum = 0;     while (x != 0)     {         sum += x %10;         x   = x /10;     }     return sum; }   // Driver Program int main() {     int n = 328;     cout << "Sum of digits in numbers from 1 to " << n << " is "          << sumOfDigitsFrom1ToN(n);     return 0; } Run on IDE Output Sum of digits in numbers from 1 to 328 is 3241 

Efficient Solution:
Above is a naive solution. We can do it more efficiently by finding a pattern. Let us take few examples. sum(9) = 1 + 2 + 3 + 4 ........... + 9 = 9*10/2 = 45 sum(99) = 45 + (10 + 45) + (20 + 45) + ..... (90 + 45) = 45*10 + (10 + 20 + 30 ... 90) = 45*10 + 10(1 + 2 + ... 9) = 45*10 + 45*10 = sum(9)*10 + 45*10 sum(999) = sum(99)*10 + 45*100 sun(10^d - 1) = sum(10 ^ (d-1))*10 + 45 * 0-9 10 - 19 20 -29 .. 90-99 100 - 109 110 - 119 .. 190 - 199 .. 200 - 209 .. 290 - 299 ... 300 - 309 ... 390 - 399 ... 400 - 409 .. 490 - 499 .. 990 - 999 In general, we can compute sum(10d – 1) using below formula sum(10d - 1) = sum(10d-1 - 1) * 10 + 45*(10d-1) In below implementation, the above formula is implemented using dynamic programming as there are overlapping subproblems.
The above formula is one core step of the idea. Below is complete algorithm Algorithm: sum(n) 1) Find number of digits minus one in n. Let this value be 'd'. For 328, d is 2. 2) Compute some of digits in numbers from 1 to 10d - 1. Let this sum be w. For 328, we compute sum of digits from 1 to 99 using above formula. 3) Find Most significant digit (msd) in n. For 328, msd is 3. 4) Overall sum is sum of following terms a) Sum of digits in 1 to "msd * 10d - 1". For 328, sum of digits in numbers from 1 to 299. For 328, we compute 3*sum(99) + (1 + 2)*100. Note that sum of sum(299) is sum(99) + sum of digits from 100 to 199 + sum of digits from 200 to 299. Sum of 100 to 199 is sum(99) + 1*100 and sum of 299 is sum(99) + 2*100. In general, this sum can be computed as w*msd + (msd*(msd-1)/2)*10d b) Sum of digits in msd * 10d to n. For 328, sum of digits in 300 to 328. For 328, this sum is computed as 3*29 + recursive call "sum(28)" In general, this sum can be computed as msd * (n % (msd*10d) + 1) + sum(n % (10d)) Below is C++ implementation of above aglorithm. // C++ program to compute sum of digits in numbers from 1 to n #include<bits/stdc++.h> using namespace std;   // Function to computer sum of digits in numbers from 1 to n // Comments use example of 328 to explain the code int sumOfDigitsFrom1ToN(int n) {     // base case: if n<10 return sum of     // first n natural numbers     if (n<10)       return n*(n+1)/2;       // d = number of digits minus one in n. For 328, d is 2     int d = log10(n);       // computing sum of digits from 1 to 10^d-1,     // d=1 a[0]=0;     // d=2 a[1]=sum of digit from 1 to 9 = 45     // d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900     // d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500     int *a = new int[d+1];     a[0] = 0, a[1] = 45;     for (int i=2; i<=d; i++)         a[i] = a[i-1]*10 + 45*ceil(pow(10,i-1));       // computing 10^d     int p = ceil(pow(10, d));       // Most significant digit (msd) of n,     // For 328, msd is 3 which can be obtained using 328/100     int msd = n/p;       // EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE     // First two terms compute sum of digits from 1 to 299     // (sum of digits in range 1-99 stored in a[d]) +     // (sum of digits in range 100-199, can be calculated as 1*100 + a[d]     // (sum of digits in range 200-299, can be calculated as 2*100 + a[d]     //  The above sum can be written as 3*a[d] + (1+2)*100       // EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE     // The last two terms compute sum of digits in number from 300 to 328     // The third term adds 3*29 to sum as digit 3 occurs in all numbers     //                from 300 to 328     // The fourth term recursively calls for 28     return msd*a[d] + (msd*(msd-1)/2)*p +             msd*(1+n%p) + sumOfDigitsFrom1ToN(n%p); }   // Driver Program int main() {     int n = 328;     cout << "Sum of digits in numbers from 1 to " << n << " is "          << sumOfDigitsFrom1ToN(n);     return 0; } Run on IDE Output Sum of digits in numbers from 1 to 328 is 3241 The efficient algorithm has one more advantage that we need to compute the array ‘a[]’ only once even when we are given multiple inputs. This article is computed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above * @author het * */ public class Compute_sum_of_digits_in_all_numbers_from1ton { }
true
35c9c9da78ad8e453c682a2efa57872d2269b95a
Java
Shaggy23-cell/Estructura-de-datos
/BEAR/src/sample/Pedido.java
UTF-8
1,198
2.640625
3
[]
no_license
package sample; import javafx.beans.property.SimpleStringProperty; public class Pedido { SimpleStringProperty juego; SimpleStringProperty cantidadJuego; SimpleStringProperty precio; public Pedido(String juego, String cantidadJuego,String precio) { this.juego=new SimpleStringProperty((juego)); this.cantidadJuego=new SimpleStringProperty((cantidadJuego)); this.precio=new SimpleStringProperty((precio)); } public String getPrecio() { return precio.get(); } public SimpleStringProperty precioProperty() { return precio; } public void setPrecio(String precio) { this.precio.set(precio); } public String getJuego() { return juego.get(); } public SimpleStringProperty juegoProperty() { return juego; } public void setJuego(String juego) { this.juego.set(juego); } public String getCantidadJuego() { return cantidadJuego.get(); } public SimpleStringProperty cantidadJuegoProperty() { return cantidadJuego; } public void setCantidadJuego(String cantidadJuego) { this.cantidadJuego.set(cantidadJuego); } }
true
e5d508c78b44ac22cea7ba1bad95a94443240b8f
Java
wsen/cbw_java
/src/tag4/A19_Zinsen.java
UTF-8
1,007
3.46875
3
[]
no_license
package tag4; import java.util.Scanner; public class A19_Zinsen { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Guthaben ?"); String line = sc.nextLine(); //.nextInt(), .nextDouble() int guthaben = Integer.parseInt(line); System.out.print("Zinssatz ?"); String line2 = sc.nextLine(); int zinssatz = Integer.parseInt(line2); double kapital1 = vermehren( guthaben, zinssatz); System.out.printf("1. Jahr: %.2f %n", kapital1); double kapital2 = vermehren(kapital1, zinssatz); System.out.printf("2. Jahr: %.2f %n", kapital2); double kapital3 = vermehren(kapital2, zinssatz); System.out.printf("3. Jahr: %.2f %n", kapital3); } private static double vermehren(double guthaben, double zinssatz) { return guthaben * (1+zinssatz/100); // double endkapital = guthaben * (1+zinssatz/100); // return endkapital; } }
true
bae4e40dc00c8880bf30207551ecfaa6e7636875
Java
evandor/skysail
/skysail.app.spotify/src/io/skysail/app/spotify/domain/OAuthCallbackData.java
UTF-8
396
1.734375
2
[ "Apache-2.0" ]
permissive
package io.skysail.app.spotify.domain; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter public class OAuthCallbackData { @JsonProperty("access_token") private String accessToken; private String token_type; private String refresh_token; private String scope; private Integer expires_in; }
true
08339b1f7afb4a8420a9e25ded4e28f2e5902a8a
Java
ffekete/FantasyManagerGame
/core/src/com/mygdx/game/logic/activity/compound/MoveAndInteractActivity.java
UTF-8
341
2
2
[]
no_license
package com.mygdx.game.logic.activity.compound; import com.mygdx.game.logic.activity.Activity; import com.mygdx.game.logic.activity.CompoundActivity; public class MoveAndInteractActivity extends CompoundActivity { public MoveAndInteractActivity(int priority, Class<? extends Activity> clazz) { super(priority, clazz); } }
true
de0e66b95b461d75a2671399589af60ff8c6cec2
Java
DatabaseGroup9/parseMaster
/src/main/java/entity/Mentioned.java
UTF-8
711
2.328125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entity; /** * * @author Andreas */ public class Mentioned { String bookID; String cityID; public Mentioned(String bookID, String cityID) { this.bookID = bookID; this.cityID = cityID; } public String getBookID() { return bookID; } public void setBookID(String bookID) { this.bookID = bookID; } public String getCityID() { return cityID; } public void setCityID(String cityID) { this.cityID = cityID; } }
true
829421419a392eb05adbaba0db66c628554d9a9a
Java
anchoranalysis/anchor
/anchor-image-voxel/src/main/java/org/anchoranalysis/image/voxel/datatype/FindCommonVoxelType.java
UTF-8
4,207
2.625
3
[ "Apache-2.0", "MIT" ]
permissive
/*- * #%L * anchor-image * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * 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. * #L% */ package org.anchoranalysis.image.voxel.datatype; import java.util.Optional; import java.util.stream.Stream; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.anchoranalysis.core.exception.friendly.AnchorImpossibleSituationException; /** * Finds a common voxel-data type to represent two types. * * <p>This usually either the class themselves or a type that is minimally larger, and can represent * both types without loss of precision. * * <p>An exception is the float-type that takes precedence over all others, and this may lead to * loss of precision. * * @author Owen Feehan */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class FindCommonVoxelType { /** * Finds a common type to represent (ideally without loss of precision} of a stream of types. * * @param stream a stream of types to find a common representation for. * @return a type that can represent all types (think of it as a minimal superset of all types), * or {@link Optional#empty} if the stream has no elements. */ public static Optional<VoxelDataType> commonType(Stream<VoxelDataType> stream) { return stream.reduce(FindCommonVoxelType::commonType); } /** * Finds a common type to represent (ideally without loss of precision} both {@code first} and * {@code second}. * * @param first the first-type that must be represented in the common type * @param second the second-type that must be represented in the common type * @return a type that can represent both (think of it as a minimal superset of both types). */ public static VoxelDataType commonType(VoxelDataType first, VoxelDataType second) { // If either type is non-integral, then use a float as the common type if (!first.isInteger() || !second.isInteger()) { return FloatVoxelType.INSTANCE; } // Then take which ever type has the highest number of bits // This assumes, whether signed or unsigned, a type with a higher // number of bits, can contain one of a lower number. // This holds true with a unsigned/signed 8, 16, 32 combinations. if (first.bitDepth() > second.bitDepth()) { return first; } if (first.bitDepth() < second.bitDepth()) { return second; } // This this point the number-of-bits must be equal of both types, // so compare the signed vs unsigned if (first.isUnsigned() == second.isUnsigned()) { // Then both seem to be the same type, so use either arbitrarily. return first; } else { // Otherwise the next highest signed integer type must be used // to contain both the unsigned and signed buffers of smaller bits // As signed types aren't properly implemented yet, this situation // should not occur. throw new AnchorImpossibleSituationException(); } } }
true
a8df5ca4e4ee2726305ed8d551108a09cf6beb85
Java
hollewsq/Merchant
/app/src/main/java/com/example/a13621/merchant/net/PMCallback.java
UTF-8
135
1.734375
2
[]
no_license
package com.example.a13621.merchant.net; public interface PMCallback { void onFail(Object msg); void onSuccess(Object reg); }
true
7e17cd86ca2c7b2a3414c7dc3334c5079de4946d
Java
YoonsooChang/netty-socketio
/src/test/java/com/corundumstudio/socketio/scheduler/TaskRunnable.java
UTF-8
467
2.703125
3
[ "Apache-2.0" ]
permissive
package com.corundumstudio.socketio.scheduler; public class TaskRunnable implements Runnable { private String id; public String called = null; public TaskRunnable(String id) { this.id = id; } @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { System.out.println(id); called = id; } } }
true
744e980a9cfaa65604cd499270f5b40d9ffd5ccc
Java
jvdassen/va-case-study
/src/test/java/ch/uzh/ifi/seal/soprafs16/model/LockboxTest.java
UTF-8
499
2.140625
2
[]
no_license
package ch.uzh.ifi.seal.soprafs16.model; import static org.junit.Assert.*; import org.junit.Test; import ch.uzh.ifi.seal.soprafs16.constant.LootType; import ch.uzh.ifi.seal.soprafs16.model.lootobject.Lockbox; /* * @author Luc Boillat */ public class LockboxTest { @Test public void test() { Lockbox testLockbox = new Lockbox(); testLockbox.setLootType(LootType.LOCKBOX); assertEquals(testLockbox.getValue(), 1000); assertEquals(testLockbox.getLootType(), LootType.LOCKBOX); } }
true
2e913f5157831e2fd29d82fff61a81762d34d6bd
Java
SongHyunkwan/CamTalk
/app/src/main/java/garmter/com/camtalk/item/ItemCard.java
UTF-8
618
2.28125
2
[]
no_license
package garmter.com.camtalk.item; import org.json.JSONException; import org.json.JSONObject; /** * Created by Youjung on 2016-12-16. */ public class ItemCard { public String path = ""; public String title = ""; public String front = ""; public String back = ""; public boolean ok = false; public String toJson() { JSONObject obj = new JSONObject(); try { obj.put("front", front); obj.put("back", back); } catch (JSONException e) { e.printStackTrace(); } return obj.toString(); } }
true
72cec03b4f158d1046c36db984622ff2e7f4f898
Java
amitkmandal/AmitJava
/src/com/info/test/WithOutThirdSwap.java
UTF-8
708
3.890625
4
[]
no_license
package com.info.test; /* * program for swapping of two number without third variable. */ import java.util.Scanner; public class WithOutThirdSwap { public static void main(String[] args) { int num1,num2; Scanner scanner = new Scanner(System.in); System.out.println("Enter two Number :"); num1 = scanner.nextInt(); num2 = scanner.nextInt(); System.out.println("Before Swapping Number Are : "+num1+"------"+num2); num1 = num1 * num2; num2 = num1/num2; num1 = num1/num2; System.out.println("After Swapping Number Are :"+num1+"------"+num2); scanner.close(); /* * Another logic * num1 = num1+num2; 5+6=11 * num2 = num1-num2; 11-6=5 * num1 = num1-num2; 11-5=6 */ } }
true
4c0a1b3d6cd30aed67a4cff1518db84a283ccc87
Java
RodrigoRP/Sistema-de-votacao
/src/main/java/com/rodrigoramos/sistemavotacaoapi/service/impl/DatabaseService.java
UTF-8
1,231
2.5625
3
[]
no_license
package com.rodrigoramos.sistemavotacaoapi.service.impl; import com.rodrigoramos.sistemavotacaoapi.dao.CustomerRepository; import com.rodrigoramos.sistemavotacaoapi.dao.RestaurantRepository; import com.rodrigoramos.sistemavotacaoapi.entity.Customer; import com.rodrigoramos.sistemavotacaoapi.entity.Restaurant; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.util.Arrays; @AllArgsConstructor @Service public class DatabaseService { private CustomerRepository customerRepository; private RestaurantRepository restaurantRepository; public void instantiateDataBase() { Customer c1 = new Customer(null, "Maria", "da Silva", "123123"); Customer c2 = new Customer(null, "Jardel", "Fonseca", "12312"); Customer c3 = new Customer(null, "Luis", "Nunes", "1231"); Customer c4 = new Customer(null, "Martha", "Medeiros", "1231"); Restaurant r1 = new Restaurant(null, "Sierra", 323, "Presidente Vargas", "Bonfim"); Restaurant r2 = new Restaurant(null, "Serve Bem", 5675, "Medianeira", "Centro"); customerRepository.saveAll(Arrays.asList(c1, c2, c3, c4)); restaurantRepository.saveAll(Arrays.asList(r1, r2)); } }
true
dc99a4686ba16d65cc127d65cf8e5a41b9ba3a6c
Java
Gerts19/ASAP
/src/test/java/com/revature/controllers/UserControllerIntegrationTest.java
UTF-8
11,341
2.109375
2
[]
no_license
package com.revature.controllers; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import java.util.Optional; import com.revature.dtos.Credentials; import com.revature.dtos.Principal; import com.revature.entities.Asset; import com.revature.entities.User; import com.revature.entities.UserRole; import com.revature.repositories.UserRepository; import com.revature.util.JwtConfig; import com.revature.util.JwtGenerator; import com.revature.util.PasswordEncryption; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SpringBootTest @ExtendWith(SpringExtension.class) public class UserControllerIntegrationTest { private MockMvc mockMvc; private WebApplicationContext webApplicationContext; private User theUser; @MockBean UserRepository userRepository; @Mock PasswordEncryption passwordEncryption; @MockBean JavaMailSender javaMailSender; @Autowired public UserControllerIntegrationTest(WebApplicationContext webContext) { this.webApplicationContext = webContext; } @BeforeEach public void setup(){ this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); theUser = new User("nana","password","fakeEmail","first","last"); theUser.setRole(UserRole.BASIC); theUser.setUserId(1); } @AfterAll public static void afterAllTest(){ System.out.println("All Test finished!"); } // Gives issues because the JavaMailSender is mocked, and needs to return an instance of a MimeMessage // on UserController.registerUser() - line 75 @Test @Disabled public void registerUserWithValidData() throws Exception { User user1 = new User("nana","password","fakeEmail","first","last"); user1.setRole(UserRole.BASIC); when(userRepository.save(user1)).thenReturn(null); String Json = "{" + "\"username\":\"" + user1.getUsername() + "\", " + "\"password\":\"" + user1.getPassword() + "\", " + "\"email\":\"" + user1.getEmail() + "\", " + "\"firstName\":\"" + user1.getFirstName() + "\", " + "\"lastName\":\"" + user1.getLastName() + "\", " + "\"role\":\"" + user1.getRole().toString().toUpperCase() + "\"" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/users") .contentType(MediaType.APPLICATION_JSON_VALUE) .content(Json)) .andExpect(status().isCreated()); } @Test public void registerUserWithInvalidData() throws Exception { User user1 = new User("nana","password","fakeEmail","first","last"); user1.setRole(UserRole.BASIC); when(userRepository.save(user1)).thenReturn(null); String Json = "{" + "\"username\":\"" + user1.getUsername() + "\", " + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/users") .contentType(MediaType.APPLICATION_JSON_VALUE) .content(Json)) .andExpect(status().isBadRequest()); } @Test public void confirmUserAccountWithValidData() throws Exception { when(userRepository.findById(theUser.getUserId())).thenReturn(Optional.of(theUser)); when(userRepository.findUserByUsername(theUser.getUsername())).thenReturn(Optional.of(theUser)); doNothing().when(userRepository).confirmedAccount(theUser.getUserId()); mockMvc.perform(MockMvcRequestBuilders.get("/users/confirmation/{username}",theUser.getUsername())) // Status should be 302 - redirect .andExpect(status().isFound()); } @Test public void confirmUserAccountWithInvalidData() throws Exception { User fakeuser = new User(); fakeuser.setUsername(" "); fakeuser.setUserId(10); fakeuser.setRole(UserRole.BASIC); mockMvc.perform(MockMvcRequestBuilders.get("/users/confirmation/{username}",fakeuser.getUsername())) // Returned status code should be bad request .andExpect(status().isBadRequest()); } @Test public void loginWithValidData() throws Exception { Credentials credentials = new Credentials("cspace","password"); User user = new User(); user.setUsername(credentials.getUsername()); user.setPassword(credentials.getPassword()); user.setEmail("[email protected]"); user.setFirstName("Cole"); user.setLastName("Space"); User hashedUser = new User(user); hashedUser.setAccountConfirmed(true); hashedUser.setPassword(PasswordEncryption.encryptString(hashedUser.getPassword())); when(userRepository.findUserByUsername(user.getUsername())).thenReturn(Optional.of(hashedUser)); String Json = "{" + "\"username\":\"" + "cspace" + "\", " + "\"password\":\"" + "password" + "\"" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/users/login") .contentType(MediaType.APPLICATION_JSON) .content(Json) ).andExpect(status().is2xxSuccessful()); } @Test public void loginWithInvalidData() throws Exception { User user = new User(); user.setUserId(1); user.setUsername("agooge"); user.setPassword("password123"); user.setEmail("[email protected]"); user.setFirstName("Alex"); user.setLastName("Googe"); org.mockito.Mockito.when(userRepository.findUserByUsername("agooge")).thenReturn(Optional.of(user)); String Json = "{" + "\"username\":\"" + user.getUsername() + "\", " + "\"password\":\"" + "password1" + "\"" + "}"; mockMvc.perform(MockMvcRequestBuilders.post("/users/login") .contentType(MediaType.APPLICATION_JSON) .content(Json) ).andExpect(status().is4xxClientError()); } @Test public void getAllWithCorrectRole() throws Exception { User adminUser = new User("agooge","password","[email protected]","Alex","Googe"); adminUser.setRole(UserRole.ADMIN); Principal principal = new Principal(adminUser); JwtGenerator generator = new JwtGenerator(new JwtConfig()); String token = generator.generateJwt(principal); List<User> userList = new ArrayList<>(); userList.add(adminUser); userList.add(theUser); when(userRepository.findAll()).thenReturn(userList); mockMvc.perform(MockMvcRequestBuilders.get("/users") .header("ASAP-token", token)) .andExpect(status().is2xxSuccessful()) .andExpect(jsonPath("$.size()").value(userList.size())) // Ideally we also check the contents of the list, but it passed visual inspection .andDo(print()); } @Test public void getAllWithWrongRole() throws Exception { User basicUser = new User("agooge","password","[email protected]","Alex","Googe"); basicUser.setRole(UserRole.BASIC); Principal principal = new Principal(basicUser); JwtGenerator generator = new JwtGenerator(new JwtConfig()); String token = generator.generateJwt(principal); mockMvc.perform(MockMvcRequestBuilders.get("/users") .header("ASAP-token", token)) .andExpect(status().is4xxClientError()); } @Test public void getWatchlist_withValidUser_whereWatchlistIsNotEmpty() throws Exception { User basicUser = new User("agooge1","password","[email protected]","Alex","Googe"); basicUser.setRole(UserRole.BASIC); Asset minAsset = new Asset(); minAsset.setAssetId(1); minAsset.setName("min asset"); minAsset.setTicker("MNAS"); minAsset.setFinnhubIndustry("Fake"); minAsset.setLastTouchedTimestamp(LocalDate.now()); List<Asset> assetList = new ArrayList<>(); assetList.add(minAsset); basicUser.setWatchlist(assetList); Principal principal = new Principal(basicUser); JwtGenerator generator = new JwtGenerator(new JwtConfig()); String token = generator.generateJwt(principal); when(userRepository.findUserByUsername(basicUser.getUsername())).thenReturn(Optional.of(basicUser)); mockMvc.perform(MockMvcRequestBuilders.get("/users/watchlist") .header("ASAP-token", token)) .andExpect(status().is2xxSuccessful()) .andExpect(jsonPath("$.size()").value(assetList.size())); } @Test public void getWatchlist_withValidUser_whereWatchlistIsEmpty() throws Exception { User basicUser = new User("agooge1","password","[email protected]","Alex","Googe"); basicUser.setRole(UserRole.BASIC); List<Asset> assetList = Collections.emptyList(); basicUser.setWatchlist(assetList); Principal principal = new Principal(basicUser); JwtGenerator generator = new JwtGenerator(new JwtConfig()); String token = generator.generateJwt(principal); when(userRepository.findUserByUsername(basicUser.getUsername())).thenReturn(Optional.of(basicUser)); mockMvc.perform(MockMvcRequestBuilders.get("/users/watchlist") .header("ASAP-token", token)) .andExpect(status().is2xxSuccessful()) .andExpect(jsonPath("$.size()").value(assetList.size())); } @Test public void getWatchlist_withInvalidUser() throws Exception { // Bad User User invalidUser = new User("ag","password","[email protected]","Alex","Googe"); invalidUser.setRole(UserRole.BASIC); Principal principal = new Principal(invalidUser); JwtGenerator generator = new JwtGenerator(new JwtConfig()); String token = generator.generateJwt(principal); when(userRepository.findUserByUsername(invalidUser.getUsername())).thenReturn(Optional.empty()); mockMvc.perform(MockMvcRequestBuilders.get("/users/watchlist") .header("ASAP-token", token)) .andExpect(status().is4xxClientError()); } }
true
f1aa217f0f8e53ddb3371196f7fa770482ff5aa0
Java
cpollet/itinerants
/mailer/daemon/src/main/java/net/cpollet/itinerants/mailer/handlers/NewAccountHandlerMock.java
UTF-8
517
2.15625
2
[ "Apache-2.0" ]
permissive
package net.cpollet.itinerants.mailer.handlers; import lombok.extern.slf4j.Slf4j; import net.cpollet.itinerants.mailer.NewAccountMessage; /** * Created by cpollet on 17.05.17. */ @Slf4j public class NewAccountHandlerMock implements Handler<NewAccountMessage> { @Override public void handle(NewAccountMessage payload) throws HandlerException { log.info(payload.toString()); } @Override public Class<NewAccountMessage> handledMessage() { return NewAccountMessage.class; } }
true
16cfa26b557130fecf88e9a691b3a076302acdde
Java
malu1851/metro_zhaopin
/hrrm/src/client/nc/ui/rm/interview/view/InterviewListView.java
GB18030
9,903
1.515625
2
[]
no_license
package nc.ui.rm.interview.view; import java.awt.Color; import java.awt.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import nc.hr.utils.PubEnv; import nc.hr.utils.ResHelper; import nc.ui.pub.beans.UIPanel; import nc.ui.pub.beans.UITable; import nc.ui.pub.beans.constenum.DefaultConstEnum; import nc.ui.pub.beans.table.GroupableTableHeader; import nc.ui.pub.bill.BillListData; import nc.ui.pub.bill.BillListPanel; import nc.ui.pub.bill.BillModel; import nc.ui.pub.bill.BillTableCellRenderer; import nc.ui.rm.pub.view.DescriptionPanel; import nc.ui.uif2.AppEvent; import nc.ui.uif2.model.BillManageModel; import nc.vo.hr.tools.pub.GeneralVO; import nc.vo.ic.m4460.entity.StateAdjustVO; import nc.vo.pub.CircularlyAccessibleValueObject; import nc.vo.pub.bill.BillTempletBodyVO; import nc.vo.pub.bill.BillTempletVO; import nc.vo.pub.lang.UFLiteralDate; import nc.vo.rm.interview.AggInterviewVO; import nc.vo.rm.interview.IVPlanStateEnum; import nc.vo.rm.interview.InterviewPlanVO; import nc.vo.rm.interview.InterviewVO; import nc.vo.rm.interview.IvReslutEnum; import nc.vo.rm.psndoc.common.RMApplyTypeEnum; import nc.vo.trade.voutils.VOUtil; import org.apache.commons.lang.ArrayUtils; public class InterviewListView extends InterviewBaseListView { private static final String InterviewVO = null; public InterviewListView() { } protected UIPanel createDescriptionPanel() { DescriptionPanel descPanel = new DescriptionPanel(); descPanel.setLeadString(ResHelper.getString("6021interview", "06021interview0037")); JLabel jLabel = new JLabel(); jLabel.setIcon(new ImageIcon(getClass().getResource( "/hr/images/icons/rmpass.png"))); descPanel.add(jLabel, ResHelper.getString("6021interview", "06021interview0038")); JLabel fLabel = new JLabel(); fLabel.setIcon(new ImageIcon(getClass().getResource( "/hr/images/icons/rmnotpass.png"))); descPanel.add(fLabel, ResHelper.getString("6021interview", "06021interview0039")); JLabel iLabel = new JLabel(); iLabel.setIcon(new ImageIcon(getClass().getResource( "/hr/images/icons/rmiv.png"))); descPanel.add(iLabel, ResHelper.getString("6021interview", "06021interview0052")); JLabel hLabel = new JLabel(); hLabel.setIcon(new ImageIcon(getClass().getResource( "/hr/images/icons/rmnoiv.png"))); descPanel.add(hLabel, ResHelper.getString("6021interview", "06021interview0072")); descPanel.add(Color.orange, ResHelper.getString("6021psndoc", "06021psndoc0032")); descPanel.add(Color.WHITE, ResHelper.getString("6021psndoc", "06021psndoc0033")); descPanel.init(); return descPanel; } public void initPageInfo() { int showOrder = 1000; BillTempletVO billTempletVO = getBillListPanel().getBillListData() .getBillTempletVO(); List<BillTempletBodyVO> itemList = new ArrayList(); itemList.addAll(Arrays.asList(this.bodyVOs)); String[] headInfo = getHeadRoundKey(); BillTempletBodyVO bodvo = (BillTempletBodyVO) this.bodyVOs[0].clone(); bodvo.setListshowflag(Boolean.valueOf(false)); bodvo.setShowflag(Boolean.valueOf(false)); bodvo.setDatatype(Integer.valueOf(0)); bodvo.setDefaultshowname("hidden"); bodvo.setItemkey("hidden"); bodvo.setPos(Integer.valueOf(0)); bodvo.setMetadatapath(null); bodvo.setMetadataproperty(null); bodvo.setList(false); bodvo.setListflag(Boolean.valueOf(true)); bodvo.setShoworder(Integer.valueOf(showOrder++)); bodvo.setWidth(Integer.valueOf(1)); itemList.add(bodvo); for (int i = 0; i < this.maxRound; i++) { BillTempletBodyVO bodyvo = (BillTempletBodyVO) this.bodyVOs[0] .clone(); bodyvo.setListshowflag(Boolean.valueOf(true)); bodyvo.setShowflag(Boolean.valueOf(true)); bodyvo.setDatatype(Integer.valueOf(0)); bodyvo.setDefaultshowname(getRoundNum(i + 1)); bodyvo.setItemkey(headInfo[i]); bodyvo.setPos(Integer.valueOf(0)); bodyvo.setMetadatapath(null); bodyvo.setMetadataproperty(null); bodyvo.setList(true); bodyvo.setListflag(Boolean.valueOf(true)); bodyvo.setShoworder(Integer.valueOf(showOrder++)); bodyvo.setWidth(Integer.valueOf(1)); itemList.add(bodyvo); } BillTempletBodyVO bodyvo = (BillTempletBodyVO) this.bodyVOs[0].clone(); bodyvo.setListshowflag(Boolean.valueOf(true)); bodyvo.setShowflag(Boolean.valueOf(true)); bodyvo.setDatatype(Integer.valueOf(0)); bodyvo.setDefaultshowname(ResHelper.getString("6021interview", "06021interview0068")); bodyvo.setItemkey("waittime"); bodyvo.setPos(Integer.valueOf(0)); bodyvo.setMetadatapath(null); bodyvo.setMetadataproperty(null); bodyvo.setList(true); bodyvo.setListflag(Boolean.valueOf(true)); bodyvo.setShoworder(Integer.valueOf(showOrder++)); bodyvo.setWidth(Integer.valueOf(1)); itemList.add(bodyvo); remove(getBillListPanel()); billTempletVO .setChildrenVO((CircularlyAccessibleValueObject[]) itemList .toArray(new BillTempletBodyVO[0])); getBillListPanel().setListData(new BillListData(billTempletVO)); this.billListPanel.getHeadTable().setSortEnabled(false); GroupableTableHeader header = (GroupableTableHeader) getBillListPanel() .getHeadTable().getTableHeader(); header.addColumnGroup(getColumnGroup(headInfo)); add(getBillListPanel()); } public void handleEvent(AppEvent event) { super.handleEvent(event); //øѡ getBillListPanel().setParentMultiSelect(true); setMultiSelectionEnable(true); //ָѡ setMultiSelectionMode(1); //öѡ setListMultiProp(); if ("Model_Initialized".equalsIgnoreCase(event.getType())) { TableColumnModel columnModel = this.billListPanel.getHeadTable() .getColumnModel(); columnModel.getColumn(columnModel.getColumnCount() - 1) .setCellRenderer(new BillTableCellRenderer() { public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cmp = super .getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); BillModel billModel = (BillModel) table.getModel(); DefaultConstEnum defaultEnum = (DefaultConstEnum) billModel .getValueObjectAt(row, "pk_psndoc.applytype"); Integer typeValue = Integer.valueOf(defaultEnum == null ? 1 : ((Integer) defaultEnum.getValue()) .intValue()); if (RMApplyTypeEnum.INAPPLY.toIntValue() == typeValue .intValue()) { setBackground(Color.orange); } Object obj = billModel.getValueObjectAt(row, "waittime"); if (obj == null) { return cmp; } if (2 < ((Integer) billModel.getValueObjectAt(row, "waittime")).intValue()) { setForeground(Color.RED); } return cmp; } }); //ֶ this.billListPanel.getHeadTable().setSortEnabled(true); this.billListPanel.updateUI(); } } public GeneralVO[] getShowValues() { Object[] objs = getModel().getData().toArray(); if (ArrayUtils.isEmpty(objs)) { return null; } List<GeneralVO> resultList = new ArrayList(); List<String> strConApp = new ArrayList(); for (int j = 0; j < objs.length; j++) { Object obj = objs[j]; AggInterviewVO aggVO = (AggInterviewVO) obj; InterviewVO headVO = aggVO.getInterviewVO(); GeneralVO vo = new GeneralVO(); resultList.add(vo); String[] names = headVO.getAttributeNames(); for (String name : names) { if (!name.equals("pk_psndoc_job")) { if (name.equals("pk_reg_dept")) { if (strConApp.contains(headVO.getPk_reg_dept() + headVO.getPk_reg_job())) { vo.setAttributeValue("hidden", "Y"); vo.setStatus(0); } else { vo.setAttributeValue("hidden", "N"); } strConApp.add(headVO.getPk_reg_dept() + headVO.getPk_reg_job()); vo.setAttributeValue("pk_reg_dept", headVO.getPk_reg_dept()); vo.setAttributeValue("pk_psndoc_job", headVO.getPk_psndoc_job()); } else { vo.setAttributeValue(name, headVO.getAttributeValue(name)); } } } // InterviewPlanVO[] bodyvos = aggVO.getInterviewPlanVOs(); // int bodyLength = ArrayUtils.getLength(bodyvos); // VOUtil.sort(bodyvos, new String[] { "roundnum" }, new int[] { 1 }); // String[] headInfo = getHeadRoundKey(); // for (int i = 0; i < headInfo.length; i++) { // Integer objValue = i >= bodyLength ? Integer.valueOf(-1) // : bodyvos[i].getResult(); // if ((objValue != null) // && (objValue.intValue() != -1) // && (IvReslutEnum.WAIT.toIntValue() != objValue // .intValue()) // && (bodyvos[i].getIvstate() != null) // && (bodyvos[i].getIvstate().intValue() == IVPlanStateEnum.SAVED // .toIntValue())) { // vo.setAttributeValue(headInfo[i], // Integer.valueOf(IvReslutEnum.WAIT.toIntValue())); // } else { // vo.setAttributeValue(headInfo[i], objValue); // } // } // for (int i = 0; i < bodyvos.length; i++) { // if ((bodyvos[i].getBegindate() != null) // && (bodyvos[i].getEnddate() == null)) { // vo.setAttributeValue("waittime", Integer.valueOf(PubEnv // .getServerLiteralDate().getDaysAfter( // bodyvos[i].getBegindate()))); // } // } } return (GeneralVO[]) resultList.toArray(new GeneralVO[0]); } }
true
b2b7a8cc3ce7b8bc812227a8ca59b459469d656f
Java
BaronND/opslabJava
/07_WebServices/src/cxfDemo/JAXWS_DEMO01/client1/jaxwsClient.java
UTF-8
1,000
2.703125
3
[]
no_license
package cxfDemo.JAXWS_DEMO01.client1; /** * 这种调用方式有些问题,暂时而为测试成功 */ import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.soap.SOAPBinding; import cxfDemo.JAXWS_DEMO01.services.helloWS; public class jaxwsClient { private static final QName SERVICE_NAME = new QName("http://services.JAXWS_DEMO01.cxfDemo/","helloWSImplService"); private static final QName PROT_NAME = new QName("http://services.JAXWS_DEMO01.cxfDemo/","helloWSImplPort"); public static void main(String[] args) { //使用服务名创建一个服务 Service service = Service.create(SERVICE_NAME); String address ="http://localhost:8888/services/helloWS"; //为服务添加端口 service.addPort(PROT_NAME, SOAPBinding.SOAP11HTTP_BINDING, address); //获取服务类的对象并处理 helloWS port = service.getPort(helloWS.class); //调用相应的方法 port.sayHello("JAX-WS client"); } }
true