text stringlengths 10 2.72M |
|---|
package net.plazmix.core.api.common.command;
/**
* @author MasterCapeXD
*/
public interface ArgumentInfo extends CommandElement {
CommandElement getParent();
}
|
package Controllers;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import Models.UserLogin;
import Models.Users;
import dao.LoginDao;
/**
* Servlet implementation class LoginCheck
*/
@WebServlet("/LoginCheck")
public class LoginCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginCheck() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
LoginDao loginDAO = new LoginDao();
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
/*
* UserLogin ul=new UserLogin();
* ul.setUsername(request.getParameter("login_username"));
* ul.setPassword(request.getParameter("login_password")); if
* (loginDAO.loginCheck(ul)) { // request.setAttribute("NOTIFICATION",
* "Employee Saved Successfully!"); response.sendRedirect("Home.jsp"); } else {
* response.sendRedirect("SignUp.jsp"); }
*/
//PrintWriter out=response.getWriter();
HttpSession session = request.getSession();
UserLogin login = new UserLogin();
login.setUsername(request.getParameter("login_username"));
login.setPassword(request.getParameter("login_password"));
Users result = loginDAO.loginCheck(login);
if (result.getUserID() > 0) {
session.setAttribute("username", login.getUsername());
int roleID = result.getRoleID();
session.setAttribute("roleid", roleID);
session.setAttribute("classid", result.getClassID());
if(roleID == 2) {
response.sendRedirect("Home.jsp");
}
}
else {
request.setAttribute("submitDone","Invalid Credentials ! Please Try Again ...");
request.getRequestDispatcher("Login.jsp").forward(request, response);
}
}
}
|
package SUT.SE61.Team07;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Collections;
import java.util.OptionalInt;
import java.util.Set;
import java.util.Date;
import javax.persistence.PersistenceException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.Before;
import org.junit.Test;
import SUT.SE61.Team07.Entity.*;
import SUT.SE61.Team07.Repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
@RunWith(SpringRunner.class)
@DataJpaTest
public class TestGender{
@Autowired
private GenderRepository genderrepository;
@Autowired
private TestEntityManager entityManager;
private Validator validator;
@Before
public void setup() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void contextLoads() {
System.out.println("Test Successful");
}
// ทดสอบ save Gender ปกติ
@Test
public void testTestInsertInitialDataSuccess() {
Gender ge = new Gender();
ge.setSex("Female");
try {
entityManager.persist(ge);
entityManager.flush();
} catch (javax.validation.ConstraintViolationException e) {
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("================ from testTestInsertGenderDataSuccess =================");
System.out.println(e.getMessage());
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
assertEquals(violations.isEmpty(), false);
assertEquals(violations.size(), 1);
}
}
// ทดสอบ Sex ห้ามเป็น null
@Test
public void testSexNull() {
Gender ge = new Gender();
ge.setSex(null);
try {
entityManager.persist(ge);
entityManager.flush();
} catch (javax.validation.ConstraintViolationException e) {
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("================ from testSexnulll ===================");
System.out.println(e.getMessage());
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
assertEquals(violations.isEmpty(), false);
assertEquals(violations.size(), 1);
}
}
// ทดสอบ ความยาวของ MinSex ไม่เกิน 3
@Test
public void testMinCustomerAddresssize2() {
Gender ge = new Gender();
ge.setSex("Fe");
try {
entityManager.persist(ge);
entityManager.flush();
fail("Should not pass to this line");
} catch (javax.validation.ConstraintViolationException e) {
System.out.println();
System.out.println();
System.out.println();
System.out.println( "============================== from testMinSexsize3 ===================================");
System.out.println(e);
System.out.println();
System.out.println();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
assertEquals(violations.isEmpty(), false);
assertEquals(violations.size(), 1);
}
}
// ทดสอบ ความยาวของ MaxSex เกิน 6
@Test
public void testMaxInitialNamesize5() {
Gender ge = new Gender();
ge.setSex("Femaleeeee");
try {
entityManager.persist(ge);
entityManager.flush();
fail("Should not pass to this line");
} catch (javax.validation.ConstraintViolationException e) {
System.out.println();
System.out.println();
System.out.println();
System.out.println("============================== from testSexsize6 ==================================================");
System.out.println(e);
System.out.println();
System.out.println();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
assertEquals(violations.isEmpty(), false);
assertEquals(violations.size(), 1);
}
}
}
|
package com.jachin.shopping.controller;
import com.jachin.shopping.bean.CartUserBook;
import com.jachin.shopping.bean.Msg;
import com.jachin.shopping.po.Cart;
import com.jachin.shopping.service.CartService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class CartController {
private CartService cartService = new CartService();
/**
* 加入购物车
* @param bookId ;
* @param httpSession;
* @return JSON
*/
@RequestMapping(value = "/cart/{bookId}",method = RequestMethod.POST)
@ResponseBody
public Msg addToCart(@PathVariable("bookId")Integer bookId, HttpSession httpSession){
Cart cart = new Cart();
cart.setUserid((Integer) httpSession.getAttribute("userId"));
cart.setBookid(bookId);
cart.setCount(1);
cartService.addToCart(cart);
return Msg.success();
}
/**
* 跳转到购物车
* @param httpSession;
* @return JSON
*/
@RequestMapping(value = "/cart",method = RequestMethod.GET)
@ResponseBody
public Msg toCart(HttpSession httpSession){
int id = (Integer) httpSession.getAttribute("userId");
List<CartUserBook> carts = cartService.getCart(id);
return Msg.success().add("cartInfo",carts);
}
/**
* 修改数量
* @return Json
*/
@RequestMapping(value = "/cart",method = RequestMethod.PUT)
@ResponseBody
public Msg toCart(@RequestParam("cartid")Integer cartId,
@RequestParam("count")Integer count,
@RequestParam("bookid")Integer bookId){
Cart cart = new Cart();
cart.setCartid(cartId);
cart.setCount(count);
cart.setBookid(bookId);
if(cartService.editCount(cart)){
return Msg.success();
}
return Msg.fail();
}
// 清空购物车
@RequestMapping(value = "/cart",method = RequestMethod.DELETE)
@ResponseBody
public Msg deleteAll(HttpSession httpSession){
int userId = (Integer) httpSession.getAttribute("userId");
cartService.deleteAll(userId);
return Msg.success();
}
// 删除单项
@RequestMapping(value = "/cart/{cartid}", method = RequestMethod.DELETE)
@ResponseBody
public Msg deleteById(@PathVariable("cartid")Integer cartId){
cartService.deleteById(cartId);
return Msg.success();
}
}
|
package ctci.chap1;
/*
* Assumptions:
* Empty and null strings are not palindromes
* We are only dealing with ascii characters [0-127]
*/
public class PalindromePermutation{
public static void main(String args[]){
}
public static boolean canBePalindrome(String str){
if(str == null || str.isEmpty()){ return false; }
// We don't actually care about the count, only whether the character appears an even or odd number of times.
boolean[] charIsOdd = new boolean[128]; // defaults value is false (which is what we want)
int numOdds = 0;
for(char c: str.toCharArray()){
if(charIsOdd[c]){
numOdds--;
}else{
numOdds++;
}
charIsOdd[c] = !charIsOdd[c];
}
if(numOdds > 1){
return false;
}else{
return true;
}
}
}
|
2017.02.23.
2. Java EA
public osztály }
metódus } bárhonna hivatkozható
mező }
... }
public NAH osztály }
félnyilvános (package private) metódus } csak a definíciót tartalmazó csomagban
mező }
... }
package misc;
public class Date {
private int year;
// ...
package int setYear() {...}
// ...
int hel???(...) {...}
} // misc csomagban van, más csomagból is használható
class Date {
private int year;
// ...
} // névtelen csimagba kerül, csak ebben a csomagban használható
osztály teljes neve: a csomagnévvel minősített név
osztály rövid neve: a deklarációban szereplő név, a csomagnév nélkül
csomagok rendszere hierarchikus, alcsomagok használatók
server.data.types csomagnév
server.data.types.Employee
fejlesztők globálisan egyedk névtereket próbálnak használni, ehhez "mélyen hierarchikus" csomagnevek
hu.elte.kto.analyzer.server...
hu.elte.kto -> fejlesztő (cég, termék) azonosítása
kül forrásból származó kódok összeépítésénél nem lesznek névkonfliktusok
csoamag nem csak névtér, azaz a program logikai tájolása, hanem a forráskód fizikai szervezésének is alapja
prg kód a fájlrendszerben
--- ---------------------
csomag könyvtár
alcsomag alkönyvtár
...
fordítási egység forrásfájl
fordítási egység
----------------
- opcionális: package utasítás
- 0, 1 v. több improt utasítás
import java.util.List;
- egy (esetleg több) típusdefiníció (pl osztálydefiníció)
legfeljebb egy publikus (többi félnyilvános segédosztály, - típus), ennek neve = forrásfájl neve
- általában 1 típus 1 fájlban
- érdemes mindig egyszer??? on ~ fh.
java csomag és alcsomagjai szabványos programkönyvtár egy része
dolgoznak egy projekten, egy munkakönyvtár (working directory)
C:\Users\kto\nalyzer
/home/kto/analyzer
ezen belül a csomaghierarchiát tükrözi a könyvtárhierarchia
a negfelelő alkönyvtárba tesszük a forrsáfjálokat és bájtkódokat
WD
- server
- data
- types
- Employee.java
- Employee.class
- client
- web
- gui
C:\Users\kto\analyzer> dir ~kto/analyzer $
server
client
C:\Users\kto\analyzer> javac server\data\types\Employee.java // javac "teljes elérési út" VAN kiterjesztés
C:\Users\kto\analyzer> java server\data\types\Employee // java "osztály neve" NINCS kiterjesztés
nem cd-zünk beljebb!
belső állapot ~ típusinvariáns
műveletek ~ megőrzik, konzisztens állapotból konzisztens állapotba
konstrukció ~ alőállítja (konzisztens állapotot)
pl. konstruktorban -> metódusnév?
package misc; // misc.Date
public class Date {
private int year;
// ...
public void setYear(int y) {
if (month == 2 && day == 29 && !isLeapYear(y)) {
throw new IllegalArgumentException();
}
year = y;
}
}
public class Date {
public Date(int y, int m, int d) {
// ellenőrzések, throw new Illegal...
year = y;
month = m;
day = d;
}
private int year, month, day;
}
new Date(2017, 2, 23); // konstruktor hívása
public class Date {
// nincs konsi
}
new Date();
v // fordító
public class Date {
public Date() {}
// ...
}
a generált konsit nevezik "default konstruktornak"
minden osztályban van konsi
- explicit (mi írtuk)
pm élküli v pm-es (igény szerint)
- implicit: default
pm nélküli
létrehozás: mint pl metódusoknál
konsi vs. metódus
szintaktika nincs return type van return type (void, int, ...)
használat csak new-val egy már létrehzott objektumon hívható meg
class Date {
private int year = 2000;
private int month = 1;
private int day = 1;
// nem írok konsit
// konsi felül tudja írni ezeket az étékeket
}
a new Date() során lefut a default konsi és "közben" beállítódnak a mezők az inicializáló kifejezésben megadott értékre, vagy ha nincs ilyen akk nullaszerű értékre
0, 00, '\n000', false, referenciáknál null
class dfgdfg??? {
// ???
}
private int year = 0, month = 0, day = 0;
class Date {
private int year, month, day;
{year = 2022;}
// nem metódus, nem konsi, hanem inicializátor blokk (ált ne mhasználjuk)
}
metódus:
--------
- specifikációs rész (láthatóság, return type, náv, formális pm, stb)
- törzs {...}
utasítássorozat
- változódeklaráció
- értékadás
- ciklus : - while (elöltesztelős)
- do-while (hátultesztelős)
- for (léptető)
- inhanced for (adatszerkezetet bejáró)
- elágazás: - if
- switch
- assert
- return int
- throw (kivétel kiváltása)
- break, continue (nem strukturált prog) -> ritkán, jó okkal
if ( x > 0)
--x;
if ( x > 0) {
--x;
} // uaz, de ez preferált, plusz fáradság, kevesebb hiba
if (x > 0)
--x;
++y; // tördelés és jelentés különbözik
=>
if (x > 0)
--x;
++y;
=>
if (x > 0) {
--x;
}
++y;
!=>
if (x > 0) {
--x;
++y;
}
if (x > 0) {
--x;
} else {
if (x < 0) {
++x;
}
}
if (x > 0) {
--x;
} else if (x < 0) {
++x;
}
}
if-then-else probléma (chellenyi? elve?/else?)
if (x > 0)
if (y > 0)
x += y;
else
x = 0;
=>
if (x > 0)
if (y > 0)
x += y;
else
x = 0;
// tördelés és a jelentés nincs összehangban -> programozói hiba |
package com.cxjd.nvwabao.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import com.cxjd.nvwabao.Activity.CirclesMainPage;
import com.cxjd.nvwabao.Activity.PeopleSendTieActivity;
import com.cxjd.nvwabao.R;
import com.cxjd.nvwabao.adapter.CircleAdapter;
import com.cxjd.nvwabao.adapter.CircleFragmentAdapter;
import com.cxjd.nvwabao.bean.Circles;
import com.cxjd.nvwabao.bean.PeopleChat;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by 李超 on 2017/10/29.
*/
public class CircleFragment extends Fragment implements View.OnClickListener {
private List<PeopleChat> peopleChatList = new ArrayList<>(); //总数据
private List<PeopleChat> someList = new ArrayList<>(); //取部分数据 每次刷新都增加
private ListView list_people;
private CircleFragmentAdapter circleFragmentAdapter;
private View footer; //底部刷新
private ProgressBar footProgressBar;
//是否加载标示
int isLoading = 1;
TextView loading_text;
/**
* 超 数据 顶
*/
private View view;
private SwipeRefreshLayout mySRL;
private List<Circles> circlesList = new ArrayList<>();
private int heads[] = {R.drawable.cr_jiuyibang,R.drawable.cr_meirong,R.drawable.cr_fuke,R.drawable.cr_liuchan,R.drawable.cr_gaoxueya,
R.drawable.cr_tangniu,R.drawable.cr_beiyun,R.drawable.cr_buyu,R.drawable.cr_yangsheng,R.drawable.cr_jianzhouyan,
R.drawable.cr_nanren};
private String titles[] = {"就医帮帮团","美容美体","妇科疾病","避孕流产","高血压","糖尿病","备孕怀孕","不孕不育","中医养生","肩周炎","男人帮"};
private String chengYuan[] = {"60.0万","59.9万","56.4万","59.9万","60.1万","60.5万","59.8万","54.7万",
"59.9万","71.3万","59.9万"};
private String tieZi[] = {"566","4989","2737","2168","427","589","4789","23","47","456","789"};
//圈子ListView
android.widget.ListView listView;
private View footerView;
//用来可显示的最后一条数据的索引
private int visibleLasIndex;
//刷新的条件,适配器中的个数
private int i = 6;
//适配器
CircleAdapter adapter;
//handler
private Handler refreshHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0x101:
Circles circles07 = new Circles(heads[6],titles[6],"6",chengYuan[6],tieZi[6],6);
Circles circles08 = new Circles(heads[7],titles[7],"5",chengYuan[7],tieZi[7],7);
Circles circles09 = new Circles(heads[8],titles[8],"4",chengYuan[8],tieZi[8],8);
Circles circles10 = new Circles(heads[9],titles[9],"3",chengYuan[9],tieZi[9],9);
Circles circles11 = new Circles(heads[10],titles[10],"2",chengYuan[10],tieZi[10],10);
circlesList.addAll(Arrays.asList(circles07,circles08,circles09,circles10,circles11));
adapter.notifyDataSetChanged();
listView.removeFooterView(footerView);
break;
}
}
};
private void initListView(View view) {
adapter = new CircleAdapter(getContext(),R.layout.cir_circles_item,circlesList,0);
listView = view.findViewById(R.id.cir_lv_circle);
footerView = getLayoutInflater().inflate(R.layout.loading_layout,null);
listView.addFooterView(footerView);
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
if (adapter.getCount() == i){
i++;
new LoadDataThread().start();
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount , int totalItemCount) {
//减去最后一个加载中那条
visibleLasIndex = firstVisibleItem + visibleItemCount - 1;
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Circles circles = circlesList.get(position);
Intent intent = new Intent(getContext(), CirclesMainPage.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable("circles",circles);
intent.putExtras(mBundle);
startActivity(intent);
}
});
}
private void initCircles() {
Circles circles01 = new Circles(heads[0],titles[0],"1",chengYuan[0],tieZi[0],0);
Circles circles02 = new Circles(heads[1],titles[1],"2",chengYuan[1],tieZi[1],1);
Circles circles03 = new Circles(heads[2],titles[2],"3",chengYuan[2],tieZi[2],2);
Circles circles04 = new Circles(heads[3],titles[3],"4",chengYuan[3],tieZi[3],3);
Circles circles05 = new Circles(heads[4],titles[4],"5",chengYuan[4],tieZi[4],4);
Circles circles06 = new Circles(heads[5],titles[5],"6",chengYuan[5],tieZi[5],5);
circlesList.addAll(Arrays.asList(circles01,circles02,circles03,circles04,circles05,circles06));
}
/**
* 模拟加载数据的线程
*/
class LoadDataThread extends Thread{
@Override
public void run() {
try{
Thread.sleep(3000);
}catch (InterruptedException e){
e.printStackTrace();
}
//通过handler发送一个更新数据的标题
refreshHandler.sendEmptyMessage(0x101);
}
}
/**
* 超 数据 尾部s
*/
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_circle,container,false);
//设置病人信息
setDate(view);
/**超头
*/
TextView textView = view.findViewById(R.id.fragment_title);
textView.setText(R.string.circle);
initListView(view);
initCircles();
/**超尾巴
*/
//设置TabHost组件
final TabHost tabHost = view.findViewById(R.id.cr_tabhost);
//初始化TabHost容器
tabHost.setup();
//创建第一个Tab页面
TabHost.TabSpec tab1 = tabHost.newTabSpec("tab1").setIndicator("动态").setContent(R.id.cr_tab_01);
//添加第一个标签页
tabHost.addTab(tab1);
//创建第二个Tab页面
TabHost.TabSpec tab2 = tabHost.newTabSpec("tab2").setIndicator("圈子").setContent(R.id.cr_tab_02);
//添加第二个Tab页面
tabHost.addTab(tab2);
//list_people.setOnItemClickListener(this);//废弃点击事件 换为adapter中 item内部多个点击事件
System.out.println("数量为---------------------------------"+peopleChatList.size());
initview(view);
//加底部刷新
addListViewFooterView();
list_people.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// 当不滚动时
if (scrollState == SCROLL_STATE_IDLE) {
//判断是否滚动到底部
if (isLoading == 1 && absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
List<PeopleChat> otherList = new ArrayList<>();
for (int i = peopleChatList.size() - 10; i <= peopleChatList.size() - 8; i++) {
otherList.add(peopleChatList.get(i));
}
someList.addAll(otherList);
circleFragmentAdapter.notifyDataSetChanged();
Log.i("testUpdate", "run: 进入 1");
}
}, 3000);
isLoading++;
System.out.println("进入刷新 +++++++" + someList.size());
return;
} else if (isLoading == 2 && absListView.getLastVisiblePosition() == absListView.getCount() - 1){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
List<PeopleChat> otherList = new ArrayList<>();
for (int i = peopleChatList.size() - 7; i <= peopleChatList.size() - 5; i++) {
otherList.add(peopleChatList.get(i));
}
someList.addAll(otherList);
circleFragmentAdapter.notifyDataSetChanged();
Log.i("testUpdate", "run: 进入 2");
}
}, 6000);
System.out.println("进入刷新 +++++++" + someList.size());
isLoading++;
return;
}else if (isLoading == 3 && absListView.getLastVisiblePosition() == absListView.getCount() - 1){
loading_text.setText("网络环境较差!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
List<PeopleChat> otherList = new ArrayList<>();
for (int i = peopleChatList.size() - 4; i <= peopleChatList.size() - 3; i++) {
otherList.add(peopleChatList.get(i));
}
someList.addAll(otherList);
circleFragmentAdapter.notifyDataSetChanged();
Log.i("testUpdate", "run: 进入 3");
}
}, 10000);
isLoading++;
return;
}else if (isLoading == 4 && absListView.getLastVisiblePosition() == absListView.getCount() - 1){
loading_text.setText("网络环境较差!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
List<PeopleChat> otherList = new ArrayList<>();
for (int i = peopleChatList.size() - 2; i <= peopleChatList.size() - 1; i++) {
otherList.add(peopleChatList.get(i));
}
someList.addAll(otherList);
circleFragmentAdapter.notifyDataSetChanged();
Log.i("testUpdate", "run: 进入 4");
}
}, 15000);
isLoading++;
return;
}
}
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
return view;
}
private void initview(View view) {
TextView titile = (TextView) view.findViewById(R.id.fragment_title);
titile.setText("动态");
ImageView sendTie = (ImageView) view.findViewById(R.id.circle_send_tie);
sendTie.setOnClickListener(this);
loading_text = (TextView) view.findViewById(R.id.loading_text);
list_people = (ListView)view.findViewById(R.id.list_people);
//关联数据和子布局
circleFragmentAdapter = new CircleFragmentAdapter(getActivity(), R.layout.fragment_circle_context, someList);
//绑定数据和适配器
list_people.setAdapter(circleFragmentAdapter);
}
//废弃点击事件 换为adapter中 item内部多个点击事件
/* @Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
PeopleChat peopleChat = peopleChatList.get(position);
Intent intent = new Intent(getActivity(), PeopleChatActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", peopleChat.getPeopleId());
intent.putExtras(bundle);
startActivity(intent);
}*/
//设置病人头像和各种信息
public void setDate(View view) {
if (peopleChatList != null || !peopleChatList.isEmpty()) {
peopleChatList.clear();
}
peopleChatList = DataSupport.findAll(PeopleChat.class);
if (peopleChatList.size() < 1) {
String[] names = {"15702456985", "15896788850", "13969652586", "与一", "枯木"
, "15398080200", "天涯", "13996850330", "CC", "奋斗人生"
, "17455562855", "16598840023", "苦涩咖啡", "18995002028", "15879633029"};
int[] ids = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
String[] chats = {"油性皮肤毛孔粗大容易长痘痘印都有点多了每次长了一颗好了别处又会长一颗",
"孩子刚出生几个小时,检查结果是血象高的离谱41.1,而且不怎么爱动,是怎么回事呢?",
"3岁女儿发烧过度在重病科,已经从卫辉医院转移到郑州医院了,我都快吓得不行了,已经住院2天了,1天半没醒没吃饭,我都快崩溃了",
"用盐洗脸,脸肿了,还发红,还热,是怎么回事,在家应该用些什么?",
"脸蛋靠鼻子眼睛位置上长痘痘,怎么办啊?是青春痘吗?阿达帕林凝胶用过但是额头还行,脸上起皮…",
"我怀孕期间TSH偏高,一直吃优甲乐。现在哺乳期,42天检查结果是4.7显示有点高。母乳有影响吗?",
"这几个月月经都是推迟的,上次来月经是1/22,这次是3/24,月经刚过两天,今天发生关系,会不会怀孕?需不需要吃紧急避孕药?!",
"骨盆疼,尿道骨头疼,大胯疼什么原因,有时小肚子也跟着疼,不知道怎么回事",
"全麻手术插管子会伤害咽喉部位吗?如果伤害了几天会好?如果伤害了咽喉部位,手术后三天内吃了食物万一食物中有病毒,会进入咽喉部位伤害的粘膜处吗?",
"宝宝的头发有圈枕秃,查了微量元素钙并不缺少,医生建议吃鱼肝油和维D促进钙吸收。去药店买药师说维D跟鱼肝油是同一种营养物质。可以给他吃维D3吗?",
"出现腰酸痛,下腹部胀痛,尿黄,尿不尽,尿分叉,龟头和睾丸凉,附睾坠痛,性功能明显减退问问用些什么药",
"我在嘴唇下面长了一个风刺,然后嘴唇都是肿的,下巴,脸也有些肿了,去诊所,医生说吃消炎药就行了,让它慢慢好,但是真的很疼,请问应该怎么办?",
"我是1月8号月经结束,目前已怀孕多久了,什么时候可以去做b超",
"怎样服用黄体酮推迟月经一天吃多少我买的是一粒100毫克应该怎么吃。"
,"宫颈息肉,3型转化区,之前有宫颈炎、盆腔积液,其他有甲亢,身体虚"
};
int[] imagesIds = {R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people
, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people
, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people, R.drawable.a1_people};
int[] zans = {1, 2, 1, 1, 1, 2, 3, 1, 4, 1, 1, 2, 3, 1, 5};
/*String[] infos = {"还好咯","去死吧","222","333",""
,"aa","vv","ssss","mmm","杀杀杀"
,"啊啊啊","买买买","来来来","方法","试试"};*/
String[] address = {"合肥市","长春市","南京市","杭州市","沈阳市"
,"福州市","杭州市","南昌市","广安市","青岛市"
,"聊城市","福州市","福州市","西安市","大庆市"};
String[] from = {"就医帮帮团","亲子育儿","妇科疾病","美容美体","美容美体"
,"备孕怀孕","妇科疾病","男人帮","就医帮帮团","就医帮帮团"
,"男人帮","美容美体","就医帮帮团","妇科疾病","就医帮帮团"};
for (int i = 0; i < chats.length; i++) {
PeopleChat peopleChat = new PeopleChat();
System.out.println(ids[i]);
peopleChat.setPeopleId(ids[i]);
peopleChat.setName(names[i]);
peopleChat.setChat(chats[i]);
peopleChat.setImageId(imagesIds[i]);
peopleChat.setZan(zans[i]);
//peopleChat.setInfo(infos[i]);
peopleChat.setAddress(address[i]);
peopleChat.setFrom(from[i]);
peopleChat.setZanAble(true);
peopleChat.save();
peopleChatList.add(peopleChat);
}
Collections.reverse(peopleChatList);
if (someList != null || !someList.isEmpty()) {
someList.clear();
}
for (int i = 0;i<=peopleChatList.size()-11;i++) {
someList.add(peopleChatList.get(i));
}
} else {
//清空 PeopleChat 表使用
/* DataSupport.deleteAll(PeopleChat.class);
System.out.println("进入删除"+peopleChatList.size());*/
Collections.reverse(peopleChatList);
if (someList != null || !someList.isEmpty()) {
someList.clear();
}
for (int i = 0;i<=peopleChatList.size()-11;i++) {
someList.add(peopleChatList.get(i));
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.circle_send_tie:
//发帖
Intent intent = new Intent(getActivity(), PeopleSendTieActivity.class);
startActivity(intent);
break;
}
}
//返回此页面刷新
@Override
public void onResume() {
super.onResume();
setDate(getView());
initview(getView());
isLoading = 1;
}
private void addListViewFooterView() {
footer = getActivity().getLayoutInflater().inflate(R.layout.a1_activity_chat_update, null);
list_people.addFooterView(footer);
}
/*合并准备*/}
/**
*
*/
//handler
|
package org.ix.grails.plugins.camel;
/**
* Created by IntelliJ IDEA.
* User: navtach
* Date: Mar 16, 2009
* Time: 3:56:43 PM
* To change this template use File | Settings | File Templates.
*/
public interface GrailsRouteClassProperty {
public static final String CONFIGURE = "configure";
public static final String ROUTE = "Route";
}
|
package com.tencent.mm.api;
import android.content.Intent;
import com.tencent.mm.kernel.c.a;
import com.tencent.mm.protocal.c.biy;
import com.tencent.mm.protocal.c.bja;
import java.util.ArrayList;
public interface h extends a {
void a(Intent intent, biy biy, int i);
void a(Intent intent, bja bja, int i);
boolean cB(String str);
ArrayList<String> cC(String str);
}
|
package com.tencent.mm.g.a;
public final class fj$a {
public String fileName;
}
|
package com.company.TemperatureTasks;
public class TemperatureDisplay {
public static void main(String[] args) {
Temperature now1 = new Temperature(15, "20-01-2020", "20:01");
showDate(now1);
showHour(now1);
showTemperature(now1);
Temperature now2 = new Temperature(22, "30.06.2020", "18:30");
showDate(now2);
showHour(now2);
showTemperature(now2);
}
public static void showTemperature(Temperature tempNew) {
System.out.println("temperatura wynosi: " + tempNew.getTemperature());
}
public static void showDate(Temperature actualDate) {
System.out.println(" W dniu : " + actualDate.getDate());
}
public static void showHour(Temperature hoursNew) {
System.out.println("o godzinie: " + hoursNew.getHours());
}
}
|
/*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle 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 sarong;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import sarong.discouraged.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Results for all benchmarks on an i7-8750H CPU clocked at 2.20GHz :
* <br>
* <pre>
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureAltThrustDetermine avgt 5 2.636 ± 0.006 ns/op
* RNGBenchmark.measureBasicRandom32 avgt 5 2.966 ± 0.004 ns/op
* RNGBenchmark.measureBasicRandom32Int avgt 5 2.178 ± 0.021 ns/op
* RNGBenchmark.measureBasicRandom32IntR avgt 5 2.383 ± 0.027 ns/op
* RNGBenchmark.measureBasicRandom32R avgt 5 3.212 ± 0.010 ns/op
* RNGBenchmark.measureBasicRandom64 avgt 5 2.549 ± 0.020 ns/op
* RNGBenchmark.measureBasicRandom64Int avgt 5 2.660 ± 0.009 ns/op
* RNGBenchmark.measureBasicRandom64IntR avgt 5 2.896 ± 0.006 ns/op
* RNGBenchmark.measureBasicRandom64R avgt 5 2.822 ± 0.015 ns/op
* RNGBenchmark.measureChurro32 avgt 5 6.071 ± 0.052 ns/op
* RNGBenchmark.measureChurro32Int avgt 5 3.663 ± 0.003 ns/op
* RNGBenchmark.measureChurro32IntR avgt 5 4.460 ± 0.021 ns/op
* RNGBenchmark.measureChurro32R avgt 5 8.272 ± 0.056 ns/op
* RNGBenchmark.measureDervish avgt 5 3.133 ± 0.038 ns/op
* RNGBenchmark.measureDervishInt avgt 5 3.248 ± 0.042 ns/op
* RNGBenchmark.measureDervishIntR avgt 5 3.588 ± 0.009 ns/op
* RNGBenchmark.measureDervishR avgt 5 3.575 ± 0.117 ns/op
* RNGBenchmark.measureDirk avgt 5 3.137 ± 0.006 ns/op
* RNGBenchmark.measureDirkDetermine avgt 5 3.016 ± 0.011 ns/op
* RNGBenchmark.measureDirkInt avgt 5 3.135 ± 0.017 ns/op
* RNGBenchmark.measureDirkIntR avgt 5 3.576 ± 0.013 ns/op
* RNGBenchmark.measureDirkR avgt 5 3.559 ± 0.022 ns/op
* RNGBenchmark.measureDizzy32 avgt 5 5.429 ± 0.066 ns/op
* RNGBenchmark.measureDizzy32Int avgt 5 3.382 ± 0.011 ns/op
* RNGBenchmark.measureDizzy32IntNative1 avgt 5 3.479 ± 0.029 ns/op
* RNGBenchmark.measureDizzy32IntNative2 avgt 5 3.479 ± 0.009 ns/op
* RNGBenchmark.measureDizzy32IntR avgt 5 3.949 ± 0.037 ns/op
* RNGBenchmark.measureDizzy32R avgt 5 6.154 ± 0.076 ns/op
* RNGBenchmark.measureFlap avgt 5 2.857 ± 0.014 ns/op
* RNGBenchmark.measureFlapInt avgt 5 2.380 ± 0.038 ns/op
* RNGBenchmark.measureFlapIntR avgt 5 2.703 ± 0.052 ns/op
* RNGBenchmark.measureFlapR avgt 5 3.210 ± 0.018 ns/op
* RNGBenchmark.measureGWT avgt 5 4.293 ± 0.026 ns/op
* RNGBenchmark.measureGWTInt avgt 5 2.918 ± 0.040 ns/op
* RNGBenchmark.measureGWTNextInt avgt 5 2.914 ± 0.020 ns/op
* RNGBenchmark.measureIsaac avgt 5 5.141 ± 0.012 ns/op
* RNGBenchmark.measureIsaac32 avgt 5 8.779 ± 0.069 ns/op
* RNGBenchmark.measureIsaac32Int avgt 5 5.242 ± 0.021 ns/op
* RNGBenchmark.measureIsaac32IntR avgt 5 5.682 ± 0.018 ns/op
* RNGBenchmark.measureIsaac32R avgt 5 9.753 ± 0.066 ns/op
* RNGBenchmark.measureIsaacInt avgt 5 5.229 ± 0.037 ns/op
* RNGBenchmark.measureIsaacIntR avgt 5 5.590 ± 0.064 ns/op
* RNGBenchmark.measureIsaacR avgt 5 5.540 ± 0.190 ns/op
* RNGBenchmark.measureJDK avgt 5 17.561 ± 0.054 ns/op
* RNGBenchmark.measureJDKInt avgt 5 8.767 ± 0.052 ns/op
* RNGBenchmark.measureJab63 avgt 5 2.397 ± 0.011 ns/op
* RNGBenchmark.measureJab63Int avgt 5 2.512 ± 0.013 ns/op
* RNGBenchmark.measureJab63IntR avgt 5 2.761 ± 0.043 ns/op
* RNGBenchmark.measureJab63R avgt 5 2.691 ± 0.030 ns/op
* RNGBenchmark.measureLap avgt 5 2.415 ± 0.027 ns/op
* RNGBenchmark.measureLapInt avgt 5 2.530 ± 0.024 ns/op
* RNGBenchmark.measureLapIntR avgt 5 2.892 ± 0.065 ns/op
* RNGBenchmark.measureLapR avgt 5 2.761 ± 0.013 ns/op
* RNGBenchmark.measureLathe32 avgt 5 4.296 ± 0.005 ns/op
* RNGBenchmark.measureLathe32Int avgt 5 2.915 ± 0.022 ns/op
* RNGBenchmark.measureLathe32IntR avgt 5 3.244 ± 0.070 ns/op
* RNGBenchmark.measureLathe32R avgt 5 4.873 ± 0.028 ns/op
* RNGBenchmark.measureLathe64 avgt 5 2.917 ± 0.028 ns/op
* RNGBenchmark.measureLathe64Int avgt 5 3.021 ± 0.036 ns/op
* RNGBenchmark.measureLathe64IntR avgt 5 3.432 ± 0.011 ns/op
* RNGBenchmark.measureLathe64R avgt 5 3.192 ± 0.008 ns/op
* RNGBenchmark.measureLight avgt 5 2.826 ± 0.017 ns/op
* RNGBenchmark.measureLight32 avgt 5 4.672 ± 0.038 ns/op
* RNGBenchmark.measureLight32Int avgt 5 2.881 ± 0.665 ns/op
* RNGBenchmark.measureLight32IntR avgt 5 3.280 ± 0.640 ns/op
* RNGBenchmark.measureLight32R avgt 5 5.463 ± 0.008 ns/op
* RNGBenchmark.measureLightDetermine avgt 5 2.805 ± 0.007 ns/op
* RNGBenchmark.measureLightInt avgt 5 2.830 ± 0.007 ns/op
* RNGBenchmark.measureLightIntR avgt 5 3.192 ± 0.032 ns/op
* RNGBenchmark.measureLightR avgt 5 3.151 ± 0.027 ns/op
* RNGBenchmark.measureLinnorm avgt 5 2.620 ± 0.026 ns/op
* RNGBenchmark.measureLinnormDetermine avgt 5 2.770 ± 0.019 ns/op
* RNGBenchmark.measureLinnormInt avgt 5 2.665 ± 0.018 ns/op
* RNGBenchmark.measureLinnormIntR avgt 5 2.875 ± 0.009 ns/op
* RNGBenchmark.measureLinnormR avgt 5 2.989 ± 0.014 ns/op
* RNGBenchmark.measureLobster32 avgt 5 4.654 ± 0.178 ns/op
* RNGBenchmark.measureLobster32Int avgt 5 3.039 ± 0.026 ns/op
* RNGBenchmark.measureLobster32IntR avgt 5 3.346 ± 0.029 ns/op
* RNGBenchmark.measureLobster32R avgt 5 5.140 ± 0.025 ns/op
* RNGBenchmark.measureLongPeriod avgt 5 3.530 ± 0.011 ns/op
* RNGBenchmark.measureLongPeriodInt avgt 5 3.607 ± 0.031 ns/op
* RNGBenchmark.measureLongPeriodIntR avgt 5 4.095 ± 0.018 ns/op
* RNGBenchmark.measureLongPeriodR avgt 5 3.955 ± 0.038 ns/op
* RNGBenchmark.measureMesh avgt 5 3.298 ± 0.022 ns/op
* RNGBenchmark.measureMeshInt avgt 5 3.243 ± 0.008 ns/op
* RNGBenchmark.measureMeshIntR avgt 5 3.718 ± 0.068 ns/op
* RNGBenchmark.measureMeshR avgt 5 3.701 ± 0.010 ns/op
* RNGBenchmark.measureMiniMover64 avgt 5 2.398 ± 0.006 ns/op
* RNGBenchmark.measureMiniMover64Int avgt 5 2.447 ± 0.010 ns/op
* RNGBenchmark.measureMiniMover64IntR avgt 5 2.635 ± 0.017 ns/op
* RNGBenchmark.measureMiniMover64R avgt 5 2.634 ± 0.020 ns/op
* RNGBenchmark.measureMizuchi avgt 5 2.673 ± 0.019 ns/op
* RNGBenchmark.measureMizuchiInt avgt 5 2.704 ± 0.012 ns/op
* RNGBenchmark.measureMizuchiIntR avgt 5 2.939 ± 0.010 ns/op
* RNGBenchmark.measureMizuchiR avgt 5 3.008 ± 0.042 ns/op
* RNGBenchmark.measureMolerat32 avgt 5 5.033 ± 0.040 ns/op
* RNGBenchmark.measureMolerat32Int avgt 5 3.050 ± 0.009 ns/op
* RNGBenchmark.measureMolerat32IntR avgt 5 3.480 ± 0.012 ns/op
* RNGBenchmark.measureMolerat32R avgt 5 5.426 ± 0.010 ns/op
* RNGBenchmark.measureMotor avgt 5 3.768 ± 0.023 ns/op
* RNGBenchmark.measureMotorInt avgt 5 3.701 ± 0.007 ns/op
* RNGBenchmark.measureMotorIntR avgt 5 4.201 ± 0.012 ns/op
* RNGBenchmark.measureMotorR avgt 5 4.098 ± 0.006 ns/op
* RNGBenchmark.measureMover32 avgt 5 3.822 ± 0.015 ns/op
* RNGBenchmark.measureMover32Int avgt 5 2.621 ± 0.013 ns/op
* RNGBenchmark.measureMover32IntR avgt 5 2.775 ± 0.032 ns/op
* RNGBenchmark.measureMover32R avgt 5 4.209 ± 0.063 ns/op
* RNGBenchmark.measureMover64 avgt 5 2.619 ± 0.025 ns/op
* RNGBenchmark.measureMover64Int avgt 5 2.636 ± 0.033 ns/op
* RNGBenchmark.measureMover64IntR avgt 5 2.772 ± 0.032 ns/op
* RNGBenchmark.measureMover64R avgt 5 2.733 ± 0.169 ns/op
* RNGBenchmark.measureMoverCounter64 avgt 5 2.463 ± 0.006 ns/op
* RNGBenchmark.measureMoverCounter64Int avgt 5 2.466 ± 0.016 ns/op
* RNGBenchmark.measureMoverCounter64IntR avgt 5 2.691 ± 0.017 ns/op
* RNGBenchmark.measureMoverCounter64R avgt 5 2.687 ± 0.016 ns/op
* RNGBenchmark.measureOrbit avgt 5 2.916 ± 0.012 ns/op
* RNGBenchmark.measureOrbitA avgt 5 2.914 ± 0.005 ns/op
* RNGBenchmark.measureOrbitB avgt 5 3.027 ± 0.010 ns/op
* RNGBenchmark.measureOrbitC avgt 5 3.003 ± 0.021 ns/op
* RNGBenchmark.measureOrbitD avgt 5 2.914 ± 0.031 ns/op
* RNGBenchmark.measureOrbitE avgt 5 3.260 ± 0.027 ns/op
* RNGBenchmark.measureOrbitF avgt 5 2.905 ± 0.026 ns/op
* RNGBenchmark.measureOrbitG avgt 5 3.027 ± 0.013 ns/op
* RNGBenchmark.measureOrbitH avgt 5 2.905 ± 0.026 ns/op
* RNGBenchmark.measureOrbitI avgt 5 3.017 ± 0.012 ns/op
* RNGBenchmark.measureOrbitInt avgt 5 3.018 ± 0.017 ns/op
* RNGBenchmark.measureOrbitIntR avgt 5 3.357 ± 0.009 ns/op
* RNGBenchmark.measureOrbitJ avgt 5 2.781 ± 0.009 ns/op
* RNGBenchmark.measureOrbitK avgt 5 2.895 ± 0.011 ns/op
* RNGBenchmark.measureOrbitL avgt 5 2.753 ± 0.012 ns/op
* RNGBenchmark.measureOrbitM avgt 5 3.141 ± 0.011 ns/op
* RNGBenchmark.measureOrbitN avgt 5 3.147 ± 0.022 ns/op
* RNGBenchmark.measureOrbitO avgt 5 3.008 ± 0.031 ns/op
* RNGBenchmark.measureOrbitR avgt 5 3.297 ± 0.019 ns/op
* RNGBenchmark.measureOriole32 avgt 5 4.691 ± 0.005 ns/op
* RNGBenchmark.measureOriole32Int avgt 5 3.134 ± 0.040 ns/op
* RNGBenchmark.measureOriole32IntR avgt 5 3.522 ± 0.017 ns/op
* RNGBenchmark.measureOriole32R avgt 5 5.153 ± 0.070 ns/op
* RNGBenchmark.measureOtter32 avgt 5 4.958 ± 0.009 ns/op
* RNGBenchmark.measureOtter32Int avgt 5 3.121 ± 0.031 ns/op
* RNGBenchmark.measureOtter32IntR avgt 5 3.509 ± 0.020 ns/op
* RNGBenchmark.measureOtter32R avgt 5 5.633 ± 0.023 ns/op
* RNGBenchmark.measureOverdrive64 avgt 5 2.493 ± 0.022 ns/op
* RNGBenchmark.measureOverdrive64Int avgt 5 2.558 ± 0.084 ns/op
* RNGBenchmark.measureOverdrive64IntR avgt 5 2.735 ± 0.022 ns/op
* RNGBenchmark.measureOverdrive64R avgt 5 2.716 ± 0.025 ns/op
* RNGBenchmark.measurePaperweight avgt 5 3.370 ± 0.029 ns/op
* RNGBenchmark.measurePaperweightInt avgt 5 3.400 ± 0.019 ns/op
* RNGBenchmark.measurePaperweightIntR avgt 5 3.879 ± 0.019 ns/op
* RNGBenchmark.measurePaperweightR avgt 5 3.796 ± 0.026 ns/op
* RNGBenchmark.measureQuixotic avgt 5 2.608 ± 0.020 ns/op
* RNGBenchmark.measureQuixoticInt avgt 5 2.660 ± 0.012 ns/op
* RNGBenchmark.measureQuixoticIntR avgt 5 2.923 ± 0.012 ns/op
* RNGBenchmark.measureQuixoticR avgt 5 2.892 ± 0.023 ns/op
* RNGBenchmark.measureSFC64 avgt 5 3.214 ± 0.011 ns/op
* RNGBenchmark.measureSFC64Int avgt 5 3.307 ± 0.025 ns/op
* RNGBenchmark.measureSFC64IntR avgt 5 3.725 ± 0.023 ns/op
* RNGBenchmark.measureSFC64R avgt 5 3.909 ± 0.156 ns/op
* RNGBenchmark.measureSeaSlater32 avgt 5 4.992 ± 0.110 ns/op
* RNGBenchmark.measureSeaSlater32Int avgt 5 3.063 ± 0.011 ns/op
* RNGBenchmark.measureSeaSlater32IntR avgt 5 3.430 ± 0.026 ns/op
* RNGBenchmark.measureSeaSlater32R avgt 5 5.585 ± 0.100 ns/op
* RNGBenchmark.measureSeaSlater64 avgt 5 3.074 ± 0.039 ns/op
* RNGBenchmark.measureSeaSlater64Int avgt 5 3.161 ± 0.009 ns/op
* RNGBenchmark.measureSeaSlater64IntR avgt 5 3.544 ± 0.058 ns/op
* RNGBenchmark.measureSeaSlater64R avgt 5 3.457 ± 0.075 ns/op
* RNGBenchmark.measureSpiral avgt 5 3.471 ± 0.031 ns/op
* RNGBenchmark.measureSpiralA avgt 5 3.475 ± 0.025 ns/op
* RNGBenchmark.measureSpiralB avgt 5 3.159 ± 0.008 ns/op
* RNGBenchmark.measureSpiralC avgt 5 3.290 ± 0.011 ns/op
* RNGBenchmark.measureSpiralD avgt 5 3.203 ± 0.073 ns/op
* RNGBenchmark.measureSpiralE avgt 5 3.223 ± 0.010 ns/op
* RNGBenchmark.measureSpiralF avgt 5 3.001 ± 0.029 ns/op
* RNGBenchmark.measureSpiralG avgt 5 3.082 ± 0.062 ns/op
* RNGBenchmark.measureSpiralH avgt 5 3.169 ± 0.031 ns/op
* RNGBenchmark.measureSpiralI avgt 5 2.669 ± 0.034 ns/op
* RNGBenchmark.measureSpiralInt avgt 5 3.513 ± 0.050 ns/op
* RNGBenchmark.measureSpiralIntR avgt 5 4.234 ± 0.010 ns/op
* RNGBenchmark.measureSpiralR avgt 5 3.991 ± 0.037 ns/op
* RNGBenchmark.measureStarfish32 avgt 5 4.449 ± 0.056 ns/op
* RNGBenchmark.measureStarfish32Int avgt 5 3.016 ± 0.017 ns/op
* RNGBenchmark.measureStarfish32IntR avgt 5 3.208 ± 0.014 ns/op
* RNGBenchmark.measureStarfish32NextInt avgt 5 2.997 ± 0.052 ns/op
* RNGBenchmark.measureStarfish32R avgt 5 5.013 ± 0.157 ns/op
* RNGBenchmark.measureTangle avgt 5 2.572 ± 0.029 ns/op
* RNGBenchmark.measureTangleA avgt 5 2.582 ± 0.008 ns/op
* RNGBenchmark.measureTangleB avgt 5 2.734 ± 0.004 ns/op
* RNGBenchmark.measureTangleC avgt 5 2.762 ± 0.018 ns/op
* RNGBenchmark.measureTangleD avgt 5 2.838 ± 0.015 ns/op
* RNGBenchmark.measureTangleInt avgt 5 2.651 ± 0.008 ns/op
* RNGBenchmark.measureTangleIntR avgt 5 2.978 ± 0.039 ns/op
* RNGBenchmark.measureTangleR avgt 5 2.963 ± 0.009 ns/op
* RNGBenchmark.measureThrust avgt 5 2.508 ± 0.024 ns/op
* RNGBenchmark.measureThrustAlt avgt 5 2.516 ± 0.012 ns/op
* RNGBenchmark.measureThrustAlt32 avgt 5 4.363 ± 0.009 ns/op
* RNGBenchmark.measureThrustAlt32Int avgt 5 2.792 ± 0.009 ns/op
* RNGBenchmark.measureThrustAlt32IntR avgt 5 3.151 ± 0.020 ns/op
* RNGBenchmark.measureThrustAlt32R avgt 5 5.111 ± 0.150 ns/op
* RNGBenchmark.measureThrustAltInt avgt 5 2.522 ± 0.006 ns/op
* RNGBenchmark.measureThrustAltIntR avgt 5 2.811 ± 0.009 ns/op
* RNGBenchmark.measureThrustAltR avgt 5 2.823 ± 0.066 ns/op
* RNGBenchmark.measureThrustInt avgt 5 2.511 ± 0.010 ns/op
* RNGBenchmark.measureThrustIntR avgt 5 2.790 ± 0.038 ns/op
* RNGBenchmark.measureThrustR avgt 5 2.791 ± 0.011 ns/op
* RNGBenchmark.measureThunder avgt 5 2.653 ± 0.035 ns/op
* RNGBenchmark.measureThunderInt avgt 5 2.761 ± 0.022 ns/op
* RNGBenchmark.measureThunderIntR avgt 5 3.023 ± 0.015 ns/op
* RNGBenchmark.measureThunderR avgt 5 2.984 ± 0.015 ns/op
* RNGBenchmark.measureVortex avgt 5 2.928 ± 0.003 ns/op
* RNGBenchmark.measureVortexInt avgt 5 3.026 ± 0.028 ns/op
* RNGBenchmark.measureVortexIntR avgt 5 3.401 ± 0.027 ns/op
* RNGBenchmark.measureVortexR avgt 5 3.342 ± 0.104 ns/op
* RNGBenchmark.measureXoRo avgt 5 2.763 ± 0.011 ns/op
* RNGBenchmark.measureXoRo32 avgt 5 3.785 ± 0.007 ns/op
* RNGBenchmark.measureXoRo32Int avgt 5 2.770 ± 0.030 ns/op
* RNGBenchmark.measureXoRo32IntR avgt 5 3.114 ± 0.050 ns/op
* RNGBenchmark.measureXoRo32R avgt 5 4.409 ± 0.012 ns/op
* RNGBenchmark.measureXoRoInt avgt 5 2.881 ± 0.025 ns/op
* RNGBenchmark.measureXoRoIntR avgt 5 3.129 ± 0.026 ns/op
* RNGBenchmark.measureXoRoR avgt 5 2.991 ± 0.007 ns/op
* RNGBenchmark.measureXoshiroAra32 avgt 5 4.929 ± 0.190 ns/op
* RNGBenchmark.measureXoshiroAra32Int avgt 5 3.257 ± 0.024 ns/op
* RNGBenchmark.measureXoshiroAra32IntR avgt 5 3.675 ± 0.024 ns/op
* RNGBenchmark.measureXoshiroAra32R avgt 5 5.349 ± 0.062 ns/op
* RNGBenchmark.measureXoshiroStarPhi32 avgt 5 5.117 ± 0.021 ns/op
* RNGBenchmark.measureXoshiroStarPhi32Int avgt 5 3.381 ± 0.009 ns/op
* RNGBenchmark.measureXoshiroStarPhi32IntR avgt 5 3.767 ± 0.012 ns/op
* RNGBenchmark.measureXoshiroStarPhi32R avgt 5 5.477 ± 0.022 ns/op
* RNGBenchmark.measureXoshiroStarStar32 avgt 5 5.257 ± 0.070 ns/op
* RNGBenchmark.measureXoshiroStarStar32Int avgt 5 3.466 ± 0.046 ns/op
* RNGBenchmark.measureXoshiroStarStar32IntR avgt 5 3.836 ± 0.096 ns/op
* RNGBenchmark.measureXoshiroStarStar32R avgt 5 5.747 ± 0.016 ns/op
* RNGBenchmark.measureXoshiroXara32 avgt 5 5.080 ± 0.014 ns/op
* RNGBenchmark.measureXoshiroXara32Int avgt 5 3.319 ± 0.011 ns/op
* RNGBenchmark.measureXoshiroXara32IntR avgt 5 3.748 ± 0.064 ns/op
* RNGBenchmark.measureXoshiroXara32R avgt 5 5.512 ± 0.149 ns/op
* RNGBenchmark.measureZag32 avgt 5 6.304 ± 0.107 ns/op
* RNGBenchmark.measureZag32Int avgt 5 3.366 ± 0.011 ns/op
* RNGBenchmark.measureZag32IntR avgt 5 3.875 ± 0.107 ns/op
* RNGBenchmark.measureZag32R avgt 5 6.411 ± 0.103 ns/op
* RNGBenchmark.measureZig32 avgt 5 5.908 ± 0.084 ns/op
* RNGBenchmark.measureZig32Int avgt 5 3.498 ± 0.043 ns/op
* RNGBenchmark.measureZig32IntR avgt 5 4.031 ± 0.063 ns/op
* RNGBenchmark.measureZig32R avgt 5 6.505 ± 0.056 ns/op
* RNGBenchmark.measureZog32 avgt 5 5.206 ± 0.076 ns/op
* RNGBenchmark.measureZog32Int avgt 5 3.216 ± 0.018 ns/op
* RNGBenchmark.measureZog32IntR avgt 5 3.693 ± 0.035 ns/op
* RNGBenchmark.measureZog32R avgt 5 5.770 ± 0.020 ns/op
* </pre>
* <br>
* The fastest generator depends on your target platform, but on a desktop or laptop using an OpenJDK-based Java
* installation, Jab63RNG and MiniMover64RNG are virtually tied for first place. Neither is at all equidistributed; for
* generators that are capable of producing all outputs with equal likelihood, LinnormRNG, MizuchiRNG, and QuixoticRNG
* are all about the same, with DiverRNG probably a little faster (but it was added after this benchmark was run, so its
* results wouldn't be from the same circumstances). DiverRNG and possibly QuixoticRNG are likely to have higher quality
* than LinnormRNG and MizuchiRNG, since the last two fail one PractRand test after 16TB while at least DiverRNG does
* not have that issue.
* <br>
* GWT-compatible generators need to work with an "int" type that isn't equivalent to Java's "int" and is closer to a
* Java "double" that gets cast to an int when bitwise operations are used on it. This JS int is about 10x-20x faster to
* do math operations on than GWT's "long" type, which is emulated using three JS numbers internally, but you need to be
* vigilant about the possibility of exceeding the limits of Integer.MAX_VALUE and Integer.MIN_VALUE, since math won't
* overflow, and about precision loss if you do exceed those limits severely, since JS numbers are floating-point. So,
* you can't safely multiply by too large of an int (I limit my multipliers to 20 bits), you need to follow up normal
* math with bitwise math to bring any overflowing numbers back to the 32-bit range, and you should avoid longs and math
* on them whenever possible. The GWT-safe generators are in the bulk results above; the ones that are GWT-safe are (an
* asterisk marks a generator that doesn't pass many statistical tests): Churro32RNG, Dizzy32RNG, Lathe32RNG,
* Lobster32RNG, Molerat32RNG, Mover32RNG, Oriole32RNG, SeaSlater32RNG*, Starfish32RNG, XoRo32RNG*, XoshiroAra32RNG,
* XoshiroStarPhi32RNG, XoshiroStarStar32RNG, XoshiroXara32RNG, Zag32RNG, Zig32RNG, and Zog32RNG. GWTRNG is a special
* case because it uses Starfish32RNG's algorithm verbatim, but implements IRNG instead of just RandomnessSource and so
* has some extra optimizations it can use when producing 32-bit values. Starfish32RNG and all of the Xoshiro-based
* generators are probably the best choices for 32-bit generators, with Starfish having a smaller and possibly more
* manageable state size, and Xoshiro variants having much longer periods.
* <br>
* You can benchmark most of these in GWT for yourself on
* <a href="https://tommyettinger.github.io/SquidLib-Demos/bench/rng/">this SquidLib-Demos page</a>; comparing "runs"
* where higher is better is a good way of estimating how fast a generator is. Each "run" is 10,000 generated numbers.
* Lathe32RNG is by far the best on speed if you consider both desktop and GWT, but it can't generate all possible
* "long" values, while XoshiroAra can generate all possible "long" values with equal frequency, and even all possible
* pairs of "long" values (less one). XoshiroAra is also surprisingly fast compared to similar Xoshiro-based generators,
* especially since it does just as well in PractRand testing. The equidistribution comment at the end of each line
* refers to that specific method; calling {@code myOriole32RNG.next(32)} repeatedly will produce all ints with equal
* frequency over the full period of that generator, ((2 to the 64) - 1) * (2 to the 32), but the same is not true of
* calling {@code myOriole32RNG.nextLong()}, which would produce some longs more frequently than others (and probably
* would not produce some longs at all). The Xoshiro-based generators have the best period and equidistribution
* qualities, with XoshiroAra having the best performance (all of them pass 32TB of PractRand). The Xoroshiro-based
* generators tend to be faster, but only Starfish has better equidistribution of the bunch (it can produce all longs
* except one, while Lathe can't and Oriole won't with equal frequency). Starfish seems to have comparable quality and
* speed relative to Oriole (excellent and pretty good, respectively), but improves on its distribution at the expense
* of its period, and has a smaller state.
* <br>
* Benchmarking determine() methods is much like benchmarking the normal RandomnessSource methods, it just requires
* passing a state that goes up as a counter. Some good determine() methods for various usage:
* <pre>
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureDiverDetermine avgt 5 5.100 ± 0.043 ns/op
* RNGBenchmark.measureLightDetermine avgt 5 4.016 ± 0.052 ns/op
* RNGBenchmark.measureLinnormDetermine avgt 5 3.858 ± 0.041 ns/op
* RNGBenchmark.measurePelican3Determine avgt 5 4.192 ± 0.026 ns/op
* RNGBenchmark.measurePelicanDetermine avgt 5 4.543 ± 0.049 ns/op // passes PractRand in many stricter cases
* </pre>
* The two slowest methods here are also the most robust, standing up to unusual patterns in the input that will cause
* LightRNG.determine(), LinnormRNG.determine(), and DiverRNG.pelican3() to fail. PelicanRNG.determine() appears to be
* the most robust of all of these and is faster than DiverRNG.determine(). LinnormRNG.determine() is the fastest, but
* incrementing by some values will cause it to fail after a few GB of testing, and rotating a counter given as input
* almost certainly will cause it to fail for some rotations, because it wasn't built to handle that.
* <br>
* The 32-bit generators are mostly intended for usage on GWT, but their performance on desktop and mobile platforms can
* also be relevant to their general usefulness. A benchmark of the {@link RandomnessSource#next(int)} method of all
* 32-bit generators currently in Sarong:
* <pre>
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureBasicRandom32Int avgt 5 2.162 ± 0.008 ns/op
* RNGBenchmark.measureCake32Int avgt 5 4.493 ± 0.012 ns/op
* RNGBenchmark.measureChurro32Int avgt 5 3.636 ± 0.021 ns/op
* RNGBenchmark.measureDizzy32Int avgt 5 3.355 ± 0.024 ns/op
* RNGBenchmark.measureIsaac32Int avgt 5 5.216 ± 0.033 ns/op
* RNGBenchmark.measureLathe32Int avgt 5 2.898 ± 0.006 ns/op
* RNGBenchmark.measureLight32Int avgt 5 2.858 ± 0.666 ns/op
* RNGBenchmark.measureLobster32Int avgt 5 3.016 ± 0.007 ns/op
* RNGBenchmark.measureMegaMover32Int avgt 5 3.274 ± 0.007 ns/op
* RNGBenchmark.measureMolerat32Int avgt 5 3.022 ± 0.043 ns/op
* RNGBenchmark.measureMover32Int avgt 5 2.599 ± 0.034 ns/op
* RNGBenchmark.measureMoverCounter32Int avgt 5 2.584 ± 0.020 ns/op
* RNGBenchmark.measureOriole32Int avgt 5 3.105 ± 0.013 ns/op
* RNGBenchmark.measureOtter32Int avgt 5 3.091 ± 0.029 ns/op
* RNGBenchmark.measureSeaSlater32Int avgt 5 3.034 ± 0.008 ns/op
* RNGBenchmark.measureStarfish32Int avgt 5 2.989 ± 0.011 ns/op
* RNGBenchmark.measureThrustAlt32Int avgt 5 2.884 ± 0.007 ns/op
* RNGBenchmark.measureXoRo32Int avgt 5 2.748 ± 0.016 ns/op
* RNGBenchmark.measureXoshiroAra32Int avgt 5 3.222 ± 0.016 ns/op
* RNGBenchmark.measureXoshiroStarPhi32Int avgt 5 3.348 ± 0.006 ns/op
* RNGBenchmark.measureXoshiroStarStar32Int avgt 5 3.439 ± 0.016 ns/op
* RNGBenchmark.measureXoshiroXara32Int avgt 5 3.288 ± 0.039 ns/op
* RNGBenchmark.measureZag32Int avgt 5 3.331 ± 0.035 ns/op
* RNGBenchmark.measureZig32Int avgt 5 3.480 ± 0.015 ns/op
* RNGBenchmark.measureZog32Int avgt 5 3.181 ± 0.008 ns/op
* </pre>
* It should be noted that not all of these pass PractRand or other tests; BasicRandom32 fails tests all over,
* ThrustAlt32RNG fails some tests, XoRo32RNG fails binary matrix rank tests as well as some others, and so on.
* The fastest ones that reliably pass tests appears to be Mover32RNG and MoverCounter32RNG, both of which
* have somewhat-challenging seeding requirements. Starfish32RNG is 2-dimensionally equidistributed, and all of the
* Xoshiro-based generators are 4-dimensionally equidistributed; not many of the others are even 1-dimensionally
* equidistributed.
* <br>
* Of the recently-added 32-bit generators, Mover32RNG remains the fastest, with GWTRNG (which uses Starfish32RNG) in
* second place. GWTRNG has better seeding properties and a slightly longer period than Mover32RNG.
* <pre>
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureCake32Int avgt 6 3.540 ± 0.013 ns/op
* RNGBenchmark.measureGWTInt avgt 6 2.980 ± 0.021 ns/op
* RNGBenchmark.measureLadder32Int avgt 6 3.095 ± 0.020 ns/op
* RNGBenchmark.measureMegaMover32Int avgt 6 3.275 ± 0.004 ns/op
* RNGBenchmark.measureMover32Int avgt 6 2.590 ± 0.021 ns/op
* </pre>
* Here's a quick comparison of the higher-quality SkippingRandomness implementations, plus DiverRNG as a reference.
* <pre>
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureDiver avgt 6 2.597 ± 0.012 ns/op // not skippable
* RNGBenchmark.measureLight avgt 6 2.804 ± 0.008 ns/op
* RNGBenchmark.measurePelican avgt 6 3.837 ± 0.012 ns/op
* RNGBenchmark.measurePulley avgt 6 3.409 ± 0.014 ns/op
* </pre>
* Comparing to their determine() methods:
* <pre>
* // run on Java 8, OpenJDK
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureDiverDetermine avgt 6 2.744 ± 0.012 ns/op // same as LinnormRNG.determine(), bad gammas possible
* RNGBenchmark.measureLightDetermine avgt 6 2.777 ± 0.009 ns/op // bad gammas possible
* RNGBenchmark.measurePelicanDetermine avgt 6 3.506 ± 0.007 ns/op
* RNGBenchmark.measurePulleyDetermine avgt 6 3.116 ± 0.003 ns/op
* RNGBenchmark.measureToppingDetermine avgt 6 3.261 ± 0.006 ns/op
* // same run on Java 11, also OpenJDK
* Benchmark Mode Cnt Score Error Units
* RNGBenchmark.measureDiverDetermine avgt 6 2.864 ± 0.016 ns/op
* RNGBenchmark.measureLightDetermine avgt 6 2.983 ± 0.007 ns/op
* RNGBenchmark.measurePelicanDetermine avgt 6 3.524 ± 0.009 ns/op
* RNGBenchmark.measurePulleyDetermine avgt 6 3.231 ± 0.024 ns/op
* RNGBenchmark.measureToppingDetermine avgt 6 3.383 ± 0.022 ns/op
* </pre>
* Some of the determine() methods are marked as having "bad gammas possible;" this means that if the inputs change by a
* certain amount (there are often many bad gamma values for a given generator), the generator's output will have lower
* quality. Pelican, Topping, and Pulley are meant to avoid this, with the most effort in Pelican applied to avoiding
* bad gammas in higher bit positions (an unusual occurrence). Generators without bad gammas should be suitable to use
* for the same purpose as SplitMix64 in SplittableRandom. PulleyRNG may have some bad gammas, while ToppingRNG is much
* less likely to have any.
*
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
@Warmup(iterations = 5, time = 5)
@Measurement(iterations = 5, time = 5)
public class RNGBenchmark {
private long state = 9000;//, stream = 9001, oddState = 9999L;
private int istate = 9000;
// private static volatile long[] inputs = new long[0x100000];
// static {
// for (int i = 0; i < 0x100000; i++) {
// inputs[i] = PelicanRNG.determine(i);
// }
// }
// public long doThunder()
// {
// ThunderRNG rng = new ThunderRNG(seed);
//
// for (int i = 0; i < 1000000007; i++) {
// seed += rng.nextLong();
// }
// return seed;
// }
//
// @Benchmark
// // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
// public void measureThunder() throws InterruptedException {
// seed = 9000;
// doThunder();
// }
//
// public int doThunderInt()
// {
// ThunderRNG rng = new ThunderRNG(iseed);
//
// for (int i = 0; i < 1000000007; i++) {
// iseed += rng.next(32);
// }
// return iseed;
// }
//
// @Benchmark
// // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
// public void measureThunderInt() throws InterruptedException {
// iseed = 9000;
// doThunderInt();
// }
// public long doThunderR()
// {
// RNG rng = new RNG(new ThunderRNG(seed));
//
// for (int i = 0; i < 1000000007; i++) {
// seed += rng.nextLong();
// }
// return seed;
// }
//
// @Benchmark
// // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
// public void measureThunderR() throws InterruptedException {
// seed = 9000;
// doThunderR();
// }
//
// public int doThunderIntR()
// {
// RNG rng = new RNG(new ThunderRNG(iseed));
//
// for (int i = 0; i < 1000000007; i++) {
// iseed += rng.nextInt();
// }
// return iseed;
// }
//
// @Benchmark
// // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
// public void measureThunderIntR() throws InterruptedException {
// iseed = 9000;
// doThunderIntR();
// }
private GearRNG Gear = new GearRNG(9999L);
private RNG GearR = new RNG(Gear);
@Benchmark
public long measureGear()
{
return Gear.nextLong();
}
@Benchmark
public int measureGearInt()
{
return Gear.next(32);
}
@Benchmark
public long measureGearR()
{
return GearR.nextLong();
}
@Benchmark
public int measureGearIntR()
{
return GearR.nextInt();
}
private XoRoRNG XoRo = new XoRoRNG(9999L);
private RNG XoRoR = new RNG(XoRo);
@Benchmark
public long measureXoRo()
{
return XoRo.nextLong();
}
@Benchmark
public int measureXoRoInt()
{
return XoRo.next(32);
}
@Benchmark
public long measureXoRoR()
{
return XoRoR.nextLong();
}
@Benchmark
public int measureXoRoIntR()
{
return XoRoR.nextInt();
}
private Lathe64RNG Lathe64 = new Lathe64RNG(9999L);
private RNG Lathe64R = new RNG(Lathe64);
@Benchmark
public long measureLathe64()
{
return Lathe64.nextLong();
}
@Benchmark
public int measureLathe64Int()
{
return Lathe64.next(32);
}
@Benchmark
public long measureLathe64R()
{
return Lathe64R.nextLong();
}
@Benchmark
public int measureLathe64IntR()
{
return Lathe64R.nextInt();
}
/*
public long doXar()
{
XarRNG rng = new XarRNG(seed);
for (int i = 0; i < 1000000007; i++) {
seed += rng.nextLong();
}
return seed;
}
@Benchmark
// @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
public void a____measureXar() throws InterruptedException {
seed = 9000;
doXar();
}
public int doXarInt()
{
XarRNG rng = new XarRNG(iseed);
for (int i = 0; i < 1000000007; i++) {
iseed += rng.next(32);
}
return iseed;
}
@Benchmark
// @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
public void a____measureXarInt() throws InterruptedException {
iseed = 9000;
doXarInt();
}
public long doXarR()
{
RNG rng = new RNG(new XarRNG(seed));
for (int i = 0; i < 1000000007; i++) {
seed += rng.nextLong();
}
return seed;
}
@Benchmark
// @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
public void a____measureXarR() throws InterruptedException {
seed = 9000;
doXarR();
}
public int doXarIntR()
{
RNG rng = new RNG(new XarRNG(iseed));
for (int i = 0; i < 1000000007; i++) {
iseed += rng.nextInt();
}
return iseed;
}
@Benchmark
// @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
public void a____measureXarIntR() throws InterruptedException {
iseed = 9000;
doXarIntR();
}
*/
private LongPeriodRNG LongPeriod = new LongPeriodRNG(9999L);
private RNG LongPeriodR = new RNG(LongPeriod);
@Benchmark
public long measureLongPeriod()
{
return LongPeriod.nextLong();
}
@Benchmark
public int measureLongPeriodInt()
{
return LongPeriod.next(32);
}
@Benchmark
public long measureLongPeriodR()
{
return LongPeriodR.nextLong();
}
@Benchmark
public int measureLongPeriodIntR()
{
return LongPeriodR.nextInt();
}
private LightRNG Light = new LightRNG(9999L);
private RNG LightR = new RNG(Light);
@Benchmark
public long measureLight()
{
return Light.nextLong();
}
@Benchmark
public int measureLightInt()
{
return Light.next(32);
}
@Benchmark
public long measureLightR()
{
return LightR.nextLong();
}
@Benchmark
public int measureLightIntR()
{
return LightR.nextInt();
}
private PaperweightRNG Paperweight = new PaperweightRNG(9999L);
private RNG PaperweightR = new RNG(Paperweight);
@Benchmark
public long measurePaperweight()
{
return Paperweight.nextLong();
}
@Benchmark
public int measurePaperweightInt()
{
return Paperweight.next(32);
}
@Benchmark
public long measurePaperweightR()
{
return PaperweightR.nextLong();
}
@Benchmark
public int measurePaperweightIntR()
{
return PaperweightR.nextInt();
}
private BrightRNG Bright = new BrightRNG(9999L);
private RNG BrightR = new RNG(Bright);
@Benchmark
public long measureBright()
{
return Bright.nextLong();
}
@Benchmark
public int measureBrightInt()
{
return Bright.next(32);
}
@Benchmark
public long measureBrightR()
{
return BrightR.nextLong();
}
@Benchmark
public int measureBrightIntR()
{
return BrightR.nextInt();
}
private FlapRNG Flap = new FlapRNG(9999L);
private RNG FlapR = new RNG(Flap);
@Benchmark
public long measureFlap()
{
return Flap.nextLong();
}
@Benchmark
public int measureFlapInt()
{
return Flap.next(32);
}
@Benchmark
public long measureFlapR()
{
return FlapR.nextLong();
}
@Benchmark
public int measureFlapIntR()
{
return FlapR.nextInt();
}
private LapRNG Lap = new LapRNG(9999L);
private RNG LapR = new RNG(Lap);
@Benchmark
public long measureLap()
{
return Lap.nextLong();
}
@Benchmark
public int measureLapInt()
{
return Lap.next(32);
}
@Benchmark
public long measureLapR()
{
return LapR.nextLong();
}
private ThunderRNG Thunder = new ThunderRNG(9999L);
private RNG ThunderR = new RNG(Thunder);
@Benchmark
public long measureThunder()
{
return Thunder.nextLong();
}
@Benchmark
public int measureThunderInt()
{
return Thunder.next(32);
}
@Benchmark
public long measureThunderR()
{
return ThunderR.nextLong();
}
@Benchmark
public int measureThunderIntR()
{
return ThunderR.nextInt();
}
@Benchmark
// @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1)
public int measureLapIntR()
{
return LapR.nextInt();
}
private SeaSlater64RNG SeaSlater64 = new SeaSlater64RNG(9999L);
private RNG SeaSlater64R = new RNG(SeaSlater64);
@Benchmark
public long measureSeaSlater64()
{
return SeaSlater64.nextLong();
}
@Benchmark
public int measureSeaSlater64Int()
{
return SeaSlater64.next(32);
}
@Benchmark
public long measureSeaSlater64R()
{
return SeaSlater64R.nextLong();
}
@Benchmark
public int measureSeaSlater64IntR()
{
return SeaSlater64R.nextInt();
}
private VelvetRNG Velvet = new VelvetRNG(9999L);
private RNG VelvetR = new RNG(Velvet);
@Benchmark
public long measureVelvet()
{
return Velvet.nextLong();
}
@Benchmark
public int measureVelvetInt()
{
return Velvet.next(32);
}
@Benchmark
public long measureVelvetR()
{
return VelvetR.nextLong();
}
@Benchmark
public int measureVelvetIntR()
{
return VelvetR.nextInt();
}
private ThrustRNG Thrust = new ThrustRNG(9999L);
private RNG ThrustR = new RNG(Thrust);
@Benchmark
public long measureThrust()
{
return Thrust.nextLong();
}
@Benchmark
public int measureThrustInt()
{
return Thrust.next(32);
}
@Benchmark
public long measureThrustR()
{
return ThrustR.nextLong();
}
@Benchmark
public int measureThrustIntR()
{
return ThrustR.nextInt();
}
//@Benchmark
// public long measureInlineThrust()
// {
// long z = (state += 0x9E3779B97F4A7C15L);
// z = (z ^ z >>> 26) * 0x2545F4914F6CDD1DL;
// return z ^ z >>> 28;
// }
// @Benchmark
// public long measureThrustAltDetermine() {
// return ThrustAltRNG.determine(state++);
// }
@Benchmark
public long measureLightDetermine() {
return LightRNG.determine(state++);
}
@Benchmark
public long measureLinnormDetermine() {
return LinnormRNG.determine(state++);
}
@Benchmark
public long measureDiverDetermine() {
return DiverRNG.determine(state++);
}
// strikes down at PractRand and slays its ruin on the mountain-side
@Benchmark
public long measurePelicanDetermine() {
return PelicanRNG.determine(state++);
}
@Benchmark
public long measurePulleyDetermine() {
return PulleyRNG.determine(state++);
}
@Benchmark
public long measureToppingDetermine() {
return ToppingRNG.determine(state++);
}
@Benchmark
public int measureThrustAlt32DetermineInt() {
return ThrustAlt32RNG.determineInt(istate++);
}
// @Benchmark
// public long measureLinnormDeCorrelatedDetermine() {
// return LinnormRNG.determine(inputs[istate++ & 0xFFFFF]);
// }
// @Benchmark
// public long measureDiverDeCorrelatedDetermine() {
// return DiverRNG.determine(inputs[istate++ & 0xFFFFF]);
// }
// @Benchmark
// public long measureAltThrustDeCorrelatedDetermine() {
// return ThrustAltRNG.determine(inputs[istate++ & 0xFFFFF]);
// }
// @Benchmark
// public long measureLightDeCorrelatedDetermine() {
// return LightRNG.determine(inputs[istate++ & 0xFFFFF]);
// }
// @Benchmark
// public long measureGlowDeCorrelatedDetermine() {
// return DiverRNG.glowDetermine(inputs[istate++ & 0xFFFFF]);
// }
// @Benchmark
// public long measureDonutDeCorrelatedDetermine() {
// return DiverRNG.donut(inputs[istate++ & 0xFFFFF]);
// }
// @Benchmark
// public long measureMotorDetermine() {
// return MotorRNG.determine(state++);
// }
//
// //@Benchmark
// public long measureVortexDetermine() {
// return VortexRNG.determine(state++);
// }
//
// //@Benchmark
// public long measureVortexDetermineBare() {
// return VortexRNG.determineBare(state += 0x6C8E9CF570932BD5L);
// }
//
// @Benchmark
// public long measureAltThrustRandomize() {
// return ThrustAltRNG.randomize(state += 0x6C8E9CF570932BD5L);
// }
//
// @Benchmark
// public long measureLinnormRandomize() { return LinnormRNG.randomize(state += 0x632BE59BD9B4E019L); }
private ThrustAltRNG ThrustAlt = new ThrustAltRNG(9999L);
private RNG ThrustAltR = new RNG(ThrustAlt);
@Benchmark
public long measureThrustAlt()
{
return ThrustAlt.nextLong();
}
@Benchmark
public int measureThrustAltInt()
{
return ThrustAlt.next(32);
}
@Benchmark
public long measureThrustAltR()
{
return ThrustAltR.nextLong();
}
@Benchmark
public int measureThrustAltIntR()
{
return ThrustAltR.nextInt();
}
// @Benchmark
// public long measureThrustAltInline()
// {
// final long s = (state += 0x6C8E9CF570932BD5L);
// final long z = (s ^ (s >>> 25)) * (s | 0xA529L);
// return z ^ (z >>> 23);
// }
// @Benchmark
// public long measureInlineThrustAltOther()
// {
// long z = (state += 0x6C8E9CF570932BD5L);
// z = (z ^ (z >>> 25)) * (z | 0xA529L);
// return z ^ (z >>> 23);
// }
private Jab63RNG Jab63 = new Jab63RNG(9999L);
private RNG Jab63R = new RNG(Jab63);
@Benchmark
public long measureJab63()
{
return Jab63.nextLong();
}
@Benchmark
public int measureJab63Int()
{
return Jab63.next(32);
}
@Benchmark
public long measureJab63R()
{
return Jab63R.nextLong();
}
@Benchmark
public int measureJab63IntR()
{
return Jab63R.nextInt();
}
// @Benchmark
// public long measureInlineJab63()
// {
// long z = (oddState += 0x3C6EF372FE94F82AL);
// z *= (z ^ (z >>> 21));
// return z - (z >>> 28);
// }
//
//
// @Benchmark
// public long measureInlineVortex()
// {
// long z = (state += 0x6C8E9CF970932BD5L);
// z = (z ^ z >>> 25) * 0x2545F4914F6CDD1DL;
// z ^= ((z << 19) | (z >>> 45)) ^ ((z << 53) | (z >>> 11));
// return z ^ (z >>> 25);
// }
private VortexRNG Vortex = new VortexRNG(9999L);
private RNG VortexR = new RNG(Vortex);
@Benchmark
public long measureVortex()
{
return Vortex.nextLong();
}
@Benchmark
public int measureVortexInt()
{
return Vortex.next(32);
}
@Benchmark
public long measureVortexR()
{
return VortexR.nextLong();
}
@Benchmark
public int measureVortexIntR()
{
return VortexR.nextInt();
}
private BasicRandom64 BasicRandom64 = new BasicRandom64(1L);
private RNG BasicRandom64R = new RNG(BasicRandom64);
@Benchmark
public long measureBasicRandom64()
{
return BasicRandom64.nextLong();
}
@Benchmark
public int measureBasicRandom64Int()
{
return BasicRandom64.next(32);
}
@Benchmark
public long measureBasicRandom64R()
{
return BasicRandom64R.nextLong();
}
@Benchmark
public int measureBasicRandom64IntR()
{
return BasicRandom64R.nextInt();
}
private BasicRandom32 BasicRandom32 = new BasicRandom32(1);
private RNG BasicRandom32R = new RNG(BasicRandom32);
@Benchmark
public long measureBasicRandom32()
{
return BasicRandom32.nextLong();
}
@Benchmark
public int measureBasicRandom32Int()
{
return BasicRandom32.next(32);
}
@Benchmark
public long measureBasicRandom32R()
{
return BasicRandom32R.nextLong();
}
@Benchmark
public int measureBasicRandom32IntR()
{
return BasicRandom32R.nextInt();
}
private MotorRNG Motor = new MotorRNG(9999L);
private RNG MotorR = new RNG(Motor);
@Benchmark
public long measureMotor()
{
return Motor.nextLong();
}
@Benchmark
public int measureMotorInt()
{
return Motor.next(32);
}
@Benchmark
public long measureMotorR()
{
return MotorR.nextLong();
}
@Benchmark
public int measureMotorIntR()
{
return MotorR.nextInt();
}
private MeshRNG Mesh = new MeshRNG(9999L);
private RNG MeshR = new RNG(Mesh);
@Benchmark
public long measureMesh()
{
return Mesh.nextLong();
}
@Benchmark
public int measureMeshInt()
{
return Mesh.next(32);
}
@Benchmark
public long measureMeshR()
{
return MeshR.nextLong();
}
@Benchmark
public int measureMeshIntR()
{
return MeshR.nextInt();
}
private SpiralRNG Spiral = new SpiralRNG(9999L);
private RNG SpiralR = new RNG(Spiral);
@Benchmark
public long measureSpiral()
{
return Spiral.nextLong();
}
@Benchmark
public int measureSpiralInt()
{
return Spiral.next(32);
}
@Benchmark
public long measureSpiralR()
{
return SpiralR.nextLong();
}
@Benchmark
public int measureSpiralIntR()
{
return SpiralR.nextInt();
}
// private SpiralRNG spiralA = new SpiralRNG(9999L, 1337L),
// spiralB = new SpiralRNG(9999L, 1337L),
// spiralC = new SpiralRNG(9999L, 1337L),
// spiralD = new SpiralRNG(9999L, 1337L),
// spiralE = new SpiralRNG(9999L, 1337L),
// spiralF = new SpiralRNG(9999L, 1337L),
// spiralG = new SpiralRNG(9999L, 1337L),
// spiralH = new SpiralRNG(9999L, 1337L),
// spiralI = new SpiralRNG(9999L, 1337L);
// @Benchmark
// public long measureSpiralA()
// {
// return spiralA.nextLongOld();
// }
// @Benchmark
// public long measureSpiralB()
// {
// return spiralB.nextLongAlt();
// }
// @Benchmark
// public long measureSpiralC()
// {
// return spiralC.nextLongNew();
// }
// @Benchmark
// public long measureSpiralD()
// {
// return spiralD.nextLongAgain();
// }
// @Benchmark
// public long measureSpiralE()
// {
// return spiralE.nextLongAgain3();
// }
// @Benchmark
// public long measureSpiralF()
// {
// return spiralF.nextLongAgain4();
// }
// @Benchmark
// public long measureSpiralG()
// {
// return spiralG.nextLongAgain5();
// }
// @Benchmark
// public long measureSpiralH()
// {
// return spiralH.nextLongAgain6();
// }
// @Benchmark
// public long measureSpiralI()
// {
// return spiralI.nextLongAgain7();
// }
private OrbitRNG Orbit = new OrbitRNG(9999L, 1337L);
private RNG OrbitR = new RNG(Orbit);
@Benchmark
public long measureOrbit()
{
return Orbit.nextLong();
}
@Benchmark
public int measureOrbitInt()
{
return Orbit.next(32);
}
@Benchmark
public long measureOrbitR()
{
return OrbitR.nextLong();
}
@Benchmark
public int measureOrbitIntR()
{
return OrbitR.nextInt();
}
private TangleRNG Tangle = new TangleRNG(9999L, 1337L);
private RNG TangleR = new RNG(Tangle);
@Benchmark
public long measureTangle()
{
return Tangle.nextLong();
}
@Benchmark
public int measureTangleInt()
{
return Tangle.next(32);
}
@Benchmark
public long measureTangleR()
{
return TangleR.nextLong();
}
@Benchmark
public int measureTangleIntR()
{
return TangleR.nextInt();
}
// private OrbitRNG OrbitA = new OrbitRNG(9999L, 1337L),
// OrbitB = new OrbitRNG(9999L, 1337L),
// OrbitC = new OrbitRNG(9999L, 1337L),
// OrbitD = new OrbitRNG(9999L, 1337L),
// OrbitE = new OrbitRNG(9999L, 1337L),
// OrbitF = new OrbitRNG(9999L, 1337L),
// OrbitG = new OrbitRNG(9999L, 1337L),
// OrbitH = new OrbitRNG(9999L, 1337L),
// OrbitI = new OrbitRNG(9999L, 1337L),
// OrbitJ = new OrbitRNG(9999L, 1337L),
// OrbitK = new OrbitRNG(9999L, 1337L),
// OrbitL = new OrbitRNG(9999L, 1337L),
// OrbitM = new OrbitRNG(9999L, 1337L),
// OrbitN = new OrbitRNG(9999L, 1337L),
// OrbitO = new OrbitRNG(9999L, 1337L);
// @Benchmark
// public long measureOrbitA()
// {
// return OrbitA.nextLong1();
// }
// @Benchmark
// public long measureOrbitB()
// {
// return OrbitB.nextLong2();
// }
// @Benchmark
// public long measureOrbitC()
// {
// return OrbitC.nextLong3();
// }
// @Benchmark
// public long measureOrbitD()
// {
// return OrbitD.nextLong4();
// }
// @Benchmark
// public long measureOrbitE()
// {
// return OrbitE.nextLong5();
// }
// @Benchmark
// public long measureOrbitF()
// {
// return OrbitF.nextLong6();
// }
// @Benchmark
// public long measureOrbitG()
// {
// return OrbitG.nextLong7();
// }
// @Benchmark
// public long measureOrbitH()
// {
// return OrbitH.nextLong8();
// }
// @Benchmark
// public long measureOrbitI()
// {
// return OrbitI.nextLong9();
// }
// @Benchmark
// public long measureOrbitJ()
// {
// return OrbitJ.nextLong10();
// }
// @Benchmark
// public long measureOrbitK()
// {
// return OrbitK.nextLong11();
// }
// @Benchmark
// public long measureOrbitL()
// {
// return OrbitL.nextLong12();
// }
// @Benchmark
// public long measureOrbitM()
// {
// return OrbitM.nextLong13();
// }
// @Benchmark
// public long measureOrbitN()
// {
// return OrbitN.nextLong14();
// }
// @Benchmark
// public long measureOrbitO()
// {
// return OrbitO.nextLong15();
// }
// private TangleRNG TangleA = new TangleRNG(9999L, 1337L),
// TangleB = new TangleRNG(9999L, 1337L),
// TangleC = new TangleRNG(9999L, 1337L),
// TangleD = new TangleRNG(9999L, 1337L);
// @Benchmark
// public long measureTangleA()
// {
// return TangleA.nextLong1();
// }
// @Benchmark
// public long measureTangleB()
// {
// return TangleB.nextLong2();
// }
// @Benchmark
// public long measureTangleC()
// {
// return TangleC.nextLong3();
// }
//
// @Benchmark
// public long measureTangleD()
// {
// return TangleD.nextLong4();
// }
private DuelistRNG Duelist = new DuelistRNG(9999L, 1337L);
private RNG DuelistR = new RNG(Duelist);
@Benchmark
public long measureDuelist()
{
return Duelist.nextLong();
}
@Benchmark
public int measureDuelistInt()
{
return Duelist.next(32);
}
@Benchmark
public long measureDuelistR()
{
return DuelistR.nextLong();
}
@Benchmark
public int measureDuelistIntR()
{
return DuelistR.nextInt();
}
private Mover32RNG Mover32 = new Mover32RNG(0);
private RNG Mover32R = new RNG(Mover32);
@Benchmark
public long measureMover32()
{
return Mover32.nextLong();
}
@Benchmark
public int measureMover32Int()
{
return Mover32.next(32);
}
@Benchmark
public long measureMover32R()
{
return Mover32R.nextLong();
}
@Benchmark
public int measureMover32IntR()
{
return Mover32R.nextInt();
}
private Cake32RNG Cake32 = new Cake32RNG(0);
private RNG Cake32R = new RNG(Cake32);
@Benchmark
public long measureCake32()
{
return Cake32.nextLong();
}
@Benchmark
public int measureCake32Int()
{
return Cake32.next(32);
}
@Benchmark
public long measureCake32R()
{
return Cake32R.nextLong();
}
@Benchmark
public int measureCake32IntR()
{
return Cake32R.nextInt();
}
private MegaMover32RNG MegaMover32 = new MegaMover32RNG(0);
private RNG MegaMover32R = new RNG(MegaMover32);
@Benchmark
public long measureMegaMover32()
{
return MegaMover32.nextLong();
}
@Benchmark
public int measureMegaMover32Int()
{
return MegaMover32.next(32);
}
// @Benchmark
// public int measureMegaMoverB32Int()
// {
// return MegaMover32.next2(32);
// }
// @Benchmark
// public int measureMegaMoverC32Int()
// {
// return MegaMover32.next3(32);
// }
@Benchmark
public long measureMegaMover32R()
{
return MegaMover32R.nextLong();
}
@Benchmark
public int measureMegaMover32IntR()
{
return MegaMover32R.nextInt();
}
private Ladder32RNG Ladder32 = new Ladder32RNG(0);
private RNG Ladder32R = new RNG(Ladder32);
@Benchmark
public long measureLadder32()
{
return Ladder32.nextLong();
}
@Benchmark
public int measureLadder32Int()
{
return Ladder32.next(32);
}
@Benchmark
public long measureLadder32R()
{
return Ladder32R.nextLong();
}
@Benchmark
public int measureLadder32IntR()
{
return Ladder32R.nextInt();
}
private MoverCounter32RNG MoverCounter32 = new MoverCounter32RNG(0);
private RNG MoverCounter32R = new RNG(MoverCounter32);
@Benchmark
public long measureMoverCounter32()
{
return MoverCounter32.nextLong();
}
@Benchmark
public int measureMoverCounter32Int()
{
return MoverCounter32.next(32);
}
@Benchmark
public long measureMoverCounter32R()
{
return MoverCounter32R.nextLong();
}
@Benchmark
public int measureMoverCounter32IntR()
{
return MoverCounter32R.nextInt();
}
// private Mover32RNG Mover32A = new Mover32RNG(0);
// @Benchmark
// public long measureMover32A()
// {
// return Mover32A.nextIntA();
// }
//
// private Mover32RNG Mover32B = new Mover32RNG(0);
// @Benchmark
// public long measureMover32B()
// {
// return Mover32B.nextIntB();
// }
// private Mover32RNG Mover32C = new Mover32RNG(0);
// @Benchmark
// public long measureMover32C()
// {
// return Mover32C.nextIntC();
// }
private Mover64RNG Mover64 = new Mover64RNG(0);
private RNG Mover64R = new RNG(Mover64);
@Benchmark
public long measureMover64()
{
return Mover64.nextLong();
}
@Benchmark
public int measureMover64Int()
{
return Mover64.next(32);
}
@Benchmark
public long measureMover64R()
{
return Mover64R.nextLong();
}
@Benchmark
public int measureMover64IntR()
{
return Mover64R.nextInt();
}
private Molerat32RNG Molerat32 = new Molerat32RNG(0);
private RNG Molerat32R = new RNG(Molerat32);
@Benchmark
public long measureMolerat32()
{
return Molerat32.nextLong();
}
@Benchmark
public int measureMolerat32Int()
{
return Molerat32.next(32);
}
@Benchmark
public long measureMolerat32R()
{
return Molerat32R.nextLong();
}
@Benchmark
public int measureMolerat32IntR()
{
return Molerat32R.nextInt();
}
private MiniMover64RNG MiniMover64 = new MiniMover64RNG(0);
private RNG MiniMover64R = new RNG(MiniMover64);
@Benchmark
public long measureMiniMover64()
{
return MiniMover64.nextLong();
}
@Benchmark
public int measureMiniMover64Int()
{
return MiniMover64.next(32);
}
@Benchmark
public long measureMiniMover64R()
{
return MiniMover64R.nextLong();
}
@Benchmark
public int measureMiniMover64IntR()
{
return MiniMover64R.nextInt();
}
private SFC64RNG SFC64 = new SFC64RNG(9999L);
private RNG SFC64R = new RNG(SFC64);
@Benchmark
public long measureSFC64()
{
return SFC64.nextLong();
}
@Benchmark
public int measureSFC64Int()
{
return SFC64.next(32);
}
@Benchmark
public long measureSFC64R()
{
return SFC64R.nextLong();
}
@Benchmark
public int measureSFC64IntR()
{
return SFC64R.nextInt();
}
private Overdrive64RNG Overdrive64 = new Overdrive64RNG(0);
private RNG Overdrive64R = new RNG(Overdrive64);
@Benchmark
public long measureOverdrive64()
{
return Overdrive64.nextLong();
}
@Benchmark
public int measureOverdrive64Int()
{
return Overdrive64.next(32);
}
@Benchmark
public long measureOverdrive64R()
{
return Overdrive64R.nextLong();
}
@Benchmark
public int measureOverdrive64IntR()
{
return Overdrive64R.nextInt();
}
private MoverCounter64RNG MoverCounter64 = new MoverCounter64RNG(9999L);
private MoverCounter64RNG MoverCounter64Alt = new MoverCounter64RNG(9999L);
private RNG MoverCounter64R = new RNG(MoverCounter64);
@Benchmark
public long measureMoverCounter64()
{
return MoverCounter64.nextLong();
}
@Benchmark
public int measureMoverCounter64Int()
{
return MoverCounter64.next(32);
}
@Benchmark
public long measureMoverCounter64R()
{
return MoverCounter64R.nextLong();
}
@Benchmark
public int measureMoverCounter64IntR()
{
return MoverCounter64R.nextInt();
}
@Benchmark
public long measureMoverCounter64Alt()
{
return MoverCounter64Alt.nextLongAlt();
}
private DirkRNG Dirk = new DirkRNG(9999L);
private RNG DirkR = new RNG(Dirk);
@Benchmark
public long measureDirk()
{
return Dirk.nextLong();
}
@Benchmark
public int measureDirkInt()
{
return Dirk.next(32);
}
@Benchmark
public long measureDirkR()
{
return DirkR.nextLong();
}
@Benchmark
public int measureDirkIntR()
{
return DirkR.nextInt();
}
// private Overdrive64RNG Overdrive1 = new Overdrive64RNG(0);
// private Overdrive64RNG Overdrive2 = new Overdrive64RNG(0);
// private Overdrive64RNG Overdrive3 = new Overdrive64RNG(0);
// private Overdrive64RNG Overdrive4 = new Overdrive64RNG(0);
//
// @Benchmark
// public long measureOverdrive1()
// {
// return Overdrive1.nextLong1();
// }
// @Benchmark
// public long measureOverdrive2()
// {
// return Overdrive2.nextLong2();
// }
// @Benchmark
// public long measureOverdrive3()
// {
// return Overdrive3.nextLong3();
// }
// @Benchmark
// public long measureOverdrive4()
// {
// return Overdrive4.nextLong4();
// }
// private Thrust32RNG Thrust32 = new Thrust32RNG(9999);
// private RNG Thrust32R = new RNG(Thrust32);
//
// @Benchmark
// public long measureThrust32()
// {
// return Thrust32.nextLong();
// }
//
// @Benchmark
// public int measureThrust32Int()
// {
// return Thrust32.next(32);
// }
// @Benchmark
// public long measureThrust32R()
// {
// return Thrust32R.nextLong();
// }
//
// @Benchmark
// public int measureThrust32IntR()
// {
// return Thrust32R.nextInt();
// }
//
//
private ThrustAlt32RNG ThrustAlt32 = new ThrustAlt32RNG(9999);
private RNG ThrustAlt32R = new RNG(ThrustAlt32);
@Benchmark
public long measureThrustAlt32()
{
return ThrustAlt32.nextLong();
}
@Benchmark
public int measureThrustAlt32Int()
{
return ThrustAlt32.next(32);
}
@Benchmark
public long measureThrustAlt32R()
{
return ThrustAlt32R.nextLong();
}
@Benchmark
public int measureThrustAlt32IntR()
{
return ThrustAlt32R.nextInt();
}
private Light32RNG Light32 = new Light32RNG(9999);
private RNG Light32R = new RNG(Light32);
@Benchmark
public long measureLight32()
{
return Light32.nextLong();
}
@Benchmark
public int measureLight32Int()
{
return Light32.next(32);
}
@Benchmark
public long measureLight32R()
{
return Light32R.nextLong();
}
@Benchmark
public int measureLight32IntR()
{
return Light32R.nextInt();
}
private Zig32RNG Zig32 = new Zig32RNG(9999L);
private RNG Zig32R = new RNG(Zig32);
@Benchmark
public long measureZig32()
{
return Zig32.nextLong();
}
@Benchmark
public int measureZig32Int()
{
return Zig32.next(32);
}
@Benchmark
public long measureZig32R()
{
return Zig32R.nextLong();
}
@Benchmark
public int measureZig32IntR()
{
return Zig32R.nextInt();
}
private Zag32RNG Zag32 = new Zag32RNG(9999L);
private RNG Zag32R = new RNG(Zag32);
@Benchmark
public long measureZag32()
{
return Zag32.nextLong();
}
@Benchmark
public int measureZag32Int()
{
return Zag32.next(32);
}
@Benchmark
public long measureZag32R()
{
return Zag32R.nextLong();
}
@Benchmark
public int measureZag32IntR()
{
return Zag32R.nextInt();
}
private Zog32RNG Zog32 = new Zog32RNG(9999L);
private RNG Zog32R = new RNG(Zog32);
@Benchmark
public long measureZog32()
{
return Zog32.nextLong();
}
@Benchmark
public int measureZog32Int()
{
return Zog32.next(32);
}
@Benchmark
public long measureZog32R()
{
return Zog32R.nextLong();
}
@Benchmark
public int measureZog32IntR()
{
return Zog32R.nextInt();
}
private XoRo32RNG XoRo32 = new XoRo32RNG(9999L);
private RNG XoRo32R = new RNG(XoRo32);
@Benchmark
public long measureXoRo32()
{
return XoRo32.nextLong();
}
@Benchmark
public int measureXoRo32Int()
{
return XoRo32.next(32);
}
@Benchmark
public long measureXoRo32R()
{
return XoRo32R.nextLong();
}
@Benchmark
public int measureXoRo32IntR()
{
return XoRo32R.nextInt();
}
private Oriole32RNG Oriole32 = new Oriole32RNG(9999, 999, 99);
private RNG Oriole32R = new RNG(Oriole32);
@Benchmark
public long measureOriole32()
{
return Oriole32.nextLong();
}
@Benchmark
public int measureOriole32Int()
{
return Oriole32.next(32);
}
@Benchmark
public long measureOriole32R()
{
return Oriole32R.nextLong();
}
@Benchmark
public int measureOriole32IntR()
{
return Oriole32R.nextInt();
}
private Lathe32RNG Lathe32 = new Lathe32RNG(9999, 999);
private RNG Lathe32R = new RNG(Lathe32);
@Benchmark
public long measureLathe32()
{
return Lathe32.nextLong();
}
@Benchmark
public int measureLathe32Int()
{
return Lathe32.next(32);
}
@Benchmark
public long measureLathe32R()
{
return Lathe32R.nextLong();
}
@Benchmark
public int measureLathe32IntR()
{
return Lathe32R.nextInt();
}
private Starfish32RNG Starfish32 = new Starfish32RNG(9999, 999);
private RNG Starfish32R = new RNG(Starfish32);
@Benchmark
public long measureStarfish32()
{
return Starfish32.nextLong();
}
@Benchmark
public int measureStarfish32Int()
{
return Starfish32.next(32);
}
@Benchmark
public int measureStarfish32NextInt()
{
return Starfish32.nextInt();
}
@Benchmark
public long measureStarfish32R()
{
return Starfish32R.nextLong();
}
@Benchmark
public int measureStarfish32IntR()
{
return Starfish32R.nextInt();
}
private GWTRNG GWT = new GWTRNG(9999, 999);
@Benchmark
public long measureGWT()
{
return GWT.nextLong();
}
@Benchmark
public int measureGWTInt()
{
return GWT.next(32);
}
@Benchmark
public int measureGWTNextInt()
{
return GWT.nextInt();
}
private Otter32RNG Otter32 = new Otter32RNG(9999, 999);
private RNG Otter32R = new RNG(Otter32);
@Benchmark
public long measureOtter32()
{
return Otter32.nextLong();
}
@Benchmark
public int measureOtter32Int()
{
return Otter32.next(32);
}
@Benchmark
public long measureOtter32R()
{
return Otter32R.nextLong();
}
@Benchmark
public int measureOtter32IntR()
{
return Otter32R.nextInt();
}
private Lobster32RNG Lobster32 = new Lobster32RNG(9999, 999);
private RNG Lobster32R = new RNG(Lobster32);
@Benchmark
public long measureLobster32()
{
return Lobster32.nextLong();
}
@Benchmark
public int measureLobster32Int()
{
return Lobster32.next(32);
}
@Benchmark
public long measureLobster32R()
{
return Lobster32R.nextLong();
}
@Benchmark
public int measureLobster32IntR()
{
return Lobster32R.nextInt();
}
private SeaSlater32RNG SeaSlater32 = new SeaSlater32RNG(9999, 999);
private RNG SeaSlater32R = new RNG(SeaSlater32);
@Benchmark
public long measureSeaSlater32()
{
return SeaSlater32.nextLong();
}
@Benchmark
public int measureSeaSlater32Int()
{
return SeaSlater32.next(32);
}
@Benchmark
public long measureSeaSlater32R()
{
return SeaSlater32R.nextLong();
}
@Benchmark
public int measureSeaSlater32IntR()
{
return SeaSlater32R.nextInt();
}
private Churro32RNG Churro32 = new Churro32RNG(9999, 999, 99);
private RNG Churro32R = new RNG(Churro32);
@Benchmark
public long measureChurro32()
{
return Churro32.nextLong();
}
@Benchmark
public int measureChurro32Int()
{
return Churro32.next(32);
}
@Benchmark
public long measureChurro32R()
{
return Churro32R.nextLong();
}
@Benchmark
public int measureChurro32IntR()
{
return Churro32R.nextInt();
}
private Dizzy32RNG Dizzy32 = new Dizzy32RNG(9999, 999, 99);
private RNG Dizzy32R = new RNG(Dizzy32);
@Benchmark
public long measureDizzy32()
{
return Dizzy32.nextLong();
}
@Benchmark
public int measureDizzy32Int()
{
return Dizzy32.next(32);
}
@Benchmark
public long measureDizzy32R()
{
return Dizzy32R.nextLong();
}
@Benchmark
public int measureDizzy32IntR()
{
return Dizzy32R.nextInt();
}
@Benchmark
public long measureDizzy32IntNative1()
{
return Dizzy32.nextInt();
}
@Benchmark
public long measureDizzy32IntNative2()
{
return Dizzy32.nextInt2();
}
private XoshiroStarStar32RNG XoshiroStarStar32 = new XoshiroStarStar32RNG(9999);
private RNG XoshiroStarStar32R = new RNG(XoshiroStarStar32);
@Benchmark
public long measureXoshiroStarStar32()
{
return XoshiroStarStar32.nextLong();
}
@Benchmark
public int measureXoshiroStarStar32Int()
{
return XoshiroStarStar32.next(32);
}
@Benchmark
public long measureXoshiroStarStar32R()
{
return XoshiroStarStar32R.nextLong();
}
@Benchmark
public int measureXoshiroStarStar32IntR()
{
return XoshiroStarStar32R.nextInt();
}
private XoshiroStarPhi32RNG XoshiroStarPhi32 = new XoshiroStarPhi32RNG(9999);
private RNG XoshiroStarPhi32R = new RNG(XoshiroStarPhi32);
@Benchmark
public long measureXoshiroStarPhi32()
{
return XoshiroStarPhi32.nextLong();
}
@Benchmark
public int measureXoshiroStarPhi32Int()
{
return XoshiroStarPhi32.next(32);
}
@Benchmark
public long measureXoshiroStarPhi32R()
{
return XoshiroStarPhi32R.nextLong();
}
@Benchmark
public int measureXoshiroStarPhi32IntR()
{
return XoshiroStarPhi32R.nextInt();
}
private XoshiroXara32RNG XoshiroXara32 = new XoshiroXara32RNG(9999);
private RNG XoshiroXara32R = new RNG(XoshiroXara32);
@Benchmark
public long measureXoshiroXara32()
{
return XoshiroXara32.nextLong();
}
@Benchmark
public int measureXoshiroXara32Int()
{
return XoshiroXara32.next(32);
}
@Benchmark
public long measureXoshiroXara32R()
{
return XoshiroXara32R.nextLong();
}
@Benchmark
public int measureXoshiroXara32IntR()
{
return XoshiroXara32R.nextInt();
}
private XoshiroAra32RNG XoshiroAra32 = new XoshiroAra32RNG(9999);
private RNG XoshiroAra32R = new RNG(XoshiroAra32);
@Benchmark
public long measureXoshiroAra32()
{
return XoshiroAra32.nextLong();
}
@Benchmark
public int measureXoshiroAra32Int()
{
return XoshiroAra32.next(32);
}
@Benchmark
public long measureXoshiroAra32R()
{
return XoshiroAra32R.nextLong();
}
@Benchmark
public int measureXoshiroAra32IntR()
{
return XoshiroAra32R.nextInt();
}
private XoshiroSushi32RNG XoshiroSushi32 = new XoshiroSushi32RNG(9999);
private RNG XoshiroSushi32R = new RNG(XoshiroSushi32);
@Benchmark
public long measureXoshiroSushi32()
{
return XoshiroSushi32.nextLong();
}
@Benchmark
public int measureXoshiroSushi32Int()
{
return XoshiroSushi32.next(32);
}
@Benchmark
public long measureXoshiroSushi32R()
{
return XoshiroSushi32R.nextLong();
}
@Benchmark
public int measureXoshiroSushi32IntR()
{
return XoshiroSushi32R.nextInt();
}
private DervishRNG Dervish = new DervishRNG(9999L);
private RNG DervishR = new RNG(Dervish);
@Benchmark
public long measureDervish()
{
return Dervish.nextLong();
}
@Benchmark
public int measureDervishInt()
{
return Dervish.next(32);
}
@Benchmark
public long measureDervishR()
{
return DervishR.nextLong();
}
@Benchmark
public int measureDervishIntR()
{
return DervishR.nextInt();
}
private LinnormRNG Linnorm = new LinnormRNG(9999L);
private RNG LinnormR = new RNG(Linnorm);
@Benchmark
public long measureLinnorm()
{
return Linnorm.nextLong();
}
@Benchmark
public int measureLinnormInt()
{
return Linnorm.next(32);
}
@Benchmark
public long measureLinnormR()
{
return LinnormR.nextLong();
}
@Benchmark
public int measureLinnormIntR()
{
return LinnormR.nextInt();
}
private MizuchiRNG Mizuchi = new MizuchiRNG(9999L);
private RNG MizuchiR = new RNG(Mizuchi);
@Benchmark
public long measureMizuchi()
{
return Mizuchi.nextLong();
}
@Benchmark
public int measureMizuchiInt()
{
return Mizuchi.next(32);
}
@Benchmark
public long measureMizuchiR()
{
return MizuchiR.nextLong();
}
@Benchmark
public int measureMizuchiIntR()
{
return MizuchiR.nextInt();
}
private QuixoticRNG Quixotic = new QuixoticRNG(9999L);
private RNG QuixoticR = new RNG(Quixotic);
@Benchmark
public long measureQuixotic()
{
return Quixotic.nextLong();
}
@Benchmark
public int measureQuixoticInt()
{
return Quixotic.next(32);
}
@Benchmark
public long measureQuixoticR()
{
return QuixoticR.nextLong();
}
@Benchmark
public int measureQuixoticIntR()
{
return QuixoticR.nextInt();
}
private DiverRNG Diver = new DiverRNG(9999L);
private RNG DiverR = new RNG(Diver);
@Benchmark
public long measureDiver()
{
return Diver.nextLong();
}
@Benchmark
public int measureDiverInt()
{
return Diver.next(32);
}
@Benchmark
public long measureDiverR()
{
return DiverR.nextLong();
}
@Benchmark
public int measureDiverIntR()
{
return DiverR.nextInt();
}
private PelicanRNG Pelican = new PelicanRNG(9999L);
private RNG PelicanR = new RNG(Pelican);
@Benchmark
public long measurePelican()
{
return Pelican.nextLong();
}
@Benchmark
public int measurePelicanInt()
{
return Pelican.next(32);
}
@Benchmark
public long measurePelicanR()
{
return PelicanR.nextLong();
}
@Benchmark
public int measurePelicanIntR()
{
return PelicanR.nextInt();
}
private PulleyRNG Pulley = new PulleyRNG(9999L);
private RNG PulleyR = new RNG(Pulley);
@Benchmark
public long measurePulley()
{
return Pulley.nextLong();
}
@Benchmark
public int measurePulleyInt()
{
return Pulley.next(32);
}
@Benchmark
public long measurePulleyR()
{
return PulleyR.nextLong();
}
@Benchmark
public int measurePulleyIntR()
{
return PulleyR.nextInt();
}
private ToppingRNG Topping = new ToppingRNG(9999L);
private RNG ToppingR = new RNG(Topping);
@Benchmark
public long measureTopping()
{
return Topping.nextLong();
}
@Benchmark
public int measureToppingInt()
{
return Topping.next(32);
}
@Benchmark
public long measureToppingR()
{
return ToppingR.nextLong();
}
@Benchmark
public int measureToppingIntR()
{
return ToppingR.nextInt();
}
private IsaacRNG Isaac = new IsaacRNG(9999L);
private RNG IsaacR = new RNG(Isaac);
@Benchmark
public long measureIsaac()
{
return Isaac.nextLong();
}
@Benchmark
public long measureIsaacInt()
{
return Isaac.next(32);
}
@Benchmark
public long measureIsaacR()
{
return IsaacR.nextLong();
}
@Benchmark
public long measureIsaacIntR()
{
return IsaacR.nextInt();
}
private Isaac32RNG Isaac32 = new Isaac32RNG(9999L);
private RNG Isaac32R = new RNG(Isaac32);
@Benchmark
public long measureIsaac32()
{
return Isaac32.nextLong();
}
@Benchmark
public long measureIsaac32Int()
{
return Isaac32.next(32);
}
@Benchmark
public long measureIsaac32R()
{
return Isaac32R.nextLong();
}
@Benchmark
public long measureIsaac32IntR()
{
return Isaac32R.nextInt();
}
private GoatRNG Goat = new GoatRNG(9999L);
private RNG GoatR = new RNG(Goat);
@Benchmark
public long measureGoat()
{
return Goat.nextLong();
}
@Benchmark
public int measureGoatInt()
{
return Goat.next(32);
}
@Benchmark
public long measureGoatR()
{
return GoatR.nextLong();
}
@Benchmark
public int measureGoatIntR()
{
return GoatR.nextInt();
}
private Random JDK = new Random(9999L);
@Benchmark
public long measureJDK()
{
return JDK.nextLong();
}
@Benchmark
public int measureJDKInt()
{
return JDK.nextInt();
}
/*
mvn clean install
java -jar target/benchmarks.jar RNGBenchmark -wi 5 -i 5 -f 1
*/
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(RNGBenchmark.class.getSimpleName())
.timeout(TimeValue.seconds(30))
.warmupIterations(5)
.measurementIterations(5)
.forks(1)
.build();
new Runner(opt).run();
}
}
|
package jp.personal.server.web.controller.api;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import jp.personal.server.data.common.PageParam;
import jp.personal.server.data.message.SaveMessageDto;
import jp.personal.server.data.room.RoomWithUsersMsgDto;
import jp.personal.server.domain.entity.SesUser;
import jp.personal.server.exception.AccessPermissonException;
import jp.personal.server.exception.AuthException;
import jp.personal.server.manager.MessageManager;
import jp.personal.server.manager.VisitorManager;
import jp.personal.server.service.MessageService;
import jp.personal.server.service.RoomService;
import jp.personal.server.utils.Cookies;
import jp.personal.server.utils.Msg;
import jp.personal.server.web.controller.base.BaseApi;
import jp.personal.server.web.form.message.MessageForm;
import jp.personal.server.web.json.message.DelMessageJson;
import jp.personal.server.web.json.message.PostMessageJson;
import jp.personal.server.web.json.message.RoomMessageJson;
/**
* ルームメッセージを管理するcontrollerです。
*
* @author noguchi_kohei
*/
@RestController
@RequestMapping(value = "/api/v1/rooms/{roomId}/messages", produces = MediaType.APPLICATION_JSON_VALUE)
public class ApiMessageController extends BaseApi {
@Autowired
private RoomService roomService;
@Autowired
private MessageService messageService;
@Autowired
private MessageManager messageManager;
@Autowired
private VisitorManager visitorManager;
/**
* ルームのメッセージ一覧をを取得します。
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public RoomMessageJson get(@PathVariable Integer roomId,
@RequestParam(value = "lastId", required = false) Optional<Integer> lastIdOpt,
@RequestParam(value = "limit", required = false) Integer limit, HttpServletRequest req) {
SesUser sesUser = visitorManager.getSesUserOpt(Cookies.getKey(req))
.orElseThrow(() -> new AuthException(Msg.FAIL_AUTH, true));
if (!roomService.isRoomUser(sesUser.getUserId(), roomId)) {
throw new AccessPermissonException(Msg.FORBIDDEN_ROOM, true);
}
Optional<PageParam> pageOpt = lastIdOpt.map(lastId -> new PageParam(lastId, limit));
Optional<RoomWithUsersMsgDto> roomWithUsersMsgOpt = roomService.getRoomWithUsersMsgOpt(sesUser.getUserId(),
roomId, pageOpt);
if (roomWithUsersMsgOpt.isPresent()) {
return RoomMessageJson.create(roomWithUsersMsgOpt.get());
} else {
return new RoomMessageJson();
}
}
/**
* メッセージを送信します。
*/
@RequestMapping(value = "", method = RequestMethod.POST)
public PostMessageJson register(@PathVariable Integer roomId, @RequestBody @Validated MessageForm form,
HttpServletRequest req) {
SesUser sesUser = visitorManager.getSesUserOpt(Cookies.getKey(req))
.orElseThrow(() -> new AuthException(Msg.FAIL_AUTH, true));
if (!sesUser.getUserId().equals(form.getUserId())) {
throw new AccessPermissonException(Msg.FORBIDDEN_USER, true);
}
if (!roomService.isRoomUser(sesUser.getUserId(), roomId)) {
throw new AccessPermissonException(Msg.FORBIDDEN_ROOM, true);
}
SaveMessageDto dto = messageService.register(roomId, form.getUserId(), form.getContent());
return PostMessageJson.create(dto);
}
@RequestMapping(value = "/{messageId}", method = RequestMethod.DELETE)
public DelMessageJson register(@PathVariable Integer roomId, @PathVariable Long messageId, HttpServletRequest req) {
SesUser sesUser = visitorManager.getSesUserOpt(Cookies.getKey(req))
.orElseThrow(() -> new AuthException(Msg.FAIL_AUTH, true));
if (!roomService.isRoomUser(sesUser.getUserId(), roomId)) {
throw new AccessPermissonException(Msg.FORBIDDEN_ROOM, true);
}
if (!messageService.isMessageUser(sesUser.getUserId(), messageId)) {
throw new AccessPermissonException(Msg.FORBIDDEN_MSG, true);
}
return DelMessageJson.create(messageService.delete(roomId, sesUser.getUserId(), messageId));
}
}
|
package com.mikhniuk.chat;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Observable;
/**
* Created by Рома on 06.02.2016.
*/
public class ClientThread extends Observable implements Runnable {
private Socket socket;
private String ip = "46.101.96.234";
private String user_id;
private String exception;
private int port = 4444;
private BufferedReader reader;
private boolean finish;
private String message;
private static ClientThread singleton;
public static ClientThread getSingleton() {
if (singleton == null) {
singleton = new ClientThread();
Thread thread = new Thread(singleton);
thread.start();
}
return singleton;
}
private ClientThread() {
finish = false;
}
/*
public ClientThread() {
finish = false;
}
*/
private String combine(String s){
String ans = "";
int i = s.length()-1;
while(s.charAt(i) != ' '){
ans = s.charAt(i) + ans;
i--;
}
return ans;
}
public String getUser_id(){
return user_id;
}
@Override
public void run() {
try {
this.socket = new Socket(ip, port);
while (!socket.isConnected()) {
Thread.sleep(100);
}
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
message = reader.readLine();
user_id = combine(message);
setChanged();
notifyObservers();
while (!finish) {
message = reader.readLine();
setChanged();
notifyObservers();
Thread.sleep(100);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void finish() {
finish = true;
singleton = null;
}
public void sendMail(final String mail) {
try {
final PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
Thread tr = new Thread(new Runnable() {
@Override
public void run() {
writer.println(mail);
}
});
tr.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getMessage() {
return message;
}
public String getException() {
return exception;
}
}
|
package com.tt.miniapp.notification;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Parcelable;
import com.tt.miniapp.process.AppProcessManager;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.host.HostDependManager;
public class MiniAppNotificationManager {
public static void cancelPayNotification(NotificationEntity paramNotificationEntity) {}
public static NotificationEntity createPayNotification() {
return null;
}
private static boolean enable() {
return HostDependManager.getInst().getPayEnable();
}
public static void init(Context paramContext) {
if (Build.VERSION.SDK_INT >= 26) {
NotificationManager notificationManager = (NotificationManager)paramContext.getSystemService("notification");
if (notificationManager == null)
return;
String str2 = paramContext.getString(2097741963);
String str1 = paramContext.getString(2097742049);
NotificationChannel notificationChannel = new NotificationChannel("miniAppPay", str2, 4);
notificationChannel.setDescription(str1);
notificationChannel.enableLights(false);
notificationChannel.enableVibration(false);
if (enable())
notificationManager.createNotificationChannel(notificationChannel);
}
}
private static void startMiniAppServiceForeground(int paramInt, Notification paramNotification) {
Class clazz = AppProcessManager.getCurrentMiniAppProcessServiceClass();
if (clazz == null)
return;
Application application = AppbrandContext.getInst().getApplicationContext();
Intent intent = new Intent((Context)application, clazz);
intent.putExtra("command", "startForeground");
intent.putExtra("foregroundNotificationId", paramInt);
intent.putExtra("foregroundNotification", (Parcelable)paramNotification);
try {
_lancet.com_ss_android_ugc_aweme_push_downgrade_StartServiceLancet_startService((Context)application, intent);
return;
} catch (Exception exception) {
AppBrandLogger.e("MiniAppNotificationManager", new Object[] { "startMiniAppServiceForeground", exception });
return;
}
}
private static void stopMiniAppServiceForeground() {
Class clazz = AppProcessManager.getCurrentMiniAppProcessServiceClass();
if (clazz == null)
return;
Application application = AppbrandContext.getInst().getApplicationContext();
Intent intent = new Intent((Context)application, clazz);
intent.putExtra("command", "stopForeground");
try {
_lancet.com_ss_android_ugc_aweme_push_downgrade_StartServiceLancet_startService((Context)application, intent);
return;
} catch (Exception exception) {
AppBrandLogger.e("MiniAppNotificationManager", new Object[] { "startMiniAppServiceForeground", exception });
return;
}
}
public static class NotificationEntity {
private final Notification mNotification;
private final int mNotificationId;
public NotificationEntity(int param1Int, Notification param1Notification) {
this.mNotificationId = param1Int;
this.mNotification = param1Notification;
}
public Notification getNotification() {
return this.mNotification;
}
public int getNotificationId() {
return this.mNotificationId;
}
}
class MiniAppNotificationManager {}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\notification\MiniAppNotificationManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
public class CalculationErrorException extends Exception{
private static final String CALCULATION_ERROR = "Calculation Error.";
public CalculationErrorException(){
super(CALCULATION_ERROR);
}
}
|
package com.products.domain.mappers;
import com.products.data.entities.ProductEntity;
import com.products.domain.dto.Product;
import org.springframework.core.convert.converter.Converter;
import java.util.ArrayList;
import java.util.List;
public class ProductsMapper implements Converter<List<ProductEntity>,List<Product>> {
@Override
public List<Product> convert(List<ProductEntity> productsEntity) {
List<Product> products = new ArrayList<>();
productsEntity.forEach(productEntity -> {
products.add(Product.builder()
.id(productEntity.getId())
.price(productEntity.getPrice())
.image(productEntity.getImage())
.description(productEntity.getDescription())
.brand(productEntity.getBrand())
.build());
});
return products;
}
}
|
package ai.skymind.skil.examples.modelserver.inference;
import ai.skymind.skil.examples.modelserver.inference.model.Knn;
import ai.skymind.skil.examples.modelserver.inference.model.Inference;
import ai.skymind.skil.examples.modelserver.inference.model.TransformedArray;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.JCommander;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class ModelServerInferenceExample {
private enum InferenceType {
Multi,
Single,
Knn
}
@Parameter(names="--transform", description="Endpoint for Transform", required=true)
private String transformedArrayEndpoint;
@Parameter(names="--inference", description="Endpoint for Inference", required=true)
private String inferenceEndpoint;
@Parameter(names="--type", description="Type of endpoint (multi or single)", required=true)
private InferenceType inferenceType;
@Parameter(names="--input", description="CSV input file", required=true)
private String inputFile;
@Parameter(names="--sequential", description="If this transform a sequential one", required=false)
private boolean isSequential = false;
@Parameter(names="--knn", description="Number of K Nearest Neighbors to return", required=false)
private int knnN = 20;
@Parameter(names="--textAsJson", description="Parse text/plain as JSON", required=false, arity=1)
private boolean textAsJson;
public void run() throws Exception {
final File file = new File(inputFile);
if (!file.exists() || !file.isFile()) {
System.err.format("unable to access file %s\n", inputFile);
System.exit(2);
}
// Open file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
SkilClient skilClient = new SkilClient(textAsJson);
// Read each line
String line = null;
while ((line = br.readLine()) != null) {
String[] fields = line.split(",");
// Maybe strip quotes
for (int i=0; i<fields.length; i++) {
final String field = fields[i];
if (field.matches("^\".*\"$")) {
fields[i] = field.substring(1, field.length()-1);
}
}
final TransformedArray.Response arrayResponse;
if (isSequential) {
arrayResponse = skilClient.transform(
transformedArrayEndpoint,
new TransformedArray.BatchedRequest(fields)
);
} else {
arrayResponse = skilClient.transform(
transformedArrayEndpoint,
new TransformedArray.Request(fields)
);
}
Object response;
if (inferenceType == InferenceType.Single) {
response = skilClient.classify(inferenceEndpoint, new Inference.Request(arrayResponse.getNdArray()));
} else if (inferenceType == InferenceType.Multi) {
response = skilClient.multiClassify(inferenceEndpoint, new Inference.Request(arrayResponse.getNdArray()));
} else {
response = skilClient.knn(inferenceEndpoint, new Knn.Request(knnN, arrayResponse.getNdArray()));
}
System.out.format("Inference response: %s\n", response.toString());
}
br.close();
}
public static void main(String[] args) throws Exception {
ModelServerInferenceExample m = new ModelServerInferenceExample();
JCommander.newBuilder()
.addObject(m)
.build()
.parse(args);
m.run();
}
}
|
package com.example.tagebuch.view.fragmentos;
import android.graphics.Color;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.tagebuch.R;
import com.example.tagebuch.controller.ControladorInterfazPrincipal;
import com.example.tagebuch.view.Actividad_interfaz_principal;
public class item_pensamiento extends Fragment {
private TextView contenedorTituloPemsamiento;
private TextView contenedorFechaPensamiento;
private TextView contenedorDescripcion;
private TextView contenedorCategoria;
private String tituloPensamiento;
private String fechaPensamiento;
private String descripicionPensamiento;
private String categoriaPensamiento;
private String colorPensamiento;
private Button marcoPensamiento;
private View rootView;
private ControladorInterfazPrincipal controladorInterfazPrincipal;
public item_pensamiento() {
// Required empty public constructor
}
public static item_pensamiento newInstance(String titulo, String fecha, String descripcion, String categoria, String color) {
item_pensamiento fragment = new item_pensamiento();
fragment.setTituloPensamiento(titulo);
fragment.setFechaPensamiento(fecha);
fragment.setDescripicionPensamiento(descripcion);
fragment.setCategoriaPensamiento(categoria);
fragment.setColorPensamiento(color);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_item_pensamiento, container, false);
contenedorTituloPemsamiento = rootView.findViewById(R.id.titulo_item_pensamiento);
contenedorFechaPensamiento = rootView.findViewById(R.id.fecha_item_pensamiento);
contenedorDescripcion = rootView.findViewById(R.id.descripcion_item_pensamiento);
contenedorCategoria = rootView.findViewById(R.id.categoria_item_pensamiento);
marcoPensamiento = rootView.findViewById(R.id.boton_marco_item_pensamiento);
contenedorTituloPemsamiento.setText(tituloPensamiento);
contenedorFechaPensamiento.setText(fechaPensamiento);
contenedorDescripcion.setText(descripicionPensamiento);
contenedorCategoria.setText(categoriaPensamiento);
marcoPensamiento.setBackgroundColor(Color.parseColor(colorPensamiento));
controladorInterfazPrincipal = new ControladorInterfazPrincipal();
marcoPensamiento.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarDetalleControlador();
}
});
return rootView;
}
public void mostrarDetalleControlador(){
controladorInterfazPrincipal.mostrarDetallePensamiento((Actividad_interfaz_principal) this.getActivity(), categoriaPensamiento,
fechaPensamiento,tituloPensamiento,descripicionPensamiento,colorPensamiento);
}
public String getTituloPensamiento() {
return tituloPensamiento;
}
public void setTituloPensamiento(String tituloPensamiento) {
this.tituloPensamiento = tituloPensamiento;
}
public String getFechaPensamiento() {
return fechaPensamiento;
}
public void setFechaPensamiento(String fechaPensamiento) {
this.fechaPensamiento = fechaPensamiento;
}
public String getDescripicionPensamiento() {
return descripicionPensamiento;
}
public void setDescripicionPensamiento(String descripicionPensamiento) {
this.descripicionPensamiento = descripicionPensamiento;
}
public String getCategoriaPensamiento() {
return categoriaPensamiento;
}
public void setCategoriaPensamiento(String categoriaPensamiento) {
this.categoriaPensamiento = categoriaPensamiento;
}
public String getColorPensamiento() {
return colorPensamiento;
}
public void setColorPensamiento(String colorPensamiento) {
this.colorPensamiento = colorPensamiento;
}
} |
package smart.lib.thymeleaf;
import smart.cache.ExpressCache;
import smart.cache.PaymentCache;
import smart.cache.RegionCache;
import smart.cache.SystemCache;
import smart.lib.Region;
import smart.lib.status.AccountStatus;
import smart.lib.status.OrderGoodsStatus;
import smart.lib.status.OrderStatus;
import smart.lib.status.GenderInfo;
import smart.util.Helper;
import java.time.LocalDateTime;
import java.util.Date;
/**
* thymeleaf utils
* helper functions for thymeleaf
* 自定义方言
*/
public class HelperUtils {
public static String dateFormat(Date date) {
return Helper.dateFormat(date);
}
public static String dateFormat(Date date, String pattern) {
return Helper.dateFormat(date, pattern);
}
public static String dateFormat(LocalDateTime localDateTime) {
return Helper.dateFormat(localDateTime);
}
public static String dateFormat(LocalDateTime localDateTime, String pattern) {
return Helper.dateFormat(localDateTime, pattern);
}
/**
* 获取账号状态信息
*
* @param code code
* @return info
*/
public static String getAccountStatusInfo(long code) {
return AccountStatus.getStatusInfo(code);
}
/**
* 获取快递公司名称
*
* @param id id
* @return 快递公司名称
*/
public static String getExpressNameById(long id) {
return ExpressCache.getNameById(id);
}
/**
* 获取支付名称
*
* @param name 支付方式英文名称
* @return 中文名称
*/
public static String getPayName(String name) {
var payment = PaymentCache.getPaymentByName(name);
if (payment == null) {
return name;
}
return payment.getName1();
}
/**
* 获取性别信息
*
* @param code code
* @return info
*/
public static String getGenderInfo(long code) {
return GenderInfo.getGenderInfo(code);
}
/**
* 获取订单商品状态信息
*
* @param code 订单商品状态码
* @return 状态信息
*/
public static String getOrderGoodsStatusInfo(long code) {
return OrderGoodsStatus.getStatusInfo(code);
}
/**
* 获取订单状态信息
*
* @param code 订单状态码
* @return 状态信息
*/
public static String getOrderStatusInfo(long code) {
return OrderStatus.getStatusInfo(code);
}
public static Region getRegion(long code) {
return RegionCache.getRegion(code);
}
/**
* 正方形图片缩放
*
* @param url 图片地址
* @param width 图片宽度
* @return 缩放后的地址
*/
public static String imgZoom(String url, long width) {
//noinspection SuspiciousNameCombination
return imgZoom(url, width, width);
}
/**
* 图片缩放
*
* @param url image url
* @param width zooming width
* @param height zooming width
* @return 缩放后的地址
*/
public static String imgZoom(String url, long width, long height) {
if (url != null) {
String url1 = url.toLowerCase();
if (url.startsWith("http")) {
/* for aliyun oss */
url += "?x-oss-process=image/resize,w_" + width;
if (height > 0) {
url += ",h_" + height;
}
return url;
}
/* for nginx */
url += "?w=" + width;
if (height > 0) {
url += "&h=" + height;
}
return url;
}
return null;
}
/**
* 格式化价格
*
* @param price 价格(分)
* @return 价格(元, 保留两位小数)
*/
public static String priceFormat(Long price) {
return price == null ? null : Helper.priceFormat(price);
}
/**
* 根据系统配置生成静态文件(css/js)路径
*
* @param path css/js file path
* @return css/js file url
*/
public static String retouch(String path) {
return SystemCache.getJsPath() + path + "?v=" + SystemCache.getJsVersion();
}
}
|
/*
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
Input: n = 10, pick = 6
Output: 6
*/
public class Solution extends GuessGame {
public int guessNumber(int n) {
int start = 1, mid , end = n;
while(start>=1 && end <=n && start <= end){
mid = (end-start)/2 + start;
if(guess(mid) == 0){
return mid;
}else if(guess(start) == 0)
return start;
else if(guess(end)== 0)
return end;
else if(guess(mid) == -1){
end = mid-1;
}else
start = mid+1;
}
return -1;
}
}
|
package com.devcamp.currencyconverter.repositories;
import com.devcamp.currencyconverter.model.entities.Currency;
import com.devcamp.currencyconverter.model.entities.RateLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
@Repository
public interface RateLogRepository extends JpaRepository<RateLog, Long> {
RateLog findFirstByDate(LocalDate date);
RateLog findBySourceCurrencyAndTargetCurrencyAndDate(Currency source, Currency target, LocalDate date);
}
|
package com.rx.rxmvvmlib.ui.base;
import android.app.Activity;
import java.lang.ref.SoftReference;
import java.util.Stack;
import androidx.fragment.app.Fragment;
/**
* activity堆栈式管理
*/
public class AppManager {
private SoftReference<Stack<Activity>> activityStack = new SoftReference<>(new Stack<Activity>());
private SoftReference<Stack<Fragment>> fragmentStack = new SoftReference<>(new Stack<Fragment>());
private static volatile AppManager instance;
private AppManager() {
}
/**
* 单例模式
*
* @return AppManager
*/
public static AppManager getInstance() {
if (instance == null) {
synchronized (AppManager.class) {
if (instance == null) {
instance = new AppManager();
}
}
}
return instance;
}
public Stack<Activity> getActivityStack() {
return activityStack.get();
}
public Stack<Fragment> getFragmentStack() {
return fragmentStack.get();
}
/**
* 添加Activity到堆栈
*/
public void addActivity(Activity activity) {
if (activityStack.get() != null) {
activityStack.get().add(activity);
}
}
/**
* 移除指定的Activity
*/
public void removeActivity(Activity activity) {
if (activityStack.get() != null) {
activityStack.get().remove(activity);
}
}
/**
* 是否有activity
*/
public boolean isActivity() {
return activityStack.get() != null && !activityStack.get().isEmpty();
}
/**
* 获取当前Activity(堆栈中最后一个压入的)
*/
public Activity currentActivity() {
try {
if (activityStack.get() != null) {
return activityStack.get().lastElement();
}
return null;
} catch (Exception e) {
return null;
}
}
/**
* 结束当前Activity(堆栈中最后一个压入的)
*/
public void finishActivity() {
if (activityStack.get() != null) {
finishActivity(activityStack.get().lastElement());
}
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
if (!activity.isFinishing()) {
activity.finish();
}
removeActivity(activity);
}
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
if (activityStack.get() != null) {
for (Activity activity : activityStack.get()) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
break;
}
}
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
if (activityStack.get() != null) {
for (int i = 0, size = activityStack.get().size(); i < size; i++) {
if (null != activityStack.get().get(i)) {
finishActivity(activityStack.get().get(i));
}
}
activityStack.get().clear();
}
}
/**
* 获取指定的Activity
*/
public Activity getActivity(Class<?> cls) {
if (activityStack.get() != null) {
for (Activity activity : activityStack.get()) {
if (activity.getClass().equals(cls)) {
return activity;
}
}
}
return null;
}
/**
* 添加Fragment到堆栈
*/
public void addFragment(Fragment fragment) {
if (fragmentStack.get() != null) {
fragmentStack.get().add(fragment);
}
}
/**
* 移除指定的Fragment
*/
public void removeFragment(Fragment fragment) {
if (fragmentStack.get() != null) {
fragmentStack.get().remove(fragment);
}
}
/**
* 是否有Fragment
*/
public boolean isFragment() {
return fragmentStack.get() != null && !fragmentStack.get().isEmpty();
}
/**
* 获取当前Activity(堆栈中最后一个压入的)
*/
public Fragment currentFragment() {
if (fragmentStack.get() != null) {
return fragmentStack.get().lastElement();
}
return null;
}
/**
* 退出应用程序
*/
public void appExit() {
try {
finishAllActivity();
// 杀死该应用进程
// android.os.Process.killProcess(android.os.Process.myPid());
// 调用 System.exit(n) 实际上等效于调用:
// Runtime.getRuntime().exit(n)
// finish()是Activity的类方法,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用System.exit(0)时,退出当前Activity并释放资源(内存),但是该方法不可以结束整个App如有多个Activty或者有其他组件service等不会结束。
// 其实android的机制决定了用户无法完全退出应用,当你的application最长时间没有被用过的时候,android自身会决定将application关闭了。
//System.exit(0);
} catch (Exception e) {
if (activityStack.get() != null) {
activityStack.get().clear();
}
e.printStackTrace();
}
}
} |
package HuaWei;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
public class 扑克牌24点运算 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String[] arr = new String[4];
int flag = 0;
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 4; i++) {
arr[i] = in.next();
if (arr[i].toUpperCase().equals("JOKER")) {
flag = 1;
}else if(arr[i].equals("J")) {
arr[i]="11";
map.put(arr[i], "J");
}else if (arr[i].equals("Q")) {
arr[i]="12";
map.put(arr[i], "Q");
}else if (arr[i].equals("K")) {
arr[i]="13";
map.put(arr[i], "K");
}else if (arr[i].equals("A")) {
arr[i]="1";
map.put(arr[i], "A");
}
else if (arr[i].equals("2")||arr[i].equals("3")||
arr[i].equals("4")||arr[i].equals("5")||arr[i].equals("6")
||arr[i].equals("7")||arr[i].equals("8")||arr[i].equals("9")
||arr[i].equals("10")||arr[i].equals("1")) {
map.put(arr[i], arr[i]);
}else {
flag=2;
}
}
if (flag==0) {
int[] data = new int[4];
for (int i = 0; i < arr.length; i++) {
data[i] = Integer.valueOf(arr[i]);
}
Stack<String> result = new Stack<>();
boolean[] flags = new boolean[4];
if (find24(data, result, flags,0,4)) {
StringBuilder a =new StringBuilder();
while (!result.isEmpty()) {
String s = result.pop();
String s1 = map.get(s);
if (s1!=null) {
a.append(s1);
}else {
a.append(s);
}
}
System.out.println(a.reverse());
}else {
System.out.println("NONE");
}
}else if (flag==1) {
System.out.println("ERROR");
} else {
System.out.println("NONE");
}
}
}
public static boolean find24(int[] arr,Stack<String> result,boolean[] flag,float total,int length){
if (length==0) {
//System.out.println(total);
return total==24;
}
if (length==4) {
for (int i = 0; i < flag.length; i++) {
total=arr[i];
flag[i]=true;
result.push(arr[i]+"");
if (find24(arr, result, flag, total, length-1)) {
return true;
}else {
result.pop();
flag[i] =false;
}
}
return false;
}
for (int i = 0; i < flag.length; i++) {
if (flag[i]==false) {
int a = arr[i];
flag[i]=true;
//减
float total2=total-a;
result.push("-");
result.push(a+"");
if (find24(arr, result, flag, total2, length-1)) {
return true;
}
result.pop();
result.pop();
//加
float total1=total+a;
result.push("+");
result.push(a+"");
if (find24(arr, result, flag, total1, length-1)) {
return true;
}
result.pop();
result.pop();
//乘
float total3 = total*a;
result.push("*");
result.push(a+"");
if (find24(arr, result, flag, total3, length-1)) {
return true;
}
result.pop();
result.pop();
//除 因为除的存在所以不能使用int 除法,要带小数才行
if (a!=0) {
float total4 = total/a;
result.push("/");
result.push(a+"");
if (find24(arr, result, flag, total4, length-1)) {
return true;
}
result.pop();
result.pop();
}
flag[i] = false;
}
}
return false;
}
}
|
package banyuan.day02.practice04;
import java.util.Scanner;
/**
* 2.输入三个班,每班10个学生的成绩,求每个班的总分和平均分
*
* @author newpc
*/
public class P02 {
public static void main(String[] args) {
int sum = 0;
int avg = 0;
int[][] student = new int[3][10];
Scanner in = new Scanner(System.in);
for (int i = 0; i < student.length; i++) {
for (int j = 0; j < student[0].length; j++) {
int input = in.nextInt();
student[i][j] = input;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < student[0].length; j++) {
sum += student[i][j];
}
avg = sum / 10;
System.out.println(sum);
System.out.println(avg);
}
}
}
|
package com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.common.shape;
import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.thirdpart.achartengine.chart.AbstractChart;
public class WPChartShape extends WPAutoShape
{
public AbstractChart getAChart()
{
return chart;
}
public void setAChart(AbstractChart chart)
{
this.chart = chart;
}
private AbstractChart chart;
}
|
package pe.egcc.pp03app;
import pe.egcc.pp03app.view.PP03View;
public class PP03App {
public static void main(String[] args) {
PP03View.main(args);
}
}
|
/**
*
*/
package com.yk.shop.modules.message.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yk.shop.baseentity.Page;
import com.yk.shop.common.service.CrudService;
import com.yk.shop.modules.message.entity.MessageBase;
import com.yk.shop.modules.message.dao.MessageBaseDao;
/**
* 消息Service
* @author 黄寿勇
* @version 2018-05-17
*/
@Service
@Transactional(readOnly = true)
public class MessageBaseService extends CrudService<MessageBaseDao, MessageBase> implements IMessageBaseService{
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jakc.payment.os.controller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jakc.common.util.ProcessCallBack;
import org.jakc.payment.Auth;
import org.jakc.payment.db.controller.BackingController;
import org.jakc.payment.db.entity.BillingParking;
import org.jakc.payment.db.entity.RequestTransaksiStiker;
import org.jakc.payment.db.entity.TarifStiker;
import org.jakc.payment.db.entity.TransaksiStiker;
import org.jakc.payment.os.gui.BillingGridFrame;
import org.jakc.payment.os.vo.BillingVo;
import org.openswing.swing.mdi.client.MDIFrame;
import org.openswing.swing.message.receive.java.ErrorResponse;
import org.openswing.swing.message.receive.java.Response;
import org.openswing.swing.message.receive.java.VOListResponse;
import org.openswing.swing.message.receive.java.ValueObject;
import org.openswing.swing.message.send.java.GridParams;
import org.openswing.swing.server.QueryUtil;
import org.openswing.swing.table.client.GridController;
import org.openswing.swing.table.java.GridDataLocator;
/**
*
* @author wahhid
*/
public class BillingGridController extends GridController implements GridDataLocator{
private ProcessCallBack pcb;
private Connection conn;
private Auth auth;
private BackingController bc;
private BillingGridFrame frame;
private BillingVo vo;
public BillingGridController(Connection conn, Auth auth){
this.conn = conn;
this.auth = auth;
this.bc = new BackingController(this.conn);
this.frame = new BillingGridFrame(this);
MDIFrame.add(this.frame);
}
@Override
public Response loadData(int action, int startIndex, Map filteredColumns, ArrayList currentSortedColumns, ArrayList currentSortedVersusColumns, Class valueObjectType, Map otherGridParams) {
try{
ArrayList vals = new ArrayList();
String strSQL="SELECT " +
"billing.billing_id," +
"billing.billing_year," +
"billing.billing_month," +
"billing.billing_status" +
" FROM billing";
Map attribute2dbField = new HashMap();
attribute2dbField.put("billing_id","billing.billing_id");
attribute2dbField.put("billing_year","billing.billing_year");
attribute2dbField.put("billing_month","billing.billing_month");
attribute2dbField.put("billing_status","billing.billing_status");
return QueryUtil.getQuery(
conn,
strSQL,
new ArrayList(), // list of values linked to "?" parameters in sql
attribute2dbField,
BillingVo.class, // v.o. to dinamically create for each row...
"Y",
"N",
new GridParams(
action,
startIndex,
filteredColumns,
currentSortedColumns,
currentSortedVersusColumns,
new HashMap() // other params...
),
25, // pagination size...
true // log query...
);
}
catch (Exception ex) {
ex.printStackTrace();
return new ErrorResponse(ex.getMessage());
}
}
@Override
public Response insertRecords(int[] rowNumbers, ArrayList newValueObjects) throws Exception {
Map attribute2dbField = new HashMap();
attribute2dbField.put("billing_year","billing_year");
attribute2dbField.put("billing_month","billing_month");
attribute2dbField.put("billing_status","billing_status");
Response res = QueryUtil.insertTable(conn, newValueObjects, "billing", attribute2dbField, "Y", "N", true);
return res;
}
@Override
public Response updateRecords(int[] rowNumbers, ArrayList oldPersistentObjects, ArrayList persistentObjects) throws Exception {
Map attribute2dbField = new HashMap();
attribute2dbField.put("billing_id","billing_id");
attribute2dbField.put("billing_year","billing_year");
attribute2dbField.put("billing_month","billing_month");
attribute2dbField.put("billing_status","billing_status");
HashSet pk = new HashSet();
pk.add("billing_id");
Response res;
BillingVo oldVo;
BillingVo newVo;
for(int i=0;i<persistentObjects.size();i++){
oldVo = (BillingVo) oldPersistentObjects.get(i);
newVo = (BillingVo) persistentObjects.get(i);
res = QueryUtil.updateTable(conn, pk, oldVo, newVo, "billing", attribute2dbField, "Y", "N", true);
if(res.isError()){
return new ErrorResponse("Error Update : " + oldVo.getBilling_id());
}
}
return new VOListResponse(persistentObjects,false,persistentObjects.size());
}
@Override
public void selectedCell(int rowNumber, int columnIndex, String attributedName, ValueObject persistentObject) {
vo = (BillingVo) persistentObject;
this.frame.getGridController().setPk(vo.getBilling_id());
this.frame.getGridControl2().reloadData();
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public BackingController getBc() {
return bc;
}
public void setBc(BackingController bc) {
this.bc = bc;
}
public ProcessCallBack generateBilling() {
Calendar cal = Calendar.getInstance();
TarifStiker ts;
List<TransaksiStiker> os;
try {
//Delete All Billing
System.out.println("Delete All Detail Billing Parking");
this.bc.getBillingParkingController().deleteall(vo.getBilling_id());
System.out.println("Delete All Done!");
//Get Stiker with cara_bayar equal 1
System.out.println("Find Sticker with Billing Flag");
this.pcb = this.bc.getTransaksiStikerController().billingList();
if(this.pcb.isError()){
System.out.println(this.pcb.getErrmsg());
return this.pcb;
}
os = (List<TransaksiStiker>) this.pcb.getObject();
System.out.println("Number of Billing : " + os.size());
//Setup Billing Periode Date
System.out.println("Setup Billing Periode Date");
String year = Integer.toString(vo.getBilling_year());
String month = Integer.toString(vo.getBilling_month());
if(month.length() == 1){
month = "0" + month ;
}
String date = "01";
//Date billingPeriode = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-" + month + "-" + date);
Date billingPeriode = new SimpleDateFormat("yyyy-MM-dd").parse("2014-12-01");
System.out.println("Billing Periode : " + billingPeriode);
//Process Billing
int billingProcessed = 0;
for(TransaksiStiker o : os){
this.pcb = this.bc.getRequestTransaksiStikerController().FetchLastRequest(o.getNotrans());
if(!this.pcb.isError()){
RequestTransaksiStiker rts = (RequestTransaksiStiker) this.pcb.getObject();
if(rts.getCara_bayar() == 1 && rts.getApprovedstatus() == 1){
System.out.println(rts.getNo_id() + "," + rts.getAwal() + "," + rts.getAkhir());
}
}
}
for(TransaksiStiker o : os){
this.pcb = this.bc.getRequestTransaksiStikerController().FetchLastRequest(o.getNotrans());
if(!this.pcb.isError()){
RequestTransaksiStiker rts = (RequestTransaksiStiker) this.pcb.getObject();
if(rts.getCara_bayar() == 1
&& rts.getApprovedstatus() == 1
&& !(new SimpleDateFormat("MMyyyy").format(rts.getAwal()).equals("122014"))
&& !(new SimpleDateFormat("MMyyyy").format(rts.getAwal()).equals("012015"))){
System.out.println("Process : " + o.getNotrans());
cal.setTime(o.getAkhir());
System.out.println("Cal getAkhir : " + cal.getTime());
int akhirYear = cal.get(Calendar.YEAR);
System.out.println("Akhir Year : " + akhirYear);
int akhirMonth = cal.get(Calendar.MONTH) + 1;
System.out.println("Akhir Month : " + akhirMonth);
int akhirDay = o.getAkhir().getDate();
System.out.println("Akhir Day : " + akhirDay);
if (akhirYear > vo.getBilling_year()){
int diffYear = akhirYear - vo.getBilling_year();
akhirMonth = akhirMonth + (diffYear * 12);
System.out.println("Akhir Month : " + akhirMonth);
}
if((akhirMonth - vo.getBilling_month()) >= 2){
//Process Generate Billing if month difference above 2
System.out.println("Detected for Billing: " + o.getNotrans());
System.out.println("Generate Billing for " + o.getNotrans());
billingProcessed++;
BillingParking bp = new BillingParking();
String jenis_langganan = o.getNotrans().substring(4);
if(jenis_langganan.equals("1")){
jenis_langganan = "1st";
}
if(jenis_langganan.equals("2")){
jenis_langganan = "2nd";
}
if(jenis_langganan.equals("3")){
jenis_langganan = "3st";
}
if(jenis_langganan.equals("4")){
jenis_langganan = "4th";
}
if(jenis_langganan.equals("5")){
jenis_langganan = "5th";
}
cal.setTime(billingPeriode);
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
System.out.println("Int Current Month : " + currentMonth);
String strCurrentYear = Integer.toString(currentYear);
String strCurrentMonth = Integer.toString(currentMonth);
System.out.println("String Current Month : " + strCurrentMonth);
if(strCurrentMonth.length() == 1){
strCurrentMonth = "0" + strCurrentMonth;
System.out.println("String Current Month : " + strCurrentMonth);
}
String strFindLastDate = strCurrentYear + "-" + strCurrentMonth + "-01";
Date findLastDate = new SimpleDateFormat("yyyy-MM-dd").parse(strFindLastDate);
cal.setTime(findLastDate);
int maxDay = cal.getActualMaximum(Calendar.DATE);
System.out.println("Max Day : " + maxDay);
String strCurrentDay;
if(akhirDay > maxDay){
strCurrentDay = Integer.toString(maxDay);
}else{
strCurrentDay = Integer.toString(akhirDay);
}
if(strCurrentDay.length() == 1){
strCurrentDay = "0" + strCurrentDay;
}
String strReferenceDate = strCurrentYear + "-" + strCurrentMonth + "-" + strCurrentDay;
System.out.println("String Reference Date : " + strReferenceDate);
Date referenceDate = new SimpleDateFormat("yyyy-MM-dd").parse(strReferenceDate);
System.out.println("Reference Date : " + referenceDate);
cal.setTime(referenceDate);
cal.add(Calendar.MONTH, 1);
Date awal = cal.getTime();
System.out.println("Awal Date : " + awal);
cal.add(Calendar.MONTH, 1);
Date akhir = cal.getTime();
System.out.println("Akhir Date : " + akhir);
String description = "Contribution A (" + jenis_langganan + ") periode " + new SimpleDateFormat("dd/MM/yy").format(awal) + " - " + new SimpleDateFormat("dd/MM/yy").format(akhir) + ")";
this.pcb = this.bc.getTarifStikerController().getByJenisLangganan(jenis_langganan);
if(this.pcb.isError()){
return this.pcb;
}else{
ts = (TarifStiker) this.pcb.getObject();
bp.setUnitno(o.getUnit_kerja());
bp.setDate_trans(new Date(System.currentTimeMillis()));
bp.setDescription(description);
bp.setAmount(ts.getTarif());
bp.setBilling_id(vo.getBilling_id());
bp.setJenis_langganan(jenis_langganan);
bp.setAwal(awal);
bp.setAkhir(akhir);
this.bc.getBillingParkingController().insert(bp);
}
}
}
}
}
return new ProcessCallBack(true, this.getClass().getSimpleName() + " - " + "Generate Billing Successfully", null);
} catch (Exception ex) {
ex.printStackTrace();
return new ProcessCallBack(true, this.getClass().getSimpleName() + " - " + ex.getMessage(), null);
}
}
public void confirmBilling(){
this.bc.getBillingController().CloseBilling(vo.getBilling_id());
}
public BillingVo getVo() {
return vo;
}
public ProcessCallBack transferBilling() {
Connection conn;
PreparedStatement pstmt;
ResultSet rst;
String strSQL;
List<BillingParking> os;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:billing");
strSQL = "DELETE FROM billing_parking";
pstmt = conn.prepareStatement(strSQL);
pstmt.execute();
pstmt.close();
System.out.println("Delete all data on MDB file");
this.pcb = this.bc.getBillingParkingController().findByBillingId(this.vo.getBilling_id());
if(this.pcb.isError()){
return this.pcb;
}else{
os = (List<BillingParking>) this.pcb.getObject();
}
System.out.println("Number of Rows : " + os.size());
strSQL = "INSERT INTO billing_parking(unitno,date_trans,description,amount) VALUES (?,?,?,?)";
int i = 0;
for(BillingParking o : os){
i++;
pstmt = conn.prepareStatement(strSQL);
pstmt.setString(1, o.getUnitno());
pstmt.setDate(2, new java.sql.Date(o.getDate_trans().getTime()));
pstmt.setString(3, o.getDescription());
pstmt.setDouble(4, o.getAmount());
pstmt.execute();
pstmt.close();
System.out.println("Processed Row : " + i + " of " + os.size());
}
return new ProcessCallBack(false, this.getClass().getSimpleName() + " - " + "Transfer Billing Successfully", null);
} catch (SQLException ex) {
ex.printStackTrace();
return new ProcessCallBack(true, this.getClass().getSimpleName() + " - " + ex.getMessage(), null);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
return new ProcessCallBack(true, this.getClass().getSimpleName() + " - " + ex.getMessage(), null);
}
}
private void insertIntoMDB(){
}
public Auth getAuth() {
return auth;
}
public void setAuth(Auth auth) {
this.auth = auth;
}
public ProcessCallBack processBilling(){
try {
//Define Periode
System.out.println("Setup Billing Periode Date");
String year = Integer.toString(vo.getBilling_year());
String month = Integer.toString(vo.getBilling_month());
if(month.length() == 1){
month = "0" + month ;
}
String date = "01";
Date billingPeriode = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-" + month + "-" + date);
System.out.println("Billing Periode : " + billingPeriode);
//Fetch Billing List
this.pcb = this.fetchBillingList();
if(this.pcb.isError()){
return this.pcb;
}
List<TransaksiStiker> os = (List<TransaksiStiker>) this.pcb.getObject();
//Check Awal Date
//Check Akhir Date
//Add Billing to Billing Parking
return this.pcb;
} catch (ParseException ex) {
return new ProcessCallBack(true, ex.getMessage(), null);
}
}
private ProcessCallBack fetchBillingList(){
return this.bc.getTransaksiStikerController().billingList();
}
} |
package ru.khachalov.spring.iocHW;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml"
);
// Books books = context.getBean("bookBean", Books.class);
// BookReader br = new BookReader(books);
BookReader bookReader = context.getBean("bookReaderByHW", BookReader.class);
bookReader.readBook();
System.out.println(bookReader.getName());
System.out.println(bookReader.getVolume());
context.close();
}
}
|
package com.tencent.mm.plugin.honey_pay.ui;
import android.view.View;
import android.view.View.OnClickListener;
class HoneyPayGiveCardUI$2 implements OnClickListener {
final /* synthetic */ HoneyPayGiveCardUI kls;
HoneyPayGiveCardUI$2(HoneyPayGiveCardUI honeyPayGiveCardUI) {
this.kls = honeyPayGiveCardUI;
}
public final void onClick(View view) {
HoneyPayGiveCardUI.b(this.kls).d(this.kls);
}
}
|
package java2.businesslogic.announcementremoval;
import java2.businesslogic.ValidationError;
import java2.businesslogic.announcementcreation.AnnouncementCreationResponse;
import java2.businesslogic.announcementediting.AnnouncementEditingValidator;
import java2.database.AnnouncementRepository;
import java2.domain.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Component
public class AnnouncementRemovalServiceImpl implements AnnouncementRemovalService {
@Autowired AnnouncementRemovalValidator validator;
@Autowired AnnouncementRepository announcementRepository;
@Override
@Transactional
public AnnouncementRemovalResponse remove(AnnouncementRemovalRequest request) {
List<ValidationError> validationErrors = validator.validate(request);
if (!validationErrors.isEmpty()) {
return new AnnouncementRemovalResponse(validationErrors);
}
Optional<Announcement> announcement = announcementRepository.findById(request.getId());
if(announcement.isPresent()) {
announcementRepository.remove(announcement.get());
return new AnnouncementRemovalResponse(announcement.get().getId());
} else {
return new AnnouncementRemovalResponse(null);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.spi;
import java.net.URL;
import java.util.Set;
/**
* <p>This SPI is for abstracting the class scanning.</p>
*
* <p>In a production environment Many different modules need to perform
* class scanning (EJB, JSF, JPA, ...). This SPI allows us to only have one
* central class scanner for the whole application server
* which only performs the scanning once at startup of each WebApp.</p>
*
* <p>All URL path Strings in this interface contain the the protocol,
* e.g. 'file:/...' we get directly from {@link java.net.URL#toExternalForm()}</p>
*
*/
public interface ScannerService
{
/**
* Any initialisation action that is
* required by the implementation.
* @param object initialization object
*/
void init(Object object);
/**
* Perform the actual class scanning.
*/
void scan();
/**
* This method will get called once the information found by the current
* scan is not needed anymore and the ScannerService might free up
* resources.
*/
void release();
/**
* Get the URLs of all bean archives in the deployment.
* In OWB-1.x this did give the base paths to META-INF/beans.xml
* files. Now, this will either return the the beans.xml locations
* or the base URL for the JAR if it is an 'implicit bean archive'.
* @return the URL of the beans.xml files.
*/
Set<URL> getBeanXmls();
/**
* Gets beans classes that are found in the
* deployment archives.
* Attention: if the ScannerService is a BdaScannerService then
* these classes will only get added to the 'default' BDA
* @return bean classes
*/
Set<Class<?>> getBeanClasses();
/**
* Indicates if BDABeansXmlScanner is available. This method
* should only return true if a BDABeansXmlScanner is implemented
* and the OpenWebBeansConfiguration.USE_BDA_BEANSXML_SCANNER
* custom property is set to true.
* @return T - BDABeansXmlScanner is available and enabled;
* F - No BDABeansXmlScanner is available or it is disabled
* @deprecated not supported anymore. Just here to
*/
@Deprecated
boolean isBDABeansXmlScanningEnabled();
/**
* Gets BDABeansXMLScanner used to determine the beans.xml
* modifiers (interceptors, decorators, and, alternatives) that
* are enabled per BDA. This is different from the default behavior
* that enables modifiers per application and not just in one BDA
* contained in an application.
* @return null or reference to BDABeansXMLScanner
*/
BDABeansXmlScanner getBDABeansXmlScanner();
}
|
package ucll.da.reportdomain.db;
import ucll.da.reportdomain.domain.Report;
import java.util.List;
/**
* Created by verme on 3/05/2017.
*/
public interface ReportDB {
List<Report> getAllReports() throws DBException;
Report getReportById(Long id) throws DBException;
boolean addReport(Report report) throws DBException;
boolean deleteReport(Long id) throws DBException;
}
|
/*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* 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.palantir.conjure.verification;
import com.palantir.conjure.parser.types.ConjureTypeVisitor;
import com.palantir.conjure.parser.types.builtin.AnyType;
import com.palantir.conjure.parser.types.builtin.BinaryType;
import com.palantir.conjure.parser.types.builtin.DateTimeType;
import com.palantir.conjure.parser.types.collect.ListType;
import com.palantir.conjure.parser.types.collect.MapType;
import com.palantir.conjure.parser.types.collect.OptionalType;
import com.palantir.conjure.parser.types.collect.SetType;
import com.palantir.conjure.parser.types.primitive.PrimitiveType;
import com.palantir.conjure.parser.types.reference.ForeignReferenceType;
import com.palantir.conjure.parser.types.reference.LocalReferenceType;
/**
* Recursively prefixes all local references with the {@code examples.} namespace.
*/
public final class ResolveLocalReferencesConjureTypeVisitor implements ConjureTypeVisitor<String> {
@Override
public String visitAny(AnyType _type) {
return "any";
}
@Override
public String visitList(ListType type) {
return "list<" + type.itemType().visit(this) + ">";
}
@Override
public String visitMap(MapType type) {
return "map<" + type.keyType().visit(this) + ", " + type.valueType().visit(this) + ">";
}
@Override
public String visitOptional(OptionalType type) {
return "optional<" + type.itemType().visit(this) + ">";
}
@Override
public String visitPrimitive(PrimitiveType type) {
return type.type().name();
}
@Override
public String visitLocalReference(LocalReferenceType type) {
// This is the juicy bit.
return "examples." + type.type().name();
}
@Override
public String visitForeignReference(ForeignReferenceType type) {
throw new UnsupportedOperationException(
"Verification endpoints do not support foreign references: " + type.toString());
}
@Override
public String visitSet(SetType type) {
return "set<" + type.itemType().visit(this) + ">";
}
@Override
public String visitBinary(BinaryType _type) {
return "binary";
}
@Override
public String visitDateTime(DateTimeType _type) {
return "datetime";
}
}
|
package Main;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author Gerador de Códigos
*/
public class PessoaControle {
ArrayList<PessoaEntidade> lista = new ArrayList<>();
public void create(PessoaEntidade obj) {
lista.add(obj);
}
public PessoaEntidade read(int id) {
PessoaEntidade val = null;
for (int i = 0; i < lista.size(); i++) {
if (lista.get(i).getnome == id) {
val = lista.get(i);
}
}
return val;
}
public void delete(int id) {
for (int i = 0; i < lista.size(); i++) {
if (lista.get(i).getnome() == id) {
lista.remove(i);
}
}
}
public void update(int id, PessoaEntidade ent) {
for (int i = 0; i < lista.size(); i++) {
if (lista.get(i).getnome() == id) {
lista.get(i).setNome(ent.getNome());
lista.get(i).setNascimento(ent.getNascimento());
lista.get(i).setIdade(ent.getIdade());
lista.get(i).setCpf(ent.getCpf());
}
}
}
}
|
package com.drzewo97.ballotbox.core.model.pollresult;
import com.drzewo97.ballotbox.core.model.candidate.Candidate;
import com.drzewo97.ballotbox.core.model.poll.Poll;
import javax.persistence.*;
import java.util.Set;
@Entity
public class PollResult {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne
private Poll poll;
private Integer votesCasted;
private Boolean resolved;
@OneToMany
private Set<Candidate> winners;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Poll getPoll() {
return poll;
}
public void setPoll(Poll poll) {
this.poll = poll;
}
public Boolean getResolved() {
return resolved;
}
public void setResolved(Boolean resolved) {
this.resolved = resolved;
}
public Set<Candidate> getWinners() {
return winners;
}
public void setWinners(Set<Candidate> winners) {
this.winners = winners;
}
public Integer getVotesCasted() {
return votesCasted;
}
public void setVotesCasted(Integer votesCasted) {
this.votesCasted = votesCasted;
}
}
|
package homework4;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
UserDao userDao = new UserDao();
CountryDao countryDao = new CountryDao();
try {
System.out.println(userDao.getAll());
System.out.println(countryDao.getAll());
System.out.println(userDao.getById(2));
System.out.println("Generated id = "
+ userDao.insert("NewFirstName", "NewLastName", 20, 2));
System.out.println(userDao.getAll());
userDao.deleteById(1);
System.out.println(userDao.getAll());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package com.comp486.knightsrush;
import java.util.ArrayList;
import com.comp486.knightsrush.GameAct.Quest.Reward;
import com.comp486.knightsrush.Potion.Size;
import com.comp486.knightsrush.dummy.ItemBonus;
import com.comp486.knightsrush.dummy.Items.Item;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;
public class KnightSprite extends Sprite {
/*
* http://gamedev.stackexchange.com/questions/55151/rpg-logarithmic-leveling
* -formula log equation constants Used graphing calculator @
* http://www.desmos.com/calculator To refine constants to slow levelling as
* player level increases If the level gap rises too fast for your taste
* increase constA, decrease constB if you want the initial level gap to be
* higher, and finally set constC ~= exp((1-constB)/constA), in order to
* properly start at level 1. Formula: Level = constA * log( XP + constC ) +
* constB Formula: Experience = (Euler's constant) raised to the power of
* ((Level - constB)/constA) - constC)
*/
private static final double constA = 8.7;
private static final double constB = -70;
private static final double constC = 3501.28;
// Base Character Statistics
protected int BASE_DMG_MIN = 5;
protected int BASE_DMG_MAX = 10;
protected int BASE_DEX = 25;
protected int BASE_STR = 25;
protected int BASE_VIT = 10;
protected int BASE_HP = 50;
protected int BASE_ENERGY = 10;
protected int BASE_MANA = 50;
private int BASE_DEFENSE = 0;
private float BASE_ML = 0;
// Base mana recovery per second
protected int BASE_MANA_RECOVERY = 2;
protected float BASE_LL = 0;
protected int BASE_MOVEX = 800;
protected int BASE_MOVEY = -900;
// Ground level at 40 pixels
protected int GROUND = 40;
// Player actions
private boolean isAttacking;
private boolean isJumping;
private boolean isRunning;
private boolean isMoving;
private boolean isFalling;
private boolean isDead;
protected boolean isOnGround;
// settings
private boolean isInvincible = false;
private boolean isHardcore = false;
protected boolean hasLL;
protected boolean hasML;
public boolean isHit;
// default level 1
protected double level = 1;
// jump direction and angle
private int jumpY;
protected double jumpAngle;
// jump variables for jump math
protected float jumpHeight = 500;
protected float jumpSpeedLimit = 25;
protected float jumpSpeed = jumpSpeedLimit;
protected int skillPointsToUse = 0;
protected int statPointsToUse = 0;
protected double experience;
private int currentHealth;
private int currentMana;
protected int addedStr = 0;
protected int addedDex = 0;
protected int addedVit = 0;
protected int addedEnergy = 0;
protected int strength;
protected int dexterity;
protected int energy;
protected int vitality;
protected int velocityY;
protected int velocityX;
// This is bad to carry around the view
// TODO: find better way to access bitmaps currently used by view
public GameView mGv;
// Unused - hitbox adjustment based on attack
// protected Rect hitbox = new Rect(0, 0, 0, 0);
// protected Rect currentHitBox = new Rect(0, 0, 0, 0);
// list of acquired rewards
protected ArrayList<Reward> rewards = new ArrayList<Reward>();
// list of equipped items
protected ArrayList<Item> equipped = new ArrayList<Item>();
// frameTodraw used to determine place on spritesheet to draw
protected Rect frameToDraw = new Rect(0, 0, 0, 0);
// whereToDraw determines place on screen to draw frame
protected RectF whereToDraw = new RectF(0, 0, 0, 0);
// collision bounds
protected Rect bounds = new Rect(0, 0, 0, 0);
// current frame
protected int currentFrame;
// comparing last frame change against frame length in milliseconds
protected long lastFrameChangeTime;
protected long lastRegenTime;
protected long frameLengthInMilliseconds = 50;
// does the current animation loop or not - only death animation does not
// loop
protected boolean loop;
// Timing stuff to determine respawn and availability of jump command
private long lastDeathTime = 0;
protected long lastJumpTime = 0;
protected long lastSpellTime = 0;
// Sprite sheets
public Bitmap bitmapknight, bitmapknightLeft, knightDeath, knightDeathLeft;
public int addedZeal, addedFB, addedLS;
public ArrayList<Spell> spells = new ArrayList<Spell>(3);
private boolean isZealing;
public int lastSpellCasted;
public KnightSprite(int x, int y, int rows, int framecount, boolean vis, int exp, Bitmap spritesheet,
ContextParameters params, GameView gv, ArrayList<Reward> rewards, ArrayList<Item> equipped,
boolean _isInvincible, boolean _isHardcore) {
super(x, y, rows, framecount, vis, null, params);
mGv = gv;
skillPointsToUse = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_SKILLSTOUSE, 0);
statPointsToUse = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_STATSTOUSE, 0);
addedDex = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDDEX, 0);
addedStr = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDSTR, 0);
addedVit = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDVIT, 0);
addedEnergy = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDENERGY, 0);
addedZeal = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDZEAL, 0);
addedFB = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDFB, 0);
addedLS = mGv.prefs.getInt(PreferenceConstants.PREFERENCE_ADDEDLS, 0);
setResources();
isInvincible = _isInvincible;
isHardcore = _isHardcore;
experience = exp;
this.rewards = rewards;
if (rewards != null) {
assignRewards();
}
this.equipped = equipped;
if (equipped != null) {
assignItemBonus();
}
spritesheet = bitmapknight;
reset(spritesheet, rows);
}
public KnightSprite() {
}
public KnightSprite(int x, int y, int rows, int framecount, boolean vis, Bitmap spritesheet,
ContextParameters params) {
super(x, y, rows, framecount, vis, spritesheet, params);
}
/*
* when character levels up add stat points and update preferences
*/
public void levelUp() {
statPointsToUse += 5;
skillPointsToUse += 1;
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_STATSTOUSE, statPointsToUse);
mGv.editor.putInt(PreferenceConstants.PREFERENCE_SKILLSTOUSE, skillPointsToUse);
mGv.editor.commit();
mGv.editor = null;
}
public void updateStatPoints() {
statPointsToUse -= 1;
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_STATSTOUSE, statPointsToUse);
mGv.editor.commit();
mGv.editor = null;
}
public void addStrPoints() {
addedStr += 1;
strength += 1;
updateStatPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDSTR, addedStr);
mGv.editor.commit();
mGv.editor = null;
}
public void addVitPoints() {
addedVit += 1;
vitality += 1;
life = getBaseHealth();
updateStatPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDVIT, addedVit);
mGv.editor.commit();
mGv.editor = null;
}
public void addEnergyPoints() {
addedEnergy += 1;
energy += 1;
mana = getBaseMana();
updateStatPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDENERGY, addedEnergy);
mGv.editor.commit();
mGv.editor = null;
}
public void addDexPoints() {
addedDex += 1;
dexterity += 1;
updateStatPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDDEX, addedDex);
mGv.editor.commit();
mGv.editor = null;
}
public void updateSkillPoints() {
skillPointsToUse -= 1;
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_SKILLSTOUSE, skillPointsToUse);
mGv.editor.commit();
mGv.editor = null;
}
public void setResources() {
final Resources res = mGv.getResources();
Runtime.getRuntime().gc();
bitmapknight = BitmapFactory.decodeResource(res, R.drawable.sprites_small);
bitmapknightLeft = BitmapFactory.decodeResource(res, R.drawable.sprites_small_left);
knightDeath = BitmapFactory.decodeResource(res, R.drawable.knight_dead);
knightDeathLeft = BitmapFactory.decodeResource(res, R.drawable.knight_dead_left);
}
public void addZealPoints() {
addedZeal += 1;
updateSkillPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDZEAL, addedZeal);
mGv.editor.commit();
mGv.editor = null;
}
public void addFirePoints() {
addedFB += 1;
updateSkillPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDFB, addedFB);
mGv.editor.commit();
mGv.editor = null;
}
public void addLightPoints() {
addedLS += 1;
updateSkillPoints();
if (mGv.editor == null) {
mGv.editor = mGv.prefs.edit();
}
mGv.editor.putInt(PreferenceConstants.PREFERENCE_ADDEDLS, addedLS);
mGv.editor.commit();
mGv.editor = null;
}
public int getBaseHealth() {
return BASE_HP + vitality;
}
public int getBaseMana() {
return BASE_MANA + energy;
}
/**
* @description Get invincibility setting
*/
public boolean isInvincible() {
return isInvincible;
}
/**
* @description Get hardcore setting
*/
public boolean isHardcore() {
return isHardcore;
}
/**
* reset all actions
*/
public void resetActionStatus() {
isAttacking = false;
// isJumping = false;
isMoving = false;
isRunning = false;
isOnGround = false;
isFalling = false;
}
public void setDead(Bitmap spritesheet, int rows) {
resetActionStatus();
isDead = true;
// lose ten percent of experience when you die but don't go below
// experience required for current level
// TODO: more sophisticated experience loss based on current difficulty
// and player level
if (experience - (experience * 0.1) > getExpByLevel((int) getCurrentLevel())) {
experience -= experience * 0.1;
} else {
experience = getExpByLevel((int) getCurrentLevel());
}
currentHealth = 0;
if (loop) {
loop = false;
}
currentFrame = 0;
framecount = 10;
lastFrameChangeTime = 0;
lastRegenTime = 0;
setSheet(spritesheet, rows);
}
public final float getCenteredPositionX() {
return mPosition.x + (width / 2.0f);
}
public final float getCenteredPositionY() {
return mPosition.y + (height / 2.0f);
}
public void setJumpSpeed(float mJumpSpeed) {
jumpSpeed = mJumpSpeed;
}
/**
* This method will be called when items are replaced/changed on the
* character cia the inventory screen
*/
public void resetBaseStats() {
BASE_DMG_MIN = 5;
BASE_DMG_MAX = 10;
BASE_DEX = 25;
BASE_STR = 25;
BASE_VIT = 10;
BASE_HP = 50;
BASE_ENERGY = 10;
BASE_MANA = 50;
BASE_DEFENSE = 0;
BASE_ML = 0;
// Base mana recovery per second
BASE_MANA_RECOVERY = 2;
BASE_LL = 0;
if (rewards != null) {
assignRewards();
}
if (equipped != null) {
assignItemBonus();
}
strength = BASE_STR + addedStr;
dexterity = BASE_DEX + addedDex;
vitality = BASE_VIT + addedVit;
energy = BASE_ENERGY + addedEnergy;
life = getBaseHealth();
mana = getBaseMana();
currentMana = mana;
currentHealth = life;
}
public void reset(Bitmap sheet, int r) {
resetActionStatus();
isDead = false;
mPosition.set(x, y);
jumpAngle = 1;
level = experience <= 0 ? 1 : getCurrentLevel();
if (this instanceof KnightSprite) {
strength = BASE_STR + addedStr + (int) (level / 2);
dexterity = BASE_DEX + addedDex + ((int) level / 2);
vitality = BASE_VIT + addedVit + (int) level;
energy = BASE_ENERGY + addedEnergy + (int) level;
team = Team.PLAYER;
} else {
team = Team.ENEMY;
}
life = getBaseHealth();
mana = getBaseMana();
currentMana = mana;
currentHealth = life;
velocityX = BASE_MOVEX;
velocityY = BASE_MOVEY;
jumpY = 0;
loop = true;
spritesheet = sheet;
rows = r;
currentFrame = 0;
lastFrameChangeTime = 0;
lastRegenTime = 0;
mCurrentAction = ActionType.IDLE;
setFrameWidth(spritesheet.getWidth());
setFrameHeight(spritesheet.getHeight());
}
public boolean canWeWear(int requiredStr, int requiredDex) {
if (strength >= requiredStr && dexterity >= requiredDex) {
return true;
} else {
return false;
}
}
public void update(long timedelta) {
int platSpeed = getXVelocity() / 100;
int groundSpeed = getXVelocity() / 60;
if (isHardcore() && lastDeathTime > 0) {
// wait two seconds after death
if (System.currentTimeMillis() - lastDeathTime > 2000) {
// restart game by finishing current task and starting new main
// menu activity, while clearing the old main menu, passing the
// newGame intent extra to wupe away preferences before setting
// up the splash screen
mGv.main.finish();
Intent i = new Intent(mGv.main, MainMenuActivity.class);
i.putExtra("newGame", true);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
mGv.main.startActivity(i);
}
} else if (!isDead()) {
if (jumpSpeed > 0) {
// Only need to check floor collisions when falling
checkFloorCollisions(mGv.plat);
}
// set bitmap according to facingDirection
if (facingDirection.x == -1) {
setSheet(bitmapknightLeft, 6);
} else {
setSheet(bitmapknight, 6);
}
handleMovementX(timedelta, groundSpeed, platSpeed);
handleJump(platSpeed, groundSpeed);
// handle knight damage on the enemy
// player does damage on the seventh frame of attack animation
} else {
// we died! set death animation and lastDeathTime
final long time = System.currentTimeMillis();
mGv.currentExperience = (int) experience;
if (getLastDeathTime() == 0) {
if (facingDirection.x == 1) {
setDead(knightDeath, 1);
} else {
setDead(knightDeathLeft, 1);
}
setLastDeathTime(time);
}
// respawn after 5 seconds
if (time - lastDeathTime >= 5000 && lastDeathTime != 0) {
// respawn enemies and potions
mGv.enemies.clear();
mGv.potions.clear();
reset(bitmapknight, 6);
setLastDeathTime(0);
setDead(false);
// if quest is active reset kill count and update distance
// walked
if (mGv.currentQuest != null && mGv.currentQuest.inProcess) {
mGv.currentKillCount = 0;
for (Item item : mGv.droppedItems) {
item.update(
mGv.distanceWalked - (mGv.currentQuest.distanceWalked - mGv.currentQuest.disactRange));
}
mGv.distanceWalked = mGv.currentQuest.distanceWalked - mGv.currentQuest.disactRange;
}
if (mGv.boss == null) {
// spawn number of enemies based on difficulty
switch (mGv.mParams.difficulty) {
case 0:
mGv.createEnemies(10);
break;
case DifficultyConstants.NORMAL:
mGv.createEnemies(10);
break;
case DifficultyConstants.NIGHTMARE:
mGv.createEnemies(15);
break;
case DifficultyConstants.HELL:
mGv.createEnemies(25);
break;
}
}
} else {
if (jumpSpeed > 0) {
checkFloorCollisionsDeath();
}
handleMovementX(timedelta, groundSpeed, platSpeed);
handleJump(platSpeed, groundSpeed);
}
}
setBounds();
frameToDraw = getCurrentFrame();
}
public void handleMovementX(long timedelta, int groundSpeed, int platSpeed) {
// If knight is moving (the player is touching the screen)
// then move him to the right based on his target speed and the
if (isMoving() || isJumping()) {
if (facingDirection.x == 1) {
platSpeed = -platSpeed;
groundSpeed = -groundSpeed;
}
if (!isAttacking()) {
mGv.back.update((int) Math.floor((platSpeed - 2) * jumpAngle));
mGv.plat.update((int) Math.floor(platSpeed * jumpAngle));
mGv.bg.update((int) Math.floor(groundSpeed * jumpAngle));
movePotions((int) Math.floor(groundSpeed * jumpAngle), (int) Math.floor(platSpeed * jumpAngle));
moveDroppedItems((int) Math.floor(groundSpeed * jumpAngle), (int) Math.floor(platSpeed * jumpAngle));
moveEnemies((int) Math.floor(groundSpeed * jumpAngle), (int) Math.floor(platSpeed * jumpAngle));
// moveSpells((int) Math.floor(groundSpeed * jumpAngle), (int)
// Math.floor(platSpeed * jumpAngle));
// Update Distance Walked in Either Direction
// will be used to spawn monsters randomly
// and to determine various checkpoints
mGv.distanceWalked += -groundSpeed * jumpAngle;
}
}
}
/**
* Move lastSpellCasted based on character movement and position of the
* spell and only runs if the current spell is visible
*
* @param gs
* @param ps
*/
private void moveSpells(int gs, int ps) {
if (lastSpellCasted > 0) {
final Spell spell = spells.get(lastSpellCasted);
if (spell.isVisible()) {
if (spell.mPosition.y >= mParams.viewHeight - mGv.groundTile2.getHeight() - 40) {
spell.mPosition.set(mPosition.x + gs, mPosition.y);
} else {
spell.mPosition.set(mPosition.x + ps, mPosition.y);
}
}
}
}
/**
* @description This method determines whether a quest is in process and
* which type of quest is currently active. We currently only
* have one quest type, killing monsters. Additional quest
* types cand be added to the switch statement.
*/
public void handleKillQuest() {
// update kill count for quest of monster killing type
if (mGv.currentQuest != null && mGv.currentQuest.inProcess) {
switch (mGv.currentQuest.type) {
case QuestConstants.QC_TYPE_MONSTER_KILL:
if (mGv.currentQuest.threshold > mGv.currentKillCount) {
// update the current kill count which is reset when quest
// was started
mGv.currentKillCount += 1;
} else {
// run game flow event BEAT QUEST
mGv.onGameFlowEvent(GameFlowEvent.EVENT_BEAT_QUEST, 0);
}
break;
}
}
}
/**
* @description Method to handle experience gain. if the player's level is
* greater after the kill, a game flow event is triggered.
* @formula experience += (100*(enemy level/4))
* @param enemy
*/
public void handleExperience(EnemySprite enemy) {
final double level = getCurrentLevel();
// experience gained Formula
// New Experience = Old Experience + (100 * (1/4 of
// monster level
setExperience(getExperience() + (100 * (enemy.getCurrentLevel() * 0.25)));
// knight.setLevel(level);
int levelAfter = (int) getCurrentLevel();
if (levelAfter > (int) level) {
/**
*
* TODO Add UI update when character levels final project will also
* handle adding skills and stat points for the player
*/
mGv.onGameFlowEvent(GameFlowEvent.EVENT_LEVELLED, levelAfter);
}
// update current experience for UI
mGv.currentExperience = (int) getExperience();
}
/**
* @description Method that determines damage output and returns an integer.
* get and setter.
* @return (int) Random.nextInt(between min and max damage) + strength/2
*/
public int getDamage() {
final float damage = (mGv.cloudRandom.nextInt(BASE_DMG_MAX) + BASE_DMG_MIN) + (int) ((double) strength * 0.5F);
if (isZealing) {
return (int) Math.floor(damage * (0.5F + ((float) addedZeal / 100F)));
} else {
return (int) Math.floor(damage);
}
}
/**
* @description Method that you call to move potions when character moves.
* @param gs
* @param ps
*/
public void movePotions(int gs, int ps) {
for (Potion potion : mGv.potions) {
if (potion.isVisible()) {
if (potion.getPosition().y >= mParams.viewHeight - 40) {
potion.update(gs, this);
} else {
potion.update(ps, this);
}
} else {
potion.mPosition.set(-1000, -1000);
}
}
}
/**
* @description Method that you call to move droped items when character
* moves.
* @param gs
* @param ps
*/
public void moveDroppedItems(int gs, int ps) {
for (Item item : mGv.droppedItems) {
if (item.getPosition().y >= mParams.viewHeight - mGv.groundTile2.getHeight() - 40) {
item.update(gs, this);
} else {
item.update(ps, this);
}
}
}
/**
* @description player jump handler.
* @param platSpeed
* @param groundSpeed
*/
private void handleJump(int platSpeed, int groundSpeed) {
if (isJumping()) {
if (facingDirection.x == 1) {
platSpeed = -platSpeed;
groundSpeed = -groundSpeed;
}
// Log.d("JumpSpeed", String.valueOf(jumpSpeed));
if (jumpSpeed < 0) {
jumpSpeed *= 1F - jumpSpeedLimit / jumpHeight;
if (jumpSpeed > -jumpSpeedLimit / 5F) {
jumpSpeed *= -1F;
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit) {
jumpSpeed *= 1F + jumpSpeedLimit / 50F;
}
// handleJumpAngle(groundSpeed, platSpeed);
mPosition.y += jumpSpeed;
setOnGround(false);
// setFalling(true);
// }
}
}
/**
* @description move enemies when player is moving
* @param gs
* groundspeed
* @param ps
* platformspeed
*/
public void moveEnemies(int gs, int ps) {
for (EnemySprite enemy : mGv.enemies) {
// move enemies
if (enemy.getPosition().y >= mParams.viewHeight - enemy.height - mGv.groundTile2.getHeight() - 40) {
enemy.getPosition().set(enemy.getPosition().x + gs, enemy.getPosition().y);
} else {
enemy.getPosition().set(enemy.getPosition().x + ps, enemy.getPosition().y);
}
}
if (mGv.boss != null) {
if (mGv.boss.getPosition().y + mGv.boss.getFrameHeight() >= mParams.viewHeight - mGv.groundTile2.getHeight()
- 40) {
mGv.boss.getPosition().set(mGv.boss.getPosition().x + gs, mGv.boss.getPosition().y);
} else {
mGv.boss.getPosition().set(mGv.boss.getPosition().x + ps, mGv.boss.getPosition().y);
}
}
}
/**
* @description Attack Speed method, we reduce time to complete frame by
* dexterity/5 5 dexterity points increased attack speed by 1
* millisecond/frame
*
* @return player attack speed
*/
public long getAttackSpeed() {
// Log.d("attackspeed", String.valueOf((float)
// (frameLengthInMilliseconds - (dexterity / 5) *
// 1F)/frameLengthInMilliseconds));
if (isZealing) {
return (long) (frameLengthInMilliseconds / 2F);
} else {
return (long) (frameLengthInMilliseconds - (((float) dexterity / 20F) * 1F));
}
}
public void setJumpY(int i) {
jumpY = i;
}
public int getJumpY() {
return jumpY;
}
public int getYVelocity() {
return velocityY;
}
public int getCurrentMana() {
return currentMana;
}
public void setStartingMana(int mana) {
currentMana = mana;
}
/**
* @description reduce or add to the player's current mana will determine if
* the addition is more than the max mana of player
* @param mana
*/
public void setCurrentMana(int mana) {
if (mana > 0) {
currentMana = currentMana + mana >= this.mana ? this.mana : currentMana + mana;
} else {
currentMana = currentMana + mana < 0 ? 0 : currentMana + mana;
}
}
public int getCurrentHealth() {
return currentHealth;
}
public void setStartingHealth(int health) {
currentHealth = health;
}
/**
* @description reduce or add to the player's current health will determine
* if the addition is more than the max health of player
* @param health
*/
public void setCurrentHealth(int health) {
currentHealth = currentHealth + health >= life ? life : currentHealth + health;
}
/**
*
* @return life/max health
*/
public int getLife() {
return life;
}
/**
* @description set max health to the input
* @param health
*/
public void setLife(int health) {
life = health;
}
/**
* @description draw the knight UI with our paint objects and draw the
* knight. All the logic is taken care of in the update()
* method to determine where to place the player.
* @param timedelta
* @param canvas
* @param paint
* @param paintOpac
*/
public void draw(long timedelta, Canvas canvas, Paint paint, Paint paintOpac) {
// TODO: Calculate image into inches based on DPI and convert to pixels
// for consistent UI display across devices
// FORMULA Inches = pixels / DPI --> Pixels = Inches * DPI
// Make the text a bit bigger
if (mGv.playing && spritesheet != null && !spritesheet.isRecycled()) {
paint.setTextSize(40);
// use stroke of particular color for health and experience bar
paint.setStrokeWidth(50);
final float liferatio = (float) currentHealth / (float) life;
final float manaratio = (float) currentMana / (float) mana;
final double expToNextLvl = getExpByLevel((int) (getCurrentLevel() + 1));
final double expToLvl = getExpByLevel((int) (getCurrentLevel()));
// Ugly magic numbers. this could be cleaned up
canvas.drawLine(265, 50, 265 + ((liferatio) * 460), 50, paint);
// blue
paint.setColor(Color.rgb(0, 0, 153));
canvas.drawLine(265, 105, 265 + ((manaratio) * 460), 105, paint);
// brown/yellow
paint.setColor(Color.rgb(199, 195, 142));
canvas.drawLine(265, 155F,
(float) (725 - (((expToNextLvl - experience) / (expToNextLvl - expToLvl)) * (460))), 155F, paint);
paint.setColor(Color.WHITE);
paint.setFakeBoldText(true);
canvas.drawBitmap(mGv.healthBar, 0, 0, paint);
canvas.drawText((int) getCurrentLevel() + "", 118, mGv.healthBar.getHeight() - 40, paint);
paint.setColor(Color.BLACK);
canvas.drawText("Distance Walked:" + mGv.distanceWalked, 20, 340, paint);
canvas.drawText((int) getExperience() + " / " + (int) expToNextLvl, 300, 160, paint);
paint.setColor(Color.rgb(128, 0, 0));
if (skillPointsToUse > 0 || statPointsToUse > 0) {
canvas.drawBitmap(mGv.tome, 0, 335, paint);
}
if (skillPointsToUse > 0) {
canvas.drawText("You have " + skillPointsToUse + " Skill Points Available", mGv.tome.getWidth(), 410,
paint);
}
if (statPointsToUse > 0) {
canvas.drawText("You have " + statPointsToUse + " Stat Points Available", mGv.tome.getWidth(), 460,
paint);
}
}
whereToDraw.set(getPosition().x, getPosition().y - height, getPosition().x + width, getPosition().y);
paint.setStrokeWidth(1);
/*
* // hit box test lines
*
* canvas.drawLine(bounds.left, bounds.top, bounds.right, bounds.top,
* paint); canvas.drawLine(bounds.left, bounds.bottom, bounds.right,
* bounds.top, paint);
*/
// Draw knight
if (spritesheet != null && !spritesheet.isRecycled()) {
if (!isHit) {
canvas.drawBitmap(spritesheet, frameToDraw, whereToDraw, paint);
} else {
canvas.drawBitmap(spritesheet, frameToDraw, whereToDraw, paintOpac);
setHit(false);
}
}
}
public void setSheet(Bitmap sheet, int rows) {
spritesheet = sheet;
this.rows = rows;
setFrameWidth(sheet.getWidth());
setFrameHeight(sheet.getHeight());
}
protected void setFrameHeight(int i) {
height = i / rows;
}
public void setFrameWidth(int i) {
width = i / framecount;
}
@Override
public int getFrameHeight() {
return height;
}
@Override
public int getFrameWidth() {
return width;
}
/**
* @description Rearranged levelling formula to get experience for the
* current player level
* @formula e (Euler's constant) raised to the power of ((Level -
* constB)/constA) - constC)
*/
public static double getExpByLevel(int lvl) {
return (Math.exp((lvl - constB) / constA) - constC);
}
/**
*
* @description Use levelling formula to get current player level based on
* experience Math.max is used to default to level 1 if below
* level 1 experience
* @formula Math.floor(constA * log(experience + constC) + constB)
*/
public double getCurrentLevel() {
return Math.max(Math.floor(constA * Math.log((double) experience + constC) + constB), 1);
}
/*
* public double solveQuadratic(int experience) {
*
* final double root1, root2; root1 = (-360 + Math.sqrt(Math.pow(360, 2) - 4
* * 40 * -experience)) / (2 * 360); root2 = (-360 - Math.sqrt(Math.pow(360,
* 2) - 4 * 40 * -experience)) / (2 * 360); return Math.max(root1, root2); }
*/
public double getExperience() {
return experience;
}
public void setExperience(double exp) {
experience = exp;
}
/**
* Gets current frame by integer
*
* @return (int) currentFrame
*/
public int getFrameInt() {
return currentFrame;
}
/**
* @description Gets the Rectangle location of the frame we want to draw.
* This method can be overriden to accompany different
* spreadsheets
* @return (Rect) frameToDraw
*/
public Rect getCurrentFrame() {
final ActionType currAnimation;
long time = System.currentTimeMillis();
// frame rate is calculated based on attack speed
if (time > lastFrameChangeTime + getAttackSpeed()) {
// update current frame and lastFrameCahngeTime
lastFrameChangeTime = time;
currentFrame++;
// if looping restart animation
if (currentFrame >= framecount && loop) {
currentFrame = 0;
}
// if looping is false stop at last frame
if (currentFrame >= framecount & !loop) {
currentFrame = framecount - 1;
}
}
// recover mana every second
if (time >= lastRegenTime + 1000) {
lastRegenTime = time;
setCurrentMana(BASE_MANA_RECOVERY);
if (isZealing) {
setCurrentMana(-spells.get(0).manaCost);
}
}
// Determine animation based on character's current state
// Run/Walk
if (isMoving() && !isJumping()) {
if (isRunning()) {
// set run speed
setXVelocity(900);
currAnimation = ActionType.RUN;
} else {
currAnimation = ActionType.MOVE;
}
} // Jump&&Attack
else if (isJumping() && isAttacking()) {
currAnimation = ActionType.JATTACK;
} // Hack for enemies to show Jump animation because they move both x
// and y when jumping
else if (isMoving() && isJumping()) {
currAnimation = ActionType.JUMP;
} // Attack
else if (isAttacking()) {
currAnimation = ActionType.ATTACK;
} // Jump
else if (isJumping() && !isDead()) {
currAnimation = ActionType.JUMP;
} // if not any of the other options must be idle or death
else {
if (isDead()) {
currAnimation = ActionType.DEATH;
} else {
currAnimation = ActionType.IDLE;
}
}
// set current top bottom of frame
setAnimation(currAnimation);
return frameToDraw;
}
/**
* @description set the animation by finding the location on spritesheet
* @param animation
*/
public void setAnimation(ActionType animation) {
int top;
int bottom;
setCurrentAction(animation);
switch (mCurrentAction) {
case ATTACK:
top = 0;
bottom = height;
break;
case JUMP:
top = height * 4;
bottom = height * 5;
break;
case MOVE:
top = height;
bottom = height * 2;
break;
case RUN:
top = height * 2;
bottom = height * 3;
break;
case JATTACK:
top = height * 3;
bottom = height * 4;
break;
case IDLE:
top = height * 5;
bottom = height * 6;
break;
case DEATH:
top = 0;
bottom = height;
break;
default:
top = 0;
bottom = height;
break;
}
frameToDraw.top = top;
frameToDraw.bottom = bottom;
setAnimationLeftRight();
}
/**
* @description update the left and right values of the source of the next
* frame on the spritesheet
* @return the frame to draw
*/
public Rect setAnimationLeftRight() {
if (facingDirection.x == 1) {
frameToDraw.left = currentFrame * width;
frameToDraw.right = frameToDraw.left + width;
} else {
if (currentFrame >= 0) {
frameToDraw.left = spritesheet.getWidth() - width * (currentFrame + 1);
}
frameToDraw.right = frameToDraw.left + width;
}
return frameToDraw;
}
/**
* @description Getter
* @return (Rect) bounds
*/
public Rect getBounds() {
return bounds;
}
/**
* @description Set and get current rectangular bounds based on the player's
* position
* @return (Rect) bounds
*/
public Rect setBounds() {
bounds.set((int) getPosition().x, (int) getPosition().y - height, (int) getPosition().x + width,
(int) getPosition().y);
return bounds;
}
public void setHit(boolean bool) {
isHit = bool;
}
public boolean isHit() {
return isHit;
}
public void setDead(boolean bool) {
isDead = bool;
}
public boolean isDead() {
return isDead;
}
public void setOnGround(boolean bool) {
isOnGround = bool;
}
public boolean isOnGround() {
return isOnGround;
}
/**
* @description Checking player collisions with potions.
* @param Rect
* a
* @param Rect
* b
* @param potion
*/
public void checkCollisions(Rect a, Rect b, Potion potion) {
// should only run once because we set the potions visibility to false
if (Rect.intersects(a, b) && potion.isVisible()) {
// adjust added health based on size enum
// use ternary statement to determine whether the addition is more
// than max health
// and add health accordingly
if (potion.size == Size.SMALL) {
currentHealth = currentHealth >= life - 50 ? life : currentHealth + 50;
} else if (potion.size == Size.LARGE) {
currentHealth = currentHealth >= life - 150 ? life : currentHealth + 150;
}
// make potion invisible and reuse on another enemy
potion.setVisible(false);
potion.setAssigned(false);
for (EnemySprite enemy : mGv.enemies) {
if (!enemy.hasPotion() && !enemy.isDead()) {
// assign potion to enemy 30 percent of the time
if (mGv.cloudRandom.nextInt(100) + 1 <= 30) {
enemy.potion = potion;
enemy.setPotion(true);
potion.setAssigned(true);
break;
}
} else {
continue;
}
}
}
}
/**
* @description Checking player collisions with dropped items.
* @param Recta
* @param Rectb
* @param item
*/
public void checkCollisions(Rect a, Rect b, final Item item) {
// should only run once because we set the potions visibility to false
if (Rect.intersects(a, b) && item.isVisible() && !item.hasBeenLookedAt
&& mGv.pref.getBoolean("pref_item_on_collide", true)) {
mGv.main.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mGv.currentItem == null) {
item.hasBeenLookedAt = true;
mGv.currentItem = ItemDetailFragment.itemPickUpView(mGv.main, item,
mGv.main.getLayoutInflater());
mGv.thisItem = item;
}
}
});
// add to inventory
}
}
/**
* @description check player collisions with the floor
* @param bg
*/
public void checkFloorCollisions(Background bg) {
Rect playerRect = getBounds();
Rect pRect;
if (jumpY == 0) {
pRect = bg.getBounds();
} else {
pRect = mGv.bg.getBounds();
}
if (Rect.intersects(playerRect, pRect)) {
hitFloor(pRect, playerRect);
}
}
/**
* @description check player collisions with the floor
* @param bg
*/
public void checkFloorCollisionsDeath() {
final Rect playerRect = getBounds();
final Rect pRect;
pRect = mGv.bg.getBounds();
if (Rect.intersects(playerRect, pRect)) {
hitFloorDeath(pRect, playerRect);
}
}
private void hitFloorDeath(Rect pRect, Rect playerRect) {
if (playerRect.bottom >= pRect.top) {
if (jumpSpeed > 0) {
getPosition().set(getPosition().x, pRect.top + 15);
setJumping(false);
setLastJumpTime(0);
setFalling(false);
setOnGround(true);
jumpAngle = 1;
}
}
}
private void hitFloor(Rect pRect, Rect playerRect) {
if (isJumping) {
if (playerRect.bottom >= pRect.top) {
if (jumpSpeed > 0) {
getPosition().set(getPosition().x, pRect.top + 15);
setJumping(false);
setLastJumpTime(0);
setFalling(false);
setOnGround(true);
jumpAngle = 1;
}
}
}
}
public void setLevel(double lvl) {
level = lvl;
}
public void setLastDeathTime(long gameTime) {
lastDeathTime = gameTime;
}
public long getLastDeathTime() {
return lastDeathTime;
}
public void setFalling(boolean bool) {
isFalling = bool;
}
public boolean isFalling() {
return isFalling;
}
public void setAttacking(boolean bool) {
isAttacking = bool;
}
public boolean isAttacking() {
return isAttacking;
}
public void setYVelocity(int velocity) {
velocityY = velocity;
}
public void setJumping(boolean bool) {
isJumping = bool;
}
public boolean isJumping() {
return isJumping;
}
public void setXVelocity(int velocity) {
velocityX = velocity;
}
public int getXVelocity() {
return velocityX;
}
public void setRunning(boolean bool) {
isRunning = bool;
}
public boolean isRunning() {
return isRunning;
}
public void setMoving(boolean bool) {
isMoving = bool;
}
public boolean isMoving() {
return isMoving;
}
public long getLastJumpTime() {
return lastJumpTime;
}
public void setLastJumpTime(long time) {
lastJumpTime = time;
}
/**
* Apply a reward on the fly
*
* @param reward
*/
public void applyReward(Reward reward) {
switch (reward.mType) {
case RewardConstants.R_TYPE_HEALTH:
// because this can be added on the fly have to add to base and
// reset health
int diff = life - currentHealth;
BASE_HP += reward.mBonus;
life = getBaseHealth();
currentHealth = life - diff;
break;
case RewardConstants.R_TYPE_STRENGTH:
BASE_STR += reward.mBonus; // add to base strength
break;
case RewardConstants.R_TYPE_DEXTERITY:
BASE_DEX += reward.mBonus; // add to base dexterity
break;
case RewardConstants.R_TYPE_LIFE_LEECH:
setLL(reward.mBonus);
break;
}
addReward(reward);
}
/**
* Assign item bonuses on initialization
*/
public void assignItemBonus() {
for (Item i : equipped) {
for (ItemBonus ib : i.itemBonuses) {
switch (ib.mType) {
case ItemBonus.DEXTERITY:
BASE_DEX += ib.mChosen;
break;
case ItemBonus.STRENGTH:
BASE_STR += ib.mChosen;
break;
case ItemBonus.ENERGY:
BASE_ENERGY += ib.mChosen;
break;
case ItemBonus.LIFELEECH_PERCENT:
if (!hasLL) {
hasLL = true;
}
setLL(ib.mChosen);
break;
case ItemBonus.PHYSICAL_DAMAGE_MAX:
BASE_DMG_MAX += ib.mChosen;
break;
case ItemBonus.PHYSICAL_DAMAGE_MIN:
BASE_DMG_MIN += ib.mChosen;
break;
case ItemBonus.PHYSICAL_DAMAGE_MAXMIN:
BASE_DMG_MIN += ib.mChosen;
BASE_DMG_MAX += ib.mChosen;
break;
case ItemBonus.VITALITY:
BASE_VIT += ib.mChosen;
break;
default:
break;
}
}
}
}
/**
* Assign Rewards on initialization
*/
public void assignRewards() {
for (Reward reward : rewards) {
switch (reward.mType) {
case RewardConstants.R_TYPE_HEALTH:
if (reward.mIsInt == RewardConstants.R_BASE) {
BASE_HP += reward.mBonus;
}
break;
case RewardConstants.R_TYPE_STRENGTH:
BASE_STR += reward.mBonus;
break;
case RewardConstants.R_TYPE_VITALITY:
BASE_VIT += reward.mBonus;
break;
case RewardConstants.R_TYPE_DEXTERITY:
BASE_DEX += reward.mBonus;
break;
case RewardConstants.R_TYPE_LIFE_LEECH:
if (!hasLL) {
hasLL = true;
}
setLL(reward.mBonus);
break;
default:
break;
}
}
}
public void setML(float mlToAdd) {
BASE_ML += mlToAdd / 100F;
}
public float getML() {
return BASE_ML;
}
public void setHasML(boolean hasML) {
this.hasML = hasML;
}
public boolean getHasML() {
return hasML;
}
public void setLL(float llToAdd) {
BASE_LL += llToAdd / 100F;
}
public float getLL() {
return BASE_LL;
}
public void setHasLL(boolean hasLL) {
this.hasLL = hasLL;
}
public boolean getHasLL() {
return hasLL;
}
public ArrayList<Reward> getRewards() {
return rewards;
}
public void addReward(Reward reward) {
rewards.add(reward);
}
public void addRewardArray(ArrayList<Reward> rewards) {
this.rewards = rewards;
}
public void destroy() {
// housekeeping
bitmapknight.recycle();
bitmapknightLeft.recycle();
knightDeath.recycle();
knightDeathLeft.recycle();
for (Spell spell : spells) {
spell.destroy();
}
}
public boolean getZeal() {
return isZealing;
}
public void setZeal(boolean b) {
isZealing = b;
}
}
|
package org.science4you.forms;
import org.apache.struts.action.ActionForm;
import org.science4you.helpers.NodeType;
public class SpecieForm extends ActionForm {
private static final long serialVersionUID = 1L;
private String id;
private String text;
private String type;
private String specieId;
private String groupName;
private String genusName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String dispatch;
public String getDispatch() {
return dispatch;
}
public void setDispatch(String dispatch) {
this.dispatch = dispatch;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSpecieId() {
return specieId;
}
public void setSpecieId(String specieId) {
this.specieId = specieId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGenusName() {
return genusName;
}
public void setGenusName(String genusName) {
this.genusName = genusName;
}
} |
package com.huangyifei.android.androidexample.mvplist.base.presenter;
/**
* Created by huangyifei on 16/10/25.
*/
public interface ILoadMorePresenter {
int STATE_NORMAL = 0;
int STATE_LOADING = 1;
int STATE_FINISHED = 2;
int STATE_ERROR = 3;
void setLoadMoreState(int state);
}
|
package com.itheima.service;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import java.util.List;
import java.util.Map;
/**
* 套餐服务接口
*/
public interface SetmealService {
/**
* 新增套餐
* @param setmeal 套餐对象
* @param checkgroupIds 检查组ids
*/
void add(Setmeal setmeal, Integer[] checkgroupIds);
Result findPage(String queryString, Integer currentPage, Integer pageSize);
/**
* 查询所有套餐列表数据
* @return
*/
List<Setmeal> findAll();
/**
* 根据套餐id查询(套餐数据+检查组数据+检查项数据)
*
*/
Setmeal findById(Integer id);
/**
* 查询套餐以及套餐预约数量 List<Map<String,Object>>
* @return
*/
List<Map<String,Object>> getSetmealReport();
}
|
package com.summer.activiti.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @program: WebConfig
* @description:
* @author: summer
* @create: 2020-10-16 17:37
**/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
registry.addResourceHandler("/templates/**")
.addResourceLocations("classpath:/templates/");
}
}
|
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
/**
* Created by NSAI on 19/05/2016.
*/
public class MyStepdefs {
@Given("^user should be on Homepage$")
public void userShouldBeOnHomepage() throws Throwable {
}
@When("^user search for the \"([^\"]*)\"$")
public void userSearchForThe(String arg0) throws Throwable {
}
@Then("^user should be able to see the respective\"([^\"]*)\" results$")
public void userShouldBeAbleToSeeTheRespectiveResults(String arg0) throws Throwable {
}
@Given("^user should be on HomePage$")
public void userShouldBeOnHomePage() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^user selects the \"([^\"]*)\" from the results$")
public void userSelectsTheFromTheResults(String arg0) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@And("^user selects the appropriate size$")
public void userSelectsTheAppropriateSize() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@And("^user adds the \"([^\"]*)\" in the Bag$")
public void userAddsTheInTheBag(String arg0) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^user should be able to see the respective \"([^\"]*)\"in the Bag$")
public void userShouldBeAbleToSeeTheRespectiveInTheBag(String arg0) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
}
|
package com.orca.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.orca.domain.Documentation;
import com.orca.domain.Survey;
import com.orca.service.SurveyService;
@SessionAttributes({ "documentation" })
@Controller
public class DocumentationController {
@Autowired
private SurveyService surveyService;
@RequestMapping(value = "documentation.html")
public ModelAndView documentation(@RequestParam("surveyId") Integer surveyId) {
Survey survey = surveyService.getSurvey(surveyId);
if (!surveyService.authorizedUser(survey)){
return new ModelAndView("notAuthorized");
}
ModelAndView mav = new ModelAndView("documentation");
mav.addObject("documentation", survey.getDocumentation());
mav.addObject("survey", survey);
return mav;
}
@RequestMapping(value = "saveDocumentation.html")
public String saveDocumentation(@ModelAttribute("documentation") Documentation documentation,
@RequestParam("surveyId") Integer surveyId, @RequestParam("submit") String submit) {
Survey survey = surveyService.getSurvey(surveyId);
if (!surveyService.authorizedUser(survey)){
return "redirect:notAuthorized.html";
}
survey.setDocumentation(documentation);
surveyService.saveSurvey(survey);
if (submit.equals("Next Metric")){
return "redirect:license.html?surveyId=" + survey.getId();
}
else {
return "redirect:evaluationSummary.html?evaluationId=" + survey.getEvaluation().getId();
}
}
}
|
package cn.canlnac.onlinecourse.data.entity;
import com.google.gson.annotations.SerializedName;
/**
* 注册实体类.
*/
public class RegisterEntity {
@SerializedName("userID")
private int userId;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
package android.support.v7.view.menu;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v7.a.a.f;
import android.support.v7.a.a.h;
import android.support.v7.a.a.k;
import android.support.v7.view.menu.m.a;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
public class ListMenuItemView extends LinearLayout implements a {
private LayoutInflater Bc;
private TextView Dm;
private RadioButton HP;
private CheckBox HQ;
private TextView HR;
private Drawable HS;
private Context HT;
private boolean HU;
private int HV;
private boolean HW;
private h bl;
private int bt;
private ImageView ii;
private Context mContext;
public ListMenuItemView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet);
this.mContext = context;
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, k.MenuView, i, 0);
this.HS = obtainStyledAttributes.getDrawable(k.MenuView_android_itemBackground);
this.bt = obtainStyledAttributes.getResourceId(k.MenuView_android_itemTextAppearance, -1);
this.HU = obtainStyledAttributes.getBoolean(k.MenuView_preserveIconSpacing, false);
this.HT = context;
obtainStyledAttributes.recycle();
}
public ListMenuItemView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
protected void onFinishInflate() {
super.onFinishInflate();
setBackgroundDrawable(this.HS);
this.Dm = (TextView) findViewById(f.title);
if (this.bt != -1) {
this.Dm.setTextAppearance(this.HT, this.bt);
}
this.HR = (TextView) findViewById(f.shortcut);
}
public final void a(h hVar) {
int i = 0;
this.bl = hVar;
this.HV = 0;
setVisibility(hVar.isVisible() ? 0 : 8);
setTitle(hVar.a((a) this));
setCheckable(hVar.isCheckable());
boolean dT = hVar.dT();
hVar.dS();
if (!(dT && this.bl.dT())) {
i = 8;
}
if (i == 0) {
CharSequence charSequence;
TextView textView = this.HR;
char dS = this.bl.dS();
if (dS == 0) {
charSequence = "";
} else {
StringBuilder stringBuilder = new StringBuilder(h.IL);
switch (dS) {
case 8:
stringBuilder.append(h.IN);
break;
case 10:
stringBuilder.append(h.IM);
break;
case ' ':
stringBuilder.append(h.IO);
break;
default:
stringBuilder.append(dS);
break;
}
charSequence = stringBuilder.toString();
}
textView.setText(charSequence);
}
if (this.HR.getVisibility() != i) {
this.HR.setVisibility(i);
}
setIcon(hVar.getIcon());
setEnabled(hVar.isEnabled());
}
public void setForceShowIcon(boolean z) {
this.HW = z;
this.HU = z;
}
public void setTitle(CharSequence charSequence) {
if (charSequence != null) {
this.Dm.setText(charSequence);
if (this.Dm.getVisibility() != 0) {
this.Dm.setVisibility(0);
}
} else if (this.Dm.getVisibility() != 8) {
this.Dm.setVisibility(8);
}
}
public h getItemData() {
return this.bl;
}
public void setCheckable(boolean z) {
if (z || this.HP != null || this.HQ != null) {
CompoundButton compoundButton;
CompoundButton compoundButton2;
if (this.bl.dU()) {
if (this.HP == null) {
dD();
}
compoundButton = this.HP;
compoundButton2 = this.HQ;
} else {
if (this.HQ == null) {
dE();
}
compoundButton = this.HQ;
compoundButton2 = this.HP;
}
if (z) {
int i;
compoundButton.setChecked(this.bl.isChecked());
if (z) {
i = 0;
} else {
i = 8;
}
if (compoundButton.getVisibility() != i) {
compoundButton.setVisibility(i);
}
if (compoundButton2 != null && compoundButton2.getVisibility() != 8) {
compoundButton2.setVisibility(8);
return;
}
return;
}
if (this.HQ != null) {
this.HQ.setVisibility(8);
}
if (this.HP != null) {
this.HP.setVisibility(8);
}
}
}
public void setChecked(boolean z) {
CompoundButton compoundButton;
if (this.bl.dU()) {
if (this.HP == null) {
dD();
}
compoundButton = this.HP;
} else {
if (this.HQ == null) {
dE();
}
compoundButton = this.HQ;
}
compoundButton.setChecked(z);
}
private void setShortcut$25d965e(boolean z) {
int i = (z && this.bl.dT()) ? 0 : 8;
if (i == 0) {
CharSequence charSequence;
TextView textView = this.HR;
char dS = this.bl.dS();
if (dS == 0) {
charSequence = "";
} else {
StringBuilder stringBuilder = new StringBuilder(h.IL);
switch (dS) {
case 8:
stringBuilder.append(h.IN);
break;
case 10:
stringBuilder.append(h.IM);
break;
case ' ':
stringBuilder.append(h.IO);
break;
default:
stringBuilder.append(dS);
break;
}
charSequence = stringBuilder.toString();
}
textView.setText(charSequence);
}
if (this.HR.getVisibility() != i) {
this.HR.setVisibility(i);
}
}
public void setIcon(Drawable drawable) {
boolean z = this.bl.bq.It || this.HW;
if (!z && !this.HU) {
return;
}
if (this.ii != null || drawable != null || this.HU) {
if (this.ii == null) {
this.ii = (ImageView) getInflater().inflate(h.abc_list_menu_item_icon, this, false);
addView(this.ii, 0);
}
if (drawable != null || this.HU) {
ImageView imageView = this.ii;
if (!z) {
drawable = null;
}
imageView.setImageDrawable(drawable);
if (this.ii.getVisibility() != 0) {
this.ii.setVisibility(0);
return;
}
return;
}
this.ii.setVisibility(8);
}
}
protected void onMeasure(int i, int i2) {
if (this.ii != null && this.HU) {
LayoutParams layoutParams = getLayoutParams();
LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) this.ii.getLayoutParams();
if (layoutParams.height > 0 && layoutParams2.width <= 0) {
layoutParams2.width = layoutParams.height;
}
}
super.onMeasure(i, i2);
}
private void dD() {
this.HP = (RadioButton) getInflater().inflate(h.abc_list_menu_item_radio, this, false);
addView(this.HP);
}
private void dE() {
this.HQ = (CheckBox) getInflater().inflate(h.abc_list_menu_item_checkbox, this, false);
addView(this.HQ);
}
public final boolean M() {
return false;
}
private LayoutInflater getInflater() {
if (this.Bc == null) {
this.Bc = LayoutInflater.from(this.mContext);
}
return this.Bc;
}
}
|
package com.bridgeit.CommercialDataProcessing;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import com.bridgeit.utility.Utility;
public class StockAccountImplement implements StockAccount {
ObjectMapper mapper = new ObjectMapper();
public static List<Company> companyList = new ArrayList<>();
public static List<Customer> customerList = new ArrayList<>();
public static List<Transaction> transactionList = new ArrayList<>();
long increaseDecreaseShare;
long currentAmount;
Date date = new Date();
/**
* function to create the file
*/
public void create() throws IOException {
System.out.println("Enter the name of your Account");
String name = Utility.inputString();
File file = new File("CommercialData/" + name + ".json");
if (file.createNewFile()) {
System.out.println("File is created");
} else {
System.out.println("File is already created");
}
}
/*
* Function to buy the share by the customer
*/
@Override
public void buy(String name) {
System.out.println("User Enter the Symbol");
String symbol = Utility.inputString();
System.out.println("User enter the Amount");
long amount = Utility.inputLong();
Transaction transaction = new Transaction();
increaseDecreaseShare = 0;
int equalSymbol = 0;
int smallAmount = 0;
for (Company company : companyList) {
if (company.getCompanySymbol().equals(symbol)) {
if (amount >= company.getCompanyPricePerShare()) {
smallAmount++;
if (!customerList.isEmpty()) {
for (Customer customerLoop : customerList) {
currentAmount = customerLoop.getCustomerAmount();
if (customerLoop.getCustomerSymbol().equals(symbol)) {
equalSymbol++;
smallAmount++;
customerLoop.setCustomerName(name);
customerLoop.setCustomerAmount(customerLoop.getCustomerAmount() - amount);
customerLoop.setCustomerShare(
customerLoop.getCustomerShare() + (amount / company.getCompanyPricePerShare()));
}
}
}
if (equalSymbol == 0) {
smallAmount++;
Customer customer = new Customer();
customer.setCustomerAmount(currentAmount - amount);
customer.setCustomerName(name);
customer.setCustomerSymbol(symbol);
customer.setCustomerShare(amount / company.getCompanyPricePerShare());
customerList.add(customer);
}
LinkedQueue<String> linkedQueue = new LinkedQueue<String>();
increaseDecreaseShare = amount / company.getCompanyPricePerShare();
company.setCompanySharesAvailable(company.getCompanySharesAvailable() - increaseDecreaseShare);
linkedQueue.add(date.toString());
System.out.println("Transaction Started");
transaction.setCustomerName(name);
transaction.setBuySell("Buy");
transaction.setSymbol(symbol);
transaction.setDate(date.toString());
transactionList.add(transaction);
linkedQueue.remove();
System.out.println("Transaction Stop");
}
}
}
if (smallAmount == 0) {
System.out.println("Your Balance is low....Please add Money");
}
}
// Function sell the share by the customer
@Override
public void sell(String name) {
Customer customer1 = new Customer();
System.out.println("User enter the Symbol");
String symbol = Utility.inputString();
System.out.println("User Enter the Amount");
long amount = Utility.inputLong();
increaseDecreaseShare = 0;
Transaction transaction = new Transaction();
for (Customer customer : customerList) {
if (customer.getCustomerSymbol().equals(symbol)) {
if (customer.getCustomerAmount() >= amount) {
for (Company company : companyList) {
if (company.getCompanySymbol().equals(symbol)) {
company.setCompanySharesAvailable(
company.getCompanySharesAvailable() + (amount / company.getCompanyPricePerShare()));
customer.setCustomerAmount(customer.getCustomerAmount() + amount);
customer.setCustomerShare(
customer.getCustomerShare() - (amount / company.getCompanyPricePerShare()));
LinkedQueue<String> linkedQueue = new LinkedQueue<String>();
linkedQueue.add(date.toString());
System.out.println("Transaction started");
customer.setCustomerName(name);
transaction.setCustomerName(name);
transaction.setBuySell("Sell");
transaction.setSymbol(symbol);
transaction.setDate(date.toString());
transactionList.add(transaction);
linkedQueue.remove();
System.out.println("transaction Stop");
}
}
} else {
System.out.println("entered amount is greater than your balance amount");
}
}
}
}
// @Override
// public long valueOf(List<Company> company) {
//
// return 0;
// }
// Function to read the file
public void read(String file) {
ObjectMapper mapper = new ObjectMapper();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("CommercialData/" + file + ".json"));
String arrayFile;
if ((arrayFile = bufferedReader.readLine()) != null) {
if (file.equals("Company")) {
companyList = mapper.readValue(arrayFile, new TypeReference<ArrayList<Company>>() {
});
} else if (file.equals("Transaction")) {
transactionList = mapper.readValue(arrayFile, new TypeReference<ArrayList<Transaction>>() {
});
} else {
customerList = mapper.readValue(arrayFile, new TypeReference<ArrayList<Customer>>() {
});
}
bufferedReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Function to check the file in the folder
public boolean checkAddressBook(String stockFile) {
File fileName = new File("CommercialData");
for (File file : fileName.listFiles()) {
if (file.isFile()) {
if (file.getName().equals(stockFile + ".json")) {
return true;
}
}
}
return false;
}
// Function to write the list in the file
public <T> void saveInFile(String file, List<T> T) {
try {
mapper.writeValue(new File("CommercialData/" + file + ".json"), T);
System.out.println("\n\tData saved");
} catch (IOException e) {
e.printStackTrace();
}
}
// function to save the file
public void savetofile(String file, String name) {
saveInFile(file, companyList);
saveInFile(name, customerList);
saveInFile("Transaction", transactionList);
}
@Override
// public void save(String fileName, String name) {
//
// int i = 0;
// while (i == 0) {
// System.out.println("\n\t1. Save Company \n\t2. Save User \n\t3. Save
// Transaction \n\t4. Exit");
// System.out.println("\n User Enter your choice");
// int choice = Utility.inputInteger();
// {
// switch (choice) {
// case 1:
//
// saveInFile(fileName, companyList);
// break;
// case 2:
//
// saveInFile(name, customerList);
// break;
// case 3:
// saveInFile("Transaction", transactionList);
// break;
// case 4:
// i = 1;
// System.out.println("save service close");
// default:
// // System.out.println("Something Wrong.....");
// }
// }
// }
// }
// Function to print the Company details
public void printReport() {
for (Company company : companyList) {
System.out.println(company.toString());
}
}
// Function to print the Details of Customer
public void printCustomer()
{
for (Customer customer : customerList) {
System.out.println(customer.toString());
}
long amount = 0;
for (Customer customer1 : customerList) {
amount = amount + customer1.getCustomerAmount();
}
System.out.println("\n\tBalance: " + amount);
}
// Function to Display the Transaction Using Stack
public void printTransaction()
{
LinkedStack<String> stack = new LinkedStack<String>();
for (Transaction transaction : transactionList) {
stack.add(transaction.toString());
}
stack.display();
}
// Function to Add Money in Customer Account
public void addMoney()
{
System.out.println("User Enter the Amount");
currentAmount = Utility.inputInteger();
}
// Function to add and remove company using Linked List
public void addRemoveCompany() {
LinkedList<Company> list = new LinkedList<Company>();
for (Company company : companyList) {
list.add(company);
}
list.display();
int addLoop = 0;
while (addLoop == 0) {
System.out.println("\n\t1. Add Company \n\t2. Remove Company \n\t3. Save Company \n\t4. Exit");
System.out.println("User Enter Your Choice");
int choice = Utility.inputInteger();
switch (choice)
{
case 1:
Company company = new Company();
System.out.println("\nEnter the company name");
String name = Utility.inputString();
company.setCompanySymbol(name);
System.out.println("Enter the Share Available");
long shares = Utility.inputLong();
company.setCompanySharesAvailable(shares);
System.out.println("Enter Price per share");
long price = Utility.inputLong();
company.setCompanyPricePerShare(price);
list.add(company);
companyList.add(company);
System.out.println();
list.display();
break;
case 2:
System.out.println("Enter the company name to remove");
String name1 = Utility.inputString();
int i = 1;
for (Company company1 : companyList) {
System.out.println("\n" + i + " for " + company1.getCompanySymbol());
i++;
}
System.out.println("Enter choice to remove Company");
int choiceRemove = Utility.inputInteger();
list.remove(choiceRemove);
companyList.remove(choiceRemove - 1);
list.display();
break;
case 3:
saveInFile("Company", companyList);
break;
case 4:
addLoop = 1;
System.out.println("Add And remove service closed ");
default:
addLoop = 1;
// System.out.println("Something Wrong......");
break;
}
}
}
// Function to close the service
public void close() {
customerList.clear();
}
}
|
package com.widera.petclinic.config;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.widera.petclinic.domain")
@ComponentScan(basePackages = "com.widera.petclinic")
public class DataConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean =
new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("com.widera.petclinic.domain.entities");
factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factoryBean.setJpaProperties(getJpaProperties());
LoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
factoryBean.setLoadTimeWeaver(loadTimeWeaver);
return factoryBean;
}
@Bean
public Properties getJpaProperties() {
Properties jpaProperties = new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "none");
jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return jpaProperties;
}
@Bean
public DataSource dataSource() {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/my_base?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
dataSource.setUser("root");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
}
|
package com.bingo.code.example.mediator;
/**
* 职员接口
*/
public abstract class ZhiYuan {
String name;
private Mediator mediator;
public ZhiYuan(Mediator mediator, String name) {
this.mediator = mediator;
this.name = name;
}
//被调停者调用的方法
public void called(String message, String nname) {
System.out.println(name + "接收到来自" + nname + "的需求:" + message);
}
//调用调停者
public void call(String message, ZhiYuan zhiyuan, String nname) {
System.out.println(nname + "发起需求:" + message);
mediator.change(message, zhiyuan, nname);
}
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.test.interceptors.dependent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Bean;
import org.junit.Assert;
import org.apache.webbeans.test.AbstractUnitTest;
import org.junit.Test;
public class DependentLifecycleTest extends AbstractUnitTest
{
@Test
@SuppressWarnings("unchecked")
public void testLifecycle()
{
Collection<String> beanXmls = new ArrayList<String>();
Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
beanClasses.add(DependentLifecycleBean.class);
startContainer(beanClasses, beanXmls);
Set<Bean<?>> beans = getBeanManager().getBeans("org.apache.webbeans.test.interceptors.dependent.DependentLifecycleBean");
Assert.assertNotNull(beans);
Bean<DependentLifecycleBean> bean = (Bean<DependentLifecycleBean>)beans.iterator().next();
CreationalContext<DependentLifecycleBean> ctx = getBeanManager().createCreationalContext(bean);
DependentLifecycleBean reference = (DependentLifecycleBean) getBeanManager().getReference(bean, DependentLifecycleBean.class, ctx);
Assert.assertNotNull(reference);
Assert.assertEquals(1, DependentLifecycleBean.value);
Assert.assertTrue(DependentSuperBean.SC);
Assert.assertTrue(MyExtraSuper.SC);
bean.destroy(reference, ctx);
shutDownContainer();
Assert.assertEquals(0, DependentLifecycleBean.value);
Assert.assertFalse(DependentSuperBean.SC);
Assert.assertFalse(MyExtraSuper.SC);
}
}
|
package AdventureGame;
import java.util.Random;
public class Monster {
public static void reGenereate()
{
Random rand = new Random();
int x = rand.nextInt(100);
int y = rand.nextInt(100);
Monster m = new Monster();
}
}
|
package by.yanpo;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Delete extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/schem_devcolibri"+
"?verifyServerCertificate=false"+
"&useSSL=false"+
"&requireSSL=false"+
"&useLegacyDatetimeCode=false"+
"&"+
"&serverTimezone=UTC";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
private static String SQL;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
if (!con.isClosed())
System.out.println("\n***Connection is OK***");
Statement stat = con.createStatement();
String id = request.getParameter("id");
String table = request.getParameter("tabl");
System.out.println(table);
if (!id.equals("0")) {
SQL = "delete from "+table+
" where id = " + id + ";";
System.out.println(SQL);
stat.executeUpdate(SQL);
}
con.close();
response.setStatus(response.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "index.jsp");
}
catch (SQLException e) {
System.err.println();
System.err.println("Error code: "+e.getErrorCode());
System.err.println("SQLState: "+e.getSQLState());
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
doGet(request, response);
}
} |
package com.naver.mapper;
import java.util.HashMap;
import org.apache.ibatis.annotations.Param;
public interface TestMapper {
int confirmIdWord(@Param("usrid")long usr_id,
@Param("bottype")int bottype, @Param("flag")int flag);
HashMap sendProblem(@Param("usrid")long usrid, @Param("bottype")int bottype,
@Param("flag")int flag);
int addTest(@Param("usrid")long usrid, @Param("bottype") int bottype,
@Param("question")String question);
int updateFlag(@Param("usrid")long usrid, @Param("flag")int flag,
@Param("bottype") int bottype);
String[] confirmAnswerR(@Param("usrid")long usrid,
@Param("bottype") int bottype);
String[] confirmAnswerL(@Param("usrid")long usrid,
@Param("bottype") int bottype);
int confirmFlag(@Param("usrid")long usrid, @Param("bottype")int bottype);
int updateRw(@Param("usrid")long usrid, @Param("bottype")int bottype,
@Param("rw") int rw);
}
|
package cn.gzcc.feibao.service.impl;
import cn.gzcc.feibao.entity.User;
import cn.gzcc.feibao.repository.UserRepository;
import cn.gzcc.feibao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServicelmpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User addUser(User user){
if (user.getUsername()!=null && user.getPassword()!=null){
userRepository.save(user);
}
else{
user=null;
}
return user;
}
}
|
package database;
import java.util.List;
import javax.sql.DataSource;
public interface BountyDAO {
public void setDataSource(DataSource ds);
public void createBounty(Bounty bounty);
public Bounty getBounty(int id);
public List<Bounty> listBounties();
public void deleteBounty(int id);
public void updateUser(int id, String title, String criteria, String description, double value, String expiration);
}
|
package view;
/**
* Created by mycomputer on 16.05.2015.
*/
public class Ffff {
}
|
/*
Copyright 2013-2014 eBay Software Foundation
*/
package com.ebay.lightning.core.async;
/**
* The {@code Callback} class defines the callback handler for {@link Reminder} thread.
*
* @author shashukla
* @see Reminder
*/
public interface Callback<T> {
/**
* This method is called by the Reminder task whenever it gets executed.
* @param data the input data
*/
public void notify(T data);
}
|
package uo.sdi.business.impl.user;
import javax.ejb.Remote;
import uo.sdi.business.UserService;
@Remote
public interface EjbUserServiceRemote extends UserService{
}
|
package stepdefinations.Grant_Application;
import cucumber.api.java.en.Then;
public class Business_Impact_step {
Business_Impact_step Business;
@Then("^click the Business Impact$")
public void click_the_Business_Impact() throws Throwable {
// Write code here that turns the phrase above into concrete actions
Business.business();
}
@Then("^Enter the FY End Date \"([^\"]*)\"$")
public void enter_the_FY_End_Date(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
Business= new Business_Impact_page(TestBase.driver);
Business.Fy_End_date(arg1);
}
}
|
package com.oxycab.provider.ui.activity.regsiter.details;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oxycab.provider.BuildConfig;
import com.oxycab.provider.R;
import com.oxycab.provider.base.BaseActivity;
import com.oxycab.provider.common.CommonValidation;
import com.oxycab.provider.common.SharedHelper;
import com.oxycab.provider.data.network.model.User;
import com.oxycab.provider.ui.activity.document.DocumentActivity;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
public class AddDriverActivity extends BaseActivity implements AddDriverIView {
AddDriverPresenter<AddDriverActivity> presenter = new AddDriverPresenter<AddDriverActivity>();
@BindView(R.id.back)
ImageView back;
@BindView(R.id.title)
TextView title;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.contact_1)
EditText contact1;
@BindView(R.id.contact_2)
EditText contact2;
@BindView(R.id.ll_emergency)
LinearLayout llEmergency;
@BindView(R.id.registration_layout)
LinearLayout registrationLayout;
@BindView(R.id.next)
TextView next;
@BindView(R.id.ll_content)
LinearLayout llContent;
Map<String, String> map = new HashMap<String, String>();
Type type = new TypeToken<Map<String, String>>(){}.getType();
@Override
public int getLayoutId() {
return R.layout.activity_add_driver;
}
@Override
public void initView() {
ButterKnife.bind(this);
presenter.attachView(this);
map = new Gson().fromJson(getIntent().getStringExtra("data"), map.getClass());
}
@Override
public void onSuccess(User user) {
SharedHelper.putKey(this, "user_id", String.valueOf(user.getId()));
SharedHelper.putKey(this, "access_token", user.getAccessToken());
SharedHelper.putKey(this, "loggged_in", "true");
SharedHelper.putKey(this, "invite_code", user.getReferralCode());
Toasty.success(this, "Registered Successfully!", Toast.LENGTH_SHORT, true).show();
finishAffinity();
Intent intent = new Intent(this, DocumentActivity.class);
intent.putExtra("first", true);
finish();
startActivity(intent);
}
@OnClick({R.id.back, R.id.next})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.back:
onBackPressed();
break;
case R.id.next:
if (!TextUtils.isEmpty(contact1.getText().toString())) {
if (CommonValidation.isValidPhone(contact1.getText().toString())) {
Toasty.error(this, getString(R.string.validmobile), Toast.LENGTH_SHORT, true).show();
contact1.requestFocus();
return;
}
}
if (!TextUtils.isEmpty(contact2.getText().toString())) {
if (CommonValidation.isValidPhone(contact2.getText().toString())) {
Toasty.error(this, getString(R.string.validmobile), Toast.LENGTH_SHORT, true).show();
contact2.requestFocus();
return;
}
}
Map<String, RequestBody> reqMap = new HashMap<>();
reqMap.put("first_name", toRequestBody(map.get("first_name" )));
reqMap.put("last_name", toRequestBody(map.get("last_name" )));
reqMap.put("mobile", toRequestBody(map.get("mobile" )));
reqMap.put("password",toRequestBody(map.get("password" )));
reqMap.put("password_confirmation", toRequestBody(map.get("password_confirmation" )));
reqMap.put("device_token",toRequestBody( map.get("device_token")));
reqMap.put("device_id", toRequestBody(map.get("device_id" )));
reqMap.put("device_type", toRequestBody(map.get("device_type" )));
reqMap.put("country_code",toRequestBody(map.get("country_code" )));
reqMap.put("email",toRequestBody(map.get("email" )));
reqMap.put("aadhar_number",toRequestBody(map.get("aadhar_number" )));
if (!map.get("referral_code" ).isEmpty())
{
reqMap.put("referral_code",toRequestBody(map.get("referral_code" )));
}
reqMap.put("emergency_contact1", toRequestBody(contact1.getText().toString()));
reqMap.put("emergency_contact2", toRequestBody(contact2.getText().toString()));
List<MultipartBody.Part> parts = new ArrayList<>();
showLoading();
presenter.register(reqMap, parts);
break;
}
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Calculator {
private String numbers;
private List<String> separators;
private static final String EMPTY_STRING = "";
private static final String COMMA = ",";
private static final String NEW_LINE = "\n";
private static final String SPLIT_LINE = "|";
private static final int ZERO_NUMBER = 0;
private static final int BIG_NUMBER = 1000;
private static final String FORWARD_SLASH = "//";
private static final String DELIMITTERS_PATTERN = "\\/\\/(\\[([^0-9]+)\\])+\n(.*)";
private static final String DELIMITTERS_END = "\\]";
private static final String NUMBERS_PATTERN_BEGGINGING = "[0-9]+([";
private static final String NUMBERS_PATTERN_END = "]+[0-9]+)*";
public Calculator(){
separators = new ArrayList<String>();
resetSeparators();
}
public List<String> getSeparators() {
return separators;
}
public void setSeparators(List<String> separators) {
this.separators = separators;
}
public String getNumbers() {
return this.numbers;
}
public void setNumbers(String numbers) {
this.numbers = numbers;
}
private void resetSeparators(){
separators.clear();
separators.add(COMMA);
separators.add(NEW_LINE);
}
private String separatorsToString(){
StringBuilder separatorsStringBuilder = new StringBuilder();
String separatorsString = "";
for (String separator : separators) {
separatorsStringBuilder.append(separator);
separatorsStringBuilder.append(SPLIT_LINE);
}
separatorsString = separatorsStringBuilder.toString();
if(!EMPTY_STRING.equals(separatorsString)){
separatorsString = separatorsString.substring(0, separatorsString.length() - 1);
}
return separatorsString.toString();
}
public int add(String numbers){
setNumbers(numbers);
if(this.numbers == null || this.numbers.equals(EMPTY_STRING)){
return 0;
}
if(!(isValidInput() && checkSeparators())){
throw new IllegalArgumentException("Illegal format");
}
boolean withNegativeNumbers = false;
List<String> negativeNumbers = new ArrayList<String>();
List<String> values = Arrays.asList(this.numbers.split(separatorsToString()));
int result = 0;
for (String value : values) {
int intValue = Integer.parseInt(value);
if(intValue <= BIG_NUMBER){
result = result += intValue;
}
if(intValue < ZERO_NUMBER){
withNegativeNumbers = true;
negativeNumbers.add(value);
}
}
if(withNegativeNumbers){
throw new IllegalArgumentException(new StringBuilder("Negatives not allowed: ").append(negativeNumbers.toString()).toString());
}
resetSeparators();
return result;
}
private boolean isValidInput(){
String separatorsString = separatorsToString();
Pattern pattern = Pattern.compile(new StringBuilder(NUMBERS_PATTERN_BEGGINGING).append(separatorsString).append(NUMBERS_PATTERN_END).toString());
Matcher matcher;
matcher = pattern.matcher(this.numbers);
if(!matcher.matches()){
return false;
}
return true;
}
private boolean checkSeparators(){
Pattern pattern = Pattern.compile(DELIMITTERS_PATTERN);
Matcher matcher;
if(this.numbers.startsWith(FORWARD_SLASH)){
matcher = pattern.matcher(this.numbers);
if(!matcher.matches()){
return false;
}
String[] numberParts = this.numbers.split(NEW_LINE);
String separatorString = numberParts[0];
separatorString = separatorString.substring(2, separatorString.length());
List<String> delimiters = Arrays.asList(separatorString.split(DELIMITTERS_END));
for (String delimiter : delimiters) {
separators.add(delimiter.substring(1, delimiter.length()));
}
this.numbers = numberParts[1];
}
return true;
}
}
|
package inter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/*
* Question
* coorditates of all rectangles and their area
* largest rectangle. rectangle is formed by 1's
* */
public class IntuitAllRect {
public static void main(String[] args) {
char matrix[][] = {
{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}
};
System.out.println(maximalRectangle(matrix));
}
public static int maximalRectangle(char[][] matrix) {
HashMap<String, List<Integer>> lookup = new HashMap<>();
List<Integer> result;
if (matrix.length == 0)
return 0;
int m = matrix.length;
int n = matrix[0].length;
int[] left = new int[n], right = new int[n], height = new int[n];
for (int i = 0; i < n; ++i)
right[i] = n;
int maxA = 0;
for (int i = 0; i < m; ++i) {
int cur_left = 0, cur_right = n;
for (int j = 0; j < n; j++) { // compute height (can do this from
// either side)
if (matrix[i][j] == '1')
height[j]++;
else
height[j] = 0;
}
for (int j = 0; j < n; j++) { // compute left (from left to right)
if (matrix[i][j] == '1')
left[j] = Math.max(left[j], cur_left);
else {
left[j] = 0;
cur_left = j + 1;
}
}
// compute right (from right to left)
for (int j = n - 1; j >= 0; j--) {
if (matrix[i][j] == '1')
right[j] = Math.min(right[j], cur_right);
else {
right[j] = n;
cur_right = j;
}
}
// compute the area of rectangle (can do this from either side)
for (int j = 0; j < n; j++){
int leftCoordsX = (i-height[j]+1);
int leftCoordsY = left[j];
int rightCoordsX = i;
int rightCoordsY = right[j] - 1;
String key = leftCoordsX + " " + leftCoordsY;
int area = (right[j] - left[j]) * height[j];
if(area == 0) continue;
result = new ArrayList<>();
result.add(leftCoordsX);
result.add(leftCoordsY);
result.add(rightCoordsX);
result.add(rightCoordsY);
result.add(area);
if(lookup.containsKey(key)){
if(lookup.get(key).get(4) < area){
lookup.put(key, result);
}
}
else{
lookup.put(key, result);
}
// System.out.println(lookup);
// System.out.println(result);
// System.out.println(i+" "+height[j]+" "+((right[j] - left[j]) * height[j]));
//System.out.println("left "+left[j]+" right "+right[j]);
// System.out.println( i+" "+(i-height[j]+1)+" "+left[j]+" "+right[j]);
maxA = Math.max(maxA, (right[j] - left[j]) * height[j]);
}
}
return maxA;
}
}
|
import java.util.Arrays;
/**
* Created by red6 on 4/5/2017.
*/
public class Fourth {
public static void main(String[] args) {
// ---------- Arrays
int [] data = new int[10];
String [] names = new String[5];
names[0] = "Oleg";
System.out.println(Arrays.toString(data));
System.out.println(Arrays.toString(names));
}
}
|
/*
* Created on May 13, 2005
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.ibm.ive.tools.japt;
/**
* Represents a message to be delivered to the user through a Japt logger.
*
* @author sfoley
*
*/
public abstract class LogMessage extends Message {
/**
* @param string
*/
public LogMessage(FormattedString string) {
super(string);
}
/**
* @param message
*/
public LogMessage(String message) {
super(message);
}
/**
* @param components
*/
public LogMessage(String[] components) {
super(components);
}
/**
* write the message using the given logger
*/
public void log(Logger logger) {
log(logger, (Object[]) null);
}
/**
* write the message using the given logger with the given argument which will
* appear after the first message component
*/
public void log(Logger logger, Object argument) {
log(logger, new Object[] {argument});
}
/**
* write the message using the given logger with the given arguments.
* Calls the final method logMessage. Override this method for specialized
* message handling.
*/
public void log(Logger logger, Object arguments[]) {
logMessage(logger, arguments);
}
/**
* write the message using the given logger with the given arguments
*/
final void logMessage(Logger logger, Object arguments[]) {
String[] components = getComponents();
if(arguments != null) {
for(int i=0; i<components.length && components[i] != null; i++) {
outputObject(logger, components[i]);
int argNum = getArgumentNumber(i);
if(argNum >= 0 && argNum < arguments.length) {
Object o = arguments[argNum];
if(o == null) {
outputObject(logger, "null");
}
else {
outputObject(logger, arguments[argNum]);
}
}
}
}
else {
for(int i=0; i<components.length && components[i] != null; i++) {
outputObject(logger, components[i]);
}
}
outputObject(logger, Logger.endl);
logger.flush();
}
/**
* output the message using the given logger.
*/
protected abstract void outputObject(Logger logger, Object object);
}
|
package edu.bluejack19_2.chronotes.model;
import android.util.Log;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.UUID;
public class Task {
private String TaskId;
private ArrayList<String> UserId;
private String Start;
private String End;
private String Title;
private String Detail;
private String Repeat;
private ArrayList<String> Tags;
private Integer Priority;
private Boolean Completed;
private String CreatedBy;
public Task() {
}
public Task(String TaskId, ArrayList<String> userId, String start, String end, String title, String detail, String repeat, ArrayList<String> tags, Integer priority, Boolean completed) {
UserId = userId;
this.TaskId = TaskId;
Start = start;
End = end;
Title = title;
Detail = detail;
Repeat = repeat;
Tags = tags;
Priority = priority;
Completed = completed;
CreatedBy = userId.get(0);
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public String getCreatedBy() {
return CreatedBy;
}
public Boolean getCompleted() {
return Completed;
}
public void setCompleted(Boolean completed) {
Completed = completed;
}
public static Comparator<Task> PriorityDescending = new Comparator<Task>() {
@Override
public int compare(Task a, Task b) {
Log.d("DEBUG", "COMPARING");
int completedComp = Boolean.compare(a.getCompleted(), b.getCompleted());
int priorityComp = a.getPriority().compareTo(b.getPriority());
//
if(completedComp == 0){
return((priorityComp == 0) ? completedComp:priorityComp);
}
return completedComp;
}
};
public static Comparator<Task> TitleDescending = new Comparator<Task>() {
@Override
public int compare(Task a, Task b) {
Log.d("DEBUG", "COMPARING");
int completedComp = Boolean.compare(a.getCompleted(), b.getCompleted());
int titleComp = a.getTitle().compareTo(b.getTitle());
//
if(completedComp == 0){
return((titleComp == 0) ? completedComp:titleComp);
}
return completedComp;
}
};
public void setTaskId(String taskId) {
TaskId = taskId;
}
public void setUserId(ArrayList<String> userId) {
UserId = userId;
}
public void addUserId(String id){
UserId.add(id);
}
public void removeUserId(String id){
UserId.remove(id);
}
public void setStart(String start) {
Start = start;
}
public void setEnd(String end) {
End = end;
}
public void setTitle(String title) {
Title = title;
}
public void setDetail(String detail) {
Detail = detail;
}
public void setRepeat(String repeat) {
Repeat = repeat;
}
public void setTags(ArrayList<String> tags) {
Tags = tags;
}
public void setPriority(Integer priority) {
Priority = priority;
}
public String getTaskId() {
return TaskId;
}
public ArrayList<String> getUserId() {
return UserId;
}
public String getStart() {
return Start;
}
public String getEnd() {
return End;
}
public String getTitle() {
return Title;
}
public String getDetail() {
return Detail;
}
public String getRepeat() {
return Repeat;
}
public ArrayList<String> getTags() {
return Tags;
}
public Integer getPriority() {
return Priority;
}
}
|
package helloworld;
/**
* Created by kth919 on 2017-08-11.
*/
/*
- 대소문자 판별 -> 서로 같은 자리수 만큼만 아스키코드에 할당되어있는 것을 이용
알파벳 26자.
- n만큼 더한 아스키코드를 문자열로 반환
-
1. 소대문자 따로
2. 범위를 아무리 넘어가는 큰 n 이어도 반응해야함.
*/
public class Caesar {
String caesar(String s, int n) {
StringBuilder result = new StringBuilder();
char[] a = s.toCharArray();
int tmpN = n;
for (int i = 0; i<s.length(); i++){
if (s.charAt(i) != 32) {
while (tmpN>0){
a[i] = (char) (a[i] + 1);
if (a[i] > 'z' ){
a[i] = 'a';
} else if (a[i] > 'Z' && s.charAt(i) < 'a' ){
a[i] = 'A';
}
tmpN--;
}
}
tmpN = n;
result.append(a[i]);
}
return result.toString();
}
public static void main(String[] args) {
Caesar c = new Caesar();
System.out.println("s는 'a B z', n은 4인 경우: " + c.caesar("vbiLIJSBXF", 34));
}
}
|
package com.example.spring.data.jpa.soft.delete.sample.repository;
import com.example.spring.data.jpa.soft.delete.sample.model.CustomerGroup;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
/**
* Created by pkpk1234 on 2017/5/28.
*/
@Repository
public interface CustomerGroupRepository extends JpaRepository<CustomerGroup,Long> {
@Modifying
@Query(value = "truncate table customer_group",nativeQuery = true)
void truncate();
}
|
package cn.zhang.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionUtil {
private static SqlSessionFactory sqlSessionFactory;
//使用ThreadLocal保存需要整个执行过程一致的对象
private static ThreadLocal<SqlSession> tl=new ThreadLocal<SqlSession>();
//加载配置,创建单例工厂,只执行一次
static{
String resource="mybatis-config.xml";
try {
InputStream in=Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private SqlSessionUtil() {}
public static SqlSession getSession(){
SqlSession session=tl.get();
if(session==null){
//如果不存在session,创建并保存到ThreadLocal中
session=sqlSessionFactory.openSession();
tl.set(session);
}
return session;
}
public static void close(SqlSession session){//关指定的session
if(session!=null){
session.close();//关闭session
//由于可能使用线程池,如果不删除tl中的内容,那么它会长久的存在,导致错误
tl.remove();
}
}
}
|
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.3.0
// Vedere <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2021.06.10 alle 04:43:49 PM CEST
//
package com.ricettadem.soap.richiestaLottiNre;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java per anonymous complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="CodRegione" type="{http://tipodati.xsd.nre.mirsac.sanita.finanze.it}CodRegioneType"/>
* <element name="IdentificativoLotto" type="{http://tipodati.xsd.nre.mirsac.sanita.finanze.it}integer1"/>
* <element name="CFMedico" type="{http://tipodati.xsd.nre.mirsac.sanita.finanze.it}CFMedicoType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"codRegione",
"identificativoLotto",
"cfMedico"
})
@XmlRootElement(name = "LottoRichiestaNRE", namespace = "http://lottorichiesta.xsd.nre.mirsac.sanita.finanze.it")
public class LottoRichiestaNRE {
@XmlElement(name = "CodRegione", namespace = "http://lottorichiesta.xsd.nre.mirsac.sanita.finanze.it", required = true)
protected String codRegione;
@XmlElement(name = "IdentificativoLotto", namespace = "http://lottorichiesta.xsd.nre.mirsac.sanita.finanze.it", required = true)
protected String identificativoLotto;
@XmlElement(name = "CFMedico", namespace = "http://lottorichiesta.xsd.nre.mirsac.sanita.finanze.it")
protected String cfMedico;
/**
* Recupera il valore della proprietà codRegione.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodRegione() {
return codRegione;
}
/**
* Imposta il valore della proprietà codRegione.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodRegione(String value) {
this.codRegione = value;
}
/**
* Recupera il valore della proprietà identificativoLotto.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdentificativoLotto() {
return identificativoLotto;
}
/**
* Imposta il valore della proprietà identificativoLotto.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdentificativoLotto(String value) {
this.identificativoLotto = value;
}
/**
* Recupera il valore della proprietà cfMedico.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCFMedico() {
return cfMedico;
}
/**
* Imposta il valore della proprietà cfMedico.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCFMedico(String value) {
this.cfMedico = value;
}
}
|
package com.tencent.mm.plugin.product.b;
import com.tencent.mm.g.a.lz;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class a extends c<lz> {
public a() {
this.sFo = lz.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
String str = null;
lz lzVar = (lz) bVar;
switch (lzVar.bWu.opType) {
case 1:
com.tencent.mm.plugin.product.a.a.bmF();
c bmG = com.tencent.mm.plugin.product.a.a.bmG();
if (bmG != null) {
m b = m.b(null, lzVar.bWu.bWw);
bmG.a(b, null);
lzVar.bWv.bWx = bmG.bmY();
lz.b bVar2 = lzVar.bWv;
if (!bi.oW(b.bnb())) {
str = com.tencent.mm.plugin.product.ui.c.JC(b.bnb());
}
bVar2.bOX = str;
lzVar.bWv.bJm = true;
break;
}
x.w("MicroMsg.MallProductListener", "error, xml[%s] can not parse", new Object[]{lzVar.bWu.bWw});
lzVar.bWv.bJm = false;
break;
}
return false;
}
}
|
public class Ex21 {
public enum Money {
ONE, TWO, THREE, FOUR, FIVE, SIX
}
public static void main(String[] args) {
for (Money m : Money.values()) {
System.out.println(m + " " + m.ordinal());
}
}
}
|
package com.pisto.frankensteinapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import io.realm.Realm;
public class FuelHistoryFragment extends Fragment
{
private Realm database;
private RecyclerView historyRecyclerView;
private LinearLayoutManager layoutManager;
private HistoryViewAdapter historyAdapter;
public FuelHistoryFragment(Realm database)
{
this.database = database;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
getHistoryFuelData(rootView);
return rootView;
}
private void getHistoryFuelData(View rootView)
{
database.beginTransaction();
populateRecyclerView(rootView, database);
database.commitTransaction();
}
private void populateRecyclerView(View rootView, Realm database)
{
historyRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_history_fuel);
historyRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(rootView.getContext());
historyRecyclerView.setLayoutManager(layoutManager);
historyAdapter = new HistoryViewAdapter(database.where(FuelItem.class).findAll());
historyRecyclerView.setAdapter(historyAdapter);
}
} |
/**
*
* ******************************************************************************
* MontiCAR Modeling Family, www.se-rwth.de
* Copyright (c) 2017, Software Engineering Group at RWTH Aachen,
* All rights reserved.
*
* This project 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 3.0 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 project. If not, see <http://www.gnu.org/licenses/>.
* *******************************************************************************
*/
package de.monticore.lang.monticar.cnnarch._symboltable;
import de.monticore.lang.monticar.types2._ast.ASTElementType;
import de.monticore.symboltable.CommonSymbol;
import de.monticore.symboltable.MutableScope;
import de.monticore.symboltable.Scope;
import de.monticore.symboltable.Symbol;
import java.util.*;
public class ArchTypeSymbol extends CommonSymbol {
public static final ArchTypeKind KIND = new ArchTypeKind();
protected static final String DEFAULT_ELEMENT_TYPE = "Q(-oo:oo)";
private ASTElementType domain;
private int channelIndex = -1;
private int heightIndex = -1;
private int widthIndex = -1;
private List<ArchSimpleExpressionSymbol> dimensions = new ArrayList<>();
public ArchTypeSymbol() {
super("", KIND);
ASTElementType elementType = new ASTElementType();
elementType.setTElementType(DEFAULT_ELEMENT_TYPE);
setDomain(elementType);
}
public ASTElementType getDomain() {
return domain;
}
public void setDomain(ASTElementType domain) {
this.domain = domain;
}
public int getHeightIndex() {
return heightIndex;
}
public void setHeightIndex(int heightIndex) {
this.heightIndex = heightIndex;
}
public int getWidthIndex() {
return widthIndex;
}
public void setWidthIndex(int widthIndex) {
this.widthIndex = widthIndex;
}
public int getChannelIndex() {
return channelIndex;
}
public void setChannelIndex(int channelIndex) {
this.channelIndex = channelIndex;
}
public ArchSimpleExpressionSymbol getHeightSymbol() {
if (getHeightIndex() == -1){
return ArchSimpleExpressionSymbol.of(1);
}
return getDimensionSymbols().get(getHeightIndex());
}
public ArchSimpleExpressionSymbol getWidthSymbol() {
if (getWidthIndex() == -1){
return ArchSimpleExpressionSymbol.of(1);
}
return getDimensionSymbols().get(getWidthIndex());
}
public ArchSimpleExpressionSymbol getChannelsSymbol() {
if (getChannelIndex() == -1){
return ArchSimpleExpressionSymbol.of(1);
}
return getDimensionSymbols().get(getChannelIndex());
}
public Integer getWidth(){
return getWidthSymbol().getIntValue().get();
}
public Integer getHeight(){
return getHeightSymbol().getIntValue().get();
}
public Integer getChannels(){
return getChannelsSymbol().getIntValue().get();
}
public void setDimensionSymbols(List<ArchSimpleExpressionSymbol> dimensions) {
this.dimensions = dimensions;
}
public List<ArchSimpleExpressionSymbol> getDimensionSymbols() {
return dimensions;
}
public void setDimensions(List<Integer> dimensionList){
List<ArchSimpleExpressionSymbol> symbolList = new ArrayList<>(dimensionList.size());
for (int e : dimensionList){
symbolList.add(ArchSimpleExpressionSymbol.of(e));
}
setDimensionSymbols(symbolList);
}
public List<Integer> getDimensions(){
List<Integer> dimensionList = new ArrayList<>(3);
for (ArchSimpleExpressionSymbol exp : getDimensionSymbols()){
dimensionList.add(exp.getIntValue().get());
}
return dimensionList;
}
public Set<VariableSymbol> resolve() {
if (!isResolved()){
if (isResolvable()){
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
dimension.resolveOrError();
}
}
}
return getUnresolvableVariables();
}
public boolean isResolvable(){
boolean isResolvable = true;
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
if (!dimension.isResolvable()){
isResolvable = false;
}
}
return isResolvable;
}
public boolean isResolved(){
boolean isResolved = true;
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
if (!dimension.isResolved()){
isResolved = false;
}
}
return isResolved;
}
public Set<VariableSymbol> getUnresolvableVariables(){
Set<VariableSymbol> unresolvableVariables = new HashSet<>();
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
unresolvableVariables.addAll(dimension.getUnresolvableVariables());
}
return unresolvableVariables;
}
public void checkIfResolvable(Set<VariableSymbol> seenVariables) {
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
dimension.checkIfResolvable(seenVariables);
}
}
@Override
public void setEnclosingScope(MutableScope scope) {
super.setEnclosingScope(scope);
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
dimension.putInScope(scope);
}
}
public void putInScope(Scope scope) {
Collection<Symbol> symbolsInScope = scope.getLocalSymbols().get(getName());
if (symbolsInScope == null || !symbolsInScope.contains(this)) {
scope.getAsMutableScope().add(this);
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
dimension.putInScope(scope);
}
}
}
public ArchTypeSymbol preResolveDeepCopy() {
ArchTypeSymbol copy = new ArchTypeSymbol();
if (getAstNode().isPresent()){
copy.setAstNode(getAstNode().get());
}
copy.setDomain(getDomain());
copy.setWidthIndex(getWidthIndex());
copy.setChannelIndex(getChannelIndex());
copy.setHeightIndex(getHeightIndex());
List<ArchSimpleExpressionSymbol> dimensionCopies = new ArrayList<>();
for (ArchSimpleExpressionSymbol dimension : getDimensionSymbols()){
dimensionCopies.add(dimension.preResolveDeepCopy());
}
copy.setDimensionSymbols(dimensionCopies);
return copy;
}
public static class Builder{
private int height = 1;
private int width = 1;
private int channels = 1;
private ASTElementType domain = null;
public Builder height(int height){
this.height = height;
return this;
}
public Builder width(int width){
this.width = width;
return this;
}
public Builder channels(int channels){
this.channels = channels;
return this;
}
public Builder elementType(ASTElementType domain){
this.domain = domain;
return this;
}
public Builder elementType(String start, String end){
domain = new ASTElementType();
domain.setTElementType("Q(" + start + ":" + end +")");
return this;
}
public ArchTypeSymbol build(){
ArchTypeSymbol sym = new ArchTypeSymbol();
sym.setChannelIndex(0);
sym.setHeightIndex(1);
sym.setWidthIndex(2);
sym.setDimensions(Arrays.asList(channels, height, width));
if (domain == null){
domain = new ASTElementType();
domain.setTElementType(DEFAULT_ELEMENT_TYPE);
}
sym.setDomain(domain);
return sym;
}
}
}
|
/*
* Purpose:-Implementation of Bill Pugh Singleton Pattern
*
* @Author:-Arpana Kumari
* Version:-1.0
* @Since:-7 May, 2018
*/
package com.bridgeit.creationalDesignPatterens;
public class BillPughSingleton {
private BillPughSingleton() {
}
private static class SingletonHelper {
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance() {
return SingletonHelper.INSTANCE;
}
public static void main(String[] args) {
System.out.println("Bill pugh singleton");
System.out.println(SingletonHelper.INSTANCE);
}
}
|
package testAutomation;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
/**
* Created by daljeetsidhu on 12/03/2017.
*/
public class Navigation {
WebDriver driver = BrowserDriver.getCurrentDriver();
@Given("^the user is on the hotel booking website$")
public void open_booking_website() throws Throwable {
BrowserDriver.loadPage(
"http://hotel-test.equalexperts.io/");
Thread.sleep(10000);
}
@When("^the user enters their firstname \"([^\"]*)\"$")
public String the_user_enters_firstname(String fnName) throws Throwable {
driver.findElement(By.id("firstname")).sendKeys(fnName);
return fnName;
}
@And("^the user enters their lastname \"([^\"]*)\"$")
public void the_user_enters_lastname(String lnName) throws Throwable {
driver.findElement(By.id("lastname")).sendKeys(lnName);
}
@And("^the user enters \"([^\"]*)\"$")
public void the_user_enters(String argument) throws Throwable {
driver.findElement(By.id("totalprice")).sendKeys(argument);
}
@And("^the value of the deposit is \"([^\"]*)\"$")
public void the_user_selects(String value) throws Throwable {
Select dropdown = new Select(driver.findElement(By.id("depositpaid")));
dropdown.selectByVisibleText(value);
}
@And("^the checkin date is selected \"([^\"]*)\"$")
public void the_user_selects_checkindate(String date) throws Throwable {
WebElement dates = driver.findElement(By.id("checkin"));
dates.click();
Thread.sleep(5000);
saveDate(date);
}
@And("^the checkout date is selected \"([^\"]*)\"$")
public void the_user_selects_checkoutdate(String date) throws Throwable {
driver.findElement(By.id("checkout")).click();
Thread.sleep(5000);
saveDate(date);
}
@Then("^the user selects Save to book their room$")
public void the_user_selects_save() throws Throwable {
WebElement save = driver.findElement(By.xpath(".//*[@id='form']/div/div[7]/input"));
save.click();
}
@Then("^the user selects Delete$")
public void the_user_selects_delete() throws Throwable {
List<WebElement> Save = driver.findElements(By.xpath("//input[@onclick and @value=\"Delete\"]"));
int elementFound = Save.size();
Thread.sleep(5000);
WebElement lastDelete = Save.get(Save.size()-1);
lastDelete.click();
Thread.sleep(5000);
}
@And("^the user can see all booking details \"([^\"]*)\" and \"([^\"]*)\" and \"([^\"]*)\"$")
public void the_user_view_details(String fName, String lName, String price) throws Throwable {
List<WebElement> bookingValues = driver.findElements(By.xpath("//div[@id='bookings']/div[@id]/div/p"));
int elementFound = bookingValues.size();
if (elementFound == 0) {
System.out.print("No bookings have been found");
}
for (int i = 0; i < bookingValues.size(); i++) {
//System.out.println(bookingValues.get(i).getText());
Thread.sleep(1000);
String value = bookingValues.get(i).getText();
if (value.equals(fName)) {
System.out.println(fName + "value has been found");
} else if (value.equals(lName)) {
System.out.println(lName + "value has been found");
} else if (value.equals(price)) {
System.out.println(price + "value has been found");
}
}
}
@And("^the user can no longer see the booking \"([^\"]*)\"$")
public void user_cannot_view_details(String fnName) throws Throwable {
try {
driver.findElement(By.name("Sue"));
} catch (NoSuchElementException ex){
System.out.print("test passed fName does not appear");
}
}
/* boolean textFound = false;
try {
driver.findElement(By.xpath("/*//*[contains(text(),'dal')]"));
System.out.println("true");
} catch (Exception e){
textFound = false;
System.out.println("fails");
}*/
//}
public boolean isElementPresent(String elementXpath){
int count = driver.findElements(By.xpath(elementXpath)).size();
if(count ==0)
return false;
else return true;
}
public void saveDate(String date){
List<WebElement> dates = driver.findElements(By.xpath(".//table[@class='ui-datepicker-calendar']/tbody/tr/td/a[@class='ui-state-default']"));
for (int i = 0; i < dates.size(); i++) {
// System.out.println(dates.get(i).getText());
if (dates.get(i).getText().equals(date)) {
dates.get(i).click();
}
}
}
}
|
package de.jmda9.core.mproc;
import de.jmda9.core.annotation.MarkerAnnotationType;
import org.junit.Test;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import static de.jmda9.core.mproc.ProcessingUtilities.*;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class JUTProcessingUtilities extends AbstractJUTProcessors
{
/** This class will be processed by {@link TestProcessor} */
@MarkerAnnotationType private class TestTypeProcessed
{
@SuppressWarnings("unused") private int field_int;
@SuppressWarnings("unused") private Integer field_Integer;
@SuppressWarnings("unused") private List<String> field_ListOfStrings;
}
@SupportedAnnotationTypes(value = { "de.jmda9.core.annotation.MarkerAnnotationType" })
@SupportedSourceVersion(value = SourceVersion.RELEASE_11)
private class TestProcessor extends Processor
{
private TypeElement typeElement_TestTypeProcessed;
private VariableElement variableElement_TestTypeProcessed_field_int;
private VariableElement variableElement_TestTypeProcessed_field_Integer;
private VariableElement variableElement_TestTypeProcessed_field_ListOfStrings;
private TypeMirror typeMirror_TestTypeProcessed;
private TypeMirror typeMirror_TestTypeProcessed_field_ListOfStrings;
private TypeMirror typeMirror_Collection;
private TypeMirror typeMirror_List;
private TypeMirror typeMirror_TestProcessor;
private TypeMirror typeMirror_ListOfStrings_OuterType;
@Override protected boolean process()
{
if (isProcessingOver() == false)
{
typeElement_TestTypeProcessed = getTypeElement(TestTypeProcessed.class);
for (Element enclosedElement : typeElement_TestTypeProcessed.getEnclosedElements())
{
String simpleName = enclosedElement.getSimpleName().toString();
VariableElement variableElement = asVariableElement(enclosedElement);
if (variableElement != null)
{
if (simpleName.equals("field_int"))
{
variableElement_TestTypeProcessed_field_int = variableElement;
}
else if (simpleName.equals("field_Integer"))
{
variableElement_TestTypeProcessed_field_Integer = variableElement;
}
else if (simpleName.equals("field_ListOfStrings"))
{
variableElement_TestTypeProcessed_field_ListOfStrings = variableElement;
}
else
{
fail(
"unexpected enclosed element named " + simpleName + ", " +
"type " + variableElement.asType());
}
}
}
typeMirror_TestTypeProcessed = getTypeMirror(TestTypeProcessed.class);
typeMirror_TestProcessor = getTypeMirror(getClass());
typeMirror_Collection = getTypeMirror(Collection.class);
typeMirror_List = getTypeMirror(List.class);
typeMirror_TestTypeProcessed_field_ListOfStrings =
typeOfAsElement(
variableElement_TestTypeProcessed_field_ListOfStrings).asType();
typeMirror_ListOfStrings_OuterType =
ProcessingUtilities.getOuterType(
typeMirror_TestTypeProcessed_field_ListOfStrings);
}
return false;
}
@Override protected Set<Class<? extends Annotation>> getSupposedSupportedAnnotationTypes()
{
return asSet(MarkerAnnotationType.class);
}
}
private TestProcessor testProcessor = new TestProcessor();
@Override protected List<? extends Processor> getProcessors()
{
return asList(testProcessor);
}
@Test
public void asDeclaredTypePrivateClass()
{
DeclaredType declaredType =
asDeclaredType(testProcessor.typeElement_TestTypeProcessed.asType());
assertEquals(
"unexpected declared type",
declaredType.toString(), normalizeBinaryClassName(TestTypeProcessed.class));
}
@Test
public void asDeclaredTypePrimitiveField()
{
DeclaredType declaredType =
asDeclaredType(
testProcessor.variableElement_TestTypeProcessed_field_int.asType());
assertNull("unexpected declared type", declaredType);
}
@Test
public void asDeclaredTypeObjectField()
{
DeclaredType declaredType =
asDeclaredType(
testProcessor.variableElement_TestTypeProcessed_field_Integer.asType());
assertEquals(
"unexpected declared type", Integer.class.getName(), declaredType.toString());
}
@Test
public void asDeclaredTypeListOfObjectsField()
{
DeclaredType declaredType =
asDeclaredType(
testProcessor.variableElement_TestTypeProcessed_field_ListOfStrings.asType());
assertEquals(
"unexpected declared type", "java.util.List<java.lang.String>", declaredType.toString());
}
@Test
public void asTypeElementPrivateClass()
{
TypeElement typeElement =
asTypeElement(testProcessor.typeElement_TestTypeProcessed.asType());
assertEquals(
"unexpected type element",
normalizeBinaryClassName(TestTypeProcessed.class),
typeElement.getQualifiedName().toString());
}
@Test
public void asTypeElementPrimitiveField()
{
TypeElement typeElement =
asTypeElement(testProcessor.variableElement_TestTypeProcessed_field_int.asType());
assertNull("unexpected type element", typeElement);
}
@Test
public void asTypeElementObjectField()
{
TypeElement typeElement =
asTypeElement(testProcessor.variableElement_TestTypeProcessed_field_Integer.asType());
assertEquals(
"unexpected type element",
Integer.class.getName(),
typeElement.getQualifiedName().toString());
}
@Test
public void asTypeElementListOfObjectsField()
{
TypeElement typeElement =
asTypeElement(testProcessor.variableElement_TestTypeProcessed_field_ListOfStrings.asType());
assertEquals(
"unexpected type element",
"java.util.List",
typeElement.getQualifiedName().toString());
}
@Test
public void getFields()
{
TypeElement typeElement = asTypeElement(testProcessor.typeElement_TestTypeProcessed);
List<VariableElement> fields = ProcessingUtilities.getFields(typeElement);
assertEquals("unexpected size of fields", 3, fields.size());
assertTrue(
"missing variable element for int field",
fields.contains(testProcessor.variableElement_TestTypeProcessed_field_int));
assertTrue(
"missing variable element for Integer field",
fields.contains(testProcessor.variableElement_TestTypeProcessed_field_Integer));
assertTrue(
"missing variable element for list of strings field",
fields.contains(testProcessor.variableElement_TestTypeProcessed_field_ListOfStrings));
}
@Test
public void typeOfAsElementTestTypeProcessed()
{
assertEquals(
"unexpected element",
normalizeBinaryClassName(TestTypeProcessed.class),
typeOfAsElement(testProcessor.typeElement_TestTypeProcessed).asType().toString());
}
@Test
public void typeOfAsElementPrimitiveField()
{
assertNull(
"unexpected element",
typeOfAsElement(testProcessor.variableElement_TestTypeProcessed_field_int));
}
@Test
public void typeOfAsElementObjectField()
{
assertEquals(
"unexpected element",
Integer.class.getName(),
typeOfAsElement(testProcessor.variableElement_TestTypeProcessed_field_Integer).asType().toString());
}
@Test
public void typeOfAsElementListOfObjectsField()
{
assertEquals(
"unexpected element",
"java.util.List<E>",
typeOfAsElement(testProcessor.variableElement_TestTypeProcessed_field_ListOfStrings).asType().toString());
}
@Test
public void getPackageOfElement()
{
assertEquals(
"unexpected package name for private class",
getClass().getPackage().getName(),
getPackageOf(testProcessor.typeElement_TestTypeProcessed).asType().toString());
}
@Test
public void typeMirrorCollection()
{
// type mirrors add generic type parameter
String expected = Collection.class.getName() + "<E>";
assertEquals(
"unexpected type mirror for " + Collection.class.getName(),
expected,
testProcessor.typeMirror_Collection.toString());
}
@Test
public void typeMirrorTestProcessor()
{
// type mirrors add generic type parameter
String expected = normalizeBinaryClassName(TestProcessor.class);
assertEquals(
"unexpected type mirror for " + Collection.class.getName(),
expected,
testProcessor.typeMirror_TestProcessor.toString());
}
@Test
public void typeMirrorTestTypeProcessed()
{
// type mirrors add generic type parameter
String expected = normalizeBinaryClassName(TestTypeProcessed.class);
assertEquals(
"unexpected type mirror for " + Collection.class.getName(),
expected,
testProcessor.typeMirror_TestTypeProcessed.toString());
}
@Test
public void isSubtypeStringObject()
{
assertTrue(
"missing sub type relation of string and object",
isSubtype(getTypeMirror(String.class), getTypeMirror(Object.class)));
}
@Test
public void isNotSubtypeListCollection()
{
assertFalse(
"unexpected sub type relation of list and collection (see subtype definition in Java spec)",
isSubtype(
getTypeMirror(List.class), getTypeMirror(Collection.class)));
}
@Test
public void isAssignableTypeStringObject()
{
assertTrue(
"missing assignable type relation of string and object",
isAssignableType(
getTypeMirror(String.class), getTypeMirror(Object.class)));
}
@Test
public void isNotAssignableTypeListCollection()
{
assertFalse(
"unexpected assignable type relation of list and collection (see subtype definition in Java spec)",
isAssignableType(
getTypeMirror(List.class), getTypeMirror(Collection.class)));
}
// private class Base {}
// private class Sub extends Base {}
@Test public void isObjectSupertypeOfString()
{
assertTrue(
"missing super type relation of " + Object.class.getName() + " and " + String.class.getName(),
isSupertype(
getTypeMirror(Object.class), getTypeMirror(String.class)));
}
@Test
public void isSupertypeCollectionList()
{
assertTrue(
"missing super type relation of collection and list",
isSupertype(
testProcessor.typeMirror_Collection, testProcessor.typeMirror_List));
}
@Test public void supertypeDistanceObjectRuntimeThrowableIs1()
{
assertThat(supertypeDistance(getTypeMirror(Object.class), getTypeMirror(Throwable.class)), is(1));
}
@Test public void supertypeDistanceObjectExceptionIs2()
{
assertThat(supertypeDistance(getTypeMirror(Object.class), getTypeMirror(Exception.class)), is(2));
}
@Test public void supertypeDistanceObjectRuntimeExceptionIs3()
{
assertThat(supertypeDistance(getTypeMirror(Object.class), getTypeMirror(RuntimeException.class)), is(3));
}
@Test
public void getOuterType()
{
assertEquals(
testProcessor.typeMirror_ListOfStrings_OuterType.toString(),
testProcessor.typeMirror_List.toString());
}
@Test
public void hasTypeParameters()
{
assertTrue(ProcessingUtilities.hasTypeParameters(testProcessor.typeMirror_Collection));
assertEquals(
// type mirror version
ProcessingUtilities.hasTypeParameters(testProcessor.typeMirror_Collection),
// declared type version
ProcessingUtilities.hasTypeParameters(
asDeclaredType(
testProcessor.variableElement_TestTypeProcessed_field_ListOfStrings.asType())));
}
@Test
public void getBinaryName()
{
TypeElement innerTypeElement = testProcessor.typeElement_TestTypeProcessed;
System.out.println(getBinaryTypeNameOf(innerTypeElement));
}
} |
package Entities;
import Entities.abstractPackage.Entity;
import Entities.abstractPackage.Immune;
import Entities.interfacePackage.Death;
import Entities.interfacePackage.Excretion;
import Entities.interfacePackage.Replication;
import Entities.interfacePackage.Suicide;
import Entities.interfacePackage.Absorption;
/**
*
* Somatic cells can't fight back. All they do is get infected and killed.
* If a soma is infected, it creates new viruses and sends out distress signals (IFN)
* @author Cowteriyaki
* @author K
*/
public class Soma extends Entity implements Replication, Excretion, Suicide, Death {
//감염 여부
private boolean infected;
//감염된 바이러스의 유전정보
private int virusGene;
//바이러스 생산 주기
private double virusInterval;
//주기별 바이러스 생산량
private int virusPerProduction = 3;
//바이러스 생산에 필요한 필드
private double virusCount;
//바이러스에 관한 감염 저항력
private double resistVirus = 0.01;
private double resistCount = 0;
//내구도
private double durability = 60;
//메신저 생산을 위한 필드
private double excretionCount;
//자가복제에 관한 필드
private double replicationCount;
private double replicationInterval = 60;
protected Immune absorbedBy;
protected double absorbedX;
protected double absorbedY;
/**
* make new soma!
* @param posX
* @param posY
*/
public Soma(double posX, double posY) {
super(posX, posY, 0);
size = Math.random() * 2 + 8;
virusInterval = Math.random() * 12 + 6;
replicationInterval = Math.random() * 48 + 24;
}
/**
*
* @return gene given by virus
*/
public int getVirusGene() {
return virusGene;
}
//check if this cell is infected or not
//세포의 감염 여부 확인
public boolean isInfected() {
if(this.infected) return true;
return false;
}
/**
* 공격당하여 감염당함.
*
* @param takeoverTime
* @param delta
* @param gene
*/
public void beInfected(int takeoverTime, double delta, int gene) {
resistCount += takeoverTime * delta;
if(resistCount > resistVirus){
infected = true;
virusGene = gene;
resistCount -= resistVirus;
//감염이 완료되었다면 감염저항력을 다시 올려서 다른 바이러스에 감염될 수 있도록 할 것.
}
}
/**
* Infected cells create new viruses(but with given gene sequence)
* @param delta
*/
public void makeVirus(double delta) {
virusCount += delta;
if(virusCount > virusInterval){
virusCount -= virusInterval;
for(int i = 0; i < virusPerProduction; i++)
entitiesContainer.add(new Virus(currentPosX, currentPosY, virusGene));
}
}
//현재 흡수당한 상태인지 확인.
public boolean isAbsorbed() {
if(absorbedBy == null)
return false;
return true;
}
/**
* Getting absorbed by neutrophils!
* @param neutro
*/
public void setAbsorbed(Neutrophil neutro) {
absorbedX = (currentPosX - neutro.getCurrentPosX()) / 2;
absorbedY = (currentPosY - neutro.getCurrentPosY()) / 2;
absorbedBy = neutro;
}
/**
* Method names sounds weird, but it actually returns the neutrophil that's absorbing this soma.
* @return
*/
public Immune getAbsorbed(){
return absorbedBy;
}
/**
* Death sentence from NK Cells comin
*/
@Override
public void suicide() {
// TODO Auto-generated method stub
entitiesContainer.remove(this);
}
/**
* Exrete IFN if distressed
*/
@Override
public void excrete(double delta) {
// TODO Auto-generated method stub
if(infected && !this.isAbsorbed()){
excretionCount += delta;
if(excretionCount > excretionInterval){
excretionCount -= excretionInterval;
for(int i = 0; i < excretionNumber; i++){
double randomDirection = Math.random() * 2 * Math.PI;
entitiesContainer.add(new IFN(currentPosX + Math.cos(randomDirection) * size,
currentPosY + Math.sin(randomDirection) * size,
randomDirection));
}
}
}
}
/**
* Somas do replicate!
*
*/
@Override
public void replicate(double delta) {
// TODO Auto-generated method stub
replicationCount += delta;
if(replicationCount > replicationInterval) {
replicationCount -= replicationInterval;
double randomX = Math.random() - 0.5;
double randomY = Math.random() - 0.5;
double length = Math.sqrt(randomX * randomX + randomY * randomY);
randomX *= size / length * 2;
randomY *= size / length * 2;
entitiesContainer.add(new Soma
(currentPosX + randomX, currentPosY + randomY));
}
}
/**
* Get damaged.
* Duplicate method?
* @param damage
*/
public void reduceDurability(int damage) {
this.durability -= damage;
if(this.durability < 0){
die();
}
}
/**
* Get damaged.
* @param delta
*/
public void changeDurability(double delta) {
durability -= Absorption.damage * delta * 5;
if(durability < 0){
entitiesContainer.remove(this);
if(absorbedBy instanceof Neutrophil)
((Neutrophil)absorbedBy).reduceCurrentAbsorption();
}
}
public void die() {
entitiesContainer.remove(this);
}
/**
* Somas don't move unless they're being eaten by neutrophils.
*/
@Override
public void move(double delta){
if(isAbsorbed()){
currentPosX = absorbedBy.getCurrentPosX();
currentPosY = absorbedBy.getCurrentPosY();
}//velocity를 delta로 나눈 값으로 이동하면 흡수당했을때 velocity를 정해도 delta
else{
}
}
}
|
package src.Enums;
import java.awt.image.BufferedImage;
/**
* Created with IntelliJ IDEA.
* User: B. Seelbinder
* UID: ga25wul
* Date: 10.07.2014
* Time: 19:39
* *
*/
public enum EFieldType {
INACCESSIBLE( EAccessible.BY_NONE ),
DIRT( EAccessible.BY_WALK_FLY ),
WATER( EAccessible.BY_SWIM_FLY ),
ROCK( EAccessible.BY_FLYING ),
ACCESSIBLE( EAccessible.BY_WALK_SWIM_FLY );
public final EAccessible accessibleBy;
public BufferedImage image = null; // TODO
EFieldType( EAccessible accessibleBy ) {
this.accessibleBy = accessibleBy;
}
@Override
public String toString() {
return super.toString() + ", accessible " + accessibleBy;
}
public void setImage( BufferedImage img ) {
this.image = img;
}
}
|
package com.mideas.rpg.v2.game.classes;
public class SelectScreenPlayer {
private String name;
private int level;
private String classe;
private String race;
private int id;
public SelectScreenPlayer(int id, String name, int level, String classe, String race) {
this.name = name;
this.id = id;
this.level = level;
this.classe = classe;
this.race = race;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public int getLevel() {
return this.level;
}
public String getClasse() {
return this.classe;
}
public String getRace() {
return this.race;
}
}
|
package com.lqs.hrm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lqs.hrm.entity.User;
import com.lqs.hrm.entity.UserExample;
import com.lqs.hrm.mapper.UserMapper;
import com.lqs.hrm.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
/**
* 修改账户密码
* @param userAccount
* @param newUserPwd
* @return
*/
public int update(String userAccount, String newUserPwd) {
UserExample example = new UserExample();
example.createCriteria().andUserAccountEqualTo(userAccount);
User user = new User();
user.setUserPwd(newUserPwd);
return userMapper.updateByExampleSelective(user, example);
}
/**
* 通过用户账户和密码获取用户信息
* @param userAccount
* @param userPwd
* @return
*/
public User get(String userAccount, String userPwd) {
UserExample userExample = new UserExample();
userExample.createCriteria().andUserAccountEqualTo(userAccount).andUserPwdEqualTo(userPwd);
List<User> users = userMapper.selectByExample(userExample);
if (users.size() == 0) {
return null;
}
return users.get(0);
}
/**
* 通过用户账户获取用户信息
* @param userAccount
* @return
*/
public User get(String userAccount) {
UserExample userExample = new UserExample();
userExample.createCriteria().andUserAccountEqualTo(userAccount);
List<User> users = userMapper.selectByExample(userExample);
if (users.size() == 0) {
return null;
}
return users.get(0);
}
/**
* 删除
*/
@Override
public int delete(String userAccount) {
UserExample example = new UserExample();
example.createCriteria().andUserAccountEqualTo(userAccount);
return userMapper.deleteByExample(example);
}
/**
* 添加
*/
@Override
public int add(User user) {
return userMapper.insert(user);
}
@Override
public int update(User user) {
UserExample example = new UserExample();
example.or().andUserAccountEqualTo(user.getUserAccount());
return userMapper.updateByExampleSelective(user, example);
}
@Override
public List<User> listByStatusId(Integer statusId) {
UserExample example = new UserExample();
example.or().andStatusIdEqualTo(statusId).andUserAccountNotEqualTo("1");
return userMapper.selectByExample(example);
}
@Override
public List<User> listByUserAccountStatusId(String userAccount, Integer statusId) {
UserExample example = new UserExample();
example.or().andStatusIdEqualTo(statusId).andUserAccountEqualTo(userAccount).andUserAccountNotEqualTo("1");
return userMapper.selectByExample(example);
}
@Override
public List<User> listByNoExceptSuperManager() {
UserExample example = new UserExample();
example.or().andUserAccountNotEqualTo("1");
return userMapper.selectByExample(example);
}
}
|
package codex.editor;
import codex.command.CommandStatus;
import codex.command.EditorCommand;
import codex.component.button.DialogButton;
import codex.component.button.PushButton;
import codex.component.dialog.Dialog;
import codex.component.render.GeneralRenderer;
import codex.mask.IMask;
import codex.model.ParamModel;
import codex.presentation.EditorPage;
import codex.property.PropertyHolder;
import codex.type.*;
import codex.utils.ImageUtils;
import codex.utils.Language;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.MessageFormat;
import java.util.AbstractMap;
import java.util.LinkedHashMap;
public class MapEditor<K, V> extends AbstractEditor<Map<K, V>, java.util.Map<K, V>> {
private static final ImageIcon EDIT_ICON = ImageUtils.resize(ImageUtils.getByPath("/images/edit.png"), 18, 18);
private static final ImageIcon VIEW_ICON = ImageUtils.resize(ImageUtils.getByPath("/images/view.png"), 18, 18);
private static final ImageIcon ADD_ICON = ImageUtils.resize(ImageUtils.getByPath("/images/plus.png"), 26, 26);
private static final ImageIcon DEL_ICON = ImageUtils.resize(ImageUtils.getByPath("/images/minus.png"), 26, 26);
private static final ImageIcon CLEAR_ICON = ImageUtils.resize(ImageUtils.getByPath("/images/remove.png"), 26, 26);
private JTextField textField;
private EditMode mode = EditMode.ModifyAllowed;
private java.util.Map<K, V> internalValue;
public MapEditor(PropertyHolder<Map<K, V>, java.util.Map<K, V>> propHolder) {
super(propHolder);
TableEditor defCommand = new TableEditor();
addCommand(defCommand);
textField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
if (event.getClickCount() == 2) {
defCommand.execute(propHolder);
}
}
});
}
public void setMode(EditMode mode) {
this.mode = mode;
}
@Override
public Box createEditor() {
internalValue = new LinkedHashMap<>();
textField = new JTextField();
textField.setFont(FONT_VALUE);
textField.setBorder(new EmptyBorder(0, 3, 0, 3));
textField.setEditable(false);
textField.setBackground(Color.WHITE);
textField.addFocusListener(this);
PlaceHolder placeHolder = new PlaceHolder(IEditor.NOT_DEFINED, textField, PlaceHolder.Show.ALWAYS);
placeHolder.setBorder(textField.getBorder());
placeHolder.changeAlpha(100);
Box container = new Box(BoxLayout.X_AXIS);
container.setBackground(textField.getBackground());
container.add(textField);
return container;
}
@Override
public void setValue(java.util.Map<K, V> value) {
internalValue.clear();
internalValue.putAll(value);
if (internalValue.isEmpty()) {
textField.setText("");
} else {
textField.setText(MessageFormat.format(Language.get(Map.class, "defined"), internalValue.size()));
}
}
@Override
public void setEditable(boolean editable) {
super.setEditable(editable);
textField.setFocusable(false);
textField.setForeground(editable && !propHolder.isInherited() ? Color.decode("#3399FF") : COLOR_DISABLED);
textField.setOpaque(editable && !propHolder.isInherited());
}
private java.util.Map.Entry<
PropertyHolder<ISerializableType<K, ? extends IMask<K>>, K>,
PropertyHolder<ISerializableType<V, ? extends IMask<V>>, V>
> createHolderEntry() {
Map<K, V> map = propHolder.getOwnPropValue();
java.util.Map.Entry<? extends ISerializableType<K, ? extends IMask<K>>, ? extends ISerializableType<V, ? extends IMask<V>>> entry = map.getEntry();
return new AbstractMap.SimpleEntry<>(
new PropertyHolder<>("key", entry.getKey(), true),
new PropertyHolder<>("val", entry.getValue(), true)
);
}
public enum EditMode {
ModifyPermitted, ModifyAllowed
}
private class TableEditor extends EditorCommand<Map<K, V>, java.util.Map<K, V>> {
TableEditor() {
super(EDIT_ICON, Language.get(MapEditor.class, "title"));
activator = holder -> new CommandStatus(
true,
MapEditor.this.isEditable() && !propHolder.isInherited() ? EDIT_ICON : VIEW_ICON
);
}
@Override
public void execute(PropertyHolder context) {
Class kClass = ((Map) propHolder.getPropValue()).getKeyClass();
Class vClass = ((Map) propHolder.getPropValue()).getValClass();
DefaultTableModel tableModel = new DefaultTableModel(ArrStr.parse(propHolder.getPlaceholder()).toArray(), 0) {
@Override
public Class<?> getColumnClass(int columnIndex) {
Class c = columnIndex == 0 ? kClass : vClass;
return c == Bool.class ? Bool.class : IComplexType.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1 && MapEditor.this.isEditable() && !propHolder.isInherited();
}
};
JTable table = new JTable(tableModel);
table.setRowHeight((IEditor.FONT_VALUE.getSize() * 2));
table.setShowVerticalLines(false);
table.setIntercellSpacing(new Dimension(0,0));
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
internalValue.entrySet().stream().forEachOrdered(entry -> {
Object[] row = new Object[] {entry.getKey(), entry.getValue()};
((DefaultTableModel) table.getModel()).addRow(row);
});
GeneralRenderer renderer = new GeneralRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(
table,
ISerializableType.class.isAssignableFrom(value.getClass()) ?
((ISerializableType) value).getValue() : value,
isSelected,
hasFocus,
row,
column
);
if (ISerializableType.class.isAssignableFrom(value.getClass())) {
if (((ISerializableType) value).isEmpty()) {
c.setForeground(Color.decode("#999999"));
}
}
return c;
}
};
table.setDefaultRenderer(Bool.class, renderer);
table.setDefaultRenderer(IComplexType.class, renderer);
table.getTableHeader().setDefaultRenderer(renderer);
table.getColumnModel().getColumn(1).setCellEditor(new CellEditor());
final JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().setBackground(Color.WHITE);
scrollPane.setViewportView(table);
scrollPane.setBorder(new CompoundBorder(
new EmptyBorder(5, 5, 5, 5),
new MatteBorder(1, 1, 1, 1, Color.GRAY)
));
JPanel content = new JPanel(new BorderLayout());
content.add(scrollPane, BorderLayout.CENTER);
if (mode.equals(EditMode.ModifyAllowed)) {
PushButton clean = new PushButton(CLEAR_ICON, null);
clean.setEnabled(MapEditor.this.isEditable() && !propHolder.isInherited() && internalValue.size() > 0);
clean.addActionListener((event) -> {
internalValue.clear();
while (tableModel.getRowCount() > 0) {
tableModel.removeRow(0);
}
table.getSelectionModel().clearSelection();
});
table.getModel().addTableModelListener(event -> {
if (event.getType() == TableModelEvent.INSERT || event.getType() == TableModelEvent.DELETE) {
clean.setEnabled(table.getRowCount() > 0);
}
});
PushButton insert = new PushButton(ADD_ICON, null);
insert.setEnabled(MapEditor.this.isEditable() && !propHolder.isInherited());
insert.addActionListener((e) -> {
java.util.Map.Entry<
PropertyHolder<ISerializableType<K, ? extends IMask<K>>, K>,
PropertyHolder<ISerializableType<V, ? extends IMask<V>>, V>
> entry = createHolderEntry();
ParamModel model = new ParamModel();
model.addProperty(entry.getKey());
model.addProperty(entry.getValue());
DialogButton btnConfirm = codex.component.dialog.Dialog.Default.BTN_OK.newInstance(Language.get(MapEditor.class, "confirm@title"));
DialogButton btnDecline = codex.component.dialog.Dialog.Default.BTN_CANCEL.newInstance();
new codex.component.dialog.Dialog(
FocusManager.getCurrentManager().getActiveWindow(),
ADD_ICON,
Language.get(MapEditor.class, "add@title"),
new EditorPage(model),
event -> {
if (event.getID() == codex.component.dialog.Dialog.OK) {
tableModel.addRow(new Object[] {
entry.getKey().getPropValue(),
entry.getValue().getPropValue()
});
internalValue.put(
entry.getKey().getPropValue().getValue(),
entry.getValue().getPropValue().getValue()
);
}
},
btnConfirm,
btnDecline
) {
@Override
public Dimension getPreferredSize() {
return new Dimension(550, super.getPreferredSize().height);
}
}.setVisible(true);
});
PushButton delete = new PushButton(DEL_ICON, null);
delete.setEnabled(false);
delete.addActionListener((event) -> {
int rowIdx = table.getSelectedRow();
internalValue.remove(table.getModel().getValueAt(rowIdx, 0));
tableModel.removeRow(rowIdx);
if (rowIdx < tableModel.getRowCount()) {
table.getSelectionModel().setSelectionInterval(rowIdx, rowIdx);
} else if (rowIdx == tableModel.getRowCount()) {
table.getSelectionModel().setSelectionInterval(rowIdx - 1, rowIdx - 1);
} else {
table.getSelectionModel().clearSelection();
}
});
table.getSelectionModel().addListSelectionListener(event -> {
delete.setEnabled(table.getSelectedRow() >= 0);
});
Box controls = new Box(BoxLayout.Y_AXIS);
controls.setBorder(new EmptyBorder(5, 0, 0, 5));
controls.add(insert);
controls.add(Box.createVerticalStrut(10));
controls.add(delete);
controls.add(Box.createVerticalStrut(10));
controls.add(clean);
content.add(controls, BorderLayout.EAST);
}
DialogButton confirmBtn = codex.component.dialog.Dialog.Default.BTN_OK.newInstance();
confirmBtn.setEnabled(isEditable() && !propHolder.isInherited());
DialogButton declineBtn = codex.component.dialog.Dialog.Default.BTN_CANCEL.newInstance();
Dialog dialog = new codex.component.dialog.Dialog(
SwingUtilities.getWindowAncestor(editor),
MapEditor.this.isEditable() && !propHolder.isInherited() ? EDIT_ICON : VIEW_ICON,
propHolder.getTitle(),
content,
event -> {
if (event.getID() == Dialog.OK) {
propHolder.setValue(new LinkedHashMap<>(internalValue));
} else {
setValue(new LinkedHashMap<>(propHolder.getPropValue().getValue()));
}
},
confirmBtn,
declineBtn
);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
}
private class CellEditor extends AbstractCellEditor implements TableCellEditor {
private java.util.Map.Entry<? extends ISerializableType<K, ? extends IMask<K>>, ? extends ISerializableType<V, ? extends IMask<V>>> entry;
private IEditor<? extends ISerializableType<V, ? extends IMask<V>>, V> editor;
CellEditor() {}
@Override
@SuppressWarnings("unchecked")
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
entry = propHolder.getPropValue().getEntry();
entry.getKey().setValue((K) table.getValueAt(row, 0));
entry.getValue().setValue((V) value);
PropertyHolder propertyHolder = new PropertyHolder<>(
"row#"+row,
entry.getValue(),
true
);
editor = entry.getValue().editorFactory().newInstance(propertyHolder);
EventQueue.invokeLater(() -> editor.getFocusTarget().requestFocus());
if (entry.getValue().getClass() == Bool.class) {
JComponent renderedComp = (JComponent) table.getCellRenderer(row, column).getTableCellRendererComponent(table, value, true, true, row, column);
JPanel container = new JPanel();
container.setOpaque(true);
container.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 2));
container.setBackground(renderedComp.getBackground());
container.setBorder(renderedComp.getBorder());
container.add(editor.getEditor());
return container;
} else {
return editor.getEditor();
}
}
@Override
public Object getCellEditorValue() {
editor.stopEditing();
V value = editor.getValue();
internalValue.put(entry.getKey().getValue(), entry.getValue().getValue());
return value;
}
}
}
|
package by.ez.smm.service;
import java.util.List;
public interface AbstractServiceImpl<ENTITY, ID, FILTER>
{
public void save(ENTITY entity);
public List<ENTITY> find(FILTER filter);
public ENTITY getById(ID id);
}
|
package com.example.riteshkumarsingh.mvpdaggerrxtemplate.data.source;
/**
* Created by riteshkumarsingh on 23/08/17.
*/
public interface DataSource {
}
|
package pattern.command;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class CommandProxyHandler implements InvocationHandler {
private Liqht light;
public CommandProxyHandler(Liqht light) {
this.light = light;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("PRE COMMAND!!");
return method.invoke(light, args);
}
}
|
package com.muse.build.utils;
public interface NacosSend {
boolean send(String... configRows);
void send();
}
|
package kodlama.io.hrms.business.abstracts;
import java.util.List;
import kodlama.io.hrms.core.utilities.results.DataResult;
import kodlama.io.hrms.core.utilities.results.Result;
import kodlama.io.hrms.entities.concretes.School;
public interface SchoolService {
DataResult<List<School>> getAll();
// DataResult<School> getById(int id);
// DataResult<List<School>> getAllByCandidateIdOrderByGraduationDateDesc(int id);
// DataResult<List<School>> getAllByCandidateId(int id);
Result add(School school);
}
|
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.Callable;
public class BrowserInvocations {
public static void main(String[] args) {
for (int i = 1; i < 4; i++) {
Chrome();
Firefox();
}
int j = 1;
while(j<4) {
Firefox();
Chrome();
j++;
}
}
//this method will invoke the chrome browser
// Created By : me Date ......
//Last Modified By: x
public static void Chrome(){
System.setProperty("webdriver.chrome.driver","/Users/vahit.peker/Desktop/chromedriver");
WebDriver driver= new ChromeDriver();
driver.get("http://syscanner.com");
}
public static void Firefox(){
System.setProperty("webdriver.gecko.driver","/Users/vahit.peker/Desktop/geckodriver");
WebDriver driver= new FirefoxDriver();
driver.get("http://syscanner.com");
}
}
|
package fr.tenebrae.MMOCore.Entities;
import net.minecraft.server.v1_9_R1.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import fr.tenebrae.MMOCore.Characters.Character;
public interface IClickable {
public void onInteract(Character clicker, Item nomItem, double distance);
public Inventory openAvailableQuestGui(Player player);
public Inventory openFinishedQuestGui(Player player);
public Inventory openPendingQuestGui(Player player);
}
|
package test.mypac;
public class Zoo {
//내부 클래스 type 을 리턴하는 메소드
public Monkey getMonkey() {
return new Monkey();
}
//내부 클래스 type 을 리턴하는 메소드
public Cat getCat() {
return new Cat();
}
//내부 클래스
public class Monkey{
public void say() {
System.out.println("안녕! 나는 원숭이야~");
}
}
//내부 클래스
public class Cat{
public void say() {
System.out.println("안녕! 나는 고양이야~");
}
}
}
|
import java.util.HashMap;
import java.util.Scanner;
public class Random35 {
public static int findMinBadness(int[] num, String[] name) {
int bad = 0;
int n = num.length;
HashMap<Integer, String> rank = new HashMap<Integer, String>();
for(int i=0;i<n;i++) {
if(rank.get(num[i])==null)
rank.put(num[i],name[i]);
else {
while(rank.containsKey(num[i])) {
num[i]++;
bad++;
}
rank.put(num[i], name[i]);
}
}
return bad;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter");
int t = scanner.nextInt();
while(t-->0) {
long n = scanner.nextLong();
scanner.nextLine();
String[] name = new String[(int) n];
int[] num = new int[(int) n];
for(int i=0;i<n;i++) {
name[i] = scanner.nextLine();
num[i] = scanner.nextInt();
scanner.nextLine();
}
System.out.println(findMinBadness(num,name));
}
// Complexity can be lessened? O(t*n*n*bad)
scanner.close();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.proxy;
import java.io.Serializable;
/**
* <p>Interface for all OpenWebBeans {@link jakarta.enterprise.context.NormalScope} Proxies.
* A normalscoping proxy just resolves the underlying Contextual Instance
* and directly invokes the target method onto it.</p>
*
* <p>Each <code>OwbNormalScopeProxy</code> contains a {@link jakarta.inject.Provider}
* which returns the current Contextual Instance.</p>
*
* <p>This interface extends Serializable because every NormalScoped bean proxy must
* be Serializable!</p>
*/
public interface OwbNormalScopeProxy extends Serializable
{
}
|
package br.com.formacao.java.composto;
/**
* Classe que representa o teste de Saque com saldo negativo
*
* @author Guilherme Vilela
* @version 0.1
*/
public class TesteSacaNegativo {
/**
*
* @param args
*/
public static void main(String[] args) {
Conta conta = new Conta();
conta.deposita(100);
System.out.println(conta.saca(101));
conta.saca(101);
System.out.println(conta.getSaldo());
}
} |
package test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import game.Dado;
public class DadoTest {
@Test
public void test() {
assertEquals(1, Dado.lanzarDado(1));
}
}
|
package ec.edu.uce.modelo.entidades;
import android.graphics.Bitmap;
import android.media.Image;
import java.io.Serializable;
import java.util.Date;
public class Vehiculo implements Serializable {
private String placa;
private String marca;
private Date fechaFabricacion;
private Double costo;
private Boolean matriculado;
private String color;
private byte [] imagen;
private String tipo;
private Bitmap fotoAux;
public Vehiculo() {
}
public Vehiculo(String placa, String marca, Date fechaFabricacion, Double costo, Boolean matriculado, String color, byte[] imagen, String tipo) {
this.placa = placa;
this.marca = marca;
this.fechaFabricacion = fechaFabricacion;
this.costo = costo;
this.matriculado = matriculado;
this.color = color;
this.imagen = imagen;
this.tipo = tipo;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public Date getFechaFabricacion() {
return fechaFabricacion;
}
public void setFechaFabricacion(Date fechaFabricacion) {
this.fechaFabricacion = fechaFabricacion;
}
public Double getCosto() {
return costo;
}
public void setCosto(Double costo) {
this.costo = costo;
}
public Boolean getMatriculado() {
return matriculado;
}
public void setMatriculado(Boolean matriculado) {
this.matriculado = matriculado;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public byte[] getImagen() {
return imagen;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public Bitmap getFotoAux() {
return fotoAux;
}
public void setFotoAux(Bitmap fotoAux) {
this.fotoAux = fotoAux;
}
}
|
package com.nextnovity;
public class Pyramid {
static char a[]={'a','b','i','b','a'};
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i<=j) {
System.out.print(" ");
}
}
for (int j = 0; j < 5; j++) {
if( j==0 || j==i){
System.out.print(a[i]);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i<=j) {
System.out.print(" ");
}
}
for (int j = 0; j < 5; j++) {
if( j==0 || j+i==5){
System.out.print(a[i]);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
|
/*
* 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 AAPA.Controllers;
import AAPA.Entity.Alarm;
import AAPA.Entity.Beneficiary;
import AAPA.Entity.Childrens;
import AAPA.Entity.Compagnon;
import AAPA.Entity.Donations;
import AAPA.Entity.Files;
import AAPA.Entity.Repo.AlarmRepo;
import AAPA.Entity.Repo.ArticlesRepo;
import AAPA.Entity.Repo.BeneficiaryRepo;
import AAPA.Entity.Repo.ChildrensRepo;
import AAPA.Entity.Repo.CompagnonRepo;
import AAPA.Entity.Repo.DonationsRepo;
import AAPA.Entity.Repo.FilesRepo;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author amine
*/
@Controller
public class Gestion {
@Inject FilesRepo fs;
@Inject BeneficiaryRepo bs;
@Inject CompagnonRepo cs;
@Inject ChildrensRepo chs;
@Inject DonationsRepo ds;
@Inject ArticlesRepo as;
@Inject AlarmRepo als;
@RequestMapping("/Gestion")
public String Gestion(Model m) {
List <Alarm> alarms= als.findAll();
List <Alarm> alarm= new ArrayList<>();
for(int i=0;i<alarms.size();i++){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
int dif= (Integer.parseInt(dateFormat.format(date).toString().substring(0, 4))*365+
Integer.parseInt(dateFormat.format(date).toString().substring(5, 7))*30+
Integer.parseInt(dateFormat.format(date).toString().substring(8, 10)))-
(Integer.parseInt(alarms.get(i).getdateDernierTraitement().substring(0, 4))*365+
Integer.parseInt(alarms.get(i).getdateDernierTraitement().substring(5, 7))*30+
Integer.parseInt(alarms.get(i).getdateDernierTraitement().substring(8, 10)));
if(alarms.get(i).getperiodicite().equals("Quotidienne")){
if(dif>0){ alarm.add(alarms.get(i));}
}else{
if(alarms.get(i).getperiodicite().equals("Hebdomadaire")){
if(dif>=7){ alarm.add(alarms.get(i));}
}else{
if(alarms.get(i).getperiodicite().equals("Mensuelle")){
if(dif>=30){ alarm.add(alarms.get(i));}
}}}}
m.addAttribute("alarms",alarm);
return "indexGPA";
}
}
|
package com.duanxr.yith.midium;
import com.duanxr.yith.define.treeNode.TreeNode;
/**
* @author 段然 2021/3/11
*/
public class ShuDeZiJieGouLcof {
/**
* English description is not available for the problem.
*
* 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
*
* B是A的子结构, 即 A中有出现和B相同的结构和节点值。
*
* 例如:
* 给定的树 A:
*
* 3
* / \
* 4 5
* / \
* 1 2
* 给定的树 B:
*
* 4
* /
* 1
* 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
*
* 示例 1:
*
* 输入:A = [1,2,3], B = [3,1]
* 输出:false
* 示例 2:
*
* 输入:A = [3,4,5,1,2], B = [4,1]
* 输出:true
* 限制:
*
* 0 <= 节点个数 <= 10000
*
*/
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (A == null || B == null) {
return false;
}
return recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
private boolean recur(TreeNode a, TreeNode b) {
if (a == null && b != null) {
return false;
} else if (b == null) {
return true;
}
return a.val == b.val && recur(a.left, b.left) && recur(a.right, b.right);
}
}
}
|
// linked list with linear search
// TODO: using binary tree
package bankQueue;
class Data {
public String key;
public double buyRate;
public double sellRate;
public double stock;
public Data next;
public Data(String key, double buyRate, double sellRate) {
this.key = key;
this.buyRate = buyRate;
this.sellRate = sellRate;
stock = 0;
next = null;
}
}
public class MyRList {
private Data first;
private int size;
public MyRList() {
first = null;
size = 0;
}
public boolean isEmpty() {
return (first == null);
}
public int size() {
return size;
}
public void add(Data data) {
if (isEmpty()) {
first = data;
} else {
data.next = first;
first = data;
}
size++;
}
public Data search(String key) {
Data temp = first;
Data ans = null;
while ((!temp.key.equalsIgnoreCase(key)) && temp.next != null) {
temp = temp.next;
}
if (temp.key.equalsIgnoreCase(key)) {
ans = temp;
}
return ans;
}
public void setStock(String key, double stock) {
Data temp = search(key);
if (temp != null) {
temp.stock = stock;
}
}
public double getSellRate(String key) {
Data temp = search(key);
if (temp != null) {
return temp.sellRate;
} else {
return -1;
}
}
public double getBuyRate(String key) {
Data temp = search(key);
if (temp != null) {
return temp.buyRate;
} else {
return -1;
}
}
public double getStock(String key) {
Data temp = search(key);
if (temp != null) {
return temp.stock;
} else {
return -1;
}
}
public String toString() {
String ans = "STORED:\n<Currency> <Buy> <Sell> <Cash on Bank>\n";
if (!isEmpty()) {
Data temp = first;
while (temp != null) {
ans += temp.key + " ";
ans += String.format("%.2f", temp.buyRate) + " ";
ans += String.format("%.2f", temp.sellRate) + " ";
ans += String.format("%.2f", temp.stock) + "\n";
temp = temp.next;
}
}
return ans;
}
public String stored() {
String ans = "STORED:\n<Currency> <Cash on Bank>\n";
if (!isEmpty()) {
Data temp = first;
while (temp != null) {
ans += temp.key + " ";
ans += String.format("%.2f", temp.stock) + "\n";
temp = temp.next;
}
}
return ans;
}
} |
package com.ehootu.sys.service;
import com.ehootu.sys.entity.RedPacketSendLogEntity;
import java.util.List;
import java.util.Map;
/**
* 红包发送记录
*
* @author zhangyong
* @email zhangyong@ehootu.com
* @date 2018-03-05 14:40:02
*/
public interface RedPacketSendLogService {
RedPacketSendLogEntity queryObject(Integer id);
List<RedPacketSendLogEntity> queryList(Map<String, Object> map);
int queryTotal(Map<String, Object> map);
void save(RedPacketSendLogEntity redPacketSendLog);
void update(RedPacketSendLogEntity redPacketSendLog);
void delete(Integer id);
void deleteBatch(Integer[] ids);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.