text
stringlengths
10
2.72M
package com.example.asus.taskapp.Utils; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.asus.taskapp.Model.Books; import com.example.asus.taskapp.Model.SoldBooks; import com.example.asus.taskapp.Model.Users; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class FetchData extends AsyncTask<String , Void , String> { public enum FetchType { USERS, USERS_FIND_BY_ID, BOOKS, BOOKS_FIND_BY_USER_ID, BOOKS_FIND_BY_ID, SOLD_BOOKS, SOLD_BOOKS_FIND_BY_USER_ID, SOLD_BOOKS_FIND_BY_ID } public Context context; public String uri; public FetchType fetchType; public String token; public TextView teksView = null; public ProgressDialog progressDialog; public OnUsersListener usersListener; public OnBooksListener booksListener; public OnSoldBooksListener soldBooksListener; public boolean isFragment = false; public FetchData(Context context , String uri , FetchType fetchType , String token , boolean isFragment){ this.context = context; this.uri = uri; this.fetchType = fetchType; this.token = token; this.isFragment = isFragment; } public void setTextView(TextView teksView){ this.teksView = teksView; } public void setUsersListener(OnUsersListener usersListener){ this.usersListener = usersListener; } public void setBooksListener(OnBooksListener booksListener){ this.booksListener = booksListener; } public void setSoldBooksListener(OnSoldBooksListener soldBooksListener){ this.soldBooksListener = soldBooksListener; } public String getDataFromURL(String uri , String token){ try { URL url = new URL(uri); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setDoInput(true); connection.setReadTimeout(15000); connection.setConnectTimeout(15000); connection.setRequestMethod("GET"); connection.setRequestProperty("x-token",token); InputStreamReader inStreamReader = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(inStreamReader); StringBuilder sb = new StringBuilder(); String line = ""; while((line = reader.readLine()) != null){ sb.append(line); } return sb.toString(); } catch(MalformedURLException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } return null; } @Override protected void onPreExecute() { if(!isFragment){ progressDialog = new ProgressDialog(context); progressDialog.setTitle("Status"); progressDialog.setCancelable(false); progressDialog.setMessage("Waiting...."); progressDialog.show(); } else { if(teksView != null){ teksView.setVisibility(View.VISIBLE); teksView.setText("Fetching data....."); } } super.onPreExecute(); } @Override protected String doInBackground(String... strings) { return getDataFromURL(uri , token); } @Override protected void onPostExecute(String s) { if(fetchType == FetchType.USERS){ try { JSONArray arrays = new JSONArray(s); if(arrays.length() > 0){ List<Users> usersList = new ArrayList<>(); for(int i = 0; i < arrays.length(); i++){ JSONObject object = arrays.getJSONObject(i); JSONObject objects = object.getJSONObject("users_detail"); usersList.add(new Users( object.getInt("id"),object.getString("email"),object.getString("name"), object.getString("password"),object.getString("sekolah"), objects.getString("kelamin"),objects.getString("image_path"), objects.getString("original_image_path") )); } usersListener.onUsersData(usersList); } else { usersListener.onUsersData(null); } } catch(JSONException e){ e.printStackTrace(); } } else if(fetchType == FetchType.USERS_FIND_BY_ID){ try { if(s != null){ JSONObject object = new JSONObject(s); JSONObject objects = object.getJSONObject("users_detail"); List<Users> usersList = new ArrayList<>(); usersList.add(new Users( object.getInt("id"),object.getString("email"),object.getString("name"), object.getString("password"),object.getString("sekolah"),objects.getString("kelamin"), objects.getString("image_path"),objects.getString("original_image_path") )); usersListener.onUsersData(usersList); } else if(s == null){ usersListener.onUsersData(null); } } catch(JSONException e){ e.printStackTrace(); usersListener.onUsersData(null); } } else if(fetchType == FetchType.BOOKS){ try { if(s != null){ JSONArray array = new JSONArray(s); if(array.length() != 0){ List<Books> booksList = new ArrayList<>(); for(int i = 0; i < array.length(); i++){ JSONObject object = array.getJSONObject(i); Books books = new Books(); books.setId(object.getInt("id")); books.setUserId(object.getInt("user_id")); books.setBookName(object.getString("book_name")); books.setCountBook(object.getInt("count_book")); books.setPriceBook(object.getInt("price_book")); books.setStatus(object.getString("status")); books.setImagePath(object.getString("image_path")); books.setOriginalImagePath(object.getString("original_image_path")); books.setCreatedAt(object.getString("created_at")); booksList.add(books); } booksListener.onBooksData(booksList); } else { booksListener.onBooksData(null); } } else { booksListener.onBooksData(null); } } catch(JSONException e){ e.printStackTrace(); } } else if(fetchType == FetchType.BOOKS_FIND_BY_USER_ID){ try { JSONArray arrays = new JSONArray(s); List<Books> booksList = new ArrayList<>(); if(arrays.length() != 0){ for(int i = 0; i < arrays.length(); i++){ JSONObject object = arrays.getJSONObject(i); Books books = new Books(); books.setId(object.getInt("id")); books.setUserId(object.getInt("user_id")); books.setBookName(object.getString("book_name")); books.setCountBook(object.getInt("count_book")); books.setPriceBook(object.getInt("price_book")); books.setStatus(object.getString("status")); books.setImagePath(object.getString("image_path")); books.setOriginalImagePath(object.getString("original_image_path")); books.setCreatedAt(object.getString("created_at")); booksList.add(books); } booksListener.onBooksData(booksList); } else { booksListener.onBooksData(null); } } catch(JSONException e){ e.printStackTrace(); } } else if(fetchType == FetchType.BOOKS_FIND_BY_ID){ try { JSONObject object = new JSONObject(s); if(object != null){ List<Books> booksList = new ArrayList<>(); Books books = new Books(); books.setId(object.getInt("id")); books.setUserId(object.getInt("user_id")); books.setBookName(object.getString("book_name")); books.setCountBook(object.getInt("count_book")); books.setPriceBook(object.getInt("price_book")); books.setStatus(object.getString("status")); books.setImagePath(object.getString("image_path")); books.setOriginalImagePath(object.getString("original_image_path")); booksList.add(books); booksListener.onBooksData(booksList); } else { booksListener.onBooksData(null); } } catch(JSONException e){ e.printStackTrace(); } } else if(fetchType == FetchType.SOLD_BOOKS){ try { JSONArray arrays = new JSONArray(s); if(arrays.length() != 0){ List<SoldBooks> soldBooksList = new ArrayList<>(); for(int i = 0; i < arrays.length(); i++){ JSONObject object = arrays.getJSONObject(i); SoldBooks soldBooks = new SoldBooks(); soldBooks.setId(object.getInt("id")); soldBooks.setUserId(object.getInt("user_id")); soldBooks.setBookName(object.getString("book_name")); soldBooks.setCountBook(object.getInt("count_book")); soldBooks.setTotalPrice(object.getInt("total_price")); soldBooks.setStatus(object.getString("status")); soldBooks.setUsersSold(object.getString("users_sold")); soldBooks.setBuyer(object.getString("buyer")); soldBooks.setSoldAt(object.getString("sold_at")); soldBooks.setImagePath(object.getString("image_path")); soldBooks.setOriginalImagePath(object.getString("original_image_path")); soldBooksList.add(soldBooks); soldBooksListener.onSoldBooksData(soldBooksList); } } else { soldBooksListener.onSoldBooksData(null); } } catch(JSONException e){ e.printStackTrace(); } } else if(fetchType == FetchType.SOLD_BOOKS_FIND_BY_USER_ID){ try { if(s != null){ List<SoldBooks> soldList = new ArrayList<>(); JSONArray arrays = new JSONArray(s); for(int i = 0; i < arrays.length(); i++){ JSONObject object = arrays.getJSONObject(i); SoldBooks soldBooks = new SoldBooks(); soldBooks.setId(object.getInt("id")); soldBooks.setUserId(object.getInt("user_id")); soldBooks.setBookId(object.getInt("book_id")); soldBooks.setBookName(object.getString("book_name")); soldBooks.setCountBook(object.getInt("count_book")); soldBooks.setTotalPrice(object.getInt("total_price")); soldBooks.setStatus(object.getString("status")); soldBooks.setUsersSold(object.getString("users_sold")); soldBooks.setBuyer(object.getString("buyer")); soldBooks.setSoldAt(object.getString("sold_at")); soldBooks.setImagePath(object.getString("image_path")); soldBooks.setOriginalImagePath(object.getString("original_image_path")); soldList.add(soldBooks); soldBooksListener.onSoldBooksData(soldList); } } else { soldBooksListener.onSoldBooksData(null); } } catch(JSONException e){ e.printStackTrace(); } } else if(fetchType == FetchType.SOLD_BOOKS_FIND_BY_ID){ try { JSONObject object = new JSONObject(s); if(object.length() != 0){ List<SoldBooks> soldBooks = new ArrayList<>(); SoldBooks books = new SoldBooks(); books.setId(object.getInt("id")); books.setUserId(object.getInt("user_id")); books.setBookName(object.getString("book_name")); books.setCountBook(object.getInt("count_book")); books.setTotalPrice(object.getInt("total_price")); books.setStatus(object.getString("status")); books.setUsersSold(object.getString("users_sold")); books.setBuyer(object.getString("buyer")); books.setSoldAt(object.getString("sold_at")); books.setImagePath(object.getString("image_path")); books.setOriginalImagePath(object.getString("original_image_path")); soldBooks.add(books); soldBooksListener.onSoldBooksData(soldBooks); } else { soldBooksListener.onSoldBooksData(null); } } catch(JSONException e){ e.printStackTrace(); } } if(!isFragment){ progressDialog.dismiss(); } else { if(teksView != null){ teksView.setVisibility(View.GONE); } } super.onPostExecute(s); } public interface OnUsersListener { void onUsersData(List<Users> usersList); } public interface OnBooksListener { void onBooksData(List<Books> booksList); } public interface OnSoldBooksListener { void onSoldBooksData(List<SoldBooks> soldBooksList); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Model; /** * * @author HermanCosta */ public class Customer { int customerId; String firstName, lastName, email, contactNo; public Customer(String _firstName, String _lastName, String _contactNo, String _email) { this.firstName = _firstName; this.lastName = _lastName; this.contactNo = _contactNo; this.email = _email; } public int getCustomerId() { return customerId; } public void setCustomerId(int customerID) { this.customerId = customerID; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getContactNo() { return contactNo; } public void setContactNo(String contactNo) { this.contactNo = contactNo; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package org.yxm.modules.wan.repo.local; import java.util.List; import org.yxm.modules.wan.entity.WanArticleEntity; import org.yxm.modules.wan.entity.WanTabEntity; /** * Wan 的model接口,控制网络,数据库,缓存数据 */ public interface IWanModel { public interface LoadDataListener<T> { void onSuccess(int code, T datas); void onFialed(int code, Throwable throwable); } List<WanTabEntity> getWanTabs(); List<WanArticleEntity> syncGetWanArticleDatas(int authorId); void asyncGetWanArticleDatas(int authorId, LoadDataListener<List<WanArticleEntity>> loadDataListener, int page); }
package com.example.fileupload.IngestionRepository; import com.example.fileupload.Entity.FileRecord; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; public interface FileRecordRepository extends MongoRepository<FileRecord, String> { List<FileRecord> getBystatus(String received); }
package main.com.java.basics.stream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import com.google.common.collect.Lists; import java.util.stream.Collectors; /** * @author Heena Hussain * */ public class RemoveDuplicateFromList { public static void main(String[] args) { List<Integer> integerWithDups = Arrays.asList(0,1,2,3,0,0); // Using hash set List<Integer> integerWithoutDups = new ArrayList<>(new HashSet<>(integerWithDups)); System.out.println(integerWithoutDups.size() == 5 ? "correct" : "incorrect"); //Using Guava library integerWithoutDups = Lists.newArrayList(integerWithDups); System.out.println(integerWithoutDups.size() == 5 ? "correct" : "incorrect"); //Using lambdas integerWithoutDups = integerWithDups.stream().distinct().collect(Collectors.toList()); System.out.println(integerWithoutDups.size() == 5 ? "correct" : "incorrect"); } }
package com.ssm.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import cn.smbms.tools.PageSupport; import cn.smbms.tools.QueryCondition; import com.ssm.mapper.user.UserMapper; import com.ssm.pojo.User; import com.ssm.service.UserService; @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; /** * 登录 */ public User login(User user) { User ret = null; try { ret = userMapper.getUserByUserCode(user); } catch (Exception e) { // TODO: handle exception } return ret; } /** * 分页获取用户列表 */ @Override public List<User> getUserListByPage(PageSupport page) { int from =(page.getCurrentPageNo()-1)*page.getPageSize(); page.setTotalCount(userMapper.getTotalCount()); return userMapper.getUserListByPage(from, page.getPageSize()); } /** * 根据查询条件,执行动态SQL,分页获取用户列表 */ @Override public List<User> getUserListByPage(QueryCondition queryCondition,PageSupport page) { int from =(page.getCurrentPageNo()-1)*page.getPageSize(); page.setTotalCount(userMapper.getTotalCountWithCondition(queryCondition)); Map<String,Object> map=new HashMap<String, Object>(); map.put("queryUserCode", queryCondition.getQueryUserCode()); map.put("queryUserName", queryCondition.getQueryUserName()); map.put("from",from); map.put("pageSize", page.getPageSize()); return userMapper.getUserListByPageWithCondition(map); } @Override public List<User> findAll() { return userMapper.findAll(); } @Override public List<User> findAllByPageIndex(int from, int pageSize) { // TODO Auto-generated method stub return userMapper.findAllByPageIndex(from, pageSize); } /** * 根据ID查询 */ @Override public User selectById(int id) { // TODO Auto-generated method stub return userMapper.selectById(id); } /** * 修改用户信息 */ @Override public boolean update(User user) { try { userMapper.update(user); return true; } catch (Exception e) { // TODO: handle exception } return false; } /** * 更改用户状态信息(1 :正常  0:禁用) */ public boolean updateState(int[] uids){ try { userMapper.updateState(uids); return true; } catch (Exception e) { // TODO: handle exception } return false; } /** * 获取事业单位列表(用于修改用户信息时,填充下拉列表) */ @Override public List<String> getInstitutionList() { // TODO Auto-generated method stub return userMapper.getInstitutionList(); } /****************************************/ public int add(User user){ return userMapper.add(user); } public int delete(int id){ return userMapper.delete(id); } @Override public User checkUserExist(User user) { // TODO Auto-generated method stub return userMapper.getUserByUserCode(user); } }
package service; import config.ConfigurationFile; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; import java.util.Random; import java.util.stream.Collectors; /** * @author Zimi Li */ public class PasswordService { public static String generatePassword() { return new Random().ints(ConfigurationFile.PASSWORD_LENGTH, 33, 122) .mapToObj(c -> String.valueOf((char) c)).collect(Collectors.joining()); } public static void sendMail(String to, String password) { String from = ConfigurationFile.EMAIL_USERNAME; String host = "smtp.gmail.com"; Properties properties = System.getProperties(); properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", 465); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(ConfigurationFile.EMAIL_USERNAME, ConfigurationFile.EMAIL_PASSWORD); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Welcome to Expense Reimbursement System"); message.setText("Thanks for registering Expense Reimbursement System. Your new password is " + password); Transport.send(message); ConfigurationFile.EMAIL_LOGGER.info("Sent message successfully to " + to); ConfigurationFile.EMAIL_LOGGER.info("Password: " + password); } catch (MessagingException e) { ConfigurationFile.EMAIL_LOGGER.error(e, e.fillInStackTrace()); } } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.common.task.dataspaces; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import org.hibernate.annotations.AccessType; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.Proxy; import org.objectweb.proactive.annotation.PublicAPI; /** * OutputSelector is a couple of {@link FileSelector} and {@link OutputAccessMode} * * @author The ProActive Team * @since ProActive Scheduling 1.1 */ @PublicAPI @Entity @Table(name = "OUTPUT_SELECTOR") @AccessType("field") @Proxy(lazy = false) @XmlAccessorType(XmlAccessType.FIELD) public class OutputSelector implements Serializable { /** */ private static final long serialVersionUID = 31L; @Id @GeneratedValue @XmlTransient protected long hId; @Cascade(CascadeType.ALL) @OneToOne(fetch = FetchType.EAGER, targetEntity = FileSelector.class) private FileSelector outputFiles = null; @Column(name = "OUTPUT_MODE") private OutputAccessMode mode; public OutputSelector() { } /** * Create a new instance of OutputSelector * * @param outputFiles * @param mode */ public OutputSelector(FileSelector outputFiles, OutputAccessMode mode) { this.outputFiles = outputFiles; this.mode = mode; } /** * Get the outputFiles * * @return the outputFiles */ public FileSelector getOutputFiles() { return outputFiles; } /** * Set the outputFiles value to the given outputFiles value * * @param outputFiles the outputFiles to set */ public void setOutputFiles(FileSelector outputFiles) { this.outputFiles = outputFiles; } /** * Get the mode * * @return the mode */ public OutputAccessMode getMode() { return mode; } /** * Set the mode value to the given mode value * * @param mode the mode to set */ public void setMode(OutputAccessMode mode) { this.mode = mode; } /** * Return a string representation of this selector. */ public String toString() { return "(" + this.mode + "-" + this.outputFiles + ")"; } }
package com.jgw.supercodeplatform.trace.dto.template; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value = "注意前面带**-字段,溯源功能-溯源节点删除") public class TraceFunTemplateconfigDeleteParam { @ApiModelProperty(value = "溯源模板id",required=true) private String traceTemplateId; //溯源模板号 @ApiModelProperty(value = "节点对应的功能id",required=true) private String nodeFunctionId; //功能ID号 @ApiModelProperty(value = "节点对应的功能id",hidden=true) private String orgnazitionId; //功能ID号 public String getTraceTemplateId() { return traceTemplateId; } public void setTraceTemplateId(String traceTemplateId) { this.traceTemplateId = traceTemplateId; } public String getNodeFunctionId() { return nodeFunctionId; } public void setNodeFunctionId(String nodeFunctionId) { this.nodeFunctionId = nodeFunctionId; } public String getOrgnazitionId() { return orgnazitionId; } public void setOrgnazitionId(String orgnazitionId) { this.orgnazitionId = orgnazitionId; } }
package com.zundrel.ollivanders.api.registries; import com.zundrel.ollivanders.api.OllivandersAPI; import com.zundrel.ollivanders.api.spells.ISpell; import com.zundrel.ollivanders.api.spells.Spell; import net.minecraft.util.Identifier; import net.minecraft.util.registry.DefaultedRegistry; import net.minecraft.util.registry.MutableRegistry; import net.minecraft.util.registry.Registry; public class SpellRegistry { public static DefaultedRegistry<Spell> SPELL = register("spell", new DefaultedRegistry<>("accio")); private static <T, R extends MutableRegistry<T>> R register(String string_1, R mutableRegistry_1) { Identifier identifier_1 = new Identifier(OllivandersAPI.MODID, string_1); return Registry.REGISTRIES.add(identifier_1, mutableRegistry_1); } public static ISpell findSpell(String name) { return SPELL.stream().filter(it -> it.getName().equals(name)).findAny().orElse(null); } public static ISpell findSpell(Spell spell) { return SPELL.stream().filter(it -> it.getName().equals(spell.getName())).findAny().orElse(null); } public static boolean isSpellVerbal(String verbalName) { return findSpellVerbal(verbalName) != null; } public static ISpell findSpellVerbal(String verbalName) { return SPELL.stream().filter(it -> it.getVerbalName().equals(verbalName)).findAny().orElse(null); } }
package com.harry; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class QueueApp extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view) { Queue queue = new Queue(5); queue.insert(10); queue.insert(20); queue.insert(30); queue.insert(40); queue.remove(); queue.remove(); queue.remove(); queue.insert(50); queue.insert(60); queue.insert(70); queue.insert(80); while (!queue.isEmpty()) { long n = queue.remove(); Log.d("test", String.valueOf(n)); } } }
package cn.edu.cqut.service; import cn.edu.cqut.entity.Menu; import java.util.List; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author CQUT SE 2020 * @since 2020-06-10 */ public interface IMenuService extends IService<Menu> { public List<Menu> selectFirstMenu(Integer parentId); }
package com.ants.theantsgo.base; import android.content.Intent; import android.os.Bundle; import com.lzy.okgo.model.Progress; import com.lzy.okgo.model.Response; import java.util.Map; /** * ===============Txunda=============== * 作者:DUKE_HwangZj * 日期:2017/6/6 0006 * 时间:17:32 * 描述:MVP模式所有的View的顶级接口(父接口) * ===============Txunda=============== */ public interface BaseView { void showDialog(); void showDialog(String text); void showContent(); void removeDialog(); void removeContent(); /** * API调用中的回调方法 * * @param progress 进度 */ void uploadProgress(Progress progress); /** * API调用成功后返回值以json对象方式通知监听器 * * @param requestUrl 链接 * @param jsonStr BaseMode */ void onComplete(String requestUrl, String jsonStr); /** * 带返回链接的错误 * * @param requestUrl 接口连接 * @param error BaseMode */ void OnError(String requestUrl, Map<String, String> error); /** * 出现网络问题等未知异常时会回调此方法 * * @param response 错误返回值 */ void onException(Response response); /** * 下载进度 * * @param progress 进度 */ void downloadProgress(Progress progress); /** * 提示错误信息 * * @param message 信息 */ void showErrotTip(String message); /** * 启动一个不传值的Activity * * @param className 跳转到的Activity */ void startActivity(Class<?> className); /** * 启动一个Activity * * @param className 将要启动的Activity的类名 * @param options 传到将要启动Activity的Bundle,不传时为null */ void startActivity(Class<?> className, Bundle options); void startActivityForResult(Class<?> className, int requestCode); /** * 启动一个有会返回值的Activity * * @param className 将要启动的Activity的类名 * @param options 传到将要启动Activity的Bundle,不传时为null * @param requestCode 请求码 */ void startActivityForResult(Class<?> className, Bundle options, int requestCode); }
package com.logzc.webzic.orm.table; import com.logzc.webzic.orm.field.ColumnStrategy; import com.logzc.webzic.orm.field.ColumnType; import java.lang.reflect.Field; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by lishuang on 2016/8/23. */ public class TableInfo<T, ID> { private final Class<T> tableClass; private String tableName; private ColumnStrategy columnStrategy; protected ColumnType[] columnTypes; protected String[] columnNames; private ColumnType idColumnType; public TableInfo(Class<T> tableClass) throws SQLException { this.tableClass = tableClass; initBasicInfo(); initColumnInfo(); } //get the table name from Class. public void initBasicInfo() { Table table = this.tableClass.getAnnotation(Table.class); if (table != null) { this.columnStrategy = table.columnStrategy(); if (table.name().length() > 0) { this.tableName = table.name(); } else { this.tableName = this.tableClass.getSimpleName().toLowerCase(); } } else { this.columnStrategy = ColumnStrategy.CAMEL_TO_UNDERSCORE; this.tableName = this.tableClass.getSimpleName().toLowerCase(); } } private void initColumnInfo() throws SQLException { List<ColumnType> columnTypeList = new ArrayList<>(); //not only self but also super father. for (Class<?> classWalk = this.tableClass; classWalk != null; classWalk = classWalk.getSuperclass()) { for (Field field : classWalk.getDeclaredFields()) { ColumnType columnType = ColumnType.create(field, this.columnStrategy); if (columnType != null) { columnTypeList.add(columnType); } } } if (columnTypeList.isEmpty()) { throw new IllegalArgumentException("No columns configured."); } this.columnTypes = columnTypeList.toArray(new ColumnType[columnTypeList.size()]); //find the id column. for (ColumnType columnType : this.columnTypes) { if (columnType.isId()) { if (idColumnType == null) { idColumnType = columnType; } else { throw new SQLException("multi id for column defined."); } } } //init the columnNames. columnNames = new String[this.columnTypes.length]; for (int i = 0; i < this.columnTypes.length; i++) { ColumnType columnType = this.columnTypes[i]; columnNames[i] = columnType.getName(); } } public Object[] getColumnValues(T entity) throws SQLException { int length = this.columnTypes.length; Object[] objects = new Object[length]; for (int i = 0; i < length; i++) { ColumnType columnType = this.columnTypes[i]; objects[i] = columnType.getValue(entity); } return objects; } public Class<T> getTableClass() { return tableClass; } public ColumnType getIdColumnType() { return idColumnType; } public String getTableName() { return tableName; } public ColumnType[] getColumnTypes() { return columnTypes; } public T createEntity() throws SQLException { try { return this.tableClass.newInstance(); } catch (Exception e) { throw new SQLException("You must define constructor without parameters."); } } @SuppressWarnings("unchecked") public ID getIdValue(T entity) throws SQLException { if (idColumnType == null) { return null; } else { return (ID) idColumnType.getValue(entity); } } public ColumnType getColumnType(String name) throws SQLException { if(name!=null){ name=name.toLowerCase(); for (ColumnType columnType : this.columnTypes) { if (columnType.getName().equals(name)) { return columnType; } } } throw new SQLException("No such column named \""+name+"\" in table \""+tableName+"\"."); } public String[] getColumnNames() { return columnNames; } }
/** * Created with IntelliJ IDEA. * User: dexctor * Date: 13-1-2 * Time: 下午1:53 * To change this template use File | Settings | File Templates. */ public class MyDepthFirstOrder { private EdgeWeightedDigraph G; private Stack<Integer> reversePost; private Queue<Integer> pre; private Queue<Integer> post; private boolean[] marked; public MyDepthFirstOrder(EdgeWeightedDigraph G) { this.G = G; reversePost = new Stack<Integer>(); pre = new Queue<Integer>(); post = new Queue<Integer>(); marked = new boolean[G.V()]; for(int i =0 ;i < G.V(); ++i) { if(!marked[i]) dfs(i); } } private void dfs(int v) { marked[v] = true; pre.enqueue(v); for(DirectedEdge e: G.adj(v)) { int w = e.to(); if(!marked[w]) dfs(w); } post.enqueue(v); reversePost.push(v); } public Iterable<Integer> reversePost() { return reversePost; } public Iterable<Integer> pre() { return pre; } public Iterable<Integer> post() { return post; } }
package com.xiaotian.framework.util; import android.app.NotificationManager; import android.content.Context; /** * @version 1.0.0 * @author Administrator * @name UtilNotification * @description 后台通知 * @date 2015-6-17 * @link gtrstudio@qq.com * @copyright Copyright © 2010-2015 小天天 Studio, All Rights Reserved. */ public class UtilNotification extends com.xiaotian.frameworkxt.android.util.UtilNotification { private Context mContext; private NotificationManager mNotificationManager;; public UtilNotification(Context context) { super(context); mContext = context; mNotificationManager = getNotificationManager(); } }
package com.beike.service.cps.tuan360; import java.util.List; import java.util.Map; /** * project:beiker * Title:团360CPS * Description: * Copyright:Copyright (c) 2012 * Company:Sinobo * @author qiaowb * @date Aug 9, 2012 2:34:40 PM * @version 1.0 */ public interface CPSTuan360Service { /** * 支付前保存商品订单数据 * @param listOrderParams * @return */ public int saveOrderNoPay(Map<String, Object> params); /** * 支付成功后更新商品订单状态 * @param trxOrderId * @param newStatus * @param oldStatus * @return */ public int updateOrderStatus(Long trxOrderId, int newStatus, int oldStatus); /** * 通过商品订单号查询CPS订单 * @param lstOrderIds * @param maxCount * @return */ public List<Map<String,Object>> queryOrdersByOrderId(List<Long> lstOrderIds, int maxCount); /** * 通过商品订单创建时间查询CPS订单 * @param startTime * @param endTime * @param lastOrderId * @param maxCount * @return */ public List<Map<String,Object>> queryOrdersByCreateTime(String startTime, String endTime, Long lastOrderId, int maxCount); /** * 通过商品订单最后更新时间查询CPS订单 * @param startTime * @param endTime * @param lastOrderId * @param maxCount * @return */ public List<Map<String,Object>> queryOrdersByUpdTime(String updStartTime, String updEndTime, Long lastOrderId, int maxCount); /** * 通过商品订单创建时间查询对账月份CPS订单 * @param billMonth * @param lastOrderId * @param maxCount * @return */ public List<Map<String,Object>> queryOrdersByBillMonth(String billMonth, Long lastOrderId, int maxCount); /** * 订单退款 * @param trxGoodsId * @return */ public int cancelOrder(Long trxGoodsId); }
package com.hg.sb_helloworld.web; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import io.swagger.annotations.ApiOperation; @Controller @RequestMapping( "/" ) public class IndexController { @ApiOperation( value = "首页", notes = "" ) @RequestMapping( value = "/index", method = RequestMethod.GET ) public String index( ModelMap map ) { map.put( "key", "hugui spring boot test" ); return "index"; } @ApiOperation( value = "错误首页", notes = "" ) @RequestMapping( value = "/indexError", method = RequestMethod.GET ) public String indexError( ModelMap map ) throws Exception { throw new Exception( "The is a test error page" ); } }
import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); private static PDDocument pdDocument = null; private static String destinationFolder = "D:\\Work\\PDF_POC\\public\\savePdf"; public static void main(String[] args) throws IOException { boolean quit = false; int choice = 0; System.out.println("Please Enter\n" + "0 - Exit\n" + "1 - Split\n" + "2 - Merge"); while (!quit) { choice = scanner.nextInt(); scanner.nextLine(); switch (choice) { case 0: quit = true; break; case 1: splitPDFFile(); break; case 2: mergePDFFiles(); break; } } } private static void mergePDFFiles() throws IOException { int choice = 0; boolean quit = false; List<String> listFileNames = new ArrayList<String>(); PDFMergerUtility mergerUtility = new PDFMergerUtility(); System.out.println("Please Enter\n" + "0 - Exit\n" + "1 - Add fileName"); while (!quit){ choice = scanner.nextInt(); scanner.nextLine(); switch (choice){ case 0: quit = true; break; case 1: System.out.println("Please enter the absolute file path - "); String absoluteFilePath = scanner.nextLine(); listFileNames.add(absoluteFilePath); break; } } mergerUtility.setDestinationFileName(destinationFolder + File.separator + "Merged_PDF_File.pdf"); for (String strFileName:listFileNames){ mergerUtility.addSource(new File(strFileName)); } mergerUtility.mergeDocuments(); System.out.println("Documents Merged"); } private static PDDocument splitPDFFile() throws IOException { PDDocument documentFinal = new PDDocument(); System.out.println("Enter the absolute file path to split - "); String sourceFilePath = scanner.nextLine(); File sourceFile = new File(sourceFilePath); pdDocument = PDDocument.load(sourceFile); System.out.println(sourceFile.getName() + " is of " + pdDocument.getNumberOfPages() + "pages."); System.out.println("Enter fromPageNumber - "); int fromPageNumber = scanner.nextInt(); System.out.println("Enter toPageNumber - "); int toPageNumber = scanner.nextInt(); if (fromPageNumber>=1 && (toPageNumber>=1 || toPageNumber<=pdDocument.getNumberOfPages())){ for (int i = fromPageNumber - 1; i < toPageNumber; i++) { PDPage page = pdDocument.getPage(i); documentFinal.addPage(page); } String strFinal = destinationFolder + File.separator + fromPageNumber + "-" + toPageNumber + "_" + sourceFile.getName(); documentFinal.save(strFinal); System.out.println("File successfully created. Path - " + strFinal); documentFinal.close(); return documentFinal; }else { System.out.println("Please enter fromPageNumber and toPageNumber from the specified range."); return null; } } }
package com.pwq.mavenT; import java.util.ArrayList; import java.util.List; /** * Created by BF100500 on 2017/3/22. */ public class copy { public static void main(String[] args) { List<Integer> tmp = new ArrayList(); for(int i=0;i<10;i++){ tmp.add(i); } System.out.println("start"); for(Integer j:tmp){ System.out.println(j); tmp.add(j); } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class CardsGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List<Integer> firstPlayerDeck = Arrays.stream(scanner.nextLine().split("\\s+")).map(Integer::parseInt).collect(Collectors.toList()); List<Integer> secondPlayerDeck = Arrays.stream(scanner.nextLine().split("\\s+")).map(Integer::parseInt).collect(Collectors.toList()); int steps = 0; int firstPlayerPoints = 0; int secondPlayerPoints = 0; int winner = 0; while (firstPlayerDeck.size() != 0 && secondPlayerDeck.size() != 0){ int i = 0; if (firstPlayerDeck.get(i) > secondPlayerDeck.get(i)){ firstPlayerPoints += (firstPlayerDeck.get(i) + secondPlayerDeck.get(i)); firstPlayerDeck.add(firstPlayerDeck.size(), firstPlayerDeck.get(i)); firstPlayerDeck.add(firstPlayerDeck.size(), secondPlayerDeck.get(i)); firstPlayerDeck.remove(i); secondPlayerDeck.remove(i); }else if(secondPlayerDeck.get(i) > firstPlayerDeck.get(i)){ secondPlayerPoints += (firstPlayerDeck.get(i) + secondPlayerDeck.get(i)); secondPlayerDeck.add(secondPlayerDeck.size(), secondPlayerDeck.get(i)); secondPlayerDeck.add(secondPlayerDeck.size(), firstPlayerDeck.get(i)); firstPlayerDeck.remove(i); secondPlayerDeck.remove(i); }else { secondPlayerDeck.remove(i); firstPlayerDeck.remove(i); } } if (firstPlayerPoints > secondPlayerPoints){ for (int n : firstPlayerDeck) { winner += n; } System.out.println("First player wins! Sum: "+winner); }else{ for (int n : secondPlayerDeck) { winner += n; } System.out.println("Second player wins! Sum: "+winner); } } }
package com.useradmin.framework.config.routes; import com.demo.blog.BlogController; import com.demo.index.IndexController; import com.jfinal.config.Routes; import live.autu.plugin.jfinal.swagger.controller.SwaggerController; public class UserAdminRoutes extends Routes { @Override public void config() { // 配置默认的ViewPath setBaseViewPath("/WEB-INF/view"); // 配置swagger的路由 add("/swagger", SwaggerController.class); // add("/", IndexController.class, "/wp"); // 第三个参数为该Controller的视图存放路径 add("/blog", BlogController.class); // 第三个参数省略时默认与第一个参数值相同,在此即为 "/blog" } }
package net.lantrack.framework.core.util; /** * 随机生成4,5,6位数字 * * @author coolcjava */ public class NumUtil { /** * 随机生成4位数字 * * @return */ public static int randomFour() { return (int) ((Math.random() * 9 + 1) * 1000); } /** * 随机生成5位数字 * * @return */ public static int randomFive() { return (int) ((Math.random() * 9 + 1) * 10000); } /** * 随机生成6位数字 * * @return */ public static int randomSix() { return (int) ((Math.random() * 9 + 1) * 100000); } }
package dwz.persistence.mapper; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; import dwz.dal.BaseMapper; import dwz.persistence.BaseConditionVO; import sop.persistence.beans.Order; import sop.persistence.beans.ProductItem; /** * @Author: LCF * @Date: 2020/1/8 17:28 * @Package: dwz.persistence.mapper */ @Repository public interface ProductItemMapper extends BaseMapper<Order, Integer> { List<ProductItem> findPageBreakByCondition(BaseConditionVO vo, RowBounds rb); Integer findNumberByCondition(BaseConditionVO vo); }
/* * Copyright 2002-2021 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.expression.spel.support; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.springframework.core.MethodParameter; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; import org.springframework.expression.ConstructorExecutor; import org.springframework.expression.ConstructorResolver; import org.springframework.expression.EvaluationContext; import org.springframework.expression.EvaluationException; import org.springframework.expression.TypeConverter; import org.springframework.lang.Nullable; /** * A constructor resolver that uses reflection to locate the constructor that should be invoked. * * @author Andy Clement * @author Juergen Hoeller * @since 3.0 */ public class ReflectiveConstructorResolver implements ConstructorResolver { /** * Locate a constructor on the type. There are three kinds of match that might occur: * <ol> * <li>An exact match where the types of the arguments match the types of the constructor * <li>An in-exact match where the types we are looking for are subtypes of those defined on the constructor * <li>A match where we are able to convert the arguments into those expected by the constructor, according to the * registered type converter. * </ol> */ @Override @Nullable public ConstructorExecutor resolve(EvaluationContext context, String typeName, List<TypeDescriptor> argumentTypes) throws AccessException { try { TypeConverter typeConverter = context.getTypeConverter(); Class<?> type = context.getTypeLocator().findType(typeName); Constructor<?>[] ctors = type.getConstructors(); Arrays.sort(ctors, Comparator.comparingInt(Constructor::getParameterCount)); Constructor<?> closeMatch = null; Constructor<?> matchRequiringConversion = null; for (Constructor<?> ctor : ctors) { int paramCount = ctor.getParameterCount(); List<TypeDescriptor> paramDescriptors = new ArrayList<>(paramCount); for (int i = 0; i < paramCount; i++) { paramDescriptors.add(new TypeDescriptor(new MethodParameter(ctor, i))); } ReflectionHelper.ArgumentsMatchInfo matchInfo = null; if (ctor.isVarArgs() && argumentTypes.size() >= paramCount - 1) { // *sigh* complicated // Basically.. we have to have all parameters match up until the varargs one, then the rest of what is // being provided should be // the same type whilst the final argument to the method must be an array of that (oh, how easy...not) - // or the final parameter // we are supplied does match exactly (it is an array already). matchInfo = ReflectionHelper.compareArgumentsVarargs(paramDescriptors, argumentTypes, typeConverter); } else if (paramCount == argumentTypes.size()) { // worth a closer look matchInfo = ReflectionHelper.compareArguments(paramDescriptors, argumentTypes, typeConverter); } if (matchInfo != null) { if (matchInfo.isExactMatch()) { return new ReflectiveConstructorExecutor(ctor); } else if (matchInfo.isCloseMatch()) { closeMatch = ctor; } else if (matchInfo.isMatchRequiringConversion()) { matchRequiringConversion = ctor; } } } if (closeMatch != null) { return new ReflectiveConstructorExecutor(closeMatch); } else if (matchRequiringConversion != null) { return new ReflectiveConstructorExecutor(matchRequiringConversion); } else { return null; } } catch (EvaluationException ex) { throw new AccessException("Failed to resolve constructor", ex); } } }
package com.joalib.board.action; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.joalib.DTO.ActionForward; import com.joalib.DTO.BoardDTO; import com.joalib.board.svc.BoardModifyFormService; public class BoardModifyFormAction implements dbAction { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; ServletContext context = request.getServletContext(); int board_no= Integer.parseInt(request.getParameter("board_num")); BoardModifyFormService mdifyForm = new BoardModifyFormService(); BoardDTO article = mdifyForm.modifyFormArticle(board_no); //넘버로 조회한 게시물데이터 article에 넣었음 request.setAttribute("article", article); forward = new ActionForward(); // forward.setRedirect(true); forward.setPath("board_update_page.jsp"); return forward; } }
/** * */ package com.oriaxx77.javaplay.gof.flyweight; import com.oriaxx77.javaplay.gof.GofExample; /** * A Weapon that uses the flyweight {@link Model} objects. * Many weapon can have the same animations. * @author BagyuraI * */ @GofExample(pattern="Flyweight", stereotype="Client") public class Weapon { /** * Name of the weapon. */ private String name; /** * Model of the weapon. It will provide the visuals and animations for the weapon. */ private Model model; /** * Creates a unique weapon. * @param name Name of the weapon. * @param model Model of the weapon. A weapon can share model with other weapons but * can have different statistics. The model will provide the visuals of the weapon. */ public Weapon( String name, Model model ) { this.name = name; this.model = model; } /** * Attack animation of the weapon. It will delegate it to the {@link Model#animate(LightCondition)} * The animation depends on the light conditions. This is coming from the context. * @param lights Light conditions. */ public void attack( LightCondition lights ) { System.out.println("Attacking with " + name ); model.animate( lights ); } }
package com.codingchili.instance.model.entity; import com.codingchili.instance.context.Ticker; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author Robin Duda * <p> * A grid to map entities onto a spatially hashed map. * * Backed by hashmaps which introduce a lot of garbage on each * update. Additionally there's no reverse lookups so the grid * is cleared on every tick. */ public class HashGrid<T extends Entity> implements Grid<T> { private static final int CELL_SIZE = 256; private ConcurrentHashMap<String, T> entities = new ConcurrentHashMap<>(); private volatile Map<Integer, List<T>> cells = new HashMap<>(); private AreaSelector<T> selector; private int width; /** * @param size the size of the grid in px of the longest axis. */ public HashGrid(int size) { this.width = size; this.selector = new AreaSelector<>(this, CELL_SIZE); } @Override public HashGrid<T> update(Ticker ticker) { Map<Integer, List<T>> buffer = new HashMap<>(); entities.values().forEach((entity) -> { entity.getVector().cells(CELL_SIZE, width).forEach(id -> { List<T> list = buffer.computeIfAbsent(id, key -> new ArrayList<>()); list.add(entity); }); }); Map<Integer, List<T>> tmp = cells; cells = buffer; tmp.clear(); return this; } @Override public HashGrid<T> add(T entity) { entities.put(entity.getId(), entity); return this; } @Override public HashGrid<T> remove(String id) { entities.remove(id); return this; } @Override public Collection<T> get(Integer cell) { return cells.get(cell); } @Override public T get(String id) { T entity = entities.get(id); Objects.requireNonNull(entity, String.format("No entity with id '%s' found.", id)); return entities.get(id); } @Override public boolean exists(String id) { return entities.containsKey(id); } @Override public Collection<T> list(int col, int row) { return cells.getOrDefault(col + row * width, Collections.emptyList()); } @Override public Collection<T> all() { return entities.values(); } @Override public Collection<T> translate(int x, int y) { return cells.getOrDefault(x / CELL_SIZE + (y / CELL_SIZE) * width, Collections.emptyList()); } @Override public Collection<T> partition(Vector vector) { // entities can be partitioned into supercells for network updates. return entities.values(); } @Override public Set<T> cone(Vector vector) { return selector.cone(vector); } @Override public Set<T> radius(Vector vector) { return selector.radius(vector); } @Override public Set<T> adjacent(Vector vector) { Set<T> set = new HashSet<>(); vector.cells(CELL_SIZE, width).forEach(bucket -> { set.addAll(cells.getOrDefault(bucket, Collections.emptyList())); }); return set; } @Override public int width() { return width; } }
package egovframework.svt.adm.hom.calendar; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import egovframework.rte.psl.dataaccess.EgovAbstractDAO; @Repository public class AdminCalendarDAO extends EgovAbstractDAO { public List<?> getCalendarList() { return list("adminCalendar.getCalendarList", null); } public void insertCalendar(Map<String, Object> commandMap) { insert("adminCalendar.insertCalendar", commandMap); } @SuppressWarnings("unchecked") public Map<String, String> getCalendarDetail(String trainSeq) { return (Map<String, String>) selectByPk("adminCalendar.getCalendarDetail", trainSeq); } public int updateCalendar(Map<String, Object> commandMap) { return update("adminCalendar.updateCalendar", commandMap); } public int deleteCalendar(Map<String, Object> commandMap) { return delete("adminCalendar.deleteCalendar", commandMap); } public int deleteCalendarPeriodFromCalendar(Map<String, Object> commandMap) { return delete("adminCalendar.deleteCalendarPeriodFromCalendar", commandMap); } public List<?> getCalendarPeriodList(Map<String, Object> commandMap) { return list("adminCalendar.getCalendarPeriodList", commandMap); } public void insertCalendarPeriod(Map<String, Object> commandMap) { insert("adminCalendar.insertCalendarPeriod", commandMap); } @SuppressWarnings("unchecked") public Map<String, String> getCalendarPeriodDetail(String trainSeq) { return (Map<String, String>) selectByPk("adminCalendar.getCalendarPeriodDetail", trainSeq); } public int updateCalendarPeriod(Map<String, Object> commandMap) { return update("adminCalendar.updateCalendarPeriod", commandMap); } public int deleteCalendarPeriod(Map<String, Object> commandMap) { return delete("adminCalendar.deleteCalendarPeriod", commandMap); } public Map<String, String> getCalendarTitle() { return (Map<String, String>) selectByPk("adminCalendar.getCalendarTitle", null); } public int updateCalendarTitle(Map<String, Object> commandMap) { return update("adminCalendar.updateCalendarTitle", commandMap); } }
package com.mittidesign.soundprofiletoggle; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.widget.RemoteViews; public class RingerModeIntentReciever extends BroadcastReceiver { //When the defined Click happens, do this @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.media.RINGER_MODE_CHANGED")) { updateWidgetPictureAndButtonListener(context); } } private void updateWidgetPictureAndButtonListener(Context context) { RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.sound_toggle_layout); remoteViews.setImageViewResource(R.id.img_speaker, getImageToSet(context)); remoteViews.setOnClickPendingIntent(R.id.img_speaker, SoundToggleWidgetProvider.getRefreshPendingIntent(context)); SoundToggleWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews); } private int getImageToSet(Context context) { final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (audioManager.getRingerMode() == 0) { return R.drawable.mute2; } else if (audioManager.getRingerMode() == 1) { return R.drawable.vibra2; } else if (audioManager.getRingerMode() == 2) { return R.drawable.speaker2; } return R.drawable.speaker2; } }
package art4muslim.macbook.rahatydriver.fragments; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import art4muslim.macbook.rahatydriver.R; /** * A simple {@link Fragment} subclass. */ public class ShareWithFriendsFragment extends Fragment { View v; Button btnCopy,btnShare; EditText editText10; boolean isRightToLeft ; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment v = inflater.inflate(R.layout.fragment_share_with_friends, container, false); isRightToLeft = getResources().getBoolean(R.bool.is_right_to_left); getActivity().setTitle(getString(R.string.callfriends)); btnCopy =(Button)v.findViewById(R.id.btnCopie); btnShare =(Button)v.findViewById(R.id.btnShare); editText10 =(EditText)v.findViewById(R.id.editText10); btnCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setClipboard(getActivity(),editText10.getText().toString()); } }); btnShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String shareBody = editText10.getText().toString(); Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.lien_share))); } }); return v; } private void setClipboard(Context context, String text) { Log.e("Copied text","text "+text); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { ClipboardManager clipboard = ( ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text); } else { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text); clipboard.setPrimaryClip(clip); } Toast.makeText(context, "Copied to Clipboard!", Toast.LENGTH_LONG).show(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu(Menu menu) { if (!isRightToLeft ) { menu.findItem(R.id.item_back).setIcon(getResources().getDrawable(R.mipmap.backright)); }else menu.findItem(R.id.item_back).setIcon(getResources().getDrawable(R.mipmap.back)); menu.findItem(R.id.item_back).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { MapCurrentFragment schedule1 = new MapCurrentFragment(); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame,schedule1,"home Fragment"); fragmentTransaction.commit(); return false; } }); super.onPrepareOptionsMenu(menu); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ledungcobra.scenes; import com.ledungcobra.applicationcontext.AppContext; import com.ledungcobra.utils.Navigator; import javax.swing.*; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import static com.ledungcobra.utils.Constants.*; /** * @author ledun */ public class ConfigDatabaseScreen extends Screen { @Override public void onCreateView() { initComponents(); if (getData() == null) throw new IllegalStateException(); String connectionString = (String) getData().get(CONNECTION_STRING); String username = (String) getData().get(USER_NAME); String password = (String) getData().get(PASSWORD); this.connectionStringTextField.setText(connectionString); this.usernameTextField.setText(username); this.passwordTextField.setText(password); } @Override public void addEventListener() { connectBtn.addActionListener(e -> onConnectBtnActionPerform()); } private void onConnectBtnActionPerform() { String connectionString = connectionStringTextField.getText(); String username = usernameTextField.getText(); String password = new String(passwordTextField.getPassword()); if (connectionString == null || connectionString.isEmpty()) { JOptionPane.showMessageDialog(this, "You have to input connection string to continue"); return; } if (username == null || username.isEmpty()) { JOptionPane.showMessageDialog(this, "You have to input username to continue"); return; } if (password == null || password.isEmpty()) { JOptionPane.showMessageDialog(this, "You have to enter password to continue"); return; } AppContext.username = username; AppContext.password = password; AppContext.connectionString = connectionString; writeConfigInfoToDatabase(connectionString, username, password); try { AppContext.build(); new Navigator<LoginScreen>().navigate(700, 300, null); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Cannot establish connection"); } } private void writeConfigInfoToDatabase(String connectionString, String username, String password) { Properties properties = new Properties(); properties.setProperty(CONNECTION_STRING, connectionString); properties.setProperty(USER_NAME, username); properties.setProperty(PASSWORD, password); try (OutputStream os = new FileOutputStream(CONFIG_FILE_NAME)) { properties.store(os, "Used for login to database"); } catch (Exception e) { JOptionPane.showMessageDialog(this, "An error occur when store properties file"); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); usernameTextField = new javax.swing.JTextField(); connectBtn = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); connectionStringTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); passwordTextField = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Config", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N connectBtn.setText("Connect"); jLabel3.setText("Password"); jLabel1.setText("Connection String"); jLabel2.setText("Username"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(connectionStringTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 429, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(usernameTextField) .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 429, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(connectBtn, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(connectionStringTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(connectBtn) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(18, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(16, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold> /** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JButton connectBtn; private javax.swing.JTextField connectionStringTextField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField passwordTextField; private javax.swing.JTextField usernameTextField; // End of variables declaration }
package fr.iutinfo.skeleton.api; import java.util.List; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; public interface EtablissementDao { @SqlUpdate("insert into etablissement (nom,ville) values(:nom ,:ville);") void addEtablissement(@Bind("nom") String nom, @Bind("ville") String ville); void close(); @SqlQuery("select * from etablissement") @RegisterMapper(EtablissementMapper.class) List<Etablissement> getEtablissements(); }
package com.cinema.biz.dao; import java.util.List; import java.util.Map; import com.cinema.biz.model.SimSimulator; import com.cinema.biz.model.base.TSimSimulator; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; public interface SimSimulatorMapper extends Mapper<TSimSimulator>,MySqlMapper<TSimSimulator>{ /**列表*/ List<SimSimulator> getList(Map<String, Object> paraMap); Boolean isParent(String simulatorId); }
package com.liujc.tabfragmentview.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; /** * 类名称:BaseTabAdapter * 创建者:Create by liujc * 创建时间:Create on 2017/4/12 13:43 * 描述:主界面适配器 */ public abstract class BaseTabAdapter { /** * tab数量 */ public abstract int getCount(); /** * tab text 数组 */ public abstract String[] getTabTextArray(); /** * tab icon 数组 */ public abstract int[] getTabIconImgArray(); /** * tab icon 选中 数组 */ public abstract int[] getSelectedTabIconImageArray(); /** * fragment 数组 */ public abstract Fragment[] getFragmentArray(); public abstract FragmentManager getFragmentManager(); }
package com.v1_4.mydiaryapp.com; public class Obj_Device{ public String deviceId = ""; public String deviceModel = ""; public String deviceVersion = ""; public String deviceLatitude = ""; public String deviceLongitude = ""; public String deviceAccuracy = ""; public String deviceConnectionType = ""; public String devicePhoneNumber = ""; public String deviceCarrier = ""; public String deviceCustomId = ""; public int deviceWidth = 0; public int deviceHeight = 0; //getters, setters public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getDeviceModel() { return deviceModel; } public void setDeviceModel(String deviceModel) { this.deviceModel = deviceModel; } public String getDeviceVersion() { return deviceVersion; } public void setDeviceVersion(String deviceVersion) { this.deviceVersion = deviceVersion; } public String getDeviceLatitude() { return deviceLatitude; } public void setDeviceLatitude(String deviceLatitude) { this.deviceLatitude = deviceLatitude; } public String getDeviceLongitude() { return deviceLongitude; } public void setDeviceLongitude(String deviceLongitude) { this.deviceLongitude = deviceLongitude; } public String getDeviceAccuracy() { return deviceAccuracy; } public void setDeviceAccuracy(String deviceAccuracy) { this.deviceAccuracy = deviceAccuracy; } public String getDeviceConnectionType() { return deviceConnectionType; } public void setDeviceConnectionType(String deviceConnectionType) { this.deviceConnectionType = deviceConnectionType; } public String getDevicePhoneNumber() { return devicePhoneNumber; } public void setDevicePhoneNumber(String devicePhoneNumber) { this.devicePhoneNumber = devicePhoneNumber; } public String getDeviceCarrier() { return deviceCarrier; } public void setDeviceCarrier(String deviceCarrier) { this.deviceCarrier = deviceCarrier; } public String getDeviceCustomId() { return deviceCustomId; } public void setDeviceCustomId(String deviceCustomId) { this.deviceCustomId = deviceCustomId; } public int getDeviceWidth() { return deviceWidth; } public void setDeviceWidth(int deviceWidth) { this.deviceWidth = deviceWidth; } public int getDeviceHeight() { return deviceHeight; } public void setDeviceHeight(int deviceHeight) { this.deviceHeight = deviceHeight; } }
package com.mj.courseraprw3.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.mikhaellopez.circularimageview.CircularImageView; import com.mj.courseraprw3.Adapter.ProfileAdapter; import com.mj.courseraprw3.R; import com.mj.courseraprw3.pets; import java.util.ArrayList; import java.util.Random; /** * A simple {@link Fragment} subclass. */ public class PerfilFragment extends Fragment { ArrayList<pets> myPetList, mojo; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private Random random; private TextView PetName; private CircularImageView PetPic; public PerfilFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_perfil, container, false); setMojo(); setData(0); mRecyclerView = (RecyclerView) v.findViewById(R.id.rcvMyPetMatrix); mRecyclerView.setHasFixedSize(true); PetName = (TextView) v.findViewById(R.id.actvProfilePetName); PetPic = (CircularImageView) v.findViewById(R.id.civProfilePhoto); PetName.setText(mojo.get(0).getName()); PetPic.setImageResource(mojo.get(0).getPicture()); mLayoutManager = new GridLayoutManager(getActivity(),3); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new ProfileAdapter(myPetList); mRecyclerView.setAdapter(mAdapter); return v; } public void setData(int element) { int maxPic = 0; random = new Random(); myPetList = new ArrayList<>(); maxPic = random.nextInt(20); for(int i=0; i < maxPic; i++ ) { myPetList.add(new pets(mojo.get(element).getId(), mojo.get(element).getName(),random.nextInt(10), mojo.get(element).getPicture())); } } public void receiveEle(int element){ PetName.setText(mojo.get(element).getName()); PetPic.setImageResource(mojo.get(element).getPicture()); myPetList.clear(); setData(element); mRecyclerView.setAdapter(new ProfileAdapter(myPetList)); mRecyclerView.invalidate(); } void setMojo (){ mojo = new ArrayList<>(); mojo.add(new pets(1,"Beary",1, R.drawable.bear)); mojo.add(new pets(2,"Beavery",2, R.drawable.beaver)); mojo.add(new pets(3,"Caty",3, R.drawable.cat)); mojo.add(new pets(4,"Cowy",4, R.drawable.cow)); mojo.add(new pets(5,"Doggy",5, R.drawable.dog)); mojo.add(new pets(6,"Elephanty",6, R.drawable.elephant)); mojo.add(new pets(7,"Goaty",7, R.drawable.goat)); mojo.add(new pets(8,"Horsy",8, R.drawable.horse)); mojo.add(new pets(9,"Jiraffy",9, R.drawable.jiraff)); mojo.add(new pets(10,"Lamby",10, R.drawable.lamb)); mojo.add(new pets(11,"Monkey",11, R.drawable.monkey)); mojo.add(new pets(12,"Moosy",12, R.drawable.moose)); mojo.add(new pets(13,"Owly",13, R.drawable.owl)); mojo.add(new pets(14,"Pandy",14, R.drawable.panda)); mojo.add(new pets(15,"Piggy",15, R.drawable.pig)); mojo.add(new pets(16,"Ramy",16, R.drawable.ram)); mojo.add(new pets(17,"Rhiny",17, R.drawable.rhino)); mojo.add(new pets(18,"Tiggy",18, R.drawable.tiger)); mojo.add(new pets(19,"Turkky",19, R.drawable.turkey)); mojo.add(new pets(20,"Zebry",20, R.drawable.zebra)); } }
package cn.zhjb.service.impl; import cn.zhjb.dao.UserDao; import cn.zhjb.dao.impl.UserDaoImpl; import cn.zhjb.pojo.User; import cn.zhjb.service.UserService; public class UserServiceImpl implements UserService { UserDao userDao = new UserDaoImpl(); @Override public User getUserInfoService(String username, String userpwd) { User user = userDao.getUserInfoDao(username,userpwd); return user; } }
package CommandPattern15.example.service; /** * @Author Zeng Zhuo * @Date 2020/5/5 13:04 * @Describe */ public class WindowHandler { public void minimize(){ System.out.println("将窗口最小化至托盘"); } }
import java.util.*; import java.io.*; /** * Class that represents the Lane as a map, mapping names * of meerkats to their families. * * @author Kody Dangtongdee * @version 2/18/2015 */ public class Lane { private Map<String, Family> map; private int noFamilies; private int noMeerkats; private int maxLocation; /** * Constructor for the Lane of meerkat lane. */ public Lane() { map = new HashMap<String, Family>(); noFamilies = 0; noMeerkats = 0; } /** * Adds the specified meerkat to the given locations, creating a new family. * @param name the name of the meerkat * @param startLoc the beginning location of where the meerkat lives * @param endLoc the end location of where the meerkat lives * @return boolean true if the meerkat was added, otherwise false */ public boolean add(String name, int startLoc, int endLoc) { //If the map already has the meerkat, dont add it if (map.containsKey(name)) { return false; } //If the meerkat has a valid name, dont add it to the lane else if (!Meerkat.validName(name)) { return false; } //If the new end location is greater than the current end, //reset the current end to the new one if (endLoc > maxLocation) { maxLocation = endLoc; } Family fam = new Family(new Meerkat(name), startLoc, endLoc); map.put(name, fam); noFamilies++; noMeerkats++; return true; } /** * Adds the second meerkat to the family of the first one. If * The second meerkat already belongs to a family, or if the first one * is not assigned to a family, an error is reported. * @param name1 the name of the meerkat who's family the second * meerkat will be added to. * @param name2 the name of the meerkat to be added to the first's * family * @return boolean true if the meerkat was added successfuly, * otherwise false */ public boolean addToFamily(String name1, String name2) { Meerkat kat1 = new Meerkat(name1); Meerkat kat2 = new Meerkat(name2); //If the second meerkat already exists, or if the first does not if (map.containsKey(name2) || !map.containsKey(name1)) { //dont add the second meerkat return false; } map.get(name1).addToFamily(kat2); map.put(name2, map.get(name1)); noMeerkats++; return true; } /** * Removes the specified meerkat from the map. * @param name the name of the meerkat to be removed * @return boolean true if the meerkat was found and removed, * otherwise false */ public boolean remove(String name) { //If the meerkat exists if (map.containsKey(name)) { //remove them from the lane map.get(name).remove(name); map.remove(name); return true; } return false; } /** * Returns information about the specified meerkat's family. * @param name the name of the meerkat * @return String the information about the meerkat's family * in the format "x1 x2 : name1 name2" */ public String lookup(String name) { String info = ""; //If the lane contains the meerkat if (map.containsKey(name)) { //retrieve the family info Family fam = map.get(name); info = fam.info(); } return info; } /** * Clears all the meerkats from the Lane. */ public void clear() { map.clear(); noMeerkats = 0; noFamilies = 0; } /** * Returns the number of meerkats in the lane. * @return int the number of meerkats that live in Meerkat Lane */ public int size() { return noMeerkats; } /** * Returns an iterator over the locations in the lane, * in which the items being iterated are Strings formatted * to the problem specification. * @return Iterator<String> the iterator over the locations */ public Iterator<String> iterator() { Collection<String> list = new ArrayList<String>(); ArrayList<Family> tempList = new ArrayList<Family>(); String line = ""; String temp = ""; String names = ""; //If the lane is not empty if (!isEmpty()) { //for all the locations in the lane for (int index = 1; index < maxLocation; index++) { line = ""; temp = ""; Set<Family> famSet = new HashSet<Family>(map.values()); //for every family that lives in the lane for (Family fam : famSet) { //if a family has members at the location if (fam.hasMembers(index)) { tempList.add(fam); } } tempList = sort(tempList); line = names(tempList); list.add(line); tempList.clear(); } } return list.iterator(); } /** * Returns a compressed version of all the mappings in the lane. * @return List<String> a list of the compressed mappings */ public List<String> getCompressed() { List<String> comp = new ArrayList<String>(); ArrayList<Family> families = new ArrayList<Family>(); Set<Family> famSet = new HashSet<Family>(map.values()); //for every location in the lane for (int index = 1; index < maxLocation; index++) { //for each family in the lane for (Family fam : famSet) { //if a family has members at this location if (fam.hasMembers(index)) { families.add(fam); } } //if there were families in the location if (families.size() > 0) { families = sort(families); String names = names(families); String range = ""; int start = index; int end = getRange(families, index); index = end; //if the compressed line only occupies one location if (start == end) { range = " " + start; } else { range = start + "-" + end; } comp.add(range + names); families.clear(); } } return comp; } /** * Determines the end of the range of compressed lines * in the lane. * @param fams the list of families in the location * @param index the location of the lane */ private int getRange(List<Family> fams, int index) { int max = fams.get(fams.size() - 1).getEnd(); int start = index; int end = start; //for every location occupied by meerkats in this list for (int jIndex = index; jIndex < max; jIndex++) { //for each family that may occupy that locaation for (Family fam : fams) { //if they do not have members, the end of the //range has been found if (!fam.hasMembers(jIndex)) { index = jIndex - 1; end = jIndex - 1; } } } return end; } /** * Sorts the families in the array list, based on the requirments. * @param fams the list of families * @return ArrayList<Family> the sorted list */ private ArrayList<Family> sort(ArrayList<Family> fams) { //bubble sort, starting at the end of the list for (int index = fams.size(); index >= 0; index--) { //comparing items at end with ones in the beginning for (int jIndex = 0; jIndex < fams.size() - 1; jIndex++) { //If a swap needs to take place if (fams.get(jIndex).getStart() > fams.get(jIndex + 1).getStart()) { Family temp = fams.get(jIndex); fams.set(jIndex, fams.get(jIndex + 1)); fams.set(jIndex + 1, temp); } else if (fams.get(jIndex).getStart() == fams.get(jIndex + 1).getStart()) { //If a swap needs to take place if (fams.get(jIndex).getEnd() < fams.get(jIndex + 1).getEnd()) { Family temp = fams.get(jIndex); fams.set(jIndex, fams.get(jIndex + 1)); fams.set(jIndex + 1, temp); } } } } return fams; } /** * Returns the string representation of the names * of the members of the list of families. * * @param fams the list of families * @return String the names of the members */ private String names(List<Family> fams) { String names = ""; for (Family fam : fams) { System.out.println(fam.getNames()); names += " :" + fam.getNames(); } return names; } /** * Loads a file containing meerkats, and adds them to the list. * @param fileName the name of the file from which the meerkats * are to be imported from * @throws FileNotFoundException */ public void loadFile(String fileName) throws FileNotFoundException { //try to load the file, if no file is found, throw //a FileNotFoundException try { File file = new File(fileName); Scanner in = new Scanner(file); in.useDelimiter("> \\s+"); in.nextLine(); //While there are still lines in the file while (in.hasNext()) { boolean added = false; in.useDelimiter("-"); int start = in.nextInt(); in.useDelimiter(" "); int end = in.nextInt(); String name = in.nextLine().trim(); //for each family in the lane for (Family fam : map.values()) { //if a meerkat in the file has the same range as a family if (fam.sameFamily(start, end)) { //add the meerkat to the family fam.addToFamily(new Meerkat(name)); added = true; noMeerkats++; } } //If the meerkat was not added to a family if (!added) { //add them to the lane, making a new family add(name, start, end); } } } catch (IOException e) { throw new FileNotFoundException(); } } /** * Returns a list of the meerkats in the lane, in alphabetical order. * @return List<String> the list of meerkats in the lane */ public List<String> listMembers() { ArrayList<String> list = new ArrayList<String>(); String temp = "a"; //For each meerkat from the set of meerkats in the lane for (String name : map.keySet()) { //Add their name, plus their start and end locations list.add(name + " " + map.get(name).getStart() + " " + map.get(name).getEnd()); } //sort the list alphabetically List<String> subList = list.subList(0, list.size()); Collections.sort(subList); return list; } /** * Determines if the meerkat exists in the lane. * @param name the name of the meerkat being searched for * @return boolean true if the meerkat is in the lane, * otherwise false */ public boolean contains(String name) { return map.containsKey(name); } /** * Determine if the lane is empty. * @return boolean true if the lane is empty, otherwise false */ public boolean isEmpty() { return map.isEmpty(); } }
package de.niklaskiefer.bnclCore.parser; import de.niklaskiefer.bnclCore.BPMNModelBuilder; import org.camunda.bpm.model.bpmn.instance.SequenceFlow; import java.util.List; /** * @author Niklas Kiefer */ public class BnclSequenceFlowParser extends AbstractBnclParser { public static final String SEQUENCE_FLOW_KEYWORD = "sequenceflow"; // attributes public static final String COMES_FROM = "comesfrom"; public static final String GOES_TO = "goesto"; private BPMNModelBuilder builder; public BnclSequenceFlowParser(BPMNModelBuilder builder) { this.builder = builder; } public SequenceFlow parseSequenceFlow(String elementString) { List<String> wordsWithoutSpaces = BnclParser.getWordsWithoutSpaces(elementString); /**for (String word : wordsWithoutSpaces) { logger().info(word); }**/ if (!BnclParser.checkWords(wordsWithoutSpaces)) { return null; } String fromId = ""; String toId = ""; if (wordsWithoutSpaces.get(0).toLowerCase().equals(SEQUENCE_FLOW_KEYWORD)) { for (int i = 1; i < wordsWithoutSpaces.size(); i++) { String word = wordsWithoutSpaces.get(i); switch (word.toLowerCase()) { case COMES_FROM: fromId = wordsWithoutSpaces.get(i + 1); break; case GOES_TO: toId = wordsWithoutSpaces.get(i + 1); break; default: break; } } } if (!fromId.equals("") && !toId.equals("")) { return builder.createSequenceFlow(builder.getProcess(), fromId, toId); } return null; } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.server.authn; /** * Marker interface. Implementations are used to exchange credentials between credential * verificator and credential retriever. * The actual exchange process might be complicated and require several interactions. E.g. * challenge based verificator might first give a challenge to the retrieval and then retrieval * return the challenge response. Typical implementation will define a method setting a callback. * The method will be implemented by verificator, and used by retriever. * <p> * Example credentials: SAML (IdP name/address), OpenID (IdP name/address), Username and password, * XX challenge, SMS * * @author K. Benedyczak */ public interface CredentialExchange { public String getExchangeId(); }
package dahe0070.thirty; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; /** * David Hegardt 2017-07-02 * Activity displaying options when app is started. * Singleplayer - starts a one player game, keeping track of this player. * Multiplayer - starts a 2 player game, keeping track of both players and compares * their score for all and individual throws. */ public class StartScreenActivity extends AppCompatActivity { private String playerOneName; private String playerTwoName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_screen); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Welcome to Thirty"); } /** * Function called after single/ multiplayer is chosen * @param playerNumber number of players in the game */ public void startGame(int playerNumber) { Intent newGame = new Intent(this,MainActivity.class); newGame.putExtra(getString(R.string.PlayerNr),playerNumber); newGame.putExtra(getString(R.string.player_one),playerOneName); // Set playernames to be sent to MainActivity newGame.putExtra(getString(R.string.player_two),playerTwoName); startActivity(newGame); // Start the game } /** * Disalog to be displayed if user chooses singleplayer */ public void singleplayerDialog(){ LayoutInflater inflater = LayoutInflater.from(this); View prompt = inflater.inflate(R.layout.single_prompt,null); // load custom dialog-layout AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setView(prompt); final EditText singlePlayer = (EditText) prompt.findViewById(R.id.editTextSinglePlayer); alert.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { playerOneName = singlePlayer.getText().toString(); startGame(1); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alert.create(); alert.show(); } /** * Dialog is displayed if user chooses multiplayer */ public void multiplayerDialog(){ LayoutInflater inflater = LayoutInflater.from(this); View prompt = inflater.inflate(R.layout.multi_prompt,null); // load custom dialog-layout AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setView(prompt); final EditText playerOne = (EditText) prompt.findViewById(R.id.editTextPlayerOne); // Setup input textfield for firstplayer final EditText playerTwo = (EditText) prompt.findViewById(R.id.editTextPlayerTwo); // Setup input textfield for secondplayer alert.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { playerOneName = playerOne.getText().toString(); // Set playernames based on input playerTwoName = playerTwo.getText().toString(); startGame(2); // Start multiplayer-game } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alert.create(); alert.show(); } /** * Show a dialog of information about the game */ public void createDialog(){ android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(StartScreenActivity.this).create(); alertDialog.setTitle(getString(R.string.About)); alertDialog.setMessage(getString(R.string.about_game)); alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } public void quit(){ finish(); } }
package com.allmsi.sys.dao; import java.util.List; import com.allmsi.sys.model.po.WebUser; public interface WebUserMapper { WebUser selectByPrimaryKey(String id); /** * 查询满足条件的用户id * @param user * @return */ List<String> checkUniqueId(WebUser user); /** * 用户修改邮箱、手机号时的校验 * @param webUser * @return */ int checkWebUser(WebUser webUser); /** * 查询满足条件的用户个数 * @param user * @return */ int checkUnique(WebUser user); int updateByPrimaryKeySelective(WebUser user); int insertSelective(WebUser user); List<WebUser> selectRoleByUserId(String id); }
/* * Copyright 2018-2020 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 * * 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 dev.miku.r2dbc.mysql; import dev.miku.r2dbc.mysql.constant.DataTypes; import io.netty.buffer.ByteBuf; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import java.util.HashMap; import java.util.Map; /** * Base class considers unit tests for implementations of {@link Query}. */ abstract class QueryTestSupport { @Test abstract void parse(); @Test abstract void getIndexes(); @Test abstract void bind(); @Test abstract void rejectGetIndexes(); @Test abstract void selfHashCode(); @Test abstract void selfEquals(); @Test abstract void indexesEquals(); static Tuple2<String, int[]> link(String name, int... indexes) { if (indexes.length == 0) { throw new IllegalArgumentException("must has least one index"); } return Tuples.of(name, indexes); } @SafeVarargs static Map<String, int[]> mapOf(Tuple2<String, int[]>... tuples) { // ceil(size / 0.75) = ceil((size * 4) / 3) = floor((size * 4 + 3 - 1) / 3) Map<String, int[]> result = new HashMap<>(((tuples.length << 2) + 2) / 3, 0.75f); for (Tuple2<String, int[]> tuple : tuples) { result.put(tuple.getT1(), tuple.getT2()); } return result; } static final class MockParameter implements Parameter { static final MockParameter INSTANCE = new MockParameter(); private MockParameter() { } @Override public boolean isNull() { return false; } @Override public Mono<ByteBuf> publishBinary() { return Mono.error(() -> new IllegalStateException("Mock parameter, has no value")); } @Override public Mono<Void> publishText(ParameterWriter writer) { return Mono.error(() -> new IllegalStateException("Mock parameter, has no value")); } @Override public short getType() { return DataTypes.INT; } @Override public void dispose() { } @Override public String toString() { return "MockParameter{}"; } } }
package com.zhongyp.spring.demo.mock; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class TestBraveKnight { @Test public void kngihtTest(){ Quest quest = mock(Quest.class); BraveKnight knight = new BraveKnight(quest); knight.embark(); verify(quest, times(1)).test(); } }
package com.javarush.task.task07.task0703; import java.io.BufferedReader; import java.io.InputStreamReader; /* Общение одиноких массивов */ public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код String[] stringList = new String[10]; int[] numList = new int[10]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); for (int i = 0; i < stringList.length; i++) { stringList[i] = br.readLine(); } for (int i = 0; i < numList.length; i++) { numList[i] = stringList[i].length(); } for (int i = 0; i < numList.length; i++) { System.out.println(numList[i]); } } }
import org.json.simple.JSONArray; import org.json.simple.JSONObject; //import org.json.JSONArray; import org.json.simple.parser.JSONParser; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.*; import org.json.JSONException; import org.json.simple.parser.JSONParser; public class App { public Object getData() throws IOException, ParseException, org.json.simple.parser.ParseException { URL url = new URL("http://intelligent-social-robots-ws.com/restaurant-data.json"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { Object obj = new JSONParser().parse(new InputStreamReader(conn.getInputStream())); JSONObject jo = (JSONObject) obj; JSONArray ja = (JSONArray) jo.get("restaurants"); return ja; } return null; } public JSONArray getByCuisineAndNeighbourhood(JSONArray ja, String cuisine, String chosenNeighbourhood) { int c = 0; JSONArray a = new JSONArray(); System.out.println("Generating restaurants with cuisine: " + cuisine + " in the neighbourhood: " + chosenNeighbourhood); for (int i = 0; i < ja.size(); i++) { JSONObject restaurant = (JSONObject) ja.get(i); String cuisine_type = (String) restaurant.get("cuisine_type"); String restaurantName = (String) restaurant.get("name"); String neighbourhood = (String) restaurant.get("neighborhood"); if (cuisine_type.equals(cuisine) & neighbourhood.equals(chosenNeighbourhood)) { System.out.println(restaurantName); a.add(restaurant); c++; } } if (c == 0) { System.out.println("Neighbourhood: " + chosenNeighbourhood + " With cuisine type: " + cuisine + " does not exist"); } return a; } public JSONArray getByOpeningHours(JSONArray ja, String day) { int c = 0; JSONArray a = new JSONArray(); System.out.println("Generating restaurants open on: " + day); for (int i = 0; i < ja.size(); i++) { JSONObject restaurant = (JSONObject) ja.get(i); String restaurantName = (String) restaurant.get("name"); JSONObject operatingHours = (JSONObject) restaurant.get("operating_hours"); if (!operatingHours.get(day).equals("Closed")) { System.out.println(restaurantName + ": " + operatingHours.get(day)); c++; a.add(restaurant); } } return a; } public JSONArray getByReviewRating(JSONArray ja, String chosenNeighbourhood, int reviewRating) { int c = 0; JSONArray a = new JSONArray(); for (int i = 0; i < ja.size(); i++) { ; JSONObject restaurant = (JSONObject) ja.get(i); String neighbourhood = (String) restaurant.get("neighborhood"); String restaurantName = (String) restaurant.get("name"); JSONArray reviews = (JSONArray) restaurant.get("reviews"); for (int e = 0; e < reviews.size(); e++) { JSONObject review = (JSONObject) reviews.get(e); long rating = Long.parseLong(String.valueOf(review.get("rating"))); String revName = (String) review.get("name"); if (neighbourhood.equals(chosenNeighbourhood)) { if (rating >= reviewRating) { System.out.println(restaurantName + ": Rating: " + rating + " review by: " + revName); c++; a.add(restaurant); } } } } return a; } public JSONArray getByDohmh(JSONArray ja, String chosenNeighbourhood) { int c = 0; //gets number of entries returned JSONArray a = new JSONArray(); for (int i = 0; i < ja.size(); i++) { JSONObject restaurant = (JSONObject) ja.get(i); String neighbourhood = (String) restaurant.get("neighborhood"); String restaurantName = (String) restaurant.get("name"); String dohmh = (String) restaurant.get("DOHMH_inspection_score"); if (neighbourhood.equals(chosenNeighbourhood)) { System.out.println(dohmh + " " + restaurantName); c++; a.add(restaurant); } } return a; } public void getNearHotel(JSONArray ja, String chosenNeighbourhood) { double neighLat = 0; double neighLng = 0; if (chosenNeighbourhood.equals("Brooklyn")) { neighLat = 40.689510; neighLng = -73.988100; } if (chosenNeighbourhood.equals("Manhattan")) { neighLat = 40.752831; neighLng = -73.985748; } if (chosenNeighbourhood.equals("Queens")) { neighLat = 40.753990; neighLng = -73.949240; } for (int i = 0; i < ja.size(); i++) { JSONObject restaurant = (JSONObject) ja.get(i); String restaurantName = (String) restaurant.get("name"); String neighbourhood = (String) restaurant.get("neighbourhood"); JSONObject latlng = (JSONObject) restaurant.get("latlng"); double lng = Double.parseDouble(String.valueOf(latlng.get("lng"))); double lat = Double.parseDouble(String.valueOf(latlng.get("lat"))); double distance = distance(lng, lat, neighLat, neighLng); System.out.println(restaurantName + ": " + distance + "Km"); } } private double distance(double lat1, double lng1, double lat2, double lng2) { double r = 6372.8; double lat = Math.toRadians(lat2 - lat1); double lng = Math.toRadians(lng2 - lng1); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double a = Math.pow(Math.sin(lat / 2), 2) + Math.pow(Math.sin(lng / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return r * c; } }
package com.fruit.crawler.serialize; /** * Created by vincent * Created on 16/2/1 11:03. */ public class SerializeImpl implements ISerialize { @Override public void serialize(String content) { } }
package Day2; import java.io.*; import java.util.Scanner; /** * Created by student on 04-May-16. */ public class InputOutput { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); //read line input String str = input.nextLine(); System.out.println("Using Scanner: " + str); //create a buffer reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str2 = ""; try { str2 = br.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Using InputStreamReader: " + str2 ); //Write to a file System.out.println(System.getProperty("user.dir")); String fileName = "test.txt"; try { FileWriter fileW = new FileWriter(fileName); BufferedWriter bw = new BufferedWriter(fileW); bw.write(str2); bw.close(); } catch (IOException ex) { System.out.println("Error writing to a file: " + fileName); } } }
/** * Support classes for web data binding. */ @NonNullApi @NonNullFields package org.springframework.web.bind.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package graphs; import java.util.ArrayList; import java.util.Stack; /** * This class implements an undirected graph to which edges can be added * randomly. It's for experimenting with the theory of random graphs, developed * by Paul Erdos and Alfred Renyi in 1959. * * @author TODO: put your name here */ public class RandomGraph { // TODO: add any necessary fields and classes for your chosen representation Vertex[] vertices; class Vertex { ArrayList<Vertex> neighbors; int label; public Vertex(int label) { this.label = label; this.neighbors = new ArrayList<>(); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.label); sb.append(": "); for (Vertex v : this.neighbors) { sb.append(v.label); sb.append(" "); } return sb.toString(); } } /** * Constructs a new graph of the given size with no edges. * * @param size */ public RandomGraph(int size) { this(size, new int[][] {}); } /** * Constructs a new graph of the given size with the given edges * * @param size * @param edges * each element is a pair giving the indices of the two nodes to * be connected */ public RandomGraph(int size, int[][] edges) { this.vertices = new Vertex[size]; for (int i = 0; i < size; i++) { this.vertices[i] = new Vertex(i); } for (int[] edge : edges) { int v1 = edge[0]; int v2 = edge[1]; vertices[v1].neighbors.add(vertices[v2]); vertices[v2].neighbors.add(vertices[v1]); } } /** * @return the size of the largest connected component of this graph */ public int largestConnectedComponentSize() { // TODO: implement this method int max = -1; boolean[] visited = new boolean[vertices.length]; for (Vertex v : vertices) { int compSize = componentSize(v, visited); if (compSize > max) { max = compSize; } } return max; } private int componentSize(Vertex v, boolean[] visited) { int size = 0; Stack<Vertex> stack = new Stack<>(); stack.push(v); while (!stack.isEmpty()) { Vertex current = stack.pop(); if (!visited[v.label]) { size++; visited[v.label] = true; } for (Vertex neighbor : current.neighbors) { if(!visited[neighbor.label]) stack.push(neighbor); } } return size; } /** * Adds a new edge, chosen uniformly from the set of missing edges. * * @throws IllegalStateException * if this.isComplete() */ public void addRandomEdge() throws IllegalStateException { // TODO: implement this method } /** * Returns whether this graph is connected, that is, whether there is a path * from any node in the graph to any other node. * * @return true iff this graph is connected */ public boolean isConnected() { // TODO: implement this method return false; } /** * Returns whether this graph is complete, that is, any two distinct * vertices are neighbors of each other. * * @return true iff this graph is complete */ public boolean isComplete() { // TODO: implement this method return false; } @Override public String toString() { /* * TODO: Implement this method by replacing the super call with code to * create a "reasonable" string representation of the Graph. Any * representation that helps you debug the other methods is fine. */ StringBuilder sb = new StringBuilder(); for (Vertex v : this.vertices) { sb.append(v.toString()); sb.append("\n"); } return super.toString(); } }
package com.lgbear.weixinplatform.message.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.lgbear.weixinplatform.message.domain.Text; import com.lgbear.weixinplatform.message.domain.TextCriteria; import com.lgbear.weixinplatform.user.domain.User; @Repository public interface TextDao { public void insert(Text text); public List<Text> findByOpeatorId(@Param("operatorId") String operatorId, @Param("offset") int offset, @Param("limit") int endset); public int countByOpeatorId(@Param("operatorId") String operatorId); public List<Text> findByOpenIdAndOpeatorId(@Param("openId") String openId, @Param("operatorId") String operatorId); public int countByOpenIdAndOpeatorId(@Param("openId") String openId, @Param("operatorId") String operatorId); public List<Text> findByCriteria(@Param("criteria") TextCriteria criteria, @Param("offset") int offset, @Param("limit") int limit); public int countByCriteria(@Param("criteria") TextCriteria criteria); public void deleteByMsgId(@Param("msgId") String msgId); public void delete(@Param("userCode") String userCode); public void deleteByTextCode(@Param("userCode") String userCode); public int findLastMsgTimeByOpenId(@Param("openId") String openId, @Param("operatorId") String operatorId); }
package com.iti.mad.firstlab.firebase; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.iti.mad.firstlab.R; import com.iti.mad.firstlab.realtime_database.RealTimeDBActivity; public class EmailAuthActivity extends AppCompatActivity { private FirebaseAuth mAuth; private EditText mEmailField; private EditText mPasswordField; private Button signin; private Button Signup; private String TAG="tag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_email_auth); mAuth = FirebaseAuth.getInstance(); mEmailField = findViewById(R.id.fieldEmail); mPasswordField = findViewById(R.id.fieldPassword); signin =findViewById(R.id.emailSignInButton); Signup= findViewById(R.id.emailCreateAccountButton); signin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String email=mEmailField.getText().toString(); String password=mPasswordField.getText().toString(); signIn(email, password); } }); Signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String email=mEmailField.getText().toString(); String password=mPasswordField.getText().toString(); createAccount(email, password); } }); } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); } private void createAccount(String email, String password) { // [START create_user_with_email] mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(EmailAuthActivity.this, "Authentication Succesfully.", Toast.LENGTH_SHORT).show(); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(EmailAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); // [END create_user_with_email] } private void signIn(String email, String password) { Log.d(TAG, "signIn:" + email); // [START sign_in_with_email] mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(EmailAuthActivity.this, "Authentication Succesfully.", Toast.LENGTH_SHORT).show(); Intent intent=new Intent(EmailAuthActivity.this, RealTimeDBActivity.class); intent.putExtra("uid", user.getUid()); startActivity(intent); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(EmailAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); // [END sign_in_with_email] } private void signOut() { mAuth.signOut(); } }
package prf.dbUtil; public abstract class DBUtil { protected String url; protected String userName; protected String password; protected String driverClassName; public abstract boolean createConnection(); public abstract boolean closeConnection(); public abstract boolean executeInsertAndUpdate(String sql); public abstract String executeQuery(String querySql); public abstract boolean executeQueryToFile(String querySql,String filePath); }
package com.ism.projects.th; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import com.ism.common.Common; import com.ism.common.exception.ErrorCode; import com.ism.common.exception.ErrorMessage; import com.ism.common.util.Utility; import com.ism.rule.entity.Field; import com.ism.rule.entity.constant.Constants; import com.ism.rule.entity.data.FieldGroupMap; import com.ism.rule.exception.RuleInterfaceException; import com.ism.transformer.exception.TransformerException; /** * EKL Deposit business service. * <ol> * <li>check input amount is positive</li> * <ul> * <li>success : next</li> * <li>fail : return 9999</li> * </ul> * <li>check account number</li> * <ul> * <li>success : next</li> * <li>fail : return 9000</li> * </ul> * <li>update DPAOCPP</li> * <ul> * <li>success : next</li> * <li>fail : return 9000</li> * </ul> * <li>insert DPARCPP</li> * <ul> * <li>success : next</li> * <li>fail : return 9999</li> * </ul> * <li>insert DPARCPP</li> * <ul> * <li>success : return 0000</li> * <li>fail : return 7000</li> * </ul> * </ol> * * @version 1.0 * @author HJ KANG */ public class EKLDepositService extends EKLService { /** * <span id="query">QUERY - {@value #QUERY_UPDATE_DPAOCPP}</span> * @see #updateDPAOCPP(int inDataIndex) */ private static final String QUERY_UPDATE_DPAOCPP = "UPDATE DPAOCPP SET AOAOVA = AOAOVA + ?, AOAFVN = ?, AOABDT = ? WHERE AOBFCD = ?"; /** * <span id="query">QUERY - {@value #QUERY_CHECK_ACCOUNT}</span> * @see #checkAccount(String acctNo) */ private static final String QUERY_CHECK_ACCOUNT = "SELECT AOBFCD, AOADCD from DPAOCPP WHERE AOBFCD = ? AND AOADCD NOT IN ('M','Z') "; /** * executeService start time. */ private Timestamp current = null; /* * (non-Javadoc) * @see com.ism.projects.th.EKLService#executeService(byte[]) */ public byte[] executeService(byte[] in) { exception = null; String result = EKL_UNKNOWN_ERROR; // input account number ( ISM Mapping ) String acctNo = new String(ai.getData()[0][0]).trim(); // input amount ( ISM Mapping ) String amount = new String(ai.getData()[0][1]).trim(); logN("deposit service [" + acctNo + "] amount[" + amount + "]"); String AMOUNT_ERROR = EKL_UNKNOWN_ERROR; byte[] bBalance = "00000000".getBytes(); try { double tmp = Double.parseDouble(amount); if(tmp <= 0) { result = AMOUNT_ERROR; String error = "input amount error.[" + amount + "] acct[" + acctNo + "]"; errorHandle(error, new IllegalStateException(error)); } else { result = EKL_SUCCESS; } } catch (Exception e) { errorHandle("input amount parse failed.[" + amount + "] acct[" + acctNo + "]", e); result = AMOUNT_ERROR; } if(!result.equals(EKL_SUCCESS)) { byte[] rtnValue = new byte[4 + 8]; System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); System.arraycopy(bBalance, 0, rtnValue, 4, 8); return rtnValue; } result = checkAccount(acctNo); if(!result.equals(EKL_SUCCESS)) { if(exception == null) { errorHandle("check account failed.[" + acctNo + "]"); } byte[] rtnValue = new byte[4 + 8]; System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); System.arraycopy(bBalance, 0, rtnValue, 4, 8); return rtnValue; } result = updateDPAOCPP(0); if(!result.equals(EKL_SUCCESS)) { rollback(); if(exception == null) { errorHandle("update DPAOCPP failed.[" + acctNo + "]"); } byte[] rtnValue = new byte[4 + 8]; System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); System.arraycopy(bBalance, 0, rtnValue, 4, 8); return rtnValue; } current = new Timestamp(new Date().getTime()); logN("current timeStamp = [" + current + "]"); result = executeUpdate(1, "DPASCPP", Constants.CRUD_CREATE); if(!result.equals(EKL_SUCCESS)) { rollback(); if(exception == null) { errorHandle("update DPASCPP failed.[" + acctNo + "]"); } byte[] rtnValue = new byte[4 + 8]; System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); System.arraycopy(bBalance, 0, rtnValue, 4, 8); return rtnValue; } /** * Commented on 25 Sep 2019 for passbookless migration */ // result = executeUpdate(2, "DPARCPP", Constants.CRUD_CREATE); // if(!result.equals(EKL_SUCCESS)) { // rollback(); // if(exception == null) { // errorHandle("insert DPARCPP failed.[" + acctNo + "]"); // } // byte[] rtnValue = new byte[4 + 8]; // System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); // System.arraycopy(bBalance, 0, rtnValue, 4, 8); // return rtnValue; // } Long balance = getBalanceLong(acctNo); if(balance == null) { rollback(); if(exception == null) { errorHandle("balance get failed.[" + acctNo + "]"); } byte[] rtnValue = new byte[4 + 8]; System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); System.arraycopy(bBalance, 0, rtnValue, 4, 8); return rtnValue; } if(balance < 0) { bBalance = Utility.createLengthAsByte(-balance, 8); bBalance[0] = '-'; } else { bBalance = Utility.createLengthAsByte(balance, 8); } byte[] rtnValue = new byte[4 + 8]; System.arraycopy(result.getBytes(), 0, rtnValue, 0, 4); System.arraycopy(bBalance, 0, rtnValue, 4, 8); try { target.commit(); } catch (SQLException e) { errorHandle("deposit service commit failed. [" + acctNo + "]", e); System.arraycopy(EKL_UNKNOWN_ERROR.getBytes(), 0, rtnValue, 0, 4); System.arraycopy("00000000".getBytes(), 0, rtnValue, 4, 8); return rtnValue; } return rtnValue; } /** * check account. * <span id="query">SQL : {@value #QUERY_CHECK_ACCOUNT}</span> * * @param acctNo account number. * @return if data exist then return '0000' else return '9000' */ private String checkAccount(String acctNo) { String method = "checkAccount"; String result = EKL_UNKNOWN_ERROR; String query = QUERY_CHECK_ACCOUNT; PreparedStatement pstmt = null; ResultSet rs = null; try { logV(method + " : query - " + query); pstmt = target.createPreparedStatement(query); Object[] params = { acctNo, }; if(!setParameters(target, pstmt, params)) { if(exception == null) { errorHandle(method + " : set parameter failed. [" + acctNo + "]", target.getException()); } throw exception; } rs = pstmt.executeQuery(); if(rs.next()) { // exist record result = EKL_SUCCESS; logE(method + " : row exist. return [" + EKL_SUCCESS + "]"); } else { errorHandle(method + " select count is 0. invalid account[" + acctNo + "]"); result = EKL_INVALID_ACCOUNT_NUMBER; } } catch (Exception e) { logE(method + " SQL execute fail[" + acctNo + "]", e); if(exception == null) { errorHandle(method + " failed to communicate with TH core [" + e.getMessage() + "]", e); } result = EKL_UNKNOWN_ERROR; } finally { close(pstmt, rs); } return result; } /** * update DPAOCPP. * <span id="query">SQL : {@value #QUERY_UPDATE_DPAOCPP}</span><br/> * PARAMS : amount, atmId, current date, account number. * * * @param inDataIndex ISM Data structure index. * @return if update count < 1 then return '9000' else return '0000' */ private String updateDPAOCPP(int inDataIndex) { String result = EKL_UNKNOWN_ERROR; logV("start update DPAOCC"); String acctNo = new String(ai.getData()[inDataIndex][0]).trim(); BigDecimal amount = new BigDecimal( new String(ai.getData()[inDataIndex][1]).trim()); String atmId = new String(ai.getData()[inDataIndex][2]).trim(); PreparedStatement pstmt = null; try { logV("query : " + QUERY_UPDATE_DPAOCPP); pstmt = target.createPreparedStatement(QUERY_UPDATE_DPAOCPP); target.setParameter(pstmt, 1, amount); target.setParameter(pstmt, 2, atmId); target.setParameter(pstmt, 3, new Date()); target.setParameter(pstmt, 4, acctNo); int count = pstmt.executeUpdate(); if ( count < 1 ) { errorHandle("update DPAOCC count 0 .invalid account number.[" + acctNo + "]"); result = EKL_INVALID_ACCOUNT_NUMBER; } else { logN("Deposit : Update DPAOCPP count : " + count); result = EKLService.EKL_SUCCESS; } } catch( Exception e ) { errorHandle("failed to communicate with TH core[" + e.getMessage() + "]", e); result = EKL_UNKNOWN_ERROR; } finally { close(pstmt); } return result; } /** * change values. * <ul> * <li>ASALVA : balance</li> * <li>ARJPVA : balance</li> * <li>ARAJVA : balance</li> * <li>ASADTS : transaction start time stamp</li> * <li>ARJKDZ : transaction start date</li> * <li>ARAYTZ : transacction start time</li> * </ul> * * @param in input data array. * @fieldMap fieldMap ISM Field group map array */ protected Object[] makeValue(String[] in, FieldGroupMap[] fieldMap) throws TransformerException { ArrayList valList = new ArrayList(); String acctNo = new String(ai.getData()[0][0]).trim(); String balance = ( getBalanceDouble(acctNo) ) + ""; if (in.length > 0) { for (int i = 0; i < fieldMap.length; i++) { if (!fieldMap[i].isSql()) { Field field = null; try { field = rmgr.getField(fieldMap[i].getFieldId()); } catch (RuleInterfaceException e) { logE("rule interface failed. [" + e.getMessage() + "]", e); throw new TransformerException(ErrorCode.RULE_CACHE_ACCESS_FAIL, ErrorMessage.getMessage(ErrorCode.RULE_CACHE_ACCESS_FAIL)); } if(Common._fissLogLevel >= Constants.LOG_TRIVIA) { logT("convert type for data[" + i + "]"); } String toUpperName = field.getName().trim().toUpperCase(); if(toUpperName.equals("ASALVA") || toUpperName.equals("ARJPVA") || toUpperName.equals("ARAJVA") ) { logV("EKLDepositService.makeValue field name[" + toUpperName + "] - change value : " + balance + "]"); in[i] = balance; } if(toUpperName.equals("ASADTS")) { in[i] = Utility.getFormattedDate("yyyyMMdd HHmmss.SSS", current); } if(toUpperName.equals("ARJKDZ")) { in[i] = Utility.getFormattedDate("yyyyMMdd", current); } if(toUpperName.equals("ARAYTZ")) { in[i] = Utility.getFormattedDate("HHmmss.SSS", current); } // if(toUpperName.equals("ARAKVA")) { // logV("EKLDepositService.makeValue field name[" + toUpperName + "] - change value : " + ( -1 * new Double(in[i].trim()) ) + "]"); // in[i] = ( -1 * new Double(in[i].trim()) ) + ""; // } valList.add(convertType(in[i], field, fieldMap[i])); } } } return valList.toArray(new Object[0]); } }
package com.smyc.kaftanis.lookingfortable; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.inputmethodservice.Keyboard; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.InputType; import android.text.method.DigitsKeyListener; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * Created by kaftanis on 3/18/16. */ public class SetRadius extends DialogFragment implements View.OnClickListener { EditText editText; Button button; public static double radius; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.set_radius, null); getDialog().setTitle("Επιλέξτε ακτίνα (σε χμ)"); editText = (EditText) view.findViewById(R.id.editText); editText.setKeyListener(DigitsKeyListener.getInstance("0123456789")); SharedPreferences prefs = getActivity().getBaseContext().getSharedPreferences("radius", getActivity().getBaseContext().MODE_PRIVATE); String rert = prefs.getString("value", "empty"); if (!rert.equals("empty")) { Double km = Double.parseDouble(rert); km=km/0.621371; editText.setHint("H τωρινή τιμή είναι "+ String.format("%.2f", km ) +" "+"χμ"); } else editText.setHint("Η τωρινή τιμή είναι 1 χμ"); button = (Button) view.findViewById(R.id.button4); button.setOnClickListener(this); return view; } @Override public void onClick(View v) { if (v.getId() == R.id.button4) { if (editText.getText().toString().equals("")) { Toast.makeText( getActivity() , "Πληκτρολογίστε κάποια τιμή" , Toast.LENGTH_SHORT).show(); } else { radius=Integer.parseInt(editText.getText().toString())*0.621371; //convert to miles SharedPreferences.Editor editor = getActivity().getBaseContext().getSharedPreferences("radius", getActivity().getBaseContext().MODE_PRIVATE).edit(); editor.putString("value", Double.toString(radius)); editor.commit(); dismiss(); Toast.makeText( getActivity() , "Ολοκληρώθηκε" , Toast.LENGTH_SHORT).show(); } } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setStyle(STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog_Alert); } Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.setTitle("Επιλέξτε ακτίνα (σε χμ)"); return dialog; } }
package com.esum.appcommon.resource.message; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; public class MessageBundle { private ResourceBundle bundle; public ResourceBundle getBundle() { return bundle; } public void setBundle(ResourceBundle value) { bundle = value; } public String getString(String key) { String value = key + "__not_found"; try { value = bundle.getString(key); } catch (Exception e) { System.out.println(value); } return value; } public String[] getStringArray(String key) { return bundle.getStringArray(key); } public Locale getLocale() { return bundle.getLocale(); } public String getString(String key, Object[] params) { return MessageFormat.format(getString(key), params); } public String getString(String key, Object param0) { Object[] parmas = {param0}; return getString(key, parmas); } public String getString(String key, Object param0, Object param1) { Object[] parmas = {param0, param1}; return getString(key, parmas); } public String getString(String key, Object param0, Object param1, Object param2) { Object[] parmas = {param0, param1, param2}; return getString(key, parmas); } public String getString(String key, Object param0, Object param1, Object param2, Object param3) { Object[] parmas = {param0, param1, param2, param3}; return getString(key, parmas); } }
package coals_crafting.fuel; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraft.item.ItemStack; import coals_crafting.item.BasisGoldCoalItem; import coals_crafting.CoalsCraftingModElements; @CoalsCraftingModElements.ModElement.Tag public class BasisGoldCoalFuelFuel extends CoalsCraftingModElements.ModElement { public BasisGoldCoalFuelFuel(CoalsCraftingModElements instance) { super(instance, 20); MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void furnaceFuelBurnTimeEvent(FurnaceFuelBurnTimeEvent event) { if (event.getItemStack().getItem() == new ItemStack(BasisGoldCoalItem.block, (int) (1)).getItem()) event.setBurnTime(6400); } }
package com.ywd.blog.dao; import java.util.List; import java.util.Map; import com.ywd.blog.entity.BlogRecommend; public interface BlogRecommendDao { public List<BlogRecommend> list(Map<String,Object> map); public Long getTotal(Map<String,Object> map); public int add(BlogRecommend BlogRecommend); public int update(BlogRecommend BlogRecommend); public int delete(Integer id); }
package com.davivienda.sara.reintegros.general; import com.davivienda.sara.base.BaseObjectContextWeb; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * DiarioElectronicoGeneralObjectContext - 27/08/2008 * Descripción : * Versión : 1.0 * * @author jjvargas * Davivienda 2008 */ public class ReintegrosGeneralObjectContext extends BaseObjectContextWeb{ public ReintegrosGeneralObjectContext(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super(request, response); } }
package com.weathair.controllers; import java.util.List; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.weathair.dto.indicators.MeteoIndicatorDto; import com.weathair.entities.indicators.AirIndicator; import com.weathair.entities.indicators.MeteoIndicator; import com.weathair.exceptions.AirIndicatorException; import com.weathair.exceptions.MeteoIndicatorException; import com.weathair.services.MeteoIndicatorService; /** * @author tarbo controller of meteo indicator * */ @CrossOrigin @RestController @RequestMapping("meteoindicators") public class MeteoIndicatorController { private MeteoIndicatorService meteoIndicatorService; public MeteoIndicatorController(MeteoIndicatorService meteoIndicatorService) { super(); this.meteoIndicatorService = meteoIndicatorService; } /** * @return all meteo indicators */ @GetMapping public List<MeteoIndicator> listAllMeteoIndicator() throws MeteoIndicatorException { return meteoIndicatorService.getAllMeteoIndicators(); } @GetMapping("township={townshipName}") public List<MeteoIndicator> listMeteoIndicatorsByTownshipName(@PathVariable String townshipName) throws MeteoIndicatorException{ return meteoIndicatorService.getMeteoIndicatorsByTownshipName(townshipName); } // @GetMapping("{townshipName}") // public ResponseEntity<?> meteoIndicatorByTownshipName(@PathVariable String townshipName) throws JsonMappingException, JsonProcessingException { // MeteoIndicatorDTO meteoIndicatorDto = this.meteoIndicatorService.findByTownshipName(townshipName); // return ResponseEntity.ok(meteoIndicatorDto); // // } /** * @param id * @return a meteo indicator by id * @throws MeteoIndicatorException */ @GetMapping("{id}") public ResponseEntity<?> meteoIndicatorByUser(@PathVariable Integer id) throws MeteoIndicatorException { MeteoIndicator meteoIndicator = this.meteoIndicatorService.getMeteoIndicatorById(id); return ResponseEntity.ok(meteoIndicator); } /** * @param dto * @return a new meteo indicator */ @PreAuthorize("hasAuthority('ROLE_ADMINISTRATOR')") @PostMapping public ResponseEntity<?> createNewMeteoIndicator(@RequestBody MeteoIndicatorDto meteoIndicatorDto) { return ResponseEntity.ok(meteoIndicatorService.createMeteoIndicator(meteoIndicatorDto)); } /** * @param id * @param newTemperature * @throws MeteoIndicatorException */ @PreAuthorize("hasAuthority('ROLE_ADMINISTRATOR')") @PutMapping("{id}") public ResponseEntity<?> updateMeteoIndicator(@RequestParam Integer id, @RequestBody MeteoIndicatorDto meteoIndicatorDto) throws MeteoIndicatorException { meteoIndicatorService.updateMeteoIndicator(id, meteoIndicatorDto); return ResponseEntity.ok("The meteo indicator with id " + id + " has been successfully updated"); } /** * @param id * @throws MeteoIndicatorException */ @PreAuthorize("hasAuthority('ROLE_ADMINISTRATOR')") @DeleteMapping("{id}") public ResponseEntity<?> deleteMeteoIndicatorByUser(@RequestParam Integer id) throws MeteoIndicatorException { meteoIndicatorService.deleteMeteoIndicator(id); return ResponseEntity.ok("The meteo indicator with id " + id + " has been successfully deleted"); } }
package gov.polisen.orm.models; public class CaseKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column cases.device_id * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ private Integer deviceId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column cases.case_id * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ private Integer caseId; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public CaseKey(Integer deviceId, Integer caseId) { this.deviceId = deviceId; this.caseId = caseId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column cases.device_id * * @return the value of cases.device_id * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public Integer getDeviceId() { return deviceId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column cases.case_id * * @return the value of cases.case_id * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public Integer getCaseId() { return caseId; } }
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.neuron.mytelkom; import android.widget.DatePicker; // Referenced classes of package com.neuron.mytelkom: // EditProfileActivity class this._cls0 implements android.app.eSetListener { final EditProfileActivity this$0; public void onDateSet(DatePicker datepicker, int i, int j, int k) { EditProfileActivity.access$0(EditProfileActivity.this, i); EditProfileActivity.access$1(EditProfileActivity.this, j); EditProfileActivity.access$2(EditProfileActivity.this, k); EditProfileActivity.access$3(EditProfileActivity.this); } ener() { this$0 = EditProfileActivity.this; super(); } }
package lang; public class CharacterDemo { public static void main(String[] args) { /* Character c = new Character('A'); System.out.println(c.charValue()); System.out.println(c.compareTo(new Character('B'))); System.out.println(c.equals(new Character('C'))); System.out.println(c.toString()); System.out.println("------------"); System.out.println(Character.isDigit('1')); System.out.println(Character.isLetter('*')); System.out.println(Character.isLetterOrDigit('#')); System.out.println(Character.isLowerCase('A')); System.out.println(Character.isUpperCase('B')); System.out.println(Character.isSpaceChar('\t')); System.out.println(Character.isWhitespace('\n')); System.out.println("------------"); System.out.println(Character.toUpperCase('a')); System.out.println(Character.toLowerCase('B')); System.out.println(Character.toTitleCase('c')); */ //char c = Character.forDigit(Character.digit('A', 10), 10); char c = 'A' + 1; System.out.println(c); } }
//package com.nextLevel.hero.common.service; // //import java.io.IOException; //import java.util.ArrayList; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // //import org.apache.poi.openxml4j.opc.OPCPackage; //import org.apache.poi.xssf.usermodel.XSSFCell; //import org.apache.poi.xssf.usermodel.XSSFRow; //import org.apache.poi.xssf.usermodel.XSSFSheet; //import org.apache.poi.xssf.usermodel.XSSFWorkbook; //import org.springframework.stereotype.Component; //import org.springframework.web.multipart.MultipartFile; // //import com.fasterxml.jackson.databind.exc.InvalidFormatException; // //@Component //public class ExcelUtil { // // // 각 셀의 데이터타입에 맞게 값 가져오기 // public String getCellValue(XSSFCell cell) { // // String value = ""; // // if(cell == null){ // return value; // } // // switch (cell.getCellType()) { // case STRING: // value = cell.getStringCellValue(); // break; // case NUMERIC: // value = (int) cell.getNumericCellValue() + ""; // break; // default: // break; // } // return value; // } // // // 엑셀파일의 데이터 목록 가져오기 (파라미터들은 위에서 설명함) // public List<Map<String, Object>> getListData(MultipartFile file, int startRowNum, int columnLength) { // // List<Map<String, Object>> excelList = new ArrayList<Map<String,Object>>(); // // try { // OPCPackage opcPackage = OPCPackage.open(file.getInputStream()); // // @SuppressWarnings("resource") // XSSFWorkbook workbook = new XSSFWorkbook(opcPackage); // // // 첫번째 시트 // XSSFSheet sheet = workbook.getSheetAt(0); // // int rowIndex = 0; // int columnIndex = 0; // // // 첫번째 행(0)은 컬럼 명이기 때문에 두번째 행(1) 부터 검색 // for (rowIndex = startRowNum; rowIndex < sheet.getLastRowNum() + 1; rowIndex++) { // XSSFRow row = sheet.getRow(rowIndex); // // // 빈 행은 Skip // if (row.getCell(0) != null && !row.getCell(0).toString().isBlank()) { // // Map<String, Object> map = new HashMap<String, Object>(); // // int cells = columnLength; // // for (columnIndex = 0; columnIndex <= cells; columnIndex++) { // XSSFCell cell = row.getCell(columnIndex); // map.put(String.valueOf(columnIndex), getCellValue(cell)); // logger.info(rowIndex + " 행 : " + columnIndex+ " 열 = " + getCellValue(cell)); // } // // excelList.add(map); // } // } // // } catch (InvalidFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return excelList; // } //}
package com.example.demo.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * Created By RenBin6 on 2020/9/12 . */ public class ProxyTester { private static Map<Integer,Integer> guolv = new HashMap<>(); public static void main(String[] args) { for (int i = 0; i < 10; i++) { Thread thread = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 100 ; j++) { if(null == ProxyTester.guolv.get(j) ){ guolv.put(j,j); ProxyTester.save(j); } } } }); thread.start(); } // jdkProxt(); } public static void test(){ Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); System.out.println("stack peek: " + stack.peek());; System.out.println("stack pop: " + stack.pop());; System.out.println("stack peek after pop: " + stack.peek());; } public static void jdkProxt(){ Singer singer = new Singer(); ISinger s = (ISinger)Proxy.newProxyInstance( singer.getClass().getClassLoader(), singer.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("hello , everyone"); Object invoke = method.invoke(singer, args); System.out.println("thanks"); return invoke; } } ); s.sing(); } public static void save(int i){ System.out.println("save : " + i); } }
package com.daydvr.store.util; /** * @author LoSyc * @version Created on 2018/1/9. 10:12 */ public class BroadCallBack { public void unObbZip(String path) { } public int deteledApkFile(String apkPackageName) { int apkId = 0; return apkId; } public void refreshAppList(String appPackageName) { } }
package com.example.push.mapper; import com.example.push.model.PushSubscriber; import org.springframework.data.repository.query.Param; import java.util.List; public interface PushSubscriberMapper { int deleteByPrimaryKey(Integer id); int insert(PushSubscriber record); int insertSelective(PushSubscriber record); PushSubscriber selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(PushSubscriber record); int updateByPrimaryKey(PushSubscriber record); /** * 根据群组ID查询订阅人列表 * @param id * @return */ List<PushSubscriber> selectByPushGroupId(String id); /** * 根据订阅人信息查询一个或多个订阅人信息 * @param record * @return */ List<PushSubscriber> selectSubscribers(PushSubscriber record); /** * 根据PushGroupId删除订阅信息 * @param pushGroupId */ int deleteByPushGroupId(String pushGroupId); /** * 删除指定退订的订阅信息 * @return */ int deleteDInfo(@Param(value = "openId")String openId,@Param(value = "topicCode")String topicCode); }
/* TwoDimensionalLatticeView -- 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.lattice.view; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Toolkit; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Iterator; import cellularAutomata.CAConstants; import cellularAutomata.CurrentProperties; import cellularAutomata.Cell; import cellularAutomata.cellState.model.CellState; import cellularAutomata.cellState.view.CellStateView; import cellularAutomata.graphics.colors.ColorScheme; import cellularAutomata.lattice.Lattice; import cellularAutomata.lattice.SquareLattice; import cellularAutomata.lattice.TwoDimensionalLattice; import cellularAutomata.movie.MovieMaker; import cellularAutomata.util.Coordinate; import cellularAutomata.util.PanelSize; import cellularAutomata.util.dataStructures.FiniteArrayList; /** * A convenience class for creating image panels that display the graphics for a * two-dimensional lattice. * * @author David Bahr */ public abstract class TwoDimensionalLatticeView extends LatticeView { // number of rows and columns in the CA private static int numRows; private static int numCols; // how many generations to average when displaying the cell's values private int runningAverage = 1; // use the "color array" graphics approach when true (see the method // drawLattice(Lattice)). private static boolean useColorArray = true; // off screen image that can be persistent (the offScreenGraphics come from // this image) private static BufferedImage offScreenImage = null; // used for macs that need special treatment of images when rescaling private boolean rescalingSize = false; // off screen image used to display the cellRGBData (for fast display) private BufferedImage img = null; // the cells on the 2-d lattice private Cell[][] cell = null; // off screen graphics object that can be persistent private static Graphics2D offScreenGraphics = null; // holds all the possible graphics configurations for the computer's // graphics card private GraphicsConfiguration graphicsConfiguration = null; // The CA lattice private Lattice lattice = null; // keeps track of whatever shape was last drawn at the given row and col private Shape[][] previousShape = null; /** * Create a graphics panel for a lattice. */ public TwoDimensionalLatticeView(TwoDimensionalLattice lattice) { super(); this.setIgnoreRepaint(true); // start out with a super small size -- the off screen image won't be // set until these are resized width = 1; height = 1; numRows = lattice.getHeight(); numCols = lattice.getWidth(); this.lattice = lattice; // setting the graphics configuration to match the current graphics card graphicsConfiguration = GraphicsEnvironment .getLocalGraphicsEnvironment().getDefaultScreenDevice() .getDefaultConfiguration(); // Initialize the array of cells. previousShape = new Shape[numRows][numCols]; cell = new Cell[numRows][numCols]; Iterator iterator = lattice.iterator(); for(int row = 0; row < numRows; row++) { for(int col = 0; col < numCols; col++) { // get the 2-d array of cells from the lattice cell[row][col] = (Cell) iterator.next(); } } // the number of generations that will be averaged for display runningAverage = CurrentProperties.getInstance().getRunningAverage(); // no layout manager setLayout(null); // get the smallest possible width and height (with the proper ratio) so // that we create a buffered image that is as small as possible (used in // setPanelSize()). This saves lots of memory. PanelSize size = rescaleToMinimumWidthAndHeight(); width = size.getWidth(); height = size.getHeight(); // set the size of the JPanel setPanelSize(); // for fast display cellRGBData = new int[numRows * numCols]; // keep track of cell colors in an array (for fast-displaying) for(int i = 0; i < numRows; i++) { for(int j = 0; j < numCols; j++) { setColorPixel(i * numCols + j, Cell.getView() .getDisplayColor(cell[i][j].getState(), null, cell[i][j].getCoordinate()).getRGB()); } } // the image used to display the cellRGBData img = graphicsConfiguration.createCompatibleImage(numCols, numRows); img.setAccelerationPriority(1.0f); } /** * Set parameters that determine the size of the graphics. */ private void setPanelSize() { // set the size of the JPanel setBounds(new Rectangle(0, 0, width, height)); setMaximumSize(new Dimension(width, height)); setMinimumSize(new Dimension(width, height)); setPreferredSize(new Dimension(width, height)); // JFrame frame = new JFrame(graphicsConfiguration); // System.out.println("TwoDimLatPanel: frame = "+frame); // // its faster to render to offscreen graphics // try // { // frame.createBufferStrategy(2); // } // catch(Exception e) // { // System.out.println(e); // } // BufferStrategy bufferStrategy = frame.getBufferStrategy(); // offScreenGraphics = (Graphics2D) bufferStrategy.getDrawGraphics(); // System.out.println("TwoDimLatPanel: offScreenGraphics = // "+offScreenGraphics); // offScreenImage = graphicsConfiguration.createCompatibleImage(width, // height, BufferedImage.TYPE_INT_RGB); // offScreenGraphics.setColor(ColorScheme.EMPTY_COLOR); // offScreenGraphics.fillRect(0, 0, width, height); // its faster to render to offscreen graphics offScreenImage = graphicsConfiguration.createCompatibleImage(width, height, BufferedImage.TYPE_INT_RGB); offScreenImage.setAccelerationPriority(1.0f); offScreenGraphics = offScreenImage.createGraphics(); offScreenGraphics.setColor(ColorScheme.EMPTY_COLOR); offScreenGraphics.fillRect(0, 0, width, height); // This is very important, particularly on Macs. Higher quality // interpolations like bilinear and bicubic do a poor job of // scaling-up(!) in image size. Square edges will be blurred. This hint // keeps the interpolation fast and keeps square edges looking nice. offScreenGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); // initializes the first time, and subsequently makes sure we don't try // to erase something that isn't there for(int row = 0; row < numRows; row++) { for(int col = 0; col < numCols; col++) { // initialize the array that keeps track of the previously drawn // shape previousShape[row][col] = null; } } } /** * Change the size of the display panel by a constant scaling factor. * * @param factor * The scaling factor. */ protected void rescalePanel(double factor) { // this is necessary because macs sometimes cache the image, and so I // have to be careful that it is drawn correctly (even when it isn't // technically being rescaled). See the method drawFastColorArray() for // more details. rescalingSize = true; // any size parameters that must be set in this class // (must come before setting parameters in the child class) setPanelSize(); // any size parameters that must be set in the child class // (must come after setting parameters in this parent class) setSizeParameters(); // now redraw drawLattice(); rescalingSize = false; } /** * Sets any size parameters that must be changed when zooming in or out on * the panel. * * @see cellularAutomata.lattice.view.TwoDimensionalLatticeView#resizePanel(double) */ protected abstract void setSizeParameters(); /** * Gets the color of a state. If the user has selected "average", then this * will be the average color of many states and or state histories. * * @return The cell state's color. */ private Color getColor(Cell cell, int row, int col) { // The color we will return Color color = null; // get the history of states for the cell FiniteArrayList<CellState> history = cell.getStateHistory(); int historyLength = history.size(); // get the running average try { if(runningAverage > 1 && historyLength > 1) { double red = 0.0; double green = 0.0; double blue = 0.0; for(int n = historyLength - 1; (n > historyLength - 1 - runningAverage) && (n >= 0); n--) { // untag the older cell states if necessary CellState state = history.get(n); Color stateColor = Cell.getView().getUntaggedColor(state, null, cell.getCoordinate()); red += stateColor.getRed(); green += stateColor.getGreen(); blue += stateColor.getBlue(); } // The state history may not be old enough to have // runningAverage int numColors = Math.min(runningAverage, historyLength); red /= (double) numColors; green /= (double) numColors; blue /= (double) numColors; color = new Color((int) Math.round(red), (int) Math .round(green), (int) Math.round(blue)); // if the current state is tagged, then tag the color CellState currentState = history.get(historyLength - 1); if(currentState.isTagged()) { // get the tagging color Color taggingColor = CellStateView.colorScheme .getTaggedColor(currentState.getTaggingObject()); // tag the color color = Cell.getView().modifyColorWithTaggedColor(color, taggingColor); } } else { color = Cell.getView().getDisplayColor(cell.getState(), null, cell.getCoordinate()); } } catch(Exception e) { // there was an error, so set the color to empty. color = ColorScheme.EMPTY_COLOR; } return color; } /** * Gets the display shape for a cell's state. If the user has selected * "average", then this will be the average shape of many states and or * state histories. * * @param cell * The cell whose state is being displayed. * @param row * The row position on the lattice. * @param col * The column position on the lattice. * @return The display shape for the cell. */ private Shape getShape(Cell cell, int row, int col) { // The shape we will return Shape shape = null; // Parameters for the CellStateView (helps tell it how to display). In // this case, the row and col are passed in because the display might // change with the position (as on a triangular lattice). Coordinate rowAndCol = new Coordinate(row, col); // get the history of states for the cell FiniteArrayList<CellState> history = cell.getStateHistory(); int historyLength = history.size(); // get the running average if(runningAverage > 1 && historyLength > 1) { ArrayList<CellState> stateList = new ArrayList<CellState>(); for(int n = historyLength - 1; (n > historyLength - 1 - runningAverage) && (n >= 0); n--) { stateList.add(history.get(n)); } if(stateList.size() > 0) { Object[] objectStates = stateList.toArray(); CellState[] states = new CellState[stateList.size()]; for(int i = 0; i < stateList.size(); i++) { states[i] = (CellState) objectStates[i]; } shape = Cell.getView().getAverageDisplayShape(states, getCellWidthInPixels(row, col), getCellHeightInPixels(row, col), rowAndCol); } } else { shape = Cell.getView().getDisplayShape(cell.getState(), getCellWidthInPixels(row, col), getCellHeightInPixels(row, col), rowAndCol); } return shape; } /** * Adds a picture to the panel. * <p> * This method is automatically called (by my implementation of * paintComponent() in the LatticeView class) whenever the window is resized * or otherwise altered. You can force it to be called by using the * <code>repaint</code> method of the encompassing JFrame or JComponent. * Never call this method directly (or the Graphics object may not be * specified properly). */ public final void draw(Graphics g) { // all along, the offScreenGraphics were actually updating this // image (that's where the offScreenGraphics came from -- the // offScreenImage). g.drawImage(offScreenImage, 0, 0, this); // necessary to prevent tearing on linux and other OS if(!CAConstants.WINDOWS_OS) { Toolkit.getDefaultToolkit().sync(); } } /** * Adds a picture to the panel, put only the specified sub-picture. * <p> * This method is currently called for printing purposes. * * @param upperLeftX * The upper-left x-position of the rectangle that will be drawn. * @param upperLeftY * The upper-left y-position of the rectangle that will be drawn. * @param width * The width the rectangle that will be drawn. * @param height * The height the rectangle that will be drawn. */ public void draw(Graphics2D g, int upperLeftX, int upperLeftY, int width, int height) { try { // all along, the offScreenGraphics were actually updating this // image (that's where the offScreenGraphics came from -- the // offScreenImage). g.drawImage(offScreenImage.getSubimage(upperLeftX, upperLeftY, width, height), 0, 0, null); } catch(Exception e) { // tried to draw a rectangle that's outside the image area. So just // draw the whole image. g.drawImage(offScreenImage, 0, 0, null); } } /** * Draws the color array on an image and then onto the graphics. Very fast, * but can only be used if the cells are not represented by special shapes. */ private void drawFastColorArrayOnGraphics() { // make the off-screen image display the array (each cell gets one // pixel). img.setRGB(0, 0, numCols, numRows, cellRGBData, 0, numCols); if(!CAConstants.MAC_OS || (!rescalingSize && cell[0][0].getGeneration() != 0)) { // now rescale to the correct size (so each cell occupies multiple // pixels). This rescaling can slow display times by a factor of 5. offScreenGraphics.drawImage(img, 0, 0, width, height, 0, 0, numCols, numRows, null); } else { // FOR MACS: // // Oh, this is painful. getScaledInstance() is VERY slow, but the // faster drawImage() used above just doesn't always work on my MAC. // In particular, when redrawing an image, the MAC seems to cache // the image (or the rendering hints), and it ignores the rendering // hints that I have set elsewhere. The result is a really // horrible-looking scaled image. So this is the only way to // ensure fast graphics with decent looking scaled images. // // Fortunately, this code is only necessary in special cases, like // when the simulation first starts, or when the size is rescaled // (both cases where the image seems to be cached, beyond my // control). offScreenGraphics.drawImage(img.getScaledInstance(width, height, BufferedImage.SCALE_FAST), new AffineTransform(1f, 0f, 0f, 1f, 0, 0), null); } // this is 5 times faster, but it doesn't fill the display // offScreenGraphics.drawImage(img, 0, 0, this); } /** * Draw a default shape for the lattice. This should be a quickly drawn * shape. The graphics method fillRect() is relatively quick and is a good * choice. Note that this method is only called when the CellStateView * returns null for the shape to draw -- hence this is only a backup and a * default. <br> * This method can be used intentionally for speed. (When drawing a Shape * would take too long, have the CellStateView return null for * getDisplayShape(), then this method will draw quickly.) * * @param row * The row position on the lattice. * @param col * The column position on the lattice. * @param g * The graphics object onto which the default shape should be * drawn. */ public abstract void drawDefaultShapeOnGraphics(int row, int col, Graphics2D g); /** * Draws a grid mesh on the graphics. Child classes should implement an * appropriate grid (square, hexagonal, triangular, or other). May do * nothing, but this will confuse the user that selects the "draw grid" * option on the menu. */ protected abstract void drawGrid(Graphics2D g); /** * Draws a grid mesh on the graphics. Called by various methods in this * class. */ private void drawGrid() { if(LatticeView.menuAskedForGrid) { drawGrid(offScreenGraphics); } } /** * Draws the single given cell onto an offscreen image. Draws the cell at * the specified position. Note, that this does not actually draw the cell * onto the component, but just onto an offscreen image. * <p> * The body of this method may be empty if there is no offscreen graphics. * * @param cell * The CA lattice. * @param xPos * The horizontal coordinate in the graphics space (in pixels) * which will be converted into a lattice position where the cell * will be drawn. * @param yPos * The vertical coordinate in the graphics space (in pixels) * which will be converted into a lattice position where the cell * will be drawn. */ public void drawCell(Cell cell, int xPos, int yPos) { // get the row and column corresponding to xPos and yPos Coordinate coordinate = getRowCol(xPos, yPos); int row = coordinate.getRow(); int col = coordinate.getColumn(); // draw on the image (using the quicker colorArray, if possible) if(useColorArray) { // set a pixel on the color array setColorPixel(row * numCols + col, getColor(cell, row, col) .getRGB()); // now draw that array on the graphics (quick) drawFastColorArrayOnGraphics(); } else { // draw a shape onto the off-screen graphics drawSingleCellWithErase(row, col, cell); } drawGrid(); } /** * Adds a picture to the background image. This method is called by * CAMenuBar. */ public final void drawLattice() { drawLattice(lattice); } /** * Decides which graphics approach is faster. * * @param lattice * The CA lattice. * @return true of the faster approach uses the color array. */ private boolean benchMark(Lattice lattice) { boolean useColorArray = true; Coordinate rowAndCol = new Coordinate(0, 0); // Note that this assumes that when the first cell has a null shape, // then ALL cell states will have a null shape. See the // CellStateView.getDisplayShape() method for information on why all // cells must return either (1) all null, or (2) all non-null shapes. // Ignoring that method's warnings will mess up the next line of code // and cause odd display bugs (where shapes don't get displayed unless // there happens to be a shape at cells[0][0] when this method is // called). Shape shape = Cell.getView().getDisplayShape(cell[0][0].getState(), 10, 10, rowAndCol); if((lattice instanceof SquareLattice) && (shape == null) && (runningAverage <= 1)) { useColorArray = true; // NO NEED TO CHECK THIS -- THE COLOR ARRAY APPROACH IS ALWAYS // FASTER WHEN IT CAN BE USED. // // // Approach #1 // long startTimeApproach1 = System.nanoTime(); // // // make the image display the array with one pixel per cell // img.setRGB(0, 0, numCols, numRows, cellRGBData, 0, numCols); // // // now rescale to the correct size (so each cell occupies // multiple // // pixels) // offScreenGraphics.drawImage(img, 0, 0, width, height, 0, 0, // numCols - 1, numRows - 1, this); // // long elapsedTimeForApproach1 = System.nanoTime() // - startTimeApproach1; // // // Approach #2 // long startTimeApproach2 = System.nanoTime(); // // // get the 2-d array of cells from the lattice // Iterator iterator = lattice.iterator(); // for(int row = 0; row < getNumRows(); row++) // { // for(int col = 0; col < getNumColumns(); col++) // { // // this cell[row][col] // Cell cell = (Cell) iterator.next(); // // drawSingleCellWithErase(row, col, cell); // } // } // // long elapsedTimeForApproach2 = System.nanoTime() // - startTimeApproach1; // // if(elapsedTimeForApproach2 < elapsedTimeForApproach1) // { // useColorArray = false; // } // System.out.println("TwoDimLatPan: elapsedTimeForApproach1 = " // + elapsedTimeForApproach1); // System.out.println("TwoDimLatPan: elapsedTimeForApproach2 = " // + elapsedTimeForApproach2); } else { // can't use the color array approach useColorArray = false; } return useColorArray; } // private static long totalTime = 0; // private static int numGenerations = 1; /** * Adds a picture to the background image. This method is called by * CellularAutomata. * * @param lattice * The CA lattice. */ public final void drawLattice(Lattice lattice) { // long startTime = System.nanoTime(); // Can display two different ways. If is a square lattice with no // special view/display shape, then is 3 to 10 times faster to use the // color array from TwoDimensionalLatticeView. (I benchmarked the // times.) // // But that's for large lattices. Small lattices sometimes (rarely) do // better without the image rescaling. // // So every 100 generations this method is called, benchmark both and // choose the best. if(cell[0][0].getGeneration() % 100 == 0) { useColorArray = benchMark(lattice); } if(useColorArray) { // the fast display -- this creates a single pixel for each cell drawFastColorArrayOnGraphics(); } else { // the slower but more general display method // get the 2-d array of cells from the lattice Iterator iterator = lattice.iterator(); for(int row = 0; row < getNumRows(); row++) { for(int col = 0; col < getNumColumns(); col++) { // this cell[row][col] Cell cell = (Cell) iterator.next(); drawSingleCellWithErase(row, col, cell); } } } // // to run this benchmarking, uncomment the static variables defined // // just before this method // long endTime = System.nanoTime(); // totalTime += (endTime - startTime); // double avgTime = totalTime / (double) numGenerations; // System.out.println("TwoDimLatPanel: avgTimeElapsed = " + avgTime); // numGenerations++; drawGrid(); // draw as a frame in the movie (if a movie is open and being // created) if(MovieMaker.isOpen()) { MovieMaker.writeFrame(offScreenImage); } } /** * Adds a picture to the background image without erasing the previous * image. This method is called by CAMenuBar. */ // public void drawLatticeWithoutErase() // { // // get the 2-d array of cells from the lattice // Iterator iterator = lattice.iterator(); // for(int row = 0; row < getNumRows(); row++) // { // for(int col = 0; col < getNumColumns(); col++) // { // // this cell[row][col] // Cell cell = (Cell) iterator.next(); // // drawSingleCellWithErase(row, col, cell); // } // } // // drawGrid(); // } /** * Draw a single cell onto the buffered graphics (does not erase any * previous drawing). * * @param row * The cell's row position. * @param col * The cell's column position. * @param cell * The cell being drawn. */ public void drawSingleCell(int row, int col, Cell cell) { // get the position of the shape int xPos = getCellXCoordinate(row, col); int yPos = getCellYCoordinate(row, col); // get the new shape Shape shape = getShape(cell, row, col); // get the color of the new shape Color cellColor = getColor(cell, row, col); if(cellColor == null) { cellColor = ColorScheme.EMPTY_COLOR; } if(shape != null) { // Prevents a mouse listener call from interfering with a lattice // call to this same code. Otherwise, can get confused about the // position of the shape and draw it in two places. synchronized(offScreenGraphics) { // offScreenGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_ON); // only reset the color if have to (expensive operation) Color color = offScreenGraphics.getColor(); if(cellColor != color) { // reset the color color = cellColor; offScreenGraphics.setColor(color); } // translate the shape to the correct position AffineTransform scalingTransform = AffineTransform .getTranslateInstance(xPos, yPos); shape = scalingTransform.createTransformedShape(shape); // set the line thickness Stroke defaultStroke = offScreenGraphics.getStroke(); Stroke stroke = Cell.getView().getStroke(cell.getState(), this.getCellWidthInPixels(row, col), this.getCellHeightInPixels(row, col), new Coordinate(row, col)); if(stroke != null) { offScreenGraphics.setStroke(stroke); } // paint the shape (slow) offScreenGraphics.draw(shape); // handles a bug with displaying the lattice gas from the // jar. The bug doesn't exist from java versions 1.5 and // earlier. if(!CurrentProperties.getInstance().getRuleClassName() .contains("Lattice")) { // oddly, the bug is only a problem on larger lattices. // || (numRows <= 20 && numCols <= 20)) offScreenGraphics.fill(shape); } // reset the line thickness to the default (but only if we reset // the stroke in the first place -- so we really do want to // check for stroke != null) if(stroke != null) { offScreenGraphics.setStroke(defaultStroke); } } } else { // only reset the color if have to (expensive operation) Color color = offScreenGraphics.getColor(); if(cellColor != color) { // reset the color color = cellColor; offScreenGraphics.setColor(color); } // use default shape for lattice drawDefaultShapeOnGraphics(row, col, offScreenGraphics); } // Set the previous shape to the new shape. // We do this now, after the AffineTransformation occurred, so that the // shape is positioned correctly (and we don't have to transform when // erasing the previous shape). previousShape[row][col] = shape; } /** * Draw a single cell onto the buffered graphics, but first erases any * previous drawing. * * @param row * The cell's row position. * @param col * The cell's column position. * @param cell * The cell being drawn. */ public void drawSingleCellWithErase(int row, int col, Cell cell) { // erase the previous shape at this position if(previousShape[row][col] != null) { // Prevents a mouse listener call from interfering with a lattice // call to this same code. Otherwise, can get confused about the // position of the shape and draw it in two places. synchronized(offScreenGraphics) { // offScreenGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_ON); // only reset the color if have to (expensive operation) Color color = offScreenGraphics.getColor(); if(color != ColorScheme.EMPTY_COLOR) { // reset the color color = ColorScheme.EMPTY_COLOR; offScreenGraphics.setColor(color); } // set the line thickness Stroke defaultStroke = offScreenGraphics.getStroke(); Stroke stroke = Cell.getView().getStroke(cell.getState(), this.getCellWidthInPixels(row, col), this.getCellHeightInPixels(row, col), new Coordinate(row, col)); if(stroke != null) { offScreenGraphics.setStroke(stroke); } try { // if select a rule with a different shape *while* the // previous rule is still running, then can get an error // because previous[row][col] can be suddenly set to null. // This catches that. // paint the shape (slow), but in the empty color. offScreenGraphics.draw(previousShape[row][col]); // This also handles another bug with displaying the lattice // gas from the jar. The bug doesn't exist from java // versions 1.5 and earlier. if(!CurrentProperties.getInstance().getRuleClassName() .contains("Lattice")) { // oddly, the bug is only a problem on larger lattices. // || (numRows <= 20 && numCols <= 20)) // this exception catching handles a Java bug offScreenGraphics.fill(previousShape[row][col]); } } catch(Exception e) { // ignore } // reset the line thickness to the default (but only if we reset // the stroke in the first place -- so we really do want to // check for stroke != null) if(stroke != null) { offScreenGraphics.setStroke(defaultStroke); } } } drawSingleCell(row, col, cell); } /** * Get the two-dimensional array of cells represented by the lattice. * * @return The two-dimensional array of cells. */ public Cell[][] getCellArray() { return cell; } /** * The height of the bounding rectangle for each cell's graphics (when * displayed on the panel). * * @param row * The row position on the lattice. * @param col * The column position on the lattice. * @return The height. */ public abstract double getCellHeight(int row, int col); /** * The width of the bounding rectangle for each cell's graphics (when * displayed on the panel). * * @param row * The row position on the lattice. * @param col * The column position on the lattice. * @return The width. */ public abstract double getCellWidth(int row, int col); /** * Get the X coordinate of the center of the cell. * * @param row * The cell's row position. * @param col * The cell's column position. * @return The X coordinate of the center of the cell. */ public abstract int getCellXCoordinate(int row, int col); /** * Get the Y coordinate of the center of the cell. * * @param row * The cell's row position. * @param col * The cell's column position. * @return The Y coordinate of the center of the cell. */ public abstract int getCellYCoordinate(int row, int col); /** * Always returns the current generation. * * @param xPos * The horizontal coordinate of the mouse. * @param yPos * The vertical coordinate of the mouse. * @return The generation of the cell displayed at the position xPos, yPos * on the graphics. May be -1 if there is no cell under the cursor. */ public int getGenerationUnderCursor(int xPos, int yPos) { return cell[0][0].getGeneration(); } /** * The number of columns displayed on the panel. * * @return The number of CA columns. */ public int getNumColumns() { return numCols; } /** * The number of rows displayed on the panel. * * @return The number of CA rows. */ public int getNumRows() { return numRows; } /** * Redraws the lattice. Typically, just a call to drawLattice() along with * resetting the color of the background. */ public void redraw() { // this is necessary because macs sometimes cache the image, and so I // have to be careful that it is drawn correctly (even when it isn't // technically being rescaled). See the method drawFastColorArray() for // more details. rescalingSize = true; // Reset the colors, in case they changed (e.g., via the menu). Only do // this if the color array is being used. if(useColorArray) { // keep track of cell colors in an array (for fast-displaying) for(int i = 0; i < numRows; i++) { for(int j = 0; j < numCols; j++) { setColorPixel(i * numCols + j, Cell.getView() .getDisplayColor(cell[i][j].getState(), null, cell[i][j].getCoordinate()).getRGB()); } } } offScreenGraphics.setColor(ColorScheme.EMPTY_COLOR); offScreenGraphics.fillRect(0, 0, width, height); // This is very important, particularly on Macs. Higher quality // interpolations like bilinear and bicubic do a poor job of // scaling-up(!) in image size. Square edges will be blurred. This hint // keeps the interpolation fast and keeps square edges looking nice. offScreenGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); drawLattice(lattice); rescalingSize = false; } /** * Rescale the width and height of the graphics panel so that it is the * smallest possible with the correct ratio. This size may vary with the * type of lattice. For example, the hexagonal lattice has rows that are * offset (every other row is offset slightly to the right, unlike a square * lattice); this increases the width of the lattice. So the panel's width * and height have to be rescaled to reflect this. * * @return A pair of integers for the width and height, as small as possible * that retains the correct ratio. */ public abstract PanelSize rescaleToMinimumWidthAndHeight(); }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.diagram.navigator; import org.eclipse.jface.viewers.ViewerSorter; import org.neuro4j.studio.core.diagram.part.Neuro4jVisualIDRegistry; /** * @generated */ public class Neuro4jNavigatorSorter extends ViewerSorter { /** * @generated */ private static final int GROUP_CATEGORY = 7016; /** * @generated */ public int category(Object element) { if (element instanceof Neuro4jNavigatorItem) { Neuro4jNavigatorItem item = (Neuro4jNavigatorItem) element; return Neuro4jVisualIDRegistry.getVisualID(item.getView()); } return GROUP_CATEGORY; } }
package com.dmtrdev.monsters.gui; import com.badlogic.gdx.Game; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.dmtrdev.monsters.DefenderOfNature; import com.dmtrdev.monsters.screens.BookScreen; import com.dmtrdev.monsters.screens.MenuScreen; import com.dmtrdev.monsters.screens.PlayScreen; import com.dmtrdev.monsters.consts.ConstGame; import com.dmtrdev.monsters.utils.PlayServices; public class LoadingGui extends Stage { private final Game mGame; private final Skin mSkin; private float mProgressSize; private final String mType; private final Image mProgress; public LoadingGui(final Game pGame, final String pType) { super(new StretchViewport(ConstGame.X, ConstGame.Y)); mGame = pGame; mType = pType; DefenderOfNature.manager.load("atlases/gui/loading_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.finishLoading(); mSkin = new Skin(DefenderOfNature.manager.get("atlases/gui/loading_atlas.txt", TextureAtlas.class)); mProgressSize = 15; final Image background = new Image(mSkin.getDrawable("loadscreen_bacground")); background.setBounds(0, 0, ConstGame.X, ConstGame.Y); addActor(background); final Image barFrame = new Image(mSkin.getDrawable("progress_bar")); barFrame.setSize(ConstGame.LOADING_FRAME_WIDTH, ConstGame.LOADING_FRAME_HEIGHT); barFrame.setPosition(ConstGame.X / 2 - barFrame.getWidth() / 2, ConstGame.LOADING_ELEMENT_POS__Y); addActor(barFrame); mProgress = new Image(mSkin.getDrawable("progress")); mProgress.setSize(mProgressSize, ConstGame.LOADING_PROGRESS_HEIGHT); mProgress.setPosition(barFrame.getX() + ConstGame.LOADING_PROGRESS_POS__X, ConstGame.LOADING_PROGRESS_POS__Y); addActor(mProgress); if (ConstGame.FIRST_LOADING.equals(mType)) { DefenderOfNature.manager.load("atlases/gui/gui_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("font/game_font.fnt", BitmapFont.class); DefenderOfNature.manager.load("sounds/click_on.wav", Sound.class); DefenderOfNature.manager.load("sounds/click_off.wav", Sound.class); DefenderOfNature.manager.load("sounds/buy.wav", Sound.class); DefenderOfNature.manager.load("music/game_menu_music.mp3", Music.class); DefenderOfNature.manager.load("music/game_music.mp3", Music.class); DefenderOfNature.manager.load("atlases/world/world_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/world/items_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/gui/game_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("sounds/error_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/coin_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/moose_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/enemy_death1__sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/enemy_death2__sound.wav", Sound.class); DefenderOfNature.manager.load("atlases/gui/google_btn_nrm.png", Texture.class); DefenderOfNature.manager.load("atlases/gui/google_brn_prs.png", Texture.class); } else if (ConstGame.SECOND_LOADING.equals(mType)) { DefenderOfNature.manager.load("atlases/book/book_atlas.txt", TextureAtlas.class); } else { DefenderOfNature.manager.load("atlases/player/player_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/armors/armor_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/effects/effects_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("sounds/game_over_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/tomato_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/pumpkin_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/stone_axe_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/shuriken_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/trap_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/barrel_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/rex_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/punch_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/birds_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/bird_death_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/molotov_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/iron_axe_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/mini_bomb_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/big_stone_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/grenade_sound.mp3", Sound.class); DefenderOfNature.manager.load("sounds/eat_plant_sound.wav", Sound.class); DefenderOfNature.manager.load("sounds/bomb_sound.wav", Sound.class); if(mType.contains(ConstGame.STORY_MODE)) { DefenderOfNature.manager.load("sounds/win_sound.mp3", Sound.class); switch (pType) { case "0" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/orcs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); break; case "1" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/orcs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); break; case "2" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/orcs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); break; case "3" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/orcs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/gargoyle_atlas.txt", TextureAtlas.class); break; case "4" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/orcs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/gargoyle_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); break; case "5" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/gargoyle_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/cyclops_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/yetsi_atlas.txt", TextureAtlas.class); break; case "6" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/gargoyle_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/cyclops_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/yetsi_atlas.txt", TextureAtlas.class); break; case "7" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/gargoyle_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/cyclops_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/yetsi_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/dragons_atlas.txt", TextureAtlas.class); break; case "8" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/yetsi_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/dragons_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/golems_atlas.txt", TextureAtlas.class); break; case "9" + ConstGame.STORY_MODE: DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/yetsi_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/dragons_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/golems_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/king_of_death_atlas.txt", TextureAtlas.class); break; } } else if(mType.contains(ConstGame.CHALLENGE_MODE)){ DefenderOfNature.manager.load("sounds/win_sound.mp3", Sound.class); switch (pType) { case "0" + ConstGame.CHALLENGE_MODE: DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); break; case "1" + ConstGame.CHALLENGE_MODE: DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); break; case "2" + ConstGame.CHALLENGE_MODE: DefenderOfNature.manager.load("atlases/enemies/dragons_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); break; case "3" + ConstGame.CHALLENGE_MODE: DefenderOfNature.manager.load("atlases/enemies/cyclops_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/golems_atlas.txt", TextureAtlas.class); break; case "4" + ConstGame.CHALLENGE_MODE: DefenderOfNature.manager.load("atlases/enemies/king_of_death_atlas.txt", TextureAtlas.class); break; } } else { DefenderOfNature.manager.load("atlases/enemies/goblins_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/orcs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/zombie_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/flyings_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/trolls_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/animals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/elementals_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/gargoyle_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/minotaurs_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/cyclops_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/yetsi_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/dragons_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/golems_atlas.txt", TextureAtlas.class); DefenderOfNature.manager.load("atlases/enemies/king_of_death_atlas.txt", TextureAtlas.class); } } } @Override public void act() { super.act(); if (DefenderOfNature.manager.update() && mProgress.getWidth() == ConstGame.LOADING_PROGRESS_WIDTH) { if (ConstGame.FIRST_LOADING.equals(mType)) { mGame.setScreen(new MenuScreen(mGame)); DefenderOfNature.manager.unload("atlases/gui/loading_atlas.txt"); } else if (ConstGame.SECOND_LOADING.equals(mType)) { mGame.setScreen(new BookScreen(mGame)); DefenderOfNature.manager.unload("atlases/gui/loading_atlas.txt"); } else { mGame.setScreen(new PlayScreen(mGame, mType)); DefenderOfNature.manager.unload("atlases/gui/loading_atlas.txt"); } } else if (DefenderOfNature.manager.getProgress() == 1) { mProgress.setWidth(ConstGame.LOADING_PROGRESS_WIDTH); } else if (mProgress.getWidth() < ConstGame.LOADING_PROGRESS_WIDTH) { mProgressSize += DefenderOfNature.manager.getProgress() / 10; mProgress.setWidth(mProgressSize); } } @Override public void dispose() { super.dispose(); mSkin.dispose(); } }
package lxy.liying.circletodo.task; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.io.File; import java.util.List; import lxy.liying.circletodo.app.App; import lxy.liying.circletodo.db.DBInfo; import lxy.liying.circletodo.domain.DateEvent; import lxy.liying.circletodo.domain.SelectedColor; /** * ======================================================= * 版权:©Copyright LiYing 2015-2016. All rights reserved. * 作者:liying * 日期:2016/8/2 15:12 * 版本:1.0 * 描述:拷贝其他人的标记 * 备注: * ======================================================= */ public class CopyOtherMarksTask extends MyAsyncTask { private OnCopyOtherMarksListener listener; /** 颜色覆盖数目 */ private int colorOverrideCount = 0; /** 颜色忽略数目 */ private int colorIgnoreCount = 0; /** 标记覆盖数目 */ private int markOverrideCount = 0; /** 标记忽略数目 */ private int markIgnoreCount = 0; /** * 当前用户所有的colorId */ private List<Integer> colorIds; public CopyOtherMarksTask(OnCopyOtherMarksListener listener) { this.listener = listener; // 覆盖、标记数目清零 colorOverrideCount = 0; colorIgnoreCount = 0; markOverrideCount = 0; markIgnoreCount = 0; } /** * 复制对方的标记 <br/> * * @param params 对方的信息(params[0]:uid,params[1]:下载的数据库文件存储路径) * @return null */ @Override protected Void doInBackground(String... params) { String uid = params[0]; colorIds = App.scService.getAllColorIds(); File tempDBFile = new File(params[1]); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(tempDBFile, null); // 更新selected_color表 updateSelectedColorTable(db, uid); // 更新date_event表 updateDateEventTable(db, uid); db.close(); return null; } /** * 更新selected_color表 * @param db * @param uid */ private void updateSelectedColorTable(SQLiteDatabase db, String uid) { String sql = "SELECT * FROM " + DBInfo.Table.TB_SELECT_COLOR + " WHERE " + SelectedColor.UID + "='" + uid + "'"; Cursor cursor = db.rawQuery(sql, null); if (cursor.getCount() > 0) { while (cursor.moveToNext()) { String cTime = cursor.getString(cursor.getColumnIndex(SelectedColor.C_TIME)); int colorId = cursor.getInt(cursor.getColumnIndex(SelectedColor.COLOR_ID)); String colorEvent = cursor.getString(cursor.getColumnIndex(SelectedColor.COLOR_EVENT)); if (colorIds != null && colorIds.size() > 0) { if (colorIds.contains(colorId)) { // 重复的颜色 if (App.SHARE_CONFLICT == 0) { // 覆盖 App.scService.updateEvent(colorId, colorEvent); App.scService.updateCTime(colorId, cTime); colorOverrideCount++; int count = App.deService.marksCount(colorId); markOverrideCount += count; } else if (App.SHARE_CONFLICT == 1) { // 忽略 colorIgnoreCount++; } } else { App.scService.addColor(new SelectedColor(cTime, colorId, colorEvent), true); } } else { App.scService.addColor(new SelectedColor(cTime, colorId, colorEvent), true); } } } cursor.close(); } /** * 更新date_event表 */ private void updateDateEventTable(SQLiteDatabase db, String uid) { String sql = "SELECT * FROM " + DBInfo.Table.TB_DATE_EVENT + " WHERE " + SelectedColor.UID + "='" + uid + "'"; Cursor cursor = db.rawQuery(sql, null); if (cursor.getCount() > 0) { while (cursor.moveToNext()) { // long d_id = cursor.getLong(cursor.getColumnIndex(DateEvent.D_ID)); String e_date = cursor.getString(cursor.getColumnIndex(DateEvent.E_DATE)); int color_id = cursor.getInt(cursor.getColumnIndex(DateEvent.COLOR_ID)); List<Integer> thisDateColorIds = App.deService.getColorId(e_date); if (thisDateColorIds.size() >= 10) { // 日标记数已达最大 markIgnoreCount++; continue; // 执行下一次循环 } if (thisDateColorIds.contains(color_id)) { // 该日期含有此颜色标记 if (App.SHARE_CONFLICT == 0) { // 覆盖原来的 markOverrideCount++; } else if (App.SHARE_CONFLICT == 1) { // 忽略新的 markIgnoreCount++; } } else { // 该日期不含有此颜色标记 App.deService.addDateEvent(new DateEvent(e_date, color_id)); } } } cursor.close(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); listener.onProgress(values[0]); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); listener.onComplete(colorOverrideCount, colorIgnoreCount, markOverrideCount, markIgnoreCount); } }
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.ml.dataset.internal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Class contains utility methods for database resources. */ public class MLDatabaseUtils { private static final Log logger = LogFactory.getLog(MLDatabaseUtils.class); /* * private Constructor to prevent any other class from instantiating. */ private MLDatabaseUtils() { } /** * Close a given set of database resources. * * @param connection Connection to be closed * @param preparedStatement PeparedStatement to be closed * @param resultSet ResultSet to be closed */ protected static void closeDatabaseResources(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) { // Close the resultSet if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { logger.error("Could not close result set: " + e.getMessage(), e); } } // Close the connection if (connection != null) { try { connection.close(); } catch (SQLException e) { logger.error("Could not close connection: " + e.getMessage(), e); } } // Close the statement if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { logger.error("Could not close statement: " + e.getMessage(), e); } } } /** * Close a given set of database resources. * * @param connection Connection to be closed * @param preparedStatement PeparedStatement to be closed */ protected static void closeDatabaseResources(Connection connection, PreparedStatement preparedStatement) { closeDatabaseResources(connection, preparedStatement, null); } /** * Close a given set of database resources. * * @param connection Connection to be closed */ protected static void closeDatabaseResources(Connection connection) { closeDatabaseResources(connection, null, null); } /** * Close a given set of database resources. * * @param preparedStatement PeparedStatement to be closed */ protected static void closeDatabaseResources(PreparedStatement preparedStatement) { closeDatabaseResources(null, preparedStatement, null); } /** * Roll-backs a connection. * * @param dbConnection Connection to be rolled-back */ protected static void rollBack(Connection dbConnection) { try { if (dbConnection != null) { dbConnection.rollback(); } } catch (SQLException e) { logger.error("An error occurred while rolling back transactions: ", e); } } /** * Enables the auto-commit of a connection. * * @param dbConnection Connection of which the auto-commit should be enabled */ protected static void enableAutoCommit(Connection dbConnection) { try { if (dbConnection != null) { dbConnection.setAutoCommit(true); } } catch (SQLException e) { logger.error("An error occurred while enabling autocommit: ", e); } } }
package com.hydrogennx.core; import com.hydrogennx.controller.SettingsMenu; import com.hydrogennx.controller.MainMenu; import com.hydrogennx.controller.WindowController; import com.hydrogennx.core.javafx.ScreenFramework; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; /** * A game manager to create instances of the various gametypes that exist. */ public class GameManager extends Application { Menu menu; String fileName = "Log"; public static final String SETTINGS_FILE = "settings"; Settings settings; private ScreenFramework screenFramework = new ScreenFramework(); GameInstance gameInstance; Stage primaryStage; Scene primaryScene; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws IOException { try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.close(); } catch (IOException e) { System.out.println("Oof"); } try { if (true) { throw new IOException(); } } catch (IOException e) { writeToLogFile(e); } this.primaryStage = primaryStage; updateGameWindow(); startLoop(); } public GameManager() { menu = menu.MAIN_MENU; screenFramework.setGameManager(this); screenFramework.loadMenus(); loadSettings(); gameInstance = null; System.out.println("Game loaded."); } public void updateScreen() { if (gameInstance != null) { gameInstance.updateScreen(); } else { switch (menu) { case MAIN_MENU: screenFramework.wcm.setScreen(screenFramework.MAIN_MENU_ID); break; case SETTINGS: screenFramework.wcm.setScreen(screenFramework.SETTING_ID); } } } protected void updateGameWindow() { primaryScene = new Scene(screenFramework.wcm, 750, 500, Color.BLACK); primaryScene.setFill(Color.BLACK); primaryScene.getStylesheets().add(getClass().getResource("/stylesheet.css").toString()); primaryStage.setTitle("Code Purple"); primaryStage.setScene(primaryScene); primaryStage.show(); updateScreen(); } public void startLocalPractice() { gameInstance = new LocalPracticeInstance(this); screenFramework.loadGameScreens(); updateScreen(); } public void startNetworkGame() { gameInstance = new NetworkGameInstance(this, true); screenFramework.loadGameScreens(); updateScreen(); } public void joinGame() { gameInstance = new NetworkGameInstance(this, false); screenFramework.loadGameScreens(); updateScreen(); } public void openSettingsMenu() { screenFramework.loadOptions(); menu = Menu.SETTINGS; updateScreen(); } long lastFramePrintMillis = 0; int frames = 0; protected void startLoop() { final long startNanoTime = System.nanoTime(); new AnimationTimer() { public void handle(long currentNanoTime) { double t = (currentNanoTime - startNanoTime) / 1000000000.0; if (menu == Menu.MAIN_MENU) { MainMenu mainMenu = (MainMenu) screenFramework.wcm.getController(ScreenFramework.MAIN_MENU_ID); mainMenu.updateTransition(t); } if (getGameInstance() != null) { getGameInstance().update(t); frames++; } if(System.currentTimeMillis()- lastFramePrintMillis >1000) { System.out.println("FPS: "+frames); frames = 0; lastFramePrintMillis = System.currentTimeMillis(); } } }.start(); } public GameInstance getGameInstance() { return gameInstance; } public void exit() { primaryStage.close(); } public void stopGame() { gameInstance = null; } public Settings getSettings() { return settings; } public void saveSettings() { try { FileOutputStream file = new FileOutputStream(SETTINGS_FILE); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(settings); out.close(); file.close(); } catch (IOException e) { writeToLogFile(e); System.out.println("Error saving settings!"); } } public void loadSettings() { try { FileInputStream file = new FileInputStream(SETTINGS_FILE); ObjectInputStream in = new ObjectInputStream(file); settings = (Settings) in.readObject(); in.close(); file.close(); } catch (IOException e) { writeToLogFile(e); System.out.println("Error loading settings, using defaults!"); settings = new Settings(); settings.setUsername("Player"); settings.setMusicEnabled(true); } catch (ClassNotFoundException e) { writeToLogFile(e); System.err.println(e.getStackTrace()); System.out.println("Using default settings"); } } public WindowController getWindowController(String windowControllerId) { return screenFramework.wcm.getController(windowControllerId); } public void setScreen(String windowControllerId) { screenFramework.wcm.setScreen(windowControllerId); } public void toMainMenu() { menu = Menu.MAIN_MENU; setScreen(ScreenFramework.MAIN_MENU_ID); } public void writeToLogFile(Exception message) { SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyy HH:mm:ss"); Date now = new Date(); String toWrite = format.format(now) + ": " + message.toString() + "\n"; System.out.println(toWrite); try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); out.write(toWrite); out.close(); // FileWriter fileWriter = new FileWriter(fileName); // Files.write(Paths.get(fileName), toWrite.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } } }
package skyrimdnd; public class NpcBalanceRnk4 { }
package com.mcode.nescompiler.exception; /** * * Exception thrown when the "calculated bytes" of a Command does * not equal to the actual bytes of the Command. * */ public class ByteCalculationException extends RuntimeException { public ByteCalculationException(String message) { super(message); } }
package com.x.hz.manager; import java.util.Set; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.x.hz.manager.listener.ClusterMembershipListener; import io.vertx.core.AbstractVerticle; import io.vertx.core.DeploymentOptions; import io.vertx.core.Future; public class MainVerticle extends AbstractVerticle { private static final org.slf4j.Logger LOG; static { LogbackInit.start(); LOG = org.slf4j.LoggerFactory.getLogger(MainVerticle.class); } @Override public void start(){ LOG.info("Main-Verticle started"); Set<HazelcastInstance> instances = Hazelcast.getAllHazelcastInstances(); LOG.info("There are {} Hazelcast instances", instances.size()); HazelcastInstance hz = instances.stream().findFirst().get(); DeploymentOptions options = new DeploymentOptions().setConfig(config()); ConfigVerticle cv = new ConfigVerticle(hz); //deploy(vertx,context,null); vertx.deployVerticle(cv, options.setWorker(true), ar -> { if(ar.succeeded()){ //startFuture.complete(); }else{ LOG.error("Config-Verticle deployment failed", ar.cause()); //startFuture.fail(ar.cause()); } }); ClusterMembershipListener cml = new ClusterMembershipListener(); vertx.deployVerticle(cml, options, ar -> { if(ar.succeeded()){ //startFuture.complete(); }else{ LOG.error("ClusterMembershipListener deployment failed", ar.cause()); //startFuture.fail(ar.cause()); } }); hz.getCluster().addMembershipListener(cml); } }
package com.service; import com.dto.Task; public interface TaskService { public void saveTask(Task task); }
package recipe.springframework.services; import java.io.IOException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import lombok.extern.slf4j.Slf4j; import recipe.springframework.domain.Recipe; import recipe.springframework.repositories.RecipeRepository; @Slf4j @Service public class ImageServiceImpl implements ImageService { private final RecipeRepository recipeRepository; public ImageServiceImpl(RecipeRepository recipeRepository) { super(); this.recipeRepository = recipeRepository; } @Override @Transactional public void saveImageFile(Long recipeId, MultipartFile file) { log.debug("Received a file"); try { Recipe recipe = recipeRepository.findById(recipeId).get(); /* * need to convert because multi-part file is primitive byte array. * Need to convert it to the wrapper class of a byte. */ Byte [] byteObjects = new Byte[file.getBytes().length]; int i = 0; //convert primitive byte to Byte for(byte b : file.getBytes()) { byteObjects[i++] = b; } recipe.setImage(byteObjects); recipeRepository.save(recipe); }catch (IOException e) { log.error("Error occurred",e); e.printStackTrace(); } } }
package br.com.fitNet.model.percistence; import java.sql.SQLException; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.stereotype.Repository; import br.com.fitNet.model.Cliente; import br.com.fitNet.model.Contrato; import br.com.fitNet.model.Endereco; import br.com.fitNet.model.Matricula; import br.com.fitNet.model.percistence.Interfaces.IRepositorioCliente; @Repository public class ClienteDao implements IRepositorioCliente{ public static Set<Cliente> LISTA_CLIENTE = new LinkedHashSet<>(); @Override public void incluir(Cliente cliente) throws SQLException { LISTA_CLIENTE.add(cliente); } @Override public void alterar(Cliente cliente) throws SQLException { for(Cliente clienteDaLista : LISTA_CLIENTE){ if(clienteDaLista.getId() == cliente.getId()){ clienteDaLista.getAcesso().setSenha(cliente.getAcesso().getSenha()); clienteDaLista.setNome(cliente.getNome()); clienteDaLista.setCpf(cliente.getCpf()); clienteDaLista.setDataAlteracao(cliente.getDataAlteracao()); clienteDaLista.setDataNascimento(cliente.getDataNascimento()); clienteDaLista.setFone(cliente.getFone()); clienteDaLista.setFone2(cliente.getFone2()); clienteDaLista.setStatusAtivo(cliente.isStatusAtivo()); //LISTA_CLIENTE.add(clienteDaLista); } } } @Override public void remover(Cliente cliente) throws SQLException { for(Cliente clienteDaConsulta : LISTA_CLIENTE){ if(clienteDaConsulta.getId() == clienteDaConsulta.getId()){ LISTA_CLIENTE.remove(clienteDaConsulta); break; } } } @Override public Set<Cliente> consultar() throws SQLException { return LISTA_CLIENTE; } @Override public Set<Cliente> consultarMatriculados() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Set<Cliente> consultarClienteParaPagamento() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Set<Cliente> consultarNaoMatriculados() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void incluirEnderecoCliente(Endereco endereco) throws SQLException { // TODO Auto-generated method stub } @Override public Endereco consultarEndereco(String cep) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int consultarAutoIncremento() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public int consultarAutoIncrementoMatricula() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public int consultarAutoIncrementoContrato() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Cliente consultarClientePorId(int idCliente) throws SQLException { Cliente clienteRetorno = null; for(Cliente clienteDaConsulta : LISTA_CLIENTE){ if(clienteDaConsulta.getId() == idCliente){ clienteRetorno = clienteDaConsulta; } } return clienteRetorno; } @Override public Set<Cliente> consultarClientePorNome(String nome) throws SQLException { Set<Cliente>clientesRetorno = new LinkedHashSet<>(); if(!nome.equals("")){ for(Cliente clienteDaConsulta : LISTA_CLIENTE){ if(clienteDaConsulta.getNome().contains(nome)){ clientesRetorno.add(clienteDaConsulta); } } return clientesRetorno; }else{ return LISTA_CLIENTE; } } @Override public Cliente consultarClientePorMatricula(int matricula) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String gerarNumeroMatricula() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void incluirContrato(Contrato contrato) throws SQLException { // TODO Auto-generated method stub } @Override public void incluirMatricula(Matricula matricula) throws SQLException { // TODO Auto-generated method stub } @Override public Set<String> consultarListaModalidadeCliente(int idContrato) throws SQLException { // TODO Auto-generated method stub return null; } }
package com.s1mple.dao; import com.s1mple.BaseTest; import com.s1mple.entity.StudentClean; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * @author s1mple * @create 2020/4/7-11:52 */ public class StudentCleanDaoTest extends BaseTest { @Autowired private StudentCleanDao studentCleanDao; @Test public void testtotalCount(){ Integer count = studentCleanDao.totalCount(1, "张杰", 123456); System.out.println(count); } @Test public void testgetStudentCleanList(){ List<StudentClean> studentCleanList = studentCleanDao.getStudentCleanList(1, "", 1, 1, 1); System.out.println(studentCleanList); } @Test public void testaddStudentClean(){ StudentClean studentClean = new StudentClean(); studentClean.setS_name("理想"); studentClean.setS_grade(9); studentClean.setS_studentid(1515345341); int i = studentCleanDao.addStudentClean(studentClean); System.out.println(i); } @Test public void testdeleteStudentClean(){ int i = studentCleanDao.deleteStudentClean(11); System.out.println(i); } @Test public void testupdateStudentClean(){ StudentClean studentClean = new StudentClean(); studentClean.setS_studentid(11); studentClean.setS_name("s1mple"); studentClean.setS_grade(4); int i = studentCleanDao.updateStudentClean(studentClean); System.out.println(i); } @Test public void testfindStudentCleanById(){ StudentClean studentCleanById = studentCleanDao.findStudentCleanById(5); System.out.println(studentCleanById); } @Test public void testgetAll(){ List<StudentClean> all = studentCleanDao.getAll(); System.out.println(all.toString()); } }
package com.pago.core.quotes.api.dto; import lombok.Data; @Data public class VenueRequest { private String name; private String description; public VenueRequest() {} }
package com.example.hemil.papa_johns.AbstractFactory; public interface Sides { String getName(); double getCost(int quantity); }
package com.lagardien.plkviolation; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Ijaaz Lagardien * 214167542 * Group 3A * Dr B. Kabaso * Date: 13 March 2016 */ public class TestMethods { private PLKDemo plk; private Order orderObect; private boolean test = false; @Before public void setUp() throws Exception { plk = new PLKDemo(); orderObect = new Order(); } @Test public void testProcess() throws Exception { try{ plk.process(orderObect); test = true; }catch (Exception e) { e.printStackTrace(); } Assert.assertTrue(test); } @Test public void testNormalise() throws Exception { try { orderObect.normalize(); test = true; }catch (Exception e) { e.printStackTrace(); } Assert.assertTrue(test); } }
package zsgetway.configure.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.apache.commons.lang.StringUtils; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @Component public class TokenFilter extends ZuulFilter { /* * pre: 这种过滤器在请求被路由之前调用。可利用这种过滤器实现身份验证、在集群中选择请求的微服务,记录调试信息等。 routing: 这种过滤器将请求路由到微服务。这种过滤器用于构建发送给微服务的请求,并使用apache httpclient或netflix ribbon请求微服务。 post: 这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的http header、收集统计信息和指标、将响应从微服务发送给客户端等。 error: 在其他阶段发送错误时执行该过滤器。 * * */ @Override public boolean shouldFilter() { //判断过滤器是否生效 // TODO Auto-generated method stub return true; } @Override public Object run() throws ZuulException { //编写顾虑器拦截业务逻辑代码 // 案例:拦截所有都服务接口,判断服务接口上是否有传递userToekn参数 //获取上下文 RequestContext currentContext = RequestContext.getCurrentContext(); //获取request对象 HttpServletRequest request = currentContext.getRequest(); //验证token时候 token的参数 从请求头获取 String userToken = request.getParameter("userToken"); if (StringUtils.isEmpty(userToken)) { //返回错误提示 currentContext.setSendZuulResponse(false); //false 不会继续往下执行 不会调用服务接口了 网关直接响应给客户了 currentContext.setResponseBody("no no no you have not userToken"); currentContext.setResponseStatusCode(401); return null; } //否则正常执行 调用服务接口... return null; } @Override public String filterType() { //过滤器的类型 return FilterConstants.PRE_TYPE; //表示在请求之前执行 } @Override public int filterOrder() { //过滤器执行的顺序 一个请求在同一个阶段存在多个过滤器时候,多个过滤器执行顺序问题 // TODO Auto-generated method stub return 0; } //网关的filter过滤器 }
package tersletsky.ru; public class Zad { private String answer; public Zad(String answer) { this.answer = answer; } public void setAnswer(String answer) { this.answer = answer; } public String getAnswer() { return this.answer; } }
package com.lxl.mvpwork.contract; import android.annotation.SuppressLint; import com.lxl.mvpwork.api.ApiService; import com.lxl.mvpwork.bean.GankResponse; import com.lxl.mvplibrary.base.BasePresenter; import com.lxl.mvplibrary.base.BaseView; import com.lxl.mvplibrary.network.NetworkApi; import com.lxl.mvplibrary.network.observer.BaseObserver; /** * 将V与M订阅起来 * @author */ public class MainContract { public static class MainPresenter extends BasePresenter<IMainView> { @SuppressLint("CheckResult") public void getGankList(){ ApiService service = NetworkApi.createService(ApiService.class); service.getList().compose(NetworkApi.applySchedulers(new BaseObserver<GankResponse>() { @Override public void onSuccess(GankResponse gankResponse) { if (getView() != null) { getView().getListResult(gankResponse); } } @Override public void onFailure(Throwable e) { if (getView() != null) { getView().getListFailed(e); } } })); } } public interface IMainView extends BaseView { //返回列表结果 void getListResult(GankResponse gankResponse); //获取列表失败返回 void getListFailed(Throwable e); } }
package com.infoworks.lab.rest.models; public class ItemExist extends Response { private Boolean isExist = false; public Boolean isExist() { return isExist; } public void setIsExist(Boolean exist) { isExist = exist; } }
package com.example.BankOperation.enums; import com.example.BankOperation.util.PaymentErrorCode; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.HashMap; import java.util.Map; public enum RequestPaymentError implements PaymentErrorCode { NOT_ENOUGH_FUNDS("not_enough_funds"), LIMIT_EXCEEDED("limit_exceeded"), ACCOUNT_BLOCKED("account_blocked"), AUTHORIZATION_REJECT("authorization_reject"),//В авторизации платежа отказано PHONE_UNKNOWN("phone_unknown"), TECHNICAL_ERROR("technical_error"); private final String code; private static final Log LOG = LogFactory.getLog(RequestPaymentError.class); private static Map<String,RequestPaymentError> map; static { map = new HashMap<String, RequestPaymentError>(); for (RequestPaymentError error : values()) { map.put(error.code, error); } } public static RequestPaymentError getByCode(String code) { if (code == null) { return null; } RequestPaymentError error = map.get(code); if (error != null) { return error; } LOG.error("unknown error code: " + code); return TECHNICAL_ERROR; } RequestPaymentError(String code) { this.code = code; } @Override public String getCode() { return code; } }
import java.util.Scanner; public class NewHouse { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String flowers = scan.nextLine().toLowerCase(); // "Roses", "Dahlias", "Tulips", "Narcissus", "Gladiolus" int flowersCount = Integer.parseInt(scan.nextLine()); int budget = Integer.parseInt(scan.nextLine()); double price = 0.0; switch (flowers) { case "roses": price = 5 * flowersCount; if (flowersCount > 80) { price -= price * 0.10; } break; case "dahlias": price = 3.80 * flowersCount; if (flowersCount > 90) { price -= price * 0.15; } break; case "tulips": price = 2.80 * flowersCount; if (flowersCount > 80) { price -= price * 0.15; } break; case "narcissus": price = 3 * flowersCount; if (flowersCount < 120) { price += price * 0.15; } break; case "gladiolus": price = 2.50 * flowersCount; if (flowersCount < 80) { price += price * 0.20; } break; } flowers = flowers.substring(0, 1).toUpperCase() + flowers.substring(1); if (budget >= price) { System.out.printf("Hey, you have a great garden with %d %s and %.2f leva left.", flowersCount, flowers, budget - price); } else { System.out.printf("Not enough money, you need %.2f leva more.", price - budget); } } }
// 코드명 : AlgoStudy 2021 프로그래머스 level 1 (score : 100/100) // 작성자 : 서민기 // 문제명 : 비밀지도 // 시작일 : 2021-01-25 // 종료일 : 2021-01-26 // 코멘트 : bit 연산자를 활용하는 문제였다. 귀찮다고 문제 내일로 미루지 말자 하루만에 풀수 있는 거였는데.... // 지도 1 또는 지도 2 중 어느 하나라도 벽인 부분은 전체 지도에서도 벽이다. (arr1, arr2 둘 중 하나라도 1일 경우 1로 부호화) // 지도 1과 지도 2에서 모두 공백인 부분은 전체 지도에서도 공백이다. (arr1, arr2 둘 다 0일 경우 0으로 부호화) // arr1, arr2 각각 NOT연산 후 AND연산하여 0 -> #, 1 -> 공백 으로 치환해 지도를 완성 public class mingiSeo_programmers_17681 { public static String[] solution(int n, int[] arr1, int[] arr2) { String[] answer = new String[n]; StringBuilder sb = new StringBuilder(); // string 수정을 위한 stringbuilder 메소드 사용 for (int i = 0; i < arr1.length; i++) { sb.append(Integer.toBinaryString(~arr1[i] & ~arr2[i])); // stringbuilder 객체에 arr1, arr2 NOT연산에 AND 연산 한거 넣음 while (true) { if (sb.length() >= 5) { sb.delete(0, sb.length() - n);// NOT 연산은 숨겨진 0들 전체를 반전하므로 반전시 생기는 불필요한 1 제거 answer[i]= sb.toString(); break; } sb.insert(0, "0"); } } for(int i=0;i< answer.length;i++){ // 0은 벽으로, 1은 공백으로 치환해 정답배열에 삽입 answer[i]=answer[i].replace("0","#"); answer[i]=answer[i].replace("1"," "); } return answer; } public static void main(String[] args) { int n = 5; int[] arr1 = {9, 20, 28, 18, 11}; int[] arr2 = {30, 1, 21, 17, 28}; solution(n, arr1, arr2); } }
package pl.jcw.demo.spring.cache; import java.util.Collections; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("pl.jcw.demo.spring.cache") @EnableCaching public class TestContext { @Bean public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(){ @Override protected Cache getMissingCache(String name) { return new ConcurrentMapCache(name); } }; cacheManager.setCaches(Collections.emptyList()); return cacheManager; } }
package com.bramgussekloo.projectb.models; import android.os.Parcel; import android.os.Parcelable; import com.bramgussekloo.projectb.Adapter.ProductIdClass; public class Product extends ProductIdClass implements Parcelable { private String title; private String desc; private String image_url; private String thumb_url; private String category; private int quantity; public Product(){} public Product( String category, String title, String desc, String image_url, String thumb_url, int quantity) { this.title = title; this.desc = desc; this.image_url = image_url; this.thumb_url = thumb_url; this.quantity = quantity; this.category = category; } protected Product(Parcel in) { title = in.readString(); desc = in.readString(); image_url = in.readString(); thumb_url = in.readString(); category = in.readString(); quantity = in.readInt(); } public static final Creator<Product> CREATOR = new Creator<Product>() { @Override public Product createFromParcel(Parcel in) { return new Product(in); } @Override public Product[] newArray(int size) { return new Product[size]; } }; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public String getThumb_url() { return thumb_url; } public void setThumb_url(String thumb_url) { this.thumb_url = thumb_url; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(title); parcel.writeString(desc); parcel.writeString(image_url); parcel.writeString(thumb_url); parcel.writeString(category); parcel.writeInt(quantity); } }
package com.shangdao.phoenix.entity.report.strategy; import com.alibaba.fastjson.JSONObject; import com.shangdao.phoenix.entity.apisearch.APISearchRepository; import com.shangdao.phoenix.entity.report.Report; import com.shangdao.phoenix.entity.report.module.BaseModule; import com.shangdao.phoenix.entity.report.module.BasicInfoModule; import com.shangdao.phoenix.entity.supplyAPI.SupplyAPI; import com.shangdao.phoenix.entity.supplyAPI.SupplyAPIRepository; import com.shangdao.phoenix.enums.Color; import com.shangdao.phoenix.util.AliyunCallable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author huanghengkun * @date 2018/04/04 */ public class BasicInfoModuleStrategy extends BaseStrategy { private static final Logger logger = LoggerFactory.getLogger(BasicInfoModuleStrategy.class); private static final long IDCARD_API_ID = 1L; private static final long MOBILE_API_ID = 2L; private static final long BANK_API_ID = 4L; private final SupplyAPI idcard_api; private final SupplyAPI mobile_api; private final SupplyAPI bank_api; private JSONObject idcardAPIResponse; private JSONObject mobileAPIResponse; private JSONObject bankAPIResponse; public BasicInfoModuleStrategy(Report report, SupplyAPIRepository supplyAPIRepository, APISearchRepository apiSearchRepository) { super(report, supplyAPIRepository, apiSearchRepository); this.idcard_api = supplyAPIRepository.findOne(IDCARD_API_ID); this.mobile_api = supplyAPIRepository.findOne(MOBILE_API_ID); this.bank_api = supplyAPIRepository.findOne(BANK_API_ID); } @Override public boolean isAPIActive() { return idcard_api.getEnabled() && mobile_api.getEnabled() && bank_api.getEnabled(); } private boolean isParameterComplete() { return super.report.getCustomerIdCard() != null && super.report.getCustomerMobile() != null && super.report.getCustomerBankCard() != null; } @Override public boolean isContainsAPI(Map<String, JSONObject> pool) { return pool.containsKey(idcard_api.getCode()) && pool.containsKey(mobile_api.getCode()) && pool.containsKey(bank_api.getCode()); } @Override public boolean isAPIUnfinished(Map<String, JSONObject> pool) { return EMPTY_JSON.equals(pool.get(idcard_api.getCode())) || EMPTY_JSON.equals(pool.get(mobile_api.getCode())) || EMPTY_JSON.equals(pool.get(bank_api.getCode())); } @Override public void tryPutEmptyAPI(Map<String, JSONObject> pool) { pool.put(idcard_api.getCode(), EMPTY_JSON); pool.put(mobile_api.getCode(), EMPTY_JSON); pool.put(bank_api.getCode(), EMPTY_JSON); } @Override public void removeEmptyAPI(Map<String, JSONObject> pool) { pool.remove(idcard_api.getCode()); pool.remove(mobile_api.getCode()); pool.remove(bank_api.getCode()); } @Override public void putAPIResponseIntoPool(Map<String, JSONObject> pool) { if (idcardAPIResponse != null && !EMPTY_JSON.equals(idcardAPIResponse)) { pool.put(idcard_api.getCode(), idcardAPIResponse); } if (mobileAPIResponse != null && !EMPTY_JSON.equals(mobileAPIResponse)) { pool.put(mobile_api.getCode(), mobileAPIResponse); } if (bankAPIResponse != null && !EMPTY_JSON.equals(bankAPIResponse)) { pool.put(bank_api.getCode(), bankAPIResponse); } } @Override public boolean fetchData(Map<String, JSONObject> pool) { JSONObject idcardAPIResponse = pool.get(idcard_api.getCode()); JSONObject mobileAPIResponse = pool.get(mobile_api.getCode()); JSONObject bankAPIResponse = pool.get(bank_api.getCode()); boolean isIdcardFetched = false; boolean isMobileFetched = false; boolean isBankFetched = false; if (idcardAPIResponse != null && !EMPTY_JSON.equals(idcardAPIResponse)) { this.idcardAPIResponse = idcardAPIResponse; isIdcardFetched = true; } if (mobileAPIResponse != null && !EMPTY_JSON.equals(mobileAPIResponse)) { this.mobileAPIResponse = mobileAPIResponse; isMobileFetched = true; } if (bankAPIResponse != null && !EMPTY_JSON.equals(bankAPIResponse)) { this.bankAPIResponse = bankAPIResponse; isBankFetched = true; } if (isIdcardFetched && isMobileFetched && isBankFetched) { return true; } if (!isIdcardFetched) { API api = new API(); api.setSupplyAPI(idcard_api); api.getParameters().put("idcard", super.report.getCustomerIdCard()); JSONObject cacheData = getCache(api); if (cacheData != null) { logger.info("缓存查询" + idcard_api.getCode()); } else { logger.info("即时查询" + idcard_api.getCode()); AliyunCallable aliyunCallable = new AliyunCallable(api.getSupplyAPI(), new HashMap<>(), api.getParameters(), "", supplyAPIRepository); cacheData = aliyunCallable.call(); logger.info(this.idcard_api.getCode() + " response:" + cacheData); if (cacheData != null && "0".equals(cacheData.getString("status"))) { putCache(api, cacheData); } } if (cacheData != null) { isIdcardFetched = true; this.idcardAPIResponse = cacheData; } } if (!isMobileFetched) { API api = new API(); api.setSupplyAPI(mobile_api); api.getParameters().put("mobile", super.report.getCustomerMobile()); JSONObject cacheData = getCache(api); if (cacheData != null) { logger.info("缓存查询" + mobile_api.getCode()); } else { logger.info("即时查询" + mobile_api.getCode()); AliyunCallable aliyunCallable = new AliyunCallable(api.getSupplyAPI(), new HashMap<>(), api.getParameters(), "", supplyAPIRepository); cacheData = aliyunCallable.call(); logger.info(this.mobile_api.getCode() + " response:" + cacheData); if (cacheData != null && "0".equals(cacheData.getString("error_code"))) { putCache(api, cacheData); } } if (cacheData != null) { isMobileFetched = true; this.mobileAPIResponse = cacheData; } } if (!isBankFetched) { API api = new API(); api.setSupplyAPI(bank_api); api.getParameters().put("bankcard", super.report.getCustomerBankCard()); // 版本号 api.getParameters().put("apiversion", "2.0.5"); JSONObject cacheData = getCache(api); if (cacheData != null) { logger.info("缓存查询" + bank_api.getCode()); } else { logger.info("即时查询" + bank_api.getCode()); AliyunCallable aliyunCallable = new AliyunCallable(api.getSupplyAPI(), new HashMap<>(), api.getParameters(), "", supplyAPIRepository); cacheData = aliyunCallable.call(); logger.info(this.bank_api.getCode() + " response:" + cacheData); if (cacheData != null && "0".equals(cacheData.getString("error_code"))) { putCache(api, cacheData); } } if (cacheData != null) { isBankFetched = true; this.bankAPIResponse = cacheData; } } // 当3个全部失败的时候才返回false return !(!isIdcardFetched && !isMobileFetched && !isBankFetched); } @Override public BaseModule analyseData() { BasicInfoModule basicInfoModule = new BasicInfoModule(Color.SUCCESS); basicInfoModule.setName(super.report.getCustomerName()); basicInfoModule.setIdCard(super.report.getCustomerIdCard()); basicInfoModule.setAddress(super.report.getCustomerAddress()); basicInfoModule.setMobile(super.report.getCustomerMobile()); basicInfoModule.setBankCard(super.report.getCustomerBankCard()); if (idcardAPIResponse != null) { if ("0".equals(idcardAPIResponse.getString("status"))) { JSONObject result = idcardAPIResponse.getJSONObject("result"); basicInfoModule.setSex(result.getString("sex")); basicInfoModule.setProvince(result.getString("province")); basicInfoModule.setCity(result.getString("city")); basicInfoModule.setTown(result.getString("town")); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); Date birth = sdf.parse(result.getString("birth")); int year1 = Calendar.getInstance().get(Calendar.YEAR); Calendar calendar = Calendar.getInstance(); calendar.setTime(birth); int year2 = calendar.get(Calendar.YEAR); basicInfoModule.setAge(year1 - year2); } catch (ParseException e) { e.printStackTrace(); } } else { basicInfoModule.setColor(Color.ERROR); } } else { basicInfoModule.setColor(Color.TIMEOUT); } if (mobileAPIResponse != null) { if ("0".equals(mobileAPIResponse.getString("error_code"))) { JSONObject result = mobileAPIResponse.getJSONObject("result"); String mobileCompany = result.getString("city") + result.getString("company").substring(2); basicInfoModule.setMobileCompany(mobileCompany); } else { basicInfoModule.setColor(Color.ERROR); } } else { basicInfoModule.setColor(Color.TIMEOUT); } if (bankAPIResponse != null) { if ("0".equals(bankAPIResponse.getString("error_code"))) { JSONObject result = bankAPIResponse.getJSONObject("result"); String bankName = result.getString("bankname"); basicInfoModule.setBankName(bankName); } else { basicInfoModule.setColor(Color.ERROR); } } else { basicInfoModule.setColor(Color.TIMEOUT); } return basicInfoModule; } @Override public void setModuleIntoReport(BaseModule module) { BasicInfoModule basicInfoModule = (BasicInfoModule) module; super.report.setBasicInfoModule(basicInfoModule); } }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2003-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.IOException; /** * A helper class for constructing dynamic DNS (DDNS) update messages. * * @author Brian Wellington */ public class Update extends Message { private final Name origin; private final int dclass; /** * Creates an update message. * * @param zone The name of the zone being updated. * @param dclass The class of the zone being updated. */ public Update(Name zone, int dclass) { super(); if (!zone.isAbsolute()) { throw new RelativeNameException(zone); } DClass.check(dclass); getHeader().setOpcode(Opcode.UPDATE); Record soa = Record.newRecord(zone, Type.SOA, DClass.IN); addRecord(soa, Section.QUESTION); this.origin = zone; this.dclass = dclass; } /** * Creates an update message. The class is assumed to be IN. * * @param zone The name of the zone being updated. */ public Update(Name zone) { this(zone, DClass.IN); } private void newPrereq(Record rec) { addRecord(rec, Section.PREREQ); } private void newUpdate(Record rec) { addRecord(rec, Section.UPDATE); } /** * Inserts a prerequisite that the specified name exists; that is, there exist records with the * given name in the zone. */ public void present(Name name) { newPrereq(Record.newRecord(name, Type.ANY, DClass.ANY, 0)); } /** * Inserts a prerequisite that the specified rrset exists; that is, there exist records with the * given name and type in the zone. */ public void present(Name name, int type) { newPrereq(Record.newRecord(name, type, DClass.ANY, 0)); } /** * Parses a record from the string, and inserts a prerequisite that the record exists. Due to the * way value-dependent prequisites work, the condition that must be met is that the set of all * records with the same and type in the update message must be identical to the set of all * records with that name and type on the server. * * @throws IOException The record could not be parsed. */ public void present(Name name, int type, String record) throws IOException { newPrereq(Record.fromString(name, type, dclass, 0, record, origin)); } /** * Parses a record from the tokenizer, and inserts a prerequisite that the record exists. Due to * the way value-dependent prequisites work, the condition that must be met is that the set of all * records with the same and type in the update message must be identical to the set of all * records with that name and type on the server. * * @throws IOException The record could not be parsed. */ public void present(Name name, int type, Tokenizer tokenizer) throws IOException { newPrereq(Record.fromString(name, type, dclass, 0, tokenizer, origin)); } /** * Inserts a prerequisite that the specified record exists. Due to the way value-dependent * prequisites work, the condition that must be met is that the set of all records with the same * and type in the update message must be identical to the set of all records with that name and * type on the server. */ public void present(Record record) { newPrereq(record); } /** * Inserts a prerequisite that the specified name does not exist; that is, there are no records * with the given name in the zone. */ public void absent(Name name) { newPrereq(Record.newRecord(name, Type.ANY, DClass.NONE, 0)); } /** * Inserts a prerequisite that the specified rrset does not exist; that is, there are no records * with the given name and type in the zone. */ public void absent(Name name, int type) { newPrereq(Record.newRecord(name, type, DClass.NONE, 0)); } /** * Parses a record from the string, and indicates that the record should be inserted into the * zone. * * @throws IOException The record could not be parsed. */ public void add(Name name, int type, long ttl, String record) throws IOException { newUpdate(Record.fromString(name, type, dclass, ttl, record, origin)); } /** * Parses a record from the tokenizer, and indicates that the record should be inserted into the * zone. * * @throws IOException The record could not be parsed. */ public void add(Name name, int type, long ttl, Tokenizer tokenizer) throws IOException { newUpdate(Record.fromString(name, type, dclass, ttl, tokenizer, origin)); } /** Indicates that the record should be inserted into the zone. */ public void add(Record record) { newUpdate(record); } /** Indicates that the records should be inserted into the zone. */ public void add(Record[] records) { for (Record record : records) { add(record); } } /** Indicates that all of the records in the rrset should be inserted into the zone. */ public <T extends Record> void add(RRset rrset) { rrset.rrs().forEach(this::add); } /** Indicates that all records with the given name should be deleted from the zone. */ public void delete(Name name) { newUpdate(Record.newRecord(name, Type.ANY, DClass.ANY, 0)); } /** Indicates that all records with the given name and type should be deleted from the zone. */ public void delete(Name name, int type) { newUpdate(Record.newRecord(name, type, DClass.ANY, 0)); } /** * Parses a record from the string, and indicates that the record should be deleted from the zone. * * @throws IOException The record could not be parsed. */ public void delete(Name name, int type, String record) throws IOException { newUpdate(Record.fromString(name, type, DClass.NONE, 0, record, origin)); } /** * Parses a record from the tokenizer, and indicates that the record should be deleted from the * zone. * * @throws IOException The record could not be parsed. */ public void delete(Name name, int type, Tokenizer tokenizer) throws IOException { newUpdate(Record.fromString(name, type, DClass.NONE, 0, tokenizer, origin)); } /** Indicates that the specified record should be deleted from the zone. */ public void delete(Record record) { newUpdate(record.withDClass(DClass.NONE, 0)); } /** Indicates that the records should be deleted from the zone. */ public void delete(Record[] records) { for (Record record : records) { delete(record); } } /** Indicates that all of the records in the rrset should be deleted from the zone. */ public <T extends Record> void delete(RRset rrset) { rrset.rrs().forEach(this::delete); } /** * Parses a record from the string, and indicates that the record should be inserted into the zone * replacing any other records with the same name and type. * * @throws IOException The record could not be parsed. */ public void replace(Name name, int type, long ttl, String record) throws IOException { delete(name, type); add(name, type, ttl, record); } /** * Parses a record from the tokenizer, and indicates that the record should be inserted into the * zone replacing any other records with the same name and type. * * @throws IOException The record could not be parsed. */ public void replace(Name name, int type, long ttl, Tokenizer tokenizer) throws IOException { delete(name, type); add(name, type, ttl, tokenizer); } /** * Indicates that the record should be inserted into the zone replacing any other records with the * same name and type. */ public void replace(Record record) { delete(record.getName(), record.getType()); add(record); } /** * Indicates that the records should be inserted into the zone replacing any other records with * the same name and type as each one. */ public void replace(Record[] records) { for (Record record : records) { replace(record); } } /** * Indicates that all of the records in the rrset should be inserted into the zone replacing any * other records with the same name and type. */ public <T extends Record> void replace(RRset rrset) { delete(rrset.getName(), rrset.getType()); rrset.rrs().forEach(this::add); } }
package com.defalt.lelangonline.data.auctions; import android.os.AsyncTask; import androidx.annotation.NonNull; import com.defalt.lelangonline.data.RestApi; import com.defalt.lelangonline.ui.SharedFunctions; import com.defalt.lelangonline.ui.auctions.Auction; import com.defalt.lelangonline.ui.auctions.AuctionsActivity; import com.defalt.lelangonline.ui.auctions.AuctionsAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.sql.Timestamp; import java.util.List; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.defalt.lelangonline.ui.recycle.PaginationListener.PAGE_START; public class AuctionsTask extends AsyncTask<String, Void, Void> { private int success; private AuctionsAdapter adapter; private List<Auction> auctionList; private int currentPage; private int totalPage; private AuctionsActivity.AuctionsUI auctionsUI; public AuctionsTask(AuctionsAdapter adapter, List<Auction> auctionList, int currentPage, int totalPage, AuctionsActivity.AuctionsUI auctionsUI) { this.adapter = adapter; this.auctionList = auctionList; this.currentPage = currentPage; this.totalPage = totalPage; this.auctionsUI = auctionsUI; } protected Void doInBackground(String... args) { RestApi server = SharedFunctions.getRetrofit().create(RestApi.class); RequestBody desiredCount = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(args[0])); RequestBody dataOffset = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(args[1])); RequestBody itemID = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(args[2])); Call<ResponseBody> req = server.getAuctionsByItem(desiredCount, dataOffset, itemID); req.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) { try { if (response.body() != null) { JSONObject json = new JSONObject(response.body().string()); success = json.getInt("success"); if (success == 1) { Timestamp serverTime = SharedFunctions.parseDate(json.getString("serverTime")); JSONArray items = json.getJSONArray("auctions"); for (int i = 0; i < items.length(); i++) { JSONObject c = items.getJSONObject(i); AuctionsActivity.setItemCount(AuctionsActivity.getItemCount() + 1); String auctionID = c.getString("auctionID"); Timestamp auctionStart = SharedFunctions.parseDate(c.getString("auctionStart")); Timestamp auctionEnd = SharedFunctions.parseDate(c.getString("auctionEnd")); String itemName = c.getString("itemName"); Double itemValue = c.getDouble("itemValue"); Double priceStart = c.getDouble("priceStart"); String itemImg = c.getString("itemImg"); int favCount = c.getInt("favCount"); Auction au = new Auction(auctionID, auctionStart, auctionEnd, itemName, itemValue, priceStart, itemImg, favCount, serverTime); auctionList.add(au); } } postExecute(); if (success == 1) { executeSuccess(); } else if (success == -1) { executeEmpty(); } else if (success == 0) { executeError(); } endExecute(); } else { postExecute(); executeError(); endExecute(); } } catch (JSONException | IOException e) { e.printStackTrace(); postExecute(); executeError(); endExecute(); } } @Override public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) { t.printStackTrace(); postExecute(); executeError(); endExecute(); } }); return null; } private void postExecute() { if (currentPage != PAGE_START) { adapter.removeLoading(); } adapter.addItems(auctionList); auctionsUI.setRefreshing(false); } private void executeSuccess() { if (auctionList.size() < totalPage) { AuctionsActivity.setLastPage(true); } else { adapter.addLoading(); } auctionsUI.updateUI(); } private void executeEmpty() { AuctionsActivity.setLastPage(true); auctionsUI.updateUI(); } private void executeError() { AuctionsActivity.setLastPage(true); if (!AuctionsActivity.isConnectionError()) { auctionsUI.showError(); AuctionsActivity.setIsConnectionError(true); } } private void endExecute() { AuctionsActivity.setLoading(false); } }
/* * @(#) TpstifDAO.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.tpstif.dao.impl; import java.util.List; import com.esum.appframework.dao.impl.SqlMapDAO; import com.esum.appframework.exception.ApplicationException; import com.esum.wp.ims.tpstif.dao.ITpstifDAO; /** * * @author heowon@esumtech.com * @version $Revision: 1.1 $ $Date: 2009/01/20 01:31:00 $ */ public class TpstifDAO extends SqlMapDAO implements ITpstifDAO { /** * Default constructor. Can be used in place of getInstance() */ public TpstifDAO () {} public String detailID = ""; public String searchETRTpIdID = ""; public String selectPageListID = ""; public String getSelectPageListID() { return selectPageListID; } public void setSelectPageListID(String selectPageListID) { this.selectPageListID = selectPageListID; } public List detail(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(detailID, object); } catch (Exception e) { throw new ApplicationException(e); } } public List searchETRTpId(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(searchETRTpIdID, object); } catch (Exception e) { throw new ApplicationException(e); } } public List selectPageList(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(selectPageListID, object); } catch (Exception e) { throw new ApplicationException(e); } } public String getDetailID() { return detailID; } public void setDetailID(String detailID) { this.detailID = detailID; } public String getSearchETRTpIdID() { return searchETRTpIdID; } public void setSearchETRTpIdID(String searchETRTpIdID) { this.searchETRTpIdID = searchETRTpIdID; } }
package org.pentaho.groovy.ui.spoon.repo; import java.util.List; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryDirectory; import org.pentaho.di.repository.RepositoryDirectoryInterface; import org.pentaho.di.repository.RepositoryElementMetaInterface; import org.pentaho.di.ui.spoon.Spoon; public class RepositoryDirectoryDecorator implements RepositoryDirectoryInterface { private RepositoryDirectoryInterface iface; public RepositoryDirectoryDecorator(RepositoryDirectoryInterface iface) { this.iface = iface; } @Override public String getName() { return iface.getName(); } @Override public ObjectId getObjectId() { return iface.getObjectId(); } @Override public List<RepositoryDirectoryInterface> getChildren() { return iface.getChildren(); } @Override public void setChildren(List<RepositoryDirectoryInterface> children) { iface.setChildren(children); } @Override public List<RepositoryElementMetaInterface> getRepositoryObjects() { return iface.getRepositoryObjects(); } @Override public void setRepositoryObjects(List<RepositoryElementMetaInterface> children) { iface.setRepositoryObjects(children); } @Override public boolean isVisible() { return iface.isVisible(); } @Override public String[] getPathArray() { return iface.getPathArray(); } @Override public RepositoryDirectoryInterface findDirectory(String path) { return iface.findDirectory(path); } @Override public RepositoryDirectoryInterface findDirectory(ObjectId id_directory) { return iface.findDirectory(id_directory); } @Override public RepositoryDirectoryInterface findDirectory(String[] path) { return iface.findDirectory(path); } @Override public ObjectId[] getDirectoryIDs() { return iface.getDirectoryIDs(); } @Override public String getPath() { return iface.getPath(); } @Override public int getNrSubdirectories() { return iface.getNrSubdirectories(); } @Override public RepositoryDirectory getSubdirectory(int i) { return iface.getSubdirectory(i); } @Override public boolean isRoot() { return iface.isRoot(); } @Override public RepositoryDirectoryInterface findRoot() { return iface.findRoot(); } @Override public void clear() { iface.clear(); } @Override public void addSubdirectory(RepositoryDirectoryInterface subdir) { iface.addSubdirectory(subdir); } @Override public void setParent(RepositoryDirectoryInterface parent) { iface.setParent(parent); } @Override public RepositoryDirectoryInterface getParent() { return iface.getParent(); } @Override public void setObjectId(ObjectId id) { iface.setObjectId(id); } @Override public void setName(String directoryname) { iface.setName(directoryname); } @Override public String getPathObjectCombination(String transName) { return iface.getPathObjectCombination(transName); } @Override public RepositoryDirectoryInterface findChild(String name) { return iface.findChild(name); } public RepositoryDirectoryList ls(String path) { String lsPath = (path == null) ? iface.getPath() : path; RepositoryDirectoryList dirList = null; try { RepositoryDirectoryInterface pathIface = Spoon.getInstance().getRepository().findDirectory(lsPath); if(pathIface != null) { RepositoryDirectoryDecorator rootDir = new RepositoryDirectoryDecorator(pathIface); dirList = new RepositoryDirectoryList(rootDir); dirList.add(new RepositoryDirectoryDecorator(rootDir)); if(rootDir.getChildren() != null) { for(RepositoryDirectoryInterface childDir : rootDir.getChildren()) { dirList.addAll(ls(childDir.getPath())); } } } return dirList; } catch(Exception e) { e.printStackTrace(System.err); return dirList; } } public void list(String path) { String lsPath = (path == null) ? iface.getPath() : path; try { for(RepositoryDirectoryInterface childDir : ls(lsPath)) { System.out.println(childDir.getPath()); } } catch(Exception e) { e.printStackTrace(System.err); } } public RepositoryDirectoryDecorator mkdir(String path) { if(path == null) return null; try { Repository repo = Spoon.getInstance().getRepository(); RepositoryDirectoryInterface parentDir = repo.findDirectory(RepositoryDirectory.DIRECTORY_SEPARATOR); String relPath = path; if(path.startsWith(RepositoryDirectory.DIRECTORY_SEPARATOR)) { relPath = path.substring(RepositoryDirectory.DIRECTORY_SEPARATOR.length()); } else { parentDir = repo.findDirectory(iface.getPath()); } return new RepositoryDirectoryDecorator(repo.createRepositoryDirectory(parentDir, relPath)); } catch(Exception e) { e.printStackTrace(System.err); return null; } } public void rmdir(String path) { try { Repository repo = Spoon.getInstance().getRepository(); String relPath = path; if(path == null) { relPath = iface.getPath(); } else { if(!path.startsWith(RepositoryDirectory.DIRECTORY_SEPARATOR)) { relPath = iface.getPath(); if(!relPath.endsWith(RepositoryDirectory.DIRECTORY_SEPARATOR)) { relPath += RepositoryDirectory.DIRECTORY_SEPARATOR; } relPath += path; } } RepositoryDirectoryInterface delDir = repo.findDirectory(relPath); repo.deleteRepositoryDirectory(delDir); } catch(Exception e) { e.printStackTrace(System.err); } } public RepositoryDirectoryDecorator dir(String path) { try { String lsPath = (path.startsWith(RepositoryDirectory.DIRECTORY_SEPARATOR)) ? path : iface.getPath() + RepositoryDirectory.DIRECTORY_SEPARATOR + path; RepositoryDirectoryInterface dir = Spoon.getInstance().getRepository().findDirectory(lsPath); return new RepositoryDirectoryDecorator(dir); } catch (Exception e) { e.printStackTrace(System.err); return null; } } }
package rs317; import jire.event.EventHandler; import jire.event.EventListener; import jire.event.EventPriority; import jire.packet.PacketParseEvent; import jire.packet.PacketRepresentation; import jire.packet.represent.HandshakeResponsePacket; import jire.packet.represent.LoginResponsePacket; import jire.plugin.AbstractPlugin; import jire.plugin.PluginManifest; @PluginManifest(name = "RS317", version = 1.3, description = "Configures the environment to use RS317 packet translation", authors = { "Thomas G. P. Nappo", "Ryley M. C. M. Kimmel" }) public final class RS317Plugin extends AbstractPlugin implements EventListener { @Override public void onEnable() { getServer().configurePacketTranslator(new RS317Translator()); getEventManager().registerListener(this); getLogger().debug("Successfully configured RS317 packet translation."); } @EventHandler(priority = EventPriority.MONITOR) public void onPacketParse(PacketParseEvent event) { PacketRepresentation rep = null; switch (event.getPacket().getID()) { case 14: rep = HandshakeResponsePacket.get(0, 0); break; case 16: rep = LoginResponsePacket.get(2, 0, false); break; default: return; } event.getClient().write(rep); } }