text
stringlengths
10
2.72M
/* * Copyright (c) 2020 Bruno Portaluri (MaximoDev) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mxdev.tidyapp; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * Parses the XML structure of a Maximo application and detects which fields are never used. * We assume all database columns with only one value can be removed. * - Always null (user never entered a value) * - User never changed the default value */ public class TidyApp { static String confDbDriver; static String confDbUrl; static String confUser; static String confPwd; static String confLoglevel; static String inFileName; static String outFileName; static String rootMboName; static String rootResultstableid; static int fieldCount; static int fieldUnusedCount; static MxDD dd; static List<Element> toBeRemoved = new ArrayList<Element>(); static Connection conn = null; static Statement statement = null; static PreparedStatement preparedStatement = null; static ResultSet resultSet = null; public static void main(String[] args) throws Exception { if (args.length!=1) { log("Missing argument: input file"); return; } inFileName = args[0]; outFileName = inFileName.replace(".xml", ".tidy.xml"); File inFile = new File(inFileName); if(!inFile.exists()) { log("Cannot find input file " + inFileName); return; } log("Starting MaximoDev TidyApp"); //log("Reading configuration"); Properties props = new Properties(); FileInputStream fis = new FileInputStream("MxDevTidyApp.properties"); props.load(fis); confDbDriver = props.getProperty("mxe.db.driver"); confDbUrl = props.getProperty("mxe.db.url"); confUser = props.getProperty("mxe.db.user"); confPwd = props.getProperty("mxe.db.password"); confLoglevel = props.getProperty("loglevel"); log("Connecting to Maximo database: " + confDbUrl); Class.forName(confDbDriver); conn = DriverManager.getConnection(confDbUrl, confUser, confPwd); logInfo("Loading Maximo data dictionary"); dd = new MxDD(); dd.init(conn); log("Processing input file: " + inFileName); SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(args[0]); Document doc = (Document) builder.build(xmlFile); Element rootNode = doc.getRootElement(); rootMboName = rootNode.getAttribute("mboname").getValue(); rootResultstableid = rootNode.getAttribute("resultstableid").getValue(); checkChildren(rootNode, 0, rootMboName, rootMboName); //for (Element element:toBeRemoved) //{ // element.getParent().removeContent(element); //} logInfo("Generating output file: " + outFileName); XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new FileWriter(outFileName)); if(!conn.getAutoCommit()) conn.commit(); conn.close(); logInfo(""); log("MxDevTidyApp ended successfully"); log("Analyzed fields: " + fieldCount); log("Unused fields: " + fieldUnusedCount + " (" + (fieldUnusedCount*100/fieldCount) +"%)"); log("Tidied app generated: " + outFileName); } /** * This is the main recursive method * Outline of the logic * * Get all the child XML elements * For each element * If it is a block (section/table/tab/etc.) * If there is a relationship/datasrc attribute * Determine the MBO on which this block is based * If it is a field (textbox/checkbox/etc.) * Query the database for distinct values to detect if the field is not used */ static void checkChildren(Element rootNode, int level, String mboPath, String mboName) throws SQLException { List<Element> childElements = rootNode.getChildren(); for(int i=0; i<childElements.size(); i++) { Element elem = childElements.get(i); String elName= elem.getName(); String elId= elem.getAttributeValue("id"); if ("|tab|page|clientarea|tabgroup|tabledetails|sectionrow|sectioncol|table|section|".contains("|"+elName+"|")) { //logDebug(elName + ": " + elId, level); String childMboPath=mboPath; String childMbo=mboName; if (elem.getAttribute("relationship")!=null) { String relName = elem.getAttributeValue("relationship").toUpperCase(); childMboPath = childMboPath + "." + relName; childMbo = dd.getRelTable(mboName, relName); } else if (elem.getAttribute("datasrc")!=null) { String relName = elem.getAttributeValue("datasrc").toUpperCase(); if(!relName.equalsIgnoreCase(rootResultstableid)) { childMboPath = childMboPath + "." + relName; childMbo = dd.getRelTable(rootMboName, relName); } } logDebug(elName + ": " + elId + " - " + childMboPath + " >>>> " + childMbo, level); checkChildren(elem, level+1, childMboPath, childMbo); if (elem.getChildren().size() == 0) { elem.getParent().removeContent(elem); // we removed the current child element so we have to stay on the current record i--; } } else if ("|tablecol|textbox|multiparttextbox|checkbox|".contains("|"+elName+"|")) { Attribute da = elem.getAttribute("dataattribute"); if (da!=null) { String attrname=da.getValue().toUpperCase(); String tablename=mboName; // sometime textbox control is linked to a specific datasrc if(elem.getAttribute("datasrc")!=null) { if(elem.getAttribute("datasrc").getValue().toUpperCase().equals("MAINRECORD")) tablename=rootMboName; } // if dataattribute contains a '.' we have to navigate relationship if(attrname.contains(".")) { String[] x = attrname.split("\\."); tablename = dd.getRelTable(tablename, x[0]); attrname = x[1]; } logDebug(elName + ": " + elId + " - " + tablename + "." + attrname, level); fieldCount++; // call the isDbFieldUsed to detect if a field is used querying the database if (isDbFieldUsed(tablename, attrname)) { logInfo(elName + ": " + elId + " - " + tablename + "." + attrname + " >>>> UNUSED", level); //toBeRemoved.add(elem); elem.getParent().removeContent(elem); fieldUnusedCount++; // we removed the current child element so we have to stay on the current record i--; } } } // TODO data sources can be defined after they are used // they should be collected in a 1st pass of the XML if ("|datasrc|table|".contains("|"+elName+"|")) { Attribute rel = elem.getAttribute("relationship"); if (rel!=null) { String tb = dd.addRel(rootMboName, elId.toUpperCase(), elem.getAttributeValue("relationship")); logInfo("Adding datasrc to DD " + elName + ": " + elId + " >>>> " + rootMboName + "." + elId.toUpperCase() + " >>> " + tb, level); } } } } static boolean isDbFieldUsed(String table, String attr) throws SQLException { if (!dd.isPersistent(table, attr)) return false; String sqlQuery = "select count(distinct("+attr+")) from " + table; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery); rs.next(); int i = rs.getInt(1); rs.close(); stmt.close(); if (i<=1) return true; else return false; } //////////////////////////////// // Logging functions //////////////////////////////// static void log(String msg) { System.out.println(msg); } static void logInfo(String msg, int indent) { if (confLoglevel.equals("DEBUG")) { for(int x=0; x<indent; x++) System.out.print(" "); System.out.println(msg); } } static void logInfo(String msg) { logInfo(msg, 0); } static void logDebug(String msg, int indent) { if (confLoglevel.equals("DEBUG") || confLoglevel.equals("INFO")) { for(int x=0; x<indent; x++) System.out.print(" "); System.out.println(msg); } } static void logDebug(String msg) { logDebug(msg, 0); } }
/* * Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.datumbox.framework.statistics.parametrics.onesample; import com.datumbox.common.dataobjects.FlatDataList; import com.datumbox.framework.statistics.distributions.ContinuousDistributions; /** * * @author bbriniotis */ public class DurbinWatson { /** * The internalDataCollections that are passed in this function are NOT modified after the analysis. * You can safely pass directly the internalDataCollection without worrying about having them modified. */ public static final boolean DATA_SAFE_CALL_BY_REFERENCE = true; /** * Test for Autocorrelation for k explanatory variables * * @param errorList * @param k * @param is_twoTailed * @param aLevel * @return * @throws IllegalArgumentException */ public static boolean test(FlatDataList errorList, int k, boolean is_twoTailed, double aLevel) throws IllegalArgumentException { int n= errorList.size(); if(n<=0) { throw new IllegalArgumentException(); } double DW=calculateScore(errorList); boolean rejectH0=checkCriticalValue(DW, n, k, is_twoTailed, aLevel); return rejectH0; } /** * Calculates DW score * * @param errorList * @return */ public static double calculateScore(FlatDataList errorList) { double DWdeltasquare=0; double DWetsquare=0; int n = errorList.size(); for(int i=0;i<n;++i) { Double error = errorList.getDouble(i); if(i>=1) { Double errorPrevious = errorList.getDouble(i-1); if(errorPrevious!=null) { DWdeltasquare+=Math.pow(error - errorPrevious,2); } } DWetsquare+=error*error; } double DW=DWdeltasquare/DWetsquare; return DW; } /** * Checks the Critical Value to determine if the Hypothesis should be rejected * * @param score * @param n * @param k * @param is_twoTailed * @param aLevel * @return */ public static boolean checkCriticalValue(double score, int n, int k, boolean is_twoTailed, double aLevel) { if(n<=200 && k<=20) { //Calculate it from tables //http://www3.nd.edu/~wevans1/econ30331/Durbin_Watson_tables.pdf } //Follows normal distribution for large samples //References: http://econometrics.com/guide/dwdist.htm double z=(score-2.0)/Math.sqrt(4.0/n); double probability=ContinuousDistributions.GaussCdf(z); boolean rejectH0=false; double a=aLevel; if(is_twoTailed) { //if to tailed test then split the statistical significance in half a=aLevel/2.0; } if(probability<=a || probability>=(1-a)) { rejectH0=true; } return rejectH0; } }
package com.god.gl.vaccination.main.home.activity; import android.os.Bundle; import android.widget.TextView; import com.god.gl.vaccination.R; import com.god.gl.vaccination.base.BaseActivity; import com.god.gl.vaccination.common.CommonUrl; import com.god.gl.vaccination.main.home.adapter.InfoBaseAdpter; import com.god.gl.vaccination.main.home.bean.BaseInfo; import com.god.gl.vaccination.main.login.LoginInfoCache; import com.god.gl.vaccination.util.GsonUtil; import com.god.gl.vaccination.util.ToastUtils; import com.god.gl.vaccination.util.okgo.OkGoUtil; import com.god.gl.vaccination.util.okgo.callback.OnResponse; import com.god.gl.vaccination.widget.TitleView; import com.god.gl.vaccination.widget.WrapContentListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; /** * @author gl * @date 2018/12/6 * @desc */ public class RegistrationInfoActivity extends BaseActivity { @BindView(R.id.tv_name) TextView mTvName; @BindView(R.id.tv_id) TextView mTvId; @BindView(R.id.tv_phone) TextView mTvPhone; @BindView(R.id.tv_adress) TextView mTvAdress; @BindView(R.id.listView) WrapContentListView mListView; private InfoBaseAdpter mInfoBaseAdpter ; private List<BaseInfo.DataBean.ChildrenListBean> mList = new ArrayList<>(); private BaseInfo mBaseInfo; @Override protected int getActivityViewById() { return R.layout.activity_registrationinfo; } @Override protected void initView(Bundle savedInstanceState) { } @Override protected void handleData() { mTitleView.setRightTitleListener(new TitleView.RightTitleListener() { @Override public void rightTitleClick() { EditInfoActivity.goEditInfoActivity(mContext,mBaseInfo.data); } }); mInfoBaseAdpter = new InfoBaseAdpter(mContext,R.layout.item_info,mList); mListView.setAdapter(mInfoBaseAdpter); getInfo(); } private void getInfo(){ Map<String,String> params = new HashMap<>(); params.put("user_token", LoginInfoCache.getToken(mContext)); OkGoUtil.request(mContext, true, CommonUrl.REGISTER_INFO, getTAG(), params, new OnResponse<String>() { @Override public void responseOk(String temp) { mBaseInfo = GsonUtil.jsonToBean(temp, BaseInfo.class); mTvName.setText("姓名:"+ mBaseInfo.data.username); mTvId.setText("身份证:"+ mBaseInfo.data.id_card); mTvPhone.setText("手机号:"+ mBaseInfo.data.mobile); mTvAdress.setText("姓名:"+ mBaseInfo.data.site_name); mList.clear(); mList.addAll(mBaseInfo.data.children_list); mInfoBaseAdpter.notifyDataSetChanged(); } @Override public void responseFail(String msg) { ToastUtils.showMsg(mContext,msg); } }); } }
package org.dbdoclet.test.sample; @Todo public interface Drinkable { }
package org.aksw.autosparql.tbsl.algorithm.search; import org.dllearner.algorithms.qtl.filters.Filter; public class DbpediaFilter implements Filter { public static final DbpediaFilter INSTANCE = new DbpediaFilter(); private DbpediaFilter() {} @Override public boolean isRelevantResource(String uri) { if(uri.startsWith("http://dbpedia.org/resource/Category:")) return false; return true; } }
package taller3.televisores; public class Control { TV tv; public void setTV (TV nuevoTV) { this.tv = nuevoTV; } public TV getTv () { return this.tv; } public void enlazar (TV EnlaceTV) { this.tv = EnlaceTV; EnlaceTV.control = this; } public void turnOn () { this.tv.turnOn(); } public void turnOff () { this.tv.turnOff(); } public void canalUp () { this.tv.canalUp(); } public void canalDown () { this.tv.canalDown(); } // Aumentar y bajar volumen public void volumenUp () { this.tv.volumenUp(); } public void volumenDown () { this.tv.volumenDown(); } public void setCanal (int ControlCanal) { this.tv.setCanal(ControlCanal); } }
package com.imagsky.exception; public class BaseException extends Exception implements ErrorCodeThrowable { //private throwable = null; // pls use JDK 1.4 parent class (java.lang.Exception) getCause(); //private message = null; // pls use parent class (java.lang.Exception) getMessage(); private String errorCode = null; // ----------- // Constructor // ----------- /** * @param errorCode */ public BaseException(String errorCode) { super(); this.errorCode = errorCode; } /** * @param errorCode * @param message */ public BaseException(String message, String errorCode) { super(message); this.errorCode = errorCode; } /** * @param message * @param errorCode * @param cause */ public BaseException(String message, String errorCode, Throwable cause) { super(message, cause); this.errorCode = errorCode; } /** * @param errorCode * @param cause */ public BaseException(String errorCode, Throwable cause) { super(cause); this.errorCode = errorCode; } // ------------- // Getter/Setter // ------------- /** * @return Returns the errorCode. */ public String getErrorCode() { return this.errorCode; } }
package com.jude.file.service.mail.impl; import com.jude.file.bean.mail.dao.PushLogDO; import com.jude.file.mapper.mail.PushLogMapper; import com.jude.file.service.mail.interf.PushLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author :wupeng * @date :Created in 15:23 2018/8/6 * @description:pushLog */ @Service public class PushLogServiceImpl implements PushLogService { @Autowired private PushLogMapper pushLogMapper; @Override public Boolean insert(PushLogDO pushLog) { return pushLogMapper.insert(pushLog) == 1; } @Override public List<PushLogDO> queryPage(Integer index, Integer size) { index = ((index-1) * size); return pushLogMapper.queryPage(index, size); } }
package com.gxtc.huchuan.utils; import android.graphics.Color; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; import android.text.util.Linkify; import android.view.View; import android.widget.TextView; import com.gxtc.huchuan.handler.QrcodeHandler; import java.util.HashSet; import java.util.Iterator; import io.rong.imkit.emoticon.AndroidEmoji; /** * Created by sjr on 2017/6/13. */ public class TextViewLinkUtils { private static TextViewLinkUtils mTextViewLinkUtils; private OnUrlLinkClickListener mUrlLinkClickListener; private TextViewLinkUtils() { } public static synchronized TextViewLinkUtils getInstance() { if (mTextViewLinkUtils == null) { mTextViewLinkUtils = new TextViewLinkUtils(); } return mTextViewLinkUtils; } public SpannableStringBuilder getUrlClickableSpan(TextView textView, String content){ textView.setAutoLinkMask(Linkify.WEB_URLS); textView.setText(content); CharSequence text = textView.getText(); SpannableStringBuilder style = new SpannableStringBuilder(text); if (text instanceof Spannable) { int end = text.length(); Spannable sp = (Spannable) textView.getText(); URLSpan[] urls = sp.getSpans(0, end, URLSpan.class); style.clearSpans(); for (URLSpan url : urls) { MyURLSpan myURLSpan = new MyURLSpan(url.getURL()); style.setSpan(myURLSpan, sp.getSpanStart(url), sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); style.setSpan(new ForegroundColorSpan(Color.parseColor("#8290AF")), sp.getSpanStart(url), sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } AndroidEmoji.ensure(style); } return style; } /** * 自己处理链接点击 */ public class MyURLSpan extends ClickableSpan { private String mUrl; MyURLSpan(String url) { mUrl = url; } @Override public void onClick(View widget) { if (mUrlLinkClickListener != null) { mUrlLinkClickListener.onLinkClick(widget, mUrl); } QrcodeHandler handler = new QrcodeHandler(widget.getContext()); handler.resolvingCode(mUrl, ""); } } public interface OnUrlLinkClickListener { void onLinkClick(View view, String url); } public void setUrlLinkClickListener(OnUrlLinkClickListener urlLinkClickListener) { mUrlLinkClickListener = urlLinkClickListener; } }
package com.rndapp.t.models; import org.json.JSONObject; /** * Created by ell on 1/18/15. */ public interface LineController { public void showSchedules(); public void showLine(Line line); }
/* * 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 logica; import clases.Jugador; /** * * @author Estudiante */ public class LogicaJugador { public String registrar(Jugador nuevoJugador){ //AQUI VAMOS A INSERTAR UN NUEVO JUGADOR String nuevoJ = "insert into jugador values(null, ' "+nuevoJugador.getNombre()+"')"; return "USUARIO REGISTRADO"; } public String consultar(){ return "ruben"; } }
package com.atguigu.lgl_err; /* customerView为主模块,负责菜单的显示和处理用户操作 本类封装以下信息: CustomerList customers = new CustomerList(10); 创建最大包含10客户对象的CustomerList 对象,供以下各成员方法使用。 该类至少提供以下方法: public void enterMainMenu() private void addNewCustomer() private void modifyCustomer() private void deleteCustomer() private void listAllCustomers() public static void main(String[] args) */ public class CustomerView { //创建CustomerList的对象 CustomerList list = new CustomerList(10); //构造器 创建一个对象添加到数组中 public CustomerView(){ Customer customer = new Customer("小许", '女', 14, "1231231", "123@qq.com"); list.addCustomer(customer); } //进入主菜单 public void enterMainMenu() { boolean flag = true; do { //页面展示 System.out.println("-----------------客户信息管理软件-----------------"); System.out.println(" 1 添 加 客 户"); System.out.println(" 2 修 改 客 户"); System.out.println(" 3 删 除 客 户"); System.out.println(" 4 客 户 列 表"); System.out.println(" 5 退 出"); System.out.print("请选择(1-5):"); //读取用户输入 char menuSelection = CMUtility.readMenuSelection(); //判断用户输入 switch (menuSelection) { case '1': addNewCustomer(); break; case '2': modifyCustomer(); break; case '3': deleteCustomer(); break; case '4': listAllCustomers(); break; case '5': System.out.print("确认是否退出(Y/N):"); //判断是否退出 char selection = CMUtility.readConfirmSelection(); if (selection == 'Y') { flag = false; System.out.println("程序退出"); } break; } } while (flag); } //添加用户 private void addNewCustomer() { /* * ---------------------添加客户--------------------- 姓名:aa 性别:男 年龄:18 电话:1521321321 邮箱:22@qq.com ---------------------添加完成--------------------- */ System.out.println("---------------------添加客户---------------------"); //读取数据 System.out.print("姓名 :" ); String name = CMUtility.readString(30); System.out.print("性别 :" ); char gender = CMUtility.readChar(); System.out.print("年龄 :" ); int age = CMUtility.readInt(); System.out.print("电话 :" ); String phone = CMUtility.readString(11); System.out.print("邮箱 :" ); String email = CMUtility.readString(30); //创建对象() Customer customer = new Customer(name, gender, age, phone, email); //添加数据 boolean addCustomer = list.addCustomer(customer); //判断 if (addCustomer) { System.out.println("---------------------添加成功---------------------"); } else { System.out.println("---------------------添加失败---------------------"); } } //修改用户 private void modifyCustomer(){ /* ---------------------修改客户--------------------- 请选择待修改客户编号(-1退出):1 姓名(小井):小罗 性别(男): 年龄(18): 电话(110): 邮箱(aaa@qq.com): */ System.out.println("---------------------修改客户---------------------"); boolean flag = true; int id = 0; Customer customer = null;//被替换的用户 while(flag){ System.out.print("请选择待修改客户编号(-1退出): "); //判断用户输入 id = CMUtility.readInt(); if (id == -1) { return; } //判断用户是否存在 customer = list.getCustomer(id - 1); System.out.println(customer); if (customer == null) { System.out.println("无法找到指定用户"); } else { flag = false; } } //下面还有代码 /* * 姓名(cc): 性别(男): 年龄(20): 电话(1533333333): 邮箱(cc@qq.com): */ System.out.print("姓名("+ customer.getName() +"):"); String name = CMUtility.readString(30, customer.getName()); System.out.print("性别("+ customer.getGender() +"):"); char gender = CMUtility.readChar(customer.getGender()); System.out.print("年龄("+ customer.getAge() +"):"); int age = CMUtility.readInt(customer.getAge()); System.out.print("电话("+ customer.getPhone() +"):"); String phone = CMUtility.readString(11, customer.getPhone()); System.out.print("邮箱("+ customer.getEmail() +"):"); String email = CMUtility.readString(30, customer.getEmail()); //封装对象 Customer sc1 = new Customer(name, gender, age, phone, email); //替换原来的用户 boolean isflag = list.replaceCustomer(id -1 , sc1); if (isflag) { System.out.println("---------------------替换成功--------------------- "); } else { System.out.println("---------------------替换失败--------------------- "); } } //删除用户 private void deleteCustomer(){ /* * ---------------------删除客户--------------------- 请选择待删除客户编号(-1退出):6 无法找到该用户 请选择待删除客户编号(-1退出):1 确认是否删除(Y/N):Y ---------------------删除完成--------------------- */ System.out.println("---------------------删除客户---------------------"); boolean flag = true; int id = 0; while (flag) { System.out.print("请选择待删除客户编号(-1退出):"); id = CMUtility.readInt(); if (id == -1) { return; } //如果id不为-1则查找该用户是否存在 Customer customer = list.getCustomer(id -1); if (customer == null) { System.out.println("无法找到该用户"); } else { break; } } System.out.println("确认是否删除(Y/N):"); char selection = CMUtility.readConfirmSelection(); if (selection == 'Y') {//确定要删 boolean deleteCustomer = list.deleteCustomer(id-1); if (deleteCustomer) { System.out.println("---------------------删除成功---------------------"); }else System.out.println("---------------------删除失败---------------------"); } } //显示用户列表信息 private void listAllCustomers(){ /* * ---------------------------客户列表--------------------------- 编号 姓名 性别 年龄 电话 邮箱 1 小井 男 20 1333333333 aaa@qq.com 2 aa 男 18 15222222222 qq@qq.com 3 aa 男 18 1521321321 22@qq.com --------------------------客户列表完成------------------------- */ System.out.println("---------------------------客户列表---------------------------"); System.out.println("编号\t姓名\t性别\t年龄\t电话\t邮箱"); //获取所有的用户 Customer[] customers = list.getAllCustomers(); if (customers.length > 0 ) { //遍历信息 for (int i = 0; i < customers.length; i++) { //获取每一个用户 Customer customer = customers[i]; System.out.println(i+1 + "\t" + customer.getName() + "\t" + customer.getGender() + "\t" + customer.getAge() + "\t" + customer.getPhone() + "\t" + customer.getEmail() ); } }else { System.out.println("亲!!!您还没有添加用户哦!!!!!"); } System.out.println("--------------------------客户列表完成-------------------------"); } //程序入口 public static void main(String[] args){ CustomerView customerView = new CustomerView(); customerView.enterMainMenu(); } }
package com.kevin.cloud.commons.dto.cloud.dto; import lombok.Data; import lombok.ToString; import java.io.Serializable; /** * @ProjectName: vue-blog-backend * @Package: com.kevin.cloud.commons.dto.cloud.dto * @ClassName: SmsDto * @Author: kevin * @Description: * @Date: 2020/2/10 12:22 * @Version: 1.0 */ @Data @ToString public class SmsDto implements Serializable { private String BizId; private String Code; private String RequestId; private String Message; private String randomCode; //系统生成的验证码 }
package jungle; import animal.Animal; import animal.Monkey; import animal.Snake; import animal.Tiger; /** * AustraliaJungleBuilder class. * It will construct a jungle (Australia). * @author Miguel Fagundez * @since 01/09/2020 * @version 1.2 */ public class AustraliaJungleBuilder implements JungleBuilder { /* * Jungle Member * */ private Jungle jungle; /* * Constructor * */ public AustraliaJungleBuilder() { this.jungle = new Jungle("Australia"); } @Override public void buildTigers() { } @Override public void buildMonkeys() { Animal monkey = new Monkey(); jungle.addNewMonkey(monkey); } @Override public void buildSnakes() { Animal snake = new Snake(); jungle.addNewSnake(snake); } @Override public Jungle getJungle() { return this.jungle; } }
package nl.kasperschipper.alligatorithm.services; import nl.kasperschipper.alligatorithm.exception.AlligatorithmValidationException; import nl.kasperschipper.alligatorithm.model.PairedByte; import java.util.List; public interface AlligatorithmService { List<PairedByte> convertByteListToPairedByteListAndValidate(List<Byte> inputBytes) throws AlligatorithmValidationException; List<Byte> applyAlgorithmToPairedByteList(List<PairedByte> inputBytes); }
// ********************************************************** // 1. 제 목: 용어사전 관리 // 2. 프로그램명: DicSubjBean.java // 3. 개 요: 용어사전 관리(과목) // 4. 환 경: JDK 1.4 // 5. 버 젼: 1.0 // 6. 작 성: 노희성 2004. 11. 14 // 7. 수 정: // ********************************************************** package com.ziaan.course; import java.sql.SQLException; import java.util.ArrayList; import com.ziaan.library.ConfigSet; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; public class DicSubjBean { private ConfigSet config ; private int row ; public DicSubjBean() { try { config = new ConfigSet(); row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다 } catch( Exception e ) { e.printStackTrace(); } } /** 용어사전 화면 리스트 @param box receive from the form object and session @return ArrayList 용어사전 리스트 */ public ArrayList selectListDicSubj(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; StringBuffer sbSQL = new StringBuffer(""); DataBox dbox = null; int iSysAdd = 0; // System.out.println을 Mehtod에서 사용하는 순서를 표시하는 변수 int v_pageno = box.getInt("p_pageno"); String v_gubun = "1"; String ss_upperclass = box.getString("s_upperclass" ); // 과목대분류 String ss_middleclass = box.getString("s_middleclass" ); // 과목중분류 String ss_lowerclass = box.getString("s_lowerclass" ); // 과목소분류 String ss_subj = box.getString("s_subjcourse" ); // 과목코드 String v_searchtext = box.getString("p_searchtext" ); String v_groups = box.getStringDefault("p_group" , ""); // ㄱ,ㄴ,ㄷ .... int total_page_count= 0; // 전체 페이지 수를 반환한다 int total_row_count = 0; // 전체 row 수를 반환한다 try { connMgr = new DBConnectionManager(); list = new ArrayList(); sbSQL.append(" SELECT a.seq \n") .append(" , a.subj \n") .append(" , b.subjnm \n") .append(" , a.words \n") .append(" , a.descs \n") .append(" , a.groups \n") .append(" , a.luserid \n") .append(" , a.ldate \n") .append(" FROM TZ_DIC a \n") .append(" , TZ_SUBJ b \n") .append(" , TZ_DICGROUP c \n") .append(" WHERE a.subj = b.subj \n") .append(" AND a.groups = c.groups \n") .append(" AND a.gubun = " + StringManager.makeSQL(v_gubun) + " \n"); if ( !ss_subj.equals("") ) // 과목이 있으면 sbSQL.append(" AND a.subj = " + StringManager.makeSQL(ss_subj) + " \n"); if ( !v_searchtext.equals("") ) // 검색어가 있으면 sbSQL.append(" AND a.words like " + StringManager.makeSQL("%" + v_searchtext + "%") + " \n"); if ( !v_groups.equals("") ) // 용어분류로 검색할때 sbSQL.append(" AND a.groups = " + StringManager.makeSQL(v_groups) + " \n"); sbSQL.append(" ORDER BY a.subj asc, a.groups asc, a.words asc \n"); System.out.println(this.getClass().getName() + "." + "selectListDicSubj() Printing Order " + ++iSysAdd + ". ======[SELECT SQL] : " + " [\n" + sbSQL.toString() + "\n]"); ls = connMgr.executeQuery(sbSQL.toString()); ls.setPageSize (row ); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage (v_pageno ); // 현재페이지번호를 세팅한다. total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다 total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다 box.put("total_row_count", String.valueOf(total_row_count)); // 총 갯수를 BOX에 세팅 while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_dispnum" , new Integer(total_row_count - ls.getRowNum() + 1)); dbox.put("d_totalpage" , new Integer(total_page_count)); dbox.put("d_rowcount" , new Integer(row)); list.add(dbox); } } catch ( SQLException e ) { ErrorManager.getErrorStackTrace(e, box, sbSQL.toString()); throw new Exception("\n SQL : [\n" + sbSQL.toString() + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } catch ( Exception e ) { ErrorManager.getErrorStackTrace(e, box, ""); throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e ) { } } } return list; } /** 용어사전 화면 리스트(컨텐츠 과목 용어사전) @param box receive from the form object and session @return ArrayList 용어사전 리스트 */ public ArrayList selectListDicSubjStudy(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; StringBuffer sbSQL = new StringBuffer(""); DataBox dbox = null; int iSysAdd = 0; // System.out.println을 Mehtod에서 사용하는 순서를 표시하는 변수 int v_pageno = box.getInt ("p_pageno" ); String v_gubun = "1"; String p_subj = box.getString ("p_subj" ); // 과목코드 String v_searchtext = box.getString ("p_searchtext" ); String v_groups = box.getStringDefault ("p_group", "ALL"); // ㄱ,ㄴ,ㄷ .... int total_page_count = 0; //ls.getTotalPage(); // 전체 페이지 수를 반환한다 int total_row_count = 0; //ls.getTotalCount(); // 전체 row 수를 반환한다 try { connMgr = new DBConnectionManager(); list = new ArrayList(); sbSQL.append(" SELECT a.seq \n") .append(" , a.subj \n") .append(" , b.subjnm \n") .append(" , a.words \n") .append(" , a.descs \n") .append(" , a.groups \n") .append(" , a.luserid \n") .append(" , a.ldate \n") .append(" FROM TZ_DIC a \n") .append(" , TZ_SUBJ b \n") .append(" , TZ_DICGROUP c \n") .append(" WHERE a.subj = b.subj \n") .append(" AND a.groups = c.groups \n"); System.out.println("v_gubun : " + v_gubun ); if ( !v_gubun.equals("") ) { sbSQL.append(" AND a.gubun = " + StringManager.makeSQL(v_gubun ) + " \n"); } sbSQL.append(" AND a.subj = " + StringManager.makeSQL(p_subj ) + " \n"); if ( !v_searchtext.equals("") ) // 검색어가 있으면 sbSQL.append(" AND a.words like " + StringManager.makeSQL("%" + v_searchtext + "%") + " \n"); if ( !v_groups.equals("ALL") ) // 용어분류로 검색할때 sbSQL.append(" AND a.groups = " + StringManager.makeSQL(v_groups) + " \n"); sbSQL.append(" ORDER BY a.subj asc, a.groups asc, a.words asc \n"); System.out.println(this.getClass().getName() + "." + "selectListDicSubjStudy() Printing Order " + ++iSysAdd + ". ======[SELECT SQL] : " + " [\n" + sbSQL.toString() + "\n]"); ls = connMgr.executeQuery(sbSQL.toString()); ls.setPageSize (row ); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage (v_pageno ); // 현재페이지번호를 세팅한다. total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다 total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다 box.put("total_row_count", String.valueOf(total_row_count)); // 총 갯수를 BOX에 세팅 while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_dispnum" , new Integer(total_row_count - ls.getRowNum() + 1)); dbox.put("d_totalpage" , new Integer(total_page_count)); dbox.put("d_rowcount" , new Integer(row)); list.add(dbox); } } catch ( SQLException e ) { ErrorManager.getErrorStackTrace(e, box, sbSQL.toString()); throw new Exception("\n SQL : [\n" + sbSQL.toString() + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } catch ( Exception e ) { ErrorManager.getErrorStackTrace(e, box, ""); throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e ) { } } } return list; } /** 용어사전 화면 리스트(전체 용어사전) @param box receive from the form object and session @return ArrayList 용어사전 리스트 */ public ArrayList selectListDicTotal(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; StringBuffer sbSQL = new StringBuffer(""); DataBox dbox = null; int iSysAdd = 0; // System.out.println을 Mehtod에서 사용하는 순서를 표시하는 변수 int v_pageno = box.getInt ("p_pageno" ); String v_gubun = "1"; String p_subj = box.getString ("p_subj" ); // 과목코드 (사용하지 않음) String v_searchtext = box.getString ("p_searchtext" ); String v_groups = box.getStringDefault ("p_group", "" ); // ㄱ,ㄴ,ㄷ .... int total_page_count = 0; // 전체 페이지 수를 반환한다 int total_row_count = 0; // 전체 row 수를 반환한다 try { connMgr = new DBConnectionManager(); list = new ArrayList(); sbSQL.append(" SELECT a.seq \n") .append(" , a.subj \n") .append(" , a.words \n") .append(" , a.descs \n") .append(" , a.groups \n") .append(" , a.luserid \n") .append(" , a.ldate \n") .append(" FROM TZ_DIC a \n") .append(" , TZ_DICGROUP c \n") .append(" WHERE a.groups = c.groups \n") .append(" AND a.gubun = " + StringManager.makeSQL(v_gubun) + " \n"); if ( !v_searchtext.equals("") ) // 검색어가 있으면 sbSQL.append(" AND a.words like " + StringManager.makeSQL("%" + v_searchtext + "%") + " \n"); if ( !v_groups.equals("") ) // 용어분류로 검색할때 sbSQL.append(" AND a.groups = " + StringManager.makeSQL(v_groups) + " \n"); sbSQL.append(" ORDER BY a.groups asc, a.words asc \n"); //System.out.println(this.getClass().getName() + "." + "selectListDicTotal() Printing Order " + ++iSysAdd + ". ======[SELECT SQL] : " + " [\n" + sbSQL.toString() + "\n]"); ls = connMgr.executeQuery(sbSQL.toString()); ls.setPageSize (row ); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage (v_pageno ); // 현재페이지번호를 세팅한다. total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다 total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다 box.put("total_row_count", String.valueOf(total_row_count)); // 총 갯수를 BOX에 세팅 while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_dispnum" , new Integer(total_row_count - ls.getRowNum() + 1)); dbox.put("d_totalpage" , new Integer(total_page_count)); dbox.put("d_rowcount" , new Integer(row)); list.add(dbox); } } catch ( SQLException e ) { ErrorManager.getErrorStackTrace(e, box, sbSQL.toString()); throw new Exception("\n SQL : [\n" + sbSQL.toString() + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } catch ( Exception e ) { ErrorManager.getErrorStackTrace(e, box, ""); throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e ) { } } } return list; } /** 용어사전 팝업상세(전체 용어사전) @param box receive from the form object and session @return ArrayList 용어사전 리스트 */ public DataBox selectWordContent(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; StringBuffer sbSQL = new StringBuffer(""); DataBox dbox = null; int iSysAdd = 0; // System.out.println을 Mehtod에서 사용하는 순서를 표시하는 변수 String p_subj = box.getString("p_subj" ); String p_gubun = box.getString("p_gubun" ); String p_seq = box.getString("p_seq" ); try { connMgr = new DBConnectionManager(); sbSQL.append(" SELECT words \n") .append(" , descs \n") .append(" FROM tz_dic \n") .append(" WHERE subj = " + SQLString.Format(p_subj ) + " \n") .append(" AND gubun = " + SQLString.Format(p_gubun ) + " \n") .append(" AND seq = " + SQLString.Format(p_seq ) + " \n"); System.out.println(this.getClass().getName() + "." + "selectWordContent() Printing Order " + ++iSysAdd + ". ======[SELECT SQL] : " + " [\n" + sbSQL.toString() + "\n]"); ls = connMgr.executeQuery(sbSQL.toString()); if ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( SQLException e ) { ErrorManager.getErrorStackTrace(e, box, sbSQL.toString()); throw new Exception("\n SQL : [\n" + sbSQL.toString() + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } catch ( Exception e ) { ErrorManager.getErrorStackTrace(e, box, ""); throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]"); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e ) { } } } return dbox; } }
package com.practise.signup.model; import lombok.Data; import javax.persistence.*; import java.util.List; @Entity @Table(name = "signup") @Data public class Signup { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "firstname") private String firstname; @Column(name = "lastname") private String lastname; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "address") private String address; @OneToMany(cascade = CascadeType.ALL, mappedBy = "userID") private List<Inventory> inventories; }
package ru.job4j.chess; /** * Класс OccupiedPositionException реализует исключение "Позиция занята". * * @author Goureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-12-13 * @since 2017-05-04 */ public class OccupiedPositionException extends RuntimeException { /** * Конструктор. * @param position позиция на доске. */ public OccupiedPositionException(String position) { super("Occupied position: " + position); } }
package com.coop.model; public class Asset { private String accno; private String asset; private double aval; private String yield; private double yval; private double ayield; private int asset_id; public int getAsset_id() { return asset_id; } public void setAsset_id(int asset_id) { this.asset_id = asset_id; } public String getAccno() { return accno; } public void setAccno(String accno) { this.accno = accno; } public String getAsset() { return asset; } public void setAsset(String asset) { this.asset = asset; } public double getAval() { return aval; } public void setAval(double aval) { this.aval = aval; } public String getYield() { return yield; } public void setYield(String yield) { this.yield = yield; } public double getYval() { return yval; } public void setYval(double yval) { this.yval = yval; } public double getAyield() { return ayield; } public void setAyield(double ayield) { this.ayield = ayield; } }
package cenarios.segundo; public interface Funcionario { public Double getValorBonus(); }
package hu.lamsoft.hms.common.persistence.food.dao; import org.springframework.stereotype.Repository; import hu.lamsoft.hms.common.persistence.dao.BaseSearchDao; import hu.lamsoft.hms.common.persistence.food.entity.Food; @Repository public interface FoodDao extends BaseSearchDao<Food> { }
package com.example.demo.repo; import com.example.demo.model.AppImage; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Repository public interface ImageRepository extends JpaRepository<AppImage, Long> { List<AppImage> findByAppUser_Id(Long appUserId); List<AppImage> findByAppUser_Username(String username); List<AppImage> findAll(); AppImage findAppImageById(Long id); @Transactional void removeAppImageById(Long id); }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.bvt.sql.hive; import com.alibaba.druid.sql.OracleTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.visitor.SchemaStatVisitor; import com.alibaba.druid.util.JdbcConstants; import org.junit.Assert; import java.util.List; public class HiveCreateTableTest_28_struct extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE EXTERNAL TABLE `json_table_1`(\n" + " `docid` string COMMENT 'from deserializer', \n" + " `user_1` struct<id:int,username:string,name:string,shippingaddress:struct<address1:string,address2:string,city:string,state:string>,orders:array<struct<itemid:int,orderdate:string>>> COMMENT 'from deserializer')\n" + "ROW FORMAT SERDE \n" + " 'org.apache.hive.hcatalog.data.JsonSerDe' \n" + "STORED AS INPUTFORMAT \n" + " 'org.apache.hadoop.mapred.TextInputFormat' \n" + "OUTPUTFORMAT \n" + " 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'\n" + "LOCATION\n" + " 'oss://acs:ram::1013022312866336:role&aliyunopenanalyticsaccessingossrole@oss-cn-beijing-for-openanalytics-test/datasets/test/json/hcatalog_serde/table_1'\n" + "TBLPROPERTIES (\n" + " 'COLUMN_STATS_ACCURATE'='false', \n" + " 'numFiles'='1', \n" + " 'numRows'='-1', \n" + " 'rawDataSize'='-1', \n" + " 'totalSize'='347', \n" + " 'transient_lastDdlTime'='1530879306')"; // List<SQLStatement> statementList = SQLUtils.toStatementList(sql, JdbcConstants.HIVE); SQLStatement stmt = statementList.get(0); System.out.println(stmt.toString()); Assert.assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.HIVE); stmt.accept(visitor); { String text = SQLUtils.toSQLString(stmt, JdbcConstants.HIVE); assertEquals("CREATE EXTERNAL TABLE `json_table_1` (\n" + "\t`docid` string COMMENT 'from deserializer',\n" + "\t`user_1` STRUCT<id:int, username:string, name:string, shippingaddress:STRUCT<address1:string, address2:string, city:string, state:string>, orders:ARRAY<STRUCT<itemid:int, orderdate:string>>> COMMENT 'from deserializer'\n" + ")\n" + "ROW FORMAT\n" + "\tSERDE 'org.apache.hive.hcatalog.data.JsonSerDe'\n" + "STORED AS\n" + "\tINPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat'\n" + "\tOUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'\n" + "LOCATION 'oss://acs:ram::1013022312866336:role&aliyunopenanalyticsaccessingossrole@oss-cn-beijing-for-openanalytics-test/datasets/test/json/hcatalog_serde/table_1'\n" + "TBLPROPERTIES (\n" + "\t'COLUMN_STATS_ACCURATE' = 'false',\n" + "\t'numFiles' = '1',\n" + "\t'numRows' = '-1',\n" + "\t'rawDataSize' = '-1',\n" + "\t'totalSize' = '347',\n" + "\t'transient_lastDdlTime' = '1530879306'\n" + ")", text); } System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(2, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); assertEquals(0, visitor.getOrderByColumns().size()); assertTrue(visitor.containsTable("json_table_1")); } }
package com.netcracker.controllers; import com.netcracker.DTO.ComplainDto; import com.netcracker.DTO.mappers.ComplainMapper; import com.netcracker.entities.Complain; import com.netcracker.services.ComplainService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/Complains") public class ComplainController { private static final Logger LOG = LoggerFactory.getLogger(ComplainController.class); @Autowired private ComplainService complainService; @Autowired private ComplainMapper complainMapper; @DeleteMapping("/deleteComplain") public void deleteComplain(@RequestParam(value = "id") Long complainId) { LOG.info("[ deleteComplain(complainId : {})", complainId); complainService.deleteComplain(complainId); LOG.info("]"); } @PostMapping("/sendComplain/{adresatId}") public ComplainDto sendComlain(@PathVariable(value = "adresatId") Long adresatId, @RequestParam(value="text") String text){ LOG.info("[sendComplain(adresatId : {})", adresatId); Complain complain = complainService.sendComplain(adresatId, text); ComplainDto complainDto = complainMapper.toDto(complain); LOG.info("]"); return complainDto; } @GetMapping("/getComplains/{userId}") public List<ComplainDto> findComplainsByUser(@PathVariable(value = "userId") Long userId){ LOG.info("[findComplainsByUser(userId:{}", userId); List<Complain> complains = complainService.findComplainsByUser(userId); List<ComplainDto>newlist= new ArrayList<ComplainDto>(); for (Complain complain: complains) { newlist.add(complainMapper.toDto(complain)); } return newlist; } @GetMapping("/getComplain/{complainId}") public ComplainDto getComplainById(@RequestParam(value = "complainId")Long complainId){ LOG.info("[findComplainById(complainId:{}", complainId); Complain complain = complainService.getComplainById(complainId); ComplainDto complainDto = complainMapper.toDto(complain); return complainDto; } }
/* BinaryRuleTemplate -- a class within the Cellular Automaton Explorer. Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package cellularAutomata.rules.templates; import cellularAutomata.cellState.view.CellStateView; import cellularAutomata.cellState.view.BinaryCellStateView; import cellularAutomata.error.exceptions.BinaryStateOutOfBoundsException; import cellularAutomata.util.MinMaxIntPair; /** * A template/convenience class for all rules that behave as boolean function of * their neighbors. This class handles conversion of the neighbors as Cells to * neighbors as integer values (0 or 1) so that the subclass only has to worry * about specifying the boolean function. This conversion makes sure that the * cells all return their state values for the same generation as the current * cell. <br> * This class is similar to IntegerRuleTemplate which can have N states * including N = 2. However, this class checks to be sure that only binary * states are allowed, sends warnings if the values are not 0 or 1, and defaults * to cell states and graphics most appropriate to binary numbers. * <p> * This class uses the Template Method design pattern. Subclasses implement the * abstract binaryRule() method which is called by the template method * integerRule(). * * @author David Bahr */ public abstract class BinaryRuleTemplate extends IntegerRuleTemplate { /** * Create a rule using the given cellular automaton properties. * <p> * When building child classes, the minimalOrLazyInitialization parameter * must be included but may be ignored. However, the boolean is intended to * indicate when the child's constructor should build a rule with as small a * footprint as possible. In order to load rules by reflection, the * application must query the child classes for information like their * display names, tooltip descriptions, etc. At these times it makes no * sense to build the complete rule which may have a large footprint in * memory. * <p> * It is recommended that the child's constructor and instance variables do * not initialize any variables and that variables be initialized only when * first needed (lazy initialization). Or all initializations in the * constructor may be placed in an <code>if</code> statement. * * <pre> * if(!minimalOrLazyInitialization) * { * ...initialize * } * </pre> * * @param minimalOrLazyInitialization * When true, the constructor instantiates an object with as * small a footprint as possible. When false, the rule is fully * constructed. If uncertain, set this variable to false. */ public BinaryRuleTemplate(boolean minimalOrLazyInitialization) { super(minimalOrLazyInitialization); } /** * Calculates a new state for the cell by finding its current generation and * then requesting the state values for its neighbors for the same * generation. The abstract boolean function is then called to calculate a * new state. By convention the neighbors should be indexed clockwise * starting to the northwest of the cell. * * @param cell * The cell being updated. * @param neighbors * The cells on which the update is based (usually neighboring * cells). By convention the neighbors should be indexed * clockwise starting to the northwest of the cell. May be null * if want this method to find the "neighboring" cells. * @param numStates * The number of states. In other words, the returned state can * only have values between 0 and numStates - 1. * @param generation * The current generation of the CA. * @return A new state for the cell. */ protected int integerRule(int cellValue, int[] neighbors, int numStates, int generation) { // call the binary rule int answer = binaryRule(cellValue, neighbors, generation); if((answer != 0) && (answer != 1)) { throw new BinaryStateOutOfBoundsException("", answer); } return answer; } /** * The rule for the cellular automaton which will be a boolean function of * the neighbors. * * @param cellValue * The current value of the cell being updated. * @param neighbors * The neighbors as their integer values (0 or 1). * @param generation * The current generation of the CA. * @return A new state for the cell. */ protected abstract int binaryRule(int cellValue, int[] neighbors, int generation); /** * Returns null to disable the "Number of States" text field. */ protected MinMaxIntPair getMinMaxAllowedStates(String latticeDescription) { return null; } /** * The value that will be displayed for the state. Should always be a 2. */ protected Integer stateValueToDisplay(String latticeDescription) { return new Integer(2); } /** * Gets an instance of the CellStateView class that will be used to display * cells being updated by this rule. Note: This method must return a view * that is able to display cell states of the type returned by the method * getCompatibleCellState(). Appropriate CellStatesViews to return include * BinaryCellStateView, IntegerCellStateView, HexagonalIntegerCellStateView, * IntegerVectorArrowView, IntegerVectorDefaultView, and * RealValuedDefaultView among others. the user may also create their own * views (see online documentation). * <p> * Any values passed to the constructor of the CellStateView should match * those values needed by this rule. * * @return An instance of the CellStateView (any values passed to the * constructor of the CellStateView should match those values needed * by this rule). */ public CellStateView getCompatibleCellStateView() { return new BinaryCellStateView(); } }
package util.concurrent; import java.util.concurrent.Callable; public class ExceptionNotifyingCallableDecorator<V> implements Callable<V> { private final Callable<V> delegate; private final UnhandledExceptionConsumer callback; public ExceptionNotifyingCallableDecorator(Callable<V> delegate, UnhandledExceptionConsumer callback) { super(); this.delegate = delegate; this.callback = callback; } @Override public V call() throws Exception { try { return delegate.call(); } catch (final Throwable t) { this.callback.acceptException(Thread.currentThread(), t); throw t; } } }
/* * generated by Xtext */ package xtext; import org.eclipse.xtext.junit4.IInjectorProvider; import com.google.inject.Injector; public class AventuraGraficaUiInjectorProvider implements IInjectorProvider { @Override public Injector getInjector() { return xtext.ui.internal.AventuraGraficaActivator.getInstance().getInjector("xtext.AventuraGrafica"); } }
package com.dabis.trimsalon.beans; import java.util.Calendar; import java.util.Date; public class Klant { private long id; private String naam; private String adres; private String huisnummer; private String postcode; private String woonplaats; private String telefoon; private String mobiel; private String email; private boolean ophalen; private String opmerkingen; private Calendar inschrijfdatum; /** * @return the id */ public long getId() { return id; } /** * @param id the id to set */ public void setId(long id) { this.id = id; } /** * @return the naam */ public String getNaam() { return naam; } /** * @param naam the naam to set */ public void setNaam(String naam) { this.naam = naam; } /** * @return the adres */ public String getAdres() { return adres; } /** * @param adres the adres to set */ public void setAdres(String adres) { this.adres = adres; } /** * @return the huisnummer */ public String getHuisnummer() { return huisnummer; } /** * @param huisnummer the huisnummer to set */ public void setHuisnummer(String huisnummer) { this.huisnummer = huisnummer; } /** * @return the postcode */ public String getPostcode() { return postcode; } /** * @param postcode the postcode to set */ public void setPostcode(String postcode) { this.postcode = postcode; } /** * @return the woonplaats */ public String getWoonplaats() { return woonplaats; } /** * @param woonplaats the woonplaats to set */ public void setWoonplaats(String woonplaats) { this.woonplaats = woonplaats; } /** * @return the telefoon */ public String getTelefoon() { return telefoon; } /** * @param telefoon the telefoon to set */ public void setTelefoon(String telefoon) { this.telefoon = telefoon; } /** * @return the mobiel */ public String getMobiel() { return mobiel; } /** * @param mobiel the mobiel to set */ public void setMobiel(String mobiel) { this.mobiel = mobiel; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the ophalen */ public boolean isOphalen() { return ophalen; } /** * @param ophalen the ophalen to set */ public void setOphalen(boolean ophalen) { this.ophalen = ophalen; } /** * @return the opmerkingen */ public String getOpmerkingen() { return opmerkingen; } /** * @param opmerkingen the opmerkingen to set */ public void setOpmerkingen(String opmerkingen) { this.opmerkingen = opmerkingen; } /** * @return the inschrijfdatum */ public Calendar getInschrijfdatum() { return inschrijfdatum; } /** * @param inschrijfdatum the inschrijfdatum to set */ public void setInschrijfdatum(Calendar inschrijfdatum) { this.inschrijfdatum = inschrijfdatum; } }
package sr.hakrinbank.intranet.api.service.bean; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostFilter; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import sr.hakrinbank.intranet.api.model.ListedPersonPep; import sr.hakrinbank.intranet.api.repository.ListedPersonPepRepository; import sr.hakrinbank.intranet.api.service.ListedPersonPepService; import sr.hakrinbank.intranet.api.util.Constant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class ListedPersonPepServiceBean implements ListedPersonPepService { @Autowired private ListedPersonPepRepository listedPersonPepRepository; @Override @PostFilter("filterObject.deleted() == false") public List<ListedPersonPep> findAllListedPersonPep() { return listedPersonPepRepository.findAll(); } @Override public ListedPersonPep findById(long id) { return listedPersonPepRepository.findOne(id); } @Override public void updateListedPersonPep(ListedPersonPep ListedPersonPep) { if(ListedPersonPep.getDate() == null){ ListedPersonPep.setDate(new Date()); listedPersonPepRepository.save(ListedPersonPep); }else{ listedPersonPepRepository.save(ListedPersonPep); } } @Override public List<ListedPersonPep> findAllActiveListedPersonPepOrderedByDate() { return listedPersonPepRepository.findActiveListedPersonPepOrderedByDate(); } @Override public List<ListedPersonPep> findAllActiveListedPersonPepByDate(String byDate) { if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.NULL_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){ LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT)); LocalDateTime todayStartOfDay = localDate.atStartOfDay(); Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant()); LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX); Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant()); return listedPersonPepRepository.findAllActiveListedPersonPepByDate(startOfDay, endOfDay); } return findAllActiveListedPersonPepOrderedByDate(); } @Override public List<ListedPersonPep> findAllActiveListedPersonPepBySearchQueryOrDate(String byTitle, String byDate) { if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){ LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT)); LocalDateTime todayStartOfDay = localDate.atStartOfDay(); Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant()); LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX); Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant()); if(byTitle != null && byTitle != "" && !byTitle.contentEquals(Constant.UNDEFINED_VALUE)){ return listedPersonPepRepository.findAllActiveListedPersonPepBySearchQueryAndDate(byTitle, startOfDay, endOfDay); }else{ return listedPersonPepRepository.findAllActiveListedPersonPepByDate(startOfDay, endOfDay); } }else { return listedPersonPepRepository.findAllActiveListedPersonPepBySearchQuery(byTitle); } } @Override public int countListedPersonPepOfTheWeek() { List<ListedPersonPep> ListedPersonPepList = listedPersonPepRepository.findActiveListedPersonPep(); DateTime currentDate = new DateTime(); int weekOfCurrentDate = currentDate.getWeekOfWeekyear(); int yearOfCurrentDate = currentDate.getYear(); List<ListedPersonPep> countList = new ArrayList<>(); DateTime specificDate; int weekOfSpecificDate; int yearOfSpecificDate; for(ListedPersonPep ListedPersonPep: ListedPersonPepList){ specificDate = new DateTime(ListedPersonPep.getDate()); weekOfSpecificDate = specificDate.getWeekOfWeekyear(); yearOfSpecificDate = specificDate.getYear(); if( (yearOfCurrentDate == yearOfSpecificDate) && (weekOfCurrentDate == weekOfSpecificDate) ){ countList.add(ListedPersonPep); } } return countList.size(); } @Override public List<ListedPersonPep> findAllActiveListedPersonPep() { return listedPersonPepRepository.findActiveListedPersonPep(); } @Override public ListedPersonPep findByName(String name) { return listedPersonPepRepository.findByName(name); } @Override public List<ListedPersonPep> findAllActiveListedPersonPepBySearchQuery(String qry) { return listedPersonPepRepository.findAllActiveListedPersonPepBySearchQuery(qry); } }
package com.example.recyclerview; import java.lang.reflect.Type; public class UserMessage { public static final int TYPE_SEND=1; public static final int TYPE_RECEIVE=0; private String content; private int type; public UserMessage(String content,int type){ this.content=content; this.type=type; } public int getType(){ return type; } public void setType(int type){ this.type=type; } public String getContent(){ return content; } public void setContent(String content) { this.content = content; } }
package gov.usgs.earthquake.nshmp.site.www; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.ELKO_NV; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.LOS_ANGELES_CA; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.NORTHRIDGE_CA; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.OAKLAND_CA; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.PROVO_UT; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.SALT_LAKE_CITY_UT; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.SAN_FRANCISCO_CA; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.SAN_JOSE_CA; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.SEATTLE_WA; import static gov.usgs.earthquake.nshmp.internal.NshmpSite.TACOMA_WA; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.junit.Test; import com.google.common.collect.ImmutableList; import gov.usgs.earthquake.nshmp.geo.Location; import gov.usgs.earthquake.nshmp.internal.NshmpSite; import gov.usgs.earthquake.nshmp.site.www.BasinTermService.Response; /** * Check basin term service. * * <p> To run tests: Must have a config.properties file in root of source folder * with a "service_host" field that defines where the basin service is deployed. * Example: service_host = http://localhost:8080 * * @author Brandon Clayton */ @SuppressWarnings("javadoc") public class BasinServiceTest { private static final Path DATA_PATH = Paths.get("test/gov/usgs/earthquake/nshmp/site/data"); private static final String RESULT_SUFFIX = "-result.json"; private static final List<NshmpSite> LOCATIONS = ImmutableList.of( /* LA Basin */ LOS_ANGELES_CA, NORTHRIDGE_CA, /* Bay Area */ SAN_FRANCISCO_CA, SAN_JOSE_CA, OAKLAND_CA, /* Wasatch Front */ SALT_LAKE_CITY_UT, PROVO_UT, /* Puget Lowland */ SEATTLE_WA, TACOMA_WA, /* Outside basin */ ELKO_NV); @Test public void testService() throws Exception { for (NshmpSite site : LOCATIONS) { compareResults(site); } } private static void compareResults(NshmpSite site) throws Exception { Response expected = readExpected(site); Response actual = generateActual(site); assertEquals( BasinUtil.GSON.toJson(expected.request), BasinUtil.GSON.toJson(actual.request)); assertEquals( BasinUtil.GSON.toJson(expected.response), BasinUtil.GSON.toJson(actual.response)); } private static Response generateActual(NshmpSite site) throws Exception { Location loc = site.location(); String serviceQuery = BasinUtil.SERVICE_URL + "?latitude=" + loc.lat() + "&longitude=" + loc.lon(); URL url = new URL(serviceQuery); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); Response svcResponse = BasinUtil.GSON.fromJson(reader, Response.class); reader.close(); return svcResponse; } private static Response readExpected(NshmpSite site) throws Exception { Path resultPath = DATA_PATH.resolve(site.id() + RESULT_SUFFIX); String result = new String(Files.readAllBytes(resultPath)); return BasinUtil.GSON.fromJson(result, Response.class); } private static void writeExpected(NshmpSite site) throws Exception { Response svcResponse = generateActual(site); String result = BasinUtil.GSON.toJson(svcResponse, Response.class) + "\n"; Path resultPath = DATA_PATH.resolve(site.id() + RESULT_SUFFIX); Files.write(resultPath, result.getBytes()); } public static void main(String[] args) throws Exception { for (NshmpSite site : LOCATIONS) { writeExpected(site); } } }
package dw2.projetweb.servlets; import dw2.projetweb.forms.FormFichier; 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 java.io.IOException; @WebServlet("/DonnerDroit") public class DonnerDroit extends HttpServlet { public static final String VUE = "/WEB-INF/Site/espaceUtilisateur.jsp"; public static final String SERVLET = "/EspaceUtilisateur"; private static final FormFichier f = new FormFichier(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.getServletContext().getRequestDispatcher(SERVLET).forward(req, res); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String lUserDoc = req.getParameter("listeUtilisateur"); String[] lUserDocs = lUserDoc.split(","); String nomAmi = lUserDocs[0]; int documentId = Integer.parseInt(lUserDocs[1]); try { f.donnerDroit(nomAmi, documentId); } catch (Exception e) { e.printStackTrace(); } this.getServletContext().getRequestDispatcher(SERVLET).forward(req, res); } }
package mb.tianxundai.com.toptoken.mall.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.youth.banner.Banner; import com.youth.banner.BannerConfig; import com.youth.banner.listener.OnBannerListener; import com.youth.banner.loader.ImageLoader; import com.zcolin.gui.pullrecyclerview.BaseRecyclerAdapter; import com.zcolin.gui.pullrecyclerview.PullRecyclerView; import com.zcolin.gui.pullrecyclerview.progressindicator.ProgressStyle; import java.util.ArrayList; import java.util.List; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.adapter.ImageAdapter; import mb.tianxundai.com.toptoken.bean.BannerBean; import mb.tianxundai.com.toptoken.bean.HomeFragmentGoodsBean; import mb.tianxundai.com.toptoken.bean.MallGoodsDetailsBean; import mb.tianxundai.com.toptoken.bean.MallMainUpdataBean; import mb.tianxundai.com.toptoken.mall.base.BaseFragment; import mb.tianxundai.com.toptoken.mall.homegoods.MallHomeInteractor; import mb.tianxundai.com.toptoken.mall.homegoods.MallHomePresenter; import mb.tianxundai.com.toptoken.mall.homegoods.MallHomeView; import mb.tianxundai.com.toptoken.mall.ui.GoodsDetialsActivity; import mb.tianxundai.com.toptoken.uitl.CommonUtil; import mb.tianxundai.com.toptoken.view.HeaderGridView; public class HomeFragment extends BaseFragment implements PullRecyclerView.PullLoadMoreListener, MallHomeView { private View view; private RelativeLayout title_back; private TextView include_title; private View header; private Banner banner; private HeaderGridView gridView; private PullRecyclerView pull_recycle; private ImageAdapter adapter; private int pageNo = 1; private MallHomePresenter presenter; List<HomeFragmentGoodsBean.DataBean.ListBean> dataList; //轮播图数据 List<BannerBean.Pic> bannerList = new ArrayList<>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_home, null); title_back = view.findViewById(R.id.title_back); include_title = view.findViewById(R.id.include_title); pull_recycle = view.findViewById(R.id.pull_recycle); header = LayoutInflater.from(getContext()).inflate(R.layout.layout_home_header, null); banner = header.findViewById(R.id.home_banner); // gridView.addHeaderView(header); pull_recycle.addHeaderView(header); title_back.setVisibility(View.VISIBLE); include_title.setText(getString(R.string.tv_mall_home)); title_back.setOnClickListener(this); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); presenter = new MallHomePresenter(this, new MallHomeInteractor(getContext())); presenter.initBanner(); initRecycle(); presenter.getHomeList(1, pageNo, 10,pull_recycle); banner.setOnBannerListener(new OnBannerListener() { @Override public void OnBannerClick(int position) { // CommonUtil.toastShort("点击==" + position); Intent intent = new Intent(getActivity(), GoodsDetialsActivity.class); intent.putExtra("goods_id", Integer.parseInt(bannerList.get(position).getContentClick())); startActivity(intent); } }); } private void initRecycle() { GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2); pull_recycle.setLayoutManager(layoutManager); pull_recycle.setLinearLayout(false); adapter = new ImageAdapter(getContext()); pull_recycle.setRefreshProgressStyle(ProgressStyle.LineScaleIndicator); pull_recycle.setIsLoadMoreEnabled(true); pull_recycle.setOnPullLoadMoreListener(this); adapter.setPullRecyclerView(pull_recycle); pull_recycle.setAdapter(adapter); pull_recycle.refreshWithPull(); adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<HomeFragmentGoodsBean.DataBean.ListBean>() { @Override public void onItemClick(View covertView, int position, HomeFragmentGoodsBean.DataBean.ListBean data) { Log.i("goods_id",data.getId()+""); Intent intent = new Intent(getActivity(), GoodsDetialsActivity.class); intent.putExtra("goods_id", data.getId()); startActivity(intent); } }); pull_recycle.setRefreshHeaderText(getContext().getResources().getString(R.string.down_refesh), getContext().getResources().getString(R.string.stop_refesh), getContext().getResources().getString(R.string.now_refesh), getContext().getResources().getString(R.string.success_refesh)); } private void configBanner(List<String> listPic) { banner.setImageLoader(new MyImageLoader()); banner.setImages(listPic); banner.isAutoPlay(true); //设置轮播时间 banner.setDelayTime(3000); // banner.setImageLoader(new MyImageLoader()); banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //设置指示器位置(当banner模式中有指示器时) banner.setIndicatorGravity(BannerConfig.CENTER); //banner设置方法全部调用完毕时最后调用 banner.start(); } @Override public void onRefresh() { pageNo = 1; presenter.getHomeList(1, pageNo, 10,pull_recycle); } @Override public void onLoadMore() { pageNo++; presenter.getHomeList(1, pageNo, 10,pull_recycle); } @Override public void initBannerListSuccess(List<BannerBean.Pic> data) { bannerList.clear(); bannerList.addAll(data); List<String> list = new ArrayList<>(); for (BannerBean.Pic pic : data) { list.add(pic.getBannerImg()); } configBanner(list); } @Override public void getHomeListSuccess(List<HomeFragmentGoodsBean.DataBean.ListBean> listBean) { dataList = new ArrayList<>(); dataList = listBean; if (pageNo == 1) { adapter.clearDatas(); adapter.setDatas(listBean); } else { adapter.addDatas(listBean); } pull_recycle.setPullLoadMoreCompleted(); } @Override public void getHomeDetailsSuccess(MallGoodsDetailsBean.DataBean listBean) { } @Override public void addShopCarSuccess(MallMainUpdataBean updataBean) { } @Override public void failure(String message) { CommonUtil.toastShort(message); } @Override public void showProgress() { } @Override public void hideProgress() { } public class MyImageLoader extends ImageLoader { @Override public void displayImage(Context context, Object path, ImageView imageView) { /** 注意: 1.图片加载器由自己选择,这里不限制,只是提供几种使用方法 2.返回的图片路径为Object类型,由于不确定到底使用的那种图片加载器, 传输的到的是什么格式,那么这种就使用Object接收和返回,你只需要强转成你传输的类型就行, 切记不要胡乱强转! */ Log.i("img===",(String) path); Picasso.with(context).load((String) path).fit().into(imageView); } } @Override public void onResume() { super.onResume(); } @Override public void onStop() { super.onStop(); banner.stopAutoPlay(); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onStart() { super.onStart(); //开始轮播 banner.startAutoPlay(); } @Override public void onClick(View v) { super.onClick(v); switch (v.getId()) { case R.id.title_back: getActivity().finish(); break; } } }
package de.cuuky.varo.player.event.events; import de.cuuky.varo.player.VaroPlayer; import de.cuuky.varo.player.event.BukkitEvent; import de.cuuky.varo.player.event.BukkitEventType; public class KickEvent extends BukkitEvent { public KickEvent() { super(BukkitEventType.KICKED); } @Override public void onExec(VaroPlayer player) { player.getStats().setBan(); player.getStats().removeCountdown(); player.getStats().addSessionPlayed(); } }
package com.atguigu.lgl; import java.rmi.StubNotFoundException; import org.junit.Test; //创建匿名实现类(匿名子类)的对象 //抽象类 abstract class GeometricObject2{ public abstract double findAre(); } //普通类 class Person2{ public void say(){ System.out.println("person2 show"); } } //接口 interface Student{ public abstract void show(); } //class Luo implements Student { // // @Override // public void show() { // System.out.println("这是创建class的实例后重写的show方法 "); // } // //} public class InterfaceTest3 { @Test public void test3(){ // Luo luo1 = new Luo(); // luo1.show(); Student st1 = new Student() { @Override public void show() { System.out.println("这是创建Student接口的实现类的匿名对象后的show方法"); } }; st1.show(); } @Test public void test2(){ //创建的是Person类的匿名子类的对象 Person2 person2 = new Person2() { @Override public void say() { //调用原来Person中的say方法 super.say(); System.out.println("person"); } }; person2.say(); } @Test public void test1(){ double radius = 2.0; //创建GeometricObject2匿名子类的对象 GeometricObject2 g2 = new GeometricObject2() { @Override public double findAre() { // return Math.PI * radius * radius; return 10; } }; System.out.println(g2.findAre()); } }
package com.nixsolutions.micrometr.service.external; public interface PublicApiWebClientBuilder { }
import java.util.*; public class Ch17_05 { private static class Index { int x; int y; Index(int x, int y) { this.x = x; this.y = y; } } private static boolean containsArray(List<List<Integer>> matrix, List<Integer> array) { List<Index> prevPotentialElements = new ArrayList<Index>(); //initial case for (int row = 0; row < matrix.size(); row++){ for (int col = 0; col < matrix.get(0).size(); col++) { if (matrix.get(row).get(col) == array.get(0)) { prevPotentialElements.add(new Index(row, col)); } } } if (prevPotentialElements.isEmpty()) { return false; } // dynamically programmed iterative steps List<Index> nextPotentialElements = prevPotentialElements; for (int i = 1; i < array.size(); i++) { prevPotentialElements = nextPotentialElements; nextPotentialElements = new ArrayList<Index>(); for (int n = 0; n < prevPotentialElements.size(); n++) { int x = prevPotentialElements.get(n).x; int y = prevPotentialElements.get(n).y; if (x - 1 >= 0) { if (matrix.get(x - 1).get(y) == array.get(i)) { nextPotentialElements.add(new Index(x - 1, y)); } } if (y - 1 >= 0) { if (matrix.get(x).get(y - 1) == array.get(i)) { nextPotentialElements.add(new Index(x, y - 1)); } } if (x + 1 < matrix.size()) { if (matrix.get(x + 1).get(y) == array.get(i)) { nextPotentialElements.add(new Index(x + 1, y)); } } if (y + 1 < matrix.get(0).size()) { if (matrix.get(x).get(y + 1) == array.get(i)) { nextPotentialElements.add(new Index(x, y + 1)); } } } if (nextPotentialElements.isEmpty()) { return false; } } return true; } public static void main(String []args) { List<Integer> array = Arrays.asList(1, 3, 4, 6); List<List<Integer>> matrix = new ArrayList<List<Integer>>(); matrix.add(Arrays.asList(1, 2, 3)); matrix.add(Arrays.asList(3, 4, 5)); matrix.add(Arrays.asList(5, 6, 7)); System.out.println(containsArray(matrix, array)); } }
package br.com.abc.javacore.associacao.classes.exercicio.test; import br.com.abc.javacore.associacao.classes.exercicio.Aluno; import br.com.abc.javacore.associacao.classes.exercicio.Local; import br.com.abc.javacore.associacao.classes.exercicio.Professor; import br.com.abc.javacore.associacao.classes.exercicio.Seminario; public class GerenciadorDeSeminarios { public static void main(String[] args) { Aluno aluno1 = new Aluno("Ana", 21); Aluno aluno2 = new Aluno("Joana", 22); Seminario s = new Seminario("Como ser um programador"); Professor prof = new Professor("Josť", "front-end"); Local local = new Local("Rua das Araras", "Jardim"); aluno1.setSeminario(s); aluno2.setSeminario(s); s.setProfessor(prof); s.setLocal(local); s.setAlunos(new Aluno[] {aluno1, aluno2}); prof.setSeminarios(new Seminario[] {s}); s.print(); prof.print(); } }
package io; import java.io.*; import java.nio.charset.StandardCharsets; /** * 简述: * * @author WangLipeng 1243027794@qq.com * @version 1.0 * @since 2020/1/10 13:35 */ public class ConvertIO { public static void main(String[] args) throws IOException { String str = "firelist"; byte[] bytes = str.getBytes(); //将字节数组转换为字符数组 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream, StandardCharsets.UTF_8); char[] chars = new char[10]; int read = inputStreamReader.read(chars, 0, str.length()); System.out.println(read + ":" + String.copyValueOf(chars)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8); outputStreamWriter.write(str, 0, str.length()); outputStreamWriter.flush(); System.out.println(byteArrayOutputStream.toString()); } }
package com.apap.igd.service; import java.sql.Timestamp; import java.util.List; import com.apap.igd.model.DetailPenangananModel; import com.apap.igd.model.JenisPenangananModel; import com.apap.igd.model.KebutuhanObatModel; import com.apap.igd.model.rest.ObatModel; import com.apap.igd.model.PenangananPasienModel; import com.apap.igd.repository.DetailPenangananDb; import com.apap.igd.repository.JenisPenangananDb; import com.apap.igd.repository.KebutuhanObatDb; import com.apap.igd.repository.PenangananPasienDb; import com.apap.igd.rest.ObatRest; import com.apap.igd.model.PenangananPasienModel; import com.apap.igd.repository.DetailPenangananDb; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DetailPenangananServiceImpl implements DetailPenangananService { @Autowired PenangananPasienService penangananPasienService; @Autowired JenisPenangananService jenisPenangananService; @Autowired KebutuhanObatService kebutuhanObatService; @Autowired DetailPenangananDb detailPenangananDb; @Override public DetailPenangananModel addDetailPenanganan(long idPasien, JenisPenangananModel jenisPenanganan) { jenisPenangananService.addJenisPenanganan(jenisPenanganan); DetailPenangananModel detailPenanganan = new DetailPenangananModel(); detailPenanganan.setJenisPenanganan(jenisPenanganan); PenangananPasienModel penangananPasien = penangananPasienService.getMostRecentPenangananPasien(idPasien); detailPenanganan.setPenangananPasien(penangananPasien); detailPenanganan.setWaktu(new Timestamp(System.currentTimeMillis())); System.out.println("sebeleum save detail"); detailPenangananDb.save(detailPenanganan); List<KebutuhanObatModel> listKebutuhanObat = jenisPenanganan.getListKebutuhanObat(); kebutuhanObatService.addListKebutuhanObat(listKebutuhanObat, jenisPenanganan); return detailPenanganan; } @Override public DetailPenangananModel getDetailPenangananByIdDetail(long idDetail) { return detailPenangananDb.findById(idDetail).get(); } @Override public List<DetailPenangananModel> getDetailPenangananByPenangananPasien(PenangananPasienModel penangananPasien) { return detailPenangananDb.findByPenangananPasien(penangananPasien); } @Override public DetailPenangananModel getDetailPenangananByJenisPenanganan(JenisPenangananModel jenisPenanganan) { return detailPenangananDb.findByJenisPenanganan(jenisPenanganan); } }
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.awt.Point; public class BackTraking { private Tablero tablero; private Set<Ficha>mano; private List<Jugada>jugadas; private boolean esMejorado; public final Random r=new Random(); private ArrayList<Ficha> fichas_repetidasMano; private Map<Ficha, Integer> repet_fichas; BackTraking(Tablero tablero,ArrayList<Ficha>pMano,boolean esMejorado) { this.tablero=tablero; this.mano=new HashSet<>(pMano); this.esMejorado=esMejorado; this.fichas_repetidasMano = getRepetsHand(pMano); this.repet_fichas = new HashMap<Ficha, Integer>(); this.repet_fichas = this.startAllCeros(); this.repet_fichas = this.updateRepetFichasWithHand(updateRepetFichas(this.repet_fichas, tablero.getFichas()), new ArrayList<>(this.mano)); //this.showPossiblePlaysHand(getPossiblePlaysHand(new ArrayList<>(mano))); } public Jugada getRespuesta() { jugadas=new ArrayList<>(getJugadas(getCombMano(new ArrayList<>(mano)))); jugadas.sort((o1,o2)->Integer.compare(o2.puntos, o1.puntos)); return jugadas.get(0); } public Map<Ficha, ArrayList<ArrayList<Ficha>>>getCombMano(ArrayList<Ficha>pFichas) { int cant_man = pFichas.size(); Map<Ficha, ArrayList<ArrayList<Ficha>>> grupos = new HashMap<Ficha, ArrayList<ArrayList<Ficha>>>(); for(int pI=0; pI<cant_man; pI++) { ArrayList<ArrayList<Ficha>> lista_fichas_slices = new ArrayList<ArrayList<Ficha>>(); ArrayList<Ficha> combination_list_1 = new ArrayList<Ficha>(); ArrayList<Ficha> combination_list_2 = new ArrayList<Ficha>(); for(int pJ=0; pJ<cant_man; pJ++) { if(!pFichas.get(pI).noCombina(pFichas.get(pJ))) { if(pFichas.get(pI).getFigura()!=pFichas.get(pJ).getFigura() &&pFichas.get(pI).getColor()==pFichas.get(pJ).getColor()) { combination_list_1.add(pFichas.get(pJ)); } else if(pFichas.get(pI).getFigura()==pFichas.get(pJ).getFigura() &&pFichas.get(pI).getColor()!=pFichas.get(pJ).getColor()) { combination_list_2.add(pFichas.get(pJ)); } } } lista_fichas_slices.add(combination_list_1); lista_fichas_slices.add(combination_list_2); grupos.put(pFichas.get(pI), lista_fichas_slices); } return grupos; } public Set<Jugada>getJugadas(Map<Ficha,ArrayList<ArrayList<Ficha>>>grupitos){ Set<Jugada>todasLasPosiblesJugadasCompletas=new HashSet<>(); for(Point xy : tablero.demeLasPosicionesEnQuePueddoEmpezarJugada()) { for(Entry<Ficha,ArrayList<ArrayList<Ficha>>> entradaGrupito:grupitos.entrySet()){ if(tablero.getCualesSePuedePoner(xy.x,xy.y).contains(entradaGrupito.getKey())){ generarArbolDeJugadas(entradaGrupito, todasLasPosiblesJugadasCompletas, xy.x, xy.y); } } } return todasLasPosiblesJugadasCompletas; } private void generarArbolDeJugadas(Entry<Ficha,ArrayList<ArrayList<Ficha>>>jugadaDeLaMano, Set<Jugada>jugadasCompletas,int x, int y) { Ficha[][] t = tablero.getFichas(); Ficha f = jugadaDeLaMano.getKey(); if((t[x][y-1]!=null&&t[x][y+1]!=null&& t[x][y-1].noCombina(t[x][y]))|| t[x-1][y]!=null&&t[x+1][y]!=null&& t[x+1][y].noCombina(t[x][y])){ System.out.println("Satanás es muy grande, porque aquí puede que haga jugadas de más de 6 xdxdxd:c"); return; } if(!jugadaDeLaMano.getValue().get(1).isEmpty()&&( (t[x][y-1]==null&&t[x][y+1]==null)|| (t[x][y-1]!=null&&t[x][y-1].figura==f.figura)|| (t[x][y+1]!=null&&t[x][y+1].figura==f.figura))){ generarArbolDeJugadas(new ArrayList<>(jugadaDeLaMano.getValue().get(1)),f, jugadasCompletas, new Jugada(), x, y, true); } else if(!jugadaDeLaMano.getValue().get(0).isEmpty()&&( (t[x][y-1]==null&&t[x][y+1]==null)|| (t[x][y-1]!=null&&t[x][y-1].color==f.color)||(t[x][y+1]!=null&&t[x][y+1].color==f.color))){ generarArbolDeJugadas(new ArrayList<>(jugadaDeLaMano.getValue().get(0)), jugadaDeLaMano.getKey(), jugadasCompletas, new Jugada(), x, y, true); } if(!jugadaDeLaMano.getValue().get(1).isEmpty()&&( (t[x-1][y]==null&&t[x+1][y]==null)|| (t[x-1][y]!=null&&t[x-1][y].figura==f.figura)|| (t[x+1][y]!=null&&t[x+1][y].figura==f.figura))){ generarArbolDeJugadas(new ArrayList<>(jugadaDeLaMano.getValue().get(1)), f, jugadasCompletas, new Jugada(), x, y, false); } else if(!jugadaDeLaMano.getValue().get(0).isEmpty()&&( (t[x-1][y]==null&&t[x+1][y]==null)|| (t[x-1][y]!=null&&t[x-1][y].color==f.color)|| (t[x+1][y]!=null&&t[x+1][y].color==f.color))){ generarArbolDeJugadas(new ArrayList<>(jugadaDeLaMano.getValue().get(0)), f, jugadasCompletas, new Jugada(), x, y, false); } if(jugadaDeLaMano.getValue().get(0).isEmpty()&&jugadaDeLaMano.getValue().get(1).isEmpty()){ generarArbolDeJugadas(new ArrayList<>(), f, jugadasCompletas, new Jugada(), x, y, null); } } private void generarArbolDeJugadas(List<Ficha>fichasQueFaltanPorColocar, Ficha fichaInicial,Set<Jugada>jugadasCompletas, Jugada jugada,int x,int y,Boolean esPorFila) { fichasQueFaltanPorColocar.remove(fichaInicial); jugada.jugaditas.add(new Jugadita(x, y, fichaInicial)); jugada.isLine = esPorFila; this.tablero.getFichas()[x][y]=fichaInicial; if(fichasQueFaltanPorColocar.isEmpty()) { int bono=0; /* Poda #1 Esta poda trata de identificar las jugadas que tengan al menos una ficha igual a una ficha que este repetida en la mano del jugador actual. */ if (this.isItInJugadaRepetFicha(this.fichas_repetidasMano, jugada.jugaditas)) bono+=6; /* Poda #2 De las fichas que faltan para que se logre un Qwirkle, ya haya salido dos veces, esa jugada es inteligente. */ if(esMejorado && this.isItChipInside(getMissingChips(y, x, esPorFila, jugada), this.repet_fichas)) bono+=6; jugadasCompletas.add(jugada.copy(this.tablero.getPuntos(jugada)+bono)); } else{ boolean flag=false; int derecha=y; int izquierda=y; int arriba=x; int abajo=x; if(esPorFila==null||esPorFila){ while(this.tablero.getFichas()[x][derecha]!=null&&derecha<Tablero.MATRIX_SIDE-1){ Ficha f=this.tablero.getFichas()[x][derecha]; fichasQueFaltanPorColocar.removeIf(j-> j.noCombina(f) ); derecha++; } while(this.tablero.getFichas()[x][izquierda]!=null&&izquierda>0){ Ficha f=this.tablero.getFichas()[x][izquierda]; fichasQueFaltanPorColocar.removeIf(j->j.noCombina(f)); izquierda--; } } if (esPorFila==null||!esPorFila){ while(tablero.getFichas()[arriba][y]!=null&&arriba<Tablero.MATRIX_SIDE-1){ Ficha f=tablero.getFichas()[arriba][y]; fichasQueFaltanPorColocar.removeIf(j->j.noCombina(f)); arriba++; } while(this.tablero.getFichas()[abajo][y]!=null&&abajo>0){ Ficha f=this.tablero.getFichas()[abajo][y]; fichasQueFaltanPorColocar.removeIf(j->j.noCombina(f)); abajo--; } } for (int indiceFichasPorColocar=0;indiceFichasPorColocar<fichasQueFaltanPorColocar.size();indiceFichasPorColocar++) { Ficha fichaPorColocar = fichasQueFaltanPorColocar.get(indiceFichasPorColocar); if(esPorFila==null||esPorFila){ if(this.tablero.getCualesSePuedePoner(x,derecha).contains(fichaPorColocar)){ generarArbolDeJugadas(fichasQueFaltanPorColocar, fichaPorColocar, jugadasCompletas, jugada, x,derecha,true); flag=true; } if(this.tablero.getCualesSePuedePoner(x,izquierda).contains(fichaPorColocar)){ generarArbolDeJugadas(fichasQueFaltanPorColocar, fichaPorColocar, jugadasCompletas, jugada, x,izquierda,true); flag=true; } }if (esPorFila==null||!esPorFila){ if(this.tablero.getCualesSePuedePoner(arriba, y).contains(fichaPorColocar)){ generarArbolDeJugadas(fichasQueFaltanPorColocar, fichaPorColocar, jugadasCompletas, jugada, arriba, y,false); flag=true; } if(this.tablero.getCualesSePuedePoner(abajo, y).contains(fichaPorColocar)){ generarArbolDeJugadas(fichasQueFaltanPorColocar, fichaPorColocar, jugadasCompletas, jugada, abajo, y,false); flag=true; } } }//Si no encontró lugar para poner if(!flag) jugadasCompletas.add(jugada.copy(this.tablero.getPuntos(jugada))); } tablero.getFichas()[x][y]=null; jugada.jugaditas.remove(jugada.jugaditas.size()-1); fichasQueFaltanPorColocar.add(fichaInicial); } /* Metodo Poda #1 */ public boolean isItInJugadaRepetFicha(ArrayList<Ficha> pFichas_repets, Set<Jugadita> pJugada) { for (Ficha pRepetFicha : pFichas_repets) { for (Jugadita pPlay: pJugada) { if(pPlay.ficha.getColor() == pRepetFicha.getColor() && pPlay.ficha.getFigura() == pRepetFicha.getFigura()) { return true; } } } return false; } /* Metodos Poda #2 */ public boolean isItChipInside(List<Ficha> pJugada_faltan, Map<Ficha, Integer> pList_repets) { //this.showArray(pJugada_faltan); int contador = 0; for (Map.Entry<Ficha, Integer> repets : pList_repets.entrySet()) { Ficha ficha = repets.getKey(); Integer value = repets.getValue(); if (value >= 2) { for (Ficha pFicha : pJugada_faltan) { if (ficha.getFigura() == pFicha.getFigura() && ficha.getColor() == pFicha.getColor()) { //System.out.println("Poda#2: Esta ficha esta en la jugada que falta y ah salido dos o tres veces "+fichaToSimbol(pFicha)); contador++; } } } } return ((float)contador) / pJugada_faltan.size() > 0.5; } public List<Ficha>getCualesFaltan(List<Jugadita> fichasDeLaJugada) { //this.showArrayPlay(fichasDeLaJugada); List<Ficha>losQueSePuedenPoner = new ArrayList<>(this.tablero.todasLasFichas); for(Jugadita f1: fichasDeLaJugada){ for(int k=0;k<losQueSePuedenPoner.size();){ if(f1.ficha.noCombina(losQueSePuedenPoner.get(k))) losQueSePuedenPoner.remove(k); else k++; } } return losQueSePuedenPoner; } public List<Ficha> getMissingChips(int y, int x, Boolean pEsPorFila, Jugada pJugada) { ArrayList<Ficha> fichas_faltantes = new ArrayList<Ficha>(); int derecha = y; int izquierda = y; int arriba = x; int abajo = x; Set<Jugadita> jugada_tablero = new HashSet<>(); Set<Jugadita> jugada_tablero1 = new HashSet<>(); if(pEsPorFila == null || pEsPorFila) { while(this.tablero.getFichas()[x][derecha] != null && derecha < Tablero.MATRIX_SIDE - 1) derecha++; while(this.tablero.getFichas()[x][izquierda] != null && izquierda>0) izquierda--; for(int i=izquierda+1; i < derecha; i++) { if(this.tablero.getFichas()[x][i] != null) { Jugadita pJugadita = new Jugadita(x, i, this.tablero.getFichas()[x][i]); jugada_tablero.add(pJugadita); } } //this.showArrayPlay(jugada_tablero); boolean pValue = false; for (Jugadita pPlay: pJugada.jugaditas) { for (Jugadita pJ : jugada_tablero) { if((pPlay.ficha.getFigura()==pJ.ficha.getFigura() && pPlay.ficha.getColor()==pJ.ficha.getColor())) { pValue = true; } } if(pValue == false){ Jugadita pJugadita2 = new Jugadita(pPlay.x, pPlay.y, pPlay.ficha); jugada_tablero1.add(pJugadita2); } } for (Jugadita pJu: jugada_tablero1) { jugada_tablero.add(pJu); } List<Jugadita> pJugada_tablero2 = new ArrayList<>(jugada_tablero); pJugada_tablero2.sort((o1,o2)->Integer.compare(o1.y, o2.y)); List<Ficha> fichas_puedo_poner_verdad = new ArrayList<Ficha>(); fichas_puedo_poner_verdad = getCualesFaltan(pJugada_tablero2); return fichas_puedo_poner_verdad; } Set<Jugadita> jugada_tablero2 = new HashSet<>(); Set<Jugadita> jugada_tablero22 = new HashSet<>(); if (pEsPorFila == null || !pEsPorFila) { while(this.tablero.getFichas()[abajo][y] != null && abajo < Tablero.MATRIX_SIDE - 1) abajo++; while(this.tablero.getFichas()[arriba][y] != null && arriba > 0) arriba--; for(int j=arriba+1; j < abajo; j++) { if(this.tablero.getFichas()[j][y] != null) { Jugadita pJugadita0 = new Jugadita(j, y, this.tablero.getFichas()[j][y]); jugada_tablero2.add(pJugadita0); } } //this.showArrayPlay(jugada_tablero2); boolean pValue = false; for (Jugadita pPlay: pJugada.jugaditas) { for (Jugadita pJ : jugada_tablero2) { if((pPlay.ficha.getFigura()==pJ.ficha.getFigura() && pPlay.ficha.getColor()==pJ.ficha.getColor())) { pValue = true; } } if(pValue == false){ Jugadita pJugadita2 = new Jugadita(pPlay.x, pPlay.y, pPlay.ficha); jugada_tablero22.add(pJugadita2); } } for (Jugadita pJu: jugada_tablero22) { jugada_tablero2.add(pJu); } List<Jugadita> pJugada_tablero = new ArrayList<>(jugada_tablero2); pJugada_tablero.sort((o1,o2)->Integer.compare(o1.x, o2.x)); List<Ficha> fichas_puedo_poner_verdad2 = new ArrayList<Ficha>(); fichas_puedo_poner_verdad2 = getCualesFaltan(pJugada_tablero); return fichas_puedo_poner_verdad2; } List<Ficha> lista_vacia = new ArrayList<Ficha>(); return lista_vacia; } /* Metodos Objeto que lleva la cuenta de las fichas que ya han saliedo de la bolsa de fichas */ public Map<Ficha, Integer> startAllCeros() { Map<Ficha, Integer> pList_repet = new HashMap<Ficha, Integer>(); ArrayList<Ficha> pTotal_fichas = this.getAllCheaps(); Integer initial_number = 0; for (Ficha pFicha : pTotal_fichas) { pList_repet.put(pFicha, initial_number); } return pList_repet; } public ArrayList<Ficha> getAllCheaps() { ArrayList<Ficha> lista = new ArrayList<Ficha>(); for (Figura figura:Qwirkle.FIGURAS) for(Color color:Qwirkle.COLORES) lista.add(new Ficha(figura,color)); return lista; } public Map<Ficha, Integer> updateRepetFichasWithHand(Map<Ficha, Integer> pRepetFichas, ArrayList<Ficha> pFicha) { Map<Ficha, Integer> pRepet_fichas = pRepetFichas; for (Ficha ficha : pFicha) { for (Map.Entry<Ficha, Integer> repetFichas : pRepetFichas.entrySet()) { Ficha ficha_repet = repetFichas.getKey(); Integer value = repetFichas.getValue(); if (ficha == ficha_repet) { value += value + 1; pRepet_fichas.put(ficha_repet, value); } } } return pRepet_fichas; } public Map<Ficha, Integer> updateRepetFichas(Map<Ficha, Integer> pRepetFichas, Ficha[][] pFichasTablero) { Map<Ficha, Integer> pRepet_fichas = pRepetFichas; int pFichas_tablero = pFichasTablero[0].length; for (int indeX = 0; indeX < pFichas_tablero; indeX++) { for (int indeY = 0; indeY < pFichas_tablero; indeY++) { for (Map.Entry<Ficha, Integer> repetFichas : pRepet_fichas.entrySet()) { Ficha ficha_repet = repetFichas.getKey(); if (pFichasTablero[indeX][indeY] == null) { break; } else if (pFichasTablero[indeX][indeY].getFigura() == ficha_repet.getFigura() && pFichasTablero[indeX][indeY].getColor() == ficha_repet.getColor()) { Integer value = repetFichas.getValue(); value++; pRepet_fichas.put(ficha_repet, value); } } } } return pRepetFichas; } public ArrayList<Ficha> getRepetsHand(ArrayList<Ficha> pMano) { int largo_mano = pMano.size()-1; ArrayList<Ficha> mano_fichas = pMano; ArrayList<Ficha> fichas_repetidas_mano = new ArrayList<Ficha>(); for (int index=0; index<largo_mano; index++) { for (int indey=index+1; indey<=largo_mano; indey++) { if(mano_fichas.get(index).getFigura()==mano_fichas.get(indey).getFigura() &&mano_fichas.get(index).getColor()==mano_fichas.get(indey).getColor()) { fichas_repetidas_mano.add(mano_fichas.get(indey)); } } } return fichas_repetidas_mano; } /* Metodos para el Objeto Mapa que tiene todas las posibles jugadas de la mano. */ public Map<Ficha, ArrayList<ArrayList<Ficha>>> getPossiblePlaysHand(ArrayList<Ficha> pFichas) { int cant_man = pFichas.size(); Map<Ficha, ArrayList<ArrayList<Ficha>>> grupos = new HashMap<Ficha, ArrayList<ArrayList<Ficha>>>(); for (int pI = 0; pI < cant_man; pI++) { ArrayList<Ficha> combination_list_1 = new ArrayList<Ficha>(); ArrayList<Ficha> combination_list_2 = new ArrayList<Ficha>(); for (int pJ = 0; pJ < cant_man; pJ++) { if (!pFichas.get(pI).noCombina(pFichas.get(pJ))) { if (pFichas.get(pI).getFigura() != pFichas.get(pJ).getFigura() && pFichas.get(pI).getColor() == pFichas.get(pJ).getColor()) { combination_list_1.add(pFichas.get(pJ)); } else if (pFichas.get(pI).getFigura() == pFichas.get(pJ).getFigura() && pFichas.get(pI).getColor() != pFichas.get(pJ).getColor()) { combination_list_2.add(pFichas.get(pJ)); } } } ArrayList<ArrayList<Ficha>> lista_fichas_slices = new ArrayList<ArrayList<Ficha>>(); lista_fichas_slices.add(combination_list_1); lista_fichas_slices.add(combination_list_2); grupos.put(pFichas.get(pI), lista_fichas_slices); } return grupos; } public ArrayList<Ficha> getCombinationList1(ArrayList<Ficha> pList) { int contador = 0; ArrayList<Ficha> combination = new ArrayList<Ficha>(); for (int index = 1; index >= 0; index--) { combination.add(contador, pList.get(index)); contador = 1; } return combination; } public void showPossiblePlaysHand(Map<Ficha, ArrayList<ArrayList<Ficha>>> pGrupo) { for(Map.Entry<Ficha, ArrayList<ArrayList<Ficha>>> entry:pGrupo.entrySet()) { Ficha key = entry.getKey(); ArrayList<ArrayList<Ficha>> value = entry.getValue(); System.out.println("\nLa ficha: " + fichaToSimbol(key) + ", tiene las siguientes jugadas: "); for (ArrayList<Ficha> playList : value) { for (Ficha ficha : playList) { System.out.println(fichaToSimbol(ficha)); } System.out.println("-"); } } } /* Metodo para imprimir el juego. */ private String getSimboloColor(Color c) { if(c==Color.AMARILLO) return "Am"; else if(c==Color.AZUL) return "Az"; else if(c==Color.NARANJA) return "Na"; else if(c==Color.MORADO) return "Mo"; else if(c==Color.ROJO) return "Ro"; else if(c==Color.VERDE) return "Ve"; else return "..."; } private String getSimboloFigura(Figura f) { switch(f){ case CIRCULO: return "O"; case CUADRADO: return "C"; case ROMBO: return "R"; case SOL: return "S"; case TREBOL: return "T"; case X: return "X"; } return "...."; } private String fichaToSimbol(Ficha ficha) { if(ficha==null)return "---"; return getSimboloFigura(ficha.getFigura())+getSimboloColor(ficha.getColor()); } public void imprimirMano(Set<Ficha> pMano) { String out="\nMano sin repetidas [ "; for (Ficha ficha : pMano) { out+= fichaToSimbol(ficha)+", "; } System.out.println(out+"]"); } public void showArrayList(ArrayList<Ficha> pMano) { String out="Poda#1: Fichas repetidas de la jugada que estan en la mano --> [ "; for (Ficha ficha : pMano) { out+= fichaToSimbol(ficha)+", "; } System.out.println(out+"]"); } public void showArray(List<Ficha> pMano) { String out="\nFichas que faltan por jugar -- [ "; for (Ficha ficha : pMano) { out+= fichaToSimbol(ficha)+", "; } System.out.println(out+"]"); } public void showArrayPlay(List<Jugadita> pMano) { String out="\nJugada del tablero con la que juego en este turno suponiendo -- [ "; for (Jugadita jugadita : pMano) { System.out.println("x: "+ jugadita.x + " y: " + jugadita.y); out+= fichaToSimbol(jugadita.ficha)+", "; } System.out.println(out+"]"); } /* Final de la clase BackTraking. */ } /* ArrayList<ArrayList<Ficha>> lista_fichas_slices2 = new ArrayList<ArrayList<Ficha>>(); if (combination_list_1.size() == 2) { ArrayList<Ficha> combination_list_1_1 = getCombinationList1(combination_list_1); lista_fichas_slices2.add(combination_list_1_1); grupos.put(pFichas.get(pI), lista_fichas_slices2); } if (combination_list_2.size() == 2) { ArrayList<Ficha> combination_list_1_2 = getCombinationList1(combination_list_2); lista_fichas_slices2.add(combination_list_1_2); grupos.put(pFichas.get(pI), lista_fichas_slices2); } if (combination_list_1.size() == 3) { ArrayList<ArrayList<Ficha>> combination_list_3_1 = this.getAllCombinations(combination_list_1); grupos.put(pFichas.get(pI), combination_list_3_1); } if (combination_list_2.size() == 3) { ArrayList<ArrayList<Ficha>> combination_list_3_2 = this.getAllCombinations(combination_list_2); grupos.put(pFichas.get(pI), combination_list_3_2); }*/ /* public void showAllComb(ArrayList<ArrayList<Integer>> pLista) { for (ArrayList<Integer> pListita : pLista) { System.out.println("["); for (Integer pNum : pListita) { System.out.println(pNum+","); } System.out.println("]"); } } public ArrayList<ArrayList<Ficha>> getAllCombinations(ArrayList<Ficha> pList) { ArrayList<ArrayList<Ficha>> lista = new ArrayList<ArrayList<Ficha>>(); ArrayList<Ficha> list_comb = new ArrayList<Ficha>(); list_comb.add(pList.get(0)); list_comb.add(pList.get(1)); list_comb.add(pList.get(2)); lista.add(list_comb); ArrayList<Ficha> list_comb_0 = new ArrayList<Ficha>(); list_comb_0.add(pList.get(0)); list_comb_0.add(pList.get(2)); list_comb_0.add(pList.get(1)); lista.add(list_comb_0); ArrayList<Ficha> list_comb_1 = new ArrayList<Ficha>(); list_comb_1.add(pList.get(2)); list_comb_1.add(pList.get(1)); list_comb_1.add(pList.get(0)); lista.add(list_comb_1); ArrayList<Ficha> list_comb_2 = new ArrayList<Ficha>(); list_comb_2.add(pList.get(2)); list_comb_2.add(pList.get(0)); list_comb_2.add(pList.get(1)); lista.add(list_comb_2); ArrayList<Ficha> list_comb_3 = new ArrayList<Ficha>(); list_comb_3.add(pList.get(1)); list_comb_3.add(pList.get(0)); list_comb_3.add(pList.get(2)); lista.add(list_comb_3); ArrayList<Ficha> list_comb_4 = new ArrayList<Ficha>(); list_comb_4.add(pList.get(1)); list_comb_4.add(pList.get(2)); list_comb_4.add(pList.get(0)); lista.add(list_comb_4); return lista; } public ArrayList<ArrayList<Integer>> getAllCombToEachComb(ArrayList<Integer> pList) { ArrayList<ArrayList<Integer>> pAll_combinations = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> pAll_list = new ArrayList<ArrayList<Integer>>(); pAll_list = getAllCombinations(pList); for (ArrayList<Integer> pLista:pAll_list ) { pAll_combinations.add(pLista); } ArrayList<ArrayList<Integer>> pAll_list_0 = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> pList_all = new ArrayList<Integer>(); pList_all.add(pList.get(3)); pList_all.add(pList.get(0)); pList_all.add(pList.get(1)); pList_all.add(pList.get(2)); pAll_list_0 = getAllCombinations(pList_all); for (ArrayList<Integer> pLista:pAll_list_0 ) { pAll_combinations.add(pLista); } ArrayList<ArrayList<Integer>> pAll_list_1 = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> pList_all_1 = new ArrayList<Integer>(); pList_all_1.add(pList.get(2)); pList_all_1.add(pList.get(3)); pList_all_1.add(pList.get(0)); pList_all_1.add(pList.get(1)); pAll_list_1 = getAllCombinations(pList_all_1); for (ArrayList<Integer> pLista:pAll_list_1 ) { pAll_combinations.add(pLista); } ArrayList<ArrayList<Integer>> pAll_list_2 = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> pList_all_2 = new ArrayList<Integer>(); pList_all_2.add(pList.get(1)); pList_all_2.add(pList.get(2)); pList_all_2.add(pList.get(3)); pList_all_2.add(pList.get(0)); pAll_list_2 = getAllCombinations(pList_all_2); for (ArrayList<Integer> pLista:pAll_list_2 ) { pAll_combinations.add(pLista); } return pAll_combinations; }*/
package com.example.dao; import javax.persistence.Id; import org.hibernate.Session; import org.hibernate.Transaction; import com.example.model.Product; import com.example.utl.HibernateUtil; import java.util.List; public class ProductDao { public void saveProduct(Product product) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); session.save(product); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } public int searchProduct(Product product) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { transaction = session.beginTransaction(); Product products = session.get(Product.class, product.getBarcode()); if(products != null) { transaction.commit(); return(0); } transaction.commit(); }catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } return(1); } public List<Product> getAllProduct() { Transaction transaction = null; List<Product> listOfProduct = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // get an user object listOfProduct = session.createQuery("from Product").getResultList(); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } return listOfProduct; } }
package com.pykj.annotation.demo.annotation.configure.componentscan; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.Arrays; /** * 测试ComponentScan */ public class MyTest { @Test public void test() { ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); String[] beanDefinitionNames = context.getBeanDefinitionNames(); System.out.println(Arrays.toString(beanDefinitionNames) .replaceAll("\\[|\\]", "") .replaceAll("\\, ", "\n")); } }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.dto.inventory; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import org.inbio.ara.dto.BaseDTOFactory; import org.inbio.ara.dto.BaseEntityOrDTOFactory; import org.inbio.ara.dto.agent.CollectionDTO; import org.inbio.ara.persistence.collection.Collection; import org.inbio.ara.persistence.gathering.CollectorObserver; import org.inbio.ara.persistence.gathering.CollectorObserverPK; import org.inbio.ara.persistence.gathering.GatheringObservation; import org.inbio.ara.persistence.gathering.GatheringObservationCollection; import org.inbio.ara.persistence.gathering.GatheringObservationCollectionPK; import org.inbio.ara.persistence.gathering.GatheringObservationProject; import org.inbio.ara.persistence.gathering.GatheringObservationProjectPK; import org.inbio.ara.persistence.gathering.Project; import org.inbio.ara.persistence.gis.GeographicLayerEntity; import org.inbio.ara.persistence.gis.GeoreferencedSite; import org.inbio.ara.persistence.gis.Site; import org.inbio.ara.persistence.person.Person; /** * * @author mvargas */ public class GatheringObservationDTOFactory extends BaseEntityOrDTOFactory<GatheringObservation, GatheringObservationDTO> { /** * Resive una DTO y lo canvierte en una entidad * @param gDTO * @return */ public GatheringObservation createEntity(GatheringObservationDTO gDTO){ if(gDTO == null) return null; GatheringObservation gEntity = new GatheringObservation(); gEntity.setGatheringObservationId(gDTO.getGatheringObservationId()); Site site = new Site(); site.setSiteId(gDTO.getLocalityId()); gEntity.setSite(site); gEntity.setInitialDate(gDTO.getInitialDateTime()); gEntity.setFinalDate(gDTO.getFinalDateTime()); gEntity.setResponsiblePersonId(gDTO.getResponsibleId()); gEntity.setExpositionId(gDTO.getExpositionId()); gEntity.setGradientPercentage(gDTO.getGradient()); gEntity.setMaximumElevation(gDTO.getMaximumElevation()); gEntity.setMinimumElevation(gDTO.getMinimumElevation()); gEntity.setMaximumDepth(gDTO.getMaximumDepth()); gEntity.setMinimumDepth(gDTO.getMinimumDepth()); gEntity.setSurroundingsDescription(gDTO.getSurroundingDescription()); gEntity.setSiteDescription(gDTO.getSiteDescription()); gEntity.setCollectionId(gDTO.getCollectionId()); /* Lista de colectores */ List<PersonDTO> colectorDTOList = gDTO.getColectorsList(); List<CollectorObserver> newList = new ArrayList(); Long secuence = new Long(1); for(PersonDTO pDTO : colectorDTOList){ CollectorObserverPK pk = new CollectorObserverPK(gDTO.getGatheringObservationId(), pDTO.getPersonKey()); CollectorObserver newEntry = new CollectorObserver(pk); newEntry.setSequence(secuence); newList.add(newEntry); secuence++; } gEntity.setCollectorObserverList(newList); /* Lista de projectos */ List<ProjectDTO> projectDTOList = gDTO.getProjectsList(); List<GatheringObservationProject> newProjects = new ArrayList(); for(ProjectDTO proDTO : projectDTOList){ GatheringObservationProjectPK pk = new GatheringObservationProjectPK(gDTO.getGatheringObservationId(), proDTO.getProjectId()); GatheringObservationProject newEntry = new GatheringObservationProject(pk); newProjects.add(newEntry); } gEntity.setGatheringProjectlist(newProjects); /* Lista de colecciones asociadas */ List<CollectionDTO> collDTOList = gDTO.getCollectionsList(); List<GatheringObservationCollection> newCollections = new ArrayList(); for(CollectionDTO colDTO : collDTOList){ GatheringObservationCollectionPK pk = new GatheringObservationCollectionPK(gDTO.getGatheringObservationId(), colDTO.getCollectionId()); GatheringObservationCollection newEntry = new GatheringObservationCollection(pk); newCollections.add(newEntry); } gEntity.setGatheringCollectionList(newCollections); return gEntity; } /** * Resive una DTO y lo convierte en una entidad sin listas asociadas * @param gDTO * @return */ public GatheringObservation createSimpleEntity(GatheringObservationDTO gDTO){ if(gDTO == null) return null; GatheringObservation gEntity = new GatheringObservation(); Site site = new Site(); site.setSiteId(gDTO.getLocalityId()); gEntity.setSite(site); gEntity.setInitialDate(gDTO.getInitialDateTime()); gEntity.setFinalDate(gDTO.getFinalDateTime()); gEntity.setResponsiblePersonId(gDTO.getResponsibleId()); gEntity.setExpositionId(gDTO.getExpositionId()); gEntity.setGradientPercentage(gDTO.getGradient()); gEntity.setMaximumElevation(gDTO.getMaximumElevation()); gEntity.setMinimumElevation(gDTO.getMinimumElevation()); gEntity.setMaximumDepth(gDTO.getMaximumDepth()); gEntity.setMinimumDepth(gDTO.getMinimumDepth()); gEntity.setSurroundingsDescription(gDTO.getSurroundingDescription()); gEntity.setSiteDescription(gDTO.getSiteDescription()); gEntity.setCollectionId(gDTO.getCollectionId()); return gEntity; } /** * Resive una entidad y la convierte en DTO * @param g es la entidad de recolecciones * @return un DTO de recolecciones */ public GatheringObservationDTO createDTO(GatheringObservation g) { if(g == null) return null; GatheringObservationDTO gDTO = new GatheringObservationDTO(); gDTO.setGatheringObservationId(g.getGatheringObservationId()); Site site = g.getSite(); if(site!=null){ gDTO.setLocalityDescription(site.getDescription()); gDTO.setCoordinates(site.getCoordinatesAsString()); gDTO.setLocalityId(site.getSiteId()); for(GeoreferencedSite gs : site.getGeoreferencedSites()){ if(GeographicLayerEntity.COUNTRY.equals(gs.getGeoreferencedSitePK().getGeographicLayerId())) gDTO.setCountryId(gs.getGeoreferencedSitePK().getGeographicSiteId()); else if(GeographicLayerEntity.PROVINCE.equals(gs.getGeoreferencedSitePK().getGeographicLayerId())) gDTO.setProvinceId(gs.getGeoreferencedSitePK().getGeographicSiteId()); } } gDTO.setGradient(g.getGradientPercentage()); gDTO.setMinimumElevation(g.getMinimumElevation()); gDTO.setMaximumElevation(g.getMaximumElevation()); gDTO.setMaximumDepth(g.getMaximumDepth()); gDTO.setMinimumDepth(g.getMinimumDepth()); Person responsiblePerson = g.getResponsiblePerson(); if(responsiblePerson!=null){ gDTO.setResponsibleName(responsiblePerson.getNaturalLongName()); gDTO.setResponsibleId(responsiblePerson.getPersonId()); } gDTO.setInitialDateTime(g.getInitialDate()); gDTO.setFinalDateTime(g.getFinalDate()); gDTO.setSiteDescription(g.getSiteDescription()); gDTO.setSurroundingDescription(g.getSurroundingsDescription()); gDTO.setCollectionId(g.getCollectionId()); gDTO.setExpositionId(g.getExpositionId()); /* Lista de colectores */ List<CollectorObserver> colectores = g.getCollectorObserverList(); List<PersonDTO> newColectores = new ArrayList(); String collectorsString = ""; for(CollectorObserver aux : colectores){ Person persona = aux.getPerson(); PersonDTO newPersona = new PersonDTO(); newPersona.setPersonKey(persona.getPersonId()); newPersona.setNaturalLongName(persona.getNaturalLongName()); newColectores.add(newPersona); collectorsString += newPersona.getNaturalLongName()+"; "; } if(collectorsString.length()>1) collectorsString = collectorsString.substring(0,collectorsString.length()-2); gDTO.setCollectorsString(collectorsString); gDTO.setColectorsList(newColectores); /* Lista de proyectos */ List<GatheringObservationProject> proyectos = g.getGatheringProjectList(); List<ProjectDTO> newProyectos = new ArrayList(); for(GatheringObservationProject aux : proyectos){ Project proyecto = aux.getProject(); ProjectDTO newProyecto = new ProjectDTO(); newProyecto.setProjectId(proyecto.getProjectId()); newProyecto.setDescription(proyecto.getDescription()); newProyectos.add(newProyecto); } gDTO.setProjectsList(newProyectos); /* Lista de colecciones asociadas */ List<GatheringObservationCollection> colecciones = g.getGatheringCollectionList(); List<CollectionDTO> newColecciones = new ArrayList(); for(GatheringObservationCollection aux : colecciones){ Collection col = aux.getCollection(); CollectionDTO newcol = new CollectionDTO(); newcol.setCollectionId(col.getCollectionId()); newcol.setCollectionName(col.getName()); newColecciones.add(newcol); } gDTO.setCollectionsList(newColecciones); //seleted is used in the Graphical Interface, should be set in false gDTO.setSelected(false); return gDTO; } @Override public GatheringObservation getEntityWithPlainValues(GatheringObservationDTO gDTO) { if(gDTO == null) return null; GatheringObservation gEntity = new GatheringObservation(); Site site = new Site(); site.setSiteId(gDTO.getLocalityId()); gEntity.setSite(site); gEntity.setInitialDate(gDTO.getInitialDateTime()); gEntity.setFinalDate(gDTO.getFinalDateTime()); gEntity.setResponsiblePersonId(gDTO.getResponsibleId()); gEntity.setExpositionId(gDTO.getExpositionId()); gEntity.setGradientPercentage(gDTO.getGradient()); gEntity.setMaximumElevation(gDTO.getMaximumElevation()); gEntity.setMinimumElevation(gDTO.getMinimumElevation()); gEntity.setMaximumDepth(gDTO.getMaximumDepth()); gEntity.setMinimumDepth(gDTO.getMinimumDepth()); gEntity.setSurroundingsDescription(gDTO.getSurroundingDescription()); gEntity.setSiteDescription(gDTO.getSiteDescription()); gEntity.setCollectionId(gDTO.getCollectionId()); //System.out.println("desde dtoFactory "+gDTO.getUserName()); return gEntity; } @Override public GatheringObservation updateEntityWithPlainValues(GatheringObservationDTO gDTO, GatheringObservation gEntity) { if(gDTO == null) return null; //GatheringObservation gEntity = new GatheringObservation(); gEntity.setGatheringObservationId(gDTO.getGatheringObservationId()); Site site = new Site(); site.setSiteId(gDTO.getLocalityId()); gEntity.setSite(site); gEntity.setInitialDate(gDTO.getInitialDateTime()); gEntity.setFinalDate(gDTO.getFinalDateTime()); gEntity.setResponsiblePersonId(gDTO.getResponsibleId()); gEntity.setExpositionId(gDTO.getExpositionId()); gEntity.setGradientPercentage(gDTO.getGradient()); gEntity.setMaximumElevation(gDTO.getMaximumElevation()); gEntity.setMinimumElevation(gDTO.getMinimumElevation()); gEntity.setMaximumDepth(gDTO.getMaximumDepth()); gEntity.setMinimumDepth(gDTO.getMinimumDepth()); gEntity.setSurroundingsDescription(gDTO.getSurroundingDescription()); gEntity.setSiteDescription(gDTO.getSiteDescription()); gEntity.setCollectionId(gDTO.getCollectionId()); /* Lista de colectores */ List<PersonDTO> colectorDTOList = gDTO.getColectorsList(); List<CollectorObserver> newList = new ArrayList(); Long secuence = new Long(1); for(PersonDTO pDTO : colectorDTOList){ CollectorObserverPK pk = new CollectorObserverPK(gDTO.getGatheringObservationId(), pDTO.getPersonKey()); CollectorObserver newEntry = new CollectorObserver(pk); newEntry.setSequence(secuence); newList.add(newEntry); secuence++; } gEntity.setCollectorObserverList(newList); /* Lista de projectos */ List<ProjectDTO> projectDTOList = gDTO.getProjectsList(); List<GatheringObservationProject> newProjects = new ArrayList(); for(ProjectDTO proDTO : projectDTOList){ GatheringObservationProjectPK pk = new GatheringObservationProjectPK(gDTO.getGatheringObservationId(), proDTO.getProjectId()); GatheringObservationProject newEntry = new GatheringObservationProject(pk); newProjects.add(newEntry); } gEntity.setGatheringProjectlist(newProjects); /* Lista de colecciones asociadas */ List<CollectionDTO> collDTOList = gDTO.getCollectionsList(); List<GatheringObservationCollection> newCollections = new ArrayList(); for(CollectionDTO colDTO : collDTOList){ GatheringObservationCollectionPK pk = new GatheringObservationCollectionPK(gDTO.getGatheringObservationId(), colDTO.getCollectionId()); GatheringObservationCollection newEntry = new GatheringObservationCollection(pk); newCollections.add(newEntry); } gEntity.setGatheringCollectionList(newCollections); gEntity.setLastModificationBy(gDTO.getUserName()); gEntity.setLastModificationDate(new GregorianCalendar()); return gEntity; } }
package org.wxy.weibo.cosmos.ui.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import org.wxy.weibo.cosmos.bean.AccountnumberBean; import org.wxy.weibo.cosmos.Activity; import org.wxy.weibo.cosmos.R; import org.wxy.weibo.cosmos.utils.GlideUtil; import org.wxy.weibo.cosmos.view.CircleImageView; import java.util.List; public class AccountnumberAdapter extends RecyclerView.Adapter<AccountnumberAdapter.AccountnumberHolder> implements View.OnClickListener { private List<AccountnumberBean> bean; private Context context; public AccountnumberAdapter(Context context,List<AccountnumberBean> bean){ this.bean=bean; this.context=context; } private OnClickListener onClickListener; @NonNull @Override public AccountnumberHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view=LayoutInflater.from(context).inflate(R.layout.item_accoutnumber,parent,false); return new AccountnumberHolder(view); } @Override public void onBindViewHolder(@NonNull AccountnumberHolder holder, int position) { holder.text.setText(bean.get(position).getName()); GlideUtil.load(Activity.mainActivity(),holder.img,bean.get(position).getUrl()); holder.linear.setOnClickListener(this); holder.linear.setTag(position); } @Override public int getItemCount() { return bean.size(); } @Override public void onClick(View v) { if (v!=null) { onClickListener.ClickListener((Integer) v.getTag()); } } class AccountnumberHolder extends RecyclerView.ViewHolder{ private TextView text; private CircleImageView img; private LinearLayout linear; public AccountnumberHolder(View v) { super(v); linear=v.findViewById(R.id.linear); text=v.findViewById(R.id.name); img=v.findViewById(R.id.img); } } public interface OnClickListener{ void ClickListener(int i); } public void OnClickListener(OnClickListener onClickListener){ this.onClickListener=onClickListener; } }
package com.cloudinte.modules.xingzhengguanli.dao; import java.util.List; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.cloudinte.modules.xingzhengguanli.entity.WorkAttendanceSetting; /** * 加班天数设置DAO接口 * @author dcl * @version 2019-12-12 */ @MyBatisDao public interface WorkAttendanceSettingDao extends CrudDao<WorkAttendanceSetting> { long findCount(WorkAttendanceSetting workAttendanceSetting); void batchInsert(List<WorkAttendanceSetting> workAttendanceSetting); void batchUpdate(List<WorkAttendanceSetting> workAttendanceSetting); void batchInsertUpdate(List<WorkAttendanceSetting> workAttendanceSetting); void disable(WorkAttendanceSetting workAttendanceSetting); void deleteByIds(WorkAttendanceSetting workAttendanceSetting); }
package com.hr.personnel.repository.impl; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.hr.login.model.LoginModel; import com.hr.personnel.model.DepartmentDetail; import com.hr.personnel.repository.AddNewPersonnelRepository; @Repository public class AddNewPersonnelRepositoryImpl implements AddNewPersonnelRepository { @Autowired EntityManager entityManager; @Override public LoginModel getLoginModelByEmpNo(String empNo) { try { return (LoginModel)entityManager.createQuery("from loginModel where empNo = :empNo", LoginModel.class).setParameter("empNo", empNo).getSingleResult(); } catch(NoResultException nre) { return null; } catch(NonUniqueResultException nure) { return null; } catch(Exception e) { return null; } } @Override public DepartmentDetail findDepartment(Integer departmentNumber) { try { return entityManager.find(DepartmentDetail.class, departmentNumber); } catch(Exception e) { return null; } } @Override public boolean createNewPersonnel(LoginModel loginModel) { try { entityManager.persist(loginModel); return true; } catch(Exception e) { e.printStackTrace(); return false; } } }
package rx.plugins; /** * Created on 2016/7/11. * By nesto * <p/> * a hacky way from * http://fedepaol.github.io/blog/2015/09/13/testing-rxjava-observables-subscriptions/ */ public class RxJavaTestPlugins extends RxJavaPlugins { RxJavaTestPlugins() { super(); } public static void resetPlugins() { getInstance().reset(); } }
package com.socialmeeting.domain.product; import com.socialmeeting.domain.meeting.MeetingTypes; public class DemonstrationEdition extends ProductFeatures implements IProductEdition { public DemonstrationEdition() { setMeetingLimitation(true); setRecording(false); addMeetingType(MeetingTypes.STANDARD); // addLanguage(english); } }
package net.tascalate.async.core; import java.io.Serializable; class Either<R, E extends Throwable> implements Serializable { final private static long serialVersionUID = 4315928456202445814L; final private R result; final private E error; protected Either(final R result, final E error) { this.result = result; this.error = error; } final boolean isError() { return null != error; } final boolean isResult() { return !isError(); } final R result() { return result; } final E error() { return error; } static <R, E extends Throwable> Either<R, E> result(final R result) { return new Either<R, E>(result, null); } static <R, E extends Throwable> Either<R, E> error(final E error) { return new Either<R, E>(null, error); } R done() throws E { if (isError()) { throw error; } else { return result; } } R doneUnchecked() { if (isError()) { return sneakyThrow(error); } else { return result; } } @SuppressWarnings("unchecked") private static <T, E extends Throwable> T sneakyThrow(Throwable ex) throws E { throw (E)ex; } }
package de.kfs.db.structure; import de.kfs.db.SceneManager; import javafx.beans.property.Property; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class AbstractBike implements Comparable<AbstractBike> { /** * Abstract Class representing a Bike */ protected String internalNumber; protected String frameNumber; protected BikeKey bikeKey; protected InformationWrapper additionalInfo; /** * default constructor */ public AbstractBike() { } private AbstractBike(String internalNumber) { this.internalNumber = internalNumber; } private AbstractBike (String internalNumber, String frameNumber, BikeKey bk, InformationWrapper info) { this.internalNumber = internalNumber; this.frameNumber = frameNumber; this.bikeKey = bk; this.additionalInfo = info; } public BikeKey getBikeKey() { return bikeKey; } public void setBikeKey(BikeKey bikeKey) { this.bikeKey = bikeKey; } /** * @return the number used to identify a bike at kfs */ public String getInternalNumber() { return internalNumber; } /** * @return the frame number as imprinted on the bike by the original manufacturer */ public String getFrameNumber() { return frameNumber; } /** * @return the Wrapper of Information */ public InformationWrapper getAdditionalInfo() { return additionalInfo; } /** * In case of modifications to a Bike (shouldn't be used often) * * @param additionalInfo the new Wrapper for additional Information about a Bike */ public void setAdditionalInfo(InformationWrapper additionalInfo) { this.additionalInfo = additionalInfo; } public Property<String> numberProperty() { return new SimpleStringProperty(this.internalNumber); } public Property<String> frameKeyProperty() { return new SimpleStringProperty(this.bikeKey.getFrameKey()); } public Property<String> bpKeyProperty() { return new SimpleStringProperty(this.bikeKey.getBpKey()); } public Property<String> frameNumberProperty() { return new SimpleStringProperty(this.frameNumber); } public Property<String> brandProperty() { return new SimpleStringProperty(this.additionalInfo.getManufacturer()); } public Property<String> colorProperty() { return new SimpleStringProperty(this.additionalInfo.getColor()); } public Property<Number> tireProperty() { return new SimpleIntegerProperty(this.additionalInfo.getTireDiameter()); } public Property<Number> frameHProperty() { return new SimpleIntegerProperty(this.additionalInfo.getFrameHeigth()); } public Property<String> backPedalProperty() { if(this instanceof EBike) { if(((EBike) this).hasBackPedalBreak()) { return new SimpleStringProperty("Rücktritt"); } else { return new SimpleStringProperty("Freilauf"); } } else { return new SimpleStringProperty(""); } } public Property<String> engineProperty() { if(this instanceof EBike) { return new SimpleStringProperty(((EBike) this).getEngineType().name); } else { return new SimpleStringProperty(""); } } /** * saves a list of bikes into the filesystem * * @param file the file to save to * @param bikes list of bikes to be saved */ public static void save(File file, List<AbstractBike> bikes) { try (DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(file.getPath())))) { out.writeInt(bikes.size()); //lenght first for (AbstractBike ab : bikes) { if (ab instanceof Bike) { //Identifier: simple classname out.writeUTF(Bike.class.getSimpleName()); ((Bike) ab).save(out); } else if (ab instanceof EBike) { out.writeUTF(EBike.class.getSimpleName()); ((EBike) ab).save(out); } } } catch (FileNotFoundException e) { SceneManager.showWarning("File Not Found Exception (save)"); } catch (IOException e) { SceneManager.showSeriousError("IOException (save)"); e.printStackTrace(); } } /** * save the general information for all bikes (no duplication in Bike & E-Bike) * * @param out the outputstream to save to * @param bike to be saved * @throws IOException gets caught where out is created */ public static void save(DataOutputStream out, AbstractBike bike) throws IOException { //Key out.writeUTF(bike.bikeKey.getFrameKey()); out.writeUTF(bike.bikeKey.getBpKey()); //InformationWrapper out.writeUTF(bike.additionalInfo.getManufacturer()); out.writeUTF(bike.additionalInfo.getColor()); out.writeInt(bike.additionalInfo.getTireDiameter()); out.writeInt(bike.additionalInfo.getFrameHeigth()); //General out.writeUTF(bike.internalNumber); out.writeUTF(bike.frameNumber); } /** * @param file the file to load from * @return all Bike & EBikes of that file */ public static List<AbstractBike> load(File file) { AbstractBike[] bikes = null; try(DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file.getPath())))) { //empty file / no list in it --> preventing IOException from being thrown if(in.available() < 4) { return new ArrayList<>(); } bikes = new AbstractBike[in.readInt()]; for(int i = 0; i < bikes.length; i++) { String next = in.readUTF(); if(next.equals(Bike.class.getSimpleName())) { bikes[i] = Bike.load(in); } else if (next.equals(EBike.class.getSimpleName())) { bikes[i] = EBike.load(in); } } } catch (FileNotFoundException e) { SceneManager.showSeriousError("File Not Found Exception (load)"); } catch (IOException e) { SceneManager.showSeriousError("IOException (load)"); } //If for some reason its null if(bikes == null) { bikes = new AbstractBike[0]; } return new ArrayList<>(Arrays.asList(bikes)); } /** * * @param in the inputstream * @return abstract bike to be used further * @throws IOException will be caught where in is created */ public static AbstractBike load(DataInputStream in) throws IOException { BikeKey bk = new BikeKey(in.readUTF(), in.readUTF()); InformationWrapper info = new InformationWrapper(in.readUTF(), in.readUTF(), in.readInt(), in.readInt()); return new AbstractBike(in.readUTF(), in.readUTF(), bk, info) { }; } //Comparison Methods public static AbstractBike createDeleteComparisonBike(String internalNumber) { return new AbstractBike(internalNumber) { }; } /** * Overrides Equals based on the comparison of internalNumbers * @param other the Object to compare to * @return true if other is a bike and they have the same internalNumber */ public boolean equals(Object other) { if(other == null) { return false; } if(other instanceof AbstractBike) { return ((AbstractBike) other).internalNumber.equals(this.internalNumber); } return false; } @Override public int compareTo(AbstractBike other) { return this.internalNumber.compareToIgnoreCase(other.internalNumber); } }
package robustgametools.model; /** * A Platform enum class to represent the type * of platforms the game is on. */ public enum Platform { PS3, PS4, PSVITA; }
package graphs.shortestpath.dag; import graphs.shortestpath.Edge; import graphs.shortestpath.Vertex; import java.util.Collections; import java.util.List; import java.util.Stack; public class TopologicalSort { private Stack<Vertex> stack; public TopologicalSort() { this.stack = new Stack<>(); } public void sort(List<Vertex> graph) { for (Vertex vertex : graph) { if (!vertex.isVisited()) { dfs(vertex); } } } private void dfs(Vertex vertex) { vertex.setVisited(true); for (Edge edge : vertex.getAdjacencies()) { if (!edge.getV().isVisited()) { edge.getV().setVisited(true); dfs(edge.getV()); } } stack.push(vertex); } public Stack<Vertex> getTopologicalOrder() { Collections.reverse(stack); return stack; } }
package com.karlosphp.movies; import javax.faces.bean.ManagedBean; /** * * @author karlosphp */ @ManagedBean(name = "index", eager = true) public class index { public index() { System.out.println("index started@!"); } public String getMessage() { return "Hello World!"; } }
import javax.swing.*; import java.awt.*; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; public class GameWindow { private JFrame frame; private BufferedImage image; private Canvas canvas; private BufferStrategy bs; private Graphics graphics; private double fpsTimer; private int fps; public GameWindow(GameContainer gc) { image = new BufferedImage(gc.getWidth(), gc.getHeight(), BufferedImage.TYPE_INT_RGB); frame = new JFrame(gc.getGameName()); canvas = new Canvas(); Dimension resolution = new Dimension((int) (gc.getWidth()*gc.getScale()), (int) (gc.getHeight()*gc.getScale())); canvas.setPreferredSize(resolution); canvas.setMinimumSize(resolution); canvas.setMaximumSize(resolution); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(canvas, BorderLayout.CENTER); frame.pack(); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); canvas.createBufferStrategy(2); bs = canvas.getBufferStrategy(); graphics = bs.getDrawGraphics(); fpsTimer=System.nanoTime()/1000000000d; } public void update() { fps++; if(((System.nanoTime()/1000000000d)-fpsTimer) > 1d) { System.out.println("FPS : "+fps); fps=0; fpsTimer = System.nanoTime()/1000000000d; } graphics.drawImage(image, 0,0, canvas.getWidth(), canvas.getHeight(), null); bs.show(); } public BufferedImage getImage() { return image; } public Canvas getCanvas() { return canvas; } }
package demoqa; import com.codeborne.selenide.Configuration; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.File; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selectors.byText; import static com.codeborne.selenide.Selenide.*; public class AutomationPracticeFormTests { @BeforeAll static void setup(){ Configuration.startMaximized = true; } @Test void successfulSubmitRegistrationFormTest(){ StudentModel student = new StudentModel( "Jone","Pane","jone@mail.ru", "Male","1234567890", "Sports", "Haryana", "Karnal","english","RnD"); open("https://demoqa.com/automation-practice-form"); $("#firstName").setValue(student.firstName); $("#lastName").setValue(student.lastName); $("#userEmail").setValue(student.email); $(byText(student.gendermale)).click(); $("#userNumber").setValue(student.mobile); $("#dateOfBirthInput").click(); $(".react-datepicker__month-select").selectOption(2); $(".react-datepicker__year-select").selectOption("2000"); $("[aria-label='Choose Tuesday, March 28th, 2000']").click(); $("#subjectsInput").setValue("e"); $("#react-select-2-option-0").click(); $(byText(student.hobbies)).click(); $("#uploadPicture").uploadFile(new File("src/test/resources/load.txt")); $("#currentAddress").setValue(student.currentaddress); $("#state").click(); $(byText(student.state)).click(); $("#city").click(); $(byText(student.city)).click(); $("#submit").click(); $(".table-responsive").shouldHave(text(student.firstName), text(student.lastName), text(student.email), text(student.gendermale), text(student.mobile), text("28 March,2000"), text(student.subjects), text(student.hobbies), text("load.txt"), text(student.currentaddress), text(student.state), text(student.city)); } }
package com.MouseOperations; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class Amazon_HelloSignIn_MouseHover { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe"); WebDriver driver = null; driver=new ChromeDriver(); String url="https://www.amazon.in/"; driver.get(url); driver.manage().window().maximize(); WebElement helloSignIn=driver.findElement(By.id("nav-link-yourAccount")); Actions act=new Actions(driver); act.moveToElement(helloSignIn).perform();; driver.findElement(By.linkText("Your Orders")).click(); driver.close(); } }
package com.game.chess.console.security; import com.game.chess.console.service.CustomUserDetailsService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j @Component public class JwtAuthenticationFilter extends OncePerRequestFilter { @Value("${app.jwt.header}") private String tokenRequestHeader; @Value("${app.jwt.header.prefix}") private String tokenRequestHeaderPrefix; private JwtTokenProvider jwtTokenProvider; private CustomUserDetailsService customUserDetailsService; public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, CustomUserDetailsService customUserDetailsService) { this.jwtTokenProvider = jwtTokenProvider; this.customUserDetailsService = customUserDetailsService; } /** * Filter the incoming request for a valid token in the request header */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)) { String email = jwtTokenProvider.getUserIdFromJWT(jwt); UserDetails userDetails = customUserDetailsService.loadUserByUsername(email); UsernamePasswordAuthenticationToken authentication = getAuthentication(request, userDetails); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(request, response); } private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request, UserDetails userDetails) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); return authentication; } /** * Extract the token from the Authorization request header */ private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader(tokenRequestHeader); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(tokenRequestHeaderPrefix)) { LOG.info("Extracted Token: {}", bearerToken); return bearerToken.replace(tokenRequestHeaderPrefix, "").trim(); } return null; } }
package usc.cs310.ProEvento.model.requestbody; public class ChangePasswordRequestBody { public long accountId; public String currentPassword; public String newPassword; }
package observer2; public class NewsSubscriber implements NewsObserver { private String name; private SubjectObservable subscribedTo; public NewsSubscriber(String name) { this.name = name; } @Override public void create() { if(this.subscribedTo == null) { System.out.println(this.getName() + " has no news set "); return; } String newNews = this.subscribedTo.getCreate(); System.out.println(this.getName() + " created: " + newNews); } @Override public void setNews(SubjectObservable news) { this.subscribedTo = news; } public String getName() { return name; } }
package operations; import java.time.LocalDateTime; import org.junit.Test; import utilities.SSExcelUtils; public class CalcTestDDT { String excelFilePath="./src/test/resources/testData/Calculator.xlsx"; @Test public void CalculatorTest(){ SSExcelUtils.openExcelFile(excelFilePath, "Sheet1"); int rowNums=SSExcelUtils.getUsedRowsCount(); System.out.println("The row numbers are: " +rowNums); for(int i=1; i<rowNums; i++){ String executionFlag=SSExcelUtils.getCellData(i, 0); String operation=SSExcelUtils.getCellData(i, 1); String number1=SSExcelUtils.getCellData(i,2); double num1=Double.parseDouble(number1); String number2=SSExcelUtils.getCellData(i, 3); double num2=Double.parseDouble(number2); if(executionFlag.contains("Y")){ double result= Calculator.Operate(operation, num1, num2); String value=String.valueOf(result); SSExcelUtils.setCellData(value, i, 5); }else{ SSExcelUtils.setCellData("Skipped", i, 5); } if(SSExcelUtils.getCellData(i, 4).equals(SSExcelUtils.getCellData(i, 5))){ SSExcelUtils.setCellData("Passed", i, 6); }else{ SSExcelUtils.setCellData("Failed", i, 6); } String now=LocalDateTime.now().toString(); SSExcelUtils.setCellData(now, i, 7); } } }
package application; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Scanner; import entities.ImportedProduct; import entities.Product; import entities.UserdProduct; public class Program { public static void main(String[] args) { // i == Import // c == product // u == usedProduct, Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); SimpleDateFormat sdf = new SimpleDateFormat("(DD/MM/YYYY"); List<Product> list = new ArrayList<>(); System.out.println("Enter the number of products: "); int n = sc.nextInt(); for(int i = 1 ; i <= n ; i ++){ System.out.println("Product # "+ i + "data:"); System.out.println("Common, used or imported (c/u/i)?"); char res = sc.next().charAt(0); System.out.println("Name:"); String name = sc.next(); System.out.println("Price:"); double price = sc.nextDouble(); if(res == 'i'){ System.out.println("Customs fee:"); double customsFree = sc.nextDouble(); ImportedProduct imp = new ImportedProduct(name, price, customsFree); list.add(imp); } else if (res == 'c'){ Product pd = new Product(name, price); list.add(pd); } else if (res == 'u'){ System.out.println("Manufacture date (DD/MM/YYYY):"); //UserdProduct up = new UserdProduct(name, price, sdf); }else{ System.out.println("erro"); } } System.out.println("PRICE TAGS:"); for(Product pd : list){ System.out.println(pd.getName() + " $ " + pd.getPrice() + pd.priceTag()); } sc.close(); } }
package Kong; public class Student { /*Dillon Kong * 31/10/16 * Class that holds getters and setters */ public static long studentNumberConstant = 324000000;// Base starting student number private String firstName, lastName, streetAddress, city, postalCode, birthDate, phoneNumber; enumProvince province; private long studentNumber = studentNumberConstant; /** * Construct for if no information is inputed. Sets all variables to blank * @throws InvalidInputException */ public Student() throws InvalidInputException { try { setBirthday(""); } catch (InvalidInputException e) { } setCity(""); setFirstName(""); setLastName(""); setNumber(""); try { setPostalCode(""); } catch (InvalidInputException e) { } setProvince(enumProvince.NONE); setAddress(""); setStudentNumber (++studentNumber); } /** * Construct for if all the variables are filled * @param firstName * @param lastName * @param birthDate * @param city * @param phoneNumber * @param postalCode * @param province * @param streetAddress * @throws InvalidInputException */ public Student(String firstName, String lastName, String birthDate, String city, String phoneNumber, String postalCode, enumProvince province, String streetAddress) throws InvalidInputException { try{ setBirthday(birthDate); setFirstName(firstName); setLastName(lastName); setCity(city); setProvince(province); setNumber(phoneNumber); setPostalCode(postalCode); setAddress(streetAddress); } catch (InvalidInputException e) { } setStudentNumber (++studentNumber); } //////////////////////////////////////////////////////////Setters and Getters//////////////////////////////////// /** * Method is called to set the student number * @param studentNmbr */ public void setStudentNumber (long studentNmbr) { if (SchoolSystem.getLastStudentNumber() > studentNumberConstant) { studentNmbr = SchoolSystem.getLastStudentNumber() + 1; } else { studentNumber = studentNumberConstant ++; } this.studentNumber = studentNmbr; } /** * Method is called to return student number is needed * @return */ public long getStudentNumber () { return studentNumber; } /** * Method is called to set first name if its correct * @param fName */ public void setFirstName (String fName){ this.firstName = fName; } /** * Method is called to return first name is needed * @return */ public String getFirstName (){ return this.firstName; } /** * Method is called to set last name if its correct * @param lName */ public void setLastName (String lName){ this.lastName = lName; } /** * Method is called to return last name is needed * @return */ public String getLastName (){ return this.lastName; } /** * Method is called to set street address if its correct * @param address */ public void setAddress (String address) { this.streetAddress = address; } /** * Method is called to return street address is needed * @return */ public String getAddress (){ return this.streetAddress; } /** * Method is called to set city if its correct * @param cName */ public void setCity (String cName){ this.city = cName; } /** * Method is called to return city is needed * @return */ public String getCity (){ return this.city; } /** * Method is called to set province if its correct * @param pName */ public void setProvince (enumProvince pName){ this.province = pName; } /** * Method is called to return province is needed * @return */ public enumProvince getProvince (){ return this.province; } /** * Method is called to set postal code if its correct * @param pCode * @throws InvalidInputException */ public void setPostalCode (String pCode)throws InvalidInputException { this.postalCode = pCode; } /** * Method is called to return postal code if needed * @return */ public String getPostalCode (){ return this.postalCode; } /** * Method is called to set phone number if its correct * @param phoneNum */ public void setNumber (String phoneNum){ this.phoneNumber = phoneNum; } /** * Method is called to return phone number if needed * @return */ public String getNumber () { return this.phoneNumber; } /** * Method is called to set birthday if its correct * @param bDay * @throws InvalidInputException */ public void setBirthday (String bDay) throws InvalidInputException { this.birthDate = bDay; } /** * Method is called to return birthday if needed * @return */ public String getBirthday (){ return this.birthDate; } ////////////////////////////////////////////////////trySet methods//////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Method is called to make sure Street Address is correct * @param address * @return */ public static Boolean trySetAddress(String address) { char [] charStrNum = address.split(" ") [0].toCharArray(); for (int i = 0; i < charStrNum.length; i ++) { if (!Character.isDigit(charStrNum[i])) { return false; } } return true; } /** * Method is called to make sure postal code is correct * @param pCode * @return */ public static Boolean trySetPostalCode (String pCode) { if (pCode.length() == 6) { if (!Character.isLetter(pCode.charAt(0))) { if (!Character.isLetter(pCode.charAt(2))) { if (!Character.isLetter(pCode.charAt(4))) { return false; } }//M6R1J2 } if (!Character.isDigit(pCode.charAt(1))) { if (!Character.isDigit(pCode.charAt(3))) { if (!Character.isDigit(pCode.charAt(5))) { return false; } }//M6R 1J2 } } else if (pCode.length() == 7) { if (!Character.isLetter(pCode.charAt(0))) { if (!Character.isLetter(pCode.charAt(2))) { if (!Character.isLetter(pCode.charAt(5))) { return false; } }//M6R1J2 } if (!Character.isDigit(pCode.charAt(1))) { if (!Character.isDigit(pCode.charAt(4))) { if (!Character.isDigit(pCode.charAt(6))) { return false; } } } } return true; } /** * Method is called to make sure phone number is correct * @param phoneNum * @return */ public static Boolean trySetNumber (String phoneNum) { char [] charPhoneNumber = phoneNum.split("-") [0].toCharArray(); if (! Character.isDigit(charPhoneNumber[0]) && Character.isDigit(charPhoneNumber[1]) && Character.isDigit(charPhoneNumber[2]) && charPhoneNumber.length > 12) { return false; } return true; } /** * Method is called to make sure birthday is correct * @param bDay * @return */ public static Boolean trySetBirthday (String bDay) { char [] charBDay= bDay.split("/")[0].toCharArray(); if (! Character.isDigit(charBDay [0]) && Character.isDigit(charBDay [1]) && Character.isDigit(charBDay[2])) { return false; } return true; } /** * Method is called to make sure province is correct * @param province * @return * @throws InvalidInputException */ public static Boolean trySetProvince (enumProvince province) throws InvalidInputException { //http://www.comeexplorecanada.com/abbreviations.php try{ if (province.equals(enumProvince.ALBERTA) || province.equals(enumProvince.BRITISHCOMUMBIA) || province.equals(enumProvince.MANITOBA) || province.equals(enumProvince.NEWBRUNSWICK) || province.equals(enumProvince.NEWFOUNDLANDANDLABRADOR) || province.equals(enumProvince.NORTHWESTTERRITORIES) || province.equals(enumProvince.NOVASCOTIA) || province.equals(enumProvince.NUNAVUT) || province.equals(enumProvince.ONTARIO) || province.equals(enumProvince.PRINCEEDWARDISLAND) || province.equals(enumProvince.QUEBEC) || province.equals(enumProvince.SASKATCHEWAN) || province.equals(enumProvince.YUKON)) { return true; } }catch (NullPointerException e) { } return false; } /** * Method is called to make sure first name is correct * @param fName * @return */ public static Boolean trySetFirstName (String fName) { char[] charFName = fName.toCharArray(); if (!Character.isLetter(charFName [0] )) { return false; } return true; } /** * Method is called to make sure last name is correct * @param lName * @return */ public static Boolean trySetLastName (String lName) { char [] charLName = lName.toCharArray(); if (! Character.isLetter(charLName[0])) { return false; } return true; } /** * Method is called to make sure city is correct */ public static Boolean trySetCity (String cName) { char [] charCName = cName.toCharArray(); if (! Character.isLetter(charCName[0])) { return false; } return true; } /////////////////////////////////////////////////////Other////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Puts all student information into a single line */ public String toString() { return firstName + " || " + lastName + " || " + streetAddress + " || " + city + " || " + province + " || " + postalCode + " || " + birthDate + " || " + phoneNumber; } /** * Makes sure the temp student equals the actual student * @param tempStudent * @return */ public boolean equals(Student tempStudent) { return (this.getStudentNumber() == tempStudent.getStudentNumber()); } /** * Compares first and last name for the student and the temp student * @param student * @return */ public int compareTo(Student student) { Student tempStudent = (Student) student; if (this.getLastName().compareToIgnoreCase(tempStudent.getLastName()) == 0) { if (this.getFirstName().compareToIgnoreCase(tempStudent.getFirstName()) == 0) { return 0; } else if (this.getFirstName().compareToIgnoreCase(tempStudent.getFirstName()) > 0) { return 1; } else { return -1; } } else if (this.getLastName().compareToIgnoreCase(tempStudent.getLastName()) > 0) { return 1; } else { return -1; } } }
package cases; import org.testng.annotations.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; public class SwapiCo { @Test() public void main() throws Throwable { given().when().get("https://swapi.co/api/people/").then() .body("count", equalTo(87)) .body("results[0].name", equalTo("Luke Skywalker")) .body("results[1].name", equalTo("C-3PO")) .body("results[2].name", equalTo("R2-D2")); } }
/* * hashmap is sorted. (sorted by hashcode() and equals()) * linkedhashmap is ordered.(perserving inserting order) * treeMap is sorted by comparing(comparable or comparator) */ package CollectionFun.Map; import java.util.Map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.TreeMap; /** * * @author YNZ */ public class MapNoOrder { public static void main(String[] args) { //HashMap has no order Map<String, Double> salaryMap = new HashMap<>(); salaryMap.put("Paul", 32222.88); salaryMap.put("Smith", 43333.98); salaryMap.put("Chris", 45556.98); salaryMap.put("Paul", 32222.88); System.out.println(salaryMap); //LinkedHashMap is a Map<String, Double> salaryMap1 = new LinkedHashMap<>(); salaryMap1.put("Paul", 32222.88); salaryMap1.put("Smith", 43333.98); salaryMap1.put("Chris", 45556.98); System.out.println(salaryMap1); //TreeMap is sorted by its natural sequence. Map<String, Double> salaryMap2 = new TreeMap<>(); salaryMap2.put("Paul", 32222.88); salaryMap2.put("Smith", 43333.98); salaryMap2.put("Chris", 45556.98); salaryMap2.put("Paul", 32222.88); System.out.println(salaryMap2); for (Entry<String, Double> e : salaryMap2.entrySet()) { if (e.getKey().equals("Paul")) { System.out.println(e.getKey() + " " + e.getValue()); } } } }
import java.io.*; import java.util.*; class median { public static void main(String[] args) { Scanner kb = new Scanner(System.in); int n=kb.nextInt(); int arr[]=new int[n]; if(n>0&&n<=1000) { for(int i=0;i<n;i++) { arr[i]=kb.nextInt(); } for(int j=0;j<n;j++) { for(int k=0;k<n-1;k++) { if(arr[k]>arr[k+1]) { int temp=arr[k]; arr[k]=arr[k+1]; arr[k+1]=temp; } } } System.out.println(arr[n/2]); } } }
package in.jaaga.thebachaoproject; import android.app.Activity; import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class SearchActivity extends Activity { private EditText edit_text_search_box; //private ListView suggestions; HttpURLConnection connection; searchLocationThread thread=null; List<String> items; List<String> center; TextWatcher textWatcher; ProgressBar progressBar; ArrayAdapter<String> adapter; SearchSuggestionsFragment suggestionsFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); items=new ArrayList<>(); center=new ArrayList<>(); //items.add("test"); // SearchSuggestionsFragment.newInstance("a","b"); suggestionsFragment=new SearchSuggestionsFragment(); // setContentView(R.layout.activity_search); /* adapter = new ArrayAdapter<String>(this, R.layout.search_list_item, items);*/ // setListAdapter(adapter); // Get the intent, verify the action and get the query Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); try { searchLocation(query); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } /* textWatcher=new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show(); //String search_query= (String) s; try { searchLocation(s); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void afterTextChanged(Editable s) { if(s.length()==0 || s.length()==-1){ items.clear(); center.clear(); adapter.clear(); adapter.notifyDataSetChanged(); } } };*/ } public void searchLocation(String location) throws ExecutionException, InterruptedException { //String searchLocation=location; // progressBar.setVisibility(View.VISIBLE); // ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter(); thread=new searchLocationThread(); do{System.out.println("running");}while (thread.getStatus().equals(AsyncTask.Status.RUNNING)); //List<String> result= thread.execute(location); // adapter.clear(); /* suggestionsFragment.updateData(result);*/ /*adapter.addAll(result); adapter.notifyDataSetChanged();*/ } /* @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); //mListener.onFragmentInteraction(center.get(position)); }*/ private class searchLocationThread extends AsyncTask<String,Void,List<String>>{ @Override protected List<String> doInBackground(String... params) { HttpClient httpClient = new DefaultHttpClient(); String[] locationarray= params; String location=locationarray[0]; String url="http://nominatim.openstreetmap.org/search?q="+ URLEncoder.encode(location)+"&format=json&addressdetails=1"; HttpResponse response = null; try { HttpGet getMethod = new HttpGet(url); response = httpClient.execute(getMethod); String result = EntityUtils.toString(response.getEntity()); JSONArray jsonArray=new JSONArray(result); System.out.println("Length of JsonArray:"+jsonArray.length()); items.clear(); for(int i=0;i<jsonArray.length();i++) { items.add(jsonArray.getJSONObject(i).getString("display_name")); center.add(jsonArray.getJSONObject(i).getString("boundingbox")); } // suggestionsFragment.updateData(items); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return items; } @Override protected void onPostExecute(List<String> list) { super.onPostExecute(list); // progressBar.setVisibility(View.INVISIBLE); } } }
package worker; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Worker { public Map<Integer, Topic> topics; public List<Topic> topicList; public int id; public String name; public Worker(Map<Integer, Topic> topics, int id) { this.topics = topics; this.id = id; this.topicList = new ArrayList<Topic>(); for (int i = 0; i < topics.size(); i++) { this.topicList.add(topics.get(i)); } } }
package chen.shu.hex_empire_v1; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Map extends GameObject { private List<ArrayList<Hex>> grid; private Hex selectedHex; private int DIA = 10; //Game.HEIGHT / 15; private int RAD = detRad(); private int seed; private int[] sij; private int[] vel; private Rectangle box; public Map(int x, int y, int is, int js, Rectangle box, int seed) { this.box = box; this.seed = seed; id = Id.MAP; vel = new int[2]; vel[0] = 0; vel[1] = 0; xy = new int[2]; xy[0] = box.x; xy[1] = box.y; sij = new int[2]; sij[0] = is; sij[1] = js; grid = new ArrayList<ArrayList<Hex>>(); Id[][] idGrid = idGen(); for (int i = 0; i < is; i++) { grid.add(new ArrayList<Hex>()); for (int j = 0; j < js; j++) { grid.get(i).add(new Hex(i, j, idGrid[i][j], this)); } } } private Id[][] idGen() { int i = getI(); int j = getJ(); Random r = new Random(getSeed()); // initialize: Id[][] idGrid = new Id[i][j]; for (int x = 0; x < i; x++) { for (int y = 0; y < j; y++) { if (r.nextBoolean()) {idGrid[x][y] = Id.HEX_RUR;} else {idGrid[x][y] = Id.HEX_SEA;} }} Id[] neighs; double z; // modify: int iterate = (int) (2 * Math.sqrt(Math.pow(Game.WIDTH, 2) + Math.pow(Game.HEIGHT, 2))); double str = 0.4; // high = land double rts = 0.4; // high = sea double rtc = 0.5; // high = city double ptr = 0.5; // high = port // land, sea proportion for (int n = 0; n < iterate; n++) { for (int x = 0; x < i; x++) { for (int y = 0; y < j; y++) { neighs = checkNeigh(x, y, idGrid); int seas = getNumNeigh(neighs, Id.HEX_SEA); int rurs = getNumNeigh(neighs, Id.HEX_RUR); z = r.nextDouble(); // sea to rural // high = land if (idGrid[x][y] == Id.HEX_SEA) { if (z <= str * rurs / 6.0) { idGrid[x][y] = Id.HEX_RUR; }} // rural to sea // high = sea else if (idGrid[x][y] == Id.HEX_RUR) { if (z <= rts * seas / 6.0) { idGrid[x][y] = Id.HEX_SEA; }} }} } // scatter cities for (int x = 0; x < i; x++) { for (int y = 0; y < j; y++) { if (idGrid[x][y] == Id.HEX_RUR) { if (r.nextDouble() <= rtc * 0.3) { idGrid[x][y] = Id.HEX_CIT; }} }} // apply placement policy for (int x = 0; x < i; x++) { for (int y = 0; y < j; y++) { neighs = checkNeigh(x, y, idGrid); int seas = getNumNeigh(neighs, Id.HEX_SEA); int cits = getNumNeigh(neighs, Id.HEX_CIT); int pors = getNumNeigh(neighs, Id.HEX_POR); z = r.nextDouble(); // convert cities to ports if (idGrid[x][y] == Id.HEX_CIT) { if (seas > 0) { idGrid[x][y] = Id.HEX_POR; }} // remove cities if (idGrid[x][y] == Id.HEX_CIT) { if (cits > 0) { idGrid[x][y] = Id.HEX_RUR; }} // reduce ports if (idGrid[x][y] == Id.HEX_POR) { if (z >= (ptr * (9 - 2 * pors) + 1) / 10.0) { idGrid[x][y] = Id.HEX_RUR; }} }} // add capitals return idGrid; } private Id[] checkNeigh(int i, int j, Id[][] idGrid) { Id[] n = new Id[6]; n[0] = getHexId(i-1, j, idGrid); n[3] = getHexId(i+1, j, idGrid); // even, odd if (j / 2 == j / 2.0) { n[1] = getHexId(i-1, j-1, idGrid); n[2] = getHexId(i, j-1, idGrid); n[4] = getHexId(i, j+1, idGrid); n[5] = getHexId(i-1, j+1, idGrid); } else { n[1] = getHexId(i, j-1, idGrid); n[2] = getHexId(i+1, j-1, idGrid); n[4] = getHexId(i+1, j+1, idGrid); n[5] = getHexId(i, j+1, idGrid); } return n; } private int getNumNeigh(Id[] neighs, Id id) { int n = 0; for (Id m: neighs) { if (m == null) {} else if (m == id) {n++;} } return n; } public void tick() { moveX(vel[0]); moveY(vel[1]); for (int i = 0; i < sij[0]; i++) { for (int j = 0; j < sij[1]; j++) { grid.get(i).get(j).tick(); } } } public void render(Graphics g) { // hex for (int i = 0; i < sij[0]; i++) { for (int j = 0; j < sij[1]; j++) { grid.get(i).get(j).render(g); }} /*/ bounds Rectangle r = getBounds(); g.drawRect(r.x, r.y, r.width, r.height); //*/ // box Game.drawMask(g, box, Color.BLACK); Rectangle b = getBox(); g.setColor(Color.WHITE); g.drawRect(b.x, b.y, b.width, b.height); } public void click(Hex hex) { if (selectedHex == null) {selectedHex = hex;} else {selectedHex = null;} } public void setVelX(int velX) { vel[0] = velX; } public void setVelY(int velY) { vel[1] = velY; } public void moveX(int dx) { xy[0] += dx; int boxM = getBox().x + getBox().width / 2; if (xy[0] >= boxM) { xy[0] = boxM - getBounds().width; } else if (xy[0]+getBounds().width < boxM) { xy[0] = boxM; } } public void moveY(int dy) { double y0 = xy[1] + dy; double y1 = y0 + getBounds().getHeight(); double b0 = box.y; double b1 = b0 + box.getHeight(); boolean topGood = y0 < b0; boolean botGood = y1 > b1; if (topGood && botGood) { xy[1] = (int) y0; } else if (!topGood && !botGood) { xy[1] = (int) ((b0 + b1 - getBounds().height) / 2); } else if (!topGood && botGood) { xy[1] = (int) b0; } else if (topGood && !botGood) { xy[1] = (int) (b1 - getBounds().getHeight()); } } public void addDia(int n) { DIA += n; RAD = detRad(); } private int detRad() { return DIA * 9 / 20; } public List<ArrayList<Hex>> getMap() { return grid; } public int getSeed() { return seed; } public int getI() { return sij[0]; } public int getJ() { return sij[1]; } public Id getHexId(int i, int j, Id[][] idGrid) { int si = getI(); int sj = getJ(); if (0 > j || j >= sj) { return null; } else if (i == -1) { return idGrid[si-1][j]; } else if (i == si) { return idGrid[0][j]; } return idGrid[i][j]; } public Rectangle getBounds() { int i = (int) (DIA * Math.sqrt(3) * (sij[0] + 0.5) / 2); double n = 1; if (sij[1] / 2 == sij[1] / 2.0) n = 0.5; int j = (int) (DIA * (3 * sij[1] / 2 + n) / 2); return new Rectangle(xy[0], xy[1], i, j); } public Rectangle getBox() { return box; } public int getDia() { return DIA; } public int getRad() { return RAD; } public Hex getSelected() { return selectedHex; } }
package lab3; public class Vanilla extends Dessert{ public static final double COST = 1.25; public Vanilla() { description ="Vanilla"; } @Override public double cost() { // TODO Auto-generated method stub return COST; } }
package Controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping(value = "/") public String test() { System.out.println("/index"); return "index"; } @RequestMapping(value = "/test") public String test2() { System.out.println("/test"); return "test"; } @RequestMapping(value = "/center1") public String center1() { System.out.println("/center1"); return "center1"; } @RequestMapping(value = "/center2") public String center2() { System.out.println("/center2"); return "center2"; } }
package factorial; import java.util.Scanner; public class factorial { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a number that you want to find the factorial of:"); int intFac = input.nextInt(); System.out.println("You have entered: "+intFac); long finalAnswer = 1; //initialized the memory for the final answer System.out.print("To calculate the answer your self multiply these: "); for(int i = intFac; i >=1; --i){ System.out.print(i+ " * ");//calculates the final answer finalAnswer = i * finalAnswer; } if(finalAnswer <= 0 ) { //checks for overflow System.out.println(""); System.out.println("Sorry the value is too large"); }else { //outputs the final answer System.out.println(""); System.out.println("Final answer is: "+ finalAnswer); } } }
package com.davivienda.multifuncional.tablas.logcajeromulti.session; import com.davivienda.sara.base.AdministracionTablasInterface; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import com.davivienda.sara.entitys.Logcajeromulti; import java.util.Collection; import java.util.Date; import java.util.Map; import javax.ejb.Local; /** * TxMultifuncionalChequeSessionLocal * Descripción : * Versión : 1.0 * * @author P-MDRUIZ * Davivienda 2011 */ @Local public interface LogCajeroMultiSessionLocal extends AdministracionTablasInterface<Logcajeromulti> { /** * Retorna un objeto Logcajeromulti que cumpla con los parámetros * @param codigoCajero * @param fecha * @return Logcajeromulti * @throws EntityServicioExcepcion */ public Collection<Logcajeromulti> getColeccionLogCajeroMulti(Integer codigoCajero, Date fecha) throws EntityServicioExcepcion; }
/* $Id$ */ package utils; import java.io.File; import java.util.Arrays; import org.apache.log4j.Logger; import utils.FileTools; import djudge.judge.CheckParams; import djudge.judge.Judge; import djudge.judge.ProblemDescription; import djudge.judge.SubmissionResult; public class JudgeDirectory { private static final Logger log = Logger.getLogger(JudgeDirectory.class); ProblemDescription desc; public JudgeDirectory(ProblemDescription desc) { this.desc = desc; } public DirectoryResult judge(String directory) { log.info("Judging directory: " + directory + " started"); DirectoryResult res = new DirectoryResult(directory); File f = new File(directory); File[] files = f.listFiles(); Arrays.sort(files); for (int i = 0; i < files.length; i++) if (!files[i].isDirectory()) if (files[i].getName().charAt(0) != '_') { log.info("Judging file: " + files[i].getName() + " started"); SubmissionResult sr = Judge.judgeSourceFile(FileTools .getAbsolutePath(files[i].getAbsolutePath()), "%AUTO%", desc, new CheckParams()); log.info("Judging file: " + files[i].getName() + " finished"); res.setProblemResult(i, sr); log.info("Judging file: " + files[i].getName() + " finished"); } log.info("Judging directory: " + directory + " finished"); return res; } }
package exam4; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadPoolEx9 { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService threadPool = Executors.newFixedThreadPool(10); Future<String> t1 = threadPool.submit(new WaitTask(5000)); Future<String> t2 = threadPool.submit(new WaitTask(3000)); Future<String> t3 = threadPool.submit(new WaitTask(1000)); // 5초간 쉬는애가 끝나야 나머지도 다 나오게 끔 구현한거임! 기다림! System.out.println(t1.get()); System.out.println(t2.get()); System.out.println(t3.get()); // 모든 작업이 종료하면 셧다운 threadPool.shutdown(); } } class WaitTask implements Callable<String> { private long time; public WaitTask(long time) { this.time = time; } @Override public String call() throws Exception { Thread.sleep(this.time); return time + "밀리초 대기후에 리턴함"; } }
package org.isc.certanalysis.service.bean.dto; import org.isc.certanalysis.domain.Scheme; import java.util.*; /** * @author p.dzeviarylin */ public class SchemeDTO { private Long id; private String name; private String comment; private Scheme.Type type; private Long sort; private Order order = Order.END; private Set<CrlUrlDTO> crlUrls = new HashSet<>(); private Collection<CertificateDTO> certificates = new TreeSet<>(); private Set<Long> notificationGroupIds = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Scheme.Type getType() { return type; } public void setType(Scheme.Type type) { this.type = type; } public Set<CrlUrlDTO> getCrlUrls() { return crlUrls; } public void setCrlUrls(Set<CrlUrlDTO> crlUrls) { this.crlUrls = crlUrls; } public Collection<CertificateDTO> getCertificates() { return certificates; } public void setCertificates(Collection<CertificateDTO> certificates) { this.certificates = certificates; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public Long getSort() { return sort; } public void setSort(Long sort) { this.sort = sort; } public Set<Long> getNotificationGroupIds() { return notificationGroupIds; } public void setNotificationGroupIds(Set<Long> notificationGroupIds) { this.notificationGroupIds = notificationGroupIds; } public enum Order { BEGIN, END } }
package com.kyo.homework.data.source; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import com.kyo.homework.data.CommentEntity; import com.kyo.homework.data.MomentEntity; import com.kyo.homework.data.UserEntity; import com.kyo.homework.data.source.remote.HomeworkRetrofit; import com.kyo.homework.data.source.remote.service.MomentsService; import com.kyo.homework.util.EspressoIdlingResource; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.RunnableFuture; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by jianghui on 2017/11/29. */ public class MomentsRepository implements MomentsDataSource { private static String USER = "jsmith"; private static MomentsRepository momentsRepository = null; private List<MomentEntity> cachedMoments = null; @Override public void getUserInfo(final LoadUserCallback callback) { EspressoIdlingResource.increment(); HomeworkRetrofit.build().create(MomentsService.class) .getUserInfo(USER) .enqueue(new Callback<UserEntity>() { @Override public void onResponse(Call<UserEntity> call, Response<UserEntity> response) { callback.onUserInfoLoaded(response.body()); EspressoIdlingResource.decrement(); } @Override public void onFailure(Call<UserEntity> call, Throwable t) { callback.onFailure(t); EspressoIdlingResource.decrement(); } }); } @Override public void getMoments(final int start, final int size, final LoadMomentsCallback callback) { EspressoIdlingResource.increment(); if (cachedMoments != null) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { List<MomentEntity> momentEntities = new ArrayList<>(size); for (int i = start; i < cachedMoments.size() && (i - start) < size; i++) { momentEntities.add(cachedMoments.get(i)); } callback.onMomentsLoaded(momentEntities); EspressoIdlingResource.decrement(); } }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); } else { HomeworkRetrofit.build().create(MomentsService.class) .getMoments(USER) .enqueue(new Callback<List<MomentEntity>>() { @Override public void onResponse(Call<List<MomentEntity>> call, Response<List<MomentEntity>> response) { List<MomentEntity> momentEntities = response.body(); if (momentEntities != null) { cachedMoments = momentEntities; momentEntities = new ArrayList<>(size); for (int i = start; i < cachedMoments.size() && (i - start) < size; i++) { momentEntities.add(cachedMoments.get(i)); } callback.onMomentsLoaded(momentEntities); } else { callback.onMomentsLoaded(null); } EspressoIdlingResource.decrement(); } @Override public void onFailure(Call<List<MomentEntity>> call, Throwable t) { callback.onFailure(t); EspressoIdlingResource.decrement(); } }); } } }
package edu.unm.cs.blites.co_lect; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.GraphResponse; import com.parse.LogInCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseFacebookUtils; import com.parse.ParseUser; import com.facebook.GraphRequest; import org.json.JSONObject; import java.util.Arrays; import java.util.List; public class LoginActivity extends ActionBarActivity { private final String APP_ID = "FjVl4ZzEsV0gP6QU416sV9FaBlIlKNG2vKUuNX9N"; private final String CLIENT_KEY = "N2K7lD281zrUmm8sydx595tGmQIqeCqk0AZ8lMz9"; private String username = null; private String id = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeParse(this, APP_ID, CLIENT_KEY); setContentView(R.layout.activity_login); String[] perms = {"public_profile", "email", "user_friends"}; List<String> permissions = Arrays.asList(perms); logIntoFacebook(this, permissions); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ParseFacebookUtils.onActivityResult(requestCode, resultCode, data); } /** * * @param context * @param appId * @param clientKey */ private void initializeParse(Context context, String appId, String clientKey) { // Enable Local Datastore. Parse.enableLocalDatastore(context); Parse.initialize(context, appId, clientKey); ParseFacebookUtils.initialize(getApplicationContext()); } /** * * @param activity * @param permissions */ private void logIntoFacebook(final Activity activity, List<String> permissions) { LogInCallback mLoginCallback = new LogInCallback() { @Override public void done(ParseUser parseUser, ParseException e) { if (parseUser == null) Log.e("LoginActivity", "Something went wrong with the login"); else if (parseUser.isNew()) Log.i("LoginActivity", "User signed up and logged in through Facebook"); else { Log.d("LoginActivity", "User logged in through Facebook!"); fetchUserInfo(activity); activity.finish(); } } }; ParseFacebookUtils.logInWithReadPermissionsInBackground(activity, permissions, mLoginCallback); } /** * * @param context */ private void fetchUserInfo(Context context) { GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) { if(jsonObject != null) { username = jsonObject.optString("name"); id = jsonObject.optString("id"); Intent intent = new Intent(); Bundle userInfo = new Bundle(); userInfo.putString("name", username); userInfo.putString("id", id); intent.putExtras(userInfo); intent.setClass(getApplicationContext(), MainActivity.class); startActivity(intent); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name"); request.setParameters(parameters); request.executeAsync(); } }
package main.java.ca.jrvs.challenges; import java.util.*; public class main { public static int fibIterative(int n){ if (n < 2) return n; int first = 0, second = 1, next = 1; for (int i=2; i < n; i++){ next = first + second; first = second; second = next; } return next; } public static int[] fibSeqDynamicProgramming(int n) { int[] fibArr = new int[n]; fibArr[0] = 1; fibArr[1] = 1; if (n < 2){ return fibArr; } for (int i = 2; i < n; i++) { fibArr[i] = fibArr[i-1] + fibArr[i-2]; } return fibArr; } public static int fibRecursive(int n){ if (n <= 1){ return n; } return fibRecursive(n - 1) + fibRecursive(n - 2); } public static char[] dupChar(String s){ Set<Character> chars = new HashSet<>(); String dups = ""; for (char c : s.toCharArray()){ if (chars.contains(c)){ dups += c; chars.remove(c); } else { chars.add(c); } } System.out.println(dups); return dups.toCharArray(); } public static String reverseString(String input){ String[] strings = input.split("\\s"); int i=0, j = strings.length - 1; while(i < j) { String tmp = strings[i]; strings[i] = strings[j]; strings[j] = tmp; i++; j--; } return String.join(" ", strings); } public static boolean validPalindrome(String isPalindrome) { String string = isPalindrome.toLowerCase().replaceAll("[^a-z0-9]", ""); int length = string.length(); for (int i = 0; i < length / 2; i++) { if (string.charAt(i) != string.charAt(length - i - 1)) { return false; } } return true; } public static boolean isPalindrome(String input){ String s = input.replaceAll("[^A-Za-z0-9]",""); int i = 0, j = s.length() - 1; while (i < j) { if (s.charAt(i++) != s.charAt(j--)) { return false; } } return true; } public static boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } char[] sArr = s.toCharArray(); char[] tArr = t.toCharArray(); Arrays.sort(sArr); Arrays.sort(tArr); return Arrays.equals(sArr, tArr); } public static boolean isAnagramMap(String s, String t) { if (s.length() != t.length()){ return false; } Map<Character, Integer> sMap = new Hashtable<>(); for (Character c : s.toCharArray()){ if (sMap.containsKey(c)){ sMap.replace(c, sMap.get(c) + 1); } else { sMap.put(c, 1); } } for (Character c : t.toCharArray()){ if (sMap.containsKey(c)){ sMap.replace(c, sMap.get(c) - 1); if (sMap.get(c) == 0){ sMap.remove(c); } } else { return false; } } return true; } //Best performance public static boolean isAnagramIntArr(String s, String t) { if (s.length() != t.length()) { return false; } int[] chars = new int[26]; for (char c : s.toCharArray()) { chars[c - 'a']++; } for (char c : t.toCharArray()) { chars[c - 'a']--; } for (int i : chars) { if (i != 0) { return false; } } return true; } public static boolean isNumeric(String s) { for (char c : s.toCharArray()) { if (c < 48 || c > 57) { return false; } } return true; } public static int[] twoSum(int[] arr, int target){ Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < arr.length; i++) { int value = target - arr[i]; if (map.containsKey(value)) { return new int[]{map.get(value), i}; } map.put(arr[i],i); } throw new IllegalArgumentException("No twoSum solution for given parameters"); } public static int missingNum(int[] nums) { Arrays.sort(nums); if (nums[nums.length - 1] != nums.length) { return nums.length; } else if (nums[0] != 0) { return 0; } for (int i = 1; i < nums.length; i++) { int expected = nums[i - 1] + 1; if (nums[i] != expected) { return expected; } } return -1; } public static int findDupicate(int[] nums) { if (nums.length == 0){ return -1; } HashSet<Integer> map = new HashSet<>(); for (int i : nums) { if (map.contains(i)){ return i; } else { map.add(i); } } return -1; } public static int[] findLargestAndSmallest1(int[] arr) { Arrays.sort(arr); int[] result = new int[2]; result[0] = arr[0]; result[1] = arr[arr.length - 1]; return result; } public static int[] findLargestAndSmallest2(int[] arr){ int smallest = arr[0]; int largest = arr[0]; for (int i : arr){ if (i < smallest){ smallest = i; } else if (i > largest){ largest = i; } } return new int[]{smallest,largest}; } public static int[] swapTwoNums(int[] arr){ int a = arr[0]; int b = arr[1]; //swap a = a + b; b = a - b; a = a - b; return new int[]{a,b}; } public static boolean isNumericRegex(String s){ return s.matches("\\d*"); } public static String reverseWords(String s){ String[] strings = s.trim().split("\\s+"); StringBuilder sb = new StringBuilder(); for (int i = strings.length - 1; i >= 0; i--){ sb.append(strings[i]); if (i != 0){ sb.append(" "); } } return sb.toString(); } public static void printLetterAndNum(String s) { for (char c : s.toLowerCase().toCharArray()){ int num = c - 96; System.out.println(c + "" + num); } } public static int binarySearchIterative(int[] arr, int t){ int l = 0; int r = arr.length - 1; while (l <= r){ int m = l + (r-l)/2; if (t == arr[m]){ return m; } else if (t < arr[m]){ r = m - 1; } else { l = m + 1; } } return -1; } public static int binarySearchRecursive(int[] arr, int t, int l, int r){ if (l > r) { return -1; } int m = l + ((r-l)/2); if (t == arr[m]){ return m; } else if (t < arr[m]){ return binarySearchRecursive(arr, t, l, m - 1); } else { return binarySearchRecursive(arr, t, m + 1, r); } } public static boolean rotateString(String A, String B){ return A.length() == B.length() && (A + A).contains(B); } public static String reverseStrByK(String s, int k) { char[] a = s.toCharArray(); for (int start = 0; start < a.length; start += 2 * k) { int i = start, j = Math.min(start + k - 1, a.length - 1); while (i < j) { char tmp = a[i]; a[i++] = a[j]; a[j--] = tmp; } } return new String(a); } public static void main(String[] args) { // int[] arr = new int[]{1,2,3,4,5}; // System.out.println(binarySearchRecursive(arr, 5, 0, arr.length - 1)); // System.out.println(binarySearchIterative(arr, 5)); // int[] arr = {1, 2, 3, 5, 6, 8, 11}; // Arrays.stream(arr).forEach(s -> System.out.println(s)); // Object[] array = new Object[]{"Andre",5}; // Object[] arrayShort = {"Andre",5}; // if (isNumericRegex("1232")){ // System.out.println("true"); // } // int[] arr = {1,0,7,2,3,5}; // int[] result = twoSum(arr, 5); // for (int i: result){ // System.out.println(i); // } // missingNum(arr); // if (validPalindrome("A man, a plan, a canal: Panama")){ // System.out.println("true"); // } // if (isPalindrome("abcba")) { // System.out.println("YES, I AM"); // } if (isAnagram("anagram", "nagaram")) { System.out.println("is Anagram"); } else { System.out.println("is not anagram"); } // // int[] arr = {-1, -2, -3, -4, -5}; // int[] result = twoSum(arr, -8); // System.out.println(result[0] + "," + result[1]); // int[] arr = {1,2,3,4,5}; // System.out.println(missingNum(arr)); // int[] arr = new int[]{1,6,2,3,4,6,5}; // System.out.println(findDupicate(arr)); // int[] result = findLargestAndSmallest(new int[]{3,4,7,3,9,6}); // for (int i : result) { // System.out.println(i); // } // int[] fib = fibSeqDynamicProgramming(8); // for (int i : // fib) { // System.out.println(i); // } // // System.out.println(reverseString("Andre is a really cool dude")); // for (int i: swapTwoNums(new int[]{1,2})){ // System.out.println(i); // } // System.out.println(fibIterative(8)); // System.out.println(fibRecursive(5)); // System.out.println(reverseWords("Andre is da best")); // dupChar("aaabccadeff"); // printLetterAndNum("abcde"); // if(isAnagramMap("aacc", "ccac")){ // System.out.println("IS ANAGRAM"); // } else { // System.out.println("is not anagram"); // } } }
package com.gabriel.handyMan.models.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gabriel.handyMan.models.dao.IReporteDao; import com.gabriel.handyMan.models.entity.Reporte; @Service public class ReporteServiceImpl implements IReporteService { @Autowired private IReporteDao reporteDao; @Override @Transactional public Reporte save(Reporte reporte) { return reporteDao.save(reporte); } @Override public List<Reporte> findByIdTecnico(Long idTecnico) { return reporteDao.findByIdTecnico(idTecnico); } }
package org.rs.core.beans; import java.util.Date; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.rs.core.utils.MyJsonDateSerializer; import org.rs.core.utils.MyJsonDateDeserializer; public class RsUserAuth { private String sqbh; private Integer sqly; private String dlmc; private String yhbh; private Date cjsj; private String cjrbh; private String cjrmc; /** * 授权编号 */ public String getSqbh(){ return this.sqbh; } /** * 授权编号 */ public void setSqbh( String sqbh ){ this.sqbh=sqbh; } /** * 授权类型,0-登录名,1-手机号,2-邮箱,其它值待实现 */ public Integer getSqly(){ return this.sqly; } /** * 授权类型,0-登录名,1-手机号,2-邮箱,其它值待实现 */ public void setSqly( Integer sqly ){ this.sqly=sqly; } /** * 登录名称或者第三方登录的账号 */ public String getDlmc(){ return this.dlmc; } /** * 登录名称或者第三方登录的账号 */ public void setDlmc( String dlmc ){ this.dlmc=dlmc; } /** * 授权对应的用户编号 */ public String getYhbh(){ return this.yhbh; } /** * 授权对应的用户编号 */ public void setYhbh( String yhbh ){ this.yhbh=yhbh; } /** * 创建时间 */ @JsonSerialize(using = MyJsonDateSerializer.class) public Date getCjsj(){ return this.cjsj; } /** * 创建时间 */ @JsonDeserialize(using = MyJsonDateDeserializer.class) public void setCjsj( Date cjsj ){ this.cjsj=cjsj; } /** * 创建人编号 */ public String getCjrbh(){ return this.cjrbh; } /** * 创建人编号 */ public void setCjrbh( String cjrbh ){ this.cjrbh=cjrbh; } /** * 创建人名称 */ public String getCjrmc(){ return this.cjrmc; } /** * 创建人名称 */ public void setCjrmc( String cjrmc ){ this.cjrmc=cjrmc; } }
package model; import java.util.ArrayList; public class ClienteDAO { ArrayList<Cliente> cliente = new ArrayList<>(); public void cadastrarCliente(Cliente cliente) { this.cliente.add(cliente); } public String listarCliente() { String cliente = ""; for (Cliente c : this.cliente) { cliente += c; } return cliente; } public Cliente procurarCliente(int id) { return this.cliente.get(id); } public void excluirCliente(int id) { this.cliente.remove(id); } }
package ai.infrrd; import ai.infrrd.Audio.PlaySound; /** * Hello world! */ public class App { public static void main(String[] args) { // Customer customer1 = new Customer(); // Thread t1 = new Thread(customer1); // t1.start(); // Customer customer2 = new Customer(); // Thread t2 = new Thread(customer2); // t2.start(); GuitarStoreSimulator simulator = new GuitarStoreSimulator(2); simulator.startSimulation(); //System.out.println("Hello World!"); } }
package com.ak.texasholdem.tests; import com.ak.texasholdem.board.Board; import com.ak.texasholdem.cards.Deck; import com.ak.texasholdem.game.Game; import com.ak.texasholdem.player.Player; import com.ak.texasholdem.player.Players; public class GameTest { public static void main(String[] args) { Board board = new Board(); Deck deck = new Deck(); Players players = new Players(); players.addPlayerToTheBoard(new Player("Player 1", "", "", 5000)); players.addPlayerToTheBoard(new Player("Player 2", "", "", 5000)); players.addPlayerToTheBoard(new Player("Player 3", "", "", 1000)); players.addPlayerToTheBoard(new Player("Player 4", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 5", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 6", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 7", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 8", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 9", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 10", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 11", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 12", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 13", "", "", 1000)); // players.addPlayerToTheBoard(new Player("Player 14", "", "", 1000)); Game game = new Game(players, 250); game.runGame(); } }
package com.example.reminiscence; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AlertDialog; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Color; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.location.Location; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MapStyleOptions; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.LocationSource; import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener; import java.util.ArrayList; import java.util.List; import java.util.Map; public class MapCoordinatesActivity extends AppCompatActivity implements OnMyLocationButtonClickListener, OnMyLocationClickListener, OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback { private class LongPressLocationSource implements LocationSource, OnMapLongClickListener { public LatLng coordinates; private OnLocationChangedListener mListener; private boolean mPaused; @Override public void activate(OnLocationChangedListener listener) { mListener = listener; } @Override public void deactivate() { mListener = null; } @Override public void onMapLongClick(LatLng point) { if (mListener != null && !mPaused) { // if (coordinates != null){ // DraggableCircle previous_circle = new DraggableCircle(coordinates, 0); // } Location location = new Location("LongPressLocationProvider"); location.setLatitude(point.latitude); location.setLongitude(point.longitude); location.setAccuracy(100); mListener.onLocationChanged(location); coordinates = point; DraggableCircle circle = new DraggableCircle(coordinates, 1000); } } public void onPause() { mPaused = true; } public void onResume() { mPaused = false; } } private GoogleMap mMap; private MapDbAdapter dbAdapter; private EditText latitude; private EditText longitude; private Long mRowId; private Long last_id; private boolean permissionDenied = false; private LongPressLocationSource mLocationSource; private static final int LOCATION_PERMISSION_REQUEST_CODE = 11; private static final String TAG = MapCoordinatesActivity.class.getSimpleName(); private static final LatLng LEGANES = new LatLng(40.3377, -3.7722); private static final String SELECTED_STYLE = "selected_style"; // Stores the ID of the currently selected style, so that we can re-apply it when // the activity restores state, for example when the device changes orientation. private int mSelectedStyleId = R.string.style_label_retro; // These are simply the string resource IDs for each of the style names. We use them // as identifiers when choosing which style to apply. private int mStyleIds[] = { R.string.style_label_retro, R.string.style_label_night, R.string.style_label_default, }; // private OnLocationChangedListener mListener; /** * Flag to keep track of the activity's lifecycle. This is not strictly necessary in this * case because onMapLongPress events don't occur while the activity containing the map is * paused but is included to demonstrate best practices (e.g., if a background service were * to be used). */ private boolean mPaused; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedStyleId = savedInstanceState.getInt(SELECTED_STYLE); } setContentView(R.layout.activity_map_coordinates); mLocationSource = new LongPressLocationSource(); dbAdapter = new MapDbAdapter(this); dbAdapter.open(); mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(MapDbAdapter.KEY_ROWID); if (mRowId == null) { Bundle extras = getIntent().getExtras(); mRowId = extras != null ? extras.getLong(MapDbAdapter.KEY_ROWID) : null; } SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } public void saveCoordinates(View view) { LatLng point = mLocationSource.coordinates; System.out.println(mRowId); System.out.println(point); System.out.println(last_id); if (point == null){ alertDialog("Please keep pressed to select the coordinates"); return; } if (mRowId == null) { long id = dbAdapter.createCoordinates(point.latitude, point.longitude); if (id > 0) { last_id = id; } } else { dbAdapter.updateCoordinates(mRowId, point.latitude, point.longitude); } setResult(RESULT_OK); dbAdapter.close(); Toast.makeText(getBaseContext(), "Marker saved", Toast.LENGTH_SHORT).show(); finish(); } @Override protected void onResume() { super.onResume(); mLocationSource.onResume(); } @Override protected void onPause() { super.onPause(); mLocationSource.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { // Store the selected map style, so we can assign it when the activity resumes. outState.putInt(SELECTED_STYLE, mSelectedStyleId); super.onSaveInstanceState(outState); } @Override public void onMapReady(GoogleMap map) { mMap = map; mMap.setLocationSource(mLocationSource); mMap.addMarker(new MarkerOptions().position(LEGANES).title("#TeamPIÉ headquarters here!")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LEGANES, 12)); mMap.setOnMyLocationButtonClickListener(this); mMap.setOnMyLocationClickListener(this); mMap.setOnMapLongClickListener(mLocationSource); mMap.setMyLocationEnabled(true); setSelectedStyle(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.styled_map_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_style_choose) { showStylesDialog(); } return true; } /** * Shows a dialog listing the styles to choose from, and applies the selected * style when chosen. */ private void showStylesDialog() { // mStyleIds stores each style's resource ID, and we extract the names here, rather // than using an XML array resource which AlertDialog.Builder.setItems() can also // accept. We do this since using an array resource would mean we would not have // constant values we can switch/case on, when choosing which style to apply. List<String> styleNames = new ArrayList<>(); for (int style : mStyleIds) { styleNames.add(getString(style)); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.style_choose)); builder.setItems(styleNames.toArray(new CharSequence[styleNames.size()]), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedStyleId = mStyleIds[which]; String msg = getString(R.string.style_set_to, getString(mSelectedStyleId)); Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show(); Log.d(TAG, msg); setSelectedStyle(); } }); builder.show(); } /** * Creates a {@link MapStyleOptions} object via loadRawResourceStyle() (or via the * constructor with a JSON String), then sets it on the {@link GoogleMap} instance, * via the setMapStyle() method. */ private void setSelectedStyle() { MapStyleOptions style; switch (mSelectedStyleId) { case R.string.style_label_retro: // Sets the retro style via raw resource JSON. style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_retro); break; case R.string.style_label_night: // Sets the night style via raw resource JSON. style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_night); break; case R.string.style_label_default: // Removes previously set style, by setting it to null. style = null; break; default: return; } mMap.setMapStyle(style); } /** * Enables the My Location layer if the fine location permission has been granted. */ private void enableMyLocation() { // [START maps_check_location_permission] if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mMap != null) { mMap.setMyLocationEnabled(true); } } else { // Permission to access the location is missing. Show rationale and request permission PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, true); } // [END maps_check_location_permission] } @Override public boolean onMyLocationButtonClick() { // Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show(); // Return false so that we don't consume the event and the default behavior still occurs // (the camera animates to the user's current position). return false; } @Override public void onMyLocationClick(@NonNull Location location) { //Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show(); } // [START maps_check_location_permission_result] @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) { return; } if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) { // Enable the my location layer if the permission has been granted. enableMyLocation(); } else { // Permission was denied. Display an error message // [START_EXCLUDE] // Display the missing permission error dialog when the fragments resume. permissionDenied = true; // [END_EXCLUDE] } } // [END maps_check_location_permission_result] @Override protected void onResumeFragments() { super.onResumeFragments(); if (permissionDenied) { // Permission was not granted, display error dialog. showMissingPermissionError(); permissionDenied = false; } } /** * Displays a dialog with error message explaining that the location permission is missing. */ private void showMissingPermissionError() { PermissionUtils.PermissionDeniedDialog .newInstance(true).show(getSupportFragmentManager(), "dialog"); } private void alertDialog(String message) { AlertDialog.Builder dialog=new AlertDialog.Builder(this); dialog.setMessage(message); dialog.setTitle("Reminiscence"); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { }; } ); AlertDialog alertDialog=dialog.create(); alertDialog.show(); } private class DraggableCircle { private final Marker mCenterMarker; private final Circle mCircle; private double mRadiusMeters; public DraggableCircle(LatLng center, double radiusMeters) { mRadiusMeters = radiusMeters; mCenterMarker = mMap.addMarker(new MarkerOptions() .position(center) .draggable(true)); mCircle = mMap.addCircle(new CircleOptions() .center(center) .radius(radiusMeters) .strokeWidth(2) .strokeColor(Color.BLACK) .fillColor(0x30ff0000)); } } }
package com.reactive; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @FunctionalInterface public interface HandlerFunction<T extends ServerResponse> { Mono<T> handlerFunction(ServerRequest request); }
package service; import java.util.LinkedList; import dto.BookAllDto; import dto.BookDetailDto; import dto.BookDto; public interface IBookSvc { public LinkedList<BookAllDto> findAllBook(); public LinkedList<BookAllDto> findBookByParam(String param); public BookDetailDto findBookByCode(long code); public void save(BookDto dto); public void update(BookDto dto); public void delete(long code); }
/** * */ package test; import static org.junit.Assert.*; import goa.GoAnnotation; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.Before; import org.junit.Test; import parser.GoaConnector; import drugbank.Partner; /** * @author Samuel Croset * */ public class ConnectorTest { private GoaConnector connector; @Before public void initConnector() throws FileNotFoundException, IOException, ClassNotFoundException { this.connector = new GoaConnector("data/drugbank.ser", "data/go.ser"); this.connector.fillPartnersWithGoTerms(); } @Test public void testAnnotations() { Partner partner = this.connector.getDrugbank().getPartner(54); assertNotNull(partner.getAnnotations()); assertEquals(109, partner.getAnnotations().size()); GoAnnotation annot = partner.getAnnotations().get(0); assertEquals("GO:0001934", annot.getGoId()); assertEquals("UniProtKB", annot.getDatabase()); assertEquals("20090305", annot.getDate()); assertEquals("IDA", annot.getEvidence()); assertEquals(":", annot.getEvidenceProvider()); assertEquals("-", annot.getQualifier()); assertEquals("PMID:7559487", annot.getReference()); assertEquals("BHF-UCL", annot.getSource()); assertEquals("9606", annot.getTaxon()); } @Test public void testSave() throws FileNotFoundException, IOException{ this.connector.save("data/dataset-test.ser"); } }
package com.zc.pivas.configfee.service; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults; import com.zc.pivas.configfee.bean.ConfigFeeBean; import java.util.List; /** * 配置费/材料费Service * * @author kunkka * @version 1.0 */ public interface ConfigFeeService { /*** * 分页查询配置费/材料费表数据 * @param bean 对象 * @param jquryStylePaging 分页参数 * @return 分页数据 * @exception Exception e */ JqueryStylePagingResults<ConfigFeeBean> getConfigFeeLsit(ConfigFeeBean bean, JqueryStylePaging jquryStylePaging) throws Exception; /** * 添加配置费/材料费表数据 * * @param bean 配置费/材料费 */ void addConfigFee(ConfigFeeBean bean); /** * 修改配置费/材料费表数据 * * @param bean 需要修改的数据 */ void updateConfigFee(ConfigFeeBean bean); /** * 根据条件查询数量 * * @param bean 查询对象 * @return 数量 */ int getConfigFeeTotal(ConfigFeeBean bean); /** * 查询配置费/材料费 * * @return 审核错误配置费/材料费 */ ConfigFeeBean getConfigFee(ConfigFeeBean bean); /*** * 删除配置费/材料费表数据 * @param gid 主键id */ void delConfigFee(String gid); /** * 根据bean查询对应的列表信息 * * @param bean 查询条件 * @return 列表数据 */ List<ConfigFeeBean> getConfigFees(ConfigFeeBean bean); /** * 修改的时候判断名称是否存在 * * @param bean 查询条件 * @return 是否存在 */ boolean checkCondigFeeName(ConfigFeeBean bean); /** * 修改的时候判断编码是否存在 * * @param bean 查询条件 * @return 是否存在 */ boolean checkCondigFeeCode(ConfigFeeBean bean); }
package be.openclinic.common; import be.mxs.common.util.db.MedwanQuery; import java.io.File; import java.io.FileFilter; public class DocumentsFilter implements FileFilter { private String sDefaultExtensions = "doc,pdf,txt,rtf"; private String sExtensions = MedwanQuery.getInstance().getConfigString("printableDocumentExtensions",sDefaultExtensions); //--- CONSTRUCTOR --- public DocumentsFilter(){ super(); // check which extension sare configed to be accepted if(sExtensions.length()==0){ sExtensions = sDefaultExtensions; } sExtensions = sExtensions.toLowerCase(); } //--- ACCEPT ---------------------------------------------------------------------------------- public boolean accept(File file) { if(!file.isDirectory()){ String sFileName = file.getName().toLowerCase(); String sFileExtension = sFileName.substring(sFileName.lastIndexOf(".")+1); return sExtensions.indexOf(sFileExtension) > -1; } else{ return false; } } //--- GET DESCRIPTION ------------------------------------------------------------------------- public String getDescription() { return "Any extension which is configured in 'printableDocumentExtensions' document. ("+sExtensions+")"; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.web.socket.sockjs.client; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.testfixture.EnabledForTestGroups; import org.springframework.http.HttpHeaders; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHttpHeaders; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketTestServer; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import org.springframework.web.socket.handler.TextWebSocketHandler; import org.springframework.web.socket.server.HandshakeHandler; import org.springframework.web.socket.server.RequestUpgradeStrategy; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.springframework.core.testfixture.TestGroup.LONG_RUNNING; /** * Abstract base class for integration tests using the * {@link org.springframework.web.socket.sockjs.client.SockJsClient SockJsClient} * against actual SockJS server endpoints. * * @author Rossen Stoyanchev * @author Sam Brannen */ @EnabledForTestGroups(LONG_RUNNING) abstract class AbstractSockJsIntegrationTests { protected Log logger = LogFactory.getLog(getClass()); private SockJsClient sockJsClient; private WebSocketTestServer server; private AnnotationConfigWebApplicationContext wac; private TestFilter testFilter; private String baseUrl; @BeforeEach void setup(TestInfo testInfo) throws Exception { logger.debug("Setting up '" + testInfo.getTestMethod().get().getName() + "'"); this.testFilter = new TestFilter(); this.wac = new AnnotationConfigWebApplicationContext(); this.wac.register(TestConfig.class, upgradeStrategyConfigClass()); this.server = createWebSocketTestServer(); this.server.setup(); this.server.deployConfig(this.wac, this.testFilter); this.server.start(); this.wac.setServletContext(this.server.getServletContext()); this.wac.refresh(); this.baseUrl = "http://localhost:" + this.server.getPort(); } @AfterEach void teardown() { try { this.sockJsClient.stop(); } catch (Throwable ex) { logger.error("Failed to stop SockJsClient", ex); } try { this.server.undeployConfig(); } catch (Throwable t) { logger.error("Failed to undeploy application config", t); } try { this.server.stop(); } catch (Throwable t) { logger.error("Failed to stop server", t); } try { this.wac.close(); } catch (Throwable t) { logger.error("Failed to close WebApplicationContext", t); } } protected abstract Class<?> upgradeStrategyConfigClass(); protected abstract WebSocketTestServer createWebSocketTestServer(); protected abstract Transport createWebSocketTransport(); protected abstract AbstractXhrTransport createXhrTransport(); protected void initSockJsClient(Transport... transports) { this.sockJsClient = new SockJsClient(Arrays.asList(transports)); this.sockJsClient.start(); } @Test void echoWebSocket() throws Exception { testEcho(100, createWebSocketTransport(), null); } @Test void echoXhrStreaming() throws Exception { testEcho(100, createXhrTransport(), null); } @Test void echoXhr() throws Exception { AbstractXhrTransport xhrTransport = createXhrTransport(); xhrTransport.setXhrStreamingDisabled(true); testEcho(100, xhrTransport, null); } // SPR-13254 @Test void echoXhrWithHeaders() throws Exception { AbstractXhrTransport xhrTransport = createXhrTransport(); xhrTransport.setXhrStreamingDisabled(true); WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); headers.add("auth", "123"); testEcho(10, xhrTransport, headers); for (Map.Entry<String, HttpHeaders> entry : this.testFilter.requests.entrySet()) { HttpHeaders httpHeaders = entry.getValue(); assertThat(httpHeaders.getFirst("auth")).as("No auth header for: " + entry.getKey()).isEqualTo("123"); } } @Test void receiveOneMessageWebSocket() throws Exception { testReceiveOneMessage(createWebSocketTransport(), null); } @Test void receiveOneMessageXhrStreaming() throws Exception { testReceiveOneMessage(createXhrTransport(), null); } @Test void receiveOneMessageXhr() throws Exception { AbstractXhrTransport xhrTransport = createXhrTransport(); xhrTransport.setXhrStreamingDisabled(true); testReceiveOneMessage(xhrTransport, null); } @Test @SuppressWarnings("deprecation") void infoRequestFailure() throws Exception { TestClientHandler handler = new TestClientHandler(); this.testFilter.sendErrorMap.put("/info", 500); CountDownLatch latch = new CountDownLatch(1); initSockJsClient(createWebSocketTransport()); this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").addCallback( new org.springframework.util.concurrent.ListenableFutureCallback<WebSocketSession>() { @Override public void onSuccess(WebSocketSession result) { } @Override public void onFailure(Throwable ex) { latch.countDown(); } } ); assertThat(latch.await(5000, TimeUnit.MILLISECONDS)).isTrue(); } @Test void fallbackAfterTransportFailure() throws Exception { this.testFilter.sendErrorMap.put("/websocket", 200); this.testFilter.sendErrorMap.put("/xhr_streaming", 500); TestClientHandler handler = new TestClientHandler(); initSockJsClient(createWebSocketTransport(), createXhrTransport()); WebSocketSession session = this.sockJsClient.execute(handler, this.baseUrl + "/echo").get(); assertThat(session.getClass()).as("Fallback didn't occur").isEqualTo(XhrClientSockJsSession.class); TextMessage message = new TextMessage("message1"); session.sendMessage(message); handler.awaitMessage(message, 5000); } @Test @Timeout(5) @SuppressWarnings("deprecation") void fallbackAfterConnectTimeout() throws Exception { TestClientHandler clientHandler = new TestClientHandler(); this.testFilter.sleepDelayMap.put("/xhr_streaming", 10000L); this.testFilter.sendErrorMap.put("/xhr_streaming", 503); initSockJsClient(createXhrTransport()); // this.sockJsClient.setConnectTimeoutScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class)); WebSocketSession clientSession = sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get(); assertThat(clientSession.getClass()).as("Fallback didn't occur").isEqualTo(XhrClientSockJsSession.class); TextMessage message = new TextMessage("message1"); clientSession.sendMessage(message); clientHandler.awaitMessage(message, 5000); clientSession.close(); } @SuppressWarnings("deprecation") private void testEcho(int messageCount, Transport transport, WebSocketHttpHeaders headers) throws Exception { List<TextMessage> messages = new ArrayList<>(); for (int i = 0; i < messageCount; i++) { messages.add(new TextMessage("m" + i)); } TestClientHandler handler = new TestClientHandler(); initSockJsClient(transport); URI url = URI.create(this.baseUrl + "/echo"); WebSocketSession session = this.sockJsClient.doHandshake(handler, headers, url).get(); for (TextMessage message : messages) { session.sendMessage(message); } handler.awaitMessageCount(messageCount, 5000); for (TextMessage message : messages) { assertThat(handler.receivedMessages.remove(message)).as("Message not received: " + message).isTrue(); } assertThat(handler.receivedMessages).as("Remaining messages: " + handler.receivedMessages).isEmpty(); session.close(); } @SuppressWarnings("deprecation") private void testReceiveOneMessage(Transport transport, WebSocketHttpHeaders headers) throws Exception { TestClientHandler clientHandler = new TestClientHandler(); initSockJsClient(transport); this.sockJsClient.doHandshake(clientHandler, headers, URI.create(this.baseUrl + "/test")).get(); TestServerHandler serverHandler = this.wac.getBean(TestServerHandler.class); assertThat(clientHandler.session).as("afterConnectionEstablished should have been called").isNotNull(); serverHandler.awaitSession(5000); TextMessage message = new TextMessage("message1"); serverHandler.session.sendMessage(message); clientHandler.awaitMessage(message, 5000); } private static void awaitEvent(BooleanSupplier condition, long timeToWait, String description) { long timeToSleep = 200; for (int i = 0 ; i < Math.floor(timeToWait / timeToSleep); i++) { if (condition.getAsBoolean()) { return; } try { Thread.sleep(timeToSleep); } catch (InterruptedException ex) { throw new IllegalStateException("Interrupted while waiting for " + description, ex); } } throw new IllegalStateException("Timed out waiting for " + description); } @Configuration(proxyBeanMethods = false) @EnableWebSocket static class TestConfig implements WebSocketConfigurer { @Autowired private RequestUpgradeStrategy upgradeStrategy; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { HandshakeHandler handshakeHandler = new DefaultHandshakeHandler(this.upgradeStrategy); registry.addHandler(new EchoHandler(), "/echo").setHandshakeHandler(handshakeHandler).withSockJS(); registry.addHandler(testServerHandler(), "/test").setHandshakeHandler(handshakeHandler).withSockJS(); } @Bean public TestServerHandler testServerHandler() { return new TestServerHandler(); } } private static class TestClientHandler extends TextWebSocketHandler { private final BlockingQueue<TextMessage> receivedMessages = new LinkedBlockingQueue<>(); private volatile WebSocketSession session; private volatile Throwable transportError; @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { this.session = session; } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { this.receivedMessages.add(message); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { this.transportError = exception; } public void awaitMessageCount(final int count, long timeToWait) throws Exception { awaitEvent(() -> receivedMessages.size() >= count, timeToWait, count + " number of messages. Received so far: " + this.receivedMessages); } public void awaitMessage(TextMessage expected, long timeToWait) throws InterruptedException { TextMessage actual = this.receivedMessages.poll(timeToWait, TimeUnit.MILLISECONDS); if (actual != null) { assertThat(actual).isEqualTo(expected); } else if (this.transportError != null) { throw new AssertionError("Transport error", this.transportError); } else { fail("Timed out waiting for [" + expected + "]"); } } } private static class EchoHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { session.sendMessage(message); } } private static class TestServerHandler extends TextWebSocketHandler { private WebSocketSession session; @Override public void afterConnectionEstablished(WebSocketSession session) { this.session = session; } public WebSocketSession awaitSession(long timeToWait) { awaitEvent(() -> this.session != null, timeToWait, " session"); return this.session; } } private static class TestFilter implements Filter { private final Map<String, HttpHeaders> requests = new HashMap<>(); private final Map<String, Long> sleepDelayMap = new HashMap<>(); private final Map<String, Integer> sendErrorMap = new HashMap<>(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); HttpHeaders headers = new ServletServerHttpRequest(httpRequest).getHeaders(); this.requests.put(uri, headers); for (String suffix : this.sleepDelayMap.keySet()) { if (httpRequest.getRequestURI().endsWith(suffix)) { try { Thread.sleep(this.sleepDelayMap.get(suffix)); break; } catch (InterruptedException ex) { ex.printStackTrace(); } } } for (String suffix : this.sendErrorMap.keySet()) { if (httpRequest.getRequestURI().endsWith(suffix)) { ((HttpServletResponse) response).sendError(this.sendErrorMap.get(suffix)); return; } } chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } } }
package com.travel.community.travel_demo.controller; import com.travel.community.travel_demo.mapper.UserMapper; import com.travel.community.travel_demo.model.User; import com.travel.community.travel_demo.model.UserExample; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.UUID; /** * @author w1586 */ @Controller @RequestMapping("/user") public class UserLoginController { @Autowired private UserMapper userMapper; @GetMapping("/telephoneRegister") public String telephoneRegister() { return "telephoneRegister"; } @GetMapping("/register") public String register() { return "register"; } @GetMapping("/login") public String login() { return "login"; } // @RequestMapping("/successLogin") // public String successLogin(){ // return "successLogin"; // } /** * 退出登录 * @param request * @param response * @return */ @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) { request.getSession().removeAttribute("user"); Cookie cookie = new Cookie("token",null); cookie.setMaxAge(0); response.addCookie(cookie); return "redirect:/"; } // @ResponseBody // @RequestMapping(value = "/successLogin", method = RequestMethod.POST) @PostMapping(value = "/successLogin") public String successLogin( HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "userName") String userName) { if(userName != null){ User user = new User(); // String token = UUID.randomUUID().toString(); // String token = userMapper.selectUserToken(userName); UserExample example = new UserExample(); example.createCriteria().andAccountIdEqualTo(userName); List<User> users = userMapper.selectByExample(example); String token = users.get(0).getToken(); user.setToken(token); // user.setUserName(userMapper.selectUserName(userName)); user.setUserName(users.get(0).getUserName()); user.setAccountId(userName); // userMapper.githubInsert(user); Cookie cookie = new Cookie("token",token); response.addCookie(cookie); // 登录成功,写cookie和session request.getSession().setAttribute("user",user); return "redirect:/"; }else{ //登录失败,重新登录 return "redirect:/"; } // return "successLogin"; } // @RequestMapping("/successRegister") @GetMapping("/successRegister") public String successRegister() { return "successRegister"; } @ResponseBody // @RequestMapping(value = "/select", method = RequestMethod.POST) @PostMapping(value = "/select") public String select(@RequestBody User user) { System.out.println(user.getUserName()+"---"+user.getAccountId()); // String result = userMapper.selectUserName(user.getAccountId()); UserExample example = new UserExample(); example.createCriteria().andAccountIdEqualTo(user.getAccountId()); List<User> users = userMapper.selectByExample(example); String result = users.get(0).getUserName(); System.out.println(result); if (result == null) { return "0"; } return "1"; } @ResponseBody // @RequestMapping(value = "/selectUserName", method = RequestMethod.POST) @PostMapping(value = "/selectUserName") public String selectUserName(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) { String userName = user.getUserName(); String accountId = userName; String userPassword = user.getUserPassword(); System.out.println(accountId+"---"+userName+"---"+userPassword); String result = "-1"; //将输入的密码加密 String passwordMD5 = passwordMD5(accountId, userPassword); UserExample example = new UserExample(); example.createCriteria().andAccountIdEqualTo(accountId); List<User> users = userMapper.selectByExample(example); //用户不存在 // userMapper.selectAccountId(accountId) == null if (users.get(0).getAccountId() == null) { // return "用户不存在"; result = "0"; System.out.println(accountId+"---"+userName+"---"+userPassword); return result; //用户存在,但密码输入错误 // !userMapper.selectUserPassword(accountId).equals(passwordMD5) }else if(!users.get(0).getUserPassword().equals(passwordMD5) ){ result = "1"; return result; // return "账号或密码输入错误"; // userMapper.selectUserPassword(accountId).equals(passwordMD5) }else if(users.get(0).getUserPassword().equals(passwordMD5)) { try{ result = "2"; System.out.println(result); User user1 = new User(); // String token = userMapper.selectUserToken(accountId); String token = users.get(0).getToken(); user1.setToken(token); // user1.setUserName(userMapper.selectUserName(accountId)); user1.setUserName(users.get(0).getUserName()); user1.setAccountId(accountId); // user.setAvatarUrl(githubUser.getAvatarUrl()); Cookie cookie = new Cookie("token",token); response.addCookie(cookie); // 登录成功,写cookie和session request.getSession().setAttribute("user",user1); // return "成功登录"; return result; }catch (Exception e){ e.printStackTrace(); } } return result; } @ResponseBody // @RequestMapping(value = "/addUser", method = RequestMethod.POST) @PostMapping(value = "/addUser") public String addUser(@RequestBody User user) { String userName = user.getUserName(); String accountId = user.getAccountId(); String userPassword = user.getUserPassword(); System.out.println(accountId+"--"+userName+"--"+userPassword); String passwordMD5 = passwordMD5(accountId, userPassword); String token = UUID.randomUUID().toString(); User user1 = new User(); user1.setUserName(user.getUserName()); user1.setAccountId(user.getAccountId()); user1.setUserPassword(passwordMD5); user1.setToken(token); user1.setGmtCreate(System.currentTimeMillis()); // userMapper.addUser(user1); userMapper.insert(user1); return "1"; } /** * 对密码进行MD5加密 */ public String passwordMD5(String userName, String userPassword) { // 需要加密的字符串 String src = userName + userPassword; try { // 加密对象,指定加密方式 MessageDigest md5 = MessageDigest.getInstance("md5"); // 准备要加密的数据 byte[] b = src.getBytes(); // 加密:MD5加密一种被广泛使用的密码散列函数, // 可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致 byte[] digest = md5.digest(b); // 十六进制的字符 char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', 'A', 'B', 'C', 'd', 'o', '*', '#', '/'}; StringBuffer sb = new StringBuffer(); // 处理成十六进制的字符串(通常) // 遍历加密后的密码,将每个元素向右位移4位,然后与15进行与运算(byte变成数字) for (byte bb : digest) { sb.append(chars[(bb >> 4) & 15]); sb.append(chars[bb & 15]); } // 打印加密后的字符串 System.out.println(sb); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } }
package com.fanfte.algorithm.jz; /** * Created by dell on 2018/7/18 **/ public class Power011 { public static void main(String[] args) { double res = new Power011().power(2, -9); System.out.println(res); } double power(double base, int exponent) { if(equal(base, 0.0) && exponent < 0) { return 0.0; } double result = 0.0; int srcExponent = exponent; if(srcExponent < 0) { exponent = -exponent; } result = powerOfUnsignedInt(base, exponent); if(srcExponent < 0) { result = 1 / result; } return result; } double powerOfUnsignedInt(double base, int exponent) { double result = 1.0; for(int i = 0;i < exponent;i++) { result *= base; } return result; } private boolean equal(double base, double v) { if((base - v > -0.0000001) &&(base - v < 0.0000001)) { return true; } else { return false; } } }
package com.example.myplaces; public class UserModel { public String fullName; public String email; public String phoneNumber; public int numLocationsAdded; public String profilePhoto; public int markerPriority; public UserModel(String fullName, String email, String phoneNumber, int numLocationsAdded) { this.fullName = fullName; this.email = email; this.phoneNumber = phoneNumber; this.numLocationsAdded = numLocationsAdded; this.markerPriority = markerPriority; } public UserModel() { } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public int getNumLocationsAdded() { return numLocationsAdded; } public void setNumLocationsAdded(int numLocationsAdded) { this.numLocationsAdded = numLocationsAdded; } public String getProfilePhoto() { return profilePhoto; } public void setProfilePhoto(String profilePhoto) { this.profilePhoto = profilePhoto; } public int getMarkerPriority() { return markerPriority; } public void setMarkerPriority(int markerPriority) { this.markerPriority = markerPriority; } }
package samwho.perf; import samwho.*; import samwho.functional.*; import battlecode.common.*; import java.io.Closeable; public class Timer implements Closeable { private static final boolean ENABLED = true; private Timer parent; private BytecodeCounter bc; private RobotController rc; private String desc; private int overhead; private int recorded; private static class FakeTimer extends Timer { public FakeTimer(RobotController rc, String desc) { super(rc, desc); } @Override public void prep() { } @Override public int record(String message) { return 0; } @Override public void close() { } } public static Timer create(RobotController rc, String desc) { if (!ENABLED) { return new FakeTimer(rc, desc); } return new Timer(rc, desc); } private Timer(RobotController rc, String desc) { this.rc = rc; this.bc = new BytecodeCounter(rc); this.desc = desc; this.overhead = 0; this.recorded = 0; } /** * Prepare to time a region of code. * * Any time elapsed up to this point is counted as overhead. */ public void prep() { overhead += bc.lap(); } /** * Record a named time interval in your code. * * Time is added to the recorded time (not overhead), and a message is printed * using Utils.debug_out. */ public int record(String message) { int l = bc.lap(); Utils.debug_out(l + " -> " + desc + ":" + message); recorded += l; return l; } @Override public void close() { prep(); Utils.debug_out("\n\nTimer[" + desc + "] ->\n" + " - recorded " + recorded + "\n" + " - overhead " + overhead + "\n" + " - total " + bc.total()); } }
package controller; import BUS.UserBUS; import DTO.UserDTO; import helper.ConfirmDialogHelper; import helper.PopupHelper; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.WindowEvent; import java.net.URL; import java.sql.SQLException; import java.util.ResourceBundle; public class LoginController implements Initializable { private Stage mainStage; private MainController mainController; @FXML private TextField tfUsername; @FXML private PasswordField pfPassword; @FXML private Text textLoginFail; @Override public void initialize(URL location, ResourceBundle resources) { mainStage = PopupHelper.createStage("/resources/fxml/todo_main.fxml", 1280, 800); mainStage.initStyle(StageStyle.TRANSPARENT); mainStage.getScene().getWindow().addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, e -> { if (ConfirmDialogHelper.confirm("Xác nhận thoát?")) { PopupHelper.createStage("/resources/fxml/LoginForm.fxml", 825, 522).show(); } else { e.consume(); } }); FXMLLoader loader = (FXMLLoader) mainStage.getUserData(); mainController = loader.getController(); textLoginFail.setVisible(false); } public void handleLogin() { String username = tfUsername.getText(); String password = pfPassword.getText(); try { if (UserBUS.checkLoginUser(username, password)) { Stage loginStage = (Stage) tfUsername.getScene().getWindow(); UserDTO user = UserBUS.getUserByUsername(username); loginStage.close(); mainController.initialize(user); mainStage.hide(); mainStage.showAndWait(); } else { tfUsername.requestFocus(); textLoginFail.setVisible(true); } } catch (SQLException e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Lỗi"); alert.setHeaderText("Không thể đăng nhập!"); alert.setContentText("Lỗi database!"); alert.showAndWait(); e.printStackTrace(); } } public void handleSignUp() { Stage signInStage = PopupHelper.createStage("/resources/fxml/SignUpForm.fxml", 757, 530); signInStage.showAndWait(); } }
package com.proximizer.client; import java.util.ArrayList; import android.app.Application; import android.content.Context; public class Global extends Application{ public static ArrayList<Contact> contacts = new ArrayList<Contact>(); // public static ArrayList<String> contactnames = new ArrayList<String>() ; public static Contact myself = new Contact() ; public static final String NAMESPACE = "http://proximizer.com/"; // public static final String URL = "http://10.0.2.2:8888/proximizer/processorSoapServerServlet" ; // public static final String SOAP_ACTION="http://l0.0.2.2:8888/proximizer/processorSoapServerServlet" ; public static final String URL = "http://proximizer.appspot.com/proximizer/processorSoapServerServlet" ; public static final String SOAP_ACTION="http://proximizer.appspot.com/proximizer/processorSoapServerServlet" ; static final String TAG ="Gobal" ; public static boolean IntializeContactsData(Context ctx) { // return true ; } }
package com.meetup.engage; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.StackedAreaChart; import javafx.scene.chart.XYChart; import javafx.stage.Stage; public class SALineCharter extends Application { final CategoryAxis xAxis = new CategoryAxis(); final NumberAxis yAxis = new NumberAxis(0,20,1); final StackedAreaChart<String, Number> sac = new StackedAreaChart<String, Number>(xAxis, yAxis); // JavaFX does not have a DateAxis... Quick workaround to get X-axis aligned. final static int YEAR_BEGIN = 2010; final static int YEAR_END = 2016; @Override public void start(Stage stage) { final Parameters params = getParameters(); final List<String> parameters = params.getRaw(); String[] evntArr = parameters.get(0).split("\\|"); Arrays.sort(evntArr); String[] grpArr = parameters.get(1).split("\\|"); Arrays.sort(grpArr); stage.setTitle("Count of Comments"); sac.setTitle("Number of Comments over Time"); XYChart.Series<String, Number> seriesEvent = new XYChart.Series<String, Number>(); seriesEvent.setName("Event Comments"); Map<String, Number> evntMap = new HashMap<String, Number>(); for (int i = 1;i<evntArr.length;i++) { String[] keyValue = evntArr[i].split(","); evntMap.put(keyValue[0],Float.parseFloat(keyValue[1])); } XYChart.Series<String, Number> seriesGroup = new XYChart.Series<String, Number>(); seriesGroup.setName("Group Comments"); Map<String, Number> grpMap = new HashMap<String, Number>();; for (int i = 1;i<grpArr.length;i++) { String[] keyValue = grpArr[i].split(","); grpMap.put(keyValue[0],Float.parseFloat(keyValue[1])); } for (int i = YEAR_BEGIN; i<YEAR_END; i++) { for (int j = 1;j<=12;j++) { String dateYYYY = new Integer(i).toString(); String dateMM = new Integer(j).toString(); if (dateMM.length() == 1) { dateMM = "0" + dateMM; } String category = dateYYYY + "-" + dateMM; Number evntCnt = evntMap.get(category); if(evntCnt == null) { seriesEvent.getData().add(new XYChart.Data<String, Number>(category,0)); } else { seriesEvent.getData().add(new XYChart.Data<String, Number>(category,evntCnt)); } Number grpCnt = grpMap.get(category); if(grpCnt == null) { seriesGroup.getData().add(new XYChart.Data<String, Number>(category,0)); } else { seriesGroup.getData().add(new XYChart.Data<String, Number>(category,grpCnt)); } } } Scene scene = new Scene(sac, 1000, 800); sac.getData().add(seriesGroup); sac.getData().add(seriesEvent); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
package com.example.suigeneris; import android.content.Context; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import static com.example.suigeneris.Spy.PersonCount; public class CheckServer extends Thread { private DatagramSocket socket; private boolean running; private byte[] buf = new byte[256]; private Context Glcontext; public CheckServer(Context context) throws SocketException { socket = new DatagramSocket(4445); Glcontext = context; } public void run() { running = true; int a = 0; while (running) { if (a == 1){ try { socket.setSoTimeout(1800000 ); Thread.sleep(1800000); socket.close(); CheckServer status_check = null; status_check = new CheckServer(Glcontext); status_check.run(); System.out.println("***********************************************************"); } catch (SocketException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } a = 0; DatagramPacket packet = new DatagramPacket(buf, buf.length); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); } try { InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); String received = new String(packet.getData(), 0, packet.getLength()); System.out.println(received); String[] parts = received.split("\r\n"); if (parts[0].equals("Notification")){ NotificationCenter mot = new NotificationCenter(Glcontext); mot.createNotification(parts[1],parts[2]); a = 1; try { socket.setSoTimeout(1800000 ); } catch (SocketException e) { e.printStackTrace(); } } else { PersonCount(); } } catch (Exception e) { e.printStackTrace(); } } socket.close(); } }
package com.example.fyp.Adapters; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.example.fyp.Adapters.OrdersAdapter; import com.example.fyp.Fragments.FragmentStockDetails; import com.example.fyp.ImageUtils.LoadImages; import com.example.fyp.MainActivity; import com.example.fyp.Models.CartBO; import com.example.fyp.Models.OrdersBO; import com.example.fyp.Models.StockBO; import com.example.fyp.R; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import butterknife.BindView; import butterknife.ButterKnife; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class StockAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private ArrayList<StockBO> arrayList; public StockAdapter(Context context, ArrayList<StockBO> arrayList) { this.context = context; this.arrayList = arrayList; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return new StockViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_recycler_stocks,null)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { StockViewHolder stockViewHolder = (StockViewHolder) viewHolder; stockViewHolder.tvDescription.setText(arrayList.get(i).getDescription()); stockViewHolder.tvGender.setText(arrayList.get(i).getGender()); stockViewHolder.tvProductType.setText(arrayList.get(i).getProductType()); stockViewHolder.tvStock.setText(arrayList.get(i).getStock()); LoadImages.loadImageFromUrl(context,arrayList.get(i).getImagepath(),stockViewHolder.ivImageView); } @Override public int getItemCount() { return arrayList.size(); } class StockViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ @BindView(R.id.tvGender) TextView tvGender; @BindView(R.id.tvProductType) TextView tvProductType; @BindView(R.id.tvDescription) TextView tvDescription; @BindView(R.id.tvStock) TextView tvStock; @BindView(R.id.tvDetails) TextView tvDetails; @BindView(R.id.ivImageView) ImageView ivImageView; public StockViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this,itemView); tvDetails.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tvDetails: { ((MainActivity)context).openNewFragment(FragmentStockDetails.newInstance(arrayList.get(getAdapterPosition()))); break; } } } } public void clear() { arrayList.clear(); } public void updateData() { notifyDataSetChanged(); } public void addItems(ArrayList<StockBO> arrayList) { clear(); this.arrayList.addAll(arrayList); updateData(); } }