text
stringlengths
10
2.72M
package projetZoo; public class Tortue extends Marin { public Tortue(String n, int age) { super(n, age); // TODO Auto-generated constructor stub } public void mange() { System.out.print( " mange de la salade \n"); } }
package kr.co.study.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotEmpty; @Setter @Getter @Validated @Component @ConfigurationProperties("spring.datasource") public class DatabaseProperties { @NotEmpty private String url; private String driverClassName; }
package com.otherhshe.niceread.presenter; import com.otherhshe.niceread.api.SplashService; import com.otherhshe.niceread.model.SplashData; import com.otherhshe.niceread.net.ApiService; import com.otherhshe.niceread.rx.RxManager; import com.otherhshe.niceread.rx.RxSubscriber; import com.otherhshe.niceread.ui.view.SplashView; /** * Author: Othershe * Time: 2016/8/11 11:26 */ public class SplashPresenter extends BasePresenter<SplashView> { public SplashPresenter(SplashView view) { super(view); } public void getSplashPic() { mSubscription = RxManager.getInstance() .doSubscribe(ApiService.getInstance().initService(SplashService.class).getSplashPic(), new RxSubscriber<SplashData>(false) { @Override protected void _onNext(SplashData data) { mView.onSuccess(data); } @Override protected void _onError() { mView.onError(); } }); } }
package com.example.maomao.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); TextView view = (TextView) findViewById(R.id.main_tv_text); view.setOnClickListener(v -> { Toast.makeText(this,"",Toast.LENGTH_LONG).show();}); } public void onTestClick(View view){ Toast.makeText(getBaseContext(),"sdsds",Toast.LENGTH_LONG).show(); } }
package com.moonlike.hl.account.domain; /** * Created by hl on 2015-9-8. */ public class Tb_pwd { private String password;//用户密码 public Tb_pwd() { } public Tb_pwd(String password) { this.password = password; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
/* * This is a sample project of a home-connected clock */ package com.iglu.example.clock; import com.iglu.networking.IGNetworkingProtocol; import com.iglu.toolkit.elements.IGPeerElement; import com.iglu.toolkit.elements.generic.IGGenericClockElement; import com.iglu.toolkit.ticket.IGPeerInformationTicket; import com.iglu.utilities.IGCommandLine; import com.iglu.utilities.IGLogger; /** * The ClockElment example class is a sample of a clock that is connected * within the Iglu home. */ public class ClockElement extends IGGenericClockElement { private ClockWindow window = null; /** * Element entry point * @param args command line arguments */ public static void main(String args[]) { // Create a new ClockElement object ClockElement clock = new ClockElement(); // Start the clock on the home clock.start(); } /** * Called when this element has been added to the home successfully. */ @Override public void beganConnection() { // Loop for setting the clock new Thread(new Runnable() { @Override public void run() { while(true) { ClockElement.this.askToSetAttribute(); // ClockElement.this.askToInquirePeer(); } } }).start(); // Create the new user interface // this.window = new ClockWindow(this); } /** * Called when this element receives a command from the peer * @param senderIdentifier the identifier of the sender of the command * @param command the command received from the peer * @return the response to the sending peer */ @Override public String receivedCommandFromPeer(String senderIdentifier, String command) { // If the command is null if(command == null) { return null; } // Split the command String parts[] = command.split(IGNetworkingProtocol.SEPARATOR); IGLogger.log(command); // If the first part is to set the time if(parts[0].equals("settime")) { // Get the other parts if(parts.length > 1) { // Set the hour this.setHours(Integer.parseInt(parts[1])); if(parts.length > 2) { // Set the minute this.setMinutes(Integer.parseInt(parts[2])); if(parts.length > 3) { // Set the second this.setSeconds(Integer.parseInt(parts[3])); } } } } // Return null in other cases return null; } private void askToSetAttribute() { // Get the parts of the command String key = IGCommandLine.prompt("Key: "); String value = IGCommandLine.prompt("Value: "); this.setAttribute(key, value); } private void askToInquirePeer() { // Get the parts of the command String peer = IGCommandLine.prompt("Peer: "); // Create a ticket IGPeerInformationTicket ticket = new IGPeerInformationTicket(peer) { @Override public void receivedPeer(IGPeerElement peer) { IGLogger.log("HEY"); for(String key : peer.getAllAttributeKeys()) { IGLogger.log("\t" + key + " : " + peer.getAttribute(key)); } } }; // Send the command this.sendTicket(ticket); } }
package com.opentangerine.genotype.yml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; /** * @author Grzegorz Gajos */ public final class ConfigSass { public static final String sass_dir = "assets/css/_sass"; public static final String style = ":compressed"; }
package com.github.MrDuoDuo2.crafting; import com.github.MrDuoDuo2.block.BlockLoader; import com.github.MrDuoDuo2.common.ConfigLoader; import com.github.MrDuoDuo2.item.ItemLoader; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.IFuelHandler; import net.minecraftforge.fml.common.registry.GameRegistry; public class CraftingLoader { public CraftingLoader() { registerRecipe(); registerSmelting(); registerFuel(); } public static void registerRecipe() { GameRegistry.addShapedRecipe(new ItemStack(ItemLoader.goldenEgg), new Object[] { "###","#*#","###",'#',Items.gold_ingot,'*',Items.egg }); } public static void registerSmelting() { GameRegistry.addSmelting(BlockLoader.grassBlock, new ItemStack(Items.beef), 0.8f); } public static void registerFuel() { GameRegistry.registerFuelHandler(new IFuelHandler() { @Override public int getBurnTime(ItemStack fuel) { // TODO 自动生成的方法存根 return Items.diamond != fuel.getItem() ? 0:Math.max(0, ConfigLoader.diamondBurnTime) * 20; } }); } }
package algorithms.chap2; import java.util.stream.IntStream; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.Stopwatch; public class InsertionSort { public static void sort(Comparable[] a) { int length = a.length; // text book impl // for (int i = 0; i < length; i++) { // for (int j = i; j > 0 && less(a[j], a[j-1]); j--) { // exchange(a, j, j-1); // } // } // my impl, same as text book one // for (int i = 0; i < length - 1; i++) { // for (int j = i+1; j > 0; j--) { // if (less(a[j], a[j-1])) { // exchange(a, j, j-1); // }else { // break; // } // } // } // minimize write operations than text book implementation for (int i = 0; i < length-1; i++) { int j = i + 1; int k = i + 1; while (j > 0) { if (less(a[k], a[j - 1])) { j--; if (j==0) { insert(a, a[k], j, k); } } else { insert(a, a[k], j, k); break; } } } } private static void insert(Comparable[] a, Comparable value, int index, int origin) { for (int i = origin; i >= index+1; i--) { a[i] = a[i - 1]; } a[index] = value; } private static boolean less(Comparable a, Comparable b) { return a.compareTo(b) < 0; } private static void exchange(Comparable[] a, int i, int j) { Comparable temp = a[i]; a[i] = a[j]; a[j] = temp; } public static boolean isSorted(Comparable[] a) { for (int i = 0; i < a.length - 1; i++) { if (less(a[i + 1], a[i])) { return false; } } return true; } public static void print(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.print(a[i] + " "); } StdOut.println(); } public static void main(String[] args) { // int[] arr = {1, 2, 43, 434, 55, 21, 3, 31}; // int[] arr = {3, 2, 1}; // String[] strs = {"alan", "jessica", "David", "Mary", "Gabi"}; In in = new In("/Users/sijin.cao/git/princeton-algo/data/14Kints.txt"); int[] arr = in.readAllInts(); // JDK8 box Integer[] boxedInts = IntStream.of(arr).boxed().toArray(Integer[]::new); // insert(boxedInts, 31, 2, 7); Stopwatch timer = new Stopwatch(); sort(boxedInts); StdOut.print("time used: " + timer.elapsedTime()); StdOut.println(); assert (isSorted(boxedInts)); print(boxedInts); } }
package com.lesports.albatross.adapter.learn; import com.lesports.albatross.entity.learn.TeachingEntity; /** * Created by Andye on 2016/5/23. */ public class LearnTwoItemWarpper { public TeachingEntity itemLeft; public TeachingEntity itemRight; public LearnTwoItemWarpper(TeachingEntity itemLeft, TeachingEntity itemRigth) { this.itemLeft = itemLeft; this.itemRight = itemRigth; } }
/** * */ package com.application.beans; import android.os.Parcel; import android.os.Parcelable; /** * @author Vikalp Patel(VikalpPatelCE) * */ public class Theme implements Parcelable { private String mColor; private boolean isSelected; public Theme() { super(); // TODO Auto-generated constructor stub } public Theme(String mColor, boolean isSelected) { super(); this.mColor = mColor; this.isSelected = isSelected; } public String getmColor() { return mColor; } public void setmColor(String mColor) { this.mColor = mColor; } public boolean isSelected() { return isSelected; } public void setSelected(boolean isSelected) { this.isSelected = isSelected; } protected Theme(Parcel in) { mColor = in.readString(); isSelected = in.readByte() != 0x00; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mColor); dest.writeByte((byte) (isSelected ? 0x01 : 0x00)); } @SuppressWarnings("unused") public static final Parcelable.Creator<Theme> CREATOR = new Parcelable.Creator<Theme>() { @Override public Theme createFromParcel(Parcel in) { return new Theme(in); } @Override public Theme[] newArray(int size) { return new Theme[size]; } }; }
package com.winksoft.yzsmk.idylpos.idylpos; import android.annotation.SuppressLint; import android.app.Dialog; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.winksoft.idcardcer.bean.IdCardBean; import com.winksoft.idcardcer.callback.IReadIdCardCallBack; import com.winksoft.idcardcer.callback.ResultCode; import com.winksoft.idcardcer.main.IDCardAuthTask; import com.winksoft.idcardcer.util.ByteUtils; import com.winksoft.yzsmk.idylpos.idylpos.homekey.HomeWatcher; import com.winksoft.yzsmk.idylpos.idylpos.homekey.OnHomePressedListener; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements IReadIdCardCallBack { @BindView(R.id.tv_name) TextView tvName; @BindView(R.id.iv_photo) ImageView ivPhoto; @BindView(R.id.tv_sex) TextView tvSex; @BindView(R.id.tv_ehtnic) TextView tvEhtnic; @BindView(R.id.tv_address) TextView tvAddress; @BindView(R.id.tv_number) TextView tvNumber; @BindView(R.id.tv_signed) TextView tvSigned; @BindView(R.id.tv_validate) TextView tvValidate; @BindView(R.id.tv_birthday) TextView tvBirthday; @BindView(R.id.t_ping) TextView tPing; @BindView(R.id.t_cer) TextView tCer; @BindView(R.id.t_comm) TextView tComm; @BindView(R.id.t_time) TextView tTime; @BindView(R.id.t_read_fail) TextView tReadFail; @BindView(R.id.t_cer_fail) TextView tCerFail; @BindView(R.id.t_comm_fail) TextView tCommFail; @BindView(R.id.t_sucess) TextView tSucess; @BindView(R.id.t_ip_port) TextView tIpPort; @BindView(R.id._conn_state) TextView tConnState; @BindView(R.id.t_read_state) TextView tReadState; private static int read_fail_count = 0; private static int cer_fail_count = 0; private static int comm_fail_count = 0; private static int success_count = 0; private String ip = "192.168.0.174"; private int port = 8988; private Dialog mIp_port_dialog; private IDCardAuthTask mIdCardAuthTask; private ProgressDialog mLoadingDialog; private AlertDialog mSet_nfc_dialog; public final static byte CARD_IDCARD = 0x0B; private static final String WG = "成功"; private boolean isRead = false; private CheckTicketTask mCheckTicketTask; public final static int START = 0; //开始 public final static int FIND_CARD = 1; //正在寻卡 public final static int READ_INFO = 2; //正在读取卡片信息 public final static int UPDATE_INFO = 3; //更新信息 public final static int END = 4; //检票结束 public final static int ERROR = 9; // HomeWatcher mHomeWatcher = new HomeWatcher(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); ButterKnife.bind(this); Log.d(WG, "onCreate: -------------------------------------------------"); mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() { @Override public void onHomePressed() { onHomeKey(); } @Override public void onHomeLongPressed() { onHomeKey(); } }); tIpPort.setText(ip + " " + port); clearUI(); // ----------------------------------------------- isRead = true; mCheckTicketTask = new CheckTicketTask(); mCheckTicketTask.start(); } @Override public void onStartRead() { clearUI(); // showLoading(); } @Override public void onSuccess(IdCardBean idCardBean) { missLoading(); if (idCardBean != null) { // 成功 tReadState.setTextColor(getResources().getColor(R.color.md_green_A400)); tReadState.setText("读取成功"); tSucess.setText(++success_count + "次"); tvName.setText(idCardBean.getName()); ivPhoto.setImageBitmap(idCardBean.getPhoto()); // 测试 将图像out 出来 /* final Bitmap bitmap = idCardBean.getPhoto(); Log.d(WG, "onSuccess: 图片地址: " + Environment.getExternalStorageDirectory() + "/sfzphoto"); new Thread(new Runnable() { @Override public void run() { BitmapUtil.saveBitmapToSDCard(bitmap, Environment.getExternalStorageDirectory() + "/sfzphoto"); } }).start();*/ tvSex.setText(idCardBean.getSex()); tvEhtnic.setText(idCardBean.getNation()); tvBirthday.setText(formatDate(idCardBean.getBirth())); tvAddress.setText(idCardBean.getAddress()); tvSigned.setText(idCardBean.getPolice()); tvValidate.setText(formatDate1(idCardBean.getFromValidDate()) + " - " + formatDate1(idCardBean.getToValidDate())); tvNumber.setText(idCardBean.getCode()); tPing.setText(idCardBean.getT_ping() + "ms"); tCer.setText(idCardBean.getT_cer() + "ms"); tComm.setText(idCardBean.getT_commun() + "ms"); tTime.setText(System.currentTimeMillis() - idCardBean.getTime() + "ms"); } } private void clearTime() { tPing.setText(""); tCer.setText(""); tComm.setText(""); tTime.setText(""); } public String formatDate(String s) { return new StringBuffer() .append(s.substring(0, 4)) .append(" 年 ") .append(s.substring(4, 6)) .append(" 月 ") .append(s.substring(6, 8)) .append(" 日 ") .toString(); } public String formatDate1(String s) { return new StringBuffer() .append(s.substring(0, 4)) .append(".") .append(s.substring(4, 6)) .append(".") .append(s.substring(6, 8)) .toString(); } @Override public void onFail(int errCode, String errMsg) { missLoading(); clearTime(); tReadState.setTextColor(getResources().getColor(R.color.md_red_500)); if (errCode == ResultCode.FAILED_TO_READ || errCode == ResultCode.TAG_LOSS || errCode == ResultCode.E_USERIDNOTFOUND || errCode == ResultCode.E_USERMACERROR || errCode == ResultCode.E_USERDATEERR || errCode == ResultCode.E_USERDAYLIMIT || errCode == ResultCode.E_USERCONCURRENCY || errCode == ResultCode.E_USERTERMDAYLIMIT || errCode == ResultCode.E_USERDAYLIMIT_IDSAM || errCode == ResultCode.E_OTHER) { // 读取错误 tReadState.setText(errMsg); tReadFail.setText(++read_fail_count + "次"); } else if (errCode == ResultCode.CER_FAILED) { // 认证错误 tReadState.setText(errMsg); tCerFail.setText(++cer_fail_count + "次"); } else if (errCode == ResultCode.COMM_FAILED) { // 通信错误 tCommFail.setText(++comm_fail_count + "次"); tReadState.setText(errMsg); } else if (errCode == ResultCode.CONNECTION_FAILED) { tConnState.setTextColor(getResources().getColor(R.color.md_red_500)); tConnState.setText(errMsg); } // againTest(); } @Override public void onConnectSuccess() { tConnState.setText("连接服务器成功"); tConnState.setTextColor(getResources().getColor(R.color.md_green_A400)); } @Override public void onConnectClose() { missLoading(); tConnState.setText("连接断开"); tConnState.setTextColor(getResources().getColor(R.color.md_red_500)); tReadState.setText(""); // againTest(); } private void claerCount() { read_fail_count = 0; cer_fail_count = 0; comm_fail_count = 0; success_count = 0; tReadFail.setText(""); tCommFail.setText(""); tCerFail.setText(""); tSucess.setText(""); } private void clearUI() { tvName.setText(""); ivPhoto.setImageBitmap(null); tvSex.setText(""); tvEhtnic.setText(""); tvBirthday.setText(""); tvAddress.setText(""); tvSigned.setText(""); tvValidate.setText(""); tvNumber.setText(""); } private void showLoading() { missLoading(); mLoadingDialog = new ProgressDialog(this); mLoadingDialog.setMessage("正在连接中,请稍后……"); mLoadingDialog.show(); } private void missLoading() { if (mLoadingDialog != null && mLoadingDialog.isShowing()) { mLoadingDialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.main_setting_menu: ipPortSettingDialog(); return true; default: return super.onOptionsItemSelected(item); } } /** * 输入IP PORT的dialog */ public void ipPortSettingDialog() { mIp_port_dialog = new Dialog(this, R.style.dialog_new); mIp_port_dialog.setContentView(R.layout.input_ip_port_dialog); TextView ptitle = (TextView) mIp_port_dialog.findViewById(R.id.pTitle); final EditText ipEt = (EditText) mIp_port_dialog.findViewById(R.id.ip_et); final EditText portEt = (EditText) mIp_port_dialog.findViewById(R.id.port_et); ipEt.setText(ip); portEt.setText(port + ""); Button qd = (Button) mIp_port_dialog.findViewById(R.id.confirm_btn); Button qx = (Button) mIp_port_dialog.findViewById(R.id.cancel_btn); ptitle.setText("参数设置"); qx.setText("取消"); qd.setText("确定"); qd.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String ip_input = ipEt.getText().toString().toString(); String port_input = portEt.getText().toString().toString(); if (TextUtils.isEmpty(ip_input)) { Toast.makeText(MainActivity.this, "ip不能设置为空", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(port_input)) { Toast.makeText(MainActivity.this, "端口号不能设置为空", Toast.LENGTH_SHORT).show(); return; } ip = ip_input; port = Integer.parseInt(port_input); tIpPort.setText(ip + " " + port); // closeIsodep(); tReadState.setText(""); tConnState.setText(""); clearUI(); clearTime(); claerCount(); if (mIdCardAuthTask != null) { mIdCardAuthTask.close(); } missSettingDialog(); } }); qx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { missSettingDialog(); } }); mIp_port_dialog.setCancelable(false); mIp_port_dialog.show(); } private void missSettingDialog() { if (mIp_port_dialog != null && mIp_port_dialog.isShowing()) { mIp_port_dialog.dismiss(); } } @SuppressLint("HandlerLeak") Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case START: Log.d(WG, "开始寻卡"); // resetUI(); // tvResult.setText("开始检票..."); break; case FIND_CARD: Log.d(WG, "开始寻卡"); // tvResult.setText("正在寻卡..."); break; case READ_INFO: Log.d(WG, "正在读取信息"); // tvResult.setText("正在读取信息..."); break; case CARD_IDCARD: Log.d(WG, "检测到身份证,准备读卡..."); // tvResult.setText("检测到身份证,准备读卡..."); startReadThread(); break; case END: // isRead = true; // isLoad = false; // ticketThread = new CheckTicketTask(); // ticketThread.setName("TicketThread"); // ticketThread.start(); break; case ERROR: // cancel(); // closeRFID(); // tvResult.setText(TicketResult.FAIL.getMesssage()); // imgResult.setImageResource(R.drawable.jpsb); // failureBeep.playBeepSound(); break; default: break; } } }; /** * 开始身份证识别操作 */ public void startReadThread() { try { showLoading(); mIdCardAuthTask = new IDCardAuthTask(new PosTrainSer(), MainActivity.this, ip, port); mIdCardAuthTask.execute(); } catch (Exception e) { e.printStackTrace(); } } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { // moveTaskToBack(false); // return true; // } // return super.onKeyDown(keyCode, event); // } private void exit() { stopThread(); } @Override protected void onDestroy() { exit(); super.onDestroy(); } protected void onHomeKey() { exit(); YFApp.getApp().unBind(); System.exit(0); } //TODO : 测试方法 // public void againTest() { // exit(); // YFApp.getApp().unBind(); // if (mIdCardAuthTask != null) { // mIdCardAuthTask.close(); // } // clearUI(); // isRead = true; // mCheckTicketTask = new CheckTicketTask(); // mCheckTicketTask.start(); // } public void againBt(View view) { exit(); YFApp.getApp().unBind(); if (mIdCardAuthTask != null) { mIdCardAuthTask.close(); } clearUI(); isRead = true; mCheckTicketTask = new CheckTicketTask(); mCheckTicketTask.start(); } private class CheckTicketTask extends Thread implements Runnable { @Override public void run() { while (isRead) { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // e.printStackTrace(); // } byte[] atr = null; try { handler.sendEmptyMessage(START);// 1开始寻找卡片 handler.sendEmptyMessage(FIND_CARD);// atr = YFApp.getApp().iService.rfidOpenEx(60); handler.sendEmptyMessage(READ_INFO);// Log.d(WG, "run: " + atr.toString()); Log.d(WG, "run: 开始寻找卡片"); // 2 判断卡片类型, if (atr != null) { Log.d(WG, "run: 身份证"); Log.d(WG, "run: atr " + ByteUtils.byteToHex(atr)); if (atr[0] == (byte) 0x01) { handler.sendEmptyMessage(CARD_IDCARD); stopThread(); } // mIdCardAuthTask = new IDCardAuthTask(new PosTrainSer(), MainActivity.this, "192.168.0.154", 8988); // mIdCardAuthTask.execute(); } } catch (Exception e) { try { Thread.sleep(1500); } catch (InterruptedException e1) { } e.printStackTrace(); } } } } /** * 停止读卡线程 */ private void stopThread() { missLoading(); if (mCheckTicketTask != null) { isRead = false; mCheckTicketTask = null; } closeRFID(); cancel(); if (mIdCardAuthTask != null) { mIdCardAuthTask.close(); } } /** * 关闭RFID */ private void closeRFID() { try { YFApp.getApp().iService.rfidCloseEx(); } catch (RemoteException e) { e.printStackTrace(); } } private void cancel() { try { YFApp.getApp().iService.cancel(); } catch (RemoteException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
package com.esum.web.apps.notifymgr.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import com.esum.appetizer.dao.AbstractDao; import com.esum.appetizer.util.PageUtil; import com.esum.web.apps.notifymgr.vo.ErrorCategory; import com.esum.web.apps.notifymgr.vo.NotifyAddrInfo; import com.esum.web.apps.notifymgr.vo.NotifyInfo; import com.esum.web.apps.notifymgr.vo.NotifyInfoMgr; import com.esum.web.apps.notifymgr.vo.NotifyMgr; import com.esum.web.apps.notifymgr.vo.NotifyModuleInfo; import com.esum.web.apps.notifymgr.vo.NotifyModuleMgr; import com.esum.web.apps.notifymgr.vo.NotifyTemplate; import com.esum.web.apps.notifymgr.vo.UserInfo; public class NotifyMgrDao extends AbstractDao{ //리스트 [NOTIFY_INFO] public List<NotifyInfo> selectListNotifyInfo(NotifyInfo notifyInfo, PageUtil pageUtil){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyInfo", notifyInfo); paramMap.put("pageUtil", pageUtil); return getSqlSession().selectList("notifyMgr.selectListNotifyInfo", paramMap); } //ROW 총 갯수 [NOTIFY_INFO] public int totalCountNotifyInfo(NotifyInfo notifyInfo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyInfo", notifyInfo); return (Integer)getSqlSession().selectOne("notifyMgr.totalCountNotifyInfo", paramMap); } //중복검사 [NOTIFY_INFO] public int dupChkNotifyInfoByNotifyId(String notifyId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyId", notifyId); return (Integer)getSqlSession().selectOne("notifyMgr.dupChkNotifyInfoByNotifyId", paramMap); } //중복검사 [NOTIFY_MGR > ERROR_PATTERN AND ERROR_TYPE] public int dupChkNotifyMgrByError(String errorPattern, String errorType){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("errorPattern", errorPattern); paramMap.put("errorType", errorType); return (Integer)getSqlSession().selectOne("notifyMgr.dupChkNotifyMgrByError", paramMap); } //사용자 검색 [USER_INFO] public List<UserInfo> selectListUserInfo(PageUtil pageUtil, UserInfo userInfo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("pageUtil", pageUtil); paramMap.put("userInfo", userInfo); return getSqlSession().selectList("notifyMgr.selectListUserInfo", paramMap); } //ROW 총 갯수 [USER_INFO] public int totalCountUserInfo(UserInfo userInfo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userInfo", userInfo); return (Integer)getSqlSession().selectOne("notifyMgr.totalCountUserInfo", paramMap); } //추가 [NOTIFY_INFO] public int insertNotifyInfo(NotifyInfo notifyInfo){ return (Integer)getSqlSession().insert("notifyMgr.insertNotifyInfo", notifyInfo); } //추가 [NOTIFY_ADDR_INFO] public int insertNotifyAddrInfo(NotifyAddrInfo notifyAddrInfo){ return (Integer)getSqlSession().insert("notifyMgr.insertNotifyAddrInfo", notifyAddrInfo); } //상세보기 [NOTIFY_INFO] public NotifyInfo selectNotifyInfo(NotifyInfo notifyInfo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyInfo", notifyInfo); return getSqlSession().selectOne("notifyMgr.selectNotifyInfo", paramMap); } //삭제 [NOTIFY_INFO] public int deleteNotifyInfo(String notifyId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyId", notifyId); return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyInfo", paramMap); } //삭제 [NOTIFY_ADDR_INFO] public int deleteNotifyAddrInfo(String notifyId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyId", notifyId); return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyAddrInfo", paramMap); } //삭제 [NOTIFY_INFO_MGR] public int deleteNotifyInfoMgr(String notifyId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyId", notifyId); return (Integer)getSqlSession().delete("deleteNotifyInfoMgrByNotifyId", paramMap); } //수정 [NOTIFY_INFO] public int updateNotifyInfo(NotifyInfo notifyInfo){ return (Integer)getSqlSession().update("notifyMgr.updateNotifyInfo", notifyInfo); } //조회 [NOTIFY_MGR] public List<NotifyMgr> selectListNotifyMgr(NotifyMgr notifyMgr, PageUtil pageUtil){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("pageUtil", pageUtil); paramMap.put("notifyMgr", notifyMgr); return getSqlSession().selectList("notifyMgr.selectListNotifyMgr", paramMap); } //ROW 총 갯수 [NOTIFY_MGR] public int totalCountNotifyMgr(NotifyMgr notifyMgr){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyMgr", notifyMgr); return (Integer)getSqlSession().selectOne("notifyMgr.totalCountNotifyMgr", paramMap); } //조회 [ERROR_CATEGORY] public List<ErrorCategory> selectListErrorCategory(ErrorCategory errorCategory, PageUtil pageUtil){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("pageUtil", pageUtil); paramMap.put("errorCategory", errorCategory); return getSqlSession().selectList("notifyMgr.selectListErrorCategory", paramMap); } //ROW 총 갯수 [NOTIFY_MGR] public int totalCountErrorCategory(ErrorCategory errorCategory){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("errorCategory", errorCategory); return (Integer)getSqlSession().selectOne("notifyMgr.totalCountErrorCategory", paramMap); } //조회 [NOTIFY_TEMPLATE] public List<NotifyTemplate> selectListNotifyTemplate(PageUtil pageUtil){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("pageUtil", pageUtil); return getSqlSession().selectList("notifyMgr.selectListNotifyTemplate", paramMap); } //ROW 총 갯수 [NOTIFY_TEMPLATE] public int totalCountNotifyTemplate(){ return (Integer)getSqlSession().selectOne("notifyMgr.totalCountNotifyTemplate"); } // 조회 [NOTIFY_MODULE_INFO] public List<NotifyModuleInfo> selectListNotifyModuleInfo(PageUtil pageUtil, NotifyModuleInfo notifyModuleInfo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("pageUtil", pageUtil); paramMap.put("notifyModuleInfo", notifyModuleInfo); return getSqlSession().selectList("notifyMgr.selectListNotifyModuleInfo", paramMap); } //ROW 총 갯수 [NOTIFY_MODULE_INFO] public int totalCountNotifyModuleInfo(NotifyModuleInfo notifyModuleInfo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyModuleInfo", notifyModuleInfo); return (Integer)getSqlSession().selectOne("notifyMgr.totalCountNotifyModuleInfo", paramMap); } //추가 [NOTIFY_MGR] public int insertNotifyMgr(NotifyMgr notifyMgr){ return (Integer)getSqlSession().insert("notifyMgr.insertNotifyMgr", notifyMgr); } //추가 [NOTIFY_MODULE_MGR] public int insertNotifyModuleMgr(NotifyModuleMgr notifyModuleMgr){ return (Integer)getSqlSession().insert("notifyMgr.insertNotifyModuleMgr", notifyModuleMgr); } //추가 [NOTIFY_INFO_MGR] public int insertNotifyInfoMgr(NotifyInfoMgr notifyInfoMgr){ return (Integer)getSqlSession().insert("notifyMgr.insertNotifyInfoMgr", notifyInfoMgr); } //수정 [NOTIFY_MGR] public int updateNotifyMgr(NotifyMgr notifyMgr){ return (Integer)getSqlSession().insert("notifyMgr.updateNotifyMgr", notifyMgr); } //삭제 [NOTIFY_MGR] public int deleteNotifyMgr(NotifyMgr notifyMgr){ return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyMgr", notifyMgr); } //삭제 [NOTIFY_INFO_MGR] public int deleteNotifyInfoMgr(NotifyMgr notifyMgr){ return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyInfoMgr", notifyMgr); } //삭제 [NOTIFY_MODULE_MGR] public int deleteNotifyModuleMgr(NotifyMgr notifyMgr){ return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyModuleMgr", notifyMgr); } //조회 [NOTIFY_MGR] public NotifyMgr selectNotifyMgr(NotifyMgr notifyMgr){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyMgr", notifyMgr); return getSqlSession().selectOne("notifyMgr.selectNotifyMgr",paramMap); } //조회 [NOTIFY_MODULE_INFO] public NotifyModuleInfo selectNotifyModuleInfo(String notifyModuleId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyModuleId", notifyModuleId); return getSqlSession().selectOne("notifyMgr.selectNotifyModuleInfo",paramMap); } //수정 [NOTIFY_MODULE_INFO] public int updateNotifyModuleInfo(NotifyModuleInfo notifyModuleInfo){ return (Integer)getSqlSession().update("notifyMgr.updateNotifyModuleInfo", notifyModuleInfo); } //추가 [NOTIFY_MODULE_INFO] public int insertNotifyModuleInfo(NotifyModuleInfo notifyModuleInfo){ return (Integer)getSqlSession().update("notifyMgr.insertNotifyModuleInfo", notifyModuleInfo); } //삭제 [NOTIFY_MODULE_MGR] public int deleteNotifyModuleMgr(NotifyModuleInfo notifyModuleInfo){ return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyModuleMgrByNotifyModuleId", notifyModuleInfo); } //삭제 [NOTIFY_MODULE_INFO] public int deleteNotifyModuleInfo(NotifyModuleInfo notifyModuleInfo){ return (Integer)getSqlSession().delete("notifyMgr.deleteNotifyModuleInfo", notifyModuleInfo); } //통보 모듈 ID 중복확인 [NOTIFY_MODULE_INFO] public int dupChkNotifyModuleId(String notifyModuleId){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("notifyModuleId", notifyModuleId); return (Integer)getSqlSession().selectOne("notifyMgr.dupChkNotifyModuleId", paramMap); } }
package com.example.sgkim94.item09; import com.example.sgkim94.item05.PrintNotification; import lombok.extern.slf4j.Slf4j; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; @Slf4j public class UseTryCatchFinally implements FileReader { @Override public void readFile() { try { FileOutputStream fos = new FileOutputStream("file.text"); try { final ObjectOutputStream oos = new ObjectOutputStream(fos); try { oos.writeObject(new PrintNotification()); oos.flush(); } catch (IOException e) { log.error("Fail write PrintNotification!"); } finally { try { oos.close(); } catch (IOException e) { log.error("Fail close ObjectOutputStream!"); } } } finally { fos.close(); } } catch (IOException e) { log.error("Fail read file.text!"); } } }
package com.hfad.quiz; import java.util.List; /** * Created by augus on 4/11/2018. */ public class PerguntaModel { public String texto; public List<String> alternativas; public int repostaCerta; }
package com.codegym; public class Student extends Person { private String className; private double grade; public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public double getGrade() { return grade; } public void setGrade(double grade) { this.grade = grade; } @Override public void hoc() { System.out.println("Tham khao cac giao trinh o truong hoc."); } }
package IPMJasperGoris.IPMJasperGoris.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class SubTask{ @Id @GeneratedValue private Long subId; private Long correspondingTask; private String name; private String description; private String tijdstip; private String datum; public SubTask(){ } public SubTask(String name, String description, String tijdstip, String datum) { this.name = name; this.description = description; this.tijdstip = tijdstip; this.datum = datum; } public void setSubId(Long subId) { this.subId = subId; } public Long getSubId() { return subId; } public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } public void setTijdstip(String tijdstip) { this.tijdstip = tijdstip; } public void setDatum(String datum) { this.datum = datum; } public String getName() { return name; } public String getDescription() { return description; } public String getTijdstip() { return tijdstip; } public String getDatum() { return datum; } public void setCorrespondingTask(Long correspondingTask) { this.correspondingTask = correspondingTask; } public Long getCorrespondingTask() { return correspondingTask; } }
package com.github.dockerjava.jaxrs; import static javax.ws.rs.client.Entity.entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.api.command.CreateExecCmd; import com.github.dockerjava.api.command.CreateExecResponse; public class CreateExecCmdExec extends AbstrDockerCmdExec<CreateExecCmd, CreateExecResponse> implements CreateExecCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(CreateExecCmdExec.class); public CreateExecCmdExec(WebTarget baseResource) { super(baseResource); } @Override protected CreateExecResponse execute(CreateExecCmd command) { WebTarget webResource = getBaseResource().path("/containers/{id}/exec").resolveTemplate("id", command.getContainerId()); LOGGER.trace("POST: {} ", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON) .post(entity(command.getExecConfig(), MediaType.APPLICATION_JSON), CreateExecResponse.class); } }
package Demo; import java.util.concurrent.*; import java.util.*; public class SyncAnotherObj { public static void main(String[] args) { DualSync ds = new DualSync(); new Thread() { @Override public void run() { ds.f(); } }.start(); ds.g(); } } class DualSync { private Object syncObj = new Object(); public synchronized void f() { //ds对象的锁 for(int i=0; i<100; i++) { System.out.println("f()"); Thread.yield(); } } public void g() { synchronized(syncObj) { //syncObj对象的锁 for(int i=0; i<100; i++) { System.out.println("g()"); Thread.yield(); } } } }
package service; import dao.FontFamilyDAO; import java.util.List; import model.bean.style.FontFamily; import util.ServiceReturn; import util.enums.DAOList; import util.exceptions.DAOException; /** * * @author Andriy */ public class StyleService extends Service { public ServiceReturn getAllFontFamilies() throws Exception { ServiceReturn result = new ServiceReturn(); try { MANAGER.beginTransaction(); FontFamilyDAO fontFamilyDao = (FontFamilyDAO) MANAGER.getDAO(DAOList.FONT_FAMILY); List<FontFamily> fontFamilies = fontFamilyDao.getAllFontFamilies(); result.addItem("fontFamilies", fontFamilies); MANAGER.commit(); } catch (DAOException e) { MANAGER.rollback(); throw treatException(e); } finally { MANAGER.close(); } return result; } }
public class DriverLicenseException extends DriverException { private static final long serialVersionUID = 1L; }
package com.netcracker.config; import com.netcracker.models.DomenUser; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class DomenUserConfig { @Bean public DomenUser getDomenUser() { return new DomenUser() .setDomenName("assistent.folktaxi@yandex.ru") .setDomenPassword("WEf-J53-v8g-dYx"); } }
package com.jeffdisher.thinktank.chat.support; import java.nio.charset.StandardCharsets; /** * Serializes/deserializes Strings for Laminar. */ public class StringCodec implements ICodec<String> { @Override public String deserialize(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8); } @Override public byte[] serialize(String object) { return object.getBytes(StandardCharsets.UTF_8); } }
package modelo; import modelo.excepciones.CasilleroOcupado; import modelo.excepciones.CasilleroVacio; public class Casillero { private final ObjetoJuego vacio = null; private ObjetoJuego objeto = vacio; public void agregarObjeto(ObjetoJuego unObjeto) { if (!this.estaVacio()) { throw new CasilleroOcupado(); } this.objeto = unObjeto; } public ObjetoJuego eliminarObjeto() { if(this.estaVacio()){ throw new CasilleroVacio(); } ObjetoJuego unObjeto = this.objeto; this.objeto = vacio; return unObjeto; } public ObjetoJuego obtenerObjeto() { if(this.estaVacio()){ throw new CasilleroVacio(); } return this.objeto; } public boolean estaVacio(){ return (objeto == vacio); } }
package za.ac.ngosa.repository; import za.ac.ngosa.domain.Beverage; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * Created by User on 2015/08/10. */ @Repository public interface BeverageRepository extends CrudRepository<Beverage,Long> { public Beverage findOne(Long code); }
package pers.mine.scratchpad.util; import java.util.Arrays; import java.util.Scanner; import com.alibaba.fastjson.JSONObject; /** * json工具类 * * @author Mine * @data 2019年9月27日 下午4:52:07 */ public class JsonKit { /** * 默认key路径分割符 */ public static final Character DEFAULT_KEY_SEPARATOR = ','; /** * 置jsonObject限定名key为指定值,key使用指定分隔符分隔<br> * ps:注意不同深度值之间的覆盖问题 * * @param jsonObject 待更新jsonObject * @param qualifiedKey 限定名key * @param baseValue 基础值 * @param keySeparator key分隔符 */ public static void updateJson(JSONObject jsonObject, String qualifiedKey, Object baseValue, Character keySeparator) { int index = qualifiedKey.indexOf(keySeparator); if (index != -1) { String key = qualifiedKey.substring(0, index); JSONObject jo; if (jsonObject.containsKey(key)) { jo = jsonObject.getJSONObject(key); } else { jo = new JSONObject(); jsonObject.put(key, jo); } String subQualifiedKey = qualifiedKey.substring(index + 1); updateJson(jo, subQualifiedKey, baseValue, keySeparator); } else { jsonObject.put(qualifiedKey, baseValue); } } /** * 置jsonObject限定名key为指定值,key使用","分隔符分隔 * * @see JsonUtils#updateJson(com.alibaba.fastjson.JSONObject, java.lang.String, * java.lang.Object, java.lang.Character) */ public static void updateJson(JSONObject jsonObject, String qualifiedKey, Object baseValue) { updateJson(jsonObject, qualifiedKey, baseValue, DEFAULT_KEY_SEPARATOR); } public static void main1(String[] args) { Scanner scan = new Scanner(System.in); int sum = 0; while (true) { System.out.println("请输入:"); String next = scan.next(); System.out.println("接收到了:" + next); JSONObject one = JSONObject.parseObject(next); for (String key : one.keySet()) { JSONObject two = one.getJSONObject(key); if (two.getJSONObject("order").containsKey("1")) { Long[] clks = two.getJSONObject("order").getJSONObject("1").getObject("clks", Long[].class); System.out.println(Arrays.deepToString(clks)); sum += clks[0]; System.out.println("sum:" + sum); } else { System.out.println("未找到order:1"); } } } } }
package com.SearchHouse.mapper; import java.util.List; import com.SearchHouse.pojo.Pay; public interface PayMapper { public List<Pay> getAllPays(); public Pay getPayById(Integer payId); }
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.idea.util; import com.atlassian.theplugin.commons.UiTask; import com.atlassian.theplugin.commons.util.LoggerImpl; import com.atlassian.theplugin.idea.ui.DialogWithDetails; import com.atlassian.theplugin.util.PluginUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; /** * @author Jacek Jaroczynski */ public final class IdeaUiMultiTaskExecutor { private Component component; private List<ErrorObject> errors = new ArrayList<ErrorObject>(); private CountDownLatch finishedLatch; private IdeaUiMultiTaskExecutor(final int numberOfThread) { finishedLatch = new CountDownLatch(numberOfThread); } public static void execute(final UiTask uiTask) { getExecutor(1).executeTask(uiTask); } public static void execute(final List<UiTask> tasks, final Component c) { getExecutor(tasks.size()).executeTasks(tasks, c); } private static IdeaUiMultiTaskExecutor getExecutor(int numberOfThread) { return new IdeaUiMultiTaskExecutor(numberOfThread); } private void executeTask(final UiTask uiTask) { component = uiTask.getComponent(); runTask(uiTask); waitForThreadsAndShowErrors(); } private void executeTasks(final List<UiTask> tasks, final Component c) { component = c; for (UiTask uiTask : tasks) { runTask(uiTask); } waitForThreadsAndShowErrors(); } private void runTask(final UiTask uiTask) { final ModalityState modalityState = ModalityState.stateForComponent(uiTask.getComponent()); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { try { uiTask.run(); } catch (final Exception e) { reportError(e, uiTask, modalityState); finishedLatch.countDown(); return; } reportSuccess(uiTask, modalityState); finishedLatch.countDown(); } }); } // todo it should not be synchronized??? private synchronized void waitForThreadsAndShowErrors() { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { try { finishedLatch.await(); EventQueue.invokeLater(new Runnable() { public void run() { if (component != null && component.isShowing()) { if (errors.size() == 1) { DialogWithDetails.showExceptionDialog(component, errors.get(0).getMessage(), errors.get(0).getException()); } else if (errors.size() > 1) { DialogWithDetails.showExceptionDialog(component, errors); } } clearErrors(); } }); } catch (InterruptedException e) { PluginUtil.getLogger().warn("InterruptedException caught when waiting for CountDownLatch", e); } } }); } private synchronized void reportSuccess(final UiTask uiTask, final ModalityState modalityState) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { uiTask.onSuccess(); } }, modalityState); } private synchronized void reportError(final Exception e, final UiTask uiTask, final ModalityState modalityState) { LoggerImpl.getInstance().warn(e); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { uiTask.onError(); } }, modalityState); addError(new ErrorObject("Error while " + uiTask.getLastAction(), e)); } private void addError(ErrorObject error) { errors.add(error); } private void clearErrors() { errors.clear(); } public static class ErrorObject { private String message; private Throwable exception; public ErrorObject(final String message, final Throwable exception) { this.message = message; this.exception = exception; } public Throwable getException() { return exception; } public String getMessage() { return message; } } }
public class Runner { public static void main(String[] args) { Classroom c = new Classroom(0, "Math 3", 250); Student s1 = new Student("John", 10, 5); Student s2 = new Student("Carl", 11, 6); Student s3 = new Student("Jim", 9, 5); Student s4 = new Student("Mary", 12, 6); c.addStudent(s1); c.addStudent(s2); c.addStudent(s3); c.addStudent(s4); System.out.println(c); System.out.println(Classroom.averageAge(c.getStudents())); System.out.println("Total Students: " + Student.getNumStudents()); } }
import java.util.*; public final class Test { public static void main(String... aArguments) { LinkedList<String> flavours = new LinkedList<String>(); flavours.add("chocolate"); flavours.add("strawberry"); flavours.add("vanilla"); useWhileLoop(flavours); useForLoop(flavours); } private static void useWhileLoop(LinkedList<String> aFlavours) { Iterator<String> flavoursIter = aFlavours.descendingIterator(); while (flavoursIter.hasNext()){ System.out.println(flavoursIter.next()); } } /** * Note that this for-loop does not use an integer index. */ private static void useForLoop(LinkedList<String> aFlavours) { for (Iterator<String> flavoursIter = aFlavours.iterator(); flavoursIter.hasNext();){ System.out.println(flavoursIter.next()); } } }
package com.bytest.autotest.innerService; import com.bytest.autotest.domain.UserInfo; import com.bytest.autotest.util.PageResult; import org.springframework.stereotype.Service; import java.util.List; /** * <h3>risk-auto-test</h3> * <p>测试数据</p> * * @author : hh * @date : 2020-05-04 02:41 **/ @Service public interface UserInfoService { public Integer gettotal(); public List<UserInfo> getall(); public PageResult getPageResult(Integer page,Integer size); public UserInfo getUserNoused(); public Integer Update(UserInfo userInfo); public Integer inSert(UserInfo userInfo); }
package xtrus.ex.mgr.excms.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.esum.appetizer.controller.AbstractController; import com.esum.appetizer.exception.ErrorCode; import com.esum.appetizer.util.RequestUtils; import com.esum.appetizer.vo.RestResult; import xtrus.ex.mgr.excms.service.ExCmsInfoService; import xtrus.ex.mgr.excms.vo.ExCmsInfo; /** * Copyright(c) eSum Technologies., Inc. All rights reserved. */ @RestController public class ExCmsInfoRestController extends AbstractController { @Autowired private ExCmsInfoService baseService; /** * EXCMS 컴포넌트 - 중복검사 */ @RequestMapping(value = "/rest/c/ex/excms/exCmsInfoExist") public RestResult exCmsInfoExist(HttpServletRequest request) throws Exception { try { String interfaceId = request.getParameter("interfaceId"); boolean exist = baseService.exist(interfaceId); return new RestResult(ErrorCode.SUCCESS, exist); } catch (Exception e) { return new RestResult(e); } } /** * EXCMS 컴포넌트 - 등록 */ @RequestMapping(value = "/rest/c/ex/excms/exCmsInfoInsert") public RestResult exCmsInfoInsert(HttpServletRequest request) throws Exception { try { String interfaceId = request.getParameter("interfaceId"); String nodeId = request.getParameter("nodeId"); String serverUseFlag = request.getParameter("serverUseFlag"); int serverListenPort = RequestUtils.getParamInt(request, "serverListenPort", 0); int serverConnTimeout = RequestUtils.getParamInt(request, "serverConnTimeout", 60); int serverIdleTimeout = RequestUtils.getParamInt(request, "serverIdleTimeout", 60); int serverReadTimeout = RequestUtils.getParamInt(request, "serverReadTimeout", 60); String workTypeCode = request.getParameter("workTypeCode"); String unitCode = request.getParameter("unitCode"); int maxPacketSize = RequestUtils.getParamInt(request, "maxPacketSize", 4041); String useServerBatch = request.getParameter("useServerBatch"); String serverBatchClass = request.getParameter("serverBatchClass"); String useServerBackup = request.getParameter("useServerBackup"); String serverBackupDir = request.getParameter("serverBackupDir"); String clientUseFlag = request.getParameter("clientUseFlag"); String clientHost = request.getParameter("clientHost"); int clientPort = RequestUtils.getParamInt(request, "clientPort", 0); int clientConnTimeout = RequestUtils.getParamInt(request, "clientConnTimeout", 60); int clientIdleTimeout = RequestUtils.getParamInt(request, "clientIdleTimeout", 60); int clientReadTimeout = RequestUtils.getParamInt(request, "clientReadTimeout", 60); String clientAuthId = request.getParameter("clientAuthId"); int clientPacketSize = RequestUtils.getParamInt(request, "clientPacketSize", 4041); String parsingRule = request.getParameter("parsingRule"); ExCmsInfo vo = new ExCmsInfo(); vo.setInterfaceId(interfaceId); vo.setNodeId(nodeId); vo.setServerUseFlag(serverUseFlag); vo.setServerListenPort(serverListenPort); vo.setServerConnTimeout(serverConnTimeout); vo.setServerIdleTimeout(serverIdleTimeout); vo.setServerReadTimeout(serverReadTimeout); vo.setUseServerBatch(useServerBatch); vo.setServerBatchClass(serverBatchClass); vo.setWorkTypeCode(workTypeCode); vo.setUnitCode(unitCode); vo.setMaxPacketSize(maxPacketSize); vo.setUseServerBackup(useServerBackup); vo.setServerBackupDir(serverBackupDir); vo.setClientUseFlag(clientUseFlag); vo.setClientHost(clientHost); vo.setClientPort(clientPort); vo.setClientConnTimeout(clientConnTimeout); vo.setClientIdleTimeout(clientIdleTimeout); vo.setClientReadTimeout(clientReadTimeout); vo.setClientAuthId(clientAuthId); vo.setClientPacketSize(clientPacketSize); vo.setParsingRule(parsingRule); baseService.insert(vo); baseService.reload(interfaceId); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } /** * EXCMS 컴포넌트 - 수정 */ @RequestMapping(value = "/rest/c/ex/excms/exCmsInfoUpdate") public RestResult exCmsInfoUpdate(HttpServletRequest request) throws Exception { try { String interfaceId = request.getParameter("interfaceId"); String nodeId = request.getParameter("nodeId"); String serverUseFlag = request.getParameter("serverUseFlag"); int serverListenPort = RequestUtils.getParamInt(request, "serverListenPort", 0); int serverConnTimeout = RequestUtils.getParamInt(request, "serverConnTimeout", 60); int serverIdleTimeout = RequestUtils.getParamInt(request, "serverIdleTimeout", 60); int serverReadTimeout = RequestUtils.getParamInt(request, "serverReadTimeout", 60); String workTypeCode = request.getParameter("workTypeCode"); String unitCode = request.getParameter("unitCode"); int maxPacketSize = RequestUtils.getParamInt(request, "maxPacketSize", 4041); String useServerBatch = request.getParameter("useServerBatch"); String serverBatchClass = request.getParameter("serverBatchClass"); String useServerBackup = request.getParameter("useServerBackup"); String serverBackupDir = request.getParameter("serverBackupDir"); String clientUseFlag = request.getParameter("clientUseFlag"); String clientHost = request.getParameter("clientHost"); int clientPort = RequestUtils.getParamInt(request, "clientPort", 0); int clientConnTimeout = RequestUtils.getParamInt(request, "clientConnTimeout", 60); int clientIdleTimeout = RequestUtils.getParamInt(request, "clientIdleTimeout", 60); int clientReadTimeout = RequestUtils.getParamInt(request, "clientReadTimeout", 60); String clientAuthId = request.getParameter("clientAuthId"); int clientPacketSize = RequestUtils.getParamInt(request, "clientPacketSize", 4041); String parsingRule = request.getParameter("parsingRule"); ExCmsInfo vo = new ExCmsInfo(); vo.setInterfaceId(interfaceId); vo.setNodeId(nodeId); vo.setServerUseFlag(serverUseFlag); vo.setServerListenPort(serverListenPort); vo.setServerConnTimeout(serverConnTimeout); vo.setServerIdleTimeout(serverIdleTimeout); vo.setServerReadTimeout(serverReadTimeout); vo.setUseServerBatch(useServerBatch); vo.setServerBatchClass(serverBatchClass); vo.setWorkTypeCode(workTypeCode); vo.setUnitCode(unitCode); vo.setMaxPacketSize(maxPacketSize); vo.setUseServerBackup(useServerBackup); vo.setServerBackupDir(serverBackupDir); vo.setClientUseFlag(clientUseFlag); vo.setClientHost(clientHost); vo.setClientPort(clientPort); vo.setClientConnTimeout(clientConnTimeout); vo.setClientIdleTimeout(clientIdleTimeout); vo.setClientReadTimeout(clientReadTimeout); vo.setClientAuthId(clientAuthId); vo.setClientPacketSize(clientPacketSize); vo.setParsingRule(parsingRule); baseService.update(vo); baseService.reload(interfaceId); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } /** * EXCMS 컴포넌트 - 삭제 */ @RequestMapping(value = "/rest/c/ex/excms/exCmsInfoDelete") public RestResult exCmsInfoDelete(HttpServletRequest request) throws Exception { try { String interfaceId = request.getParameter("interfaceId"); baseService.delete(interfaceId); baseService.reload(interfaceId); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } /** * EXCMS 컴포넌트 - 리로드 */ @RequestMapping(value = "/rest/c/ex/excms/exCmsInfoReload") public RestResult exCmsInfoReload(HttpServletRequest request) throws Exception { try { baseService.reload(null); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } }
//package com.an.scone.controller; // //import com.an.scone.service.KeywordService; //import org.springframework.beans.factory.annotation.Autowired; // //public class KeywordController { // // private KeywordService keywordService; // // @Autowired // KeywordController( // KeywordService keywordService // ) { // this.keywordService = keywordService; // } // // public String getKeywordInfoByCompany(String company){ // String keyword = keywordService.getKeywordInfoByCompany(company); // System.out.println("keyword : " + keyword); // return keywordService.getKeywordInfoByCompany(company); // } // // public int isCompany(String company){ // return keywordService.isCompany(company); // } // // public void saveCompany(String company){ // keywordService.setCompany(company); // } // // public void saveKeyword(String company){ // keywordService.setKeyword(company); // } // // public void update(String company, String keyword){ // keywordService.updateKeywordInfo(company, keyword); // } //}
package Pro41.FindContinuousSequence; import java.util.ArrayList; /*小明很喜欢数学,有一天他在做数学作业时, 要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此, 他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久, 他就得到另一组连续正数和为100的序列:18,19,20,21,22。 现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!*/ // //public class Solution //{ // public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) // { // // } //}
/* * 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 controlador; import vista.Formulario; /** *La clase encargada de ejecutar la aplicación. * @author pablo */ public class Main { /** * El método main llama al menú de la vista instanciando la clase Formulario. * @param args the command line arguments */ public static void main(String[] args) { Formulario f1 = new Formulario(); f1.menu(); } }
package org.exoplatform.management.ecmadmin.operations.templates.applications; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.exoplatform.services.cms.views.ApplicationTemplateManagerService; import org.gatein.management.api.PathAddress; import org.gatein.management.api.exceptions.OperationException; import org.gatein.management.api.operation.OperationContext; import org.gatein.management.api.operation.OperationHandler; import org.gatein.management.api.operation.ResultHandler; import org.gatein.management.api.operation.model.ReadResourceModel; /** * @author <a href="mailto:thomas.delhomenie@exoplatform.com">Thomas * Delhoménie</a> * @version $Revision$ */ public class ApplicationTemplatesReadResource implements OperationHandler { @Override public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException { String operationName = operationContext.getOperationName(); PathAddress address = operationContext.getAddress(); String applicationName = address.resolvePathTemplate("application-name"); if (applicationName == null) { throw new OperationException(operationName, "No application name specified."); } Set<String> templates = null; ApplicationTemplateManagerService templateManagerService = operationContext.getRuntimeContext().getRuntimeComponent( ApplicationTemplateManagerService.class); try { Set<String> nonSortedTemplates = templateManagerService.getConfiguredAppTemplateMap(applicationName); // convert to List in order to sort it List<String> templatesList = new ArrayList<String>(nonSortedTemplates); Collections.sort(templatesList); templates = new TreeSet<String>(templatesList); } catch (Exception e) { throw new OperationException("Read template applications", "Error while retrieving applications with templates", e); } resultHandler.completed(new ReadResourceModel("Available application templates", templates)); } }
package com.itcia.itgoo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.itcia.itgoo.dao.ITestDao; import com.itcia.itgoo.dto.Adopt; @Service public class AdminTest { @Autowired ITestDao tDao; public void documentPass(Adopt adopt) { tDao.documentPass(adopt); } @Transactional public void adoptOut(Adopt adopt) { tDao.dogUpdate(adopt); tDao.adoptOut(adopt); tDao.testOut(adopt); } }
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); String t = scanner.nextLine(); int m = s.length(); int n = t.length(); int[][] S = new int[m+1][n+1]; int max1 = 0; int max2 = 0; boolean a = false; boolean b = false; boolean c = false; for (int i = 0; i < m+1; i++) { for (int j = 0; j < n+1; j++) { S[i][j] = Integer.MIN_VALUE; } } S[0][0] = 0; for (int i = 1; i < m+1; i++) { S[i][0] = S[i-1][0] + 1; //gap penalty } for (int j = 1; j < n+1; j++) { S[0][j] = S[0][j-1] + 1; //gap penalty } for (int i = 1; i < m+1; i++) { for (int j = 1; j < n+1; j++) { if (isSame(s.charAt(i-1),t.charAt(j-1))) S[i][j] = S[i-1][j-1]; else S[i][j] = Math.min( S[i-1][j-1] ,Math.min( S[i-1][j] , S[i][j-1])) +1; } } System.out.println(S[m][n]); } public static boolean isSame(char a, char b){ return (a==b); } }
package cn.sort.insertSort; import cn.sort.GoodsPrice; import java.util.ArrayList; import java.util.List; /** * Created by xiaoni on 2017/12/22. * 直接插入排序 * 基本思想:在要排序的一组数中,假设前面(n-1)[n>=2] 个数已经是排 好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数 也是排好顺序的。如此反复循环,直到全部排好顺序。 */ public class InsertSort { public static void insertSort(List<GoodsPrice> array) { //至少有两个元素才排序 if(array != null && array.size() > 1) { for (int i = 1; i < array.size(); i++) { GoodsPrice temp = array.get(i); int j = i - 1; for (; j >= 0 && array.get(j).getPrice() > temp.getPrice(); j--) { //将大于temp的值整体后移一个单位 array.set(j + 1 , array.get(j)); } array.set(j + 1, temp); } } displayArray(array); } public static void displayArray(List<GoodsPrice> array) { if(array != null && array.size() > 0) { for(GoodsPrice goodsPrice : array) { System.out.println(goodsPrice.getName() + goodsPrice.getPrice() + ","); } } } public static void main(String[] args) { List<GoodsPrice> goodsPrices = new ArrayList<>(); goodsPrices.add(new GoodsPrice("apple", 12L)); goodsPrices.add(new GoodsPrice("banana", 12L)); goodsPrices.add(new GoodsPrice("pear", 10L)); goodsPrices.add(new GoodsPrice("orange", 3L)); System.out.println("插入排序"); insertSort(goodsPrices); } }
package interaction; import elements.Status; import elements.Worker; import java.io.IOException; import java.util.List; /** * Интерфейс для классов, управляющих взаимодействием с коллекцией. */ public interface InteractionInterface { String info(); String show(); void add(Worker worker) throws Exception; void update(long id, Worker worker); void removeById(long id); void clear(); void save() throws IOException; void exit(); void addIfMin(Worker worker); void removeGreater(Worker worker); void removeLower(Worker worker); int countByStatus(Status status); List<String> printAscending(); List<String> printUniqueOrganization(); int getSize(); boolean findById(long key); boolean checkChanges(); String returnSeparator(); }
package com.social.server.service.impl; import com.social.server.dao.GroupRepository; import com.social.server.dto.GroupDto; import com.social.server.entity.EventType; import com.social.server.entity.Group; import com.social.server.entity.GroupRelation; import com.social.server.entity.User; import com.social.server.http.model.GroupModel; import com.social.server.service.EventService; import com.social.server.service.GroupService; import com.social.server.service.PhotoSaver; import com.social.server.service.UserService; import com.social.server.service.transactional.ReadTransactional; import com.social.server.service.transactional.WriteTransactional; import com.social.server.validator.GroupModelValidator; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.util.Collections; import java.util.List; @Slf4j @Service public class GroupServiceImpl extends CommonServiceImpl<Group, Long, GroupRepository> implements GroupService { private final UserService userService; private final EventService eventService; private final PhotoSaver<Group> photoSaver; @Autowired public GroupServiceImpl(GroupRepository groupRepository, UserService userService, EventService eventService, PhotoSaver<Group> photoSaver) { super(groupRepository); this.userService = userService; this.eventService = eventService; this.photoSaver = photoSaver; } @Override public Page<GroupDto> findBy(long userId, int page) { return repository.findByUsersIdIn(userId, PageRequest.of(page, 10)).map(GroupDto::of); } @Override public GroupDto find(long groupId) { return GroupDto.of(getById(groupId)); } @Override public long countParticipant(long groupId) { return repository.countParticipant(groupId); } @Override @WriteTransactional public GroupDto create(long adminId, GroupModel groupModel) { validateEmptyEntityId(adminId); log.debug("Creating group start. Admin={}", adminId); User admin = userService.getById(adminId); Group group = new Group(); group.setName(groupModel.getName()); group.setDescription(groupModel.getDescription()); group.setAdmin(admin); group.getUsers().add(admin); log.debug("Save new group"); group = repository.save(group); eventService.createEvent(admin.getId(), group.getId(), group.getName(), EventType.ENTER_GROUP); log.debug("Creating group completed successfully"); return GroupDto.of(group); } @Override public boolean isUserHasGroup(long userId, long groupId) { validateEmptyEntityId(userId, groupId); return repository.existsByIdAndUsersIdIn(groupId, userId); } @Override @WriteTransactional public void join(long userId, long groupId) { log.debug("Join user to group; userId={}, groupId={}", userId, groupId); validateEmptyEntityId(userId, groupId); Group group = getById(groupId); User user = userService.getById(userId); group.getUsers().add(user); eventService.createEvent(userId, group.getId(), group.getName(), EventType.ENTER_GROUP); log.debug("Join user to group completed successfully"); } @Override public List<GroupDto> search(String name) { log.debug("Search group by name={}", name); if (StringUtils.isBlank(name)) { return Collections.emptyList(); } return GroupDto.of(repository.searchByName(name.toLowerCase())); } @Override @WriteTransactional public long savePhoto(long groupId, MultipartFile file, boolean isMini) { validateEmptyEntityId(groupId); return photoSaver.savePhoto(getById(groupId), file, isMini); } @Override @WriteTransactional public void exit(long userId, long groupId) { log.debug("Exit from group; userId={}, groupId={}", userId, groupId); validateEmptyEntityId(userId, groupId); Group group = getById(groupId); User user = userService.getById(userId); group.getUsers().remove(user); log.debug("Exit from group completed successfully"); } @Override public long countBy(long userId) { return repository.countAllByUsersIdIn(userId); } @Override @ReadTransactional public GroupRelation getGroupRelationToUser(long groupId, long rootUserId) { validateEmptyEntityId(rootUserId, groupId); if (!isUserHasGroup(rootUserId, groupId)) { return GroupRelation.NOT_PARTICIPANT; } Group group = getById(groupId); if (group.getAdmin().getId() == rootUserId) { return GroupRelation.ADMIN; } return GroupRelation.PARTICIPANT; } @Override @WriteTransactional public GroupDto edit(GroupModel groupModel) { GroupModelValidator.validate(groupModel); log.debug("Edit group; groupId={}", groupModel.getId()); Group group = getById(groupModel.getId()); group.setDescription(groupModel.getDescription()); group.setName(groupModel.getName()); return GroupDto.of(group); } }
package vape.springmvc.dao; import java.util.List; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import vape.springmvc.entity.ProductosNuevos; @Repository public class ProductosNuevosDAOImpl implements ProductosNuevosDAO { @Autowired private SessionFactory sessionFactory; @Override public List < ProductosNuevos > getProductosNuevos() { Session session = sessionFactory.getCurrentSession(); CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery < ProductosNuevos > cq = cb.createQuery(ProductosNuevos.class); Root < ProductosNuevos > root = cq.from(ProductosNuevos.class); CriteriaQuery<ProductosNuevos> all = cq.select(root); TypedQuery<ProductosNuevos> allQuery = session.createQuery(all); return allQuery.getResultList(); } @Override public void deleteProductosNuevos(int id) { Session session = sessionFactory.getCurrentSession(); ProductosNuevos dele = session.byId(ProductosNuevos.class).load(id); session.delete(dele); } }
package com.fgtit.app; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import android.content.Context; import android.os.Handler; import android.os.SystemClock; import android.widget.Toast; public class LocatorServer { private final byte TAG_CMD = (byte) 0xff; private final byte TAG_STATUS = (byte) 0xfe; private final byte CMD_DISCOVER_TARGET = 0x02; private static LocatorServer instance; private Context pcontext=null; private Handler phandler=null; private byte[] LocatorData=new byte[84]; public static LocatorServer getInstance() { if(null == instance) { instance = new LocatorServer(); } return instance; } public void setContext(Context context){ pcontext=context; } public void setHandler(Handler handler){ phandler=handler; } public void ShowMessage(final String msg){ if(phandler!=null){ phandler.post(new Runnable() { @Override public void run() { Toast.makeText(pcontext, msg, Toast.LENGTH_SHORT).show(); } }); } } public void startUdpServer() { for(int ulIdx = 0; ulIdx < 84; ulIdx++){ LocatorData[ulIdx]=0; } // Fill in the header for the response data. LocatorData[0] = TAG_STATUS; LocatorData[1] = 84; LocatorData[2] = CMD_DISCOVER_TARGET; // Save the board type in the response data. LocatorData[3] = (byte) 0xAC; // Save the board ID in the response data. LocatorData[4] = (byte) 0x0C; // Save the MAC address. LocatorData[9] = DeviceConfig.getInstance().macaddr[0]; LocatorData[10] = DeviceConfig.getInstance().macaddr[1]; LocatorData[11] = DeviceConfig.getInstance().macaddr[2]; LocatorData[12] = DeviceConfig.getInstance().macaddr[3]; LocatorData[13] = DeviceConfig.getInstance().macaddr[4]; LocatorData[14] = DeviceConfig.getInstance().macaddr[5]; // Save the firmware version number in the response data. LocatorData[15] = (byte) ((DeviceConfig.getInstance().lport) & 0xff); LocatorData[16] = (byte) ((DeviceConfig.getInstance().lport >> 8) & 0xff); LocatorData[17] = (byte) ((DeviceConfig.getInstance().lport >> 16) & 0xff); LocatorData[18] = (byte) ((DeviceConfig.getInstance().lport >> 24) & 0xff); String szDevSn=String.format("%02X%02X%02X%02X", DeviceConfig.getInstance().devsn[0], DeviceConfig.getInstance().devsn[1], DeviceConfig.getInstance().devsn[2], DeviceConfig.getInstance().devsn[3]); String szDevMac=String.format("%02X%02X%02X%02X%02X%02X", DeviceConfig.getInstance().macaddr[0], DeviceConfig.getInstance().macaddr[1], DeviceConfig.getInstance().macaddr[2], DeviceConfig.getInstance().macaddr[3], DeviceConfig.getInstance().macaddr[4], DeviceConfig.getInstance().macaddr[5]); String szTmp="|"; byte[] szTitle=new byte[64]; try { byte[] p1 = DeviceConfig.getInstance().devname.getBytes("gb2312"); byte[] p2=szDevSn.getBytes("gb2312"); byte[] p3=szDevMac.getBytes("gb2312"); byte[] p4=szTmp.getBytes("gb2312"); System.arraycopy(p1,0, szTitle,0,p1.length); System.arraycopy(p4,0, szTitle,p1.length,p4.length); System.arraycopy(p2,0, szTitle,p1.length+p4.length,p2.length); System.arraycopy(p4,0, szTitle,p1.length+p4.length+p2.length,p4.length); System.arraycopy(p3,0, szTitle,p1.length+p4.length+p2.length+p4.length,p3.length); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // Copy the application title string into the response data. for(int ulCount = 0; ulCount < 64; ulCount++){ LocatorData[ulCount + 19] = szTitle[ulCount]; } new Thread(){ @Override public void run() { try{ //InetAddress serverAddr = InetAddress.getByName("127.0.0.1"); DatagramSocket ds = new DatagramSocket(1024); ShowMessage("Start UDP Server ..."); while(true){ byte[] revdata = new byte[128]; DatagramPacket dpr = new DatagramPacket(revdata,128); ds.receive(dpr); if((revdata[0] == TAG_CMD) && (revdata[1] == 4) && (revdata[2] == CMD_DISCOVER_TARGET) && (revdata[3] == (byte)((0 - TAG_CMD - 4 - CMD_DISCOVER_TARGET) & 0xff))){ ShowMessage("Finder..."); SystemClock.sleep(100); InetAddress addr = dpr.getAddress(); int port = dpr.getPort(); DatagramPacket dps = new DatagramPacket(LocatorData,LocatorData.length,addr,port); ds.send(dps); }else{ //InetAddress addr = dpr.getAddress(); //int port = dpr.getPort(); //DatagramPacket dps = new DatagramPacket(LocatorData,LocatorData.length,addr,port); //ds.send(dps); } } //ds.close(); }catch (Exception e){ ShowMessage("UDP Error"); } } }.start(); } }
package task2; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class RadixSort { public static int read(int[] Anum ,String file) throws FileNotFoundException { Scanner input = new Scanner(new File(file)); int counter = 0; while (input.hasNextInt()) { Anum[counter] = input.nextInt(); counter++; } return counter; } public static void sort(int[]num,int count, int width) { for (int i = 0; i <width ; i++) { radixSingle(num, i, count); } } public static void radixSingle(int[]num, int position, int count) { int numItems = num.length; int[]countArr = new int[count]; for (int value : num) { countArr[getD(position,value,count)]++; } for (int j = 1; j < count ; j++) { countArr[j] += countArr[j - 1]; } int[]temp = new int[numItems]; for (int index = numItems - 1; index >= 0 ; index--) { temp[--countArr[getD(position,num[index], count)]] = num[index]; } for (int index = 0; index < numItems; index++) { num[index] = temp[index]; } } public static int getD(int positon, int value, int radix) { return value/(int) Math.pow(10,positon) % radix; } public static void store(int[]numArrray, int count, String fileName) throws IOException { PrintWriter writer = new PrintWriter(fileName); for (int i = 0; i < count; i++) { writer.write(numArrray[i]+"\n"); } writer.close(); } }
package by.epam.kooks.action.post; import by.epam.kooks.action.constants.Constants; import by.epam.kooks.action.manager.Action; import by.epam.kooks.entity.Customer; import by.epam.kooks.util.Encoder; import by.epam.kooks.action.manager.ActionResult; import by.epam.kooks.service.CustomerService; import by.epam.kooks.service.exception.ServiceException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Action class , allows customer and admin edit password. * * @author Eugene Kooks */ public class PasswordEditAction implements Action { private static final Logger log = LogManager.getLogger(PasswordEditAction.class); private boolean wrong = false; @Override public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) { CustomerService customerService = new CustomerService(); Customer customer = new Customer(); Properties properties = new Properties(); HttpSession session = req.getSession(); int id = (int) session.getAttribute(Constants.ATT_CUSTOMER_ID); try { properties.load(RegisterAction.class.getClassLoader().getResourceAsStream(Constants.VALIDATION_PROPERTIES)); } catch (IOException e) { log.error("Can't load validation properties.", e); } String oldPassword = req.getParameter(Constants.OLD_PASSWORD); String password = req.getParameter(Constants.PASSWORD); String passwordConfirm = req.getParameter(Constants.PASSWORD_CONFIRM); try { customer = customerService.findCustomerById(id); if (!customer.getPassword().equals(Encoder.toEncode(oldPassword))) { wrong = true; log.debug("Customer by id = {} can't change oldPassword", customer.getId()); req.setAttribute(Constants.OLD_PASSWORD_ERROR, true); } else { if (customer.getPassword().equals(Encoder.toEncode(password))) { wrong = true; log.debug("Customer by id = {} can't confirm new password", customer.getId()); req.setAttribute(Constants.MATCH_PASSWORD_ERROR, true); } } if (!password.equals(passwordConfirm)) { log.debug("Customer by id = {} can't confirm password", customer.getId()); wrong = true; req.setAttribute(Constants.PASSWORD_ERROR, true); } else { checkParamValid(Constants.PASSWORD, password, properties.getProperty(Constants.PASSWORD_VALID), req); } customer.setPassword(Encoder.toEncode(password)); } catch (ServiceException e) { e.printStackTrace(); } if (wrong) { wrong = false; log.debug("Wrong! Referring back again {} page | customer id = {}", Constants.PROFILE_EDIT, customer.getId()); return new ActionResult(Constants.PROFILE_EDIT); } else { try { customerService.updateCustomer(customer); } catch (ServiceException e) { log.info("Can't update customer password {}", e); } } return new ActionResult(Constants.ACCOUNT, true); } private void checkParamValid(String paramName, String paramValue, String validator, HttpServletRequest request) { Pattern pattern = Pattern.compile(validator); Matcher matcher = pattern.matcher(paramValue); if (!matcher.matches()) { request.setAttribute(paramName + Constants.ERROR, true); wrong = true; } } }
package br.com.clean.arch.controller.rest.impl; import br.com.clean.arch.provider.entity.mapper.ResultHistoryMapper; import br.com.clean.arch.provider.repository.ResultHistoryRepository; import br.com.clean.arch.controller.rest.SumController; import br.com.clean.arch.domain.dto.GivenParamDTO; import br.com.clean.arch.domain.entity.ResultHistoryEntity; import br.com.clean.arch.domain.usecase.sum.SumUseCase; import io.micronaut.http.HttpResponse; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Post; import io.micronaut.http.annotation.RequestAttribute; import javax.inject.Inject; import javax.inject.Named; @Controller(value = "/sum") class SumControllerImpl implements SumController { private final @Named("Implementation") SumUseCase sumUseCase; private final ResultHistoryRepository resultHistoryRepository; private final ResultHistoryMapper mapper; @Inject SumControllerImpl( SumUseCase sumUseCase, ResultHistoryRepository resultHistoryRepository, ResultHistoryMapper mapper) { this.sumUseCase = sumUseCase; this.resultHistoryRepository = resultHistoryRepository; this.mapper = mapper; } @Override @Post public HttpResponse<ResultHistoryEntity> calculateSum( @RequestAttribute("X-first-param") GivenParamDTO firstParam, @RequestAttribute("X-second-param") GivenParamDTO secondParam, @RequestAttribute("X-other-param") GivenParamDTO... otherParam) { final var resultHistoryValue = sumUseCase.calculate(firstParam, secondParam, otherParam); final var map = mapper.map(resultHistoryValue); resultHistoryRepository.save(map); return HttpResponse.created(null); } }
package com.DeltaFish.pojo; import java.util.ArrayList; import java.util.List; public class BookExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public BookExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andOwnerIdIsNull() { addCriterion("owner_id is null"); return (Criteria) this; } public Criteria andOwnerIdIsNotNull() { addCriterion("owner_id is not null"); return (Criteria) this; } public Criteria andOwnerIdEqualTo(String value) { addCriterion("owner_id =", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdNotEqualTo(String value) { addCriterion("owner_id <>", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdGreaterThan(String value) { addCriterion("owner_id >", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdGreaterThanOrEqualTo(String value) { addCriterion("owner_id >=", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdLessThan(String value) { addCriterion("owner_id <", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdLessThanOrEqualTo(String value) { addCriterion("owner_id <=", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdLike(String value) { addCriterion("owner_id like", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdNotLike(String value) { addCriterion("owner_id not like", value, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdIn(List<String> values) { addCriterion("owner_id in", values, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdNotIn(List<String> values) { addCriterion("owner_id not in", values, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdBetween(String value1, String value2) { addCriterion("owner_id between", value1, value2, "ownerId"); return (Criteria) this; } public Criteria andOwnerIdNotBetween(String value1, String value2) { addCriterion("owner_id not between", value1, value2, "ownerId"); return (Criteria) this; } public Criteria andBookNameIsNull() { addCriterion("book_name is null"); return (Criteria) this; } public Criteria andBookNameIsNotNull() { addCriterion("book_name is not null"); return (Criteria) this; } public Criteria andBookNameEqualTo(String value) { addCriterion("book_name =", value, "bookName"); return (Criteria) this; } public Criteria andBookNameNotEqualTo(String value) { addCriterion("book_name <>", value, "bookName"); return (Criteria) this; } public Criteria andBookNameGreaterThan(String value) { addCriterion("book_name >", value, "bookName"); return (Criteria) this; } public Criteria andBookNameGreaterThanOrEqualTo(String value) { addCriterion("book_name >=", value, "bookName"); return (Criteria) this; } public Criteria andBookNameLessThan(String value) { addCriterion("book_name <", value, "bookName"); return (Criteria) this; } public Criteria andBookNameLessThanOrEqualTo(String value) { addCriterion("book_name <=", value, "bookName"); return (Criteria) this; } public Criteria andBookNameLike(String value) { addCriterion("book_name like", value, "bookName"); return (Criteria) this; } public Criteria andBookNameNotLike(String value) { addCriterion("book_name not like", value, "bookName"); return (Criteria) this; } public Criteria andBookNameIn(List<String> values) { addCriterion("book_name in", values, "bookName"); return (Criteria) this; } public Criteria andBookNameNotIn(List<String> values) { addCriterion("book_name not in", values, "bookName"); return (Criteria) this; } public Criteria andBookNameBetween(String value1, String value2) { addCriterion("book_name between", value1, value2, "bookName"); return (Criteria) this; } public Criteria andBookNameNotBetween(String value1, String value2) { addCriterion("book_name not between", value1, value2, "bookName"); return (Criteria) this; } public Criteria andEditionIsNull() { addCriterion("edition is null"); return (Criteria) this; } public Criteria andEditionIsNotNull() { addCriterion("edition is not null"); return (Criteria) this; } public Criteria andEditionEqualTo(String value) { addCriterion("edition =", value, "edition"); return (Criteria) this; } public Criteria andEditionNotEqualTo(String value) { addCriterion("edition <>", value, "edition"); return (Criteria) this; } public Criteria andEditionGreaterThan(String value) { addCriterion("edition >", value, "edition"); return (Criteria) this; } public Criteria andEditionGreaterThanOrEqualTo(String value) { addCriterion("edition >=", value, "edition"); return (Criteria) this; } public Criteria andEditionLessThan(String value) { addCriterion("edition <", value, "edition"); return (Criteria) this; } public Criteria andEditionLessThanOrEqualTo(String value) { addCriterion("edition <=", value, "edition"); return (Criteria) this; } public Criteria andEditionLike(String value) { addCriterion("edition like", value, "edition"); return (Criteria) this; } public Criteria andEditionNotLike(String value) { addCriterion("edition not like", value, "edition"); return (Criteria) this; } public Criteria andEditionIn(List<String> values) { addCriterion("edition in", values, "edition"); return (Criteria) this; } public Criteria andEditionNotIn(List<String> values) { addCriterion("edition not in", values, "edition"); return (Criteria) this; } public Criteria andEditionBetween(String value1, String value2) { addCriterion("edition between", value1, value2, "edition"); return (Criteria) this; } public Criteria andEditionNotBetween(String value1, String value2) { addCriterion("edition not between", value1, value2, "edition"); return (Criteria) this; } public Criteria andAuthorIsNull() { addCriterion("author is null"); return (Criteria) this; } public Criteria andAuthorIsNotNull() { addCriterion("author is not null"); return (Criteria) this; } public Criteria andAuthorEqualTo(String value) { addCriterion("author =", value, "author"); return (Criteria) this; } public Criteria andAuthorNotEqualTo(String value) { addCriterion("author <>", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThan(String value) { addCriterion("author >", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThanOrEqualTo(String value) { addCriterion("author >=", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThan(String value) { addCriterion("author <", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThanOrEqualTo(String value) { addCriterion("author <=", value, "author"); return (Criteria) this; } public Criteria andAuthorLike(String value) { addCriterion("author like", value, "author"); return (Criteria) this; } public Criteria andAuthorNotLike(String value) { addCriterion("author not like", value, "author"); return (Criteria) this; } public Criteria andAuthorIn(List<String> values) { addCriterion("author in", values, "author"); return (Criteria) this; } public Criteria andAuthorNotIn(List<String> values) { addCriterion("author not in", values, "author"); return (Criteria) this; } public Criteria andAuthorBetween(String value1, String value2) { addCriterion("author between", value1, value2, "author"); return (Criteria) this; } public Criteria andAuthorNotBetween(String value1, String value2) { addCriterion("author not between", value1, value2, "author"); return (Criteria) this; } public Criteria andPressIsNull() { addCriterion("press is null"); return (Criteria) this; } public Criteria andPressIsNotNull() { addCriterion("press is not null"); return (Criteria) this; } public Criteria andPressEqualTo(String value) { addCriterion("press =", value, "press"); return (Criteria) this; } public Criteria andPressNotEqualTo(String value) { addCriterion("press <>", value, "press"); return (Criteria) this; } public Criteria andPressGreaterThan(String value) { addCriterion("press >", value, "press"); return (Criteria) this; } public Criteria andPressGreaterThanOrEqualTo(String value) { addCriterion("press >=", value, "press"); return (Criteria) this; } public Criteria andPressLessThan(String value) { addCriterion("press <", value, "press"); return (Criteria) this; } public Criteria andPressLessThanOrEqualTo(String value) { addCriterion("press <=", value, "press"); return (Criteria) this; } public Criteria andPressLike(String value) { addCriterion("press like", value, "press"); return (Criteria) this; } public Criteria andPressNotLike(String value) { addCriterion("press not like", value, "press"); return (Criteria) this; } public Criteria andPressIn(List<String> values) { addCriterion("press in", values, "press"); return (Criteria) this; } public Criteria andPressNotIn(List<String> values) { addCriterion("press not in", values, "press"); return (Criteria) this; } public Criteria andPressBetween(String value1, String value2) { addCriterion("press between", value1, value2, "press"); return (Criteria) this; } public Criteria andPressNotBetween(String value1, String value2) { addCriterion("press not between", value1, value2, "press"); return (Criteria) this; } public Criteria andIntroductionIsNull() { addCriterion("introduction is null"); return (Criteria) this; } public Criteria andIntroductionIsNotNull() { addCriterion("introduction is not null"); return (Criteria) this; } public Criteria andIntroductionEqualTo(String value) { addCriterion("introduction =", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionNotEqualTo(String value) { addCriterion("introduction <>", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionGreaterThan(String value) { addCriterion("introduction >", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionGreaterThanOrEqualTo(String value) { addCriterion("introduction >=", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionLessThan(String value) { addCriterion("introduction <", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionLessThanOrEqualTo(String value) { addCriterion("introduction <=", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionLike(String value) { addCriterion("introduction like", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionNotLike(String value) { addCriterion("introduction not like", value, "introduction"); return (Criteria) this; } public Criteria andIntroductionIn(List<String> values) { addCriterion("introduction in", values, "introduction"); return (Criteria) this; } public Criteria andIntroductionNotIn(List<String> values) { addCriterion("introduction not in", values, "introduction"); return (Criteria) this; } public Criteria andIntroductionBetween(String value1, String value2) { addCriterion("introduction between", value1, value2, "introduction"); return (Criteria) this; } public Criteria andIntroductionNotBetween(String value1, String value2) { addCriterion("introduction not between", value1, value2, "introduction"); return (Criteria) this; } public Criteria andOperationIsNull() { addCriterion("operation is null"); return (Criteria) this; } public Criteria andOperationIsNotNull() { addCriterion("operation is not null"); return (Criteria) this; } public Criteria andOperationEqualTo(String value) { addCriterion("operation =", value, "operation"); return (Criteria) this; } public Criteria andOperationNotEqualTo(String value) { addCriterion("operation <>", value, "operation"); return (Criteria) this; } public Criteria andOperationGreaterThan(String value) { addCriterion("operation >", value, "operation"); return (Criteria) this; } public Criteria andOperationGreaterThanOrEqualTo(String value) { addCriterion("operation >=", value, "operation"); return (Criteria) this; } public Criteria andOperationLessThan(String value) { addCriterion("operation <", value, "operation"); return (Criteria) this; } public Criteria andOperationLessThanOrEqualTo(String value) { addCriterion("operation <=", value, "operation"); return (Criteria) this; } public Criteria andOperationLike(String value) { addCriterion("operation like", value, "operation"); return (Criteria) this; } public Criteria andOperationNotLike(String value) { addCriterion("operation not like", value, "operation"); return (Criteria) this; } public Criteria andOperationIn(List<String> values) { addCriterion("operation in", values, "operation"); return (Criteria) this; } public Criteria andOperationNotIn(List<String> values) { addCriterion("operation not in", values, "operation"); return (Criteria) this; } public Criteria andOperationBetween(String value1, String value2) { addCriterion("operation between", value1, value2, "operation"); return (Criteria) this; } public Criteria andOperationNotBetween(String value1, String value2) { addCriterion("operation not between", value1, value2, "operation"); return (Criteria) this; } public Criteria andLinkIsNull() { addCriterion("link is null"); return (Criteria) this; } public Criteria andLinkIsNotNull() { addCriterion("link is not null"); return (Criteria) this; } public Criteria andLinkEqualTo(String value) { addCriterion("link =", value, "link"); return (Criteria) this; } public Criteria andLinkNotEqualTo(String value) { addCriterion("link <>", value, "link"); return (Criteria) this; } public Criteria andLinkGreaterThan(String value) { addCriterion("link >", value, "link"); return (Criteria) this; } public Criteria andLinkGreaterThanOrEqualTo(String value) { addCriterion("link >=", value, "link"); return (Criteria) this; } public Criteria andLinkLessThan(String value) { addCriterion("link <", value, "link"); return (Criteria) this; } public Criteria andLinkLessThanOrEqualTo(String value) { addCriterion("link <=", value, "link"); return (Criteria) this; } public Criteria andLinkLike(String value) { addCriterion("link like", value, "link"); return (Criteria) this; } public Criteria andLinkNotLike(String value) { addCriterion("link not like", value, "link"); return (Criteria) this; } public Criteria andLinkIn(List<String> values) { addCriterion("link in", values, "link"); return (Criteria) this; } public Criteria andLinkNotIn(List<String> values) { addCriterion("link not in", values, "link"); return (Criteria) this; } public Criteria andLinkBetween(String value1, String value2) { addCriterion("link between", value1, value2, "link"); return (Criteria) this; } public Criteria andLinkNotBetween(String value1, String value2) { addCriterion("link not between", value1, value2, "link"); return (Criteria) this; } public Criteria andCommentIsNull() { addCriterion("comment is null"); return (Criteria) this; } public Criteria andCommentIsNotNull() { addCriterion("comment is not null"); return (Criteria) this; } public Criteria andCommentEqualTo(String value) { addCriterion("comment =", value, "comment"); return (Criteria) this; } public Criteria andCommentNotEqualTo(String value) { addCriterion("comment <>", value, "comment"); return (Criteria) this; } public Criteria andCommentGreaterThan(String value) { addCriterion("comment >", value, "comment"); return (Criteria) this; } public Criteria andCommentGreaterThanOrEqualTo(String value) { addCriterion("comment >=", value, "comment"); return (Criteria) this; } public Criteria andCommentLessThan(String value) { addCriterion("comment <", value, "comment"); return (Criteria) this; } public Criteria andCommentLessThanOrEqualTo(String value) { addCriterion("comment <=", value, "comment"); return (Criteria) this; } public Criteria andCommentLike(String value) { addCriterion("comment like", value, "comment"); return (Criteria) this; } public Criteria andCommentNotLike(String value) { addCriterion("comment not like", value, "comment"); return (Criteria) this; } public Criteria andCommentIn(List<String> values) { addCriterion("comment in", values, "comment"); return (Criteria) this; } public Criteria andCommentNotIn(List<String> values) { addCriterion("comment not in", values, "comment"); return (Criteria) this; } public Criteria andCommentBetween(String value1, String value2) { addCriterion("comment between", value1, value2, "comment"); return (Criteria) this; } public Criteria andCommentNotBetween(String value1, String value2) { addCriterion("comment not between", value1, value2, "comment"); return (Criteria) this; } public Criteria andBookIdIsNull() { addCriterion("book_id is null"); return (Criteria) this; } public Criteria andBookIdIsNotNull() { addCriterion("book_id is not null"); return (Criteria) this; } public Criteria andBookIdEqualTo(String value) { addCriterion("book_id =", value, "bookId"); return (Criteria) this; } public Criteria andBookIdNotEqualTo(String value) { addCriterion("book_id <>", value, "bookId"); return (Criteria) this; } public Criteria andBookIdGreaterThan(String value) { addCriterion("book_id >", value, "bookId"); return (Criteria) this; } public Criteria andBookIdGreaterThanOrEqualTo(String value) { addCriterion("book_id >=", value, "bookId"); return (Criteria) this; } public Criteria andBookIdLessThan(String value) { addCriterion("book_id <", value, "bookId"); return (Criteria) this; } public Criteria andBookIdLessThanOrEqualTo(String value) { addCriterion("book_id <=", value, "bookId"); return (Criteria) this; } public Criteria andBookIdLike(String value) { addCriterion("book_id like", value, "bookId"); return (Criteria) this; } public Criteria andBookIdNotLike(String value) { addCriterion("book_id not like", value, "bookId"); return (Criteria) this; } public Criteria andBookIdIn(List<String> values) { addCriterion("book_id in", values, "bookId"); return (Criteria) this; } public Criteria andBookIdNotIn(List<String> values) { addCriterion("book_id not in", values, "bookId"); return (Criteria) this; } public Criteria andBookIdBetween(String value1, String value2) { addCriterion("book_id between", value1, value2, "bookId"); return (Criteria) this; } public Criteria andBookIdNotBetween(String value1, String value2) { addCriterion("book_id not between", value1, value2, "bookId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package pl.edu.pjatk.System.zarzadzania.zamowieniami.model; import javax.persistence.*; @Entity @Table(name = "onOrderMaterial") public class OnOrderMaterial { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int positionId; @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) @JoinColumn(name = "materialId") private Material material; @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) @JoinColumn(name = "materialOrderId") private MaterialOrder materialOrder; @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) @JoinColumn(name = "serviceOrderId") private ServiceOrder serviceOrder; @Column(name = "quantity") private double quantity; public OnOrderMaterial(int positionId, Material material, MaterialOrder materialOrder, ServiceOrder serviceOrder, double quantity) { this.positionId = positionId; this.material = material; this.materialOrder = materialOrder; this.serviceOrder = serviceOrder; this.quantity = quantity; } public int getPositionId() { return positionId; } public void setPositionId(int positionId) { this.positionId = positionId; } public Material getMaterial() { return material; } public void setMaterial(Material material) { this.material = material; } public MaterialOrder getMaterialOrder() { return materialOrder; } public void setMaterialOrder(MaterialOrder materialOrder) { this.materialOrder = materialOrder; } public ServiceOrder getServiceOrder() { return serviceOrder; } public void setServiceOrder(ServiceOrder serviceOrder) { this.serviceOrder = serviceOrder; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } }
package my.datastrusture.array; /// Reverse the element public class ReverseArrayTwoPointerTechnique { public static void main(String[] args) { int [] a = {1,2,3,4}; reverse(a, a.length); System.out.println(a); for(int i=0; i<a.length ; ++i) { System.out.println(a[i]); } } public static void reverse(int[] v, int N) { int i =0; int j = N-1; while (i<j) { swap(v,i,j); i++; j--; } } private static void swap(int[] v, int i, int j) { int tmp = v[i]; v[i] = v[j]; v[j]= tmp; } }
package pl.basistam.users; import pl.basistam.login.ActiveUsers; import pl.basistam.login.UsersRepository; 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 java.io.IOException; @WebServlet("/users") public class UsersController extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/users.jsp").forward(request,response); } }
package org.study.adim.controller; import java.util.List; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.study.admin.CinemaDAO; import org.study.admin.CinemaRoomDAO; import org.study.admin.CinemaRoomVO; import org.study.admin.CinemaVO; @Controller @RequestMapping("cinema") public class cinemaController { Logger log = LoggerFactory.getLogger(cinemaController.class); @Autowired CinemaDAO cinemaDAO; @Autowired CinemaRoomDAO cinemaRoomDAO; /* admin - 지점등록, 상영관 등록 */ /* 지점등록 메뉴*/ @GetMapping("cinemaRegist") public String cinemaRegist(Model model) { model.addAttribute("cinemaVO", new CinemaVO()); model.addAttribute("a_center", "cinema/cinemaRegist"); return "a_home"; } /* 지점등록 */ @PostMapping("cinemaRegist") public String movieRegDone(CinemaVO cinemaVO, Model model) throws Exception { cinemaDAO.insert(cinemaVO); return "redirect:http://localhost:8080/springteam04/cinema/cinemaList"; } /* 상영관 등록 메뉴*/ /* 지점 리스트 보여주기 */ @GetMapping("cinemaList") public String cinemaList(Model model) throws Exception { List<CinemaVO> cinemaList = cinemaDAO.selectAll(); model.addAttribute("cinemaList", cinemaList); model.addAttribute("a_center", "cinema/cinemaList"); return "a_home"; } /* 상영관 등록화면으로 가기 */ @PostMapping("cinemaInfoRegist") public String cinemaInfoRegist(CinemaRoomVO cinemaRoomVO, Model model, HttpServletRequest request) throws Exception { String code=request.getParameter("cinema_code"); int cinema_code=Integer.parseInt(code); log.info("cinema_code : "+cinema_code); CinemaVO list = cinemaDAO.selectByCode(cinema_code); model.addAttribute("cinemaVO", list); model.addAttribute("a_center", "cinema/cinemaInfoRegist"); return "a_home"; } /* 상영관 등록 */ @PostMapping("cinemaRoomRegist") public String cinemaRoomRegist(CinemaRoomVO cinemaRoomVO, Model model,HttpServletRequest request) throws Exception { /* log.info("memberVo:"+memberVO.getEmail()); */ String code=request.getParameter("cinema_code"); int cinema_code=Integer.parseInt(code); cinemaRoomDAO.insertRoom(cinemaRoomVO); return "redirect:http://localhost:8080/springteam04/cinema/cinemaList"; } /* 상영관 삭제 */ @PostMapping("cinemaInfoRoomDelete") public String cinemaInfoRoomDelete(CinemaRoomVO cinemaRoomVO, Model model, HttpServletRequest request) throws Exception { int cinemaroom_code = Integer.parseInt(request.getParameter("cinemaroom_code")); System.out.println("cinemaInfoRoomDelete controller - cinemaroom_code : "+cinemaroom_code); CinemaRoomVO cinemaRoom = new CinemaRoomVO(); cinemaRoomDAO.deleCode(cinemaroom_code); model.addAttribute("cinemaRoom", cinemaRoom); return "redirect:cinemaList"; } /* 지점에 상영관 리스트보기 */ @PostMapping("cinemaInfoList") public String cinemaInfoList(Model model,HttpServletRequest request) throws Exception { String code=request.getParameter("cinema_code"); int cinema_code=Integer.parseInt(code); List<CinemaRoomVO> roomList = cinemaRoomDAO.selectCode(cinema_code); model.addAttribute("roomList", roomList); model.addAttribute("a_center", "cinema/cinemaInfoList"); return "a_home"; } /*지점 삭제*/ @PostMapping("cinemaInfoDelete") public String cinemaInfoDelete(CinemaRoomVO cinemaRoomVO, Model model, HttpServletRequest request) throws Exception { String code=request.getParameter("cinema_code"); int cinema_code=Integer.parseInt(code); CinemaVO cinemaVO = new CinemaVO(); cinemaDAO.delete(cinema_code); // 지점 삭제 cinemaRoomDAO.deleCineCode(cinema_code); // 지점에 있는 상영관 삭제 model.addAttribute("cinemaVO", cinemaVO); return "redirect:cinemaList"; } }
package ru.gurps.generator.desktop.controller.tables; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.control.cell.TextFieldTableCell; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import ru.gurps.generator.desktop.Main; import ru.gurps.generator.desktop.controller.helpers.AbstractController; import ru.gurps.generator.desktop.models.rules.Cultura; import ru.gurps.generator.desktop.models.characters.CharactersCultura; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class CulturasController extends AbstractController { public TableView<Cultura> tableView; public TableColumn<Cultura, String> nameColumn; public TableColumn<Cultura, String> costColumn; public TableColumn<Cultura, Boolean> characterColumn; public TableColumn<Cultura, Boolean> dbColumn; public TextField nameText; public TextField costText; public Button addButton; public Button updateFromServer; public Button sedToServer; private Cultura cultura; @FXML private void initialize() { nameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); costColumn.setCellValueFactory(new PropertyValueFactory<>("cost")); costColumn.setOnEditCommit(event -> { if(event.getNewValue().equals("0") || !event.getNewValue().matches("\\d+")) return; Cultura cultura = event.getTableView().getItems().get(event.getTablePosition().getRow()); if(cultura.cost != Integer.parseInt(event.getNewValue())) cultura.cost = Integer.parseInt(event.getNewValue()); }); costColumn.setCellFactory(TextFieldTableCell.forTableColumn()); characterColumn.setCellValueFactory(new PropertyValueFactory<>("add")); characterColumn.setCellFactory(p -> new CulturasCharacterButtonCell()); dbColumn.setCellValueFactory(p -> new SimpleBooleanProperty(true)); dbColumn.setCellFactory(p -> new CulturasDbButtonCell()); setCulturas(); tableView.setPlaceholder(new Label(Main.locale.getString("cultures_not_found"))); tableView.setEditable(true); nameText.textProperty().addListener((observable, oldValue, newValue) -> { if(newValue.equals("")) return; addButton.setDisable(false); }); addButton.setOnAction(event -> { String name = nameText.getText().substring(0, 1).toUpperCase() + nameText.getText().substring(1); cultura = (Cultura) new Cultura(name).create(); cultura.cost = Integer.parseInt(costText.getText()); cultura.add = true; new CharactersCultura(character.id, cultura.id, cultura.cost).create(); if(cultura.cost != 0) setCurrentPoints(Integer.parseInt(character.currentPoints) + cultura.cost); setCulturas(); nameText.setText(""); addButton.setDisable(true); sedToServer.setDisable(false); }); updateFromServer.setOnAction(event -> updateFromServer()); sedToServer.setOnAction(event -> sedToServer(cultura.name)); } private void updateFromServer() { String repose = getPage("data/culturas", 1); if (repose.equals("")) return; JsonObject json = new JsonParser().parse(repose).getAsJsonObject(); boolean next = newCulturas(json); HashMap<String, Object> pages = pages(json.getAsJsonObject("pagination")); if (next) { while (next && (Boolean) pages.get("next")) { json = new JsonParser().parse(getPage("culturas", (int) pages.get("page") + 1)).getAsJsonObject(); pages = pages(json.getAsJsonObject("pagination")); next = newCulturas(json); } } setCulturas(); } private boolean newCulturas(JsonObject json) { if (json.get("culturas").getAsJsonArray().size() == 0) return false; for (JsonElement cultura : json.get("culturas").getAsJsonArray()) { String name = cultura.getAsJsonObject().get("name").getAsString(); if (((Cultura) new Cultura().find_by("name", name)).id != null) return false; new Cultura(name).create(); } return true; } private void sedToServer(String name) { sedToServer.setDisable(true); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("cultura", name)); HttpResponse httpResponse = sendRequest("data/culturas", params); if(httpResponse == null) return; if (httpResponse.getStatusLine().getStatusCode() == 204) return; try { HttpEntity entity = httpResponse.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader((entity.getContent()))); String response = br.readLine(); JsonElement error = new JsonParser().parse(response).getAsJsonObject().get("error"); System.out.println(error); } catch (IOException e) { e.printStackTrace(); } } private void setCulturas() { ObservableList<Cultura> culturas = FXCollections.observableArrayList(); for (Object object : new Cultura().all()) { Cultura cultura = (Cultura) object; for (Cultura characterCultura : character.cultures()) { if (cultura.id == characterCultura.id) { cultura.cost = characterCultura.cost; characterCultura.add = true; } } culturas.add(cultura); } tableView.setItems(culturas); } private class CulturasCharacterButtonCell extends TableCell<Cultura, Boolean> { Button addButton = new Button(Main.locale.getString("add")); Button removeButton = new Button(Main.locale.getString("remove")); CulturasCharacterButtonCell() { addButton.setOnAction(t -> { Cultura cultura = (Cultura) getTableRow().getItem(); new CharactersCultura(character.id, cultura.id, cultura.cost).create(); cultura.add = true; setCurrentPoints(Integer.parseInt(character.currentPoints) + cultura.cost); setGraphic(removeButton); }); removeButton.setOnAction(t -> { Cultura cultura = (Cultura) getTableRow().getItem(); new CharactersCultura().find_by("culturaId", cultura.id).delete(); cultura.add = false; setCurrentPoints(Integer.parseInt(character.currentPoints) - cultura.cost); setGraphic(addButton); }); } @Override protected void updateItem(Boolean t, boolean empty) { super.updateItem(t, empty); if(getGraphic() != null && t == null) setGraphic(null); if(empty){ setGraphic(null); return; } Cultura cultura = (Cultura) getTableRow().getItem(); if(cultura == null) return; setGraphic(cultura.add ? removeButton : addButton); } } private class CulturasDbButtonCell extends TableCell<Cultura, Boolean> { Button removeButton = new Button(Main.locale.getString("remove")); CulturasDbButtonCell() { removeButton.setOnAction(t -> { Cultura cultura = (Cultura) getTableRow().getItem(); new CharactersCultura().delete_all(new CharactersCultura().where("culturaId", cultura.id)); cultura.delete(); setCulturas(); }); } @Override protected void updateItem(Boolean t, boolean empty) { super.updateItem(t, empty); if(getGraphic() != null && t == null) setGraphic(null); if(empty){ setGraphic(null); return; } Cultura cultura = (Cultura) getTableRow().getItem(); if(cultura == null) return; setGraphic(removeButton); } } }
package cn.bakon.web; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.bakon.WebApplication; import cn.bakon.domain.EquipmentStatusRecord; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.util.Date; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(WebApplication.class) public class EquipmentStatusRecordRepositoryTest { @Autowired EquipmentStatusRecordRepository repository; @Test public void findAll() { this.repository.save(new EquipmentStatusRecord("1W01", "W", "127.0.0.1", 1, new Date(), "+80", "+-80")); this.repository.save(new EquipmentStatusRecord("1W01", "W", "127.0.0.1", 1, new Date(), "+80", "+-80")); Page<EquipmentStatusRecord> records = this.repository.findAll(new PageRequest(0, 10)); assertThat(records.getTotalElements(), is(equalTo(2L))); } }
package com.apap.igd.service; import java.util.List; import com.apap.igd.model.DetailPenangananModel; import com.apap.igd.model.JenisPenangananModel; import com.apap.igd.model.PenangananPasienModel; public interface DetailPenangananService { DetailPenangananModel addDetailPenanganan(long idPasien, JenisPenangananModel jenisPenanganan); DetailPenangananModel getDetailPenangananByIdDetail(long idDetail); List<DetailPenangananModel> getDetailPenangananByPenangananPasien(PenangananPasienModel penangananPasien); DetailPenangananModel getDetailPenangananByJenisPenanganan(JenisPenangananModel jenisPenanganan); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.eao.gathering.impl; import org.inbio.ara.eao.gathering.*; import javax.ejb.Stateless; import javax.persistence.Query; import org.inbio.ara.eao.BaseEAOImpl; import org.inbio.ara.persistence.gathering.GatheringObservationProject; /** * * @author esmata */ @Stateless public class GatheringObservationProjectEAOImpl extends BaseEAOImpl<GatheringObservationProject,Long> implements GatheringObservationProjectEAOLocal { //Delete Projects and GatheringID public void deleteByGathering(Long gId) { Query q = em.createQuery("delete from GatheringObservationProject gop " + "where gop.gatheringObservationProjectPK.gatheringObservationId = :gId"); q.setParameter("gId", gId); q.executeUpdate(); em.flush(); } }
package com.unipg.tommaso.apartmentmanager; import android.os.AsyncTask; import android.util.Log; import com.unipg.tommaso.apartmentmanager.roommates.Roommate; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; /** * Created by tommaso on 24/06/2018. */ class SynchUser extends AsyncTask<Roommate, Void, Void>{ private static final String urlString = "http://ec2-34-242-40-246.eu-west-1.compute.amazonaws.com/api/inmate/create.php"; private static final String RequestMethod = "POST"; private static final int READ_TIMEOUT = 15000; private static final int CONNECTION_TIMEOUT = 15000; @Override protected Void doInBackground(Roommate... roommates) { String roommateName = roommates[0].getName(); HttpURLConnection connection; try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(RequestMethod); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.connect(); JSONObject JSONObject = new JSONObject().put("name", roommateName); GenericRESTCall.makeRESTCall(connection,JSONObject); connection.disconnect(); //Create a new buffered reader and String Builder }catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }
package fr.lteconsulting.pomexplorer.commands; import fr.lteconsulting.pomexplorer.*; import fr.lteconsulting.pomexplorer.graph.relation.GAVRelation; import fr.lteconsulting.pomexplorer.graph.relation.Relation; import org.apache.maven.model.Dependency; import org.apache.maven.model.Parent; import org.apache.maven.project.MavenProject; import org.jboss.shrinkwrap.resolver.api.maven.pom.ParsedPomFile; import java.util.*; import java.util.Map.Entry; @Command public class ProjectsCommand extends AbstractCommand { public ProjectsCommand(Application application) { super(application); } @Help("list the session's projects") public void main(WorkingSession session, ILogger log) { log.html("<br/>Project list:<br/>"); List<Project> list = new ArrayList<>(); list.addAll(session.projects().values()); Collections.sort(list, new Comparator<Project>() { @Override public int compare(Project o1, Project o2) { return Tools.gavAlphabeticalComparator.compare(o1.getGav(), o2.getGav()); } }); for (Project project : list) log.html(project + "<br/>"); } @Help("list the session's projects - with details") public void details(WorkingSession session, ILogger log) { details(session, null, log); } @Help("list the session's projects - with details. Parameter is a filter for the GAVs") public void details(WorkingSession session, FilteredGAVs gavFilter, ILogger log) { log.html("Projects details. Filter with: '" + gavFilter.getFilter() + "'<br/>"); for (Project project : session.projects().values()) { ParsedPomFile resolvedPom = project.getResolvedPom(); MavenProject unresolvedProject = project.getUnresolvedPom(); if (!gavFilter.accept(project.getGav())) continue; log.html("file : " + project.getPomFile().getAbsolutePath() + "<br/>"); log.html("gav : " + project.getGav() + " " + resolvedPom.getPackagingType().getId() + ":" + resolvedPom.getPackagingType().getExtension() + ":" + resolvedPom.getPackagingType().getClassifier() + "<br/>"); Parent parent = unresolvedProject.getModel().getParent(); if (parent != null) log.html("parent : " + parent.getId() + ":" + parent.getRelativePath() + "<br/>"); Properties ptties = unresolvedProject.getProperties(); if (ptties != null) { for (Entry<Object, Object> e : ptties.entrySet()) log.html("property : " + e.getKey() + " = " + e.getValue() + "<br/>"); } if (unresolvedProject.getDependencyManagement() != null) { for (Dependency dependency : unresolvedProject.getDependencyManagement().getDependencies()) log.html("dependency management : " + dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + dependency.getVersion() + ":" + dependency.getClassifier() + ":" + dependency.getScope() + "<br/>"); } for (Dependency dependency : unresolvedProject.getDependencies()) log.html("dependency : " + dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + dependency.getVersion() + ":" + dependency.getClassifier() + ":" + dependency.getScope() + "<br/>"); log.html("effective dependencies :<br/>"); Set<GAVRelation<? extends Relation>> directDependencies = effectiveDependencies(session, project.getGav()); directDependencies.forEach(d -> log.html("[" + d.getRelation().getRelationType().shortName() + "] " + d.getTarget() + " " + d.getRelation().toString() + "<br/>")); log.html("<br/>"); } } private Set<GAVRelation<? extends Relation>> effectiveDependencies(WorkingSession session, GAV gav) { HashSet<GAVRelation<? extends Relation>> res = new HashSet<>(); GAV parent = session.graph().parent(gav); if (parent != null) res.addAll(effectiveDependencies(session, parent)); res.addAll(session.graph().dependencies(gav)); res.addAll(session.graph().buildDependencies(gav)); return res; } }
package com.fuchangyao.mapper; import com.fuchangyao.pojo.BoughtGoods; import com.fuchangyao.pojo.BoughtGoodsExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface BoughtGoodsMapper { long countByExample(BoughtGoodsExample example); int deleteByExample(BoughtGoodsExample example); int deleteByPrimaryKey(Integer bid); int insert(BoughtGoods record); int insertSelective(BoughtGoods record); List<BoughtGoods> selectByExample(BoughtGoodsExample example); BoughtGoods selectByPrimaryKey(Integer bid); int updateByExampleSelective(@Param("record") BoughtGoods record, @Param("example") BoughtGoodsExample example); int updateByExample(@Param("record") BoughtGoods record, @Param("example") BoughtGoodsExample example); int updateByPrimaryKeySelective(BoughtGoods record); int updateByPrimaryKey(BoughtGoods record); BoughtGoods findOne(int bid); }
package com.revolut.moneytransfer.config; import com.google.inject.AbstractModule; import com.revolut.moneytransfer.repository.AccountRepository; import com.revolut.moneytransfer.repository.TransactionRepository; import com.revolut.moneytransfer.service.AccountService; import com.revolut.moneytransfer.service.TransactionService; import com.revolut.moneytransfer.service.impl.AccountServiceImpl; import com.revolut.moneytransfer.service.impl.TransactionServiceImpl; import org.jooq.DSLContext; import static com.revolut.moneytransfer.Application.jooq; public class MoneyTransferModule extends AbstractModule { @Override protected void configure() { bind(TransactionService.class).to(TransactionServiceImpl.class); bind(AccountService.class).to(AccountServiceImpl.class); bind(AccountRepository.class); bind(TransactionRepository.class); bind(DSLContext.class).toInstance(jooq); } }
package com.getkhaki.api.bff.domain.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.time.Instant; import java.util.UUID; @Data @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class TimeBlockSummaryDm { UUID organizationId; StatisticsFilterDe filterDe; Long totalSeconds; Integer meetingCount; Instant start; Instant end; Integer numEmployees; Integer numWorkdays; Integer totalInternalMeetingAttendees; Integer totalMeetingAttendees; Long meetingLengthSeconds; Integer numEmployeesOverTimeThreshold; Integer averageMeetingLength; Integer averageStaffTimePerMeeting; }
package com.jgchk.haven.di.module; import android.app.Application; import android.content.Context; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.gson.Gson; import com.jgchk.haven.R; import com.jgchk.haven.data.AppDataManager; import com.jgchk.haven.data.DataManager; import com.jgchk.haven.data.local.db.AppDatabase; import com.jgchk.haven.data.local.db.AppDbHelper; import com.jgchk.haven.data.local.db.DbHelper; import com.jgchk.haven.data.local.location.AppLocationHelper; import com.jgchk.haven.data.local.location.LocationHelper; import com.jgchk.haven.data.local.prefs.AppPreferencesHelper; import com.jgchk.haven.data.local.prefs.PreferencesHelper; import com.jgchk.haven.di.DatabaseInfo; import com.jgchk.haven.di.PreferenceInfo; import com.jgchk.haven.utils.AppConstants; import com.jgchk.haven.utils.rx.AppSchedulerProvider; import com.jgchk.haven.utils.rx.SchedulerProvider; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import static com.jgchk.haven.utils.AppConstants.GSON; @SuppressWarnings("TypeMayBeWeakened") @Module public class AppModule { @Provides @Singleton AppDatabase provideAppDatabase(Context context, @DatabaseInfo String dbName) { return AppDatabase.getInstance(context, dbName); } @Provides @Singleton CalligraphyConfig provideCalligraphyDefaultConfig() { return new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/source-sans-pro/SourceSansPro-Regular.ttf") .setFontAttrId(R.attr.fontPath) .build(); } @Provides @Singleton Context provideContext(Application application) { return application; } @Provides @Singleton DataManager provideDataManager(AppDataManager appDataManager) { return appDataManager; } @Provides @DatabaseInfo String provideDatabaseName() { return AppConstants.DB_NAME; } @Provides @Singleton DbHelper provideDbHelper(AppDbHelper appDbHelper) { return appDbHelper; } @Provides @Singleton PreferencesHelper providePreferencesHelper(AppPreferencesHelper appPreferencesHelper) { return appPreferencesHelper; } @Provides @Singleton Gson provideGson() { return GSON; } @Provides @PreferenceInfo String providePreferenceName() { return AppConstants.PREF_NAME; } @Provides SchedulerProvider provideSchedulerProvider() { return new AppSchedulerProvider(); } @Provides @Singleton FusedLocationProviderClient provideFusedLocationProviderClient(Context context) { return LocationServices.getFusedLocationProviderClient(context); } @Provides @Singleton LocationHelper provideLocationHelper(AppLocationHelper appLocationHelper) { return appLocationHelper; } }
package po; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; public class MatchPO implements Serializable{ private static final long serialVersionUID = 1L; // TODO fileName? private Calendar date;//比赛日期 private HashMap<String, TeamPerformancePO> performances = new HashMap<String, TeamPerformancePO>();//Map:球队缩写->球队表现 private boolean errorFlag = false; public void setErrorFlag(boolean flag){ errorFlag = flag; } public boolean getErrorFlag(){ return errorFlag; } public void setDate(Calendar date) { this.date = date; } public Calendar getDate() { return this.date; } public void putTeamPerformance(String teamAbbr, TeamPerformancePO performancePO) { this.performances.put(teamAbbr, performancePO); } public ArrayList<TeamPerformancePO> getTeamPerformanceList() { return new ArrayList<TeamPerformancePO>(this.performances.values()); } public TeamPerformancePO getPerformanceByTeamAbbr(String abbr) { return performances.get(abbr); } public TeamPerformancePO getHomeTeamPerformancePO(){ for(TeamPerformancePO tp:performances.values()){ if(tp.getIsHome()){ return tp; } } return null; } public TeamPerformancePO getAwayTeamPerformancePO(){ for(TeamPerformancePO tp:performances.values()){ if(!tp.getIsHome()){ return tp; } } return null; } public ArrayList<String> getTeamAbbrs() { return new ArrayList<String>(performances.keySet()); } public PlayerPerformancePO getPlayerPerformance(String playerName) { PlayerPerformancePO playerPerformance = null; for (TeamPerformancePO tp : performances.values()) { if((playerPerformance=tp.getPlayerPerformance(playerName))!=null){ return playerPerformance; } } return playerPerformance; } public String toString(){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String match = "Date:"+sdf.format(getDate().getTime())+",Teams:\n"; ArrayList<String> teams = new ArrayList<String>(performances.keySet()); match+=performances.get(teams.get(0)).toString(); match+=performances.get(teams.get(1)).toString(); return match; } }
package proj4; /** * @author Perry Ogwuche * @version April 16th 2011 */ public class Report extends Document { // Instance variables for the Report class. private String title; /**@Name: Report * @Description: Constructor for the report class, this constructor gets the input given by the user and * uses them to create a report document. It calls the super class'constructor which * handles the input string gotten from the user as the author's name. It then initializes * its instance variables * @param email * @param memo * @param report */ public Report(String author, String title, String textBody, int ID) { super(author,textBody, ID); this.title = title; } /** * Name: getTitle * Description: Gets the tile for the report class * postcondition: Returns the title */ public String getTitle() { return title; } /** * Name: toString * Description: This method invokes the super's toSting method and that already prints the document number * date, and author. It then adds the title and the text body. So when a user creates * a new report document and views it, the order will be unique. * postcondition: Returns the string representation of the user's input. */ public String toString() { return super.toString() + "\nTitle: " + title; } }
package com.mycompany.app.dao; import java.util.List; import com.mycompany.app.account.SavingsAccount; public interface SavingsAccountDAO { SavingsAccount createNewAccount(SavingsAccount account); SavingsAccount getAccountById(int accountNumber); SavingsAccount deleteAccount(int accountNumber); List<SavingsAccount> getAllSavingsAccount(); void updateBalance(int accountNumber, double currentBalance); double checkCurrentBalance(int accountNumber); boolean updateAccountType(SavingsAccount account); SavingsAccount getAccountByName(String accountName); List<SavingsAccount> sortAllSavingsAccount(int choice); }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class MainClass { static WebDriver driver; public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.gecko.driver", "C:\\Users\\Frost\\geckodriver\\drivers\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://mail.ru"); LoginPage loginPage = new LoginPage(driver); loginPage.logginIn("Логин","Пароль"); NewLetter newLetter = new NewLetter(driver); Thread.sleep(10000); newLetter.writingALetter("Почта получателя", "Тема письма", "Само сообщение"); Thread.sleep(5000); driver.quit(); } }
package de.scads.gradoop_service.server.helper.vertex_fusion; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.common.model.impl.id.GradoopIdSet; import org.gradoop.common.model.impl.pojo.Vertex; import org.gradoop.common.model.impl.properties.Properties; import org.gradoop.common.model.impl.properties.PropertyValue; public class CountValues implements VertexFusionFunction, Serializable{ @Override public Vertex apply(ArrayList<Vertex> vertices, String vertexAttribute) { Vertex superVertex = new Vertex(); GradoopId superVertexId = GradoopId.get(); Properties properties = new Properties(); properties.set("count", vertices.size()); GradoopIdSet graphIds = new GradoopIdSet(); graphIds.add(superVertexId); boolean firstElement = true; HashSet<String> labels = new HashSet<String>(); for(Vertex groupItem: vertices) { PropertyValue propertyValue = groupItem.getPropertyValue(vertexAttribute); long vertexAttributeValue = 0; // numerical properties passed as LogicalGraph can be passed as long if(propertyValue.getByteSize() == 9) { vertexAttributeValue = propertyValue.getLong(); } // numerical properties read from disk are likely to be parsed as int else if(propertyValue.getByteSize() == 5) { vertexAttributeValue = (long)propertyValue.getInt(); } labels.add(groupItem.getLabel()); if(firstElement) { superVertex.setId(superVertexId); superVertex.setProperties(properties); superVertex.setGraphIds(graphIds); properties.set("clusterId", vertexAttributeValue); firstElement = false; } } superVertex.setLabel(labels.toString()); return superVertex; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.una.clienteaeropuerto.service; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import org.una.clienteaeropuerto.dto.ImagenesDTO; import org.una.clienteaeropuerto.utils.ConnectionUtils; /** * * @author rache */ public class ImagenService { private final String urlFindAll = "http://localhost:8098/imagenes"; private final String urlCreate = "http://localhost:8098/imagenes/"; public List<ImagenesDTO> getAll() throws InterruptedException, ExecutionException, IOException { return ConnectionUtils.ListFromConnectionImagen(urlFindAll, ImagenesDTO.class); } public void add(ImagenesDTO object) throws InterruptedException, ExecutionException, IOException { ConnectionUtils.ObjectToConnection(urlCreate, object); } public static ImagenService getInstance() { return ImagenesServiceHolder.INSTANCE; } private static class ImagenesServiceHolder { private static final ImagenService INSTANCE = new ImagenService(); } }
package com.example.atpc.cms; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Camera; import android.media.AudioManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.telephony.SmsManager; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; /** * Created by USER on 08/7/2016. */ public class RingtonePlayer extends Service { private Ringtone ringtone; private Camera camera; private boolean isFlashOn=false; private Camera.Parameters params; private boolean flash = true; TimerTask sendTask; final Handler handler = new Handler(); String Phno; public void sendLocation(){ GPSTracker gps = new GPSTracker(this); if(gps.canGetLocation()) { final double latitude = gps.getLatitude(); final double longitude = gps.getLongitude(); final String Mes = "Lat: " + latitude + " Long: " + longitude; final String Mes1 = "http://maps.google.com/maps?q=" + latitude + "," + longitude; SharedPreferences sharedpref1 = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String one = sharedpref1.getString("PhoneNo1", ""); String two = sharedpref1.getString("PhoneNo2", ""); String three = sharedpref1.getString("PhoneNo3", ""); String message = Mes1; try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(one, null, message, null, null); // smsManager.sendTextMessage(two, null, Mes1, null, null); // smsManager.sendTextMessage(three, null, Mes1, null, null); // Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show(); } catch (Exception e) { // Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show(); e.printStackTrace(); } }else{ gps.showSettingsAlert(); } } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE); int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM); if (volume == 0) volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM); audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); Uri ringTonePath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); //Uri ringtoneUri = Uri.parse(intent.getExtras().getString("ringtone-uri")); this.ringtone = RingtoneManager.getRingtone(this, ringTonePath); if (ringtone != null) { ringtone.setStreamType(AudioManager.STREAM_ALARM); ringtone.play(); } ringtone.play(); camera = Camera.open(); params = camera.getParameters(); blink(200); sendTask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { sendLocation(); } }); }}; new Timer().scheduleAtFixedRate(sendTask, 0, 60000); return START_NOT_STICKY; } @Override public void onDestroy() { ringtone.stop(); flash = false; params = camera.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.release(); sendTask.cancel(); } private void blink(final int delay) { Thread t = new Thread() { public void run() { try { while (flash) { if (isFlashOn) { turnOffFlash(); } else { turnOnFlash(); } sleep(delay); } } catch (Exception e) { e.printStackTrace(); } } }; t.start(); } private void turnOnFlash() { if (!isFlashOn) { if (camera == null || params == null) { return; } params = camera.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(params); camera.startPreview(); isFlashOn = true; } } private void turnOffFlash() { if (isFlashOn) { if (camera == null || params == null) { return; } params = camera.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(params); camera.stopPreview(); isFlashOn = false; } } }
package br.assembleia.dao.impl; import br.assembleia.dao.CongregacaoDAO; import br.assembleia.entidades.Congregacao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; @Repository public class CongregacaoDAOImpl implements CongregacaoDAO { @PersistenceContext private EntityManager entityManager; @Override public Congregacao getById(Long id) { return entityManager.find(Congregacao.class, id); } @SuppressWarnings("unchecked") @Override public List<Congregacao> listarTodos() { return entityManager.createQuery("FROM " + Congregacao.class.getName()) .getResultList(); } @Override public void salvar(Congregacao congregacao) { entityManager.merge(congregacao); entityManager.flush(); } @Override public void editar(Congregacao congregacao) { entityManager.merge(congregacao); entityManager.flush(); } @Override public void deletar(Congregacao congregacao) { congregacao = getById(congregacao.getId()); entityManager.remove(congregacao); entityManager.flush(); } @Override public void deletarId(final Long id) { Congregacao congregacao = getById(id); entityManager.remove(congregacao); entityManager.flush(); } }
import java.nio.file.Files; import java.nio.file.Path; /** * These are the test cases for comparing the actual and expected output for * searching the inverted index from query file. */ @SuppressWarnings("javadoc") public enum SearchTestCases { // various simple test cases SimpleWords ("words.txt", Path.of("simple", "words.tExT")), SimpleSimple ("simple.txt", Path.of("simple")), // the single rfc file test cases RFC475 ("complex.txt", Path.of("rfcs", "rfc475.txt")), RFC5646("complex.txt", Path.of("rfcs", "rfc5646.txt")), RFC6797("complex.txt", Path.of("rfcs", "rfc6797.txt")), RFC6805("complex.txt", Path.of("rfcs", "rfc6805.txt")), RFC6838("complex.txt", Path.of("rfcs", "rfc6838.txt")), RFC7231("complex.txt", Path.of("rfcs", "rfc7231.txt")), // the single gutenberg test cases Guten1400 ("complex.txt", Path.of("guten", "1400-0.txt")), Guten1228 ("complex.txt", Path.of("guten", "pg1228.txt")), Guten1322 ("complex.txt", Path.of("guten", "pg1322.txt")), Guten1661 ("complex.txt", Path.of("guten", "pg1661.txt")), Guten22577("complex.txt", Path.of("guten", "pg22577.txt")), Guten37134("complex.txt", Path.of("guten", "pg37134.txt")), // the directory test cases using letters.txt AllRFC ("complex.txt", Path.of("rfcs")), AllGuten ("complex.txt", Path.of("guten")), AllText ("complex.txt", Path.of(".")); /** The input path to use for building the index. */ public final Path input; /** The input path to use for the query file. */ public final Path query; /** The filename to use for actual/expected output. */ public final String label; /** * Initializes this test case based on the input and query paths. * @param query the query path to use for searching the index * @param input the input path to use for building the index */ private SearchTestCases(String query, Path input) { this.input = Path.of("text").resolve(input).normalize(); this.query = Path.of("query").resolve(query).normalize(); // determine filename to use for actual/expected output if (Files.isDirectory(this.input)) { this.label = this.input.getFileName().toString(); } else { String[] parts = this.input.getFileName().toString().split("\\."); String subdir = this.input.getParent().getFileName().toString(); this.label = subdir + "-" + parts[0]; } } }
package com.tickets.controller; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.tickets.common.exceptions.InternalServerErrorException; import com.tickets.common.exceptions.NotAcceptableException; import com.tickets.common.exceptions.NotFoundException; import com.tickets.common.validator.CommonValidator; import com.tickets.entity.Agent; import com.tickets.service.AgentService; /** * <h1>Controller to manage Agents</h1> * Rest controller to manage and maintain api related to the agent management * "/rb" is the root mappling for this class * @author Joby Chacko * @version 1.0 * @since 2020-03-20 * For http status codes def: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html * For pagination https://github.com/vijjayy81/spring-boot-jpa-rest-demo-filter-paging-sorting */ @RestController @RequestMapping(value = "/rb") public class AgentController { @Autowired private AgentService agentService; private Agent agent; private boolean validationStatus; private List<Agent> agentList; private HttpHeaders headers; /** * Logback supports ERROR, WARN, INFO, DEBUG, or TRACE as logging level. * By default, logging level is set to INFO. * It means that code>DEBUG and TRACE messages are not visible. */ private static final Logger LOGGER=LoggerFactory.getLogger(AgentController.class); /** * This method is a dummy one to test application is running successfully * It doens't accept any parameters * @return string This returns "Hello World" as response */ @RequestMapping("/") public String hello() { return "Hello RB"; } /** * This method is a dummy one to test application is running successfully * It doens't accept any parameters * @return string This returns "Hello World" as response */ @RequestMapping("/list/one") public String hellorb() { return "Hello /rb/list/one"; } @PostMapping("/tests") public Agent createsAgent() { return new Agent(); } @GetMapping("/testsget") public Agent fetchAgent() { return new Agent(); } /** * This method is used to handle the create agent POST request * @param RequestBody Agents to get the properties related to agents * @param UriComponentsBuilder builder to buld the right url back in the response * @return ResponseEntity with created agent, headers and CREATED status. */ @PostMapping("/agents") public ResponseEntity<Agent> createAgent(@RequestBody Agent agent) { try { LOGGER.info("Inside the /create api"); validationStatus = false; agent.setEnable(true); agent.setCreateDate(new Date().toString()); validationStatus = agentService.validateCreateAgent(agent); if(!validationStatus) { throw new NotAcceptableException("Validation Failes while creating the Agent"); } agent = agentService.createAgent(agent); if(null == agent) { throw new InternalServerErrorException("Something Went Wrong in creating the Agent - Agent created is null"); } if(agent.getId() ==0) { throw new InternalServerErrorException("Something Went Wrong in creating the Agent - Agent created is null or not created"); } HttpHeaders headers = new HttpHeaders(); return new ResponseEntity<Agent>(agent, headers, HttpStatus.CREATED); } catch (Exception e) { LOGGER.info("Something went wrong while creating an Agent: "+e.fillInStackTrace()); LOGGER.debug("Exception while creating Agent: ", e.fillInStackTrace()); throw e; } } /** * This method is used to handle the update agent PUT request * @param RequestBody Agents to get the properties related to agents. Should have the ID to be updated * @param UriComponentsBuilder builder to buld the right url back in the response * @return ResponseEntity with created agent, headers and UPDATE status. */ @PutMapping("/agents") public ResponseEntity<Agent> updateAgent(@RequestBody Agent agent) { try { if(agent == null) { throw new IllegalArgumentException(); } LOGGER.info("Updating the agent :"+agent.getId()); validationStatus = agentService.validateUpdateAgent(agent); if(!validationStatus) { throw new NotAcceptableException("Validation Failes while updating the Agent"); } agent = agentService.updateAgent(agent); if(null == agent) { throw new InternalServerErrorException("Something Went Wrong in updating the Agent - Agent updated is null"); } headers = new HttpHeaders(); return new ResponseEntity<Agent>(agent, headers, HttpStatus.ACCEPTED); } catch(Exception e) { LOGGER.info("Something went wrong while updating Agent"); LOGGER.debug("Exception while updating Agent", e.fillInStackTrace()); throw e; } } /** * This method is used to handle fetching the agent from the Database * @param RequestParm agnetId will have the id of the agent to be fetched * @param UriComponentsBuilder builder to buld the right url back in the response * @return ResponseEntity with created agent, headers and DELETE status. */ @GetMapping("agents/{id}") public ResponseEntity<Agent> fetchAgent(@PathVariable long id) { try { if(id == 0) { throw new IllegalArgumentException("Agent ID Id is not defined"); } LOGGER.info("Fetching the agent with Agent Id: "+id); agent = agentService.fetchAgent(id); if(null == agent) { throw new NotFoundException("Requested Agent is not available"); } headers = new HttpHeaders(); return new ResponseEntity<Agent>(agent, headers, HttpStatus.OK); } catch (Exception e) { LOGGER.info("Something went wrong while fetching the agent"); LOGGER.debug("Something went wrong while fetching the agent"+e.getMessage()); throw e; } } /** * This method is used to handle the delete agent DELTE request * @param RequestParm ID will have the id of the agent to be deleted * @param UriComponentsBuilder builder to buld the right url back in the response * @return ResponseEntity with created agent, headers and DELETE status. */ @DeleteMapping("agents/{id}") public ResponseEntity<String> deleteAgent(@PathVariable long id) { try { if(id == 0) { throw new IllegalArgumentException("Delete Id is not defined"); } LOGGER.info("Deleting the specified agent"); agentService.deleteAgent(id); HttpHeaders headers = new HttpHeaders(); return new ResponseEntity<String>("Deleted the Agent", headers, HttpStatus.NO_CONTENT); } catch (Exception e) { LOGGER.info("Something went wrong while deleting the agent"); LOGGER.debug("Something went wrong in deleting the agent"+e.getMessage()); throw e; } } /** * This method is used to handle GET request for agents list for the like name search * @param RequestParam String firstName used to accept the searched first name * @return ResponseEntity with agents list, headers and OK status. */ @GetMapping("/agents") public ResponseEntity<List<Agent>> agentsByName(@RequestParam(value = "firstName", required = false, defaultValue = "") String firstName) { try { System.out.println("First name to search is "+firstName); LOGGER.info("Searchin Agents by Name"); agentList = null; if(firstName.equals("")){ agentList = agentService.agentList(); } else { agentList = agentService.agentListByName(firstName); } if(null == agentList) { throw new InternalServerErrorException("Something went wrong while fetching the agents by name"); } return new ResponseEntity<List<Agent>>(agentList, HttpStatus.OK); } catch(Exception e) { LOGGER.info("Something went wrong while searching the agent list"); LOGGER.debug("Something went wrong while searching the agent list"+e.getMessage()); throw e; } } /** * This method is used to handle GET request for agents list for the like name search * @param RequestParam String firstName used to accept the searched first name * @return ResponseEntity with agents list, headers and OK status. */ @GetMapping("/agentsList") public ResponseEntity<Page<Agent>> agentsList(@RequestParam(value = "pageNo", required = false, defaultValue = "0") String pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "5") String pageSize, @RequestParam(value = "sortBy", required = false, defaultValue = "firstName") String sortBy) { try { Page<Agent> agentList = agentService.agentList(Integer.parseInt(pageNo), Integer.parseInt(pageSize), sortBy); if(null == agentList) { throw new InternalServerErrorException("Something went wrong while fetching the agents by name"); } return new ResponseEntity<Page<Agent>>(agentList, HttpStatus.OK); } catch(Exception e) { LOGGER.info("Something went wrong while searching the agent list"); LOGGER.debug("Something went wrong while searching the agent list"+e.getMessage()); throw e; } } }
package com.minecraftabnormals.allurement.core.other; import com.google.common.collect.Maps; import com.minecraftabnormals.allurement.core.Allurement; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.LivingEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.util.Util; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.common.Mod; import vazkii.quark.content.tools.module.ColorRunesModule; import java.util.Map; @Mod.EventBusSubscriber(modid = Allurement.MOD_ID) public class AllurementUtil { public static final Map<String, Integer> ENCHANTABILITY_MAP = Util.make(Maps.newHashMap(), (map) -> { map.put("minecraft:leather_horse_armor", 15); map.put("minecraft:iron_horse_armor", 9); map.put("minecraft:golden_horse_armor", 25); map.put("minecraft:diamond_horse_armor", 10); map.put("nether_extension:netherite_horse_armor", 15); map.put("caverns_and_chasms:silver_horse_armor", 17); map.put("caverns_and_chasms:necromium_horse_armor", 13); }); public static int getTotalEnchantmentLevel(Enchantment ench, LivingEntity entity, EquipmentSlotType.Group group) { int count = 0; for (EquipmentSlotType slot : EquipmentSlotType.values()) { if (slot.getType() == group) { count += EnchantmentHelper.getItemEnchantmentLevel(ench, entity.getItemBySlot(slot)); } } return count; } public static int getEnchantmentCount(Enchantment ench, LivingEntity entity) { return getTotalEnchantmentLevel(ench, entity, EquipmentSlotType.Group.ARMOR) + getTotalEnchantmentLevel(ench, entity, EquipmentSlotType.Group.HAND); } public static void setColorRuneTarget(ItemStack stack) { if (ModList.get().isLoaded("quark")) ColorRunesModule.setTargetStack(stack); } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.config; import org.kie.api.runtime.KieContainer; /** * Do not use this class, it is an internal class. * It should be in impl. * <p> * Will be removed in 8.0. */ public class SolverConfigContext { private final KieContainer kieContainer; /** * Vanilla context. */ public SolverConfigContext() { kieContainer = null; } /** * Useful for a kjar deployment. The {@link KieContainer} also defines the non-vanilla {@link ClassLoader}. * * @param kieContainer if null behaves as {@link #SolverConfigContext()} */ public SolverConfigContext(KieContainer kieContainer) { this.kieContainer = kieContainer; } /** * @return sometimes null, affects the {@link ClassLoader} to use for loading all resources and {@link Class}es */ public KieContainer getKieContainer() { return kieContainer; } // ************************************************************************ // Complex methods // ************************************************************************ public void validate() { } }
package com.loneless.second_task.entity; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Text { private List<Sentence> sentences=new ArrayList<>(); private String header; public List<Sentence> getWords() { return sentences; } public void setWords(List<Sentence> words) { this.sentences = words; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public StringBuilder receiveIdea() { StringBuilder idea=new StringBuilder(); for (Sentence sentence : sentences) { idea.append(sentence.receiveIdea().append(" ")); } return idea; } public void supplementation(Sentence sentence){ sentences.add(sentence); } public void supplementation(Word word){ Sentence sentence=new Sentence(); sentence.supplementation(word); sentences.add(sentence); } public void supplementation(String sentence){ } @Override public String toString() { return "Text{" + "sentences=" + sentences + ", header='" + header + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Text text = (Text) o; return Objects.equals(sentences, text.sentences) && Objects.equals(header, text.header); } @Override public int hashCode() { return Objects.hash(sentences, header); } public List<Sentence> getSentences() { return sentences; } public void setSentences(List<Sentence> sentences) { this.sentences = sentences; } }
package lj.moviebase.resource.parameter.conventer; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.time.Year; @SuppressWarnings("unchecked") public class AdditionalParamConverterProvider implements ParamConverterProvider { @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (Year.class.isAssignableFrom(rawType)) { return (ParamConverter<T>) new YearParamConverter(); } return null; } }
package com.g2utools.whenmeet.activity.account; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.bumptech.glide.Glide; import com.firebase.ui.storage.images.FirebaseImageLoader; import com.g2utools.whenmeet.Manifest; import com.g2utools.whenmeet.R; import com.g2utools.whenmeet.dialog.ProgressDialog; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.UploadTask; import com.makeramen.roundedimageview.RoundedImageView; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class ProfileSetActivity extends AppCompatActivity implements View.OnClickListener { private static final int PERMISSION_REQ_CAMERA = 189; private static final int REQ_TAKE_PHOTO = 498; private static final int REQ_TAKE_ALBUM = 914; private static final int REQ_IMAGE_CROP = 991; private RoundedImageView mThumnail; private FloatingActionButton mProfile; private ProgressBar mUpload; private EditText mNickname; private Button mStart; private Uri imageURI, resultUIR; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile_set); mThumnail = findViewById(R.id.thumnail); mProfile = findViewById(R.id.profile); mUpload = findViewById(R.id.upload); mNickname = findViewById(R.id.nickname); mStart = findViewById(R.id.start); //todo: 썸네일 삽입 코드 String displayName = FirebaseAuth.getInstance().getCurrentUser().getDisplayName(); if(displayName != null) mNickname.setText(displayName); String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); FirebaseStorage.getInstance().getReference("profiles/"+uid +".jpg"); Glide.with(this).using(new FirebaseImageLoader()).load(FirebaseStorage.getInstance().getReference("profiles/"+uid +".jpg")).into(mThumnail); mStart.setOnClickListener(this); mProfile.setOnClickListener(this); checkPermission(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.start:{ UserProfileChangeRequest build = new UserProfileChangeRequest.Builder() .setDisplayName(mNickname.getText().toString()) .build(); final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("프로필 업데이트 중..."); progressDialog.setCancelable(false); progressDialog.show(); FirebaseAuth.getInstance().getCurrentUser().updateProfile(build).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { progressDialog.dismiss(); if (task.isSuccessful()) { Toast.makeText(ProfileSetActivity.this, "적용됨", Toast.LENGTH_SHORT).show(); finish(); }else{ Toast.makeText(ProfileSetActivity.this, "오류남ㅇㅇ\n" + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference refPublicUser = FirebaseDatabase.getInstance().getReference("public").child(uid); refPublicUser.child("nickname").setValue(mNickname.getText().toString()); }break; case R.id.profile:{ new AlertDialog.Builder(this) .setTitle("사진 가져오기") .setMessage("사진을 어디서 가져올까요?") .setCancelable(true) .setPositiveButton("갤러리", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { getAlbum(); } }) .setNeutralButton("사진 찍기", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { captureCamera(); } }) .setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .create() .show(); } } } private File createImageFile() throws IOException { // 이미지 파일 이름 생성 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + ".jpg"; File imageFile = null; File storageDir = new File(Environment.getExternalStorageDirectory() + "/Pictures","uploads"); //해당 디렉토리가 없으면 생성 if(!storageDir.exists()){ storageDir.mkdirs(); } //파일 생성 imageFile = new File(storageDir,imageFileName); //mCurrentPhotoPath = imageFile.getAbsolutePath(); return imageFile; } private void captureCamera(){ String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)){ //외장 메모리가 사용 가능시(사용가능) Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(intent.resolveActivity(getPackageManager()) != null){ File photoFile = null; try { photoFile = createImageFile(); } catch (IOException e) { e.printStackTrace(); } //이미지 파일 만들기 성공했다면 if(photoFile != null){ //다른 앱에 파일 공유하기 위한 프로바이더 생성 imageURI = FileProvider.getUriForFile(this,getPackageName(),photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI); startActivityForResult(intent, REQ_TAKE_PHOTO); } } else { Toast.makeText(this,"저장 공간에 접근이 불가능합니다.",Toast.LENGTH_SHORT).show(); return; } } } private void getAlbum(){ Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); intent.setType(MediaStore.Images.Media.CONTENT_TYPE); startActivityForResult(intent,REQ_TAKE_ALBUM); } private void cropImage(){ try { resultUIR = Uri.fromFile(createImageFile()); } catch (IOException e) { e.printStackTrace(); return; } Intent intent = new Intent("com.android.camera.action.CROP"); intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(imageURI,"image/*"); intent.putExtra("outputX",200); intent.putExtra("outputY",200); intent.putExtra("aspectX",1); intent.putExtra("aspectY",1); intent.putExtra("scale",true); intent.putExtra("output",resultUIR); startActivityForResult(intent,REQ_IMAGE_CROP); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case REQ_TAKE_PHOTO:{ if(resultCode == RESULT_OK){ cropImage(); } }break; case REQ_TAKE_ALBUM:{ if(resultCode == RESULT_OK){ if(data.getData() != null){ imageURI = data.getData(); cropImage(); } } }break; case REQ_IMAGE_CROP:{ if(resultCode == RESULT_OK){ //mThumnail.setImageURI(resultUIR); mUpload.setVisibility(View.VISIBLE); String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); FirebaseStorage.getInstance().getReference("profiles/"+uid +".jpg").putFile(resultUIR).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() { @Override public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) { mUpload.setVisibility(View.INVISIBLE); if(!task.isSuccessful()){ String message = task.getException().getMessage(); Toast.makeText(ProfileSetActivity.this, "이미지 업로드 실패하였습니다.\n" + message, Toast.LENGTH_SHORT).show(); } } }); } }break; } } private void checkPermission(){ if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if ((ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) || (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.CAMERA))) { new AlertDialog.Builder(this) .setTitle("알림") .setMessage("저장소 권한이 거부되었습니다. 사용을 원하시면 설정에서 해당 권한을 직접 허용하셔야 합니다.") .setNeutralButton("설정", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } }) .setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }) .setCancelable(false) .create() .show(); } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, PERMISSION_REQ_CAMERA); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PERMISSION_REQ_CAMERA: for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] < 0) { Toast.makeText(ProfileSetActivity.this, "해당 권한을 활성화 하셔야 합니다.", Toast.LENGTH_SHORT).show(); return; } } break; } } }
package services; import java.util.Calendar; import java.util.Date; import javax.transaction.Transactional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import utilities.AbstractTest; import domain.Event; @ContextConfiguration(locations = { "classpath:spring/junit.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class EventServiceTest extends AbstractTest { // System under test ------------------------------------------------------ @Autowired private EventService eventService; // Tests ------------------------------------------------------------------ // A continuación se van a realizar pruebas para comprobar el correcto funcionamiento de los casos de uso relacionados con Event. // Registro y edicion de un event: @Test public void driverCreateAndSave() { Calendar correctCalendar; Calendar wrongCalendar; correctCalendar = Calendar.getInstance(); correctCalendar.set(2017, 9, 31, 12, 30, 00); wrongCalendar = Calendar.getInstance(); wrongCalendar.set(2017, 3, 20, 9, 30, 00); final Object testingData[][] = { { // Bien "manager1", "prueba1", correctCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, null }, {// Tarjeta de credito no valida "manager3", "prueba1", correctCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, IllegalArgumentException.class }, {// Fecha de organizacion pasada+Edicion de un evento de otro manager "manager1", "prueba1", wrongCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) this.testCreate((String) testingData[i][0], (String) testingData[i][1], (Date) testingData[i][2], (String) testingData[i][3], (String) testingData[i][4], (Integer) testingData[i][5], (Class<?>) testingData[i][6]); } @Test public void driverEdit() { Calendar correctCalendar; Calendar wrongCalendar; correctCalendar = Calendar.getInstance(); correctCalendar.set(2017, 9, 31, 12, 30, 00); wrongCalendar = Calendar.getInstance(); wrongCalendar.set(2017, 3, 20, 9, 30, 00); final Object testingData[][] = { { // Bien "manager1", 70, "prueba1", correctCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, null }, {// Tarjeta de credito no valida "manager3", 70, "prueba1", correctCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, IllegalArgumentException.class }, {// Fecha de organizacion pasada "manager1", 70, "prueba1", wrongCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, IllegalArgumentException.class }, {// Edicion de un evento de otro manager "manager1", 72, "prueba1", wrongCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 10, IllegalArgumentException.class }, {// Menos asientos de los que ya estan registrados "manager1", 71, "prueba1", wrongCalendar.getTime(), "Descripcion prueba 1", "http://www.texasbungalow.com/events.jpg", 1, IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) this.testEdit((String) testingData[i][0], (int) testingData[i][1], (String) testingData[i][2], (Date) testingData[i][3], (String) testingData[i][4], (String) testingData[i][5], (Integer) testingData[i][6], (Class<?>) testingData[i][7]); } // Eliminacion de un event: @Test public void driverDelete() { final Object testingData[][] = { { // Bien "manager1", 70, null }, {// Manager sin autenticar null, 70, IllegalArgumentException.class }, {// Eliminacion de un evento de otro manager "manager1", 72, IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) this.testDelete((String) testingData[i][0], (int) testingData[i][1], (Class<?>) testingData[i][2]); } // Inscripcion y cancelacion de la inscripcion a un event: @Test public void driverRegister() { final Object testingData[][] = { { // Bien "chorbi1", 73, null }, {// Chorbi sin autenticar null, 73, IllegalArgumentException.class }, {// Register: no hay plazas libres; Unregister: no esta registrado "chorbi3", 71, IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) { this.testRegister((String) testingData[i][0], (int) testingData[i][1], (Class<?>) testingData[i][2]); this.testUnregister((String) testingData[i][0], (int) testingData[i][1], (Class<?>) testingData[i][2]); } } protected void testCreate(final String username, final String title, final Date organisedMoment, final String description, final String picture, final Integer seatsNumber, final Class<?> expected) { Class<?> caught; caught = null; try { this.authenticate(username); Event event; event = this.eventService.create(); event.setTitle(title); event.setOrganisedMoment(organisedMoment); event.setDescription(description); event.setPicture(picture); event.setSeatsNumber(seatsNumber); event = this.eventService.save(event); this.unauthenticate(); } catch (final Throwable oops) { caught = oops.getClass(); } this.checkExceptions(expected, caught); } protected void testEdit(final String username, final int eventId, final String title, final Date organisedMoment, final String description, final String picture, final Integer seatsNumber, final Class<?> expected) { Class<?> caught; caught = null; try { this.authenticate(username); Event event; event = this.eventService.findOne(eventId); event.setTitle(title); event.setOrganisedMoment(organisedMoment); event.setDescription(description); event.setPicture(picture); event.setSeatsNumber(seatsNumber); event = this.eventService.save(event); this.unauthenticate(); } catch (final Throwable oops) { caught = oops.getClass(); } this.checkExceptions(expected, caught); } protected void testDelete(final String username, final int eventId, final Class<?> expected) { Class<?> caught; caught = null; try { this.authenticate(username); Event event; event = this.eventService.findOne(eventId); this.eventService.delete(event); this.unauthenticate(); } catch (final Throwable oops) { caught = oops.getClass(); } this.checkExceptions(expected, caught); } protected void testRegister(final String username, final int eventId, final Class<?> expected) { Class<?> caught; caught = null; try { this.authenticate(username); Event event; event = this.eventService.findOne(eventId); this.eventService.register(event); this.unauthenticate(); } catch (final Throwable oops) { caught = oops.getClass(); } this.checkExceptions(expected, caught); } protected void testUnregister(final String username, final int eventId, final Class<?> expected) { Class<?> caught; caught = null; try { this.authenticate(username); Event event; event = this.eventService.findOne(eventId); this.eventService.unregister(event); this.unauthenticate(); } catch (final Throwable oops) { caught = oops.getClass(); } this.checkExceptions(expected, caught); } }
package mx.itesm.lightsgone; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.Screen; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.ArrayList; import java.util.Map; import java.util.Random; import java.util.TreeMap; /** * Created by allanruiz on 19/09/16. */ public class LightsGone implements Screen, InputProcessor{ public static final int ANCHO_MUNDO = 1280; public static final int ALTO_MUNDO = 800; public static final int YBOTON = 30; public static final float YCOCINA3 = 361.0f; public static final float YCOCINA2 = 1950; public static final float YCOCINA1 = 2039.0f; public static final float YJARDIN1 = 1320; public static final float YJARDIN2 = 2200; public static final float YJARDIN3 = 700; public static final float YSALA = 1142; public static final float TRANSICIONNIVEL = 0.005f; public static final float TRANSICIONNEUTRAL = 0.01f; public static final int MUNICIONX = 264; public static final int MUNICIONY = 706; public static final float YBAJA = 135f, YMEDIA = 800f, YALTA =1100f; public static final float YARMARIO = 450; public static final float ANCHOBOTON = 137; private static final float ALTOBOTON = 134; private float velocidadTransicion = TRANSICIONNEUTRAL; public static final int LATAX = 4871; private final float VIDACOCO = 12; private OrthographicCamera camara; private OrthographicCamera camaraHUD; private Viewport vista; private SpriteBatch batch; private Music ambiente, gameover, leche, recarga, sonidos; private Juego juego; private AssetManager assetManager = new AssetManager(); public static Texture plataforma; private Texture capa,capa25,capa50,capa0,capa75,municion, habilidadLanzaPapas, transicionCocina,transicionJardin, transicionArmario, transicionSotano, transicionCoco, transicionNeutral, dano, nivelVida, gameOver,habilidadDes, habilidadPogo,save,pausaTex,quitTex, opciones, botonSalto, JFondo, botonVida, habilidad, texPausa; private Sprite transicionNivel, pausaActual, fondoCielo; static Abner abner; private Texto vida, municionTex; private Pad pad; private static Texture malteada,papa; private Sprite imgVida, menuGameOver, imgMunicion, miniMapa, indicaciones; private boolean right, saveB; public static boolean musica; private Boton botonBack, botonOn, botonOff, botonTry, botonMain,botonSaltar, botonArma, pausa, botonResume, botonOpciones,botonQuit, botonYes,botonNo, botonSave, botonHabilidad, botonMapa, botonMapaBack; private float alpha = 0; private Array<String> mapas; private static Mapa mapa; static int mapaActual; private ArrayList<Proyectil> proyectiles; private Transicion transicion; private Estado estado; private EstadoPausa estadoPausa; private InfoJuego gameInfo; private float alphaGame; private AdministradorMapa mapManager; public static Habilidad habilidadActual; private Array<Sprite> vidas; private Arma estadoArma; private Sprite flechasArma, flechasHabilidad, cascaronBarraCoco, barraCoco; private boolean switchAtaque, switchHabilidad, switchSalto, switchedSalto,switchedAtaque, switchedHabilidad; private static boolean capaActiva; public static boolean cinematicaInicio, cinematicaPelea; private static Array<Sprite> malteadas, papas; private int leftPointer, rightPointer; private float timer, timerR, timerG; private static Capa estadoCapa; private Salto saltoActual; private Cinematica cinematica; private int contador = 1; private float anchBarra; private Music lampara; private boolean sonidoInicial; private Map<Integer, Rectangle> zonasMinimapas; Array<Enemigo> enemigos; private static Lampara estadoLampara; private Texture lamparaOff, lamparaOn; private Sprite flechasSalto; private float xInicial; private float yInicial; private float camaraInicialX; private float camaraInicialY; private Sprite marcardor; public LightsGone(Juego juego) { this.juego = juego; right = true; saveB = false; gameInfo = new InfoJuego(); } public LightsGone(Juego juego, String nombre){ this.juego = juego; right = true; saveB = false; gameInfo = new InfoJuego(nombre); } public LightsGone(Juego juego, InfoJuego gameInfo){ this.juego = juego; right = true; saveB = false; this.gameInfo = gameInfo; } public static boolean getLampara() { return abner.getLampara(); } @Override public void show() { cargarTexturas(); iniciarCamara(); crearMapas(); crearEscena(); Gdx.input.setInputProcessor(this); } private void crearMapas() { mapas = new Array<String>(18); zonasMinimapas = new TreeMap<Integer, Rectangle>(); mapManager = new AdministradorMapa(camara, batch); abner = new Abner(camara, null, gameInfo); mapas.add("CuartoAbner.tmx"); zonasMinimapas.put(0, new Rectangle(991,611,95,45)); mapas.add("Pasillo.tmx"); zonasMinimapas.put(1,new Rectangle(1094,613,150,41)); mapas.add("Sala.tmx"); zonasMinimapas.put(2, new Rectangle(1250,564,104,66)); mapas.add("Cocina1.tmx"); zonasMinimapas.put(3, new Rectangle(1619,418,383,113)); mapas.add("Cocina2.tmx"); zonasMinimapas.put(4,new Rectangle(1400,493,205,101)); mapas.add("Cocina3.tmx"); zonasMinimapas.put(5, new Rectangle(1615,549,235,103)); mapas.add("Jardin1.tmx"); zonasMinimapas.put(6, new Rectangle(1392,861,722,97)); mapas.add("Jardin2.tmx"); zonasMinimapas.put(7,new Rectangle(2065,756,662,88)); mapas.add("Jardin3.tmx"); zonasMinimapas.put(8,new Rectangle(2651,860,293,107)); mapas.add("Armario1.tmx"); zonasMinimapas.put(9,new Rectangle(540,726,420,60)); mapas.add("Armario2.tmx"); zonasMinimapas.put(10, new Rectangle(35,726,492,73)); mapas.add("Armario3.tmx"); zonasMinimapas.put(11, new Rectangle(119,578,323,67)); mapas.add("Armario4.tmx"); zonasMinimapas.put(12, new Rectangle(35,610,66,27)); mapas.add("Sotano1.tmx"); zonasMinimapas.put(13, new Rectangle(310,66,860,460)); mapas.add("Sotano2.tmx"); zonasMinimapas.put(14,new Rectangle(860,295,295,153)); mapas.add("Sotano3.tmx"); zonasMinimapas.put(15, new Rectangle(885,86,270,200)); mapas.add("CaminoAlCoco.tmx"); zonasMinimapas.put(16, new Rectangle(1146,663,45,126)); mapas.add("Atico1.tmx"); zonasMinimapas.put(17, new Rectangle(1124,838,58,36)); mapas.add("Atico2.tmx"); zonasMinimapas.put(18, new Rectangle(1056,881,125,45)); mapaActual = gameInfo.getMapa(); mapa = mapManager.getNewMapa(mapas.get(mapaActual),mapaActual,abner, gameInfo); abner.setMapa(mapa); enemigos = mapa.getEnemigos(); musica = true; switchAtaque = false; switchHabilidad = false; cinematicaInicio = gameInfo.isCinematicaInicio(); cinematicaPelea = gameInfo.isCinematicaPelea(); if(cinematicaPelea){ Enemigo.reiniciarManager(); Enemigo.Coco.cargar(); Array<Enemigo> enemigos = new Array<Enemigo>(); enemigos.add(new Enemigo.Coco(mapa, abner)); mapa.setEnemigos(enemigos); Enemigo.Coco coco = (Enemigo.Coco)enemigos.get(0); cascaronBarraCoco = coco.getCascaron(); barraCoco = coco.getBarra(); this.enemigos = mapa.getEnemigos(); anchBarra = barraCoco.getWidth(); } } private void iniciarCamara() { camara = new OrthographicCamera(ANCHO_MUNDO,ALTO_MUNDO); camara.position.set(ANCHO_MUNDO / 2, ALTO_MUNDO/2, 0); camara.update(); vista = new StretchViewport(ANCHO_MUNDO,ALTO_MUNDO, camara); camaraHUD = new OrthographicCamera(ANCHO_MUNDO,ALTO_MUNDO); camaraHUD.position.set(ANCHO_MUNDO/2,ALTO_MUNDO/2,0); camaraHUD.update(); batch = new SpriteBatch(); } private void crearEscena() { botonSaltar = new Boton(botonSalto, ANCHO_MUNDO - habilidadDes.getWidth()- botonSalto.getWidth()-20, YBOTON, false); pad = new Pad(JFondo); vidas = new Array<Sprite>(3); for (int i=0;i<3;i++) { Sprite sprite = new Sprite(nivelVida); sprite.setPosition(30, ALTO_MUNDO-35-(40*(i+1))); vidas.add(sprite); } botonArma = new Boton(habilidad, ANCHO_MUNDO - habilidadDes.getWidth()- botonSalto.getWidth()-habilidad.getWidth()-30, YBOTON, false); flechasArma.setPosition(botonArma.getX() + ANCHOBOTON-flechasArma.getWidth()-10, botonArma.getY()+ALTOBOTON-flechasArma.getHeight()-8); pausa = new Boton(texPausa, ANCHO_MUNDO- texPausa.getWidth(), ALTO_MUNDO - texPausa.getHeight(), false); imgVida = new Sprite(botonVida); Gdx.input.setCatchBackKey(true); malteadas = new Array<Sprite>(); papas = new Array<Sprite>(); imgVida.setPosition(0, 780 - imgVida.getHeight()); imgMunicion = new Sprite(municion); imgMunicion.setPosition(MUNICIONX, MUNICIONY); vida = new Texto("font.fnt", imgVida.getWidth(),690); municionTex = new Texto("font.fnt", imgMunicion.getX(), MUNICIONY+60); transicionNivel = new Sprite(transicionNeutral); estadoLampara = Lampara.APAGADA; habilidadActual = Habilidad.VACIA; saltoActual = Salto.NORMAL; transicionNivel.setSize(LightsGone.ANCHO_MUNDO, LightsGone.ALTO_MUNDO); enemigos = mapa.getEnemigos(); gameInfo.setAbner(abner); estado = Estado.CAMBIO; transicion = Transicion.AUMENTANDO; botonHabilidad = new Boton(habilidadDes, ANCHO_MUNDO-habilidadDes.getWidth()-10,YBOTON,false); flechasHabilidad.setPosition(botonHabilidad.getX()+10, botonHabilidad.getY()+ALTOBOTON-flechasHabilidad.getHeight()+10); flechasSalto.setPosition(botonSaltar.getX()+10, botonSaltar.getY()+ALTOBOTON-flechasSalto.getHeight()-10); estadoPausa = EstadoPausa.PRINCIPAL; menuGameOver = new Sprite(gameOver); pausaActual = new Sprite(pausaTex); botonResume = new Boton(502,405,295,75); botonOpciones= new Boton(502,247,295,75); botonQuit = new Boton(538,93,202,79); botonYes = new Boton(402,106,141,79); botonNo = new Boton(714, 106,141,79); botonSave = new Boton(save, ANCHO_MUNDO/2-(save.getWidth()/2), ALTO_MUNDO - save.getHeight(), false); botonMain = new Boton(195,91,355,65); botonTry = new Boton(195,224,355,65); botonOn = new Boton(378,166,134,67); botonOff = new Boton(757,166,134,67); botonBack = new Boton(526, 53,209, 81); alphaGame = 0; estadoArma = Arma.RESORTERA; ambiente.setVolume(0.5f); leftPointer = -1; rightPointer = -1; estadoCapa = Capa.CAPA100; capaActiva = false; timer = 8; timerR = 0; timerG = 0; } private void cargarTexturas() { assetManager.load("BotonSalto.png", Texture.class); assetManager.load("JoystickBoton.png", Texture.class); assetManager.load("BotonPausa.png", Texture.class); assetManager.load("BotonVida.png", Texture.class); assetManager.load("BotonResortera.png", Texture.class); assetManager.load("nivel.png", Texture.class); assetManager.load("PlataformaInclinada.png", Texture.class); assetManager.load("menuPausa.jpg", Texture.class); assetManager.load("menuPausaQuit.jpg", Texture.class); assetManager.load("menuPausaAudio.jpg", Texture.class); assetManager.load("Save6.png", Texture.class); assetManager.load("BotonHabilidadDesactivado.png", Texture.class); assetManager.load("BotonHabPogo.png", Texture.class); assetManager.load("gameOver.png", Texture.class); assetManager.load("BotonNivelVida.png", Texture.class); assetManager.load("MalteadaMundo.png", Texture.class); assetManager.load("PapaMundo.png", Texture.class); assetManager.load("FondoCielo.jpg", Texture.class); assetManager.load("cocina.jpg", Texture.class); assetManager.load("coco.jpg", Texture.class); assetManager.load("jardin.jpg", Texture.class); assetManager.load("ropero.jpg", Texture.class); assetManager.load("sotano.jpg", Texture.class); assetManager.load("BotonHabLanzaPapa.png", Texture.class); assetManager.load("BotonMunicion.png", Texture.class); assetManager.load("CajaMovilDer.png", Texture.class); assetManager.load("BotonHabLamparaOff.png", Texture.class); assetManager.load("BotonHabLamparaOn.png", Texture.class); assetManager.load("LuzConLampara.png", Texture.class); assetManager.load("OscuridadConLampara.png", Texture.class); assetManager.load("FlechasArmas.png", Texture.class); assetManager.load("FlechasHabilidades.png",Texture.class); assetManager.load("FlechasSaltos.png", Texture.class); assetManager.load("BotonHabCapa100.png", Texture.class); assetManager.load("BotonHabCapa0.png", Texture.class); assetManager.load("BotonHabCapa25.png", Texture.class); assetManager.load("BotonHabCapa50.png", Texture.class); assetManager.load("BotonHabCapa75.png", Texture.class); assetManager.load("ambiente.mp3", Music.class); assetManager.load("risa.mp3", Music.class); assetManager.load("leche.mp3", Music.class); assetManager.load("recargar papas.mp3", Music.class); assetManager.load("Sonidos.mp3", Music.class); assetManager.load("lamparita.mp3", Music.class); assetManager.load("Mapa Lights Gone.png", Texture.class); assetManager.load("Indicaciones.png", Texture.class); assetManager.load("BotonMapa.png", Texture.class); assetManager.load("back.png", Texture.class); assetManager.load("mapmarker.png", Texture.class); assetManager.finishLoading(); miniMapa = new Sprite(assetManager.get("Mapa Lights Gone.png", Texture.class)); indicaciones = new Sprite(assetManager.get("Indicaciones.png", Texture.class)); indicaciones.setPosition(ANCHO_MUNDO- indicaciones.getHeight(), 0); marcardor = new Sprite(assetManager.get("mapmarker.png", Texture.class)); botonSalto = assetManager.get("BotonSalto.png"); JFondo = assetManager.get("JoystickBoton.png"); texPausa = assetManager.get("BotonPausa.png"); habilidad = assetManager.get("BotonResortera.png"); botonVida =assetManager.get("BotonVida.png"); transicionNeutral = assetManager.get("nivel.png"); transicionCocina = assetManager.get("cocina.jpg"); transicionCoco = assetManager.get("coco.jpg"); transicionJardin = assetManager.get("jardin.jpg"); transicionArmario = assetManager.get("ropero.jpg"); transicionSotano = assetManager.get("sotano.jpg"); plataforma = assetManager.get("PlataformaInclinada.png"); pausaTex = assetManager.get("menuPausa.jpg"); opciones = assetManager.get("menuPausaAudio.jpg"); quitTex = assetManager.get("menuPausaQuit.jpg"); save = assetManager.get("Save6.png"); habilidadDes = assetManager.get("BotonHabilidadDesactivado.png"); habilidadPogo = assetManager.get("BotonHabPogo.png"); gameOver = assetManager.get("gameOver.png"); nivelVida = assetManager.get("BotonNivelVida.png"); ambiente = assetManager.get("ambiente.mp3"); gameover = assetManager.get("risa.mp3"); malteada = assetManager.get("MalteadaMundo.png"); fondoCielo = new Sprite((Texture)assetManager.get("FondoCielo.jpg")); fondoCielo.setPosition(0,0); habilidadLanzaPapas = assetManager.get("BotonHabLanzaPapa.png"); municion = assetManager.get("BotonMunicion.png"); lamparaOff = assetManager.get("BotonHabLamparaOff.png"); lamparaOn = assetManager.get("BotonHabLamparaOn.png"); flechasArma = new Sprite((Texture)assetManager.get("FlechasArmas.png")); flechasHabilidad = new Sprite((Texture)assetManager.get("FlechasHabilidades.png"));; flechasSalto = new Sprite((Texture)assetManager.get("FlechasSaltos.png")); leche = assetManager.get("leche.mp3"); papa = assetManager.get("PapaMundo.png"); recarga = assetManager.get("recargar papas.mp3"); capa = assetManager.get("BotonHabCapa100.png"); capa0 = assetManager.get("BotonHabCapa0.png"); capa25 = assetManager.get("BotonHabCapa25.png"); capa50 = assetManager.get("BotonHabCapa50.png"); capa75 = assetManager.get("BotonHabCapa75.png"); sonidos = assetManager.get("Sonidos.mp3"); sonidos.setVolume(0.5f); lampara = assetManager.get("lamparita.mp3"); botonMapa = new Boton(assetManager.get("BotonMapa.png", Texture.class), ANCHO_MUNDO-texPausa.getWidth()-125f-20f,ALTO_MUNDO-123f,false); botonMapaBack = new Boton(assetManager.get("back.png", Texture.class), 0,0,false); } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); if(abner.getLampara()&&habilidadActual == Habilidad.VACIA) { habilidadActual = Habilidad.LAMPARA; } estado = abner.isDead()?Estado.MUERTE:estado; if(estado == Estado.GANO){ batch.setProjectionMatrix(camara.combined); mapa.draw(); batch.begin(); abner.draw(batch, right, false); batch.end(); timerG+=Gdx.graphics.getDeltaTime(); if(timerG>=3){ batch.setProjectionMatrix(camaraHUD.combined); batch.begin(); cinematica.play(batch); batch.end(); } if(cinematica.finished()){ stop(); juego.setScreen(new MenuPrincipal(juego)); } } else if(estado == Estado.CINEMATICA){ batch.setProjectionMatrix(camaraHUD.combined); batch.begin(); cinematica.play(batch); batch.end(); if(cinematica.finished()){ cinematica.dispose(); gameInfo.actualizarDatos(); juego.setScreen(new LightsGone(juego, gameInfo)); } } else if(estado != Estado.PAUSA&&estado!=Estado.MUERTE&&estado!=Estado.MAPA){ switch (habilidadActual){ case LAMPARA: switch (estadoLampara){ case ENCENDIDA: if(!sotano()){ abner.setLampara(Lampara.ENCENDIDALUZ); estadoLampara = Lampara.ENCENDIDALUZ; } botonHabilidad.setTexture(lamparaOn); break; case ENCENDIDALUZ: if(sotano()){ abner.setLampara(Lampara.ENCENDIDA); estadoLampara = Lampara.ENCENDIDA; } botonHabilidad.setTexture(lamparaOn); break; case APAGADA: botonHabilidad.setTexture(lamparaOff); break; } break; case CAPITA: switch (estadoCapa){ case APAGADA: if(capaActiva){ capaActiva = false; timer = 8; } timerR += Gdx.graphics.getDeltaTime(); botonHabilidad.setTexture(capa0); if(timerR>=2.5){ estadoCapa = Capa.CAPA25; } break; case CAPA25: botonHabilidad.setTexture(capa25); if(capaActiva){ timer -= Gdx.graphics.getDeltaTime(); if(timer<=0){ estadoCapa = Capa.APAGADA; } } else{ timerR+=Gdx.graphics.getDeltaTime(); if(timerR>=5){ estadoCapa = Capa.CAPA50; } } break; case CAPA50: botonHabilidad.setTexture(capa50); if(capaActiva){ timer-=Gdx.graphics.getDeltaTime(); if(timer<=2){ estadoCapa = Capa.CAPA25; } } else { timerR += Gdx.graphics.getDeltaTime(); if(timerR>=7.5){ estadoCapa = Capa.CAPA75; } } break; case CAPA75: botonHabilidad.setTexture(capa75); if(capaActiva){ timer-=Gdx.graphics.getDeltaTime(); if(timer<=4){ estadoCapa = Capa.CAPA50; } } else { timerR += Gdx.graphics.getDeltaTime(); if(timerR>=10){ estadoCapa = Capa.CAPA100; timerR = 0; } } break; case CAPA100: botonHabilidad.setTexture(capa); if(capaActiva){ timer-= Gdx.graphics.getDeltaTime(); if(timer<=6){ estadoCapa = Capa.CAPA75; } } break; } break; case VACIA: botonHabilidad.setTexture(habilidadDes); break; } if(musica){ switch(mapaActual){ case 0: if(!cinematicaInicio&&!sonidos.isPlaying()&&!sonidoInicial){ sonidos.play(); ambiente.stop(); sonidoInicial = true; } else if(cinematicaInicio&&!ambiente.isPlaying()){ ambiente.play(); sonidos.stop(); } break; case 1: if(sonidos.isPlaying()){ sonidos.stop(); } if(!cinematicaInicio&&ambiente.isPlaying()){ ambiente.stop(); } else if(cinematicaInicio&&!ambiente.isPlaying()){ ambiente.play(); } break; default: if(!ambiente.isPlaying()){ ambiente.play(); } break; } } else{ ambiente.pause(); sonidos.pause(); } if(timerR!=0&&habilidadActual!=Habilidad.CAPITA){ timerR+=Gdx.graphics.getDeltaTime(); if(timerR>=10){ estadoCapa = Capa.CAPA100; timerR = 0; } else if(timerR>=7.5){ estadoCapa = Capa.CAPA75; } else if (timerR>=5){ estadoCapa = Capa.CAPA50; } else if(timerR>=2.5){ estadoCapa = Capa.CAPA25; } } //Inicio de los controles del teclado, si quieren habilitarlos quiten el /* al inicio y el */ al final if(Gdx.app.getType()== Application.ApplicationType.Desktop){ if(Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT)) pad.getLeft().setEstado(Boton.Estado.PRESIONADO); else{ pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); } if(Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT)) pad.getRight().setEstado(Boton.Estado.PRESIONADO); else { pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); } if(Gdx.input.isKeyJustPressed(Input.Keys.DPAD_UP)||Gdx.input.isKeyJustPressed(Input.Keys.DPAD_DOWN)){ habilidadSiguiente(); } if(Gdx.input.isKeyJustPressed(Input.Keys.A)&&!abner.isJumping()&&!abner.isAttacking()) botonSaltar.setEstado(Boton.Estado.PRESIONADO); if(Gdx.input.isKeyJustPressed(Input.Keys.S)&&!abner.isAttacking()) botonArma.setEstado(Boton.Estado.PRESIONADO); if(Gdx.input.isKeyJustPressed(Input.Keys.D)&&!abner.isJumping()&&!abner.isAttacking()&&abner.getPogo()){ botonHabilidad.setEstado(Boton.Estado.PRESIONADO); } } else { if(!Gdx.input.isTouched()){ abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); } } //Fin de los controles del teclado if(botonSaltar.isPressed()) { switch (saltoActual){ case POGO: abner.setEstadoVertical(Abner.Vertical.POGO); abner.setSalto(Abner.Salto.SUBIENDO); break; case NORMAL: abner.setEstadoVertical(Abner.Vertical.ACTIVADO); abner.setSalto(Abner.Salto.SUBIENDO); break; } } if(botonHabilidad.isPressed()){ switch (habilidadActual){ case LAMPARA: lampara.play(); switch (estadoLampara){ case ENCENDIDA: case ENCENDIDALUZ: estadoLampara = Lampara.APAGADA; abner.setLampara(Lampara.APAGADA); break; case APAGADA: abner.setLampara(sotano()?Lampara.ENCENDIDA:Lampara.ENCENDIDALUZ); estadoLampara = sotano()?Lampara.ENCENDIDA:Lampara.ENCENDIDALUZ; break; } break; case CAPITA: if(!capaActiva&&estadoCapa==Capa.CAPA100){ capaActiva=true; } break; } } if(botonArma.isPressed()){ if(!capaActiva){ switch(estadoArma){ case LANZAPAPAS: abner.setEstadoAtaque(Abner.Ataque.LANZAPAPAS); break; case RESORTERA: abner.setEstadoAtaque(Abner.Ataque.ACTIVADO); break; } } } if(pad.getRight().isPressed()) { right = true; abner.setEstadoHorizontal(Abner.Horizontal.ACTIVADO); } else if(pad.getLeft().isPressed()) { right = false; abner.setEstadoHorizontal(Abner.Horizontal.ACTIVADO); } //Cinematica inicial if(mapaActual==1&&abner.getX()>=1300&&!cinematicaInicio){ estado = Estado.CINEMATICA; cinematica = new Cinematica.Inicio(abner); cinematicaInicio = true; pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); stop(); dispose(); } //Cinematica antes de la pelea if(mapaActual==mapas.size-1&&abner.getX()<=1500&&!cinematicaPelea){ estado = Estado.CINEMATICA; cinematica = new Cinematica.Pelea(abner); cinematicaPelea = true; pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); stop(); dispose(); } //Cinematica final y vida del coco if(mapaActual==mapas.size-1&&cinematicaPelea&&enemigos!=null){ Enemigo.Coco coco = (Enemigo.Coco)mapa.getEnemigos().get(0); float vidaCoco = coco.getVida(); float porcentaje = vidaCoco/VIDACOCO; if(vidaCoco<=0){ camara.position.set(coco.getX()-530,camara.position.y,0); camara.update(); cinematica = new Cinematica.Final(); estado = Estado.GANO; abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); ambiente.stop(); mapa.stop(); abner.stop(); } barraCoco.setSize(anchBarra*porcentaje,barraCoco.getHeight()); //dispose(); } int cambio= abner.cambioNivel(); if(cambio>=0){ if(mapaActual<=6||mapaActual>15) abner.setEstadoVertical(Abner.Vertical.DESACTIVADO); int tempMapa = mapaActual; transicion = Transicion.AUMENTANDO; mapaActual = cambio; malteadas = new Array<Sprite>(); papas = new Array<Sprite>(); switch (mapaActual){ case 3: if(tempMapa==2){ transicionNivel.setTexture(transicionCocina); velocidadTransicion = TRANSICIONNIVEL; } break; case 6: if(tempMapa==2){ transicionNivel.setTexture(transicionJardin); velocidadTransicion = TRANSICIONNIVEL; } break; case 9: if(tempMapa ==0){ transicionNivel.setTexture(transicionArmario); velocidadTransicion = TRANSICIONNIVEL; } break; case 13: if(tempMapa == 2){ transicionNivel.setTexture(transicionSotano); velocidadTransicion = TRANSICIONNIVEL; } break; case 16: if(tempMapa==1){ transicionNivel.setTexture(transicionCoco); velocidadTransicion = TRANSICIONNIVEL; } break; default: transicionNivel.setTexture(transicionNeutral); velocidadTransicion = TRANSICIONNEUTRAL; break; } mapa.stop(); mapa.dispose(); mapa = mapManager.getMapa(mapas.get(mapaActual), mapaActual, abner, gameInfo); abner.setMapa(mapa); abner.setInitialPosition(tempMapa); estado = Estado.CAMBIO; mapa.draw(); enemigos = mapa.getEnemigos(); } proyectiles = abner.getProyectiles(); if(jardin()){ batch.setProjectionMatrix(camaraHUD.combined); batch.begin(); fondoCielo.draw(batch); batch.end(); } batch.setProjectionMatrix(camara.combined); mapa.draw(); batch.begin(); abner.draw(batch, right,true); for(Sprite sprite:malteadas) { if(abner.getBoundingRectangle().overlaps(sprite.getBoundingRectangle())){ abner.setCantVida(abner.getcantVida()+10); leche.play(); malteadas.removeIndex(malteadas.indexOf(sprite, true)); } else { if(mapa.colisionY(sprite.getX()+sprite.getWidth()/2, sprite.getY()-10)==-1) sprite.translate(0,-10); sprite.draw(batch); } } for(Sprite sprite:papas) { if(abner.getBoundingRectangle().overlaps(sprite.getBoundingRectangle())){ abner.setPapas(abner.getPapas()+4); recarga.play(); papas.removeIndex(papas.indexOf(sprite, true)); } else { if(mapa.colisionY(sprite.getX()+sprite.getWidth()/2, sprite.getY()-10)==-1) sprite.translate(0,-10); sprite.draw(batch); } } for (int i=0;i<proyectiles.size();i++) { Proyectil proyectil = proyectiles.get(i); if(proyectil instanceof Proyectil.Papa&&mapa.colisionPuertaCerrada(proyectil.getRectangle().getX()-proyectil.getRectangle().getWidth(), proyectil.getRectangle().getY())){ mapa.remove("PuertaCerrada"); proyectiles.remove(i); abner.setArmario(true); gameInfo.actualizarDatosTemp(); } else if(proyectil.out()) { proyectiles.remove(i); } else{ proyectil.draw(batch); } } if(mapaActual!=2&&mapaActual!=6&&!abner.subiendo()) mapa.drawE(); else if(mapaActual==2&&!abner.subiendo()){ mapa.drawE(); } else if(mapaActual == 6&&!abner.subiendo()){ mapa.drawE(); } batch.end(); if(estado ==Estado.CAMBIO){ switch (transicion){ case AUMENTANDO: pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); alpha = 1; transicion = Transicion.DISMINUYENDO; break; case DISMINUYENDO: alpha-= velocidadTransicion; if (alpha<=0) { estado = Estado.JUGANDO; alpha = 0; } break; } } transicionNivel.setAlpha(alpha); batch.setProjectionMatrix(camaraHUD.combined); saveB = abner.guardar(); if(saveB) botonSave.desaparecer(!saveB); else botonSave.desaparecer(!saveB); batch.begin(); if(cinematicaPelea&&barraCoco!=null){ barraCoco.draw(batch); cascaronBarraCoco.draw(batch); } botonSaltar.draw(batch); pad.draw(batch); botonHabilidad.draw(batch); botonSave.draw(batch); botonArma.draw(batch); botonMapa.draw(batch); if(abner.getCapita()){ flechasHabilidad.draw(batch); } if(abner.getLanzapapas()){ flechasArma.draw(batch); } if(abner.getPogo()){ flechasSalto.draw(batch); } pausa.draw(batch); imgVida.draw(batch); if(estadoArma == Arma.LANZAPAPAS){ imgMunicion.draw(batch); municionTex.mostrarMensaje(batch, abner.getMunicion()+""); } vida.mostrarMensaje(batch, "" + abner.getcantVida()); gameInfo.draw(batch); for(int i = 0;i<abner.getVidas();i++) vidas.get(i).draw(batch); transicionNivel.draw(batch); batch.end(); } else if(estado == Estado.PAUSA){ pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); switch (estadoPausa){ case PRINCIPAL: pausaActual.setTexture(pausaTex); break; case QUIT: pausaActual.setTexture(quitTex); break; case OPCIONES: pausaActual.setTexture(opciones); break; } batch.setProjectionMatrix(camaraHUD.combined); batch.begin(); pausaActual.draw(batch); batch.end(); } else if(estado == Estado.MUERTE){ if(ambiente.isPlaying()) ambiente.stop(); if(alphaGame<1&&musica) gameover.play(); batch.setProjectionMatrix(camara.combined); mapa.draw(); alphaGame+= TRANSICIONNEUTRAL; if(alphaGame>=1) alphaGame=1; menuGameOver.setAlpha(alphaGame); batch.setProjectionMatrix(camaraHUD.combined); batch.begin(); menuGameOver.draw(batch); batch.end(); } if(estado == Estado.MAPA){ batch.setProjectionMatrix(camara.combined); batch.begin(); miniMapa.draw(batch); marcardor.draw(batch); batch.end(); batch.setProjectionMatrix(camaraHUD.combined); batch.begin(); indicaciones.draw(batch); botonMapaBack.draw(batch); batch.end(); } } private boolean jardin() { return mapaActual == 6 || mapaActual ==7||mapaActual==8; } public static boolean sotano() { return (abner.getLampara()&&mapaActual==12)||mapaActual == 13 || mapaActual ==14||mapaActual == 15; } private void saltoSiguiente(){ if(abner.getPogo()){ if(saltoActual==Salto.POGO){ saltoActual = Salto.NORMAL; } else if(saltoActual == Salto.NORMAL){ saltoActual = Salto.POGO; } } switch (saltoActual){ case NORMAL: botonSaltar.setTexture(botonSalto); break; case POGO: botonSaltar.setTexture(habilidadPogo); break; } } private void habilidadSiguiente() { if(habilidadActual!= Habilidad.VACIA){ switch (habilidadActual){ case LAMPARA: if(abner.capita){ estadoLampara = Lampara.APAGADA; abner.setLampara(estadoLampara); habilidadActual = Habilidad.CAPITA; } break; case CAPITA: if(!capaActiva) habilidadActual = Habilidad.LAMPARA; break; } } } @Override public void resize(int width, int height) { vista.update(width, height); } @Override public void pause() { } @Override public void resume() { } public static Lampara getEstadoLampara(){ return estadoLampara; } @Override public void hide() { dispose(); } @Override public void dispose() { //batch.dispose(); //abner.dispose(); mapa.dispose(); assetManager.dispose(); } static void agregarItem(float x, float y){ Random rnd = new Random(); switch (rnd.nextInt(2)){ case 0: Sprite sprite = new Sprite(malteada); sprite.setPosition(x,y); malteadas.add(sprite); break; case 1: Sprite sprite1 = new Sprite(papa); sprite1.setPosition(x,y); papas.add(sprite1); break; } } static void agregarItem(Enemigo enemigo){ if(!abner.getLanzapapas()){ Random rnd = new Random(); int i = rnd.nextInt(2); if(i==0){ Sprite sprite = new Sprite(malteada); sprite.setPosition(enemigo.getX(), enemigo.getY()+100); malteadas.add(sprite); } } else { Random rnd = new Random(); int i = rnd.nextInt(3); if(i==0){ Sprite sprite = new Sprite(malteada); sprite.setPosition(enemigo.getX(), enemigo.getY()+100); malteadas.add(sprite); } else if(i==1){ Sprite sprite = new Sprite(papa); sprite.setPosition(enemigo.getX(), enemigo.getY()+100); papas.add(sprite); } } } @Override public boolean keyDown(int keycode) { if(keycode == Input.Keys.BACK){ if(estado==Estado.JUGANDO||estado == Estado.CAMBIO){ estado = Estado.PAUSA; estadoPausa = EstadoPausa.QUIT; abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); } else if(estado == Estado.PAUSA){ if(estadoPausa == EstadoPausa.PRINCIPAL){ estado = Estado.JUGANDO; } else if(estadoPausa==EstadoPausa.QUIT||estadoPausa == EstadoPausa.OPCIONES){ estadoPausa = EstadoPausa.PRINCIPAL; } } } return true; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { Vector3 v = new Vector3(screenX, screenY, 0); camaraHUD.unproject(v); float x = v.x; float y = v.y; if(estado == Estado.JUGANDO) { if (pad.getLeft().contiene(x, y)){ pad.getLeft().setEstado(Boton.Estado.PRESIONADO); leftPointer = pointer; } if (pad.getRight().contiene(x, y)){ pad.getRight().setEstado(Boton.Estado.PRESIONADO); leftPointer = pointer; } if (botonSaltar.contiene(x, y)){ switchedSalto = false; switchSalto = true; rightPointer = pointer; } if (botonArma.contiene(x, y)){ switchAtaque = true; rightPointer = pointer; switchedAtaque = false; } if(pausa.contiene(x,y)) estado = Estado.PAUSA; if(botonMapa.contiene(x,y)) { estado = Estado.MAPA; camaraInicialY = camara.position.y; camaraInicialX = camara.position.x; setPositionMarker(); camara.position.set(miniMapa.getWidth()/2, miniMapa.getHeight()/2, 0); camara.update(); } if(saveB) { if(botonSave.contiene(x,y)) { gameInfo.guardarJuego(); botonSave.setEstado(Boton.Estado.PRESIONADO); } } if(abner.getLampara()){ if(botonHabilidad.contiene(x,y)) { switchHabilidad = true; rightPointer = pointer; switchedHabilidad = false; } } } if(estado == Estado.PAUSA){ switch (estadoPausa){ case PRINCIPAL: if(botonResume.contiene(x,y)) estado = Estado.JUGANDO; if(botonOpciones.contiene(x,y)) estadoPausa = EstadoPausa.OPCIONES; if(botonQuit.contiene(x,y)) estadoPausa = EstadoPausa.QUIT; break; case QUIT: if(botonNo.contiene(x,y)) estadoPausa = EstadoPausa.PRINCIPAL; if(botonYes.contiene(x,y)){ juego.setScreen(new MenuPrincipal(juego)); stop(); } break; case OPCIONES: if(botonOn.contiene(x,y)){ musica = true; } else if(botonOff.contiene(x,y)){ musica = false; stop(); } else if(botonBack.contiene(x,y)) estadoPausa = EstadoPausa.PRINCIPAL; break; } } if(estado == Estado.MUERTE){ if(botonMain.contiene(x,y)){ juego.setScreen(new MenuPrincipal(juego)); if(gameover.isPlaying()) gameover.stop(); mapa.stop(); } if(botonTry.contiene(x,y)){ reiniciarEscena(); gameover.stop(); alphaGame = 0; } } if(estado == Estado.MAPA){ if(botonMapaBack.contiene(x,y)){ estado = Estado.JUGANDO; camara.position.set(camaraInicialX, camaraInicialY, 0); } xInicial = x; yInicial = y; } return false; } private void reiniciarEscena() { abner.reiniciar(gameInfo); mapaActual = gameInfo.getMapa(); alpha = 0; mapa.stop(); mapa.dispose(); mapa = mapManager.getNewMapa(mapas.get(mapaActual),mapaActual, abner, gameInfo); abner.setMapa(mapa); enemigos = mapa.getEnemigos(); if(cinematicaPelea){ cinematicaPelea = false; } if(!gameInfo.isLampara()){ habilidadActual = Habilidad.VACIA; } if(!gameInfo.isLanzapapas()){ estadoArma = Arma.RESORTERA; } if(!gameInfo.isPogo()){ saltoActual = Salto.NORMAL; } botonHabilidad.setEstado(Boton.Estado.NOPRESIONADO); botonSaltar.setEstado(Boton.Estado.NOPRESIONADO); pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); botonArma.setEstado(Boton.Estado.NOPRESIONADO); estado = Estado.JUGANDO; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { Vector3 v = new Vector3(screenX, screenY, 0); camaraHUD.unproject(v); float x = v.x; float y = v.y; if(estado == Estado.JUGANDO){ if(pad.getLeft().contiene(x,y)&&pointer==leftPointer) { pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); leftPointer =-1; } if(pad.getRight().contiene(x,y)&&pointer==leftPointer) { pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); leftPointer =-1; } if(botonArma.contiene(x,y)&&(!abner.isAttacking())&&pointer==rightPointer&&!switchedAtaque){ botonArma.setEstado(Boton.Estado.PRESIONADO); switchAtaque = false; rightPointer = -1; } if(abner.getLampara()&&botonHabilidad.contiene(x,y)&&!abner.isAttacking()&&!switchedHabilidad&&pointer==rightPointer){ botonHabilidad.setEstado(Boton.Estado.PRESIONADO); switchHabilidad = false; rightPointer = -1; } if(botonSaltar.contiene(x,y)&&(!abner.isJumping())&&(!abner.isAttacking())&&!switchedSalto&&pointer==rightPointer){ switchSalto = false; botonSaltar.setEstado(Boton.Estado.PRESIONADO); rightPointer = -1; } } return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { Vector3 v = new Vector3(screenX, screenY, 0); camaraHUD.unproject(v); float x = v.x; float y = v.y; if(estado == Estado.JUGANDO){ if(pad.getLeft().contiene(x,y)&&leftPointer==pointer) { pad.getLeft().setEstado(Boton.Estado.PRESIONADO); } else if(leftPointer==pointer){ pad.getLeft().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); } if(pad.getRight().contiene(x,y)&&leftPointer==pointer) pad.getRight().setEstado(Boton.Estado.PRESIONADO); else if (leftPointer==pointer){ pad.getRight().setEstado(Boton.Estado.NOPRESIONADO); abner.setEstadoHorizontal(Abner.Horizontal.DESACTIVADO); } if(!botonArma.contiene(x,y)&&switchAtaque&&rightPointer==pointer){ ataqueSiguiente(); switchAtaque = false; switchedAtaque= true; } if(!botonSaltar.contiene(x,y)&switchSalto&&rightPointer == pointer){ saltoSiguiente(); switchSalto = false; switchedSalto = true; } if(!botonHabilidad.contiene(x,y)&&switchHabilidad&&rightPointer==pointer){ habilidadSiguiente(); switchHabilidad = false; switchedHabilidad = true; } } if(estado == Estado.MAPA){ deslizarCamara(x,y); xInicial = x; yInicial = y; } return false; } private void deslizarCamara(float x, float y) { float incX = xInicial - x; float incY = yInicial -y; if(camara.position.y+incY<=miniMapa.getHeight()-400&&camara.position.y+incY>=400) camara.position.y = camara.position.y+incY; if(camara.position.x+incX<=miniMapa.getWidth()-640&&camara.position.x+incX>=640) camara.position.x = camara.position.x+incX; camara.update(); } public static boolean getCapa(){ return capaActiva; } private void ataqueSiguiente() { switch(estadoArma){ case LANZAPAPAS: estadoArma = Arma.RESORTERA; break; case RESORTERA: estadoArma = abner.lanzapapas? Arma.LANZAPAPAS: estadoArma; break; } switch(estadoArma){ case LANZAPAPAS: botonArma.setTexture(habilidadLanzaPapas); break; case RESORTERA: botonArma.setTexture(habilidad); break; } } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } private void setPositionMarker(){ Rectangle zona = zonasMinimapas.get(mapaActual); float relacionX = zona.getWidth()/mapa.getWidth(); float relacionY = zona.getHeight()/mapa.getHeight(); marcardor.setPosition((zona.getX()+abner.getX()*relacionX)-(marcardor.getWidth()/2), zona.getY()+abner.getY()*relacionY); } @Override public boolean scrolled(int amount) { return false; } public void stop(){ if(ambiente.isPlaying()){ ambiente.stop(); } if(sonidos.isPlaying()){ sonidos.stop(); } if(gameover.isPlaying()){ gameover.stop(); } if(leche.isPlaying()){ leche.stop(); } if(recarga.isPlaying()){ recarga.stop(); } mapa.stop(); abner.stop(); } private enum EstadoPausa{ PRINCIPAL, OPCIONES, QUIT } private enum Estado{ JUGANDO, CINEMATICA, CAMBIO, PAUSA, MUERTE, GANO, MAPA } public enum Transicion{ AUMENTANDO, DISMINUYENDO } public enum Habilidad{ VACIA, LAMPARA, CAPITA } public enum Arma{ RESORTERA, LANZAPAPAS } public enum Salto{ POGO, NORMAL } public enum Lampara{ ENCENDIDA, ENCENDIDALUZ, APAGADA } public enum Capa{ APAGADA, CAPA25, CAPA50, CAPA75, CAPA100 } }
package war; /* * 2. Create a class called App with a main method. */ public class App { public static void main(String[] args) { /* * 3. Instantiate a Deck and two Players, call the shuffle method on the deck */ // Create a new deck of class Deck Deck deck = new Deck(); // Create a new player of class Player, assign it the value of player 1 Player player1 = new Player("player 1 draws: \n"); // Create a new player of class Player, assign it the value of player 2 Player player2 = new Player("player 2 draws \n"); // Shuffle the deck before playing deck.shuffle(); /* * 4. Using a traditional for loop, iterate 52 times * calling the Draw method on the other player each iteration * using the Deck you instantiated. */ //Create a for loop that will loop through the deck for (int i = 0; i < 52; i++) { // If even player one draws a card if ( i % 2 == 0) { //player one draws card player1.draw(deck); // if odd player two draws card } else { //player two draws card player2.draw(deck); } } // Call describe from Player for player1 player1.describe(); // Call describe from Player for player2 player2.describe(); /* * 5. Using a traditional for loop, iterate 26 times and call the flip method for each player. * a. Compare the value of each card returned by the two player’s flip methods. Call * the incrementScore method on the player whose card has the higher value. */ /* Create a for loop what will go through half the deck, * return flip from player, * get the value and increase score if on flip is higher then the other. */ for (int i = 0; i < 26; i++) { // Player 1 will flip each iteration Card player1Card = player1.flip(); // player 2 will flip each iteration Card player2Card = player2.flip(); // if player 1 card value is higher then player 2 then increment player1 score if (player1Card.getValue() > player2Card.getValue()) { player1.incrementScore(); // if player 2 card value is higher then player 1 then increment player2 score } else if (player1Card.getValue() < player2Card.getValue()) { player2.incrementScore(); } } /* * 6. After the loop, compare the final score from each player. */ // If player one's score is greater then print player one wins. if (player1.getScore() > player2.getScore()) { System.out.println("Player1 wins."); // If player two's score is greater then print player two wins. } else if (player1.getScore() < player2.getScore()) { System.out.println("Player2 wins."); //if player one and player two scores are the same then print draw } else { System.out.println("Draw."); } /* * 7. Print the final score of each player and either “Player 1”, “Player 2”, * or “Draw” depending on which score is higher or if they are both the same. */ // Print Player1 score. System.out.printf("Player1 score = %d\n", player1.getScore()); // print Player2 score. System.out.printf("Player2 score = %d\n", player2.getScore()); } }
package com.wb.welfare.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.wb.welfare.dominio.Cliente; import com.wb.welfare.repository.ClienteRepository; @Controller public class ClienteController { @Autowired private ClienteRepository clienteRepository; @RequestMapping(method=RequestMethod.GET, value="/cadastrocliente") public ModelAndView cadastro() { ModelAndView modelAndView = new ModelAndView("cadastro/cadastrocliente"); modelAndView.addObject("clientebj",new Cliente()); return modelAndView; } @RequestMapping(method=RequestMethod.POST, value="**/salvarcliente") public ModelAndView salvar(Cliente cliente) { clienteRepository.save(cliente); ModelAndView andView = new ModelAndView("cadastro/cadastrocliente"); Iterable<Cliente> clientesIt = clienteRepository.findAll(); andView.addObject("clientes", clientesIt); andView.addObject("clientebj",new Cliente()); return andView; } }
package OOP.Constructors.this_usage; public class Cat { String name; int age; // Cat(String n, int ag){ // Name: Barsik, Age; 5. It's ok, because names are different // name = n; // age = ag; // } // Cat(String name, int age){ // Name: null, Age; 0. When we use the same names, as we should by convention, we face problems // name = name; // age = age; // } Cat(String name, int age){ // Name: Barsik, Age; 5. The right way! this.name = name; this.age = age; } }
public class typeClass { /* public static void main(String args[]) { long ci; long im; im = 5280 * 12; ci = im * im * im; System.out.println("B одной кубической миле содержится " + ci +" кубических дюймов"); } public static void main(String args[]) { double x, у, z; x = 3; у = 4; z = Math.sqrt(x*x + у*у); System.out.println("Длинa гипотенузы: " +z); } */ public static void main(String args[]) { boolean b; b = false; System.out.println("Знaчeниe b: " + b); b = true; System.out.println("Знaчeниe b " + b); // Логическое значение можно использовать для // управления условным оператором if if (b) { System.out.println("Эта инструкция вьполняется"); } b = false; if (b) { System.out.println("Этa инструкция не выполняется"); } // В результате выполнения сравнения получается логическое значение System.out.println("Peзyльтaт сравнения 10 > 9: " + (10 > 9)); } }
package com.example.driver.repositories; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.example.driver.models.License; public interface LicenseRepository extends CrudRepository<License, Long>{ List<License> findAll(); }
// package us.team7pro.EventTicketsApp.Services; // import org.springframework.stereotype.Service; // import us.team7pro.EventTicketsApp.Models.Event; // import org.springframework.context.annotation.Primary; // import java.util.LinkedList; // import java.util.List; // import java.util.Objects; // import java.util.stream.Collectors; // /** // * This class is just for testing // */ // @Service // @Primary // public class EventServiceStubImpl implements EventService { // private List<Event> events = new LinkedList<>(); // // public EventServiceStubImpl() { // // events.add(new Event(1, "Event Dummy 1", "Concerts", "Albany")); // // events.add(new Event(2, "Event Dummy 2", "Sports", "Canada")); // // events.add(new Event(3, "Event Dummy 3", "Festival", "Troy")); // // events.add(new Event(6, "Event Dummy 6", "Concerts", "New Jersey")); // // events.add(new Event(5, "Event Dummy 5", "Theater", "Queens")); // // events.add(new Event(4, "Event Dummy 4", "Concerts", "Long Island")); // // } // @Override // public List<Event> findAll() { // return this.events; // } // @Override // public List<Event> findLatest4() { // return this.events.stream() // .sorted((a,b)->b.getEventCategory().compareTo(a.getEventCategory())) // .limit(4).collect(Collectors.toList()); // } // @Override // public List<Event> findLatest5() { // return this.events.stream() // .sorted((a,b)->b.getEventCategory().compareTo(a.getEventCategory())) // .limit(5).collect(Collectors.toList()); // } // @Override // public Event findByEventID(int eventID) { // return this.events.stream().filter(e-> Objects.equals(e.getEventID(), eventID)) // .findFirst().orElse(null); // } // }
package com.example.xml; import java.util.ArrayList; import java.util.List; import com.example.xml.domain.Person; import com.example.xml.service.PersonService; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.TextureView; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv_play; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_play = (TextView) findViewById(R.id.tv_play); PersonService service = new PersonService(this); /***********这是演示解析XML文件****************/ List<Person> persons = service.getPersons("person.xml"); StringBuffer sb = new StringBuffer(); for(Person person : persons){ String age ="年龄"+person.getAge(); String name = person.getName(); String id = "id"+person.getId(); sb.append(name+""+age+""+id); } tv_play.setText(sb.toString()); /*************这是演示生成一个XML文件*******************/ List<Person> personsl = new ArrayList<Person>(); Person person1 = new Person(21,"张三",18); Person person2 = new Person(13,"李四",19); Person person3 = new Person(43,"王五",20); Person person4 = new Person(28,"刘琪",78); personsl.add(person1); personsl.add(person2); personsl.add(person3); personsl.add(person4); service.savePersonToXml(personsl); } }
package ChainOfResponsibilityPattern14.exercise.service.serviceImp; import ChainOfResponsibilityPattern14.exercise.entity.Vacation; import ChainOfResponsibilityPattern14.exercise.service.Allover; /** * @Author Zeng Zhuo * @Date 2020/5/4 17:08 * @Describe */ public class Director extends Allover { public Director(String name) { super(name); } @Override public String approval(Vacation vacation) { if(vacation.getDays()<3){ System.out.println("主任:" + this.name + " 审批 " + vacation.getApplicant() + " 的假条,允许请假" + vacation.getDays()+"天"); return "主任审核通过"; }else{ return this.allover.approval(vacation); } } }
package simple_armors_mod; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.server.FMLServerHandler; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; public class Armory extends Item { public Armory(int par1, int item) { super(par1); this.LoadsetItem(item); } private String iconPath; private boolean initialized = false; public void LoadsetItem(int item){ if(!initialized){ if(FMLServerHandler.instance().getServer() != null){ System.out.println("The Server Does Not Require Texutre For the Mod, skipping textures"); } else if(FMLServerHandler.instance().getServer() == null){ System.out.println("Loading textures "); this.setItem(item); initialized = true; } } } /* 0 = ObsidianScale 1 = BrushCamo 2 = Stone Plate 3 = SoulBlade Hilt 4 = SoulBlade Razor 5 = SoulBlade Tip 6 = Hardened Leather 7 = Diamond Shards 8 = Salt 9 = Tin Ingot 10 = Tin Pan 11 = Dough 12 = ChainLink 13 = IronChunk 14 = GoldChain 15 = GoldChunk */ @SideOnly(Side.CLIENT) private void setItem(int type){ switch (type){ case 0: this.setUnlocalizedName("ObsidianScale"); this.iconPath = "armory:ObsidianScale"; break; case 1: this.setUnlocalizedName("BrushCamo"); this.iconPath = "armory:BrushCamo"; break; case 2: this.setUnlocalizedName("StonePlate"); this.iconPath = "armory:StonePlate"; break; case 3: this.setUnlocalizedName("SoulHilt"); this.iconPath = "armory:SoulHilt"; break; case 4: this.setUnlocalizedName("SoulRazor"); this.iconPath = "armory:SoulRazor"; break; case 5: this.setUnlocalizedName("SoulTip"); this.iconPath = "armory:SoulTip"; break; case 6: this.setUnlocalizedName("HardenedLeather"); this.iconPath = "armory:HardenedLeather"; break; case 7: this.setUnlocalizedName("DiamondShards"); this.iconPath = "armory:DiamondShards"; break; case 8: this.setUnlocalizedName("Salt"); this.iconPath = "armory:Salt"; break; case 9: this.setUnlocalizedName("TinIngot"); this.iconPath = "armory:TinIngot"; break; case 10: this.setUnlocalizedName("TinPan"); this.iconPath = "armory:TinPan"; break; case 11: this.setUnlocalizedName("Dough"); this.iconPath = "armory:Dough"; break; case 12: this.setUnlocalizedName("ChainLink"); this.iconPath = "armory:ChainLink"; break; case 13: this.setUnlocalizedName("IronChunk"); this.iconPath = "armory:IronChunk"; break; case 14: this.setUnlocalizedName("GoldChain"); this.iconPath = "armory:GoldChain"; break; case 15: this.setUnlocalizedName("IronChunk"); this.iconPath = "armory:GoldChunk"; break; } } public void registerIcons(IconRegister icon){ this.itemIcon = icon.registerIcon(this.iconPath); } }
package com.fhsoft.word.control; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSON; import com.fhsoft.base.bean.JsonResult; import com.fhsoft.base.bean.Page; import com.fhsoft.model.SubjectProperty; import com.fhsoft.model.Users; import com.fhsoft.model.Word; import com.fhsoft.util.ExcelContentParser; import com.fhsoft.word.service.ClassicalWordService; /** * * @Classname com.fhsoft.word.control.ModenWordCtrol * @Description * * @author lw * @Date 2015-11-5 上午9:56:27 * */ @Controller public class ClassicalWordCtrol { @Autowired private ClassicalWordService wordService; private Logger logger = Logger.getLogger(ClassicalWordCtrol.class); @RequestMapping("toClassicalWordList.do") public String czyw(){ return "word/classicalWordList"; } @RequestMapping("addClassicalWord") @ResponseBody public Object addWord(HttpServletRequest request, HttpServletResponse response,HttpSession session,Word word){ Users u = (Users) session.getAttribute("user_info"); word.setCreator_id(u.getId()+""); word.setLastModifierId(u.getId()+""); word.setLastModifier(u.getName()); word.setCreator(u.getName()); JsonResult result = new JsonResult(); try { wordService.addWord(word); result.setSuccess(true); result.setMsg("添加成功!"); } catch (Exception e) { result.setMsg("添加失败!"); logger.error("文言文字词添加失败!", e); } return JSON.toJSONString(result); } @RequestMapping("updateClassicalWord") @ResponseBody public Object updateWord(HttpServletRequest request, HttpServletResponse response,HttpSession session,Word word){ JsonResult result = new JsonResult(); try { Users u = (Users) session.getAttribute("user_info"); word.setLastModifierId(u.getId()+""); word.setLastModifier(u.getName()); wordService.updateWord(word); result.setSuccess(true); result.setMsg("修改成功!"); } catch (Exception e) { result.setMsg("修改失败!"); logger.error("文言文字词修改失败!", e); } return JSON.toJSONString(result); } @RequestMapping("delClassicalWord") @ResponseBody public Object delWord(HttpServletRequest request, HttpServletResponse response,Word word){ JsonResult result = new JsonResult(); try { wordService.delWord(word); result.setSuccess(true); result.setMsg("删除成功!"); } catch (Exception e) { result.setMsg("删除失败!"); logger.error("文言文字词删除失败!", e); } return JSON.toJSONString(result); } @RequestMapping("classicalWordList") @ResponseBody public Object classicalWordList(HttpServletRequest request, HttpServletResponse response,Word word){ int pageRows=20; int page=1; if(null!=request.getParameter("rows")){ pageRows=Integer.parseInt(request.getParameter("rows").toString()); } if(null!=request.getParameter("page")){ page=Integer.parseInt(request.getParameter("page").toString()); } Page pageInfo = null; try { pageInfo = wordService.list(page,pageRows,word); } catch(Exception e) { e.printStackTrace(); logger.error("得到文言文字词信息出错", e); } return pageInfo; } @RequestMapping("uploadClassicalWord") @ResponseBody public Object uploadClassicalWord(MultipartFile file,HttpServletRequest request, HttpServletResponse response,HttpSession session){ JsonResult result = new JsonResult(); try { ExcelContentParser<Word> parser = new ExcelContentParser<Word>(); Users u = (Users) session.getAttribute("user_info"); List<Word> list = new ArrayList<Word>(); String[] propertyNames = {"name","soundmark","type","property","meaning","example"}; parser.parseExcel(list, Word.class, file.getInputStream(), propertyNames, file.getOriginalFilename(), 1); String msg = wordService.save(list,u); if("success".equals(msg)) { result.setSuccess(true); result.setMsg("上传成功"); } else { result.setSuccess(false); result.setMsg(msg); } } catch (Exception e) { result.setMsg("导入失败!"); logger.error("文言文字词导入失败!", e); } return JSON.toJSONString(result); } @RequestMapping("addExampleClassicalWord") @ResponseBody public Object addExampleWord(HttpServletRequest request, HttpServletResponse response,Word word){ JsonResult result = new JsonResult(); try { int id = wordService.addExample(word); result.setSuccess(true); result.setObj(id); result.setMsg("添加成功!"); } catch (Exception e) { result.setMsg("添加失败!"); logger.error("文言文字词添加失败!", e); } return JSON.toJSONString(result); } @RequestMapping("updateAdditionalClassicalWord") @ResponseBody public Object updateAdditionalWord(HttpServletRequest request, HttpServletResponse response,Word word){ JsonResult result = new JsonResult(); try { wordService.updateAdditionalWord(word); result.setSuccess(true); result.setMsg("修改成功!"); } catch (Exception e) { result.setMsg("修改失败!"); logger.error("文言文字词附加信息修改失败!", e); } return JSON.toJSONString(result); } @RequestMapping("updExampleClassicalWord") @ResponseBody public Object updExampleWord(HttpServletRequest request, HttpServletResponse response,Word word){ JsonResult result = new JsonResult(); try { wordService.updExampleWord(word); result.setSuccess(true); result.setMsg("修改成功!"); } catch (Exception e) { result.setMsg("修改失败!"); logger.error("文言文字词例句修改失败!", e); } return JSON.toJSONString(result); } @RequestMapping("delClassicalExample") @ResponseBody public Object delExample(HttpServletRequest request, HttpServletResponse response,Word word){ JsonResult result = new JsonResult(); try { wordService.delExample(word); result.setSuccess(true); result.setMsg("删除成功!"); } catch (Exception e) { result.setMsg("删除失败!"); logger.error("文言文字词删除失败!", e); } return JSON.toJSONString(result); } @RequestMapping("getClassicalWordInfo") @ResponseBody public Object getWordInfo(HttpServletRequest request, HttpServletResponse response, Word word){ JsonResult result = new JsonResult(); try { List<Word> list = wordService.getWordInfo(word); List<SubjectProperty> sps = wordService.getJctxOfYw(); List<Word> ws = wordService.getWordJctx(word); Map<String,Object> obj = new HashMap<String, Object>(); obj.put("list", list); obj.put("sps", sps); obj.put("ws", ws); result.setObj(obj); result.setSuccess(true); } catch (Exception e) { result.setSuccess(false); result.setMsg("查询字词信息失败!"); logger.error("查询文言文字词信息失败!", e); } return JSON.toJSONString(result); } @RequestMapping("getClassicalExampleById") @ResponseBody public Object getExampleById(HttpServletRequest request, HttpServletResponse response, Word word){ try { word = wordService.getExampleById(word); } catch (Exception e) { logger.error("查询字词例句信息失败!", e); } return word; } @RequestMapping("getClassicalWordBasic") @ResponseBody public Object getClassicalWordBasic(HttpServletRequest request, HttpServletResponse response, Word word){ try { word = wordService.getClassicalWordBasic(word); } catch (Exception e) { logger.error("查询字词基本信息失败!", e); } return word; } @RequestMapping("getClassicalWordAdditional") @ResponseBody public Object classicalword_additional(HttpServletRequest request, HttpServletResponse response, Word word){ try { word = wordService.getClassicalWordAdditional(word); } catch (Exception e) { logger.error("查询字词附加信息失败!", e); } return word; } }
// Generated by view binder compiler. Do not edit! package com.designurway.idlidosa.databinding; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import androidx.viewbinding.ViewBinding; import com.designurway.idlidosa.R; import java.lang.NullPointerException; import java.lang.Override; import java.lang.String; public final class FragmentFeaturedBinding implements ViewBinding { @NonNull private final FrameLayout rootView; @NonNull public final ImageView appLogoIv; @NonNull public final RelativeLayout noDataLy; @NonNull public final RecyclerView recyclerFeaturefragment; private FragmentFeaturedBinding(@NonNull FrameLayout rootView, @NonNull ImageView appLogoIv, @NonNull RelativeLayout noDataLy, @NonNull RecyclerView recyclerFeaturefragment) { this.rootView = rootView; this.appLogoIv = appLogoIv; this.noDataLy = noDataLy; this.recyclerFeaturefragment = recyclerFeaturefragment; } @Override @NonNull public FrameLayout getRoot() { return rootView; } @NonNull public static FragmentFeaturedBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, null, false); } @NonNull public static FragmentFeaturedBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) { View root = inflater.inflate(R.layout.fragment_featured, parent, false); if (attachToParent) { parent.addView(root); } return bind(root); } @NonNull public static FragmentFeaturedBinding bind(@NonNull View rootView) { // The body of this method is generated in a way you would not otherwise write. // This is done to optimize the compiled bytecode for size and performance. int id; missingId: { id = R.id.app_logo_iv; ImageView appLogoIv = rootView.findViewById(id); if (appLogoIv == null) { break missingId; } id = R.id.no_data_ly; RelativeLayout noDataLy = rootView.findViewById(id); if (noDataLy == null) { break missingId; } id = R.id.recycler_featurefragment; RecyclerView recyclerFeaturefragment = rootView.findViewById(id); if (recyclerFeaturefragment == null) { break missingId; } return new FragmentFeaturedBinding((FrameLayout) rootView, appLogoIv, noDataLy, recyclerFeaturefragment); } String missingId = rootView.getResources().getResourceName(id); throw new NullPointerException("Missing required view with ID: ".concat(missingId)); } }
package io.pivotal.racquetandroid.model.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Player { private String name = ""; private String twitterHandle = ""; private String profileImageUrl = ""; private int wins; private int losses; private int points; private double winningPercentage; public double getWinningPercentage() { return winningPercentage; } public void setWinningPercentage(double winningPercentage) { this.winningPercentage = winningPercentage; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public int getLosses() { return losses; } public void setLosses(int losses) { this.losses = losses; } public int getWins() { return wins; } public void setWins(int wins) { this.wins = wins; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTwitterHandle() { return twitterHandle; } public void setTwitterHandle(String twitterHandle) { this.twitterHandle = twitterHandle; } public String getProfileImageUrl() { return profileImageUrl; } public void setProfileImageUrl(String profileImageUrl) { this.profileImageUrl = profileImageUrl; } @Override public boolean equals(Object otherPlayer) { return otherPlayer instanceof Player && ((Player)otherPlayer).twitterHandle.equals(twitterHandle); } @Override public int hashCode() { return twitterHandle.hashCode(); } }
package recuperacion; import java.io.IOException; public class EsVocal { public static void main(String[] args) throws IOException { System.out.println("introduce un carácter:"); char car = (char) System.in.read(); if(esVocal(car)) System.out.println(car+ " es vocal"); else System.out.println(car+ " no es vocal"); } ///////////////////////////////////////////////7 public static boolean esVocal(char car) { return (car == 'a' || car == 'A' || car == 'e' || car == 'E' || car == 'i' || car == 'I' || car == 'o' || car =='O' || car == 'u' || car == 'U'); } }
package sign.com.biz.user.dto; public class UserDto { private Integer iduser; // '主键id', private String loginName; // '登录名称', public Integer getIduser() { return iduser; } public void setIduser(Integer iduser) { this.iduser = iduser; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } }
package cn.novelweb.tool.upload.fastdfs.pool; import cn.novelweb.tool.upload.fastdfs.conn.Connection; import org.apache.commons.pool2.KeyedPooledObjectFactory; import org.apache.commons.pool2.impl.GenericKeyedObjectPool; import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig; import java.net.InetSocketAddress; /** * 定义FastDFS连接池对象<br/> * 定义了对象池要实现的功能,对一个地址进行池化Map Pool<br/> * <p>2020-02-03 17:22</p> * * @author LiZW **/ public class ConnectionPool extends GenericKeyedObjectPool<InetSocketAddress, Connection> { /** * 默认构造函数 */ public ConnectionPool(KeyedPooledObjectFactory<InetSocketAddress, Connection> factory, GenericKeyedObjectPoolConfig<Connection> config) { super(factory, config); } /** * 默认构造函数 */ public ConnectionPool(KeyedPooledObjectFactory<InetSocketAddress, Connection> factory) { super(factory); } }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(Dability)设备能力 //generate by redcloud,2020-07-24 19:59:20 public class Dability implements Serializable { private static final long serialVersionUID = 18L; // 主键ID private Long id ; // 厂商 private String corp ; // 协议名称 private String protocolname ; // 发送格式 private String sendformat ; // 设备名称 private String title ; // 头参数 private String header ; // 内容参数 private String body ; // 实际参数 private String actheader ; // 实际参数 private String actbody ; // 动作名称 private String actname ; // 备注 private String memo ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getCorp() { return corp ; } public void setCorp(String corp) { this.corp = corp; } public String getProtocolname() { return protocolname ; } public void setProtocolname(String protocolname) { this.protocolname = protocolname; } public String getSendformat() { return sendformat ; } public void setSendformat(String sendformat) { this.sendformat = sendformat; } public String getTitle() { return title ; } public void setTitle(String title) { this.title = title; } public String getHeader() { return header ; } public void setHeader(String header) { this.header = header; } public String getBody() { return body ; } public void setBody(String body) { this.body = body; } public String getActheader() { return actheader ; } public void setActheader(String actheader) { this.actheader = actheader; } public String getActbody() { return actbody ; } public void setActbody(String actbody) { this.actbody = actbody; } public String getActname() { return actname ; } public void setActname(String actname) { this.actname = actname; } public String getMemo() { return memo ; } public void setMemo(String memo) { this.memo = memo; } }
package MVC.views; import java.awt.GridLayout; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import MVC.controllers.editInvController; import MVC.models.inventoryModel; public class editInvView extends JFrame { private inventoryModel model; private JButton saveButton = new JButton("Save"); private JButton cancelButton = new JButton("Cancel"); private String partName; private String loc; private int quantity; private JLabel nameLabel = new JLabel("Part Name: "); private JLabel locLabel = new JLabel("Location: "); private JLabel qLabel = new JLabel("Quantity: "); private JTextField nameText = new JTextField(255); private JTextField locText = new JTextField(255); private JTextField qText = new JTextField(20); private Date d; private java.util.Date date2; //private JComboBox combo1; private JComboBox combo2; private ArrayList<String> loclist = new ArrayList(); private String[] locations; //private ArrayList<String> partlist = new ArrayList(); //private String[] parts; public editInvView(inventoryModel model) { // TODO Auto-generated constructor stub super("Edit Inventory Item"); this.model = model; GridLayout grid = new GridLayout(6,2); partName = model.getCurrentPartName();/*gets and sets values of currentObject*/ loc = model.getCurrentLocation(); quantity = model.getCurrentInvQ(); String str = Integer.toString(quantity); /* model.getPartsList(); partlist = model.getNameArray(); //System.out.println("combo1 = "+partlist.toString()); parts = new String[partlist.size()]; parts = partlist.toArray(parts); combo1 = new JComboBox(parts);*/ loclist = model.getLocationsArray(); //System.out.println("combo2 = "+loclist.toString()); locations = new String[loclist.size()]; locations = loclist.toArray(locations); combo2 = new JComboBox(locations); nameText.setText(partName); locText.setText(loc); qText.setText(str); this.setLayout(grid); this.add(nameLabel); this.add(nameText); //this.add(combo1); this.add(locLabel); //this.add(locText); this.add(combo2); this.add(qLabel); this.add(qText); this.add(saveButton); this.add(cancelButton); } public void registerListeners(editInvController editInventoryController) { // TODO Auto-generated method stub cancelButton.addActionListener(editInventoryController); saveButton.addActionListener(editInventoryController); } public void closeWindow (){ this.dispose(); } /* * gets text from text fields */ public String getNameText(){ return nameText.getText(); } public int getQText(){ int zero; if (qText.getText().isEmpty()) { zero = 0; } else { zero = Integer.parseInt(qText.getText()); } return zero; //return qText.getText(); } public String getLocText() { return locText.getText(); } }
package hu.juzraai.proxymanager.batch.reader; import org.easybatch.core.reader.RecordReader; import org.easybatch.core.reader.RecordReaderClosingException; import org.easybatch.core.reader.RecordReaderOpeningException; import org.easybatch.core.reader.RecordReadingException; import org.easybatch.core.record.Header; import org.easybatch.core.record.StringRecord; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.util.Date; import java.util.Iterator; /** * Reads an <code>Iterable&lt;String&gt;</code> object and produces {@link * StringRecord} instances. * * @author Zsolt Jurányi */ public class StringIterableReader implements RecordReader { private final Iterator<String> i; private long recordNumber; /** * Creates a new instance. * * @param c The {@link Iterable} to read */ public StringIterableReader(@Nonnull Iterable<String> c) { i = c.iterator(); } /** * Does absolutely nothing. * * @throws RecordReaderClosingException */ @Override public void close() throws RecordReaderClosingException { } /** * @return Name of the datasource */ @Nonnull @Override public String getDataSourceName() { return "collection-reader"; } /** * @return Return <code>null</code> because total record count is not known */ @CheckForNull @Override public Long getTotalRecords() { return null; } /** * @return <code>true</code> if there are more records to read or * <code>false</code> otherwise */ @Override public boolean hasNextRecord() { return i.hasNext(); } /** * Initializes the reader by setting record counter to 0. * * @throws RecordReaderOpeningException */ @Override public void open() throws RecordReaderOpeningException { recordNumber = 0; } /** * Reads the next element from the {@link Iterable} and produces a {@link * StringRecord}. * * @return A {@link StringRecord} which has the element read from the {@link * Iterable} as payload * @throws RecordReadingException */ @Nonnull @Override public StringRecord readNextRecord() throws RecordReadingException { Header header = new Header(++recordNumber, getDataSourceName(), new Date()); return new StringRecord(header, i.next()); } }
package com.jd.jarvisdemonim.ui.testfragment.decorator; import android.content.Context; import android.graphics.drawable.ColorDrawable; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import java.util.Calendar; /** * Auther: Jarvis Dong * Time: on 2017/1/11 0011 * Name: * OverView:用于设置日历的标记背景色; * Usage: */ public class HighLightBgDecorator implements DayViewDecorator { private int color; private Context mContext; public HighLightBgDecorator(Context context, int color) { this.mContext = context; this.color = color; } @Override public boolean shouldDecorate(CalendarDay day) { Calendar calendar = Calendar.getInstance(); day.copyTo(calendar); int i = calendar.get(Calendar.DAY_OF_WEEK); return i == Calendar.SATURDAY || i==Calendar.SUNDAY; } @Override public void decorate(DayViewFacade view) { view.setBackgroundDrawable(new ColorDrawable(color)); } }
package instruments; public class Guitar extends Instrument{ private int numberOfStrings; private GuitarType guitarType; public Guitar(int numberOfStrings, GuitarType guitarType, String material, String type, String colour, int basePrice, int retailPrice, String sound){ super(material, type, colour, basePrice, retailPrice, sound); this.numberOfStrings = numberOfStrings; this.guitarType = guitarType; } public int getNumberOfStrings() { return numberOfStrings; } public GuitarType getGuitarType() { return guitarType; } public String play(String sound) { return sound; } public double calculateMarkup() { return getRetailPrice() - getBasePrice(); } }
/* * Node by Yanfeng Jin (Tony) and Uriel Ulloa */ import java.util.*; /** * Represents a Node for the n-Puzzle */ public class Node{ private static int[][] goal = {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}; //the goal configuration of the board. //Properties of this Node private int size = 3; //3 is the board size for 8-Puzzle. int[][] board; private Node parent; private int depth; //depth of this node //Added boards for my heuristic function private static int[][] board1 = {{1, 2, 3}, {4, 5, 6}, {0, 7, 8}}; private static int[][] board2 = {{1, 2, 3}, {4, 0, 6}, {7, 5, 8}}; private static int[][] board3 = {{1, 2, 3}, {4, 0, 5}, {7, 8, 6}}; private static int[][] board4 = {{1, 2, 0}, {4, 5, 3}, {7, 8, 6}}; /** * Constructor to be used by BFS search. * par - The parent node. * dep - The depth of this node. * brd - The board - a 3x3 array of integers from 0 to 15. * The 0 is the blank spot. */ public Node(Node par, int dep, int[][] brd) { this.parent = par; this.depth = dep; this.board = (int[][]) brd.clone(); } /************* ********** Setter and Getter methods for Node variables ********** *************/ public void setparent(Node par) { this.parent = par; } public Node getparent() { return this.parent; } public void setdepth(int dep) { this.depth = dep; } public int getdepth() { return this.depth; } public void setboard(int[][] brd) { this.board = brd; } public int[][] getboard() { return this.board; } /************* ********** End of Setter and Getter methods ********** *************/ /** * Returns true if the state of this node is the goal state of the puzzle. */ public boolean isGoal() { for(int i=0; i<size; i++) { for(int j=0; j<size; j++) if(board[i][j] != goal[i][j]) return false; } return true; } /** * Returns true if brd is same as this board. */ public boolean isSameBoard(int[][] brd) { for(int i=0; i<size; i++) { for(int j=0; j<size; j++) if(this.board[i][j] != brd[i][j]) return false; } return true; } /** * Expands the current board to create the new states. * The next possible states are based on the current location of the '0' (ie. blank spot) */ public ArrayList<int[][]> expand() { ArrayList<int[][]> nodeslist = new ArrayList<int[][]>(); //If the '0' (blank spot) is at board[0][0], we can either move the blank //down or to the right. if(board[0][0] == 0){ nodeslist.add(moveBlankDown(0, 0)); nodeslist.add(moveBlankRight(0, 0)); } else if (board[0][1]==0) { // Similar to what is provided above, we specify where "0" can move in each situation. nodeslist.add(moveBlankDown(0, 1)); nodeslist.add(moveBlankRight(0, 1)); nodeslist.add(moveBlankLeft(0, 1)); } else if (board[0][2]==0) { nodeslist.add(moveBlankDown(0, 2)); nodeslist.add(moveBlankLeft(0, 2)); } else if (board[1][0]==0) { nodeslist.add(moveBlankUp(1, 0)); nodeslist.add(moveBlankDown(1, 0)); nodeslist.add(moveBlankRight(1, 0)); } else if (board[1][1]==0) { nodeslist.add(moveBlankLeft(1, 1)); nodeslist.add(moveBlankUp(1, 1)); nodeslist.add(moveBlankDown(1, 1)); nodeslist.add(moveBlankRight(1, 1)); } else if (board[1][2]==0) { nodeslist.add(moveBlankLeft(1, 2)); nodeslist.add(moveBlankUp(1, 2)); nodeslist.add(moveBlankDown(1, 2)); } else if (board[2][0]==0) { nodeslist.add(moveBlankUp(2, 0)); nodeslist.add(moveBlankRight(2, 0)); } else if (board[2][1]==0) { nodeslist.add(moveBlankLeft(2, 1)); nodeslist.add(moveBlankUp(2, 1)); nodeslist.add(moveBlankRight(2, 1)); } else if (board[2][2]==0) { nodeslist.add(moveBlankLeft(2, 2)); nodeslist.add(moveBlankUp(2, 2)); } /*TO DO*//////////////////////////////// // for (int[][] node:nodeslist) { // System.out.print(node[0][0]); // System.out.print(node[0][1]); // System.out.println(node[0][2]); // System.out.print(node[1][0]); // System.out.print(node[1][1]); // System.out.println(node[1][2]); // System.out.print(node[2][0]); // System.out.print(node[2][1]); // System.out.println(node[2][2]); // System.out.println("----------"); // } return nodeslist; } /** * Moves the blank down by swapping the '0' with the entry below it */ public int[][] moveBlankDown(int row, int col) { int[][] newboard = new int[size][size]; newboard = copyBoard(); if(row+1<size) swap(newboard, row, col, row+1, col); else System.out.println("row out of bounds in moveBlankDown: "+row); return newboard; } /** * Moves the blank up by swapping the '0' with the entry above it */ public int[][] moveBlankUp(int row, int col) { int[][] newboard = new int[size][size]; newboard = copyBoard(); if(row-1>=0) swap(newboard, row, col, row-1, col); else System.out.println("row out of bounds in moveBlankUp: "+row); return newboard; } /** * Moves the blank right by swapping the '0' with the entry right of it */ public int[][] moveBlankRight(int row, int col) { int[][] newboard = new int[size][size]; newboard = copyBoard(); if(col+1<size) swap(newboard, row, col, row, col+1); else System.out.println("col out of bounds in moveBlankRight: "+col); return newboard; } /** * Moves the blank left by swapping the '0' with the entry left of it */ public int[][] moveBlankLeft(int row, int col) { int[][] newboard = new int[size][size]; newboard = copyBoard(); if(col-1>=0) swap(newboard, row, col, row, col-1); else System.out.println("row out of bounds in moveBlankLeft: "+col); return newboard; } /* * Prints the board configuration of the given Node */ public void print(Node node) { int[][] brd = node.getboard(); for(int i=0; i<size; i++) { for(int j=0; j<size; j++){ if(brd[i][j]==0){ System.out.print(" "); continue; } if (brd[i][j] <10) System.out.print(" "); System.out.print(brd[i][j]); } System.out.println(); } System.out.println(); } /* * Method to determine if two states are equal, where a state is a node or a board. * Parameter o can either be a Node or an int[][] (i.e. the board) */ public boolean equals(Object o) { //if the object to compare is a Node if(o.getClass() == this.getClass()){ if(this.toString().equals( ((Node)o).toString())) return true; else return false; } //if the object to compare is an int[][] else if(o.getClass() == this.board.getClass()){ if(isSameBoard((int[][]) o)) return true; else return false; } //if the object to compare is something weird (code shouldn't come here!) else{ System.out.println("something weird"); return false; } } /** * Returns the String representation of this node's state. */ public String toString() { String sb = ""; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (board[i][j] == 0) { sb += " "; continue; } if (board[i][j] < 10) { sb += " "; } sb+=board[i][j]; } sb+="\n"; } return sb; } /****Private Helper Methods****/ /** * Helper method for the moveBlank methods */ private int[][] copyBoard() { int[][] newboard = new int[size][size]; for(int i=0; i<size; i++){ for(int j=0; j<size; j++) newboard[i][j] = board[i][j]; } return newboard; } /** * Helper method for the moveBlank methods */ private void swap(int[][] node, int x1, int y1, int x2, int y2) { int tmp = node[x1][y1]; node[x1][y1] = node[x2][y2]; node[x2][y2] = tmp; } //------------------A* Code Begins Here-------------------------// private double gvalue; //To be used by A*Star search private double hvalue; //To be used by A*Star search /** * Constructor to be used by A*Star search only. * par - The parent node. * gval - The g-value for this node. * hval - The h-value for this node. * brd - The board which should be a 3x3 array of integers from 0 to 8. */ public Node(Node par, double gval, double hval, int[][] brd) { this.parent = par; this.gvalue = gval; this.hvalue = hval; this.board = (int[][]) brd.clone(); } /************* ********** Setter and Getter methods for A* Search variables ********** *************/ public void setgvalue(double g) { this.gvalue = g; } public double getgvalue() { return this.gvalue; } public void sethvalue(double h) { this.hvalue = h; } public double gethvalue() { return this.hvalue; } /** * Used by A* Search only. * Returns the heuristic value. The heuristic for the state of this node is the sum of Manhattan * distances from each tile's position to that tile's final position. */ public double evaluateHeuristic(int heuristic) { /* * Implementation notes: * Return your heuristic value here, based on the state configuration * stored in "int[][] board". * You may find the method "getManhattanDistance" useful. */ if (heuristic == 0) { int manhattanDistance = 0; // for each value in the current board, calculate its distance to the goal board and add the values together. for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { int goalRow = (getGoalRowsNCols(board[i][j]))[0]; int goalCol = (getGoalRowsNCols(board[i][j]))[1]; manhattanDistance += getManhattanDistance(i,j,goalRow,goalCol); } } return manhattanDistance; } if (heuristic == 1) { } return -1; } /** * Returns the rows and columns of a specific number in the goal state. */ private int[] getGoalRowsNCols (int num) { //finalResult contains the row and column information of where a number lies in the goal state. int[] finalResult = new int[2]; // For example, number 1 should be at (0,0) in the goal state. if (num==1) { finalResult[0] = 0; finalResult[1] = 0; } else if (num==2) { finalResult[0] = 0; finalResult[1] = 1; } else if (num==3) { finalResult[0] = 0; finalResult[1] = 2; } else if (num==4) { finalResult[0] = 1; finalResult[1] = 0; } else if (num==5) { finalResult[0] = 1; finalResult[1] = 1; } else if (num==6) { finalResult[0] = 1; finalResult[1] = 2; } else if (num==7) { finalResult[0] = 2; finalResult[1] = 0; } else if (num==8) { finalResult[0] = 2; finalResult[1] = 1; } else if (num==0) { finalResult[0] = 2; finalResult[1] = 2; } return finalResult; } /** * Helper method used by A* Search only. * Returns the Manhattan distance between the given two cells of the 4x4 board. */ private static int getManhattanDistance(int row1, int col1, int row2, int col2) { return Math.abs(row1 - row2) + Math.abs(col1 - col2); } }
package ru.ifmo.diploma.synchronizer.messages; /* * Created by Юлия on 30.05.2017. */ public abstract class AbstractMsg { String sender; private String recipient; MessageType type; private boolean broadcast; public AbstractMsg() { } //broadcast public AbstractMsg(String sender) { this.sender = sender; broadcast = true; } //unicast public AbstractMsg(String sender, String recipient) { this.sender = sender; this.recipient = recipient; broadcast = false; } public MessageType getType() { return type; } public String getSender() { return sender; } public String getRecipient() { return recipient; } public boolean isBroadcast() { return broadcast; } }