text
stringlengths
10
2.72M
package com.kadiraydemir.websocket; import java.util.HashSet; import java.util.Set; import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerEndpointConfig; public class ServerApplicationConfigDemo implements ServerApplicationConfig { @Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) { Set<ServerEndpointConfig> serverEndpointConfigSet = new HashSet<ServerEndpointConfig>(); serverEndpointConfigSet.add(ServerEndpointConfig.Builder.create(EndpointServerDemo.class, "/endpointserverdemo").build()); return serverEndpointConfigSet; } @Override public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> arg0) { return null; } }
package one.digitalInovation.dominio; //>>Classe PAI abstrata não pode ser instanciada em outras public abstract class Conteudo { //>>Classe protected >>só os filhos podem acessar protected static final double XP_PADRAO = 10.0; private String titulo; private String descricao; //Criando um metodo abstrato T1:00>> exportanto >> obriga a implementar nas classes filhas public abstract double calcularXp(); public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } }
/** * Created by Abuser on 5/2/2017. */ public class OsParser implements Parser { @Override public String parse(String line) { String res = null; if (line.toLowerCase().indexOf("windows") >= 0) { res = "Windows"; } else if (line.toLowerCase().indexOf("mac") >= 0) { res = "Mac"; } else if (line.toLowerCase().indexOf("x11") >= 0) { res = "Unix"; } else if (line.toLowerCase().indexOf("android") >= 0) { res = "Android"; } else if (line.toLowerCase().indexOf("iphone") >= 0) { res = "IPhone"; } else { res = "UnKnown"; } return res; } @Override public String getName() { return "OS"; } }
package br.com.missionsst.javacrud.domain.model; import javax.persistence.*; @Entity public class Departamento { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long codDepartamento; private String nomeDepartamento; @ManyToOne private Regiao codRegiao; public Long getCodDepartamento() { return codDepartamento; } public void setCodDepartamento(Long codDepartamento) { this.codDepartamento = codDepartamento; } public String getNomeDepartamento() { return nomeDepartamento; } public void setNomeDepartamento(String nomeDepartamento) { this.nomeDepartamento = nomeDepartamento; } public Regiao getCodRegiao() { return codRegiao; } public void setCodRegiao(Regiao codRegiao) { this.codRegiao = codRegiao; } }
package com.metoo.modul.app.game.tree.tools; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.Address; import com.metoo.foundation.domain.Game; import com.metoo.foundation.domain.GameTask; import com.metoo.foundation.domain.OrderForm; import com.metoo.foundation.domain.PlantingTrees; import com.metoo.foundation.domain.SubTrees; import com.metoo.foundation.domain.User; import com.metoo.foundation.service.IAddressService; import com.metoo.foundation.service.IGameTaskService; import com.metoo.foundation.service.IOrderFormService; import com.metoo.foundation.service.ISubTreesService; import com.metoo.foundation.service.IUserService; @Component public class AppGameTreeTools { @Autowired private IGameTaskService gameTaskService; @Autowired private IOrderFormService orderService; @Autowired private IUserService userService; @Autowired private ISubTreesService subTreesService; @Autowired private IAddressService addressService; // 下单赠送水滴-- 不用设置任务状态 public String grantWater(Map<String, Object> params) { if (!params.isEmpty()) { // TODO Auto-generated method stub GameTask gameTask = this.gameTaskService.getObjById(CommUtil.null2Long(params.get("game_task_id"))); if (gameTask != null) { Game game = gameTask.getGame(); if (game != null && game.getStatus() == 0) { if (gameTask != null) { // LinkedHashMap<Object, Object> map = Json.fromJson(LinkedHashMap.class, gameTask.getWater()); String user_id = params.get("user_id").toString(); String order_id = params.get("order_id").toString(); OrderForm order = this.orderService.getObjById(CommUtil.null2Long(params.get("order_id"))); User user = this.userService.getObjById(CommUtil.null2Long(user_id)); if (order != null && user != null) { if (order.getOrder_main() == 1) { int water = order.getTotalPrice().intValue(); /*for (Map.Entry<Object, Object> entry : map.entrySet()) { if (CommUtil.subtract(entry.getKey(), order_total_price) <= 0) { water = Integer.parseInt(entry.getValue().toString()); } }*/ user.setWater_drops_unused(user.getWater_drops_unused() + water); this.userService.update(user); return gameTask.getMessage(); } } } } return null; } } return null; } /** * 收获 * * @param user */ /*public void harvest(User user) { PlantingTrees plantingTree = user.getPlanting_trees(); if (plantingTree != null) { Trees trees = plantingTree.getTrees(); SubTrees subTrees = this.subTreesService.getObjById(plantingTree.getSub_trees()); Map params = new HashMap(); params.put("trees_id", trees.getId()); List<SubTrees> sub_trees = this.subTreesService.query( "SELECT obj FROM SubTrees obj WHERE obj.trees.id=:trees_id AND obj.status=(SELECT MAX(status) FROM SubTrees)", params, -1, -1); // 是否满级 if (subTrees.getStatus() == sub_trees.get(0).getStatus() && subTrees.getWatering() >= subTrees.getWatering()) { user.getTrees().add(trees); this.userService.update(user); } } }*/ public boolean fill_level(PlantingTrees plantingTree) { boolean fill_level = false; SubTrees subTrees = this.subTreesService.getObjById(plantingTree.getSub_trees()); Map params = new HashMap(); params.put("tree_id", plantingTree.getTree().getId()); List<SubTrees> sub_trees = this.subTreesService.query( "SELECT obj FROM SubTrees obj WHERE obj.tree.id=:tree_id AND obj.status=(SELECT MAX(status) FROM SubTrees)", params, -1, -1); // 是否满级 if (subTrees.getStatus() == sub_trees.get(0).getStatus() && subTrees.getWatering() >= subTrees.getWatering()) { fill_level = true; } return fill_level; } /** * 验证用户是否存在收货地址 * * @param user * @return */ public boolean verifyAddress(User user) { Map params = new HashMap(); params.put("user_id", user.getId()); List<Address> addressList = this.addressService.query("SELECT obj FROM Address obj WHERE obj.user.id=:user_id", params, -1, -1); if(addressList.size() > 0){ return true; } return false; } }
package org.spongepowered.asm.launch; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.LaunchClassLoader; import org.spongepowered.asm.launch.platform.CommandLineOptions; import java.io.File; import java.util.List; public class MyBootstrap implements ITweaker { private String[] launchArguments = new String[0]; public MyBootstrap() { MixinBootstrap.start(); } @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { if (args != null && !args.isEmpty()) { this.launchArguments = args.toArray(new String[0]); } MixinBootstrap.doInit(CommandLineOptions.ofArgs(args)); } @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { classLoader.addClassLoaderExclusion("com.mojang.util.QueueLogAppender"); classLoader.addClassLoaderExclusion("jline."); classLoader.addClassLoaderExclusion("org.fusesource."); classLoader.addClassLoaderExclusion("org.slf4j."); MixinBootstrap.inject(); } @Override public String getLaunchTarget() { return "org.bukkit.craftbukkit.Main"; } @Override public String[] getLaunchArguments() { return launchArguments; } }
package com.company; public class Painting { public static void main(String[] args) { int length = 32; int width = 40; int height = 16; int multi = (length*width) + (length*height*2) + (width*height*2) - (20*2) - (15*4); System.out.println (multi); int finale = multi/350; System.out.println(finale); System.out.println("You will need "+finale+" gallons of paint"); } }
package net.b07z.sepia.server.mesh.plugins; import org.json.simple.JSONObject; /** * Holds a result created via {@link Plugin} execute. * * @author Florian Quirin * */ public class PluginResult { JSONObject resultJson; public PluginResult(JSONObject result){ this.resultJson = result; } public JSONObject getJson(){ return resultJson; } }
package com.sl.web.category.vo; public class WebCategoryVO { private int cat_id; private int member_id; private String key_id; private int sort; private String crt_dt; private String crt_email; private String updt_dt; private String updt_email; public int getCat_id() { return cat_id; } public void setCat_id(int cat_id) { this.cat_id = cat_id; } public int getMember_id() { return member_id; } public void setMember_id(int member_id) { this.member_id = member_id; } public String getKey_id() { return key_id; } public void setKey_id(String key_id) { this.key_id = key_id; } public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } public String getCrt_dt() { return crt_dt; } public void setCrt_dt(String crt_dt) { this.crt_dt = crt_dt; } public String getCrt_email() { return crt_email; } public void setCrt_email(String crt_email) { this.crt_email = crt_email; } public String getUpdt_dt() { return updt_dt; } public void setUpdt_dt(String updt_dt) { this.updt_dt = updt_dt; } public String getUpdt_email() { return updt_email; } public void setUpdt_email(String updt_email) { this.updt_email = updt_email; } }
package com.qst.servlet; import com.qst.bean.Applicant; import com.qst.bean.ResumeBasicInfo; import com.qst.dao.ApplicantDAO; import com.qst.dao.ResumeDAO; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet(urlPatterns = "/ApplicantLoginServlet") public class ApplicantLoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String user = request.getParameter("user"); String password = request.getParameter("password"); //根据email和密码查询申请人 ApplicantDAO applicantDAO=new ApplicantDAO(); Applicant applicant=applicantDAO.getApplicantByUserAndPass(user,password); // System.out.println(applicant); if(applicant!=null){ //将登陆用户对象保存到session request.getSession().setAttribute("SESSION_APPLICANT",applicant); //用户名和密码正确,是否填写简历 //按照当前登录用户user判断,用户是否填写简历 Integer qid=applicantDAO.isExistResume(applicant.getUser()); // System.out.println(qid); if (qid!=null) { //将简历放入session中 request.getSession().setAttribute("SESSION_QID",qid); response.sendRedirect("index.html"); /*request.getRequestDispatcher("index.html").forward(request,response);*/ }else{ response.sendRedirect("applicant/resumeBasicInfoAdd.jsp"); } }else{ PrintWriter writer = response.getWriter(); writer.write("<script>"); writer.write("alert('用户名或密码错误!');"); writer.write("window.location.href='login.html';"); writer.write("</script>"); writer.flush(); writer.close(); } } }
package hu.fallen.popularmovies.database; import android.net.Uri; import android.provider.BaseColumns; public class FavoriteMoviesContract { private FavoriteMoviesContract() {} static final String AUTHORITY = "hu.fallen.popularmovies"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY); public static final String PATH_MOVIE = "movie"; public static final String PATH_FAVORITE = PATH_MOVIE + "/favorite"; public static class MovieEntry implements BaseColumns { static final String TABLE_NAME = "movie"; public static final String COLUMN_NAME_POSTER_PATH = "poster_path"; public static final String COLUMN_NAME_OVERVIEW = "overview"; public static final String COLUMN_NAME_RELEASE_DATE = "release_date"; public static final String COLUMN_NAME_ID = "id"; public static final String COLUMN_NAME_ORIGINAL_TITLE = "original_title"; public static final String COLUMN_NAME_VOTE_AVERAGE = "vote_average"; } static final String SQL_CREATE_MOVIE_ENTRIES = "CREATE TABLE " + MovieEntry.TABLE_NAME + " (" + MovieEntry._ID + " INTEGER PRIMARY KEY, " + MovieEntry.COLUMN_NAME_POSTER_PATH + " TEXT, " + MovieEntry.COLUMN_NAME_OVERVIEW + " TEXT, " + MovieEntry.COLUMN_NAME_RELEASE_DATE + " TEXT, " + MovieEntry.COLUMN_NAME_ID + " INTEGER, " + MovieEntry.COLUMN_NAME_ORIGINAL_TITLE + " TEXT, "+ MovieEntry.COLUMN_NAME_VOTE_AVERAGE + " REAL" + ")"; static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + MovieEntry.TABLE_NAME; }
package com.cts.aopdemo.service; public interface GreetService { String greet(String userName); }
package com.tianwotian.tools; /** * 生成6位随机数 */ public class GenerateSixRandomNums { public static int count; public static int generateSixNums(){ count = (int) ((Math.random()*9+1)*100000); return count; } }
package org.example.utility.common; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class DateUtil { private static final DateUtil o = new DateUtil(); public DateUtil() { } public static DateUtil get() { return o; } public String localDateToStr(LocalDateTime localDateTime) { return localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); } public String localTimeToStr(LocalDateTime localDateTime) { return localDateTime.format(DateTimeFormatter.ofPattern("HHmmss")); } public String localDateTimeToStr(LocalDateTime localDateTime) { return localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); } public LocalTime strToLocalTime(String strTime){ return LocalTime.parse(strTime,DateTimeFormatter.ofPattern("HHmmss")); } public LocalDateTime strToLocalDateTime(String strDate) { return LocalDateTime.parse(strDate, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); } }
package com.zantong.mobilecttx.utils.dialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.zantong.mobilecttx.R; /** * 自定义dialog * * @author Wanghy */ public class NetLocationDialog extends Dialog { //定义回调事件,用于dialog的点击事件 public interface OnChooseDialogListener { void back(String[] name); } private String[] name; private OnChooseDialogListener chooseDialogListener; EditText etName; private int layou; private NetlocationPicker mNetlocationPicker; public NetLocationDialog(Context context, String[] name, OnChooseDialogListener chooseDialogListener) { super(context); this.name = name; this.chooseDialogListener = chooseDialogListener; } @Override protected void onCreate(Bundle savedInstanceState) { //设置标题 super.onCreate(savedInstanceState); setContentView(R.layout.netlocationpickers); // setTitle(name); mNetlocationPicker = (NetlocationPicker) findViewById(R.id.citypicker); Button btn_choose = (Button) findViewById(R.id.btn_choose); if (name != null) { mNetlocationPicker.setDefaultLocation(name); } btn_choose.setOnClickListener(clickListener); } private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { try { // int month = Integer.parseInt(mCityPicker.getMonth()); // int day = Integer.parseInt(mCityPicker.getDay()); // String tempMonth = String.valueOf(month); // String tempDay = String.valueOf(day); // if (month < 10) { // tempMonth = "0" + tempMonth; // } // if (day < 10) { // tempDay = "0" + tempDay; // } String[] data = new String[5]; data[0] = mNetlocationPicker.getProvince(); data[1] = mNetlocationPicker.getDataBean().getNetLocationCode(); data[2] = mNetlocationPicker.getCity(); data[3] = mNetlocationPicker.getDataBean().getNetLocationXiang(); data[4] = mNetlocationPicker.getDataBean().getNetLocationNumber(); // data[2] = mCityPicker.getDistrinc(); if (chooseDialogListener != null) chooseDialogListener.back(data); NetLocationDialog.this.dismiss(); } catch (Exception e) { } } }; }
package com.example.springboot.urlshortener.controller; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.HttpServletResponse; import org.apache.commons.validator.routines.UrlValidator; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.example.springboot.urlshortener.entity.URLPair; import com.example.springboot.urlshortener.service.URLShortenerService; @Controller @RequestMapping("/shortener") public class URLController { private Logger logger = Logger.getLogger(getClass().getName()); private URLShortenerService customerService; public URLController(URLShortenerService theCustomerService) { customerService = theCustomerService; } @GetMapping("") public String showHomePage(Model theModel) { logger.info("[Log info] home page"); // create model attribute to bind form data URLPair theUrl = new URLPair(); theModel.addAttribute("url", theUrl); return "shortener/home-form"; } @PostMapping("") public String shortenUrl(@ModelAttribute("url") URLPair theUrl) { logger.info("[Log info] going to get a shortened URL"); // generate the short URL String longUrl = theUrl.getLongUrl(); logger.info("[Log info] The long URL is: " + longUrl); //check the original long URL is valid URL or not UrlValidator urlValidator = new UrlValidator(); if (!urlValidator.isValid(longUrl) && !urlValidator.isValid("https://" + longUrl) && !urlValidator.isValid("http://" + longUrl) && !urlValidator.isValid("https" + longUrl) && !urlValidator.isValid("http:" + longUrl)) { logger.info("[Log info] URL is invalid"); return "shortener/invalid-url"; } else { String shortUrl = customerService.searchOrGenerateShortUrl(longUrl); theUrl.setShortUrl(shortUrl); logger.info("[Log info] the short URL is: " + theUrl.getShortUrl()); return "shortener/shortener-result"; } } @GetMapping(path = "/{shortU}") public void redirect(@PathVariable String shortU, HttpServletResponse response) throws IOException { logger.info("[Log info] the short URL to be redirected is: " + shortU); URLPair theUrl = customerService.findUrlByShortUrl(shortU); if (theUrl == null) { logger.info("[Log info] the short URL to be redirected doesn't exist in the database."); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String longUrl = theUrl.getLongUrl(); logger.info("[Log info] the original long URL is: " + longUrl); if (longUrl.startsWith("://")) { longUrl = "http" + longUrl; } else if (!longUrl.startsWith("http")) { longUrl = "http://" + longUrl; } logger.info("[Log info] redirect to: " + longUrl); response.sendRedirect(longUrl); return; } }
package com.prestech.chitchat.service.imp; import com.prestech.chitchat.service.AuthService; public class AuthServiceImp implements AuthService { }
package com.esrinea.dotGeo.tracking.model.component.sensorConfiguration.dao; import java.util.List; import org.apache.log4j.Logger; import com.esrinea.dotGeo.tracking.model.common.dao.AbstractDAO; import com.esrinea.dotGeo.tracking.model.component.sensorConfiguration.entity.SensorConfiguration; public class SensorConfigurationDAOImpl extends AbstractDAO<SensorConfiguration> implements SensorConfigurationDAO { private static Logger LOG = Logger.getLogger(SensorConfigurationDAOImpl.class); public SensorConfigurationDAOImpl() { super(SensorConfiguration.class); } @Override public List<SensorConfiguration> find(int sensorId, boolean retired) { LOG.debug(String.format("SensorConfiguration.findBySensorIdRetired is called, parameters: %s, %s", sensorId, retired)); List<SensorConfiguration> sensorConfigurations = entityManager .createNamedQuery("SensorConfiguration.findBySensorIdRetired", SensorConfiguration.class).setParameter("sensorId", sensorId) .setParameter("retired", retired).getResultList(); if (sensorConfigurations.isEmpty()) { LOG.info(String.format("%s with ID %s has no %s sensor configurations.", "Sensor", sensorId, retired ? "retired" : "active")); } return sensorConfigurations; } }
// // Decompiled by Procyon v0.5.36 // package com.davivienda.sara.administracion.programadortareas; import java.util.Calendar; import java.util.Locale; import java.util.Date; import java.util.GregorianCalendar; import com.davivienda.utilidades.conversion.Fecha; import com.davivienda.sara.config.SaraConfig; public class ProgramadorTareas { protected SaraConfig appConfiguracion; protected static final long DIA_EN_MILISEGUNDOS = 86400000L; protected static final long HORA_EN_MILESEGUNDOS = 3600000L; protected static final long MINUTO_EN_MILESEGUNDOS = 60000L; protected long getHoraInicioProgramador(final int horaProgramacionTimer) { final Locale loc = Fecha.ZONA_FECHA; final Calendar cal = new GregorianCalendar(loc); cal.setTime(new Date()); final long horaActualMili = cal.get(11) * 3600000L + cal.get(12) * 60000L + cal.get(13) * 1000; long horaInicio = 0L; if (horaActualMili < horaProgramacionTimer) { horaInicio = horaProgramacionTimer - horaActualMili; } else { horaInicio = 86400000L - horaActualMili + horaProgramacionTimer; } return horaInicio; } }
package com.chinasoft.dao; import java.util.List; import com.chinasoft.domain.Clothing; import com.chinasoft.domain.Rkmx; public interface RkmxDao extends BaseDao<Rkmx>{ List<Rkmx> findAllRkmxLists(Integer rkdId) throws Exception; }
package com.dian.diabetes.activity.sugar; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.dian.diabetes.R; import com.dian.diabetes.activity.sugar.adapter.SugarTotalAdapter; import com.dian.diabetes.activity.sugar.model.CountModel; import com.dian.diabetes.db.dao.Diabetes; import com.dian.diabetes.tool.Config; import com.dian.diabetes.utils.ContantsUtil; import com.dian.diabetes.utils.DateUtil; import com.dian.diabetes.widget.VerticalViewPager; import com.dian.diabetes.widget.anotation.ViewInject; public class SugarTotalChartFragment extends TotalBaseFragment { @ViewInject(id = R.id.sugar_total) private VerticalViewPager totalView; private SugarTotalAdapter adaper; private SugarTotalFragment parent; private int model = 0; private List<List<CountModel>> sugarData; private List<String> data; private boolean iscreate = false; public static SugarTotalChartFragment getInstance() { return new SugarTotalChartFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); parent = (SugarTotalFragment) getParentFragment(); sugarData = new ArrayList<List<CountModel>>(); data = initAdapterData(); adaper = new SugarTotalAdapter(getChildFragmentManager(), data); } /** * 初始化数据,写死算了 * * @return */ private List<String> initAdapterData() { List<String> data = new ArrayList<String>(); data.add("44"); data.add(ContantsUtil.BRECKFAST + "" + ContantsUtil.EAT_PRE); data.add(ContantsUtil.BRECKFAST + "" + ContantsUtil.EAT_AFTER); data.add(ContantsUtil.LAUNCH + "" + ContantsUtil.EAT_PRE); data.add(ContantsUtil.LAUNCH + "" + ContantsUtil.EAT_AFTER); data.add(ContantsUtil.DINNER + "" + ContantsUtil.EAT_PRE); data.add(ContantsUtil.DINNER + "" + ContantsUtil.EAT_AFTER); data.add(ContantsUtil.SLEEP_PRE + "" + ContantsUtil.EAT_PRE); return data; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sugar_total, container, false); fieldView(view); initView(view); return view; } private void initView(View view) { if (!Config.getPageState(className)) { new DataTask().execute(); Config.pageMap.put(className, true); } totalView.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { parent.switchChartModel(position); model = position; } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int position) { } }); } private void initData() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, parent.getDay()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Map<String, Diabetes> list = parent.getMapData(); List<CountModel> all = new ArrayList<CountModel>(); List<CountModel> brekPre = new ArrayList<CountModel>(); List<CountModel> brekAfter = new ArrayList<CountModel>(); List<CountModel> lunchPre = new ArrayList<CountModel>(); List<CountModel> lunchAfter = new ArrayList<CountModel>(); List<CountModel> dinnerPre = new ArrayList<CountModel>(); List<CountModel> dinnerAfter = new ArrayList<CountModel>(); List<CountModel> sleep = new ArrayList<CountModel>(); int index = 0,delta = - parent.getDelta(); int brekPrei = 0, brekAfteri = 0, lunchPrei = 0, lunchAfteri = 0, dinnerPrei = 0, dinnerAfteri = 0, sleepi = 0; float brekPref = 0, brekAfterf = 0, lunchPref = 0, lunchAfterf = 0, dinnerPref = 0, dinnerAfterf = 0, sleepf = 0; int preMonth = -1; for (int i = 0; i > parent.getDay(); i=i-delta) { calendar.add(Calendar.DATE, delta); index++; String day = DateUtil.parseToString(calendar.getTime(), DateUtil.yyyyMMdd); int tempMonth = calendar.get(Calendar.MONTH); String dayout; if(tempMonth == preMonth){ dayout = DateUtil.parseToString(calendar.getTime(), DateUtil.dd); }else{ dayout = DateUtil.parseToString(calendar.getTime(), DateUtil.MMdd); } preMonth = tempMonth; // 早餐前 Diabetes bpre = list.get(day + ContantsUtil.BRECKFAST + ContantsUtil.EAT_PRE); Diabetes bafter = list.get(day + ContantsUtil.BRECKFAST + ContantsUtil.EAT_AFTER); Diabetes lpre = list.get(day + ContantsUtil.LAUNCH + ContantsUtil.EAT_PRE); Diabetes lafter = list.get(day + ContantsUtil.LAUNCH + ContantsUtil.EAT_AFTER); Diabetes dpre = list.get(day + ContantsUtil.DINNER + ContantsUtil.EAT_PRE); Diabetes dafter = list.get(day + ContantsUtil.DINNER + ContantsUtil.EAT_AFTER); Diabetes sleepDiabetes = list.get(day + ContantsUtil.SLEEP_PRE + ContantsUtil.EAT_PRE); if (bpre != null) { brekPref += bpre.getValue(); brekPrei ++; } if (bafter != null) { brekAfterf += bafter.getValue(); brekAfteri ++; } if (lpre != null) { lunchPref += lpre.getValue(); lunchPrei ++; } if (lafter != null) { lunchAfterf += lafter.getValue(); lunchAfteri ++; } if (dpre != null) { dinnerPref += dpre.getValue(); dinnerPrei ++; } if (dafter != null) { dinnerAfterf += dafter.getValue(); dinnerAfteri ++; } if (sleepDiabetes != null) { sleepf += sleepDiabetes.getValue(); sleepi ++; } //if (index == delta || i == (parent.getDay() + 1)) { brekPre.add(getCountModel(dayout,brekPref/brekPrei)); brekAfter.add(getCountModel(dayout,brekAfterf/brekAfteri)); lunchPre.add(getCountModel(dayout,lunchPref/lunchPrei)); lunchAfter.add(getCountModel(dayout,lunchAfterf/lunchAfteri)); dinnerPre.add(getCountModel(dayout,dinnerPref/dinnerPrei)); dinnerAfter.add(getCountModel(dayout,dinnerAfterf/dinnerAfteri)); sleep.add(getCountModel(dayout,sleepf/sleepi)); float allValue = (brekPref + brekAfterf +lunchPref+lunchAfterf+dinnerPref+dinnerAfterf+sleepf) /(brekPrei + brekAfteri +lunchPrei+lunchAfteri+dinnerPrei+dinnerAfteri+sleepi); all.add(getCountModel(dayout,allValue)); index = 0; brekPref = brekAfterf = lunchPref = lunchAfterf = 0; dinnerPref = dinnerAfterf = sleepf = 0; brekPrei = brekAfteri = lunchPrei = lunchAfteri = 0; dinnerPrei = dinnerAfteri = sleepi = 0; //} } sugarData.clear(); sugarData.add(all); sugarData.add(brekPre); sugarData.add(brekAfter); sugarData.add(lunchPre); sugarData.add(lunchAfter); sugarData.add(dinnerPre); sugarData.add(dinnerAfter); sugarData.add(sleep); } private CountModel getCountModel(String day,float value){ CountModel model = new CountModel(); if(Float.isNaN(value)){ model.setValue(0); }else{ model.setValue((float)(Math.round(value*100))/100); } model.setDate(day); return model; } public void onDestroy(){ super.onDestroy(); } public void notifyData() { new DataTask().execute(); } public void setCurentPage(int position) { totalView.setCurrentItem(position); } public List<CountModel> getData(int position){ return sugarData.get(position); } public int getModel() { return model; } private class DataTask extends AsyncTask<Object, Object, Object> { @Override protected Object doInBackground(Object... arg0) { initData(); return null; } @Override protected void onPostExecute(Object result) { if(iscreate){ adaper.notifyDataSetChanged(); }else{ totalView.setAdapter(adaper); totalView.setCurrentItem(model); } } } }
/** * */ package ethan.traffic; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @since 2013-10-31 * @author ethan * @version $Id$ */ public class Road { private String name; private List<String> cars = new ArrayList<String>(); public Road(String name) { this.name = name; //^^ 使用线程池生产汽车,防止Road构造方法难产 Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { for (int i = 1; i < 1000; i++) { // 车经过的频率为0到5秒 try { // Thread.sleep(new Random().nextInt(2) * 1000); Thread.sleep((new Random().nextInt(10) + 1) * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //^^ cars.add(Road.this.name + "_" + i); } } }); //由方法调用改成定时器每隔一段时间自动检查车辆是否放行 // public void carGothrought() { // boolean lighted = Lamp.valueOf(name).isLighted(); // if(lighted){ // System.out.println(cars.remove(0)+" is go throught ..."); // } // // } //检查绿灯的调度 Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(new Runnable() { @Override public void run() { if(cars.size()>0){ System.out.println(cars.size()+"---------------------------------"); boolean lighted = Lamp.valueOf(Road.this.name).isLighted(); if(lighted){ //^^经典编程思想,从你的口袋拿走馒头,并返回给我 System.out.println(cars.remove(0)+" is go throught ..."); } } } }, 1, 1, TimeUnit.SECONDS); } }
package com.xinhua.api.domain.xQczBean; import com.apsaras.aps.increment.domain.AbstractIncRequest; import java.io.Serializable; /** * Created by lirs_wb on 2015/8/25. * 续期冲正 请求 */ public class XuQCZRequest extends AbstractIncRequest implements Serializable { private String bankDate; private String transExeTime; private String bankCode; private String regionCode; private String branch; private String teller; private String authTellerNo; private String postCode; private String transRefGUID; private String functionFlag; private String transType; private String carrierCode; private String transMode; private String corTransrNo; private String orgTransDate; private String transCode; private String bkOthOldSeq; private String originalTransRefGUID; private String bkTellerNo; private String bkChnlNo; private String bkPlatSeqNo; private String bkBrchNo; private String bkBrchName; private String transNo; private String insuTrans; private String transSide; private String entrustWay; private String provCode; private String grossPremAmt; private String polNumber; private String hOAppFormNumber; private String prodCode; private String password; private String undoSum; private String prem; private String payDate; private String pDate; private String finActivityType; private String accountNumber; private String mainProductId; private String productCode; private String bdPrintNo; public String getBankDate() { return bankDate; } public void setBankDate(String bankDate) { this.bankDate = bankDate; } public String getTransExeTime() { return transExeTime; } public void setTransExeTime(String transExeTime) { this.transExeTime = transExeTime; } public String getBankCode() { return bankCode; } public void setBankCode(String bankCode) { this.bankCode = bankCode; } public String getRegionCode() { return regionCode; } public void setRegionCode(String regionCode) { this.regionCode = regionCode; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getTeller() { return teller; } public void setTeller(String teller) { this.teller = teller; } public String getAuthTellerNo() { return authTellerNo; } public void setAuthTellerNo(String authTellerNo) { this.authTellerNo = authTellerNo; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getTransRefGUID() { return transRefGUID; } public void setTransRefGUID(String transRefGUID) { this.transRefGUID = transRefGUID; } public String getFunctionFlag() { return functionFlag; } public void setFunctionFlag(String functionFlag) { this.functionFlag = functionFlag; } public String getTransType() { return transType; } public void setTransType(String transType) { this.transType = transType; } public String getCarrierCode() { return carrierCode; } public void setCarrierCode(String carrierCode) { this.carrierCode = carrierCode; } public String getTransMode() { return transMode; } public void setTransMode(String transMode) { this.transMode = transMode; } public String getCorTransrNo() { return corTransrNo; } public void setCorTransrNo(String corTransrNo) { this.corTransrNo = corTransrNo; } public String getOrgTransDate() { return orgTransDate; } public void setOrgTransDate(String orgTransDate) { this.orgTransDate = orgTransDate; } public String getTransCode() { return transCode; } public void setTransCode(String transCode) { this.transCode = transCode; } public String getBkOthOldSeq() { return bkOthOldSeq; } public void setBkOthOldSeq(String bkOthOldSeq) { this.bkOthOldSeq = bkOthOldSeq; } public String getOriginalTransRefGUID() { return originalTransRefGUID; } public void setOriginalTransRefGUID(String originalTransRefGUID) { this.originalTransRefGUID = originalTransRefGUID; } public String getBkTellerNo() { return bkTellerNo; } public void setBkTellerNo(String bkTellerNo) { this.bkTellerNo = bkTellerNo; } public String getBkChnlNo() { return bkChnlNo; } public void setBkChnlNo(String bkChnlNo) { this.bkChnlNo = bkChnlNo; } public String getBkPlatSeqNo() { return bkPlatSeqNo; } public void setBkPlatSeqNo(String bkPlatSeqNo) { this.bkPlatSeqNo = bkPlatSeqNo; } public String getBkBrchNo() { return bkBrchNo; } public void setBkBrchNo(String bkBrchNo) { this.bkBrchNo = bkBrchNo; } public String getBkBrchName() { return bkBrchName; } public void setBkBrchName(String bkBrchName) { this.bkBrchName = bkBrchName; } public String getTransNo() { return transNo; } public void setTransNo(String transNo) { this.transNo = transNo; } public String getInsuTrans() { return insuTrans; } public void setInsuTrans(String insuTrans) { this.insuTrans = insuTrans; } public String getTransSide() { return transSide; } public void setTransSide(String transSide) { this.transSide = transSide; } public String getEntrustWay() { return entrustWay; } public void setEntrustWay(String entrustWay) { this.entrustWay = entrustWay; } public String getProvCode() { return provCode; } public void setProvCode(String provCode) { this.provCode = provCode; } public String getGrossPremAmt() { return grossPremAmt; } public void setGrossPremAmt(String grossPremAmt) { this.grossPremAmt = grossPremAmt; } public String getPolNumber() { return polNumber; } public void setPolNumber(String polNumber) { this.polNumber = polNumber; } public String gethOAppFormNumber() { return hOAppFormNumber; } public void sethOAppFormNumber(String hOAppFormNumber) { this.hOAppFormNumber = hOAppFormNumber; } public String getProdCode() { return prodCode; } public void setProdCode(String prodCode) { this.prodCode = prodCode; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUndoSum() { return undoSum; } public void setUndoSum(String undoSum) { this.undoSum = undoSum; } public String getPrem() { return prem; } public void setPrem(String prem) { this.prem = prem; } public String getPayDate() { return payDate; } public void setPayDate(String payDate) { this.payDate = payDate; } public String getpDate() { return pDate; } public void setpDate(String pDate) { this.pDate = pDate; } public String getFinActivityType() { return finActivityType; } public void setFinActivityType(String finActivityType) { this.finActivityType = finActivityType; } public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getMainProductId() { return mainProductId; } public void setMainProductId(String mainProductId) { this.mainProductId = mainProductId; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getBdPrintNo() { return bdPrintNo; } public void setBdPrintNo(String bdPrintNo) { this.bdPrintNo = bdPrintNo; } }
package view.insuranceSystemView.salesView.salesMan; import java.awt.Color; import java.awt.event.ActionListener; import view.aConstant.InsuranceSystemViewConstant; import view.component.BasicLabel; import view.component.SeparateLine; import view.component.button.LinkButton; import view.component.button.SelectButton; import view.component.group.StaticGroup; import view.insuranceSystemView.absInsuranceSystemView.InsuranceSystemView; @SuppressWarnings("serial") public class SalesManTaskSelectView extends InsuranceSystemView { // Static public enum EActionCommands {SigninCustomer,LookupAvailableProduct,WatchActivityPlan, WatchSalesTrainingPlan} // Constructor public SalesManTaskSelectView(ActionListener actionListener) { // add component this.addComponent(new BasicLabel("원하시는 업무를 선택하세요.")); this.addComponent(new SeparateLine(Color.black)); StaticGroup g = new StaticGroup(new int[] {1,1,1,1}); g.addGroupComponent(new SelectButton("고객 가입", EActionCommands.SigninCustomer.name(), actionListener)); g.addGroupComponent(new SelectButton("가능 보험 조회", EActionCommands.LookupAvailableProduct.name(), actionListener)); g.addGroupComponent(new SelectButton("판매 활동 조회", EActionCommands.WatchActivityPlan.name(), actionListener)); g.addGroupComponent(new SelectButton("영업 활동 조회", EActionCommands.WatchSalesTrainingPlan.name(), actionListener)); this.addComponent(g); this.addToLinkPanel( new LinkButton(InsuranceSystemViewConstant.SomeThingLookGreat, "", null), new LinkButton(InsuranceSystemViewConstant.SomeThingLookNide, "", null), new LinkButton("고객 가입", EActionCommands.SigninCustomer.name(), actionListener), new LinkButton("가능 보험 조회", EActionCommands.LookupAvailableProduct.name(), actionListener), new LinkButton("판매 활동 조회", EActionCommands.WatchActivityPlan.name(), actionListener), new LinkButton("영업 활동 조회", EActionCommands.WatchSalesTrainingPlan.name(), actionListener) ); } }
package edu.mum.sonet.models; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.ManyToOne; @Data @NoArgsConstructor @Entity public class UserNotificationJoin extends BaseEntity { @ManyToOne private User user; @ManyToOne private UserNotification userNotification; }
package com.company; public class Masinuta extends PistaMasini { String brandMasina; int nrUsi; public Masinuta(int anAparitie, boolean calitate, String nume, String culoare, String tipMaterial, boolean copiiSubCinciAni, boolean instructiuniAsamblare, float dimensiune, boolean esteInTrend, String brandMasina, int nrUsi) { super(anAparitie, calitate, nume, culoare, tipMaterial, copiiSubCinciAni, instructiuniAsamblare, dimensiune, esteInTrend); this.brandMasina = brandMasina; this.nrUsi = nrUsi; } void showMasinuta() { System.out.println("Brand masinuta: " + brandMasina); System.out.println("Numar usi: " + nrUsi); } }
package com.framgia.fsalon.data.model; import com.framgia.fsalon.FSalonApplication; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import static com.framgia.fsalon.utils.Constant.DATE_FORMAT_MM_DD_YYYY; import static com.framgia.fsalon.utils.Constant.DAY_OF_WEEK_FORMAT; /** * Created by MyPC on 20/07/2017. */ public class DateBooking { private String mDay; private String mDayOfWeek; private String mDateTime; private long mTimeMillis; public DateBooking(String day, long timeMillis) { mDay = day; mTimeMillis = timeMillis / 1000; Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeMillis); SimpleDateFormat formatDayOfWeek = new SimpleDateFormat(DAY_OF_WEEK_FORMAT, Locale.US); setDayOfWeek(formatDayOfWeek.format(calendar.getTime())); SimpleDateFormat formatDate = new SimpleDateFormat(DATE_FORMAT_MM_DD_YYYY, Locale.US); setDateTime(formatDate.format(calendar.getTime())); } public String getDay() { return mDay; } public void setDay(String day) { mDay = day; } public String getDayOfWeek() { return mDayOfWeek; } public void setDayOfWeek(String dayOfWeek) { mDayOfWeek = dayOfWeek; } public String getDateTime() { return mDateTime; } public void setDateTime(String dateTime) { mDateTime = dateTime; } public long getTimeMillis() { return mTimeMillis; } public void setTimeMillis(long timeMillis) { mTimeMillis = timeMillis; } private String getStringRes(int resId) { return FSalonApplication.getInstant().getResources().getString(resId); } }
package com.jxtb.thread.run; import com.core.exception.BdRuntimeException; import com.jxtb.thread.RunThreadService; import com.jxtb.thread.server.service.SyncTestService; import com.util.ConfigurationHelper; import org.apache.log4j.Logger; import javax.annotation.Resource; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 17-3-30 * Time: 上午11:07 * To change this template use File | Settings | File Templates. */ public class ThreadTestServiceImpl extends RunThreadService { private Logger logger = Logger.getLogger(ThreadTestServiceImpl.class); @Resource(name = "syncTestService") protected SyncTestService syncTestService; public void startRun() { logger.info("==============启动发送队列同步程序=============="); alive = true; thread = new Thread(this, "ThreadTestServiceImpl"); thread.setDaemon(false); thread.start(); } /** * * 服务停止方法 * * */ public void stopRun() { alive = false; if (thread != null) { thread.interrupt(); thread = null; } } @Override public void run() { try { logger.info("加载配置文件中........."); Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } while (alive) { try { syncTestService.doSyncInfo();//启动同步 //主线程配置时间 int minus = ConfigurationHelper.getProperty("main.thread.sleep")==null?1:Integer.valueOf(ConfigurationHelper.getProperty("main.thread.sleep")); Thread.sleep(minus*1000*60); }catch (BdRuntimeException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package io.github.satr.aws.lambda.bookstore.strategies.intenthandler; // Copyright © 2022, github.com/satr, MIT License import com.amazonaws.services.lambda.runtime.LambdaLogger; import io.github.satr.aws.lambda.bookstore.constants.IntentSlotName; import io.github.satr.aws.lambda.bookstore.constants.IntentSlotValue; import io.github.satr.aws.lambda.bookstore.constants.SessionAttributeKey; import io.github.satr.aws.lambda.bookstore.entity.Book; import io.github.satr.aws.lambda.bookstore.entity.formatter.MessageFormatter; import io.github.satr.aws.lambda.bookstore.request.Request; import io.github.satr.aws.lambda.bookstore.respond.Response; import io.github.satr.aws.lambda.bookstore.services.BookStorageService; import io.github.satr.aws.lambda.bookstore.services.SearchBookResultService; import io.github.satr.aws.lambda.bookstore.strategies.booksearch.*; import java.util.HashMap; import java.util.List; import java.util.Map; public class SearchBookByTitleIntentHandlerStrategy extends AbstractIntentHandlerStrategy { private final BooksWithTitleSearchStrategy booksWithTitleSearchStrategy; private final SearchBookResultService searchBookResultService; private Map<String, BookSearchStrategy> bookSearchStrategies = new HashMap<>(); public SearchBookByTitleIntentHandlerStrategy(BookStorageService bookStorageService, SearchBookResultService searchBookResultService, MessageFormatter messageFormatter) { super(messageFormatter); this.searchBookResultService = searchBookResultService; bookSearchStrategies.put(IntentSlotValue.WordsPosition.Starts, new BooksWithTitleStartingWithTextSearchStrategy(bookStorageService)); bookSearchStrategies.put(IntentSlotValue.WordsPosition.Ends, new BooksWithTitleEndingWithTextSearchStrategy(bookStorageService)); bookSearchStrategies.put(IntentSlotValue.WordsPosition.Contains, new BooksWithTitleContainingTextSearchStrategy(bookStorageService)); booksWithTitleSearchStrategy = new BooksWithTitleSearchStrategy(bookStorageService); } @Override public Response handle(Request request, LambdaLogger logger) { StringBuilder responseMessageBuilder = new StringBuilder(); String wordsPosition = request.getSlot(IntentSlotName.WordsPosition); String titleQuery = request.getSlot(IntentSlotName.BookTitle); if(titleQuery == null || titleQuery.length() < 2) { logger.log(String.format("SearchBookByTitle: WordsPosition=\"%s\", BookTitle=\"%s\"", wordsPosition, titleQuery)); return getCloseFulfilledLexRespond(request, getInvalidTitleMessage(wordsPosition)); } responseMessageBuilder.append(getQueryDescription(wordsPosition, titleQuery) + "\n"); List<Book> bookSearchResult = getBookSearchStrategyBy(wordsPosition).queryBy(titleQuery); searchBookResultService.put(bookSearchResult); if (bookSearchResult.isEmpty()) { responseMessageBuilder.append("No books found. Please try another criteria."); return getCloseFulfilledLexRespond(request, responseMessageBuilder); } responseMessageBuilder.append(messageFormatter.getBookShortDescriptionList(bookSearchResult, "Found %s:\n", messageFormatter.amountOfBooks(bookSearchResult.size()))); Response respond = getCloseFulfilledLexRespond(request, responseMessageBuilder); if(bookSearchResult.size() == 1) respond.setSessionAttribute(SessionAttributeKey.SelectedBookIsbn, bookSearchResult.get(0).getIsbn());//auto-select the only found book else respond.removeSessionAttribute(SessionAttributeKey.SelectedBookIsbn); return respond; } private StringBuilder getInvalidTitleMessage(String wordsPosition) { StringBuilder builder = new StringBuilder("Sorry, could you repeat what a title " + wordsPosition); if(!wordsPosition.equals(IntentSlotValue.WordsPosition.Contains)) builder.append(" with"); builder.append("?"); return builder; } private BookSearchStrategy getBookSearchStrategyBy(String wordsPosition) { return bookSearchStrategies.getOrDefault(wordsPosition, booksWithTitleSearchStrategy); } private String getQueryDescription(String wordsPosition, String titleQuery) { return wordsPosition == null ? String.format("Searched books by title: \"%s\"", titleQuery) : String.format("Searched books \"%s\" in title \"%s\"", wordsPosition, titleQuery); } }
package com.example.gamedb.adapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.gamedb.R; import com.example.gamedb.db.entity.Video; import java.util.ArrayList; import java.util.List; public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.VideoListViewModel> { private List<Video> mVideos = new ArrayList<>(); public void setVideos(List<Video> videos) { mVideos = videos; } @NonNull @Override public VideoListViewModel onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_list_item, parent, false); return new VideoListViewModel(view); } @Override public void onBindViewHolder(@NonNull VideoListViewModel holder, int position) { Video video = mVideos.get(position); Uri youtubeUri = Uri.parse(holder.mYoutubeImageUrl).buildUpon() .appendPath(video.getVideoImage()) .appendPath("0") .build(); Glide.with(holder.mContext) .load(youtubeUri.toString() + ".jpg") .fitCenter() .into(holder.mImageView); } @Override public int getItemCount() { return mVideos.size(); } public class VideoListViewModel extends RecyclerView.ViewHolder { private final Context mContext; private final ImageView mImageView; private final String mYoutubeWatchUrl; private final String mYoutubeImageUrl; public VideoListViewModel(@NonNull View itemView) { super(itemView); mContext = itemView.getContext(); mImageView = itemView.findViewById(R.id.image_view_video_list_item); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); mYoutubeImageUrl = preferences.getString(mContext.getResources().getString( R.string.youtube_image_url), ""); mYoutubeWatchUrl = preferences.getString(mContext.getResources().getString( R.string.youtube_watch_url), ""); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Video video = mVideos.get(getAdapterPosition()); // Open video in YouTube or Web Browser Uri youtubeUri = Uri.parse(mYoutubeWatchUrl).buildUpon() .appendPath(video.getVideoImage()) .build(); Intent intent = new Intent(Intent.ACTION_VIEW, youtubeUri); mContext.startActivity(intent); } }); } } }
/* * 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 servidor; import java.io.File; import java.io.IOException; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.file.Files; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author julie.goncalves */ public class ThreadConexao implements Runnable { private final Socket socket; private boolean conectado; public ThreadConexao(Socket socket){ this.socket = socket; } @Override public void run(){ conectado = true; System.out.println(socket.getInetAddress()); while (conectado){ try { RequisicaoHTTP requisicao = RequisicaoHTTP.lerRequisicao(socket.getInputStream()); if (requisicao.isManterViva()){ socket.setKeepAlive(true); socket.setSoTimeout(requisicao.getTempoLimite()); } else { socket.setSoTimeout(300); } if (requisicao.getRecurso().equals("/")){ requisicao.setRecurso("index.html"); } File arquivo = new File(requisicao.getRecurso().replaceFirst("/","")); RespostaHTTP resposta; if (arquivo.exists()){ resposta = new RespostaHTTP(requisicao.getProtocolo(), 200, "OK"); } else { resposta = new RespostaHTTP(requisicao.getProtocolo(), 404, "Not Found"); arquivo = new File("Erro404.html"); } resposta.setConteudoResposta(Files.readAllBytes(arquivo.toPath())); String dataFormatada = Util.formatarDataGMT(new Date()); resposta.setCabecalho("Location", "https://localhost:8000/"); resposta.setCabecalho("Date",dataFormatada); resposta.setCabecalho("Server","MeuServidor /1.0"); resposta.setCabecalho("Content-Type","text/html"); resposta.setCabecalho("Content-length", resposta.getTamanhoResposta()); resposta.setSaida(socket.getOutputStream()); resposta.enviar(); } catch (IOException ex){ if (ex instanceof SocketTimeoutException){ try { conectado = false; socket.close(); } catch (IOException ex1) { Logger.getLogger(ThreadConexao.class.getName()).log(Level.SEVERE, null, ex1); } } } } } }
import java.util.ArrayList; import java.util.HashMap; public class GroceryItem { private String name; private int quantity; private int category; public ArrayList<GroceryItem> groceryList = new ArrayList<>(); public static void main(String[] args) { HashMap<Integer, String> categories = new HashMap<>(); categories.put(1, "Produce"); categories.put(2, "Eggs and Dairy"); categories.put(3, "Meat"); categories.put(4, "Canned Goods"); categories.put(5, "Dry Goods"); } public static void displayChoices(){ System.out.println("Please select a category by typing the corresponding number:"); System.out.println("1: Produce"); System.out.println("2: Eggs and Dairy"); System.out.println("3: Meat"); System.out.println("4: Canned Goods"); System.out.println("5: Dry Goods"); } public GroceryItem(String name, int quantity, int category){ this.name = name; this.quantity = quantity; this.category = category; } public void addItem(GroceryItem itemToAdd){ groceryList.add(itemToAdd); } public static void displayAllItems(ArrayList<GroceryItem> groceryList){ for(GroceryItem item: groceryList){ System.out.println("Category: " + item.category + ", Item: " + item.name + ", Quantity: " + item.quantity); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public ArrayList<GroceryItem> getGroceryList() { return groceryList; } public void setGroceryList(ArrayList<GroceryItem> groceryList) { this.groceryList = groceryList; } }
package biz.dreamaker.workreport.security; import biz.dreamaker.workreport.security.filters.FilterSkipMatcher; import biz.dreamaker.workreport.security.filters.FormLoginFilter; import biz.dreamaker.workreport.security.filters.JwtAuthenticationFilter; import biz.dreamaker.workreport.security.handlers.FormLoginAuthenticationSuccessHandler; import biz.dreamaker.workreport.security.handlers.JwtAuthenticationFailureHandler; import biz.dreamaker.workreport.security.jwt.HeaderTokenExtractor; import biz.dreamaker.workreport.security.providers.FormLoginAuthenticationProvider; import biz.dreamaker.workreport.security.providers.JwtAuthenticationProvider; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private FormLoginAuthenticationSuccessHandler formLoginAuthenticationSuccessHandler; @Autowired private FormLoginAuthenticationProvider formLoginProvider; @Autowired private JwtAuthenticationProvider jwtProvider; @Autowired private JwtAuthenticationFailureHandler jwtFailureHandler; @Autowired private HeaderTokenExtractor headerTokenExtractor; @Autowired private ObjectMapper objectMapper; @Bean public AuthenticationManager getAuthenticationManager() throws Exception { return super.authenticationManagerBean(); } protected FormLoginFilter formLoginFilter() throws Exception { FormLoginFilter formLoginFilter = new FormLoginFilter("/formlogin", formLoginAuthenticationSuccessHandler, null, objectMapper); formLoginFilter.setAuthenticationManager(super.authenticationManagerBean()); return formLoginFilter; } protected JwtAuthenticationFilter jwtFilter() throws Exception { FilterSkipMatcher matcher = new FilterSkipMatcher( Arrays.asList("/formlogin", "/social" , "/enroll/admin/**"), "/api/**"); JwtAuthenticationFilter filter = new JwtAuthenticationFilter(matcher, jwtFailureHandler, headerTokenExtractor); filter.setAuthenticationManager(super.authenticationManagerBean()); return filter; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .authenticationProvider(this.formLoginProvider) .authenticationProvider(this.jwtProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http .csrf().disable(); http .headers().frameOptions().disable(); http .authorizeRequests() .antMatchers("/h2-console**").permitAll(); http .addFilterBefore(formLoginFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class); } }
package com.metoo.foundation.domain; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.metoo.core.constant.Globals; import com.metoo.core.domain.IdEntity; /** * * <p> * Title: RefundLog.java * </p> * * <p> * Description:退款日志类,用来记录店铺对买家的退款日志信息 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-4-25 * * * @version koala_b2b2c v2.0 2015版 */ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Entity @Table(name = Globals.DEFAULT_TABLE_SUFFIX + "refund_log") public class RefundLog extends IdEntity { private String refund_id;// 退款编号 private Long returnLog_id;// 对应退货服务单id private String returnService_id;// 对应退货服务单的服务号 ReturnGoodsLog.java private // String return_service_id; private String returnLog_userName;// 收款人用户名 private Long returnLog_userId;// 收款人id private String refund_log;// 日志信息 private String refund_type;// 退款方式 @Column(precision = 12, scale = 2) private BigDecimal refund;// 退款金额 @ManyToOne(fetch = FetchType.LAZY) private User refund_user;// 日志操作员 public RefundLog() { super(); // TODO Auto-generated constructor stub } public RefundLog(Long id, Date addTime) { super(id, addTime); // TODO Auto-generated constructor stub } public Long getReturnLog_userId() { return returnLog_userId; } public void setReturnLog_userId(Long returnLog_userId) { this.returnLog_userId = returnLog_userId; } public String getReturnLog_userName() { return returnLog_userName; } public void setReturnLog_userName(String returnLog_userName) { this.returnLog_userName = returnLog_userName; } public Long getReturnLog_id() { return returnLog_id; } public void setReturnLog_id(Long returnLog_id) { this.returnLog_id = returnLog_id; } public String getReturnService_id() { return returnService_id; } public void setReturnService_id(String returnService_id) { this.returnService_id = returnService_id; } public String getRefund_log() { return refund_log; } public void setRefund_log(String refund_log) { this.refund_log = refund_log; } public BigDecimal getRefund() { return refund; } public void setRefund(BigDecimal refund) { this.refund = refund; } public User getRefund_user() { return refund_user; } public void setRefund_user(User refund_user) { this.refund_user = refund_user; } public String getRefund_type() { return refund_type; } public void setRefund_type(String refund_type) { this.refund_type = refund_type; } public String getRefund_id() { return refund_id; } public void setRefund_id(String refund_id) { this.refund_id = refund_id; } }
package test.gensee.com.joinroom; import android.content.Context; import com.gensee.callback.IRoomCallBack; import com.gensee.callback.IVideoCallBack; import com.gensee.common.ServiceType; import com.gensee.entity.LiveInfo; import com.gensee.room.RtSdk; import com.gensee.routine.State; import com.gensee.routine.UserInfo; import com.gensee.taskret.OnTaskRet; public class Room implements IRoomCallBack{ private RtSdk rtSdk; private Context mContext; private OnJoinRoomListener onJoinRoomListener; public RtSdk getRtSdk() { return rtSdk; } public void setVideoCallBack(IVideoCallBack iVideoCallBack) { rtSdk.setVideoCallBack(iVideoCallBack); } public void setOnJoinRoomListener(OnJoinRoomListener onJoinRoomListener) { this.onJoinRoomListener = onJoinRoomListener; } public void joinRoom(Context context, String lunachCode) { this.mContext = context; if(null == rtSdk) { rtSdk = new RtSdk(); } rtSdk.initWithParam("", lunachCode, this); } @Override public void onInit(boolean b) { if(b) { rtSdk.join(null); } } @Override public void onJoin(boolean b) { } @Override public void onRoomJoin(int i, UserInfo userInfo, boolean b) { if(null != onJoinRoomListener) { onJoinRoomListener.onRoomJoin(i); } } @Override public void onRoomLeave(final int i) { rtSdk.release(new OnTaskRet() { @Override public void onTaskRet(boolean ret, int id, String desc) { if(null != onJoinRoomListener) { onJoinRoomListener.onRoomRelease(i); } } }); } @Override public void onRoomReconnecting() { if(null != onJoinRoomListener) { onJoinRoomListener.onRoomReconnecting(); } } @Override public void onRoomLock(boolean b) { } @Override public void onRoomUserJoin(UserInfo userInfo) { } @Override public void onRoomUserUpdate(UserInfo userInfo) { } @Override public void onRoomUserLeave(UserInfo userInfo) { } @Override public Context onGetContext() { return mContext; } @Override public ServiceType getServiceType() { return null; } @Override public void onRoomPublish(State state) { } @Override public void onRoomRecord(State state) { } @Override public void onRoomData(String s, long l) { } @Override public void onRoomBroadcastMsg(String s) { } @Override public void onRoomRollcall(int i) { } @Override public void onRoomRollcallAck(long l) { } @Override public void onRoomHandup(long l, String s) { } @Override public void onRoomHanddown(long l) { } @Override public void OnUpgradeNotify(String s) { } @Override public void onChatMode(int i) { } @Override public void onFreeMode(boolean b) { } @Override public void onLottery(byte b, String s) { } @Override public void onSettingSet(String s, int i) { } @Override public void onSettingSet(String s, String s1) { } @Override public int onSettingQuery(String s, int i) { return 0; } @Override public String onSettingQuery(String s) { return null; } @Override public void onNetworkReport(byte b) { } @Override public void onNetworkBandwidth(int i, int i1) { } @Override public void onRoomPhoneServiceStatus(boolean b) { } @Override public void onRoomPhoneCallingStatus(String s, int i, int i1) { } @Override public void onLiveInfo(LiveInfo liveInfo) { } public interface OnJoinRoomListener{ void onRoomJoin(int result); void onRoomRelease(int leave); void onRoomReconnecting(); } }
package modelo.personajes; import modelo.Personaje; public abstract class EnemigoDeLaTierra extends Personaje { protected boolean esGuerreroZ(){return false;}; protected boolean esEnemigoDeLaTierra(){return true;}; }
package com.example.suneel.musicapp.Utils; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.net.ConnectivityManager; import android.support.v7.app.AlertDialog; /** * Created by suneel on 29/5/18. */ public class Utils { public static boolean isInternetAvaliable(Context context) { if (((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null) { return true; } return false; } public static void showNetworkAlertDialog(Activity activity) { new AlertDialog.Builder(activity) .setMessage("Please check your internet connection") .setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.xjc.writer; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassContainer; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JPackage; import com.sun.codemodel.JType; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.FieldOutline; import com.sun.tools.xjc.outline.Outline; /** * Dumps an annotated grammar in a simple format that * makes signature check easy. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class SignatureWriter { public static void write( Outline model, Writer out ) throws IOException { new SignatureWriter(model,out).dump(); } private SignatureWriter( Outline model, Writer out ) { this.out = out; this.classes = model.getClasses(); for( ClassOutline ci : classes ) classSet.put( ci.ref, ci ); } /** All the ClassItems in this grammar. */ private final Collection<? extends ClassOutline> classes; /** Map from content interfaces to ClassItem. */ private final Map<JDefinedClass,ClassOutline> classSet = new HashMap<JDefinedClass,ClassOutline>(); private final Writer out; private int indent=0; private void printIndent() throws IOException { for( int i=0; i<indent; i++ ) out.write(" "); } private void println(String s) throws IOException { printIndent(); out.write(s); out.write('\n'); } private void dump() throws IOException { // collect packages used in the class. Set<JPackage> packages = new TreeSet<JPackage>(new Comparator<JPackage>() { public int compare(JPackage lhs, JPackage rhs) { return lhs.name().compareTo(rhs.name()); } }); for( ClassOutline ci : classes ) packages.add(ci._package()._package()); for( JPackage pkg : packages ) dump( pkg ); out.flush(); } private void dump( JPackage pkg ) throws IOException { println("package "+pkg.name()+" {"); indent++; dumpChildren(pkg); indent--; println("}"); } private void dumpChildren( JClassContainer cont ) throws IOException { Iterator itr = cont.classes(); while(itr.hasNext()) { JDefinedClass cls = (JDefinedClass)itr.next(); ClassOutline ci = classSet.get(cls); if(ci!=null) dump(ci); } } private void dump( ClassOutline ci ) throws IOException { JDefinedClass cls = ci.implClass; StringBuilder buf = new StringBuilder(); buf.append("interface "); buf.append(cls.name()); boolean first=true; Iterator itr = cls._implements(); while(itr.hasNext()) { if(first) { buf.append(" extends "); first=false; } else { buf.append(", "); } buf.append( printName((JClass)itr.next()) ); } buf.append(" {"); println(buf.toString()); indent++; // dump the field for( FieldOutline fo : ci.getDeclaredFields() ) { String type = printName(fo.getRawType()); println(type+' '+fo.getPropertyInfo().getName(true)+';'); } dumpChildren(cls); indent--; println("}"); } /** Get the display name of a type. */ private String printName( JType t ) { String name = t.fullName(); if(name.startsWith("java.lang.")) name = name.substring(10); // chop off the package name return name; } }
package com.test; import com.zking.Entity.StudentEntity; import com.zking.dao.StudentDao; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; /** * @author: longyt * @create: 2018-01-10 20:58 * @desc: **/ public class TestSpring { @Test public void testSpring(){ ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml"); StudentDao studentDao = (StudentDao) context.getBean("studentDao"); List<StudentEntity> list = studentDao.getallStudent(); for (StudentEntity studentEntity : list) { System.out.println(studentEntity.getSname()); } } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.examples.test.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.user.client.ui.RootPanel; import com.sencha.gxt.widget.core.client.Resizable; import com.sencha.gxt.widget.core.client.button.TextButton; import com.sencha.gxt.widget.core.client.container.FlowLayoutContainer; public class ResizableTest implements EntryPoint { @Override public void onModuleLoad() { FlowLayoutContainer con = new FlowLayoutContainer(); con.setPixelSize(300, 300); con.setBorders(true); final TextButton button = new TextButton("Test"); con.add(button); con.addResizeHandler(new ResizeHandler() { @Override public void onResize(ResizeEvent event) { button.setPixelSize(event.getWidth(), event.getHeight()); } }); new Resizable(con); RootPanel.get().add(con); } }
package com.drivetuningsh.service.user.impl; import com.drivetuningsh.dto.UserRequestDto; import com.drivetuningsh.entity.user.Role; import com.drivetuningsh.entity.user.RoleEnum; import com.drivetuningsh.entity.user.User; import com.drivetuningsh.repository.user.RoleRepository; import com.drivetuningsh.repository.user.UserRepository; import com.drivetuningsh.service.user.UserService; import lombok.RequiredArgsConstructor; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.HashSet; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final RoleRepository roleRepository; private final BCryptPasswordEncoder encoder; @Override public User save(UserRequestDto userRequestDto) { Role userRole = roleRepository.findByRole(RoleEnum.USER.getRole()); User newUser = new User(); newUser.setFirstName(userRequestDto.getFirstName()); newUser.setLastName(userRequestDto.getLastName()); newUser.setEmail(userRequestDto.getEmail()); newUser.setPassword(encoder.encode(userRequestDto.getPassword())); newUser.setEmailVerified(true); newUser.setRoles(new HashSet<>(Collections.singletonList(userRole))); return userRepository.save(newUser); } @Override public void saveAdmin(String ... args) { if (userRepository.findByEmail(args[2]) == null) { Role userRole = roleRepository.findByRole(RoleEnum.ADMIN.getRole()); User admin = new User(); admin.setFirstName(args[0]); admin.setLastName(args[1]); admin.setEmail(args[2]); admin.setPassword(encoder.encode(args[3])); admin.setEmailVerified(true); admin.setRoles(new HashSet<>(Collections.singletonList(userRole))); userRepository.save(admin); } } @Override public User findByEmail(String email) { return userRepository.findByEmail(email); } }
package Library.serializers; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import Library.entities.Book; import Library.entities.Employee; import Library.entities.Library; import com.google.gson.*; import org.hibernate.Hibernate; public class LibrarySerializer implements JsonSerializer { @Override public JsonElement serialize(Object library, Type type, JsonSerializationContext jsonSerializationContext) { final Library b = (Library) library; final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id", b.getId()); jsonObject.addProperty("name", b.getName()); jsonObject.addProperty("city", b.getCity()); jsonObject.addProperty("street", b.getStreet()); jsonObject.addProperty("post_code", b.getPostCode()); jsonObject.addProperty("books_id", new Gson().toJson(b.getBooks().stream().map(book -> book.getId()).collect(Collectors.toList()))); jsonObject.addProperty("employees_id", new Gson().toJson(b.getEmployees().stream().map(e -> e.getId()).collect(Collectors.toList()))); return jsonObject; } }
package com.xiaole.mvc.model.checker.simpleChecker; import net.sf.json.JSONObject; import org.apache.log4j.Logger; /** * Created by llc on 17/3/24. */ public class XiaoleSimpleChecker implements CheckSimpleInterface { private static final Logger logger = Logger.getLogger(XiaoleSimpleChecker.class); @Override public boolean checkSimple(String slog) { return !getContentText(slog).equals(""); } public String getContentText(String slog){ String content; JSONObject jsonObject; try { JSONObject jlog = JSONObject.fromObject(slog); content = jlog.getString("content"); jsonObject = JSONObject.fromObject(content); if (content.contains("nonFirstStart")){ return "nonFirstStart " + jsonObject.getString("sendModule"); } else if (content.contains("sendContent")){ return jsonObject.getString("sendContent")+" "+jsonObject.getString("sendType"); } else if (content.contains("replyContent")){ return jsonObject.getString("replyContent") + " " + jsonObject.getString("replyType"); } else return ""; } catch (Exception e) { logger.error("解析日志内容出错,错误日志:" + slog + ", 错误详情:" + e.getMessage()); return ""; } } }
package com.stubborn.receievingsmsbybroadcast; import android.Manifest; import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Bundle; import android.provider.Telephony; import android.widget.Toast; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; public class MainActivity extends AppCompatActivity { String[] PERMISSIONS = {Manifest.permission.READ_SMS}; private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; private Object SMSBroadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "inside the permi 1", Toast.LENGTH_LONG).show(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 0); Toast.makeText(this, "inside the permi 2", Toast.LENGTH_LONG).show(); } else { // register sms receiver IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION); registerReceiver((BroadcastReceiver) SMSBroadcastReceiver, filter); Toast.makeText(this, "inside the permi 2 else", Toast.LENGTH_LONG).show(); } requestContactsPermissions(); } } private ArrayList requestContactsPermissions() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_SMS)) { ActivityCompat.requestPermissions(this, PERMISSIONS, 1); } else { ActivityCompat.requestPermissions(this, PERMISSIONS, 1); } return null; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "inside the req permi 2", Toast.LENGTH_LONG).show(); } else { // register sms receiver IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION); registerReceiver((BroadcastReceiver) SMSBroadcastReceiver, filter); Toast.makeText(this, "inside the req permi 2 else" , Toast.LENGTH_LONG).show(); } } }
package com.git.cloud.resmgt.common.dao; import java.sql.SQLException; import java.util.List; import java.util.Map; import com.git.cloud.common.dao.ICommonDAO; import com.git.cloud.common.exception.RollbackableBizException; import com.git.cloud.common.support.Pagination; import com.git.cloud.common.support.PaginationParam; import com.git.cloud.excel.model.vo.DataStoreVo; import com.git.cloud.excel.model.vo.HostVo; import com.git.cloud.policy.model.vo.PolicyInfoVo; import com.git.cloud.resmgt.common.model.po.CmHostPo; import com.git.cloud.resmgt.common.model.po.CmHostUsernamePasswordPo; import com.git.cloud.resmgt.common.model.vo.CmHostVo; public interface ICmHostDAO extends ICommonDAO{ /** * 更新CmHost的已用CPU和内存 * @Title: updateCmHostUsed * @Description: TODO * @field: @param cmHost * @field: @throws RollbackableBizException * @return void * @throws */ public void updateCmHostUsed(CmHostPo cmHost) throws RollbackableBizException; public void updateCmHostUsed() throws RollbackableBizException; /** * 根据Id获取CmHost * @Title: findCmHostById * @Description: TODO * @field: @param id * @field: @return * @field: @throws RollbackableBizException * @return CmHostPo * @throws */ public CmHostPo findCmHostById(String id) throws RollbackableBizException; public List<?> findHostCpuCdpInfo(String hostId) throws RollbackableBizException; public String findHostIpById(String id) throws SQLException; public CmHostUsernamePasswordPo findHostUsernamePassword(String hostId) throws RollbackableBizException; public DataStoreVo findDiskInfoByHostId(String hostId) throws RollbackableBizException; /** * @Title: findDatastoreByHostIp * @Description: 查询物理机挂载的所有存储信息 * @param hostIp * @return List<DataStoreVo> 返回类型 */ public List<DataStoreVo> findDatastoreByHostIp(String hostIp) throws RollbackableBizException; public List<HostVo> findHostInfoListByParams(Map<String,String> params); public List<DataStoreVo> findSanStorgeListByHostId(String hostId); public void deleteSanDataStoreList(List<DataStoreVo> dataStoreList); public void deleteHostDataStoreRefList(List<DataStoreVo> dataStoreList); public Pagination<CmHostVo> getHostList(PaginationParam paginationParam) throws RollbackableBizException ; public void updateUserNamePasswd(CmHostUsernamePasswordPo cupp) throws RollbackableBizException; /** * 通过物理机ID,在cm_datastore表中,查找datastore的名称 * @param hostId,物理机ID * @return * @throws RollbackableBizException */ public String getGYRXHostDatastore(String hostId)throws SQLException; public int findExistUserNamePassWd(CmHostUsernamePasswordPo cupp)throws RollbackableBizException ; public void insertHostUserNamePasswd(CmHostUsernamePasswordPo cupp)throws RollbackableBizException ; public List<PolicyInfoVo> findHostByResPoolId(String resPoolId)throws RollbackableBizException; /** * 查询物理机id,通过物理机ip * @param hostId * @return */ CmHostVo selectHostIdByIp(String hostIp) ; }
package app; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.MarkerManager; public class University { static Logger logger = LogManager.getLogger(University.class); public void doSomething(){ logger.info("qwert from university"); logger.error(MarkerManager.getMarker("FLOW"), "error with marker \"flow\" from university"); } }
// https://www.interviewbit.com/problems/least-common-ancestor/ // #tree #binary-tree /** * Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int * x) { val = x; left=null; right=null; } } */ public class Solution { public int lca(TreeNode A, int B, int C) { // idea: find in left => 0,1,2 => not found any target, find 1 target, find 2 target // if find both in left // ignore right // find in left, // if find one target in left // find the other in right // if find 0 in left // find both in right int[] result = new int[1]; result[0] = -1; helper(A, B, C, result); return result[0]; } private int helper(TreeNode node, int B, int C, int[] result) { int val = 0; if (node == null) { return val; } if (node.val == B && node.val == C) { val = 2; } else if (node.val == B || node.val == C) { val = 1; } int left = helper(node.left, B, C, result); int right = 0; if ((val + left) == 2) { if (result[0] == -1) { if (left == 2) { result[0] = node.left.val; } else { result[0] = node.val; } } } else { right = helper(node.right, B, C, result); if ((val + left + right) == 2) { if (result[0] == -1) { if (right == 2) { result[0] = node.right.val; } else { result[0] = node.val; } } } } return val + left + right; } }
package com.example.myapplication; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import java.util.List; public class VehicleListAdapter extends ArrayAdapter { private List<String> vehicleList; private Activity context; public VehicleListAdapter(Activity context,List<String> vehicleList) { super(context, R.layout.list_vehicle, vehicleList); this.context = context; this.vehicleList = vehicleList; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row=convertView; LayoutInflater inflater = context.getLayoutInflater(); if(convertView==null) row = inflater.inflate(R.layout.list_vehicle, null, true); TextView txtVehicle = (TextView) row.findViewById(R.id.vehicle_number); txtVehicle.setText(vehicleList.get(position)); return row; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package avimarkmodmedcond; import java.util.ArrayList; /** * * @author jbaudens */ public class ClinicalComplaints { private ArrayList<ClinicalComplaint> listOfClinicalComplaints; private ArrayList<String> categories; public void setListOfClinicalComplaints(ArrayList<ClinicalComplaint> listOfBodySystems) { this.listOfClinicalComplaints = listOfBodySystems; } /** * * @return */ public ArrayList<ClinicalComplaint> getListOfClinicalComplaints() { return listOfClinicalComplaints; } /** * */ public ClinicalComplaints(){ listOfClinicalComplaints = new ArrayList<>(); } public ArrayList<String> getCategories() { return categories; } public void setCategories(ArrayList<String> categories) { this.categories = categories; } }
package gromcode.main.lesson30.homework30_1.dao; import gromcode.main.lesson30.homework30_1.Customer; import java.util.HashSet; import java.util.Set; public class CustomerDAO { private static Set<Customer> customers = new HashSet<>(); public void setCustomers(Customer customer) { customers.add(customer); } public static Customer getCustomerByName(String name, String country){ for(Customer c : customers){ if(c.getName().equals(name) && c.getCountry().equals(country)) return c; } return null; } }
package net.lantrack.framework.springplugin.view; import org.springframework.oxm.xstream.XStreamMarshaller; public class Marshaller extends XStreamMarshaller { }
/* * Copyright 2002-2022 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.test.web.reactive.server; import java.util.Arrays; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseCookie; import org.springframework.http.server.reactive.ServerHttpResponse; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; /** * Test scenarios involving a mock server. * @author Rossen Stoyanchev */ public class MockServerTests { @Test // SPR-15674 (in comments) public void mutateDoesNotCreateNewSession() { WebTestClient client = WebTestClient .bindToWebHandler(exchange -> { if (exchange.getRequest().getURI().getPath().equals("/set")) { return exchange.getSession() .doOnNext(session -> session.getAttributes().put("foo", "bar")) .then(); } else { return exchange.getSession() .map(session -> session.getAttributeOrDefault("foo", "none")) .flatMap(value -> { DataBuffer buffer = toDataBuffer(value); return exchange.getResponse().writeWith(Mono.just(buffer)); }); } }) .build(); // Set the session attribute EntityExchangeResult<Void> result = client.get().uri("/set").exchange() .expectStatus().isOk().expectBody().isEmpty(); ResponseCookie session = result.getResponseCookies().getFirst("SESSION"); // Now get attribute client.mutate().build() .get().uri("/get") .cookie(session.getName(), session.getValue()) .exchange() .expectBody(String.class).isEqualTo("bar"); } @Test // SPR-16059 public void mutateDoesCopy() { WebTestClient.Builder builder = WebTestClient .bindToWebHandler(exchange -> exchange.getResponse().setComplete()) .configureClient(); builder.filter((request, next) -> next.exchange(request)); builder.defaultHeader("foo", "bar"); builder.defaultCookie("foo", "bar"); WebTestClient client1 = builder.build(); builder.filter((request, next) -> next.exchange(request)); builder.defaultHeader("baz", "qux"); builder.defaultCookie("baz", "qux"); WebTestClient client2 = builder.build(); WebTestClient.Builder mutatedBuilder = client1.mutate(); mutatedBuilder.filter((request, next) -> next.exchange(request)); mutatedBuilder.defaultHeader("baz", "qux"); mutatedBuilder.defaultCookie("baz", "qux"); WebTestClient clientFromMutatedBuilder = mutatedBuilder.build(); client1.mutate().filters(filters -> assertThat(filters).hasSize(1)); client1.mutate().defaultHeaders(headers -> assertThat(headers).hasSize(1)); client1.mutate().defaultCookies(cookies -> assertThat(cookies).hasSize(1)); client2.mutate().filters(filters -> assertThat(filters).hasSize(2)); client2.mutate().defaultHeaders(headers -> assertThat(headers).hasSize(2)); client2.mutate().defaultCookies(cookies -> assertThat(cookies).hasSize(2)); clientFromMutatedBuilder.mutate().filters(filters -> assertThat(filters).hasSize(2)); clientFromMutatedBuilder.mutate().defaultHeaders(headers -> assertThat(headers).hasSize(2)); clientFromMutatedBuilder.mutate().defaultCookies(cookies -> assertThat(cookies).hasSize(2)); } @Test // SPR-16124 public void exchangeResultHasCookieHeaders() { ExchangeResult result = WebTestClient .bindToWebHandler(exchange -> { ServerHttpResponse response = exchange.getResponse(); if (exchange.getRequest().getURI().getPath().equals("/cookie")) { response.addCookie(ResponseCookie.from("a", "alpha").path("/pathA").build()); response.addCookie(ResponseCookie.from("b", "beta").path("/pathB").build()); } else { response.setStatusCode(HttpStatus.NOT_FOUND); } return response.setComplete(); }) .build() .get().uri("/cookie").cookie("a", "alpha").cookie("b", "beta") .exchange() .expectStatus().isOk() .expectHeader().valueEquals(HttpHeaders.SET_COOKIE, "a=alpha; Path=/pathA", "b=beta; Path=/pathB") .expectBody().isEmpty(); assertThat(result.getRequestHeaders().get(HttpHeaders.COOKIE)).isEqualTo(Arrays.asList("a=alpha", "b=beta")); } @Test public void responseBodyContentWithFluxExchangeResult() { FluxExchangeResult<String> result = WebTestClient .bindToWebHandler(exchange -> { ServerHttpResponse response = exchange.getResponse(); response.getHeaders().setContentType(MediaType.TEXT_PLAIN); return response.writeWith(Flux.just(toDataBuffer("body"))); }) .build() .get().uri("/") .exchange() .expectStatus().isOk() .returnResult(String.class); // Get the raw content without consuming the response body flux. byte[] bytes = result.getResponseBodyContent(); assertThat(bytes).isNotNull(); assertThat(new String(bytes, UTF_8)).isEqualTo("body"); } private DataBuffer toDataBuffer(String value) { byte[] bytes = value.getBytes(UTF_8); return DefaultDataBufferFactory.sharedInstance.wrap(bytes); } }
package no.nav.vedtak.sikkerhet.kontekst; public enum Groups { SAKSBEHANDLER, BESLUTTER, OVERSTYRER, OPPGAVESTYRER, VEILEDER, DRIFT }
package Commands; import java.io.Serializable; import java.util.Scanner; import collection.Collection; import data.*; import collection.loader.*; /* Краткая информация: На сервер передается несколько пакетов: 1. Команда add 2. - 8. Элементы команды add */ public class addCommand implements Serializable { private LabWork labWork; public LabWork getLabWork() { return labWork; } public boolean clientjob(Scanner in) { String D0 = ""; double D1 = 0.0; int D2 = 0; long D3 = 0; int D4 = 0; String D5 = ""; String D6 = null; long D7 = 0L; class Error { private String Message; public String getMessage() { return Message; } public void setMessage(String message) { Message = message; } } Error A = new Error(); try { for (int i = 0; i < 8; i++) { String command = in.next(); switch (i) { case 0: { A.setMessage("Что это такое : " + command); D0 = command; } break; case 1: { A.setMessage("Ошибка при вводе значения - не является double: " + command); D1 = Double.parseDouble(command); } break; case 2: { A.setMessage("Ошибка при вводе значения - не является int: " + command); D2 = Integer.parseInt(command); } break; case 3: { A.setMessage("Ошибка при вводе значения - не является long: " + command); D3 = Long.parseLong(command); } break; case 4: { A.setMessage("Ошибка при вводе значения - не является int: " + command ); D4 = Integer.parseInt(command); } break; case 5: { D5 = command; } break; case 6: { A.setMessage("Что это такое : " + command); D6 = command; } break; case 7: { A.setMessage("Ошибка при вводе значения - не является long: " + command); D7 = Long.parseLong(command); } break; default: //До этого не дойдет } } //D0 = "Math"; A.setMessage("ВВеденное значение difficulty не является Difficulty: " + D5); Discipline discipline = new Discipline(D6, D7); Difficulty difficulty = StringtoEnum(D5); Coordinates coordinates = new Coordinates(D1, D2); this.labWork = new LabWork(D0, 0L, coordinates, D3, D4, difficulty, discipline); return true; } catch (Exception E) { System.out.println(A.getMessage()); } return false; } public void serverjob(LabWork labwork, Collection collection) { Long MAX = 0L; for(LabWork a: collection.getVector()){ if(a.getId()>MAX)MAX = a.getId(); } labwork.setId(MAX+1); collection.getVector().add(labwork); } public Difficulty StringtoEnum(String line) throws DifficultyExeption { Difficulty difficulty; if (line.startsWith("VERY_EASY") && line.length() <= "VERY_EASY".length()) difficulty = Difficulty.VERY_EASY; else if (line.startsWith("NORMAL")) difficulty = Difficulty.NORMAL; else if (line.startsWith("TERRIBLE")) difficulty = Difficulty.TERRIBLE; else if (line.startsWith("IMPOSSIBLE")) difficulty = Difficulty.IMPOSSIBLE; else if (line.startsWith("INSANE")) difficulty = Difficulty.INSANE; else throw new DifficultyExeption(); return difficulty; } } //add Math 0.0 0 0 0 VERY_EASY MATH 8 //+
package com.midea.designmodel.factorypartern.simplefactory; public interface Car { public void getName(); }
package edu.neu.ccs.cs5010; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class CustomerTest { private Address address; private Customer customer; @Before public void setUp() throws Exception { address = new Address("6649 N Blue Gum St", "New Orleans", "Orleans", "LA", "70116"); customer = new Customer("James", "Butt", address, "504-621-8927", "jbutt@gmail.com", "gold"); } @Test public void printCustomer() throws Exception { customer.printCustomer(); } @Test public void getFirstName() throws Exception { assertEquals(customer.getFirstName(), "James"); } @Test public void getLastName() throws Exception { assertEquals(customer.getLastName(), "Butt"); } @Test public void getLocation() throws Exception { assertEquals(customer.getLocation(), address); } @Test public void getPhoneNumber() throws Exception { assertEquals(customer.getPhoneNumber(), "504-621-8927"); } @Test public void getEmail() throws Exception { assertEquals(customer.getEmail(), "jbutt@gmail.com"); } @Test public void getRewards() throws Exception { assertEquals(customer.getRewards(), "gold"); } }
/* * 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 exceptionprograms; public class NativeMethodCode { public static native void printText(); static { System.loadLibrary("happy"); } public static void main(String[] args) { Happy happy = new Happy(); happy.printText(); } } class Happy{ public native void printText(); static{ System.loadLibrary("happy"); } }
package com.example.authenticationservice.service; import com.example.authenticationservice.domain.Product; import com.example.authenticationservice.dto.ProductDto; import com.example.authenticationservice.repositiory.ProductRepository; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class ProductServiceImpl implements ProductService{ @Autowired private ProductRepository productRepository; @Autowired private ModelMapper modelMapper; public Optional<Product> findById(long id) { return productRepository.findById(id); } @Override public List<Product> findAll() { return productRepository.findAll(); } @Override public Product create(ProductDto request) { Product product = new Product(request.getName(), request.getVendor(), request.getCategory()); return productRepository.save(product); } }
package net.leseonline.sundial; import android.app.IntentService; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.annotation.NonNull; import android.util.Log; import android.widget.Toast; import java.util.Arrays; import java.util.Collection; import java.util.ArrayDeque; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This service provides an external port for remote access by a known application. */ public class LocationService extends IntentService implements SensorEventListener { private final String TAG = "LocationService"; private Messenger mRemoteMessenger = new Messenger(new MyRemoteHandler()); private Messenger mLocalMessenger = new Messenger(new MyLocalHandler()); private Thread mWorker; private Object mLockObject = new Object(); private float[] mGravity; private float[] mGeomagnetic; private float mAzimuthAngle = Float.MIN_VALUE; private boolean mSendLocations = false; private Sensor mAccelerometer; private SensorManager mSensorManager; private ArrayDeque<Location> mLocations; private int mRotation; static final int SEND_LOCATIONS = 7; static final int RECEIVE_LOCATIONS = 8; public LocationService() { super("location-service"); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); } } @Override public IBinder onBind(Intent arg0) { return mLocalMessenger.getBinder(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onCreate() { super.onCreate(); mWorker = new Thread() { int counter = 0; public void run() { boolean interrupted = false; while (!interrupted) { try { // Every 10 seconds for now. if ((counter % 10) == 0) { getLocation(); } counter++; Thread.sleep(1000); } catch (InterruptedException ex) { interrupted = true; } } } }; mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mLocations = new ArrayDeque<Location>(); this.mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI); startRemoteService(); mWorker.start(); } @Override public void onDestroy() { mWorker.interrupt(); try { mWorker.join(1000); } catch (InterruptedException ex) { } if (serviceConnection != null && isBound) { unbindService(serviceConnection); } mSensorManager.unregisterListener(this); super.onDestroy(); } private void getLocation() { // Get the current location. // If different than the most recent in the deque, add to the deque. LocationSupervisor ls = LocationSupervisor.getHandle(); Location location = ls.getLocation(); if (location != null) { if (mLocations.size() == 0) { mLocations.addFirst(location); } else { Location first = mLocations.peekFirst(); if (first.getLatitude() != location.getLatitude() || first.getLongitude() != location.getLongitude()) { mLocations.addFirst(location); } } if (mLocations.size() > 10) { mLocations.removeLast(); } } synchronized (mLockObject) { if (mSendLocations) { mSendLocations = false; sendLocations(); } } } private Intent convertImplicitIntentToExplicitIntent(Intent implicitIntent, Context context) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> resolveInfoList = pm.queryIntentServices(implicitIntent, 0); if (resolveInfoList == null || resolveInfoList.size() != 1) { return null; } ResolveInfo serviceInfo = resolveInfoList.get(0); ComponentName component = new ComponentName(serviceInfo.serviceInfo.packageName, serviceInfo.serviceInfo.name); Intent explicitIntent = new Intent(implicitIntent); explicitIntent.setComponent(component); return explicitIntent; } private void startRemoteService() { try { Intent mIntent = new Intent(); mIntent.setAction("net.leseonline.nasaclient.RemoteService"); Intent explicitIntent = convertImplicitIntentToExplicitIntent(mIntent, getApplicationContext()); bindService(explicitIntent, serviceConnection, BIND_AUTO_CREATE); } catch(Exception ex) { ex.printStackTrace(); } } private boolean isBound = false; private Messenger remoteMessgener = null; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { try { isBound = true; remoteMessgener = new Messenger(service); } catch(Exception ex) { ex.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { serviceConnection = null; isBound = false; } }; /** * This Handler handles the message from the remote entity. * There should not be any. */ class MyRemoteHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SEND_LOCATIONS: { Log.d(TAG, "in SEND_LOCATIONS."); Toast.makeText(getApplicationContext(), "NASA client says please send locations.", Toast.LENGTH_LONG).show(); doWork(); break; } } } private void doWork() { } } public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { // int rotation = getWindowManager().getDefaultDisplay().getRotation(); // if (rotation != mRotation) { // mRotation = rotation; // synchronized (mLockObject) { // mSendLocations = true; // } // } // if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) // mGravity = event.values; // if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) // mGeomagnetic = event.values; // if (mGravity != null && mGeomagnetic != null) { // float R[] = new float[9]; // float I[] = new float[9]; // boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic); // if (success) { // float orientation[] = new float[3]; // SensorManager.getOrientation(R, orientation); // // orientation contains: azimuth, pitch and roll // float azimuth_angle = orientation[0]; // if (Math.abs(azimuth_angle - mAzimuthAngle) > 0.001) { // Log.d(TAG, Arrays.toString(orientation)); // // Orientation changed, so send the locations to remote server. // synchronized (mLockObject) { // mSendLocations = true; // } // } // mAzimuthAngle = azimuth_angle; // } // } } private JSONObject locationsToJSON() { JSONObject result = new JSONObject(); try { JSONArray locations = new JSONArray(); for (Location loc : mLocations) { JSONObject item = new JSONObject(); item.put("lat", loc.getLatitude()); item.put("long", loc.getLongitude()); item.put("time", loc.getTime()); locations.put(item); } result.put("locations", locations); } catch(JSONException ex) { result = null; } return result; } private void sendLocations() { String jsonString = locationsToJSON().toString(); Log.d(TAG, "JSON: " + jsonString); Bundle bundle = new Bundle(); bundle.putString("locations", jsonString); Message msg = Message.obtain(null, SEND_LOCATIONS, 0, 0); msg.setData(bundle); try { remoteMessgener.send(msg); } catch (RemoteException ex) { ex.printStackTrace(); } } /** * This Handler handles the message from the local entity, which is the main activity. */ class MyLocalHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case RECEIVE_LOCATIONS: { Log.d(TAG, "in RECEIVE_LOCATIONS."); doWork(); break; } } } private void doWork() { } } }
package com.cinema.sys.service; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSONObject; import com.cinema.sys.model.User; import com.cinema.sys.model.base.TUser; public interface UserService { User getDetail(String id); User getDetail(String id,String password); List<User> getList(Map<String, Object> paraMap); List<User> getAllList(); int delete(String id); int insert(TUser t); int update(TUser t) ; Boolean exist(String id); }
package com.xiaoxz.controller; import com.alibaba.fastjson.JSON; import com.github.pagehelper.PageInfo; import com.xiaoxz.exception.MyExceptionHandler; import com.xiaoxz.pjo.Result; import com.xiaoxz.service.BookService; import com.xiaoxz.utils.OrderInfoUtil2_0; import com.xiaoxz.utils.PropertyLoad; import com.xiaoxz.utils.PublicUtil; import org.apache.commons.lang.StringUtils; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; /** * 订单申请 */ @RestController @RequestMapping("/book") public class BookController { private static Logger logger = LoggerFactory.getLogger(BookController.class); @Autowired private BookService bookService; /** * 订单申请确认 * 取消签名 * @param params * @return */ @RequestMapping("/applyBook") public Result applyBook(@RequestParam Map<String, String> params, MultipartFile sign) throws Exception { logger.info("本次请求参数:" + params); Boolean b = StringUtils.isEmpty(params.get("sku_id")); logger.info("istrue:" + b); // if (sign == null || sign.isEmpty()) { // return new Result().fail("签名不能为空!"); // } // String filename = dealFile(sign); //获取产品id, 产品名称, 产品租期 if ((StringUtils.isEmpty(params.get("sku_id")) && StringUtils.isEmpty(params.get("msgid")))) { return new Result(0, "参数异常!"); } return bookService.applyBook(params, null); } private String dealFile(MultipartFile file) throws IOException { if (file == null) { return null; } String file_sourcename = file.getOriginalFilename(); String ref = file_sourcename.substring(file_sourcename.lastIndexOf(".")); String uuid = UUID.randomUUID().toString().replaceAll("_", "").substring(0, 12); //生成文件名称 String filename = uuid + ref; String dir = PropertyLoad.getProperty("book_accessory_dir"); File dirFile = new File(dir); if (!dirFile.exists()) { dirFile.mkdirs(); } File bookFile = new File(dir + File.separator + filename); file.transferTo(bookFile); return filename; } /** * 查询客户订单信息 */ @RequestMapping("/getBookList") public Result getBookList(@RequestBody Map<String, Object> params) { if (params.get("state") == null) { return new Result(0, "参数异常!"); } String state = String.valueOf(params.get("state")); //订单状态 if (StringUtils.isEmpty(state)) { return new Result(0, "参数异常!"); } //获取分页参数 return bookService.getBookList(createPage(params), state); } private PageInfo createPage(Map<String, Object> params) { int pageNum = params.get("pageNum") != null ? (int) params.get("pageNum") : 1; int pageSize = params.get("pageSize") != null ? (int) params.get("pageSize") : 15; PageInfo page = new PageInfo(); page.setPageNum(pageNum); page.setPageSize(pageSize); return page; } @RequestMapping("/saveTeardown") public Result saveTeardown(MultipartFile teardown, String bid) throws IOException { String filename = dealFile(teardown); String teardownUrl = PropertyLoad.getProperty("book_accessory_ngImg") + filename; return bookService.saveTeardown(teardownUrl ,bid); } /** * 查询还款记录, 我的页面的所有的还款记录 */ @RequestMapping("/getBills") public Result getBills() { return bookService.getBills(); } /** * 查询某一账单详细信息 */ @RequestMapping("/getBillWithId") public Result getBillWithId(@RequestBody Map<String, Object> params) { String pid = String.valueOf(params.get("pid")); return bookService.getBillWithId(pid); } /** * 获取支付宝sign * * @param params * @return */ @RequestMapping("/getAliPaySign") public Result getAliPaySign(@RequestBody Map<String, String> params) throws Exception { logger.info("---------开始接口调用--------"); logger.info(params.toString()); if (StringUtils.isEmpty(params.get("bid"))) { return new Result(0, "参数异常!"); } //查询本次待支付金额, (意外保障费,或者订单费用, 或者当期费用) Result result = bookService.getPayFee(params.get("bid"), params.get("pid")); Map<String, Object> resMap = (Map<String, Object>) result.getData(); //封装回调参数 String back_params = createBizNameValuePair(params, result); //String.valueOf(resMap.get("fee")) Map<String, String> appMap = OrderInfoUtil2_0.buildOrderParamMap("订单支付", String.valueOf(resMap.get("fee")), "商品还款", back_params); logger.info(appMap.toString()); String orderParam = OrderInfoUtil2_0.buildOrderParam(appMap); String sign = OrderInfoUtil2_0.getSign(appMap, PropertyLoad.getProperty("zhifb_privatekey")); String orderInfo = orderParam + "&" + sign; return new Result(1, "查询成功!", orderInfo); } private String createBizNameValuePair(Map<String, String> params, Result result) throws UnsupportedEncodingException { StringBuilder sbd = new StringBuilder(); sbd.append("bid="); sbd.append(params.get("bid")); sbd.append(";"); if (!StringUtils.isEmpty(params.get("pid"))) { sbd.append("pid="); sbd.append(params.get("pid")); sbd.append(";"); } Map<String, Object> resData = (Map<String, Object>) result.getData(); sbd.append("type="); sbd.append(resData.get("type")); String back_params = URLEncoder.encode(sbd.toString(), "UTF-8"); System.out.println(back_params); return back_params; } /** * 用户发起外部链接申请 */ @RequestMapping("/addLink") public Result addLink(@RequestBody Map<String, String> params) { if (StringUtils.isEmpty(params.get("link"))) { return new Result(0, "请输入商品链接地址"); } return bookService.addLink(params); } @RequestMapping("/getApplyInfoByMsgId") public Result getApplyInfo(@RequestBody Map<String, String> params) { if (StringUtils.isEmpty(params.get("msgid")) && StringUtils.isEmpty(params.get("sku_id")) || StringUtils.isEmpty(params.get("type"))) { return new Result(0, "参数异常!"); } return bookService.getApplyInfo(params); } @RequestMapping("/getProtocol") public @ResponseBody Result getProtocol(@RequestParam Map<String, String> params) throws Exception { logger.info("--------接口getProtocol-------" + params); if (!StringUtils.isEmpty(params.get("bid"))) { return bookService.getProtocolByBId(params.get("bid")); } else if (StringUtils.isEmpty(params.get("type")) || StringUtils.isEmpty(params.get("cid"))) { return new Result(0, "参数异常!"); } return bookService.getProtocol(params); } }
package Service; import model.RFID; import utils.SqlHelper; /** * Created by RJzz on 2016/12/3. */ public class RFIDService { //添加RFID设备 public boolean addRFID(RFID rfid) { boolean isOK = false; String sql = "insert into rfid values(?,?,?,?,?,?,?,?,?)"; String parameters[] = { null, rfid.getrTag(), rfid.getrName(), rfid.getrId(), rfid.getrPosition(), rfid.getrType(), rfid.getrKId(), rfid.getrDId() }; if(new SqlHelper().executeUpdate(sql, parameters) == 1) { isOK = true; } return isOK; } //删除设备 public boolean deleteRFID(RFID rfid) { boolean isOK = false; String sql = "delete from rfid where rTag=?"; String[] parameters = {rfid.getrTag()}; if((new SqlHelper().executeUpdate(sql, parameters)) == 1) { isOK = true; } return isOK; } //修改设备 public boolean updateRFID(RFID rfid) { boolean isOK = false; String sql = "update rfid set rTag=?, rName=?, rId=?, rType=?, rPosition=?, rKId=?, rDId=?, rDate=?"; String[] parameters = { null, rfid.getrTag(), rfid.getrName(), rfid.getrId(), rfid.getrPosition(), rfid.getrType(), rfid.getrKId(), rfid.getrDId() }; if(new SqlHelper().executeUpdate(sql, parameters) == 1) { isOK = true; } return isOK; } }
package com.Radiabutton; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Facebook_Radiobuttons_Test { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe"); WebDriver driver=null; driver=new ChromeDriver(); String Url="http://facebook.com"; driver.get(Url); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); //<input type="radio" name="sex" value="1" id="u_0_9"> //<input type="radio" name="sex" value="2" id="u_0_a"> WebElement radiobutton=driver.findElement(By.id("u_0_9")); radiobutton.getAttribute("value"); radiobutton.click(); WebElement radiobutton1=driver.findElement(By.id("u_0_a")); radiobutton1.getAttribute("value"); radiobutton1.click(); System.out.println(radiobutton.getAttribute("value") ); System.out.println(radiobutton1.getAttribute("value")); driver.close(); } }
/** * This class is generated by jOOQ */ package schema.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.AssessmentAssessmentRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class AssessmentAssessment extends TableImpl<AssessmentAssessmentRecord> { private static final long serialVersionUID = 1301354782; /** * The reference instance of <code>bitnami_edx.assessment_assessment</code> */ public static final AssessmentAssessment ASSESSMENT_ASSESSMENT = new AssessmentAssessment(); /** * The class holding records for this type */ @Override public Class<AssessmentAssessmentRecord> getRecordType() { return AssessmentAssessmentRecord.class; } /** * The column <code>bitnami_edx.assessment_assessment.id</code>. */ public final TableField<AssessmentAssessmentRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.assessment_assessment.submission_uuid</code>. */ public final TableField<AssessmentAssessmentRecord, String> SUBMISSION_UUID = createField("submission_uuid", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, ""); /** * The column <code>bitnami_edx.assessment_assessment.scored_at</code>. */ public final TableField<AssessmentAssessmentRecord, Timestamp> SCORED_AT = createField("scored_at", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.assessment_assessment.scorer_id</code>. */ public final TableField<AssessmentAssessmentRecord, String> SCORER_ID = createField("scorer_id", org.jooq.impl.SQLDataType.VARCHAR.length(40).nullable(false), this, ""); /** * The column <code>bitnami_edx.assessment_assessment.score_type</code>. */ public final TableField<AssessmentAssessmentRecord, String> SCORE_TYPE = createField("score_type", org.jooq.impl.SQLDataType.VARCHAR.length(2).nullable(false), this, ""); /** * The column <code>bitnami_edx.assessment_assessment.feedback</code>. */ public final TableField<AssessmentAssessmentRecord, String> FEEDBACK = createField("feedback", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); /** * The column <code>bitnami_edx.assessment_assessment.rubric_id</code>. */ public final TableField<AssessmentAssessmentRecord, Integer> RUBRIC_ID = createField("rubric_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * Create a <code>bitnami_edx.assessment_assessment</code> table reference */ public AssessmentAssessment() { this("assessment_assessment", null); } /** * Create an aliased <code>bitnami_edx.assessment_assessment</code> table reference */ public AssessmentAssessment(String alias) { this(alias, ASSESSMENT_ASSESSMENT); } private AssessmentAssessment(String alias, Table<AssessmentAssessmentRecord> aliased) { this(alias, aliased, null); } private AssessmentAssessment(String alias, Table<AssessmentAssessmentRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<AssessmentAssessmentRecord, Integer> getIdentity() { return Keys.IDENTITY_ASSESSMENT_ASSESSMENT; } /** * {@inheritDoc} */ @Override public UniqueKey<AssessmentAssessmentRecord> getPrimaryKey() { return Keys.KEY_ASSESSMENT_ASSESSMENT_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<AssessmentAssessmentRecord>> getKeys() { return Arrays.<UniqueKey<AssessmentAssessmentRecord>>asList(Keys.KEY_ASSESSMENT_ASSESSMENT_PRIMARY); } /** * {@inheritDoc} */ @Override public List<ForeignKey<AssessmentAssessmentRecord, ?>> getReferences() { return Arrays.<ForeignKey<AssessmentAssessmentRecord, ?>>asList(Keys.ASSESSMENT_AS_RUBRIC_ID_7997F01DCBD05633_FK_ASSESSMENT_RUBRIC_ID); } /** * {@inheritDoc} */ @Override public AssessmentAssessment as(String alias) { return new AssessmentAssessment(alias, this); } /** * Rename this table */ public AssessmentAssessment rename(String name) { return new AssessmentAssessment(name, null); } }
package com.demo.validator_demo.one; import com.demo.validator_demo.BeanValidator; import io.swagger.annotations.Api; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.validation.Valid; /** * @author yudong * @create 2019-11-14 10:47 */ @RestController @RequestMapping("/api") @Api(value = "测试Controller1", tags = {"测试Controller1"}) public class PersonController { @PostMapping("/person") public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) { return ResponseEntity.ok().body(person); } @PostMapping("/person1") public ResponseEntity<Person> getPerson1(@RequestBody Person person) { BeanValidator.check(person); return ResponseEntity.ok().body(person); } }
package pl.basistam.beer; import pl.basistam.beer.model.BeerExpert; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(value = "/WyborPiwa", name = "Servlet_wybierzpiwo") public class BeerChoice extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String color = request.getParameter("color"); BeerExpert ekspert = new BeerExpert(); request.setAttribute("brands", ekspert.getBrands(color)); RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/wynik.jsp"); view.forward(request, response); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/form.html").forward(request,response); } }
package exercicios.desafios.uri; import java.util.Locale; import java.util.Scanner; public class GastoCombustivel1017 { public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); int tempo = sc.nextInt(); int velocidade = sc.nextInt(); int qtdKm = tempo * velocidade; double qtdLitros = qtdKm / 12.0; System.out.format("%.3f%n", qtdLitros); sc.close(); } }
package com.movieapp.anti.movieapp.Models; import java.io.Serializable; /** * Created by Anti on 2/18/2018. */ public class Cast implements Serializable { String name; String character; String profile_path; public String getCharacter() { return character; } public void setCharacter(String character) { this.character = character; } public String getProfile_path() { return profile_path; } public void setProfile_path(String profile_path) { this.profile_path = profile_path; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package collections; import java.util.*; public class GenericCollection { public static void main(String[] args) { ArrayList<String> al = new ArrayList<String>(); // al.add(10);//error al.add("xxx"); al.add("yyy"); al.add("zzz"); System.out.println(al);// [xxx,yyy,zzz] for (String s : al) System.out.println(s); } }
package com.hello.suripu.service.pairing; import com.hello.suripu.api.ble.SenseCommandProtos; import com.hello.suripu.service.utils.RegistrationLogger; public class PairingResult { public final SenseCommandProtos.MorpheusCommand.Builder builder; public final RegistrationLogger onboardingLogger; public PairingResult(final SenseCommandProtos.MorpheusCommand.Builder builder, final RegistrationLogger onboardingLogger) { this.builder = builder; this.onboardingLogger = onboardingLogger; } }
package com.jushu.video.entity; import com.baomidou.mybatisplus.annotation.IdType; import java.util.Date; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author chen * @since 2020-01-09 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class GmOperation implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 管理员ID */ private String userId; /** * 管理员名称 */ private String userName; /** * 管理员操作 */ private String operation; /** * 方法名称 */ private String method; /** * 操作时间 */ private Date operationTime; /** * IP地址 */ private String loginIp; /** * 是否成功 (0成功、1失败) */ private Integer isSuccess; /** * 备注 */ private String remark; }
package com.lenovohit.ssm.treat.manager.impl; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import com.lenovohit.core.utils.StringUtils; import com.lenovohit.ssm.treat.dao.HisRestDao; import com.lenovohit.ssm.treat.manager.HisAppointmentManager; import com.lenovohit.ssm.treat.model.Appointment; import com.lenovohit.ssm.treat.model.Department; import com.lenovohit.ssm.treat.model.Patient; import com.lenovohit.ssm.treat.model.Schedule; import com.lenovohit.ssm.treat.transfer.dao.RestEntityResponse; import com.lenovohit.ssm.treat.transfer.dao.RestListResponse; import com.lenovohit.ssm.treat.transfer.dao.RestRequest; import com.lenovohit.ssm.treat.transfer.manager.HisEntityResponse; import com.lenovohit.ssm.treat.transfer.manager.HisListResponse; /** * HIS预约 * @author xiaweiyi * */ public class HisAppointmentManagerImpl implements HisAppointmentManager{ protected transient final Log log = LogFactory.getLog(getClass()); @Autowired private HisRestDao hisRestDao; /** * 一级科室基本信息查询 APPOINT001 * @param param * @return */ public HisListResponse<Department> getDepartments(){ RestListResponse response = hisRestDao.postForList("APPOINT0011", RestRequest.SEND_TYPE_LOCATION, null); HisListResponse<Department> result = new HisListResponse<Department>(response); List<Map<String, Object>> resMaplist = response.getList(); List<Department> resList = new ArrayList<Department>(); Department department = null; if(response.isSuccess() && null != resMaplist){ for(Map<String, Object> resMap : resMaplist){ department = new Department(); department.setCode(object2String(resMap.get("DETP_CODE_FIRST"))); department.setName(object2String(resMap.get("DETP_NMAE_FIRST"))); //department.setDesc(object2String(resMap.get("DEPT_INTRODUCE"))); department.setPinyin(object2String(resMap.get("PINYIN"))); resList.add(department); } result.setList(resList); } return result; } /** * 二级科室信息查询APPOINT0012 */ public HisListResponse<Department> getChildrenDepartments(String code) { Map<String, Object> reqMap = new HashMap<String, Object>(); reqMap.put("DETP_CODE_FIRST", code); RestListResponse response = hisRestDao.postForList("APPOINT0012", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Department> result = new HisListResponse<Department>(response); List<Map<String, Object>> resMaplist = response.getList(); List<Department> resList = new ArrayList<Department>(); Department department = null; if(response.isSuccess() && null != resMaplist){ for(Map<String, Object> resMap : resMaplist){ department = new Department(); department.setCode(object2String(resMap.get("DETP_CODE"))); department.setName(object2String(resMap.get("DETP_NMAE"))); department.setDescription(object2String(resMap.get("DEPT_INTRODUCE"))); department.setPinyin(object2String(resMap.get("PINYIN"))); department.setType(object2String(resMap.get("DETP_TYPE"))); resList.add(department); } result.setList(resList); } return result; } /** * 医生号源排班信息查询(按科室) APPOINT0031 * @param param * @return */ public HisListResponse<Schedule> getDepartmentSchedules(Schedule param) { Map<String, Object> reqMap = new HashMap<String, Object>(); // 入参字段映射 reqMap.put("BOOKING_PLATFORM", param.getBookingPlatform()); reqMap.put("START_DATE", param.getStartDate()); reqMap.put("END_DATE", param.getEndDate()); reqMap.put("DEPT_CODE", param.getDeptCode()); reqMap.put("DOCTOR_CODE", param.getDoctorCode()); reqMap.put("DEPT_TYPE", param.getDeptType()); //{DOCTOR_CODE=, DEPT_CODE=null, END_DATE=2017-10-27, START_DATE=2017-09-27, BOOKING_PLATFORM=111, DEPT_TYPE=1} RestListResponse response = hisRestDao.postForList("APPOINT0031", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Schedule> result = new HisListResponse<Schedule>(response); List<Map<String, Object>> resMaplist = response.getList(); List<Schedule> resList = new ArrayList<Schedule>(); Schedule schedule = null;//SPECIAL_DISEASES_NAME:专病 DEPT_NAME:专科 if(response.isSuccess() && null != resMaplist){ for(Map<String, Object> resMap : resMaplist){ schedule = new Schedule(); schedule.setScheduleId(object2String(resMap.get("SCHEDULEID"))); schedule.setDoctorCode(object2String(resMap.get("DOCTOR_CODE"))); schedule.setDoctorName(object2String(resMap.get("DOCTOR_NAME"))); schedule.setDoctorPinyin(StringUtils.getFirstUpPinyin(schedule.getDoctorName())); schedule.setDoctorType(object2String(resMap.get("DOCTOR_TYPE"))); schedule.setDoctorTypeName(object2String(resMap.get("DOCTOR_TYPENAME"))); schedule.setDeptCode(object2String(resMap.get("DEPT_CODE"))); schedule.setDeptName(object2String(resMap.get("DEPT_NAME"))); schedule.setOnDutyTime(object2String(resMap.get("ON_DUTY_TIME"))); schedule.setOffDutyTime(object2String(resMap.get("OFF_DUTY_TIME"))); schedule.setClinicType(object2String(resMap.get("DOCTOR_CLINIC_TYPE"))); schedule.setClinicTypeName(object2String(resMap.get("DOCTOR_CLINIC_TYPENAME"))); schedule.setClinicDate(object2String(resMap.get("CLINIC_DATE"))); schedule.setClinicDuration(object2String(resMap.get("CLINIC_DURATION"))); schedule.setClinicDurationName(object2String(resMap.get("CLINIC_DURATIONNAME"))); schedule.setHospitalDistrict(object2String(resMap.get("HOSPITAL_DISTRICT"))); schedule.setHospitalDistrictName(object2String(resMap.get("HOSPITAL_DISTRICTNAME"))); schedule.setServiceStation(object2String(resMap.get("OUTPATIENT_SERVICESTATION"))); schedule.setCountNo(object2String(resMap.get("APPOINTMENT_COUNTNO"))); schedule.setSpecialDiseasesCode(object2String(resMap.get("SPECIAL_DISEASES_CODE"))); schedule.setSpecialDiseasesName(object2String(resMap.get("SPECIAL_DISEASES_NAME"))); // 处理号源 String countNO = schedule.getCountNo(); List<Appointment> appointments = new ArrayList<Appointment>(); String[] appoints = countNO.split(";"); for(String appoint : appoints ){ if(StringUtils.isBlank(appoint)){ continue; } String[] data = appoint.split(","); if(data.length != 2){ log.info("号源数据格式错误 : "+appoint); continue; } Appointment appointment = new Appointment(); appointment.setScheduleId(schedule.getScheduleId()); appointment.setAppointmentNo(data[0]); String[] dateTime = data[1].split(" "); if(dateTime.length != 2){ log.info("日期格式错误 : "+data[1]); appointment.setAppointmentTime(data[1]); }else{ appointment.setAppointmentDate(dateTime[0]); appointment.setAppointmentTime(data[1]); } appointment.setDeptName(schedule.getDeptName()); appointment.setClinicTypeName(schedule.getClinicTypeName()); appointment.setClinicDurationName(schedule.getClinicDurationName()); appointment.setDoctorName(schedule.getDoctorName()); appointment.setDoctorTypeName(schedule.getDoctorTypeName()); appointment.setHospitalDistrictName(schedule.getHospitalDistrictName()); appointments.add(appointment); } schedule.setAppointments(appointments); resList.add(schedule); } resList.sort(new Comparator<Schedule>() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public int compare(Schedule o1, Schedule o2) { if(StringUtils.isEmpty(o1.getOnDutyTime()) || StringUtils.isEmpty(o2.getOnDutyTime())) return 0; try { Date date1 = format.parse(o1.getOnDutyTime()); Date date2 = format.parse(o2.getOnDutyTime()); if(date1.before(date2))return -1; else return 1; } catch (ParseException e) { return 0; } } }); result.setList(resList); } return result; } /** * 医生号源排班信息查询(按医师) APPOINT004 * @param param * @return */ public HisListResponse<Schedule> getDoctorSchedules(Schedule param){ Map<String, Object> reqMap = new HashMap<String, Object>(); // 入参字段映射 reqMap.put("BOOKING_PLATFORM", param.getBookingPlatform()); reqMap.put("START_DATE", param.getStartDate()); reqMap.put("END_DATE", param.getEndDate()); reqMap.put("DEPT_CODE", param.getDeptId()); reqMap.put("DOCTOR_CODE", param.getDoctorCode()); RestListResponse response = hisRestDao.postForList("APPOINT004", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Schedule> result = new HisListResponse<Schedule>(response); List<Map<String, Object>> resMaplist = response.getList(); List<Schedule> resList = new ArrayList<Schedule>(); Schedule schedule = null; if(response.isSuccess() && null != resMaplist){ for(Map<String, Object> resMap : resMaplist){ schedule = new Schedule(); schedule.setScheduleId(object2String(resMap.get("SCHEDULEID"))); schedule.setDoctorCode(object2String(resMap.get("DOCTOR_CODE"))); schedule.setDoctorName(object2String(resMap.get("DOCTOR_NAME"))); schedule.setDoctorPinyin(StringUtils.getFirstUpPinyin(schedule.getDoctorName())); schedule.setDoctorType(object2String(resMap.get("DOCTOR_TYPE"))); schedule.setDoctorTypeName(object2String(resMap.get("DOCTOR_TYPENAME"))); schedule.setDeptCode(object2String(resMap.get("DEPT_CODE"))); schedule.setDeptName(object2String(resMap.get("DEPT_NAME"))); schedule.setOnDutyTime(object2String(resMap.get("ON_DUTY_TIME"))); schedule.setOffDutyTime(object2String(resMap.get("OFF_DUTY_TIME"))); schedule.setClinicType(object2String(resMap.get("DOCTOR_CLINIC_TYPE"))); schedule.setClinicType(object2String(resMap.get("DOCTOR_CLINIC_TYPE"))); schedule.setClinicTypeName(object2String(resMap.get("DOCTOR_CLINIC_TYPENAME"))); schedule.setClinicDate(object2String(resMap.get("CLINIC_DATE"))); schedule.setClinicDuration(object2String(resMap.get("CLINIC_DURATION"))); schedule.setClinicDurationName(object2String(resMap.get("CLINIC_DURATIONNAME"))); schedule.setHospitalDistrict(object2String(resMap.get("HOSPITAL_DISTRICT"))); schedule.setHospitalDistrictName(object2String(resMap.get("HOSPITAL_DISTRICTNAME"))); schedule.setServiceStation(object2String(resMap.get("OUTPATIENT_SERVICESTATION"))); schedule.setCountNo(object2String(resMap.get("APPOINTMENT_COUNTNO"))); schedule.setSpecialDiseasesCode(object2String(resMap.get("SPECIAL_DISEASES_CODE"))); schedule.setSpecialDiseasesName(object2String(resMap.get("SPECIAL_DISEASES_NAME"))); // 处理号源 String countNO = schedule.getCountNo(); List<Appointment> appointments = new ArrayList<Appointment>(); String[] appoints = countNO.split(","); for(String appoint : appoints ){ if(StringUtils.isBlank(appoint)){ continue; } String[] data = appoint.split(","); if(data.length != 2){ log.info("号源数据格式错误 : "+appoint); continue; } Appointment appointment = new Appointment(); appointment.setScheduleId(schedule.getScheduleId()); appointment.setAppointmentNo(data[0]); String[] dateTime = data[1].split(" "); if(dateTime.length != 2){ log.info("日期格式错误 : "+data[1]); appointment.setAppointmentTime(data[1]); }else{ appointment.setAppointmentDate(dateTime[0]); appointment.setAppointmentTime(data[1]); } appointment.setDeptName(schedule.getDeptName()); appointment.setClinicTypeName(schedule.getClinicTypeName()); appointment.setClinicDurationName(schedule.getClinicDurationName()); appointment.setDoctorName(schedule.getDoctorName()); appointment.setDoctorTypeName(schedule.getDoctorTypeName()); appointment.setHospitalDistrictName(schedule.getHospitalDistrictName()); appointments.add(appointment); } schedule.setAppointments(appointments); resList.add(schedule); } result.setList(resList); } return result; } /** * 获取某一排班的可预约序号列表(APPOINT005) * @param param * @return */ public HisListResponse<Appointment> getAppointSources(Schedule param){ RestListResponse response = hisRestDao.postForList("二期", RestRequest.SEND_TYPE_LOCATION, param); HisListResponse<Appointment> result = new HisListResponse<Appointment>(response); List<Appointment> resList = new ArrayList<Appointment>(); result.setList(resList); return result; } /** * 预约记录生成(APPOINT006) * @param patient * @param srouce * @param param * @return */ public HisEntityResponse<Appointment> bookAppiontment(Appointment param){ Map<String,Object> reqMap = new HashMap<String,Object>(); //入参字段映射 reqMap.put("BOOKING_PLATFORM", param.getBookingPlatform()); reqMap.put("SCHEDULEID", param.getScheduleId()); reqMap.put("APPOINTMENT_NO", param.getAppointmentNo()); reqMap.put("APPOINTMENT_TIME", param.getAppointmentTime()); reqMap.put("PATIENTNO", param.getPatientNo()); reqMap.put("PATIENT_NAME", param.getPatientName()); reqMap.put("PATIENT_SEX", param.getPatientSex()); reqMap.put("PATIENT_PHONE_NO", param.getPatientPhone()); reqMap.put("PATIENT_ID_NO", param.getPatientIdNo()); reqMap.put("REMARKS", param.getRemarks()); reqMap.put("OperaterUserID", param.getOperaterUserID()); RestEntityResponse response = hisRestDao.postForEntity("APPOINT006", RestRequest.SEND_TYPE_POST, reqMap); Map<String, Object> resMap = response.getEntity(); HisEntityResponse<Appointment> result = new HisEntityResponse<Appointment>(response); if(response.isSuccess() && null != resMap){ Appointment appointment = new Appointment(); appointment.setVerifyCode(object2String(resMap.get("VERIFY_CODE")));//取号凭证 appointment.setAppointmentNo(object2String(resMap.get("APPOINTMENT_NO")));//预约序号 appointment.setAppointmentTime(object2String(resMap.get("APPOINTMENT_TIME")));//预约时间 appointment.setAppointmentInfo(object2String(resMap.get("APPOINTMENT_INFO")));//预约信息 appointment.setPatientName(object2String(resMap.get("brxm")));//病人姓名 appointment.setAppointmentDate(object2String(resMap.get("yyrq")));//预约日期 appointment.setDeptName(object2String(resMap.get("zk")));//预约科室 appointment.setScheduleDeptName(object2String(resMap.get("zb")));//值班科室 appointment.setClinicHouse(object2String(resMap.get("zs")));//预约诊室 appointment.setHouseLocation(object2String(resMap.get("fjwz")));//房间位置 appointment.setHospitalDistrictName(object2String(resMap.get("yq")));//院区 result.setEntity(appointment); } return result; } /** * 未签到预约记录查询 appointment/unsigned/list get * @param appiont * @return */ @Deprecated public HisListResponse<Appointment> unsignedList(Patient param){ RestListResponse response = hisRestDao.postForList("二期", RestRequest.SEND_TYPE_LOCATION, param); return new HisListResponse<Appointment>(response); } /** * 已预约挂号信息查询(APPOINT007) * 根据病人姓名、电话、时间查询 * @param appiont * @return */ @Deprecated public HisListResponse<Appointment> appointments(Appointment param){ Map<String,Object> reqMap = new HashMap<String,Object>(); //入参字段映射 reqMap.put("PATIENT_NAME", param.getPatientName()); reqMap.put("PATIENT_PHONE_NO", param.getPatientPhone()); reqMap.put("APPOINTMENT_TIME", param.getAppointmentTime()); RestListResponse response = hisRestDao.postForList("APPOINT007", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Appointment> reuslt =new HisListResponse<Appointment>(); List<Map<String, Object>> resMapList = response.getList(); List<Appointment> resList = new ArrayList<Appointment>(); Appointment appointment = null; if(null != resMapList){ for(Map<String, Object> resMap : resMapList){ appointment = new Appointment(); appointment.setAppointmentId(object2String(resMap.get("APPOINTMENT_ID"))); appointment.setDoctorName(object2String(resMap.get("DOCTOR_NAME"))); appointment.setDoctorTypeName(object2String(resMap.get("DOCTOR_TYPENAME"))); appointment.setDeptName(object2String(resMap.get("DEPT_NAME"))); appointment.setClinicTypeName(object2String(resMap.get("DOCTOR_CLINIC_TYPENAME"))); appointment.setHospitalDistrictName(object2String(resMap.get("HOSPITAL_DISTRICTNAME"))); appointment.setAppointmentNo(object2String(resMap.get("APPOINTMENT_NO"))); appointment.setAppointmentTime(object2String(resMap.get("APPOINTMENT_TIME"))); appointment.setAppointmentState(object2String(resMap.get("APPOINTMENT_STATE"))); resList.add(appointment); } reuslt.setList(resList); } return reuslt; } /** * 已预约挂号信息查询(APPOINT0071) * @param appiont * @return */ public HisListResponse<Appointment> getAppointments(Appointment param){ Map<String,Object> reqMap = new HashMap<String,Object>(); //入参字段映射 reqMap.put("PATIENT_NO", param.getPatientNo()); reqMap.put("APPOINTMENT_TIME", param.getAppointmentTime()); RestListResponse response = hisRestDao.postForList("APPOINT0071", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Appointment> result = new HisListResponse<Appointment>(response); List<Map<String, Object>> resMapList = response.getList(); List<Appointment> resList = new ArrayList<Appointment>(); Appointment appointment = null; if(null != resMapList){ for(Map<String, Object> resMap : resMapList){ appointment = new Appointment(); appointment.setAppointmentId(object2String(resMap.get("APPOINTMENT_ID"))); appointment.setDoctorName(object2String(resMap.get("DOCTOR_NAME"))); appointment.setDoctorTypeName(object2String(resMap.get("DOCTOR_TYPENAME"))); appointment.setDeptName(object2String(resMap.get("DEPT_NAME"))); appointment.setClinicTypeName(object2String(resMap.get("DOCTOR_CLINIC_TYPENAME"))); appointment.setHospitalDistrictName(object2String(resMap.get("HOSPITAL_DISTRICTNAME"))); appointment.setAppointmentNo(object2String(resMap.get("APPOINTMENT_NO"))); appointment.setAppointmentTime(object2String(resMap.get("APPOINTMENT_TIME"))); appointment.setAppointmentState(object2String(resMap.get("APPOINTMENT_STATE")));//0预留,1预约,2等待,3已呼叫,4已刷卡,5完成,9放弃 resList.add(appointment); } result.setList(resList); } return result; } /** * 就诊登记(APPOINT011) * @param appiont * @return */ public HisEntityResponse<Appointment> sign(Appointment param){ Map<String,Object> reqMap = new HashMap<String,Object>(); //入参字段映射 reqMap.put("BOOKING_PLATFORM", param.getBookingPlatform()); reqMap.put("CARDNO", param.getCardNo()); reqMap.put("PATIENTNO", param.getPatientNo()); reqMap.put("APPOINTMENTID", param.getAppointmentId()); reqMap.put("OperaterUserID", param.getOperaterUserID()); RestEntityResponse response = hisRestDao.postForEntity("APPOINT011", RestRequest.SEND_TYPE_POST, reqMap); Map<String, Object> resMap = response.getEntity(); HisEntityResponse<Appointment> result = new HisEntityResponse<Appointment>(response); if(response.isSuccess() && null != resMap){ Appointment appointment = new Appointment(); appointment.setAppointmentInfo(object2String(resMap.get("APPOINTMENT_INFO")));//预约信息 appointment.setPatientName(object2String(resMap.get("brxm")));//病人姓名 appointment.setAppointmentDate(object2String(resMap.get("yyrq")));//预约日期 appointment.setDeptName(object2String(resMap.get("zk")));//预约科室 appointment.setScheduleDeptName(object2String(resMap.get("zb")));//值班科室 appointment.setClinicHouse(object2String(resMap.get("zs")));//预约诊室 appointment.setHouseLocation(object2String(resMap.get("fjwz")));//房间位置 appointment.setHospitalDistrictName(object2String(resMap.get("yq")));//院区 result.setEntity(appointment); } return result; } /** * 3.4取消预约(APPOINT008) * @param appiont * @return */ public HisEntityResponse<Appointment> cancel(Appointment param) { Map<String, Object> reqMap = new HashMap<String, Object>(); // 入参字段映射 reqMap.put("ll_fzyyid", param.getAppointmentId()); reqMap.put("OperaterUserID", param.getOperaterUserID()); RestEntityResponse response = hisRestDao.postForEntity("APPOINT008", RestRequest.SEND_TYPE_POST, reqMap); HisEntityResponse<Appointment> result= new HisEntityResponse<Appointment>(response); return result; } private String object2String(Object obj){ return obj==null ? "" : obj.toString(); } }
/* * 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 mbh.employee; /** * * @author Benny.D */ import javax.swing.JPanel; import javax.swing.border.TitledBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.SystemColor; public class DeleteEmployeePanel extends JPanel { /** * */ private static final long serialVersionUID = 1L; private JTextField idField; /** * Create the panel. */ public DeleteEmployeePanel() { setBackground(SystemColor.controlHighlight); setBorder(new TitledBorder(null, "Delete Employee", TitledBorder.LEADING, TitledBorder.TOP, null, null)); this.setBounds(100, 100, 750, 550); setLayout(null); JLabel employeeIdLabel = new JLabel("Employee ID:"); employeeIdLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); employeeIdLabel.setBounds(22, 30, 100, 20); add(employeeIdLabel); idField = new JTextField(); idField.setFont(new Font("Tahoma", Font.PLAIN, 14)); idField.setBounds(130, 30, 126, 22); add(idField); idField.setColumns(10); JButton createBookingButton = new JButton("Delete"); createBookingButton.setFont(new Font("Tahoma", Font.PLAIN, 14)); createBookingButton.setBounds(64, 60, 126, 33); add(createBookingButton); } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.network; /** * Session存储属性的Map接口. * * @author 小流氓[176543888@qq.com] * @since 3.2.2 */ public interface SessionAttrMap { /** * 获取指定{@link SessionAttrKey}的一个{@link SessionAttr}. * <p> * 这个返回值决不为null,但可能{@link SessionAttr}中所包含的值为空 * * @param <T> 属性值的类型 * @param key 属性Key * @return 返回指定Key对应的值 */ <T> SessionAttr<T> attr(SessionAttrKey<T> key); }
package items; import board.blockingobject.Player; import board.square.Square; import util.parameters.ItemUseParameter; import util.parameters.PlayerEventParameter; import util.parameters.StepOnParameter; public class Teleporter extends Item { private Square position; private Teleporter destination; /** * Creates a new teleporter * @param position The square the teleporter is on * * @throws IllegalArgumentException * when the position is null. */ public Teleporter(Square position) throws IllegalArgumentException{ if(position == null) throw new IllegalArgumentException(); this.position = position; } /** * * @return The destination teleporter that this teleporter teleports to */ public Teleporter getDestination() { return destination; } /** * Sets the teleporter that this teleporter teleports to * @param destination teleporter that this teleporter teleports to * @throws IllegalArgumentException | destination == null * | The teleporter already has his destination set */ public void setDestination(Teleporter destination) throws IllegalArgumentException{ if(destination == null || this.destination != null) throw new IllegalArgumentException(); this.destination = destination; } /** * Method that gets the current square on which this teleporter is located * * @return Square * Square on which the teleporter is located */ public Square getPosition() { return position; } @Override public boolean isAccessible() { if(destination.getPosition().hasBlockingObject()) return false; return true; } @Override public void stepOn(StepOnParameter effectStepOnParameter) { if(effectStepOnParameter.getPlayer() != null){ Player player = effectStepOnParameter.getPlayer(); player.notifyObservers(new PlayerEventParameter(false)); position.removeBlockingObject(); destination.getPosition().setBlockingObject(player); player.setPosition(destination.getPosition()); destination.getPosition().teleportOn(player); player.getLightTrail().addHeadOfTrail(destination.getPosition()); } } @Override public void startOn(Player player) { } @Override public void use(Square sq, ItemUseParameter param) { } @Override public boolean canPickup() { return false; } @Override public boolean canPickup(Player player) { return false; } @Override public boolean canUseOnSquare(Square sq) { return false; } @Override public void actionPerformed() { } @Override public void turnPerformed() { } @Override public void onLeave(Player player) { } }
package com.esum.wp.ims.restinfo.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.esum.appframework.service.IBaseService; public interface IRestInfoService extends IBaseService { Object insert(Object object); Object update(Object object); Object delete(Object object); Object restInfoDetail(Object object); Object restInfoPageList(Object object); void saveRestInfoExcel(Object object, HttpServletRequest request, HttpServletResponse response) throws Exception; Object checkRestInfoDuplicate(Object object); }
package br.com.raiox.controller; import java.io.IOException; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import org.primefaces.model.LazyDataModel; import br.com.raiox.dao.CargoDAO; import br.com.raiox.dao.PessoaDAO; import br.com.raiox.dao.ServidorDAO; import br.com.raiox.dao.UORGDAO; import br.com.raiox.dao.lazy.LazyDataModelServidor; import br.com.raiox.model.Campus; import br.com.raiox.model.Cargo; import br.com.raiox.model.Pessoa; import br.com.raiox.model.Servidor; import br.com.raiox.model.UORG; import br.com.raiox.util.StringUtil; @ViewScoped @ManagedBean(name = "servidorController") public class ServidorController implements Serializable { private static final long serialVersionUID = 1L; private Servidor servidor = new Servidor(); private Cargo cargo = new Cargo(); private UORG uorgExercicio = new UORG(); private UORG uorgLotacao = new UORG(); private Pessoa pessoa = new Pessoa(); private PessoaDAO pessoaDAO = new PessoaDAO(); private UORGDAO uorgDAO = new UORGDAO(); private ServidorDAO servidorDAO = new ServidorDAO(); private CargoDAO cargoDAO = new CargoDAO(); private LazyDataModel<Servidor> servidors; private List<Cargo> cargos; private List<Campus> campuss; private List<UORG> UORGs; private List<Pessoa> pessoas; @PostConstruct public void init() { servidorDAO = new ServidorDAO(); servidors = getServidors(); cargos = cargoDAO.findAll(); UORGs = uorgDAO.findAll(); pessoas = pessoaDAO.findAll(); } /** * Chama o lazy data model do objeto para realizar consulta sob demanda * * @return */ public LazyDataModel<Servidor> getServidors() { if (servidors == null) { servidors = new LazyDataModelServidor(servidorDAO); } return servidors; } public Integer tamanhoLista() { return servidors.getRowCount(); } public void save() { // DAO save the add, load list try { servidor.setCargo(cargo); servidor.setUorgExercicio(uorgExercicio); servidor.setUorgLotacao(uorgLotacao); servidor.setPessoa(pessoa); if (!StringUtil.isNullOrEmpty(servidor.validate())) { FacesContext.getCurrentInstance().addMessage("growlMessage", new FacesMessage(FacesMessage.SEVERITY_WARN, "Alerta", servidor.validate())); return; } servidorDAO.update(servidor); // for="growlMessage" FacesContext.getCurrentInstance().addMessage("growlMessage", new FacesMessage(FacesMessage.SEVERITY_INFO, "Mensagem", "Salvo com sucesso.")); } catch (Exception e) { e.printStackTrace(); FacesContext.getCurrentInstance().addMessage("growlMessage", new FacesMessage(FacesMessage.SEVERITY_FATAL, "Contate o admin do sistema", e.getMessage())); // TODO: handle exception } servidor = new Servidor(); cargo = new Cargo(); uorgExercicio = new UORG(); uorgLotacao = new UORG(); pessoa = new Pessoa(); } public void edit() { if (servidor.getCargo() != null && servidor.getCargo().getId() != null) { cargo = servidor.getCargo(); } if (servidor.getPessoa() != null && servidor.getPessoa().getId() != null) { pessoa = servidor.getPessoa(); } if (servidor.getUorgExercicio() != null && servidor.getUorgExercicio().getId() != null) { uorgExercicio = servidor.getUorgExercicio(); } if (servidor.getUorgLotacao() != null && servidor.getUorgLotacao().getId() != null) { uorgLotacao = servidor.getUorgLotacao(); } } public void limpar() { pessoa = new Pessoa(); servidor = new Servidor(); cargo = new Cargo(); uorgExercicio = new UORG(); uorgLotacao = new UORG(); pessoa = new Pessoa(); } public void delete() throws IOException { // DAO save the add, load list try { servidorDAO.remove(servidor); // for="growlMessage" FacesContext.getCurrentInstance().addMessage("growlMessage", new FacesMessage(FacesMessage.SEVERITY_INFO, "Mensagem", "Removido com sucesso.")); } catch (Exception e) { FacesContext.getCurrentInstance().addMessage("growlMessage", new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", "Ocorreu um erro ao remover os dados!")); // TODO: handle exception } servidor = new Servidor(); } public Servidor getServidor() { return servidor; } public void setServidor(Servidor servidor) { this.servidor = servidor; } public List<Cargo> getCargos() { return cargos; } public void setCargos(List<Cargo> cargos) { this.cargos = cargos; } public Cargo getCargo() { return cargo; } public void setCargo(Cargo cargo) { this.cargo = cargo; } public UORG getUorgExercicio() { return uorgExercicio; } public void setUorgExercicio(UORG uorgExercicio) { this.uorgExercicio = uorgExercicio; } public UORG getUorgLotacao() { return uorgLotacao; } public void setUorgLotacao(UORG uorgLotacao) { this.uorgLotacao = uorgLotacao; } public void setServidors(LazyDataModel<Servidor> servidors) { this.servidors = servidors; } public List<UORG> getUORGs() { return UORGs; } public void setUORGs(List<UORG> uORGs) { UORGs = uORGs; } public Pessoa getPessoa() { return pessoa; } public void setPessoa(Pessoa pessoa) { this.pessoa = pessoa; } public List<Pessoa> getPessoas() { return pessoas; } public void setPessoas(List<Pessoa> pessoas) { this.pessoas = pessoas; } }
package network.nerve.swap.storage; import io.nuls.base.data.NulsHash; import network.nerve.swap.model.po.FarmUserInfoPO; /** * @author Niels */ public interface FarmUserInfoStorageService { FarmUserInfoPO save(int chainId,FarmUserInfoPO po); boolean delete(int chainId,NulsHash farmHash, byte[] address); FarmUserInfoPO load(int chainId,NulsHash farmHash, byte[] address); FarmUserInfoPO loadByKey(int chainId,byte[] key); }
package orm.integ.test.entity; import java.util.Date; import orm.integ.dao.annotation.ForeignKey; import orm.integ.dao.annotation.Table; import orm.integ.eao.model.Entity; @Table( name="tb_student") public class Student extends Entity { private String name; private Integer sex; private Date birthday; @ForeignKey(masterClass=SchoolClass.class) private int schoolClassId; private String className; private int age; public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public int getSchoolClassId() { return schoolClassId; } public void setSchoolClassId(int schoolClassId) { this.schoolClassId = schoolClassId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.example.adnan.reportcard; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView listView; ArrayList<students> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); list = new ArrayList<students>(); list.add(new students("Adnan Ahmed", "5th", "present", "A+", R.drawable.aa)); list.add(new students("Fawad khan", "0th", "Absent", "Fail", R.drawable.bb)); list.add(new students("Kashan Zafar", "2nd", "present", "A+", R.drawable.aa)); list.add(new students("Faiz Rehman", "10th", "present", "B+", R.drawable.bb)); list.add(new students("Zeeshan Ali", "15th", "present", "C", R.drawable.aa)); list.add(new students("Muhammad Adnan", "7th", "present", "B+", R.drawable.bb)); list.add(new students("Arslan Ghani", "8th", "present", "B+", R.drawable.aa)); list.add(new students("Owais Khan", "9th", "present", "B+", R.drawable.bb)); adaptor adaptor = new adaptor(this, list); listView.setAdapter(adaptor); } }
package com.example.onix_android; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class FullScreenNote extends AppCompatActivity { TextView bigTitle, bigText, bigDate, bigTag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_full_screen_note); bigTitle = findViewById(R.id.big_title); bigText = findViewById(R.id.big_text); bigTag = findViewById(R.id.big_tag); bigDate = findViewById(R.id.big_created); Intent intent = getIntent(); String title = intent.getStringExtra("title"); String tag = intent.getStringExtra("tag"); String text = intent.getStringExtra("text"); String date = intent.getStringExtra("date"); bigTitle.setText(title); bigText.setText(text); bigTag.setText(String.format("Tag: %s", tag)); bigDate.setText(String.format("Created: %s", date)); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.result.view.freemarker; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Locale; import freemarker.template.Configuration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; import org.springframework.context.ApplicationContextException; import org.springframework.context.support.GenericApplicationContext; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.ModelMap; import org.springframework.web.reactive.result.view.ZeroDemandResponse; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; import org.springframework.web.server.session.DefaultWebSessionManager; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest; import org.springframework.web.testfixture.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rossen Stoyanchev * @author Sam Brannen */ class FreeMarkerViewTests { private static final String TEMPLATE_PATH = "classpath*:org/springframework/web/reactive/view/freemarker/"; private final FreeMarkerView freeMarkerView = new FreeMarkerView(); private final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); private final GenericApplicationContext context = new GenericApplicationContext(); private Configuration freeMarkerConfig; @BeforeEach void setup() throws Exception { this.context.refresh(); FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setPreferFileSystemAccess(false); configurer.setTemplateLoaderPath(TEMPLATE_PATH); configurer.setResourceLoader(this.context); this.freeMarkerConfig = configurer.createConfiguration(); } @Test void noFreeMarkerConfig() { freeMarkerView.setApplicationContext(this.context); freeMarkerView.setUrl("anythingButNull"); assertThatExceptionOfType(ApplicationContextException.class) .isThrownBy(freeMarkerView::afterPropertiesSet) .withMessageContaining("Must define a single FreeMarkerConfig bean"); } @Test void noTemplateName() { assertThatIllegalArgumentException() .isThrownBy(freeMarkerView::afterPropertiesSet) .withMessageContaining("Property 'url' is required"); } @Test void checkResourceExists() throws Exception { freeMarkerView.setConfiguration(this.freeMarkerConfig); freeMarkerView.setUrl("test.ftl"); assertThat(freeMarkerView.checkResourceExists(Locale.US)).isTrue(); } @Test void resourceExists() { freeMarkerView.setConfiguration(this.freeMarkerConfig); freeMarkerView.setUrl("test.ftl"); StepVerifier.create(freeMarkerView.resourceExists(Locale.US)) .assertNext(b -> assertThat(b).isTrue()) .verifyComplete(); } @Test void resourceDoesNotExists() { freeMarkerView.setConfiguration(this.freeMarkerConfig); freeMarkerView.setUrl("foo-bar.ftl"); StepVerifier.create(freeMarkerView.resourceExists(Locale.US)) .assertNext(b -> assertThat(b).isFalse()) .verifyComplete(); } @Test void render() { freeMarkerView.setApplicationContext(this.context); freeMarkerView.setConfiguration(this.freeMarkerConfig); freeMarkerView.setUrl("test.ftl"); ModelMap model = new ExtendedModelMap(); model.addAttribute("hello", "hi FreeMarker"); freeMarkerView.render(model, null, this.exchange).block(Duration.ofMillis(5000)); StepVerifier.create(this.exchange.getResponse().getBody()) .consumeNextWith(buf -> assertThat(buf.toString(StandardCharsets.UTF_8)) .isEqualTo("<html><body>hi FreeMarker</body></html>")) .expectComplete() .verify(); } @Test // gh-22754 void subscribeWithoutDemand() { ZeroDemandResponse response = new ZeroDemandResponse(); ServerWebExchange exchange = new DefaultServerWebExchange( MockServerHttpRequest.get("/path").build(), response, new DefaultWebSessionManager(), ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver()); freeMarkerView.setApplicationContext(this.context); freeMarkerView.setConfiguration(this.freeMarkerConfig); freeMarkerView.setUrl("test.ftl"); ModelMap model = new ExtendedModelMap(); model.addAttribute("hello", "hi FreeMarker"); freeMarkerView.render(model, null, exchange).subscribe(); response.cancelWrite(); response.checkForLeaks(); } @SuppressWarnings("unused") private String handle() { return null; } }
package br.com.cast.scc.dao; import org.springframework.stereotype.Component; import br.com.cast.scc.model.DominioTipoVeiculo; @Component public class DominioTipoVeiculoDAO extends DAOBase<DominioTipoVeiculo> { }
/* ~~ The PreviewRow is part of BusinessProfit. ~~ * * The BusinessProfit's classes and any part of the code * cannot be copied/distributed without * the permission of Sotiris Doudis * * Github - RiflemanSD - https://github.com/RiflemanSD * * Copyright © 2016 Sotiris Doudis | All rights reserved * * License for BusinessProfit project - in GREEK language * * Οποιοσδήποτε μπορεί να χρησιμοποιήσει το πρόγραμμα για προσωπική του χρήση. * Αλλά απαγoρεύεται η πώληση ή διακίνηση του προγράμματος σε τρίτους. * * Aπαγορεύεται η αντιγραφή ή διακίνηση οποιοδήποτε μέρος του κώδικα χωρίς * την άδεια του δημιουργού. * Σε περίπτωση που θέλετε να χρεισημοποιήσετε κάποια κλάση ή μέρος του κώδικα. * Πρέπει να συμπεριλάβεται στο header της κλάσης τον δημιουργό και link στην * αυθεντική κλάση (στο github). * * ~~ Information about BusinessProfit project - in GREEK language ~~ * * Το BusinessProfit είναι ένα project για την αποθήκευση και επεξεργασία * των εσόδων/εξόδων μίας επιχείρησης με σκοπό να μπορεί ο επιχειρηματίας να καθορήσει * το καθαρό κέρδος της επιχείρησης. Καθώς και να κρατάει κάποια σημαντικά * στατιστικά στοιχεία για τον όγκο της εργασίας κτλ.. * * Το project δημιουργήθηκε από τον Σωτήρη Δούδη. Φοιτητή πληροφορικής του Α.Π.Θ * για προσωπική χρήση. Αλλά και για όποιον άλλον πιθανόν το χρειαστεί. * * Το project προγραμματίστηκε σε Java (https://www.java.com/en/download/). * Με χρήση του NetBeans IDE (https://netbeans.org/) * Για να το τρέξετε πρέπει να έχετε εγκαταστήσει την java. * * Ο καθένας μπορεί δωρεάν να χρησιμοποιήσει το project αυτό. Αλλά δεν επιτρέπεται * η αντιγραφή/διακήνηση του κώδικα, χωρίς την άδεια του Δημιουργού (Δείτε την License). * * Github - https://github.com/RiflemanSD/BusinessProfit * * * Copyright © 2016 Sotiris Doudis | All rights reserved */ package org.riflemansd.businessprofit.panels; import javax.swing.JOptionPane; /** <h1>PreviewRow</h1> * * <p></p> * * <p>Last Update: 30/01/2016</p> * <p>Author: <a href=https://github.com/RiflemanSD>RiflemanSD</a></p> * * <p>Copyright © 2016 Sotiris Doudis | All rights reserved</p> * * @version 1.0.7 * @author RiflemanSD */ public class PreviewRow extends javax.swing.JFrame { /** * Creates new form PreviewRow */ public PreviewRow() { initComponents(); } public PreviewRow(String[] data) { initComponents(); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); id.setText(data[0]); date.setText(data[1]); category.setText(data[2]); inout.setText(data[3]); value.setText(data[4]); info.setText(data[5]); par.setText(data[6]); pal.setText(data[7]); } public String[] getDatas() { String[] datas = new String[8]; datas[0] = id.getText(); datas[1] = date.getText(); datas[2] = category.getText(); datas[3] = inout.getText(); datas[4] = info.getText(); datas[5] = value.getText(); datas[6] = par.getText(); datas[7] = pal.getText(); return datas; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); id = new javax.swing.JTextField(); date = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); category = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); inout = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); value = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); info = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); par = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); pal = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); saveButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setText("ID"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("Ημερομηνία"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("Κατηγορία"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("Έσοδο/Έξοδο"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("Ποσό (€)"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setText("Αιτιολογία"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setText("Παραλαβές"); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel8.setText("Παραδόσεις"); saveButton.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N saveButton.setText("Save"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); cancelButton.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel8)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(category, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(inout, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(value, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(info, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(par, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pal, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(27, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(category, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(inout, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(value, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(par, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(pal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed JOptionPane.showMessageDialog(rootPane, "Η επεξεργασία των δεδομένων δεν είναι ακόμη διαθέσιμη!"); this.dispose(); }//GEN-LAST:event_saveButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.dispose(); }//GEN-LAST:event_cancelButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PreviewRow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PreviewRow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PreviewRow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PreviewRow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PreviewRow().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JTextField category; private javax.swing.JTextField date; private javax.swing.JTextField id; private javax.swing.JTextField info; private javax.swing.JTextField inout; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JTextField pal; private javax.swing.JTextField par; private javax.swing.JButton saveButton; private javax.swing.JTextField value; // End of variables declaration//GEN-END:variables }
package cn.com.signheart.common.util; import java.util.ArrayList; import java.util.List; public class TreeObject { String icon; String title; String titleurl; List<TreeObject> nodes = new ArrayList(); public TreeObject() { } public String getIcon() { return this.icon; } public void setIcon(String icon) { this.icon = icon; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getTitleurl() { return this.titleurl; } public void setTitleurl(String titleurl) { this.titleurl = titleurl; } public List<TreeObject> getNodes() { return this.nodes; } public void setNodes(List<TreeObject> nodes) { this.nodes = nodes; } public void addChild(TreeObject treeObject) { this.nodes.add(treeObject); } }
package user.com.foodexuserui; import android.app.Activity; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.renderscript.Allocation; import android.renderscript.Element; import android.renderscript.RenderScript; import android.renderscript.ScriptIntrinsicBlur; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.support.v4.widget.DrawerLayout; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import user.com.Entities.MenuBean; import user.com.commons.CustomPagerAdapter; import user.com.foodexuserui.NavDrawerPages.MyAccount; import user.com.foodexuserui.NavDrawerPages.MyAddress; import user.com.foodexuserui.R; public class NavigationDrawer extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks { /** * Fragment managing the behaviors, interactions and presentation of the * navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private static final float BITMAP_SCALE = 0.4f; private static final float BLUR_RADIUS = 7.5f; /** * Used to store the last screen title. For use in * {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar acb = getSupportActionBar(); acb.setIcon(R.drawable.img_profile); setContentView(R.layout.activity_navdraw); //added to set breakfast list items List<MenuBean> listMenuBean = new ArrayList<MenuBean>(); MenuBean bean1 = new MenuBean(); bean1.setFoodKey(101); bean1.setItemName("Idly"); bean1.setItemPrice(5.00); bean1.setCourseFlag(1); MenuBean bean2 = new MenuBean(); bean2.setFoodKey(102); bean2.setItemName("Dosa"); bean2.setItemPrice(5.00); bean2.setCourseFlag(1); MenuBean bean3 = new MenuBean(); bean3.setFoodKey(103); bean3.setItemName("Poori"); bean3.setItemPrice(5.00); bean3.setCourseFlag(1); MenuBean bean4 = new MenuBean(); bean4.setFoodKey(104); bean4.setItemName("Chappathi"); bean4.setItemPrice(5.00); bean4.setCourseFlag(1); MenuBean bean5 = new MenuBean(); bean5.setFoodKey(105); bean5.setItemName("Pongal"); bean5.setItemPrice(5.00); bean5.setCourseFlag(1); listMenuBean.add(bean1); listMenuBean.add(bean2); listMenuBean.add(bean3); listMenuBean.add(bean4); listMenuBean.add(bean5); SharedPreferences prefs = getSharedPreferences("MenuData", 0); SharedPreferences.Editor editor = prefs.edit(); editor.clear(); Gson json = new Gson(); editor.putString("list1", json.toJson(listMenuBean)); editor.commit(); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager() .findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); if (position == 0) { fragmentManager.beginTransaction() .replace(R.id.container, HomeFragment.newInstance()) .commit(); } else if (position == 1) { Intent i = new Intent(NavigationDrawer.this, MyAccount.class); startActivity(i); /*fragmentManager.beginTransaction() .replace(R.id.container, MailFragment.newInstance()) .commit();*/ } else if (position == 2) { Intent i = new Intent(NavigationDrawer.this, MyAddress.class); startActivity(i); /*fragmentManager.beginTransaction() .replace(R.id.container, SettingsFragment.newInstance()) .commit();*/ } else if (position == 5) { SharedPreferences prefs = getSharedPreferences("UserData", 0); SharedPreferences.Editor editor = prefs.edit(); editor.clear(); editor.commit(); Intent i = new Intent(NavigationDrawer.this, Login.class); startActivity(i); /*fragmentManager.beginTransaction() .replace(R.id.container, SettingsFragment.newInstance()) .commit();*/ } } //Get the title of current fragment public void onSectionAttached(int number) { System.out.println(mTitle); switch (number) { case 1: mTitle = "Home"; break; case 2: mTitle = "My Account"; break; case 3: mTitle = "Contact Us"; break; } } //Change the title of page to current fragments title public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); actionBar.setHomeAsUpIndicator(R.drawable.img_drawer); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.menu, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void myMethod(View view) { Intent intent=new Intent(); /*switch(view.getId()) { case R.id.plan1btn: intent=new Intent(NavigationDrawer.this,Plan1.class); //startActivity(intent); startActivity(intent.putExtra("from", "plan1btn")); break; case R.id.plan2btn: intent=new Intent(NavigationDrawer.this,Plan1.class); //startActivity(intent); startActivity(intent.putExtra("from", "plan2btn")); break; case R.id.plan5btn: intent=new Intent(NavigationDrawer.this,Plan1.class); //startActivity(intent); startActivity(intent.putExtra("from", "plan5btn")); break; case R.id.plan7btn: intent=new Intent(NavigationDrawer.this,Plan1.class); //startActivity(intent); startActivity(intent.putExtra("from", "plan7btn")); break; default:*/ intent=new Intent(view.getContext(),Plan1.class); //startActivity(intent); startActivity(intent); //break; } }
/* * Copyright 2014. AppDynamics LLC and its affiliates. * All Rights Reserved. * This is unpublished proprietary source code of AppDynamics LLC and its affiliates. * The copyright notice above does not evidence any actual or intended publication of such source code. */ package com.appdynamics.monitors.iPlanet.beans; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; @XStreamAlias("thread-pool") public class ThreadPool { @XStreamAsAttribute() private String id; @XStreamAsAttribute() private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package kr.ac.kopo.day17; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; public class FileMain { public static void main(String[] args) { File fileObj = new File("iodata/a.txt"); String name = fileObj.getName(); String parent = fileObj.getParent(); String path = fileObj.getPath(); String abPath = fileObj.getAbsolutePath(); System.out.println("파일명 : " + name); System.out.println("부모이름 : " + parent); System.out.println("경로 : " + path); System.out.println("절대경로 : " + abPath); boolean bool = fileObj.isFile(); System.out.println(bool ? "파일 입니다." : "파일 아닙니다."); bool = fileObj.isDirectory(); System.out.println(bool ? "디렉토리 입니다." : "디렉토리 아닙니다."); bool = fileObj.exists(); System.out.println(bool ? "존재함" : "존재 ㄴ"); long size = fileObj.length(); System.out.println("파일크기:" + size + "byte(s)"); long time = fileObj.lastModified(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 55초"); System.out.println(sdf.format(new Date(time))); bool = fileObj.canWrite(); System.out.println(bool ? "쓰기 가능" : "불능"); bool = fileObj.canRead(); System.out.println(bool ? "읽기 가능" : "불능"); System.out.println("-------------------------------------------"); File dirObj = new File("iodata"); System.out.println(dirObj.exists()); System.out.println(dirObj.isDirectory()); String[] list = dirObj.list(); for (String nam2 : list) { System.out.println(nam2); } //폴더 생성 //mkdir // 새새폴더 밑에 오리 폴더. //mkdirs 상위폴더가 없으면 그거도 만들어준다. } }
package com.gxtc.huchuan.ui.circle.findCircle; import com.gxtc.commlibrary.BaseListPresenter; import com.gxtc.commlibrary.BaseListUiView; import com.gxtc.commlibrary.BasePresenter; import com.gxtc.commlibrary.BaseUiView; import com.gxtc.huchuan.bean.CircleBean; import java.util.List; /** * 来自 伍玉南 的装逼小尾巴 on 17/5/5. */ public interface CircleListContract { interface View extends BaseUiView<CircleListContract.Presenter>,BaseListUiView<CircleBean>{ void showData(List<CircleBean> datas); void showListType(List<CircleBean> datas); } interface Presenter extends BasePresenter,BaseListPresenter{ void getData(String k,String isfree,String orderType,Integer typeId); void getListType(); } }
package com.rev.dao.spring; import com.rev.dao.GenericRepository; import org.apache.log4j.Logger; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; /** * @author Trevor * @param <T> What model do we expect to return from this */ @Repository @Transactional public abstract class SpringRepository<T> implements GenericRepository<T> { protected final static Logger log = Logger.getLogger(SpringRepository.class.getName()); public SessionFactory sessionFactory; //horrible, no good, bad code using reflections, this wont work if T doesn't have a super class but were working on a DAO so..... private Class<T> getType(){ return ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); } @Autowired public SpringRepository(SessionFactory sf){ sessionFactory = sf; } @Transactional(isolation = Isolation.READ_COMMITTED) @Override public Serializable save(T t) { Session session = sessionFactory.getCurrentSession(); return session.save(t); } @Transactional(isolation = Isolation.READ_COMMITTED, readOnly=true) @Override public List<T> findAll() { Session session = sessionFactory.getCurrentSession(); return session.createCriteria(getType()).list(); } @Transactional(isolation = Isolation.READ_COMMITTED, readOnly=true) @Override public T findById(Serializable id) { try { Session session = sessionFactory.getCurrentSession(); return (T)session.get(getType(), id); } catch (Exception e){ log.error("Find call failed at id: " + id, e); } return null; } @Transactional(isolation = Isolation.READ_COMMITTED) @Override public boolean update(T t) { try { Session session = sessionFactory.getCurrentSession(); session.update(t); return true; } catch (Exception e){ log.error("Update call failed for: " + t.toString(), e); } return false; } @Transactional(isolation = Isolation.READ_COMMITTED) @Override public boolean deleteById(Serializable id) { try { Session session = sessionFactory.getCurrentSession(); session.delete(session.get(getType(), id)); //cant call findById() bc you cant have 2 uncommited sessions i think return true; } catch (Exception e){ log.error("Delete call failed at id: " + id, e); } return false; } }
package chatClient; import chatClient.videoUI.VideoCallReceiver; import chatClient.videoUI.VideoCallServer; import chatServer.ServerWorker; import dependencies.Listeners.LoginListener; import dependencies.Listeners.MessageListener; import dependencies.lib.Config; import dependencies.lib.UserBean; import des.KeyGenerator; import des.RSA; import java.io.*; import java.math.BigInteger; import java.net.InetAddress; import java.net.Socket; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class ChatClient { static Map<String, KeySheet> keys = new HashMap<>(); VideoCallServer vcServer; VideoCallReceiver vcReceiver; RSA rsa; private KeyGenerator keyGenerator = new KeyGenerator(); private ArrayList<MessageListener> messageListeners = new ArrayList<>(); private LoginListener listener; private String serverName; private int serverPort; private Socket serverSocket; private InputStream serverIn; private OutputStream serverOut; public ChatClient(String serverName, int serverPort) { this.serverName = serverName; this.serverPort = serverPort; if (connect()) { new Thread(() -> { try { listenServer(); } catch (IOException e) { System.err.println("ChatClient : Server Disconnected!"); e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } else { System.err.println("ChatClient : Connection Failed!"); } } public static BigInteger getKeys(String username) { if (keys.containsKey(username)) { return keys.get(username).getDh_key(); } else { System.err.println("ChatClient : Key not created yet!"); return new BigInteger("0"); } } public void setLoginListener(LoginListener listener) { this.listener = listener; } public void setRsa(RSA rsa) { this.rsa = rsa; } public void login(UserBean bean) throws IOException { send("login " + bean.getUserHandle() + " " + bean.getPassword()); } private void listenServer() throws IOException, SQLException, ClassNotFoundException, InterruptedException { String line; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(serverIn)); while ((line = bufferedReader.readLine()) != null) { // System.out.println("Chat CLient : " + line); String[] tokens = line.split(" "); if (tokens[0].equalsIgnoreCase("online")) { System.out.println(line); handleOnlineCommand(tokens); } else if (tokens[0].equalsIgnoreCase("offline")) { System.out.println(line); handleOfflineCommand(tokens[1]); } else if (tokens[0].equalsIgnoreCase("message")) { handleMessageCommand(line); } else if (tokens[0].equalsIgnoreCase("login")) { handleLoginCommand(line); } else if (tokens[0].equalsIgnoreCase("key")) { handleKeyCommand(tokens); } else if (tokens[0].equalsIgnoreCase("video")) { handleVideoCommand(tokens); } } } private void handleVideoCommand(String[] tokens) throws IOException, InterruptedException { /** * if command = video init receiver_url * start videoCallServer destined at receiver_url port 42070 * else if command = video start * start videoCallReceiver at port 420 */ if (tokens[1].equalsIgnoreCase("init")) { InetAddress ip = InetAddress.getByName(tokens[2]); vcServer = new VideoCallServer(ip, Config.VIDEO_CALLER_PORT); } else if (tokens[1].equalsIgnoreCase("start")) { vcReceiver = new VideoCallReceiver(Config.VIDEO_CALLER_PORT, tokens[2]) {{ addAcceptListener(ChatClientMain.localhost); addRejectListener(ChatClientMain.localhost); }}; } else if (tokens[1].equalsIgnoreCase("accept")) { InetAddress ip = InetAddress.getByName(tokens[2]); System.out.println(ip.getHostAddress()); vcServer = new VideoCallServer(ip, Config.VIDEO_RECEIVER_PORT); vcReceiver.setServer(vcServer); } else if (tokens[1].equalsIgnoreCase("accepted")) { vcReceiver = new VideoCallReceiver(Config.VIDEO_RECEIVER_PORT, tokens[2]) {{ addAcceptListener(ChatClientMain.localhost); addRejectListener(ChatClientMain.localhost); setServer(vcServer); }}; } else if (tokens[1].equalsIgnoreCase("end")) { vcServer.stopSending(); vcReceiver.stopReceiving(); } } private void handleKeyCommand(String[] tokens) throws IOException { //key @userhandle init rsa_public_variable //key @userhandle exchange dh_key signature if (tokens.length >= 4) { String userHandle = tokens[1]; if (tokens[2].equalsIgnoreCase("init")) { BigInteger rsa_public_variable = new BigInteger(tokens[3], 16); if (!keys.containsKey(userHandle)) { keys.put(userHandle, new KeySheet(rsa_public_variable)); String Ka = keyGenerator.initializeDHKeyExchange(); String sign = rsa.sign(new BigInteger(Ka, 16), keys.get(userHandle).getRsa_public_variable()); // System.out.println("ChatClient : sign = " + sign); String keyCommand = "key " + userHandle + " exchange " + sign; // System.out.println("Signed key sent : " + keyCommand); send(keyCommand); } } else if (tokens[2].equalsIgnoreCase("exchange")) { BigInteger public_variable = rsa.verify(tokens[3] + " " + tokens[4], keys.get(userHandle).getRsa_public_variable()); //public variables sent and received are same //send signed key and received signed key are also same if (public_variable != null) { keyGenerator.receive(public_variable.toString(16)); System.out.println(keyGenerator.getKey()); keys.get(userHandle).setDh_key(keyGenerator.getKey()); } else { System.err.println("ChatClient : Failed to exchange symmetric keys."); } // KeySheet keySheet = keys.get(userHandle); // keySheet.setDh_key(keyGenerator.getKey()); // keys.put(userHandle, keySheet); } } } private void handleLoginCommand(String line) { System.out.println(line); String[] split = line.split(":"); if (split[0].equalsIgnoreCase(ServerWorker.LOGIN_SUCCESS)) { listener.onChatServerLogin(new UserBean() {{ setUserHandle(split[1]); }}); } } private void handleMessageCommand(String line) { String[] tokens = line.split(" ", 3); if (tokens.length == 3) { if (tokens[1].equalsIgnoreCase("sent")) { if (tokens[2].equalsIgnoreCase("success")) { //update view only message sent success is received for (MessageListener messageListener : messageListeners) { messageListener.onSend(); } } } else { String from = tokens[1]; String message = tokens[2]; for (MessageListener messageListener : messageListeners) { // System.out.println("Chat Client : Notifying Observers"); messageListener.onMessage(from, message); } } } } private void handleOnlineCommand(String[] tokens) throws IOException { if (tokens.length == 2) { String[] split = tokens[1].split("~"); String keyCommand = "key " + split[0] + " init " + rsa.getPublic_variable().toString(16); send(keyCommand); // System.out.println("Chat Client : " + keyCommand); for (MessageListener messageListener : messageListeners) { messageListener.online(new UserBean() {{ setUserHandle(split[0]); setFirstName(split[1]); setLastName(split[2]); }}); } } } private void handleOfflineCommand(String line) throws SQLException, ClassNotFoundException { String[] split = line.split("~"); if (split.length == 3) { keys.remove(split[0]); for (MessageListener messageListener : messageListeners) { messageListener.offline(new UserBean() {{ setUserHandle(split[0]); setFirstName(split[1]); setLastName(split[2]); }}); } } } public void send(String message) throws IOException { serverOut.write((message + "\n").getBytes()); } public boolean connect() { try { this.serverSocket = new Socket(this.serverName, this.serverPort); this.serverIn = serverSocket.getInputStream(); this.serverOut = serverSocket.getOutputStream(); return true; } catch (Exception e) { System.err.println("Server Down!"); e.printStackTrace(); } return false; } public void addMessageListener(MessageListener listener) { messageListeners.add(listener); } public void register(UserBean bean) throws IOException { send("register " + bean.getFirstName() + "~" + bean.getLastName() + "~" + bean.getUserHandle() + "~" + bean.getPassword()); } }
package com.example.noteit.DAO; import android.content.Context; import com.example.noteit.Note; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; @Database(entities = {Note.class},version = 1) // adding schema dependency helps to create a json database file public abstract class NoteDatabase extends RoomDatabase { public static final String DATABASE_NAME="notes_db"; private static NoteDatabase instance; static NoteDatabase getInstance(final Context context){ if(instance==null) { instance= Room.databaseBuilder(context.getApplicationContext(),NoteDatabase.class,DATABASE_NAME).build(); } return instance; } public abstract NoteDao getNoteDao(); }
package p05; import java.util.Scanner; public class ArrayExam2 { public static void main(String[]args) { Scanner s=new Scanner(System.in); int x=s.nextInt(); int y=s.nextInt(); for(int i=1;i<=x;i++) { for(int j=1;j<=y;j++) { System.out.print(i+" * "+j+" = "+(i*j)+"||"); /*if(j<y) { System.out.print(", "); }*/ }System.out.println(); } } }
package logHandling; import java.util.List; public class PRElement { public final long id; public List<Long> physicalNodes; public final String type; public PRElement(long id, String type) { this.id = id; this.type = type; } public String getTypeId(){ return type+id; } public void setPhysicalNode(List<Long> nodes) { this.physicalNodes = nodes; } }
import java.util.ArrayList; public class Hospital { // Atributos private ArrayList<Paciente> listaPacientes = new ArrayList<Paciente>(); private ArrayList<Medico> listaMedicos = new ArrayList<Medico>(); private ArrayList<Enfermeiro> listaEnfermeiros = new ArrayList<Enfermeiro>(); private ContaJuridica contaJ; private Medico medicoPaciente; private String nomeMedicoAux; // Construtores // Métodos Get & Set public ArrayList<Paciente> getListaPacientes() { return listaPacientes; } public void setListaPacientes(ArrayList<Paciente> listaPacientes) { this.listaPacientes = listaPacientes; } public ArrayList<Medico> getListaMedicos() { return listaMedicos; } public void setListaMedicos(ArrayList<Medico> listaMedicos) { this.listaMedicos = listaMedicos; } public ArrayList<Enfermeiro> getListaEnfermeiros() { return listaEnfermeiros; } public void setListaEnfermeiros(ArrayList<Enfermeiro> listaEnfermeiros) { this.listaEnfermeiros = listaEnfermeiros; } public ContaJuridica getContaJ() { return contaJ; } public void setContaJ(ContaJuridica contaJ) { this.contaJ = contaJ; } public Medico getMedicoPaciente() { // Precisa de get e set para medicoPaciente? return medicoPaciente; } public void setMedicoPaciente(Medico medicoPaciente) { this.medicoPaciente = medicoPaciente; } /* Métodos - consultar todos os pacientes de um médico a partir do nome do médico * Hospital --> Paciente --> Médico **/ public void buscarPacientes(String nomeMedico){ ArrayList<Paciente> listaPacientes2 = new ArrayList<Paciente>(); for(Paciente i: listaPacientes) { medicoPaciente = i.getMedico(); nomeMedicoAux = medicoPaciente.getNome(); if(nomeMedicoAux.equals(nomeMedico)) { listaPacientes2.add(i); } } System.out.println("Lista de pacientes de " + nomeMedico); if (listaPacientes2.size()==0) { System.out.println("Médico não encontrado!"); } else { for(Paciente i:listaPacientes2) { System.out.println(i.getNome()); } } } }
package testing; import static org.junit.Assert.*; import org.junit.Test; import obj.Action; public class ActionTest extends GenericTest { public Action action = new Action(10, "Boil", "Heat liquid at a medium temperature until it begins to bubble"); @Test public void testConstructor() { assertEquals(10, action.getID()); assertEquals("Boil", action.getName()); assertEquals("Heat liquid at a medium temperature until it begins to bubble", action.getDescription()); assertEquals(false, action.getChanges()); } @Test public void testIDChange(){ action.setID(15); assertEquals(15, action.getID()); testChanges(action); } @Test public void testNameChange(){ action.setName("Something else"); assertEquals("Something else", action.getName()); testChanges(action); } @Test public void testDescriptionChange(){ action.setDescription("New Description"); assertEquals("New Description", action.getDescription()); testChanges(action); } }
package com.novakivska.app.homework.homework3; import com.novakivska.app.homework.homework3.TrainingMethods; import org.junit.Assert; import org.junit.Test; /** * Created by Tas_ka on 3/16/2017. */ public class TrainingMethodsTest { int a = 30; int b = 30; TrainingMethods method = new TrainingMethods(); @Test public void devision() { int actualResult = method.divide(a, b); int expectedResult = 1; Assert.assertEquals(expectedResult, actualResult); } @Test public void modullo(){ int actualResult = method.modullo(a, b); int expectedResult = 0; Assert.assertEquals(expectedResult, actualResult); } @Test public void reverse(){ String actualResult = method.reverse("test"); String expectedResult = "tset"; Assert.assertEquals(actualResult, expectedResult); } }
package com.lesports.albatross.adapter.community; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import com.facebook.drawee.view.SimpleDraweeView; import com.lesports.albatross.R; import com.lesports.albatross.activity.PhotoActivity; import com.lesports.albatross.activity.PublishActivity; import com.lesports.albatross.utils.image.ImageLoader; import com.lesports.albatross.utils.image.ImageLoaderUtil; import java.io.File; import java.util.ArrayList; /** * 发表动态,图片adapter * Created by jiangjianxiong on 16/6/15. */ public class PublishPhotoAdapter extends BaseAdapter { private static final int TYPE_ADD = 0;//+号 private static final int TYPE_NORMAL = 1;//正常图片 private Context mContext; private LayoutInflater inflater; private ArrayList<String> mList = new ArrayList<>(); private boolean isFull = Boolean.FALSE; public PublishPhotoAdapter(Context ctx, ArrayList<String> list) { this.inflater = LayoutInflater.from(ctx); this.mContext = ctx; this.mList = list; if (mList.size() == 9) { isFull = true; } } @Override public int getCount() {//判断长度(加号) if (mList != null && !mList.isEmpty()) { if (mList.size() != 9) { return mList.size() + 1; } else { isFull = true; return 9; } } else { return 1; } } @Override public String getItem(int position) { if (null != mList && !mList.isEmpty()) { if (mList.size() != 9) { if (position != getCount() - 1) { return mList.get(position); } else { return "add"; } } else { return mList.get(position); } } else { return "add"; } } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) {//判断类型(图片or加号) if (getCount() != 1) { if (!isFull) { if (position != getCount() - 1) { return TYPE_NORMAL; } else { return TYPE_ADD; } } else { return TYPE_NORMAL; } } else { return TYPE_ADD; } } @Override public View getView(final int position, View convertView, ViewGroup parent) { switch (getItemViewType(position)) { case TYPE_NORMAL: ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.publish_photo_grid_item, parent, false); holder.image = (SimpleDraweeView) convertView.findViewById(R.id.image); holder.del = (ImageView) convertView.findViewById(R.id.del); holder.image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, PhotoActivity.class); intent.putExtra("position", position); intent.putExtra("isLocal", true); intent.putStringArrayListExtra("data", mList); ((PublishActivity) mContext).startActivityForResult(intent, PublishActivity.REQUEST_IMAGE); } }); holder.del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((PublishActivity) mContext).deleteSinglePhoto(position); } }); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } File imageFile = new File(getItem(position)); if (imageFile.exists() && null != holder) { ImageLoaderUtil.getInstance().loadImage(mContext, new ImageLoader.Builder() .path(getItem(position)).widthAndHeight(200).placeHolder(R.mipmap.default_image_bg) .mImageView(holder.image).build()); } return convertView; case TYPE_ADD: View view_add = inflater.inflate(R.layout.publish_photo_add_grid_item, parent, false); ImageView image = (ImageView) view_add.findViewById(R.id.image); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((PublishActivity) mContext).pickPhoto(); } }); return view_add; } return convertView; } private class ViewHolder { SimpleDraweeView image; ImageView del; } }
package fri1; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/TemperaturServlet") public class TemperaturServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { double userInput; String userInputFormat, convertedOutput = null; PrintWriter out = response.getWriter(); String converterType = request.getParameter("converter"); DecimalFormat formatter = new DecimalFormat("#0.0"); out.println(HTMLhead()); try { userInput = Double.parseDouble(request.getParameter("num")); userInputFormat = formatter.format(userInput); if (converterType.equals("f2c") && isValidNumber(userInput, converterType)) { convertedOutput = formatter.format((userInput - 32) * 5 / 9) + "°C"; userInputFormat += "°F"; } else if (converterType.equals("c2f") && isValidNumber(userInput, converterType)) { convertedOutput = formatter.format((userInput * 9 / 5) + 32) + "°F"; userInputFormat += "°C"; }else { Double.parseDouble("send to catch"); //dette er en cheeky løsning } out.println("<p>Temperaturomregning resultat</p>"); out.println("<p>" + userInputFormat + "=" + convertedOutput + "</p>"); } catch (NumberFormatException e) { out.println( "<p>Ugyldig brukerinput. " + "Temperaturen må være et tall (lik eller over det absoulutte nullpunkt</p>"); } out.println(HTMLlegs()); } private boolean isValidNumber(double inn, String parameter) { if(parameter.equals("f2c")&&inn>=-459.67) {return true;} else {return parameter.equals("c2f")&&inn>=-273.15;} } private String HTMLhead() { return "<!DOCTYPE html>" +"<html>" +"<head>"+"<meta charset=\"ISO-8859-1\">" +"<title>Kvittering</title>" +"</head>" +"<body>"; } private String HTMLlegs() { return "<a href=\"http://localhost:8080/friopgpreoblig3/temp.html\">gå tilbake</a>" +"</body>" +"</html>"; } }
package projectImplementation; import java.time.LocalDate; import java.time.LocalTime; public class MiniStatement { String transcationType; int transactionAmount; LocalTime transactionTime; double balance; LocalDate transactionDate; public MiniStatement(String transactionType, int transactionAmount, LocalTime Time, LocalDate Date, double balance) { this.transcationType = transactionType; this.transactionAmount = transactionAmount; this.transactionDate = Date; this.transactionTime = Time; this.balance= balance; } }