text stringlengths 10 2.72M |
|---|
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
@Entity
public class Reference extends Model {
/**
*
*/
private static final long serialVersionUID = -2822969871869514078L;
@Id
public String id;
public String references;
}
|
package symap.contig;
import symap.marker.Marker;
import symap.marker.MarkerData;
import symap.marker.MarkerTrack;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Vector;
import java.util.Iterator;
import java.util.Map;
import number.GenomicsNumber;
public class MarkerCloneData extends MarkerData {
private String[] cloneNames;
public MarkerCloneData(String name, String type, long pos, Collection<String> cloneNames) {
super(name,type,pos);
if (cloneNames == null) this.cloneNames = new String[0];
else {
this.cloneNames = new String[cloneNames.size()];
Iterator<String> iter = cloneNames.iterator();
for (int i = 0; i < this.cloneNames.length; i++)
this.cloneNames[i] = (iter.next());//.intern(); // mdb removed intern() 2/2/10 - can cause memory leaks in this case
}
}
public MarkerCloneData(MarkerData md, Collection<String> cloneNames) {
this(md.getName(),md.getType(),md.getPosition(),cloneNames);
}
/**
* Method <code>getMarker</code>
*
* @param track a <code>MarkerTrack</code> value
* @param condFilters a <code>Vector</code> value
* @param clones a <code>Map</code> value a map with the key being the clone name and the value being a Clone object
* @return a <code>Marker</code> value
*/
public Marker getMarker(MarkerTrack track, Vector<Object> condFilters, Map<String,Clone> clones) {
List<Clone> mclones = new ArrayList<Clone>(cloneNames.length);
if (clones != null) {
for (int i = 0; i < cloneNames.length; i++)
mclones.add(clones.get(cloneNames[i]));
}
return new Marker(track,condFilters,getName(),getType(),new GenomicsNumber(track,getPosition()),mclones);
}
}
|
package com.example.springaop.myaop;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MikeApplicationContext implements ApplicationContext {
// 支持高并发
private Map<String, Class<?>> beanDefinitionMap = new ConcurrentHashMap<>(256);
// 可以有多个切面,这里用一个来代替模拟
private Aspect aspect;
@Override
public Object getBean(String beanName) throws Throwable{
// 怎么创建bean对象 用户给出
// 用户给出bean配置 BeanDefinition
Object bean = createBeanInstance(beanName);
//这里需要返回加工后的代理
bean = proxyEnhance(bean);
return bean;
}
private Object proxyEnhance(Object bean) {
// 判断是否要增强切面
if(this.aspect != null && bean.getClass().getName().matches(this.aspect.getPointcut().getClassPattern())){
return Proxy.newProxyInstance(bean.getClass().getClassLoader(),bean.getClass().getInterfaces(), new AopInvocationHandler(this.aspect,bean));
}
return bean;
}
private Object createBeanInstance(String beanName) throws Throwable{
return this.beanDefinitionMap.get(beanName).newInstance();
}
@Override
public void registerBeanDefinition(String beanName, Class<?> beanClass) {
// 保存下来
this.beanDefinitionMap.put(beanName, beanClass);
}
@Override
public void setAspect(Aspect aspect) {
this.aspect = aspect;
}
}
|
package com.jecarm.rpc.server;
/**
* Created by loagosad on 2018/8/19.
*/
public class HelloRpcServiceImpl implements HelloRpcService {
@Override
public String sayHello(String name) {
return "hello "+name+", this is a simple RPC service";
}
}
|
package com.project.springboot.entity;
import java.io.Serializable;
import javax.persistence.Column;
public class EmbededInvoiceBill implements Serializable{
@Column(name = "product_id",nullable = false)
private Integer productId;
@Column(name = "service_id",nullable = false)
private Integer serviceId;
@Column(name="bill_id",nullable = false)
private Integer billId;
public EmbededInvoiceBill() {}
public EmbededInvoiceBill(Integer productId, Integer serviceId, Integer billId) {
super();
this.productId = productId;
this.serviceId = serviceId;
this.billId = billId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getServiceId() {
return serviceId;
}
public void setServiceId(Integer serviceId) {
this.serviceId = serviceId;
}
public Integer getBillId() {
return billId;
}
public void setBillId(Integer billId) {
this.billId = billId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((billId == null) ? 0 : billId.hashCode());
result = prime * result + ((productId == null) ? 0 : productId.hashCode());
result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EmbededInvoiceBill other = (EmbededInvoiceBill) obj;
if (billId == null) {
if (other.billId != null)
return false;
} else if (!billId.equals(other.billId))
return false;
if (productId == null) {
if (other.productId != null)
return false;
} else if (!productId.equals(other.productId))
return false;
if (serviceId == null) {
if (other.serviceId != null)
return false;
} else if (!serviceId.equals(other.serviceId))
return false;
return true;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.services;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.datacrow.core.DcRepository;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.services.plugin.IServer;
import net.datacrow.fileimporters.FileImporter;
import net.datacrow.util.StringUtils;
import org.apache.log4j.Logger;
/**
* Simple online search which can run completely in the background.
* It has implemented the {@link IOnlineSearchClient} interface. This class can
* be used by other processes which want to enable online search (such as the {@link FileImporter})
*
* @author Robert Jan van der Waals
*/
public class OnlineSearchHelper implements IOnlineSearchClient {
private static Logger logger = Logger.getLogger(OnlineSearchHelper.class.getName());
private final int module;
private SearchTask task;
private int maximum = 2;
private IServer server;
private Region region;
private SearchMode mode;
private int itemMode;
private Collection<DcObject> result = new ArrayList<DcObject>();
/**
* Creates a new instance.
* @param module The module index
* @param itemMode {@link SearchTask#_ITEM_MODE_FULL} or {@link SearchTask#_ITEM_MODE_SIMPLE}
*/
public OnlineSearchHelper(int module, int itemMode) {
this.module = module;
this.itemMode = itemMode;
}
/**
* The server to be used.
* @param server
*/
public void setServer(IServer server) {
this.server = server;
}
/**
* The region to be used.
* @param region
*/
public void setRegion(Region region) {
this.region = region;
}
/**
* The search mode to be used.
* @param mode
*/
public void setMode(SearchMode mode) {
this.mode = mode;
}
/**
* The maximum search result.
* @param maximum
*/
public void setMaximum(int maximum) {
this.maximum = maximum;
}
/**
* Queries for new information for the supplied item.
* Uses the services URL as stored in the item (see {@link DcObject#_SYS_SERVICEURL}).
* @param item
* @return The supplied item. Either updated or not.
*/
public DcObject query(DcObject item) {
IServer server = getServer();
Region region = getRegion(server);
task = server.getSearchTask(this, getSearchMode(server), region, null, item);
task.setItemMode(SearchTask._ITEM_MODE_FULL);
try {
return task.getItem(new URL((String) item.getValue(DcObject._SYS_SERVICEURL)));
} catch (Exception e) {
logger.error(e, e);
return item;
}
}
/**
* Queries for items and checks if they are similar to the supplied item
* the item most similar to the base item will be returned. Similarity is based
* on the values of the provided field indices.
* @param base The item to check the results against.
* @param query The query to base the search on.
* @param matcherFieldIdx The field indices used to check for similarity.
* @return The most similar result or null.
*/
public DcObject query(DcObject base, String query, int[] matcherFieldIdx) {
IServer server = getServer();
Region region = getRegion(server);
task = server.getSearchTask(this, getSearchMode(server), region, query, base);
task.setItemMode(itemMode);
task.setMaximum(maximum);
task.run();
return getMatchingItem(base, matcherFieldIdx);
}
/**
* Searches for items based on the provided query string.
* @param query
* @return Collection of results.
*/
public List<DcObject> query(String query, DcObject client) {
IServer server = getServer();
Region region = getRegion(server);
task = server.getSearchTask(this, getSearchMode(server), region, query, client);
task.setItemMode(itemMode);
task.setMaximum(maximum);
task.run();
return new ArrayList<DcObject>(result);
}
/**
* Retrieves the server to be used. If no server has yet been set the default server
* will be used. If no default server is available it will be selected at random.
* @return The server to be used.
*/
private IServer getServer() {
OnlineServices os = DcModules.get(module).getOnlineServices();
IServer defaultSrv =
os.getServer(DcModules.get(module).getSettings().getString(DcRepository.ModuleSettings.stOnlineSearchDefaultServer));
IServer server = this.server != null ? this.server : defaultSrv;
return server == null ? (IServer) os.getServers().toArray()[0] : server;
}
/**
* Retrieves the region to be used. In case a region has already been specified this
* region will be used only when the region is part of the provided server.
* If not, the default region will be used. If no default region is available it will be selected
* at random or be left empty if the server simply doesn't have any regions.
* @param server The server for which a region is being retrieved.
* @return The region to be used or null.
*/
private Region getRegion(IServer server) {
OnlineServices os = DcModules.get(module).getOnlineServices();
Region region = this.region != null ? this.region : os.getDefaultRegion();
if (region != null) {
boolean partOfServer = false;
for (Region serverRegion : server.getRegions()) {
if (serverRegion.getCode().equals(region.getCode())) {
region = serverRegion;
partOfServer = true;
}
}
if (!partOfServer) region = null;
}
return region == null && server.getRegions().size() > 0 ? (Region) server.getRegions().toArray()[0] : region;
}
/**
* Retrieves the search mode to be used. In case a mode has already been specified this
* mode will be used only when the mode is part of the provided server.
* If not, the default mode will be used. If no default mode is available it will be selected
* at random or be left empty if the server simply doesn't support search modes.
* @param server The server for which a search mode is being retrieved.
* @return The search mode to be used or null.
*/
private SearchMode getSearchMode(IServer server) {
OnlineServices os = DcModules.get(module).getOnlineServices();
SearchMode mode = this.mode == null ? os.getDefaultSearchMode() : this.mode;
if (server.getSearchModes() == null)
return null;
if (mode != null) {
boolean partOfServer = false;
for (SearchMode serverMode : server.getSearchModes()) {
if (serverMode.getDisplayName().equals(mode.getDisplayName())) {
mode = serverMode;
partOfServer = true;
}
}
if (!partOfServer) mode = null;
}
if (mode == null && server.getSearchModes() != null) {
for (SearchMode serverMode : server.getSearchModes())
mode = serverMode.keywordSearch() ? serverMode : mode;
}
return mode;
}
/**
* Retrieves the matching result. Each of the results is checked against the provided
* base item. The match field indices indicate which values are to be checked.
* @param base The item to check against.
* @param matcherFieldIdx The field indices to use for checking for similarities.
* @return A matching result or null.
*/
private DcObject getMatchingItem(DcObject base, int[] matcherFieldIdx) {
for (DcObject dco : result) {
boolean match = true;
for (int i = 0; i < matcherFieldIdx.length; i++) {
Object o1 = base.getValue(matcherFieldIdx[i]);
Object o2 = dco.getValue(matcherFieldIdx[i]);
String value1 = o1 == null || o1.toString().equals("-1") ? "" : StringUtils.normalize(o1.toString().trim());
String value2 = o2 == null || o2.toString().equals("-1") ? "" : StringUtils.normalize(o2.toString().trim());
match &= value1.equals(value2);
}
if (match) return dco;
}
return null;
}
/**
* Free resources.
* @param except Do not clear the resources of this item.
*/
public void clear() {
task = null;
server = null;
region = null;
result.clear();
result = null;
}
@Override
public void addError(Throwable t) {
logger.error(t, t);
}
@Override
public void addError(String message) {
logger.error(message);
}
@Override
public void addMessage(String message) {}
@Override
public void addObject(DcObject dco) {
if (result != null) {
result.add(dco);
if (isPerfectMatch(dco))
task.cancel();
}
}
private boolean isPerfectMatch(DcObject dco) {
String string = StringUtils.normalize(task.getQuery()).toLowerCase();
String item = StringUtils.normalize(dco.toString()).toLowerCase();
return string.equals(item);
}
@Override
public void addWarning(String warning) {}
public DcObject getDcObject() {
return null;
}
@Override
public DcModule getModule() {
return DcModules.get(module);
}
@Override
public void processed(int i) {}
@Override
public void processing() {}
@Override
public void processingTotal(int i) {}
@Override
public int resultCount() {
return result.size();
}
@Override
public void stopped() {}
}
|
package exercises.chapter3.ex1;
import static net.mindview.util.Print.*;
/**
* @author Volodymyr Portianko
* @date.created 02.03.2016
*/
public class Exercise1 {
public static void main(String[] args) {
System.out.println("First line");
print("Second line");
}
}
|
package com.god.gl.vaccination.base;
import android.content.Context;
import com.zhy.adapter.recyclerview.CommonRecyclerRecyclerAdapter;
import java.util.List;
/**
* @author gl
* @date 2018/5/22
* @desc adapter基类
*/
public abstract class AdapterBase<T> extends CommonRecyclerRecyclerAdapter<T> {
protected List<T> list;
protected Context mContext;
public AdapterBase(Context context, int layoutId, List<T> datas) {
super(context, layoutId, datas);
this.list=datas;
this.mContext = context;
}
public void refresh(List<T> data) {
if (data != null) {
if (data.size() > 0) {
if (list==data) { // 两个list 是同一个
notifyDataSetChanged();
return;
} else {
list.clear();
list.addAll(data);
}
} else {
list.clear();
}
} else {
list.clear();
}
notifyDataSetChanged();
}
/**
* 清理List集合
*/
public void clean() {
list.clear();
notifyDataSetChanged();
}
/**
* 添加集合
*
* @param list
*/
public void addAll(List<T> list) {
if (list != null) {
if (list.size() > 0) {
if (this.list.equals(list)) { // 两个list 是同一个
notifyDataSetChanged();
return;
} else {
this.list.addAll(list);
}
}
notifyDataSetChanged();
}
}
/**
* 添加集合到指定位置
*
* @param list
* @param position
*/
public void addAll(List<T> list, int position) {
this.list.addAll(position, list);
notifyDataSetChanged();
}
/**
* 返回List集合
*
* @return
*/
public List<T> getList() {
return list;
}
}
|
/**
* MVC infrastructure for annotation-based handler method processing, building on the
* {@code org.springframework.web.method.annotation} package. Entry points are
* {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping}
* and {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter}.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.servlet.mvc.method.annotation;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package controllers;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Singleton;
import model.Report;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
/**
* Created by suesstnorma1 on 14.03.17.
*/
@Singleton
public class Reports extends Controller {
public CompletionStage<Result> listReports() {
// hier liste hier liste
// ------------- ---------------
//CompletionStage<List<Report>> promiseOfReport = CompletableFuture.supplyAsync(() -> loadReports());
System.out.println("Before start");
// Promise/Versprechen und Aufruf
CompletionStage<List<Report>> promiseOfReport =
CompletableFuture.supplyAsync(() -> loadReports());
System.out.println("After start");
// Das Promise wird nach Ausfuehrung (z.B. nach n Sekunden) hier eingeloest
CompletionStage<Result> promiseOfResult =
promiseOfReport.thenApply(r -> ok(Json.toJson(r)));
System.out.println("fertig");
return promiseOfResult;
}
// public CompletionStage<Result> kpiReports() {
//
// CompletionStage<Report> promiseOfKPIReport =
// CompletableFuture.supplyAsync(
// () -> intensiveKPIReport())
// ;
//
//
// CompletionStage<Result> promiseOfResult =
// promiseOfKPIReport.thenApply(
// r -> ok(Json.toJson(r)));
//
// return promiseOfResult;
// }
public static List<Report> loadReports() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Report.reportListe;
}
}
|
package projecteuler;
public class Problem019
{
public static void main(String[] args)
{
int dayCounter; //mod 7 where: 0 = sunday, 1 = monday, 2 = tuesday, 3 = wednesday, 4 = thursday, 5 = friday, 6 = saturday.
int sundaysOnFirstOfTheMonthCounter = 0;//the number of Sundays that occurred on the first of the month so far.
dayCounter = 1;//Jan 1st, 1990 was monday.
for(int year = 1900; year <= 2000; year++)
{
for(int month = 1; month <= 12; month++)
{
if(dayCounter == 0 && year != 1990)//stupid gimmick
{
sundaysOnFirstOfTheMonthCounter++;
System.out.println(month + "/1st/" + year + " was a Sunday!");
}
dayCounter = (dayCounter + numberOfDaysInMonthYear(month,year)) % 7;
}
}
System.out.println(sundaysOnFirstOfTheMonthCounter);
}
private static int numberOfDaysInMonthYear(int month, int year)
{
if(month == 2)//Feb and leap years
{
if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))//every 4 years *except* for centuries *except* for every 4 centuries
{
return 29;
}
else
{
return 28;
}
}
else if(month == 9 || month == 6 || month == 4 || month == 11)
{
return 30;
}
else
{
return 31;
}
}
}
|
package com.jiacaizichan.baselibrary.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 创建日期:2018/5/23 19:01
* @author lihao
* decs: 正则匹配工具类
*/
public class MatcherUtil {
public static final String PHONE = "^((13[0-9])|(19[0-9])|(14[0-9])|(16([0-9]))|(15([0-9]))|(17[0-9])|(18[0-9]))\\d{8}$";
public static final String PASSWORD = "^[a-zA-Z0-9]{6,12}$";
public static final String BANKCARD = "^\\d{15,19}$";
public static final String IDCARD = "^\\d{15}$|^\\d{17}[0-9Xx]$";
public static final String QQNUM = "^\\d{6,12}$";
public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
static Pattern p;
static Matcher m;
public static boolean isPhone(String value){
p = Pattern.compile(PHONE);
m = p.matcher(value);
return m.matches();
}
public static boolean isEmail(String value){
p = Pattern.compile(REGEX_EMAIL);
m = p.matcher(value);
return m.matches();
}
public static boolean isIDCard(String value) {
p = Pattern.compile(IDCARD);
m = p.matcher(value);
return m.matches();
}
public static boolean isBankCard(String value) {
p = Pattern.compile(BANKCARD);
m = p.matcher(value);
return m.matches();
}
public static boolean isPassword(String value) {
p = Pattern.compile(PASSWORD);
m = p.matcher(value);
return m.matches();
}
public static boolean isLegalName(String name){
if (name.contains("·") || name.contains("•")){
if (name.matches("^[\\u4e00-\\u9fa5]+[·•][\\u4e00-\\u9fa5]+$")){
return true;
}else {
return false;
}
}else {
if (name.matches("^[\\u4e00-\\u9fa5]+$")){
return true;
}else {
return false;
}
}
}
}
|
package com.finalyearproject.spring.web.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.finalyearproject.spring.web.dao.CommentDao;
import com.finalyearproject.spring.web.entity.Comment;
@Service("commentService")
public class CommentService {
private CommentDao commentDao;
@Autowired
public void setCommentDao(CommentDao commentDao) {
this.commentDao = commentDao;
}
public Comment getComment(int id) {
return commentDao.getComment(id);
}
public void update(Comment commentObj) {
commentDao.update(commentObj);
}
public void merge(Comment commentObj) {
commentDao.merge(commentObj);
}
public void delete(Comment commentObj){
commentDao.delete(commentObj);
}
}
|
// MutationRateModel.java
//
// (c) 1999-2001 PAL Development Core Team
//
// This package may be distributed under the
// terms of the Lesser GNU General Public License (LGPL)
package net.maizegenetics.taxa.tree;
import net.maizegenetics.util.FormattedOutput;
import net.maizegenetics.stats.math.OrthogonalHints;
import net.maizegenetics.util.Report;
import java.io.Serializable;
/**
* This abstract class contains methods that are of general use for
* modelling mutation rate changes over time.
*
* @version $Id: MutationRateModel.java,v 1.1 2007/01/12 03:26:17 tcasstevens Exp $
*
* @author Alexei Drummond
*/
public abstract class MutationRateModel implements Units,
Parameterized, Report, Cloneable, Serializable
{
//
// Private and protected stuff
//
protected FormattedOutput fo;
/**
* Units in which time units are measured.
*/
private int units;
private double maximumMutationRate_;
private static final long serialVersionUID=-1755051453782951214L;
//serialver -classpath ./classes net.maizegenetics.pal.mep.ConstantMutationRate
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
out.writeByte(1); //Version number
out.writeInt(units);
out.writeDouble(maximumMutationRate_);
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException{
byte version = in.readByte();
switch(version) {
default : {
units = in.readInt();
maximumMutationRate_ = in.readDouble();
fo = FormattedOutput.getInstance();
break;
}
}
}
protected MutationRateModel(int units, double maximumMutationRate)
{
setUnits(units,maximumMutationRate);
fo = FormattedOutput.getInstance();
}
protected MutationRateModel(MutationRateModel toCopy) {
this.units = toCopy.units;
this.maximumMutationRate_ = toCopy.maximumMutationRate_;
fo = FormattedOutput.getInstance();
}
public abstract Object clone();
//
// Because I don't like casting if I don't have to
//
public abstract MutationRateModel getCopy();
//
// functions that define a mutation rate model (left for subclass)
//
/**
* Gets the mutation rate, value of mu(t) at time t.
*/
public abstract double getMutationRate(double t);
/**
* Returns integral of mutation rate function
* (= integral mu(x) dx from 0 to t).
*/
public abstract double getExpectedSubstitutions(double t);
/**
* Return the time at which expected substitutions has occurred.
*/
public double getTime(double expectedSubs) {
return getEndTime(expectedSubs,0);
}
/**
* Return the end time at which expected substitutions has occurred, given we start at start time
*/
public abstract double getEndTime(double expectedSubs, double startTime);
/**
* Linearly scales this mutation rate model.
* @param scale getExpectedSubstitutions should return scale instead of 1.0 at time t.
*/
public abstract void scale(double scale);
// Parameterized and Report interface is also left for subclass
// general functions
/**
* Calculates the integral 1/mu(x) dx between start and finish.
*/
public double getExpectedSubstitutions(double start, double finish)
{
return getExpectedSubstitutions(finish) - getExpectedSubstitutions(start);
}
/**
* @throws IllegalArgumentException if units of this Model doenot match
* the units of the TimeOrderCharacterData object (toScale).
* @return a TimeOrderCharacterData scaled to use EXPECTED_SUBSTITUTIONS based on
* this MutationRateModel
*/
// public TimeOrderCharacterData scale(TimeOrderCharacterData toScale) {
// if(getUnits()!=toScale.getUnits()) {
// throw new IllegalArgumentException("Incompatible units, expecting "+getUnits()+", found (in toScale) "+toScale.getUnits());
// }
// TimeOrderCharacterData scaled = toScale.clone(toScale);
// double[] times = new double[scaled.numberOfTaxa()];
// for (int i = 0; i < times.length; i++) {
// times[i] = getExpectedSubstitutions(scaled.getTime(i));
// }
// scaled.setTimes(times,Units.EXPECTED_SUBSTITUTIONS,false);
// return scaled;
// }
/**
* sets units of measurement.
* @throws IllegalArgumentException if units are ExpectedSubstitutions
*
* @param u units
* @param maximumMutationRate that is allowable, given the units. This needs to be given intelligently.
*/
public final void setUnits(int u, double maximumMutationRate)
{
if(u==Units.EXPECTED_SUBSTITUTIONS) { throw new IllegalArgumentException("Units cannot be Expected Substitutions!"); }
units = u;
this.maximumMutationRate_ = maximumMutationRate;
}
/**
* @return the maximum mutation rate as indicated by the user
*/
protected final double getMaximumMutationRate() { return maximumMutationRate_; }
/**
* returns units of measurement.
*/
public int getUnits()
{
return units;
}
/**
* Overide if there is any orthogonal hint information available
* @return null
*/
public OrthogonalHints getOrthogonalHints() {
return null;
}
public abstract String toSingleLine();
public abstract Factory generateFactory();
// ===========================================================================
// ==== Factory interface
/**
* An interface for objects which generate fresh MutationRAteModels
*/
public interface Factory {
/**
* Request a new MutationRateModel instance
*/
public MutationRateModel generateNewModel();
}
}
|
/*
* LcmsSeqRollupConditionServiceImpl.java 1.00 2011-09-05
*
* Copyright (c) 2011 ???? Co. All Rights Reserved.
*
* This software is the confidential and proprietary information
* of um2m. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the license agreement
* you entered into with um2m.
*/
package egovframework.adm.lcms.cts.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.stereotype.Service;
import egovframework.rte.fdl.excel.EgovExcelService;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import egovframework.adm.lcms.cts.service.LcmsSeqRollupConditionService;
import egovframework.adm.lcms.cts.dao.LcmsSeqRollupConditionDAO;
import egovframework.adm.lcms.cts.domain.LcmsSeqRollupCondition;
/**
* <pre>
* system :
* menu :
* source : LcmsSeqRollupConditionServiceImpl.java
* description :
* </pre>
* @version
* <pre>
* 1.0 2011-09-05 created by ?
* 1.1
* </pre>
*/
@Service("lcmsSeqRollupConditionService")
public class LcmsSeqRollupConditionServiceImpl extends EgovAbstractServiceImpl implements LcmsSeqRollupConditionService {
@Resource(name="lcmsSeqRollupConditionDAO")
private LcmsSeqRollupConditionDAO lcmsSeqRollupConditionDAO;
public List selectLcmsSeqRollupConditionPageList( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.selectLcmsSeqRollupConditionPageList( commandMap);
}
public int selectLcmsSeqRollupConditionPageListTotCnt( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.selectLcmsSeqRollupConditionPageListTotCnt( commandMap);
}
public List selectLcmsSeqRollupConditionList( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.selectLcmsSeqRollupConditionList( commandMap);
}
public Object selectLcmsSeqRollupCondition( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.selectLcmsSeqRollupCondition( commandMap);
}
public Object insertLcmsSeqRollupCondition( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.insertLcmsSeqRollupCondition( commandMap);
}
public int updateLcmsSeqRollupCondition( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.updateLcmsSeqRollupCondition( commandMap);
}
public int updateFieldLcmsSeqRollupCondition( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.updateLcmsSeqRollupCondition( commandMap);
}
public int deleteLcmsSeqRollupCondition( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.deleteLcmsSeqRollupCondition( commandMap);
}
public int deleteLcmsSeqRollupConditionAll( Map<String, Object> commandMap) throws Exception {
return lcmsSeqRollupConditionDAO.deleteLcmsSeqRollupConditionAll( commandMap);
}
public Object existLcmsSeqRollupCondition( LcmsSeqRollupCondition lcmsSeqRollupCondition) throws Exception {
return lcmsSeqRollupConditionDAO.existLcmsSeqRollupCondition( lcmsSeqRollupCondition);
}
}
|
package com.example.restfulwebservice.user;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
// insert into user values(1001, sysdate(), 'eony1','asdf','111');
// insert into post values(2001, 'My second post', 1001); |
package com.freehyun.book.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
//@EnableJpaAuditing //따로분리 config/JpaConfig 선언
@SpringBootApplication //스프링 부트의 자동 설정, 스프링 Bean 읽기와 생성을 모두 자동으로 설정
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args); //SpringApplication.run 으로 인해 내장 WAS(Web Application Server) 를 실행
}
}
|
package com.fb.util;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class NumUtils {
public static final String PATTERN = "0.00";
private static DecimalFormat df = new DecimalFormat(PATTERN);
public static Integer getNumInt(Double num) {
if(num!=null){
if(num==0){
return 0;
}
return num.intValue();
}else{
return 0;
}
}
public static void main(String args[]){
/*Double s = 80.0;
Double dd = ArithUtil.sub(s,new Double(s.intValue()));
Double ff = ArithUtil.mul(ArithUtil.sub(s, new Double(s.intValue())),new Double(100));
System.out.println(""+ff.toString());*/
//double s = 999999999999999d;
double s = 10000000000000.0000011d;
//double s = 01.225d;
//double s = 0.00000000000009d;
System.out.println(s);
System.out.println(NumUtils.getPlainDecimal(s));
}
public static double getArrivalMoney(Double money,Double fee ,Double cashFine){
BigDecimal sub1 = new BigDecimal(Double.toString(cashFine));
BigDecimal sub2 = new BigDecimal(Double.toString(fee));
BigDecimal sub3 = new BigDecimal(Double.toString(money));
double monry = sub3.subtract(sub2).subtract(sub1).doubleValue();
return monry;
}
/**
* 获取正常的小数
* 根治科学计数法 返回该数字的String串
* 10000000000000.0000011 参数
* 1.0E13 使用前
* 10000000000000.00 使用后
* @param money
* @return
*/
public static String getPlainDecimal(Double money){
if(money!=null){
return df.format(money);
}else{
return "";
}
}
}
|
package tw.org.iiijava;
public class zora31 {
public static void main(String[] args) {
int a=10, b=0;
int[] d={1,2,3,4};
try{
int c =a/b;
System.out.println(c);
System.out.println(d[4]);
}catch(ArithmeticException ae){//直系要將最小的放在最上面,才會被捕捉
System.out.println("haha");
}catch(RuntimeException g){
System.out.println("OK");
// }catch (ArrayIndexOutOfBoundsException ioy){
// System.out.println("You see see you");
}
System.out.println("Game Over!");
}
}
|
package com.Hackerrank.algos.warmup;
import java.io.*;
import java.util.*;
public class DiagonalDifference {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] ar=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
ar[i][j]=sc.nextInt();
}
}
int d1=0,d2=0;
for(int i=0,j=n-1;i<n;i++,j--){
d1=d1+ar[i][i];
d2=d2+ar[i][j];
}
int diff=Math.abs(d1-d2);
System.out.println(diff);
}
} |
package com.lesports.albatross.entity.community;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by jiangjianxiong on 16/6/15.
*/
public class Location {
@SerializedName("latitude")
@Expose
private double latitude;
@SerializedName("longitude")
@Expose
private double longitude;
@SerializedName("location_name")
@Expose
private String location_name;
public double getLatitude() {
return this.latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return this.longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getLocation_name() {
return location_name;
}
public void setLocation_name(String location_name) {
this.location_name = location_name;
}
}
|
package com.example.mvvmtest.data;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.mvvmtest.entity.Student;
import java.util.List;
/**
* @author hy
* @Date 2019/10/25 0025
**/
public class StudentsViewModel extends ViewModel {
private static StudentsViewModel INSTANCE;
private String name;
private MutableLiveData<List<Student>> studentList;
public StudentsViewModel(List<Student> defaultStudents) {
this.studentList = new MutableLiveData<>(defaultStudents);
}
public MutableLiveData<List<Student>> getStudentList() {
//这里还是要返回LiveData,否则视图中的绑定值变化不会生效
return studentList;
}
public void setStudentList(List<Student> studentList) {
//要用setValue!
this.studentList.setValue(studentList);
}
}
|
package vista;
import java.util.Hashtable;
import Juego.DragonAlgoBall;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import modelo.ObjetoJuego;
import modelo.Posicion;
import modelo.Tablero;
import modelo.turnos.Turno;
public class CanvasTablero extends Canvas{
DragonAlgoBall juego;
GraphicsContext context;
Turno turno;
public CanvasTablero(DragonAlgoBall juego){
this.juego = juego;
this.setWidth(ValoresGraficos.tamanioTablero);
this.setHeight(ValoresGraficos.tamanioTablero);
this.context = this.getGraphicsContext2D();
this.turno = juego.getTurnoActual();
}
private void limpiar(){
Image casillero = new Image("file:src/vista/Imagenes/casilleroVacio.jpg");
for(int i=0 ; i< ValoresGraficos.ladoCasillero ;i++){
for(int j=0 ;j<ValoresGraficos.ladoCasillero;j++){
context.drawImage(casillero, ValoresGraficos.tamanioCasillero*i, ValoresGraficos.tamanioCasillero*j, ValoresGraficos.tamanioCasillero, ValoresGraficos.tamanioCasillero);
}
}
}
private int coordenadaTableroX(int posX){
return ((posX -1)*ValoresGraficos.tamanioCasillero);
}
private int coordenadaTableroY(int posY){
return Math.abs((posY -10)*ValoresGraficos.tamanioCasillero);
}
public void dibujarTablero(){
limpiar();
Hashtable<String,Image> imagenes = ValoresGraficos.imagenes;
Tablero tablero = turno.obtenerTablero();
for(Posicion pos: tablero.obtenerPosiciones()){
ObjetoJuego objeto = tablero.obtenerObjeto(pos);
int coorX = coordenadaTableroX(pos.getCoordenadaX());
int coorY = coordenadaTableroY(pos.getCoordenadaY());
context.drawImage(imagenes.get(objeto.getNombre()), coorX, coorY, ValoresGraficos.tamanioCasillero, ValoresGraficos.tamanioCasillero);
}
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common.attributes;
import pl.edu.icm.unity.exceptions.IllegalAttributeValueException;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.webui.common.ComponentsContainer;
import pl.edu.icm.unity.webui.common.FormValidationException;
import pl.edu.icm.unity.webui.common.ListOfEmbeddedElementsStub;
import pl.edu.icm.unity.webui.common.ListOfEmbeddedElementsStub.Editor;
import pl.edu.icm.unity.webui.common.ListOfEmbeddedElementsStub.EditorProvider;
import pl.edu.icm.unity.webui.common.safehtml.HtmlConfigurableLabel;
import com.vaadin.ui.AbstractOrderedLayout;
/**
* Base of the components allowing to edit an attribute. The values are displayed too, however may be
* presented in a simplified form.
* <p>
* This base class provides a common editor code so it is easy to wire the {@link ListOfEmbeddedElementsStub}
* class to edit valuesof an attribute.
*
* @author K. Benedyczak
*/
public abstract class AbstractAttributeEditor
{
protected UnityMessageSource msg;
private AttributeHandlerRegistry registry;
public AbstractAttributeEditor(UnityMessageSource msg, AttributeHandlerRegistry registry)
{
this.msg = msg;
this.registry = registry;
}
protected ListOfEmbeddedElementsStub<LabelledValue> getValuesPart(AttributeType at, String label,
boolean required, boolean adminMode, AbstractOrderedLayout layout)
{
ListOfEmbeddedElementsStub<LabelledValue> ret = new ListOfEmbeddedElementsStub<LabelledValue>(msg,
new AttributeValueEditorAndProvider(at, label, required, adminMode),
at.getMinElements(), at.getMaxElements(), false, layout);
ret.setLonelyLabel(label);
return ret;
}
protected class AttributeValueEditorAndProvider implements EditorProvider<LabelledValue>, Editor<LabelledValue>
{
private AttributeType at;
private AttributeValueEditor<?> editor;
private LabelledValue editedValue;
private String baseLabel;
private boolean required;
private boolean adminMode;
public AttributeValueEditorAndProvider(AttributeType at, String label, boolean required,
boolean adminMode)
{
this.at = at;
this.baseLabel = label;
this.required = required;
this.adminMode = adminMode;
}
@Override
public Editor<LabelledValue> getEditor()
{
return new AttributeValueEditorAndProvider(at, baseLabel, required, adminMode);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public ComponentsContainer getEditorComponent(LabelledValue value, int position)
{
if (value == null)
value = new LabelledValue(null, establishLabel(position));
WebAttributeHandler handler = registry.getHandler(at.getValueType().getValueSyntaxId());
editor = handler.getEditorComponent(value.getValue(), value.getLabel(), at.getValueType());
editedValue = value;
ComponentsContainer ret = editor.getEditor(required, adminMode);
String description = at.getDescription().getValue(msg);
if (description != null && !description.equals(""))
ret.setDescription(HtmlConfigurableLabel.conditionallyEscape(description));
return ret;
}
@Override
public LabelledValue getValue() throws FormValidationException
{
try
{
return new LabelledValue(editor.getCurrentValue(), editedValue.getLabel());
} catch (IllegalAttributeValueException e)
{
throw new FormValidationException(e);
}
}
@Override
public void setEditedComponentPosition(int position)
{
editor.setLabel(establishLabel(position));
}
private String establishLabel(int position)
{
if (baseLabel == null)
{
if (at.getMaxElements() > 1)
return "(" + (position+1) +")";
else
return "";
}
if (at.getMaxElements() > 1)
{
String base = (baseLabel.endsWith(":")) ? baseLabel.substring(0, baseLabel.length()-1)
: baseLabel;
return base +" (" + (position+1) +"):";
} else
return baseLabel;
}
}
protected class LabelledValue
{
private Object value;
private String label;
public LabelledValue(Object value, String label)
{
this.value = value;
this.label = label;
}
public Object getValue()
{
return value;
}
public void setValue(Object value)
{
this.value = value;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
}
}
|
package hardware;
public interface HardwarePrimitiveActions {
/*
* Writes the given message to some form of output.
*/
public void writeToDisplay(String message);
/*
* Dispenses a given amount from a specified canister.
*/
public void dispense(int canisterNumber, int amount);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.sara.dto;
import com.davivienda.utilidades.conversion.FormatoFecha;
/**
*
* @author jmcastel
*/
public class ConsultarAjustesDTO {
private Integer idRegistro;
private String tipoAjuste;
private String usuario;
private String codigoOcca;
private String codigoOficina;
private String codigoCajero;
private String fecha;
private String talon;
private String valor;
private String codigoError;
private String descripcionError;
/**
* @return the idRegistro
*/
public Integer getIdRegistro() {
return idRegistro;
}
/**
* @param idRegistro the idRegistro to set
*/
public void setIdRegistro(Integer idRegistro) {
this.idRegistro = idRegistro;
}
/**
* @return the tipoAjuste
*/
public String getTipoAjuste() {
return tipoAjuste;
}
/**
* @param tipoAjuste the tipoAjuste to set
*/
public void setTipoAjuste(String tipoAjuste) {
this.tipoAjuste = tipoAjuste;
}
/**
* @return the usuario
*/
public String getUsuario() {
return usuario;
}
/**
* @param usuario the usuario to set
*/
public void setUsuario(String usuario) {
this.usuario = usuario;
}
/**
* @return the codigoOcca
*/
public String getCodigoOcca() {
return codigoOcca;
}
/**
* @param codigoOcca the codigoOcca to set
*/
public void setCodigoOcca(String codigoOcca) {
this.codigoOcca = codigoOcca;
}
/**
* @return the codigoCajero
*/
public String getCodigoCajero() {
return codigoCajero;
}
/**
* @param codigoCajero the codigoCajero to set
*/
public void setCodigoCajero(String codigoCajero) {
this.codigoCajero = codigoCajero;
}
/**
* @return the fecha
*/
public String getFecha() {
return fecha;
}
/**
* @param fecha the fecha to set
*/
public void setFecha(String fecha) {
this.fecha = fecha;
}
/**
* @return the talon
*/
public String getTalon() {
return talon;
}
/**
* @param talon the talon to set
*/
public void setTalon(String talon) {
this.talon = talon;
}
/**
* @return the valor
*/
public String getValor() {
return valor;
}
/**
* @param valor the valor to set
*/
public void setValor(String valor) {
this.valor = valor;
}
/**
* @return the codigoError
*/
public String getCodigoError() {
return codigoError;
}
/**
* @param codigoError the codigoError to set
*/
public void setCodigoError(String codigoError) {
this.codigoError = codigoError;
}
/**
* @return the descripcionError
*/
public String getDescripcionError() {
return descripcionError;
}
/**
* @param descripcionError the descripcionError to set
*/
public void setDescripcionError(String descripcionError) {
this.descripcionError = descripcionError;
}
public String getCodigoOficina() {
return codigoOficina;
}
public void setCodigoOficina(String codigoOficina) {
this.codigoOficina = codigoOficina;
}
}
|
/**
* Sender
*/
package com.bs.bod;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.bs.bod.converter.ConfirmationCodeDeserializer;
import com.bs.bod.converter.ConfirmationCodeSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* @author dbs on Dec 25, 2015 11:13:35 AM
* @version 1.0
* @since 0.0.1
*/
@JsonAutoDetect(fieldVisibility = Visibility.NON_PRIVATE, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@JsonInclude(Include.NON_NULL)
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Sender implements Serializable{
private static final long serialVersionUID = 1L;
static String __logicalId = null;
static String __componentId = null;
static String __taskId = null;
static String __referenceId = null;
static ConfirmationCode __confirmationCode = ConfirmationCode.never;
static String __authorizationId = null;
/**
* The Logical Identifier element provides the logical location of the server and application from which the Business Object Document originated. It can be
* used to establish a logical to physical mapping, however its use is optional.
*
* Each system or combination of systems should maintain an external central reference table containing the logical names or logical addresses of the
* application systems in the integration configuration. This enables the logical names to be mapped to the physical network addresses of the resources
* needed on the network.
*
* Note: The technical implementation of this Domain Naming Service is not dictated by this specification.
*
* This logical to physical mapping may be done at execution time by the application itself or by a middleware transport mechanism, depending on the
* integration architecture used.
*
* This provides for a simple but effective directory access capability while maintaining application independence from the physical location of those
* resources on the network.
* <br><strong>default is <code>null</code></strong>
*/
@JsonProperty("lid")
String logicalId = __logicalId;
/**
* The Component ID provides a finer level of control than Logical Identifier and represents the business application that issued the Business Object
* document. Its use is optional.
*
* The Open Applications Group has not constructed the list of valid Component names. A suggestion for naming is to use the application component names used
* in the scenario diagrams in section two of OAGIS. Example Components may be “Inventory”, or “Payroll”.
* <br><strong>default is <code>null</code></strong>
*/
@JsonProperty("cid")
String componentId = __componentId;
/**
* The Task ID describes the business event that initiated the need for the Business Object Document to be created.
* Its use is optional. Although the Task may differ depending on the specific implementation,
* it is important to enable drill back capability. Example Tasks may be “Receipt” or “Adjustment”.
*
* <br><strong>default is <code>null</code></strong>
*/
@JsonProperty("tid")
String taskId = __taskId;
/**
* Reference ID enables the sending application to indicate the instance identifier of the event or task that caused the BOD to be created.
* This allows drill back from the BOD message into the sending application.
* The may be required in environments where an audit trail must be maintained for all transactions.
* <br><strong>default is <code>null</code></strong>
* @see transaction ID
*/
@JsonProperty("rid")
String referenceId = __referenceId;
/**
* The Confirmation Code request is an option controlled by the Sender business application.
* It is a request to the receiving application to send back a confirmation BOD to the sender.
* The confirmation Business Object Document may indicate the successful processing of the original Business Object Document
* or return error conditions if the original Business Object Document was unsuccessful.
* <br><strong>default is assumed to be ConfirmationCode.never</strong>
*/
@JsonProperty("cc")
@JsonSerialize(using = ConfirmationCodeSerializer.class)
@JsonDeserialize(using = ConfirmationCodeDeserializer.class)
ConfirmationCode confirmationCode = __confirmationCode;
/**
* The Authorization Identifier describes the point of entry, such as the machine or device the user uses to perform the task that caused the creation of
* the Business Object Document.
*
* The Authorization Identifier is used as a return routing mechanism for a subsequent BOD, or for diagnostic or auditing purposes.
* Valid Authorization Identifiers are implementation specific.
* The Authorization Identifier might be used for authentication in the business process. As an example, in the case of Plant Data Collection,
* the Authorization Identifier is used to fully define the path between the user of a hand held terminal, any intermediate
* controller and the receiving application.
*
* In returning a BOD, the receiving application would pass the Authorization Identifier back to the controller to allow the message to be routed back to
* the hand held terminal.
*
* <br><strong>default is <code>null</code></strong>
*/
@JsonProperty("aid")
String authorizationId = __authorizationId;
public Sender(){
}
public Sender(ConfirmationCode confirmationCode){
this.confirmationCode = confirmationCode;
}
public Sender(String logicalId, String componentId, String taskId, String referenceId, ConfirmationCode confirmationCode, String authorizationId) {
this(confirmationCode);
this.logicalId = logicalId;
this.componentId = componentId;
this.taskId = taskId;
this.referenceId = referenceId;
this.authorizationId = authorizationId;
}
/**
* @return the logicalId
*/
public String getLogicalId() {
return logicalId;
}
/**
* @param logicalId the logicalId to set
* @return this for convenient chaining
*/
public Sender setLogicalId(String logicalId) {
this.logicalId = logicalId;
return this;
}
/**
* @return the componentId
*/
public String getComponentId() {
return componentId;
}
/**
* @param componentId the componentId to set
* @return this for convenient chaining
*/
public Sender setComponentId(String componentId) {
this.componentId = componentId;
return this;
}
/**
* @return the taskId
*/
public String getTaskId() {
return taskId;
}
/**
* @param taskId the taskId to set
* @return this for convenient chaining
*/
public Sender setTaskId(String taskId) {
this.taskId = taskId;
return this;
}
/**
* @return the referenceId
*/
public String getReferenceId() {
return referenceId;
}
/**
* @param referenceId the referenceId to set
* @return this for convenient chaining
*/
public Sender setReferenceId(String referenceId) {
this.referenceId = referenceId;
return this;
}
/**
* @return the confirmationCode
*/
public ConfirmationCode getConfirmationCode() {
return confirmationCode;
}
/**
* @param confirmationCode the confirmationCode to set
* @return this for convenient chaining
*/
public Sender setConfirmationCode(ConfirmationCode confirmationCode) {
this.confirmationCode = confirmationCode;
return this;
}
/**
* @return the authorizationId
*/
public String getAuthorizationId() {
return authorizationId;
}
/**
* @param authorizationId the authorizationId to set
* @return this for convenient chaining
*/
public Sender setAuthorizationId(String authorizationId) {
this.authorizationId = authorizationId;
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((authorizationId == null) ? 0 : authorizationId.hashCode());
result = prime * result + ((componentId == null) ? 0 : componentId.hashCode());
result = prime * result + ((confirmationCode == null) ? 0 : confirmationCode.hashCode());
result = prime * result + ((logicalId == null) ? 0 : logicalId.hashCode());
result = prime * result + ((referenceId == null) ? 0 : referenceId.hashCode());
result = prime * result + ((taskId == null) ? 0 : taskId.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Sender other = (Sender) obj;
if (authorizationId == null) {
if (other.authorizationId != null)
return false;
} else if (!authorizationId.equals(other.authorizationId))
return false;
if (componentId == null) {
if (other.componentId != null)
return false;
} else if (!componentId.equals(other.componentId))
return false;
if (confirmationCode != other.confirmationCode)
return false;
if (logicalId == null) {
if (other.logicalId != null)
return false;
} else if (!logicalId.equals(other.logicalId))
return false;
if (referenceId == null) {
if (other.referenceId != null)
return false;
} else if (!referenceId.equals(other.referenceId))
return false;
if (taskId == null) {
if (other.taskId != null)
return false;
} else if (!taskId.equals(other.taskId))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package exercicios.desafios.uri;
import java.util.Scanner;
public class Distancia1016 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int X = 60;
int Y = 90;
int tempo = sc.nextInt();
Y = tempo * 2;
System.out.println(Y + " " + "minutos");
sc.close();
}
} |
package com.gaoshin.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.gaoshin.beans.Category;
import common.util.reflection.ReflectionUtil;
@Entity
@Table(name = "category")
public class CategoryEntity extends GenericEntity {
@Column(length = 128, nullable = false, unique = true)
private String name;
@Column(length = 512)
private String description;
@OneToMany(mappedBy = "parent")
private List<CategoryEntity> children = new ArrayList<CategoryEntity>();
@ManyToOne
@JoinColumn
private CategoryEntity parent;
@OneToMany(mappedBy = "category")
private List<CatDimRelationEntity> dimensions;
@ManyToMany(mappedBy = "categories")
private List<ObjectEntity> objects;
public CategoryEntity() {
}
public CategoryEntity(Category bean) {
ReflectionUtil.copyPrimeProperties(this, bean);
}
public Category getBean(Class... views) {
Category category = ReflectionUtil.copy(Category.class, this, views);
return category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<CategoryEntity> getChildren() {
return children;
}
public void setChildren(List<CategoryEntity> subcategories) {
this.children = subcategories;
}
public CategoryEntity getParent() {
return parent;
}
public void setParent(CategoryEntity parent) {
this.parent = parent;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setObjects(List<ObjectEntity> objects) {
this.objects = objects;
}
public List<ObjectEntity> getObjects() {
return objects;
}
public boolean contains(Long childId) {
for (CategoryEntity child : children) {
if (child.getId().equals(childId))
return true;
}
return false;
}
public boolean hasDimension(Long dimId) {
for (CatDimRelationEntity dim : dimensions) {
if (dim.getDimension().getId().equals(dimId))
return true;
}
return false;
}
public CatDimRelationEntity removeDimension(Long dimensionId) {
for (int i = 0; i < dimensions.size(); i++) {
CatDimRelationEntity dim = dimensions.get(i);
if (dim.getDimension().getId().equals(dimensionId)) {
dimensions.remove(i);
return dim;
}
}
return null;
}
public void setDimensions(List<CatDimRelationEntity> dimensions) {
this.dimensions = dimensions;
}
public List<CatDimRelationEntity> getDimensions() {
return dimensions;
}
}
|
package com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter;
import android.support.v7.widget.RecyclerView;
import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.gravity.IRowStrategyFactory;
import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.gravity.RTLRowStrategyFactory;
import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter.breaker.IBreakerFactory;
import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter.breaker.RTLRowBreakerFactory;
class RTLRowsOrientationStateFactory implements IOrientationStateFactory {
@Override
public ILayouterCreator createLayouterCreator(RecyclerView.LayoutManager lm) {
return new RTLRowsCreator(lm);
}
@Override
public IRowStrategyFactory createRowStrategyFactory() {
return new RTLRowStrategyFactory();
}
@Override
public IBreakerFactory createDefaultBreaker() {
return new RTLRowBreakerFactory();
}
}
|
package com.example.customcitydatabase;
/**
* 这个类从DBManager类获得数据库的实例,然后定义了从数据库中获取city_spell,city_area,city_province的方法
* 没有继承SQLiteOpenHelper,因为不需要创建新表
*/
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper {
private DBManager dbManager;
private SQLiteDatabase db;
public DBHelper(Context context) {
super();
dbManager=new DBManager(context);
}
public ArrayList<String>getCityProvince(){
dbManager.openDatabase();//先导入数据库或者打开数据库
db=dbManager.getDatabase();//从dbManager获得数据库实例
ArrayList<String> cityProvince=new ArrayList<String>();
//查询city_id表中city_province列
Cursor cursor=db.query("city_id", new String[]{"city_province"},null, null, null, null, null);
while(cursor.moveToNext()){
String province=cursor.getString(cursor.getColumnIndex("city_province"));
cityProvince.add(province);
}
cursor.close();
dbManager.closeDatabase();
db.close();
return cityProvince;
}
public ArrayList<String>getCitySpellZH(){
dbManager.openDatabase();
db=dbManager.getDatabase();
ArrayList<String> citySpellZH=new ArrayList<String>();
Cursor cursor=db.query("city_id", new String[]{"city_spell_zh"},null,null,null,null,null);
while(cursor.moveToNext()){
String spellZH=cursor.getString(cursor.getColumnIndex("city_spell_zh"));
citySpellZH.add(spellZH);
}
cursor.close();
dbManager.closeDatabase();
db.close();
return citySpellZH;
}
/**
* 查询city_id表中的city_area,city_province,city_town三个列
* 并且用逗号连接字符串
* @return
*/
public ArrayList<String> getCityProvinceArea(){
dbManager.openDatabase();
db=dbManager.getDatabase();
ArrayList<String> cityProvinceArea=new ArrayList<String>();
Cursor cursor=db.query("city_id", new String[]{"city_area","city_province","city_town"}, null, null, null, null,null);
while(cursor.moveToNext()){
String provinceArea=cursor.getString(cursor.getColumnIndex("city_province"))+","+
cursor.getString(cursor.getColumnIndex("city_town"))+","+
cursor.getString(cursor.getColumnIndex("city_area"));
cityProvinceArea.add(provinceArea);
}
cursor.close();
dbManager.closeDatabase();
db.close();
return cityProvinceArea;
}
public ArrayList<String> getCityArea(){
dbManager.openDatabase();
db=dbManager.getDatabase();
ArrayList<String> cityArea=new ArrayList<String>();
Cursor cursor=db.query("city_id",new String[]{"city_area"},null,null,null,null,null);
while(cursor.moveToNext()){
String area=cursor.getString(cursor.getColumnIndex("city_area"));
cityArea.add(area);
}
cursor.close();
dbManager.closeDatabase();
db.close();
return cityArea;
}
}
|
package com.pelephone_mobile.mypelephone.network.rest.pojos;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by Gali.Issachar on 20/01/14.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class NormalLoginItem extends Pojo {
// to map to the property in json
@JsonProperty("responseError")
public ResponseErrorItem responseError;
// to map to the property in json
@JsonProperty("customerId")
public String customerId;
// to map to the property in json
@JsonProperty("firstName")
public String firstName;
// to map to the property in json
@JsonProperty("fullName")
public String fullName;
// to map to the property in json
@JsonProperty("lastName")
public String lastName;
// to map to the property in json
@JsonProperty("longToken")
public String longToken;
// to map to the property in json
@JsonProperty("subscriberNumber")
public String subscriberNumber;
// to map to the property in json
@JsonProperty("userType")
public int userType;
}
|
package com.netcracker.DTO.mappers;
import com.netcracker.DTO.UserDto;
import com.netcracker.entities.User;
import org.springframework.stereotype.Component;
@Component
public class UserMapper extends AbstractMapper<User, UserDto> {
public UserMapper() {
super(User.class, UserDto.class);
}}
|
package com.example.hw4111219_v2;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
//declare objects
EditText editTextZipCodeSearch;
Button buttonSearch;
TextView textViewBirdName, textViewZipCode, textViewUserName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
//connect to the UI
editTextZipCodeSearch = findViewById(R.id.editTextZipCodeSearch);
buttonSearch = findViewById(R.id.buttonSearch);
textViewBirdName = findViewById(R.id.textViewBirdName);
textViewZipCode = findViewById(R.id.textViewZipCode);
textViewUserName = findViewById(R.id.textViewUserName);
buttonSearch.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("hw4lfg");
if(view == buttonSearch){
Integer findZipCode = Integer.parseInt(editTextZipCodeSearch.getText().toString());
myRef.orderByChild("zipcode").equalTo(findZipCode).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
BirdSightings foundBird = dataSnapshot.getValue(BirdSightings.class);
//grab the bird name, the zip code, and the user who put it in
String findBirdName = foundBird.birdname;
Integer findZipCode = foundBird.zipcode;
String findUser = foundBird.birdsighter;
//diplay the info
textViewBirdName.setText(findBirdName);
textViewZipCode.setText(findZipCode.toString());
textViewUserName.setText(findUser);
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater Inflater = getMenuInflater();
Inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == R.id.itemInputForm) {
Intent InputIntent = new Intent(this, MainActivity.class);
startActivity(InputIntent);
} else if(item.getItemId() == R.id.itemSearch) {
Toast.makeText(this, "You are already here", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
|
public class Solution {
private static int count = 0;
private static int threshold1;
private static int rows1;
private static int cols1;
public int movingCount(int threshold, int rows, int cols)
{
threshold1 = threshold;
rows1 = rows;
cols1 = cols;
// System.out.println(rows1+" "+cols1);
boolean[][] hasPassed = new boolean[rows][cols];
// hasPassed[0][0] = true;
move(0,0,hasPassed);
return count;
}
private void move(int i, int j, boolean[][] hasPassed)
{
// System.out.println("i:"+i+",j:"+j+";是否经过:"+hasPassed[i][j]);
// 这个点满足条件则统计数量,并且以这个点为中心检查上下左右
if (i>=0 && i<rows1 && j>=0 && j<cols1 && !hasPassed[i][j] && calDigitalSum(i,j)<=threshold1)
{
count += 1;
hasPassed[i][j] = true;
// 上下左右
move(i+1,j,hasPassed);
move(i-1,j,hasPassed);
move(i,j+1,hasPassed);
move(i,j-1,hasPassed);
}
}
private int calDigitalSum(int i,int j)
{
// 计算数位之和
int sum = 0;
while(i>0)
{
sum += i % 10;
i = i / 10;
}
while (j>0)
{
sum += j % 10;
j = j /10;
}
return sum;
}
public static void main(String[] args) {
Solution solution = new Solution();
// System.out.println(solution.calDigitalSum(0,0));
System.out.println(solution.movingCount(15,20,20));
}
}
|
package be.openclinic.finance;
import be.openclinic.common.OC_Object;
import be.openclinic.common.ObjectReference;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import java.util.Date;
import java.util.Vector;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
public class Balance extends OC_Object implements Comparable{
private double balance;
private double minimumBalance;
private double maximumBalance;
private ObjectReference owner; //Person or Service
private Date date;
private String remarks;
private Date closedTime;
//--- COMPARE TO ------------------------------------------------------------------------------
public int compareTo(Object o){
int comp;
if (o.getClass().isInstance(this)){
comp = this.getDate().compareTo(((Balance)o).getDate());
}
else {
throw new ClassCastException();
}
return comp;
}
public double getBalance() {
return getCurrency(balance);
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getMinimumBalance() {
return minimumBalance;
}
public void setMinimumBalance(double minimumBalance) {
this.minimumBalance = minimumBalance;
}
public double getMaximumBalance() {
return maximumBalance;
}
public void setMaximumBalance(double maximumBalance) {
this.maximumBalance = maximumBalance;
}
public ObjectReference getOwner() {
return owner;
}
public void setOwner(ObjectReference owner) {
this.owner = owner;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Date getClosedTime() {
return closedTime;
}
public void setClosedTime(Date date) {
this.closedTime = date;
}
public static Balance get(String uid) throws ClassCastException {
Balance balance = new Balance();
if ((uid!=null)&&(uid.length()>0)){
String [] ids = uid.split("\\.");
ResultSet rs = null;
PreparedStatement ps= null;
String sSelect = "";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
if (ids.length==2){
sSelect = " SELECT * FROM OC_BALANCES WHERE OC_BALANCE_SERVERID = ? AND OC_BALANCE_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
rs = ps.executeQuery();
if (rs.next()){
balance.setUid(uid);
balance.setBalance(rs.getDouble("OC_BALANCE_VALUE"));
balance.setMaximumBalance(rs.getDouble("OC_BALANCE_MAXIMUMBALANCE"));
balance.setMinimumBalance(rs.getDouble("OC_BALANCE_MINIMUMBALANCE"));
balance.setDate(rs.getTimestamp("OC_BALANCE_DATE"));
ObjectReference or = new ObjectReference();
or.setObjectType(ScreenHelper.checkString(rs.getString("OC_BALANCE_OWNERTYPE")));
or.setObjectUid(ScreenHelper.checkString(rs.getString("OC_BALANCE_OWNERUID")));
balance.setOwner(or);
balance.setRemarks(ScreenHelper.checkString(rs.getString("OC_BALANCE_REMARKS")));
balance.setCreateDateTime(rs.getTimestamp("OC_BALANCE_CREATETIME"));
balance.setUpdateDateTime(rs.getTimestamp("OC_BALANCE_UPDATETIME"));
balance.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_BALANCE_UPDATEUID")));
balance.setVersion(rs.getInt("OC_BALANCE_VERSION"));
balance.setClosedTime(rs.getTimestamp("OC_BALANCE_CLOSEDTIME"));
}
rs.close();
ps.close();
}
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => get => "+e.getMessage()+" = "+sSelect);
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
return balance;
}
public void store(){
String sSelect = "";
PreparedStatement ps = null;
ResultSet rs = null;
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
int iVersion = 1;
String[] ids;
if ((this.getUid()!=null) && (this.getUid().length() >0)){
ids = getUid().split("\\.");
if (ids.length==2){
sSelect = " SELECT * FROM OC_BALANCES WHERE OC_BALANCE_SERVERID = ? AND OC_BALANCE_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
rs = ps.executeQuery();
if (rs.next()){
iVersion = rs.getInt("OC_BALANCE_VERSION")+1;
}
rs.close();
ps.close();
sSelect = " INSERT INTO OC_BALANCES_HISTORY SELECT * FROM OC_BALANCES WHERE OC_BALANCE_SERVERID = ? AND OC_BALANCE_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
sSelect = " UPDATE OC_BALANCES SET OC_BALANCE_SERVERID = ?, " +
"OC_BALANCE_OBJECTID = ?, " +
"OC_BALANCE_VALUE = ?, " +
"OC_BALANCE_MINIMUMBALANCE = ?, " +
"OC_BALANCE_MAXIMUMBALANCE = ?, " +
"OC_BALANCE_OWNERTYPE = ?, " +
"OC_BALANCE_OWNERUID = ?, " +
"OC_BALANCE_DATE = ?, " +
"OC_BALANCE_REMARKS = ?, " +
"OC_BALANCE_CREATETIME = ?, " +
"OC_BALANCE_UPDATETIME = ?, " +
"OC_BALANCE_UPDATEUID = ?, " +
"OC_BALANCE_VERSION = ?, " +
"OC_BALANCE_CLOSEDTIME = ? " +
" WHERE OC_BALANCE_SERVERID = ? AND OC_BALANCE_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.setDouble(3,this.getBalance());
ps.setDouble(4,this.getMinimumBalance());
ps.setDouble(5,this.getMaximumBalance());
ps.setString(6,this.getOwner().getObjectType());
ps.setString(7,this.getOwner().getObjectUid());
ScreenHelper.getSQLTimestamp(ps,8,this.getDate());
/* if(this.getDate() == null){
ps.setTimestamp(8,new Timestamp(ScreenHelper.getSQLDate(ScreenHelper.getDate()).getTime()));
}else{
ps.setTimestamp(8,new Timestamp(this.getDate().getTime()));
}*/
ps.setString(9,this.getRemarks());
ps.setTimestamp(10,new Timestamp(this.getCreateDateTime().getTime()));
ps.setTimestamp(11,new Timestamp(this.getUpdateDateTime().getTime()));
ps.setString(12,this.getUpdateUser());
ps.setInt(13,iVersion);
//ScreenHelper.getSQLTimestamp(ps,14, ScreenHelper.stdDateFormat.format(this.closedTime),new SimpleDateFormat("hh:mm").format(this.closedTime));
ScreenHelper.getSQLTimestamp(ps,14,this.closedTime);
ps.setInt(15,Integer.parseInt(ids[0]));
ps.setInt(16,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
}
}else{
ids = new String[] {MedwanQuery.getInstance().getConfigString("serverId"),MedwanQuery.getInstance().getOpenclinicCounter("OC_BALANCES")+""};
this.setUid(ids[0]+"."+ids[1]);
if (ids.length==2){
sSelect = " INSERT INTO OC_BALANCES (" +
"OC_BALANCE_SERVERID, " +
"OC_BALANCE_OBJECTID, " +
"OC_BALANCE_VALUE, " +
"OC_BALANCE_MINIMUMBALANCE, " +
"OC_BALANCE_MAXIMUMBALANCE, " +
"OC_BALANCE_OWNERTYPE, " +
"OC_BALANCE_OWNERUID, " +
"OC_BALANCE_DATE, " +
"OC_BALANCE_REMARKS, " +
"OC_BALANCE_CREATETIME, " +
"OC_BALANCE_UPDATETIME, " +
"OC_BALANCE_UPDATEUID, " +
"OC_BALANCE_VERSION" +
") " +
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.setDouble(3,this.getBalance());
ps.setDouble(4,this.getMinimumBalance());
ps.setDouble(5,this.getMaximumBalance());
ps.setString(6,this.getOwner().getObjectType());
ps.setString(7,this.getOwner().getObjectUid());
/*if(this.getDate() == null){
ps.setNull(8,java.sql.Types.TIMESTAMP);
}else{
ps.setTimestamp(8,new Timestamp(this.getDate().getTime()));
}*/
ScreenHelper.getSQLTimestamp(ps,8,this.getDate());
ps.setString(9,this.getRemarks());
ps.setTimestamp(10,new Timestamp(this.getCreateDateTime().getTime()));
ps.setTimestamp(11,new Timestamp(this.getUpdateDateTime().getTime()));
ps.setString(12,this.getUpdateUser());
ps.setInt(13,iVersion);
ps.executeUpdate();
ps.close();
this.setUid(ids[0] + "." + ids[1]);
}
}
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => store => "+e.getMessage()+" = "+sSelect);
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void updateBalanceValue(){
double debet = 0
,credit = 0;
PreparedStatement ps = null;
ResultSet rs = null;
String sSelect = "";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
sSelect = " SELECT OC_DEBET_AMOUNT FROM OC_DEBETS WHERE OC_DEBET_BALANCEUID = ?";
ps = oc_conn.prepareStatement(sSelect);
ps.setString(1,this.getUid());
rs = ps.executeQuery();
while(rs.next()){
debet += rs.getDouble("OC_DEBET_AMOUNT");
}
rs.close();
ps.close();
sSelect = " SELECT OC_CREDIT_AMOUNT FROM OC_CREDITS WHERE OC_CREDIT_BALANCEUID = ?";
ps = oc_conn.prepareStatement(sSelect);
ps.setString(1,this.getUid());
rs = ps.executeQuery();
while(rs.next()){
credit += rs.getDouble("OC_CREDIT_AMOUNT");
}
rs.close();
ps.close();
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => updateBalanceValue => "+e.getMessage()+" = "+sSelect);
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
this.setBalance(credit - debet);
this.store();
this.checkZeroBalance();
}
private void checkZeroBalance(){
if(this.getBalance() == 0){
PreparedStatement ps = null;
ResultSet rs = null;
String sSelect = "";
String ids[] = this.getUid().split("\\.");
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
sSelect = "UPDATE OC_BALANCES SET OC_BALANCE_CLOSEDTIME = ? WHERE OC_BALANCE_SERVERID = ? AND OC_BALANCE_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sSelect);
ps.setTimestamp(1,new Timestamp(ScreenHelper.getSQLDate(ScreenHelper.getDate()).getTime()));
ps.setInt(2,Integer.parseInt(ids[0]));
ps.setInt(3,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
ids = new String[] {MedwanQuery.getInstance().getConfigString("serverId"),MedwanQuery.getInstance().getOpenclinicCounter("OC_BALANCES")+""};
sSelect = " INSERT INTO OC_BALANCES (" +
"OC_BALANCE_SERVERID, " +
"OC_BALANCE_OBJECTID, " +
"OC_BALANCE_VALUE, " +
"OC_BALANCE_MINIMUMBALANCE, " +
"OC_BALANCE_MAXIMUMBALANCE, " +
"OC_BALANCE_OWNERTYPE, " +
"OC_BALANCE_OWNERUID, " +
"OC_BALANCE_DATE, " +
"OC_BALANCE_REMARKS, " +
"OC_BALANCE_CREATETIME, " +
"OC_BALANCE_UPDATETIME, " +
"OC_BALANCE_UPDATEUID, " +
"OC_BALANCE_VERSION" +
") " +
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.setDouble(3,this.getBalance());
ps.setDouble(4,this.getMinimumBalance());
ps.setDouble(5,this.getMaximumBalance());
ps.setString(6,this.getOwner().getObjectType());
ps.setString(7,this.getOwner().getObjectUid());
ps.setTimestamp(8,new Timestamp(ScreenHelper.getSQLDate(ScreenHelper.getDate()).getTime()));
ps.setString(9,this.getRemarks());
ps.setTimestamp(10,new Timestamp(new Date().getTime()));
ps.setTimestamp(11,new Timestamp(this.getUpdateDateTime().getTime()));
ps.setString(12,this.getUpdateUser());
ps.setInt(13,1);
ps.executeUpdate();
ps.close();
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => checkZeroBalance => "+e.getMessage()+" = "+sSelect);
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
public static Balance getActiveBalance(String sUID){
Balance balance = new Balance();
PreparedStatement ps = null;
ResultSet rs = null;
String sSelect = "";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
sSelect = "SELECT * FROM OC_BALANCES WHERE OC_BALANCE_OWNERUID = ? AND OC_BALANCE_CLOSEDTIME IS NULL ";
ps = oc_conn.prepareStatement(sSelect);
ps.setString(1,sUID);
rs = ps.executeQuery();
if (rs.next()){
String sBalanceUID = rs.getInt("OC_BALANCE_SERVERID")+"."+rs.getInt("OC_BALANCE_OBJECTID");
balance = Balance.get(sBalanceUID);
}
rs.close();
ps.close();
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => getActiveBalance => "+e.getMessage()+" = "+sSelect);
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return balance;
}
public static double getCurrency(double d){
/* int decimalPlace = 2;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
return (bd.doubleValue());*/
return d;
}
public static double getPatientBalance(String personid){
double total=0;
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
PreparedStatement ps=null;
String sSelect = "select sum(total) balance from" +
" (" +
" select sum(oc_patientcredit_amount) total from oc_patientcredits a,oc_encounters b" +
" where" +
" a.oc_patientcredit_encounteruid='"+MedwanQuery.getInstance().getConfigString("serverId")+".'"+MedwanQuery.getInstance().concatSign()+MedwanQuery.getInstance().convert("varchar", "b.oc_encounter_objectid")+" and" +
" b.oc_encounter_patientuid=?" +
" union" +
" select -sum(oc_debet_amount) total from oc_debets a,oc_encounters b" +
" where" +
" a.oc_debet_encounteruid='"+MedwanQuery.getInstance().getConfigString("serverId")+".'"+MedwanQuery.getInstance().concatSign()+MedwanQuery.getInstance().convert("varchar", "b.oc_encounter_objectid")+" and" +
" b.oc_encounter_patientuid=? and" +
" (a.oc_debet_extrainsuraruid2 is null or a.oc_debet_extrainsuraruid2 ='')" +
") a";
if(MedwanQuery.getInstance().getConfigString("convertDataTypeVarchar","").equalsIgnoreCase("char")){
//This is MySQL, no conversion to be used
sSelect = "select sum(total) balance from" +
" (" +
" select sum(oc_patientcredit_amount) total from oc_patientcredits a,oc_encounters b" +
" where" +
" a.oc_patientcredit_encounteruid='"+MedwanQuery.getInstance().getConfigString("serverId")+".'"+MedwanQuery.getInstance().concatSign()+"b.oc_encounter_objectid and" +
" b.oc_encounter_patientuid=?" +
" union" +
" select -sum(oc_debet_amount) total from oc_debets a IGNORE INDEX (OC_DEBET_EXTRAINSURARUID2),oc_encounters b" +
" where" +
" a.oc_debet_encounteruid='"+MedwanQuery.getInstance().getConfigString("serverId")+".'"+MedwanQuery.getInstance().concatSign()+"b.oc_encounter_objectid and" +
" b.oc_encounter_patientuid=? and" +
" (a.oc_debet_extrainsuraruid2 is null or a.oc_debet_extrainsuraruid2 ='')" +
") a";
}
ps = oc_conn.prepareStatement(sSelect);
ps.setString(1,personid);
ps.setString(2,personid);
ResultSet rs = ps.executeQuery();
if(rs.next()){
total=rs.getDouble("balance");
}
rs.close();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
try {
oc_conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return total;
}
public static Vector getDebets(String sBalanceID, Timestamp ts) {
Vector vReturn = new Vector();
String sSelect = "";
ResultSet rs = null;
PreparedStatement ps = null;
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
sSelect = "SELECT * FROM OC_DEBETS WHERE OC_DEBET_BALANCEUID = ? AND OC_DEBET_CREATETIME >= ?";
ps = oc_conn.prepareStatement(sSelect);
ps.setString(1,sBalanceID);
ps.setTimestamp(2,ts);
rs = ps.executeQuery();
DebetTransaction debet;
while(rs.next()){
debet = new DebetTransaction();
debet.setAmount(rs.getDouble("OC_DEBET_AMOUNT"));
debet.setDate(rs.getTimestamp("OC_DEBET_DATE"));
debet.setUid(ScreenHelper.checkString(rs.getString("OC_DEBET_SERVERID")) + "." + ScreenHelper.checkString(rs.getString("OC_DEBET_OBJECTID")));
debet.setDescription(ScreenHelper.checkString(rs.getString("OC_DEBET_DESCRIPTION")));
debet.setReferenceObject(new ObjectReference(rs.getString("OC_DEBET_REFTYPE"),rs.getString("OC_DEBET_REFUID")));
vReturn.add(debet);
}
rs.close();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => getDebets => "+e.getMessage()+" = "+sSelect);
e.printStackTrace();
}
}
return vReturn;
}
public static Vector getCredits(String sBalanceID, Timestamp ts) {
Vector vReturn = new Vector();
String sSelect = "";
ResultSet rs = null;
PreparedStatement ps = null;
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
sSelect = "SELECT * FROM OC_CREDITS WHERE OC_CREDIT_BALANCEUID = ? AND OC_CREDIT_CREATETIME >= ?";
ps = oc_conn.prepareStatement(sSelect);
ps.setString(1,sBalanceID);
ps.setTimestamp(2,ts);
rs = ps.executeQuery();
CreditTransaction credit;
while(rs.next()){
credit = new CreditTransaction();
credit.setUid(ScreenHelper.checkString(rs.getString("OC_CREDIT_SERVERID")) + "." + ScreenHelper.checkString(rs.getString("OC_CREDIT_OBJECTID")));
credit.setDate(rs.getTimestamp("OC_CREDIT_DATE"));
credit.setDescription(ScreenHelper.checkString(rs.getString("OC_CREDIT_DESCRIPTION")));
credit.setAmount(rs.getDouble("OC_CREDIT_AMOUNT"));
credit.setType(rs.getString("OC_CREDIT_TYPE"));
vReturn.add(credit);
}
rs.close();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}
catch(Exception e){
Debug.println("OpenClinic => Balance.java => getCredits => "+e.getMessage()+" = "+sSelect);
e.printStackTrace();
}
}
return vReturn;
}
public static Vector searchBalances(String sSelectOwner){
PreparedStatement ps = null;
ResultSet rs = null;
Vector vResults = new Vector();
Balance objBalance;
String sSelect = "";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
// compose query
if ((sSelectOwner.trim().length()>0)&&(sSelectOwner.trim().length()>0)) {
sSelect+= " UPPER(OC_BALANCE_OWNERUID) like '"+sSelectOwner.toUpperCase()+"%' AND";
}
// complete query
if(sSelect.length()>0) {
sSelect = " SELECT * FROM OC_BALANCES " +
" WHERE " + sSelect.substring(0,sSelect.length()-3) +
" ORDER BY OC_BALANCE_DATE";
ps = oc_conn.prepareStatement(sSelect);
rs = ps.executeQuery();
while(rs.next()){
objBalance = new Balance();
objBalance.setUid(ScreenHelper.checkString(rs.getString("OC_BALANCE_SERVERID")) + "." + ScreenHelper.checkString(rs.getString("OC_BALANCE_OBJECTID")));
objBalance.setBalance(rs.getDouble("OC_BALANCE_VALUE"));
objBalance.setMaximumBalance(rs.getDouble("OC_BALANCE_MAXIMUMBALANCE"));
objBalance.setMinimumBalance(rs.getDouble("OC_BALANCE_MINIMUMBALANCE"));
objBalance.setDate(rs.getTimestamp("OC_BALANCE_DATE"));
ObjectReference or = new ObjectReference();
or.setObjectType(ScreenHelper.checkString(rs.getString("OC_BALANCE_OWNERTYPE")));
or.setObjectUid(ScreenHelper.checkString(rs.getString("OC_BALANCE_OWNERUID")));
objBalance.setOwner(or);
objBalance.setRemarks(ScreenHelper.checkString(rs.getString("OC_BALANCE_REMARKS")));
objBalance.setCreateDateTime(rs.getTimestamp("OC_BALANCE_CREATETIME"));
objBalance.setUpdateDateTime(rs.getTimestamp("OC_BALANCE_UPDATETIME"));
objBalance.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_BALANCE_UPDATEUID")));
objBalance.setVersion(rs.getInt("OC_BALANCE_VERSION"));
objBalance.setClosedTime(rs.getTimestamp("OC_BALANCE_CLOSEDTIME"));
vResults.addElement(objBalance);
}
rs.close();
ps.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return vResults;
}
public static Vector getNonClosedBalancesByOwnerDate(String sOwner, String sDate){
PreparedStatement ps = null;
ResultSet rs = null;
Vector vBalances = new Vector();
String sSelect = "SELECT * FROM OC_BALANCES WHERE OC_BALANCE_CLOSEDTIME IS NULL AND";
if (sOwner.length() > 0 || sDate.length() > 0) {
//sSelect += " WHERE";
if (sOwner.length() > 0) sSelect += " OC_BALANCE_OWNERUID LIKE ? AND";
if (sDate.length() > 0) sSelect += " OC_BALANCE_DATE > ? AND";
}
sSelect = sSelect.substring(0, sSelect.length() - 3);
if (Debug.enabled) {
Debug.println("SELECT QUERY: " + sSelect);
}
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
ps = oc_conn.prepareStatement(sSelect);
int iParams = 1;
if (sOwner.length() > 0) ps.setString(iParams++, sOwner);
if (sDate.length() > 0) ps.setDate(iParams++, ScreenHelper.getSQLDate(sDate));
rs = ps.executeQuery();
Balance objBalance;
while(rs.next()){
objBalance = new Balance();
objBalance.setUid(ScreenHelper.checkString(rs.getString("OC_BALANCE_SERVERID")) + "." + ScreenHelper.checkString(rs.getString("OC_BALANCE_OBJECTID")));
objBalance.setBalance(rs.getDouble("OC_BALANCE_VALUE"));
objBalance.setMaximumBalance(rs.getDouble("OC_BALANCE_MAXIMUMBALANCE"));
objBalance.setMinimumBalance(rs.getDouble("OC_BALANCE_MINIMUMBALANCE"));
objBalance.setDate(rs.getTimestamp("OC_BALANCE_DATE"));
ObjectReference or = new ObjectReference();
or.setObjectType(ScreenHelper.checkString(rs.getString("OC_BALANCE_OWNERTYPE")));
or.setObjectUid(ScreenHelper.checkString(rs.getString("OC_BALANCE_OWNERUID")));
objBalance.setOwner(or);
objBalance.setRemarks(ScreenHelper.checkString(rs.getString("OC_BALANCE_REMARKS")));
objBalance.setCreateDateTime(rs.getTimestamp("OC_BALANCE_CREATETIME"));
objBalance.setUpdateDateTime(rs.getTimestamp("OC_BALANCE_UPDATETIME"));
objBalance.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_BALANCE_UPDATEUID")));
objBalance.setVersion(rs.getInt("OC_BALANCE_VERSION"));
objBalance.setClosedTime(rs.getTimestamp("OC_BALANCE_CLOSEDTIME"));
vBalances.addElement(objBalance);
}
rs.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return vBalances;
}
} |
package atividade;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**
* @author André Luiz Dias de Oliveira
* Implementar um pequeno protocolo para coletar informações sobre a máquina remota (servidor).
* As informações devem incluir, Memória total, Memória usada, Memória livre,
* Número de processadores disponíveis, espaço total do disco principal e espaço livre do disco principal.
*/
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);
System.out.println("Menu:\n" +
"Digite 1 - Memoria Total\n" +
"Digite 2 - Memoria Livre\n" +
"Digite 3 - Memoria Usada\n" +
"Digite 4 - Numero de Processadores disponiveis\n" +
"Digite 5 - Espaço total em disco\n" +
"Digite 6 - Espaço disponivel em disco\n" +
"Digite 0 - Para sair"
);
Scanner scanner = new Scanner(System.in);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while (true) {
String clientChoice = scanner.nextLine();
if (clientChoice.equals("0")) {
socket.close();
break;
}
printWriter.println(clientChoice);
printWriter.flush();
String serverResponse = bufferedReader.readLine();
System.out.println(serverResponse);
}
}
}
|
/*
* © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.molr.commons.annotations;
import com.sun.tools.javac.code.Symbol;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Base64;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A processor annotation, which is automatically plugged into javac
* (see META-INF/services/javax.annotation.processing.Processor).
* It recognizes {@link SourceMe} annotations and create a companion class containing the source code
* (encoded in BASE64) of the annotated class.
*
* @author mgalilee
*/
@SupportedAnnotationTypes("cern.molr.commons.annotations.SourceMe")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SourceMeProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element elem : roundEnv.getElementsAnnotatedWith(SourceMe.class)) {
if (elem.getKind() == ElementKind.CLASS) {
TypeElement classElement = (TypeElement) elem;
if (classElement instanceof Symbol.ClassSymbol) {
Symbol.ClassSymbol classSymbol = (Symbol.ClassSymbol) classElement;
JavaFileObject javaFileObject;
try (BufferedReader reader = new BufferedReader(classSymbol.sourcefile.openReader(true))) {
String content = reader.lines().collect(Collectors.joining("\n"));
String base64Content = Base64.getEncoder().encodeToString(content.getBytes());
javaFileObject = processingEnv.getFiler()
.createSourceFile(classElement.getQualifiedName() + "Source");
BufferedWriter bufferedWriter = new BufferedWriter(javaFileObject.openWriter());
if (!classSymbol.packge().isUnnamed()) {
bufferedWriter.append("package ");
bufferedWriter.append(classSymbol.packge().fullname);
bufferedWriter.append(";\n");
}
bufferedWriter.append("public class ");
bufferedWriter.append(classSymbol.getSimpleName());
bufferedWriter.append("Source implements cern.molr.commons.annotations.Source {\n");
bufferedWriter.append(" public final String base64Value() {\n return \"");
bufferedWriter.append(base64Content);
bufferedWriter.append("\";\n }\n}");
bufferedWriter.close();
} catch (IOException e) {
System.out.println(String.format("Exception while processing %s", classSymbol.className()));
e.printStackTrace();
}
} else {
System.out.println(String.format("Skipped %s as not an instance of ClassSymbol", classElement));
}
}
}
return true;
}
}
|
package com.eintern.restclient.client;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class ConvertClient {
static final String REST_URI = "http://localhost:7001/RESTService2";
static final String YARDS_TO_METERS = "/ConvertService/YardsToMeters/";
public static void main(String[] args) {
int yards = 12;
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(REST_URI);
WebResource convertService = service.path("rest").path(YARDS_TO_METERS + yards);
System.out.println("Convert yards to meters XML" + getOutputAsXml(convertService));
}
private static String getOutputAsXml(WebResource service) {
return service.accept(MediaType.TEXT_XML).get(String.class);
}
}
|
package assignments.niit.java.lab1;
public class Test1 {
public static void main(String[] args) {
System.out.println("What's wrong with this program?");
}
}
/*
* A single file cannot have 2 public classes
*/
/*public*/ class TestAnother1 {
public static void main(String[] args) {
System.out.println("What's wrong with this program?");
}
}
|
package ai.cheap.petbot;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
// OpenCv
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
// Usb Serial
// Android
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Toast;
// Java
import java.lang.ref.WeakReference;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements CvCameraViewListener2 {
// OpenCv
private static final String TAG = "OCVSample::Activity";
private CameraBridgeViewBase mOpenCvCameraView;
private boolean mIsJavaCamera = true;
private MenuItem mItemSwitchCamera = null;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
// UsbSerial
private UsbService usbService;
public static String UglyFeedBack = "GraOOu";
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.camView);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setMaxFrameSize(640,480);
mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
// Intelligence will emerge from this point !!!
// Controller controller = new ReplayerController ( );
Controller controller = null;
public Mat onCameraFrame ( CvCameraViewFrame inputFrame ) {
// Mat mat = inputFrame.rgba ( );
Mat mat = inputFrame.gray ( );
ParamContainer params = new ParamContainer ( );
params.Frame = mat;
params.Cmd = UglyFeedBack;
if ( controller == null ) {
controller = new HumanTrackingController ( );
//controller = new BasicTestController ( );
}
controller.Update ( params );
// if UsbService was correctly binded, Send data
if ( ( params.Cmd != null ) && ( usbService != null ) ) {
String cmd = params.Cmd + "\r\n";
usbService.write ( cmd.getBytes ( ) );
}
return params.Frame;
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
// Seems not working ...
UglyFeedBack = data;
Toast.makeText(mActivity.get(), data,Toast.LENGTH_LONG).show();
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE",Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE",Toast.LENGTH_LONG).show();
break;
}
}
}
} |
package Problem_17626;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int cnt;
static int[] dp = new int[50001];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Arrays.fill(dp, 1000000);
for(int i = 1; i*i<=50000;i++) {
dp[i*i] = 1;
}
for(int i = 2; i<=N; i++) {
for(int j = 1; j*j<=i;j++) {
dp[i] = Math.min(dp[i], dp[i-j*j]+1);
}
}
System.out.println(dp[N]);
}
}
|
package com.Github;
import java.util.Scanner;
class Main{
public static void main(String[] args) {
int matrik [] [] = new int[10][10];
Scanner scan = new Scanner (System.in);
int x = scan.nextInt();
for (int i = 0 ; i <x ; i++){
for (int j = 0 ; j <x ; j++){
System.out.print( ("*") + " ");
}
System.out.println("");
}
}
} |
package com.tpg.brks.ms.expenses.service;
import com.tpg.brks.ms.expenses.domain.Account;
import com.tpg.brks.ms.expenses.domain.Assignment;
import com.tpg.brks.ms.expenses.persistence.entities.AccountEntity;
import com.tpg.brks.ms.expenses.persistence.entities.AssignmentEntity;
import com.tpg.brks.ms.expenses.persistence.repositories.AssignmentQueryRepository;
import com.tpg.brks.ms.expenses.service.converters.AccountConverter;
import com.tpg.brks.ms.expenses.service.converters.AssignmentConverter;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.Optional;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AssignmentQueryServiceImplTest extends ServiceImplTest {
@Mock
private AssignmentQueryRepository assignmentQueryRepository;
private AssignmentQueryServiceImpl assignmentQueryService;
@Before
public void setUp() {
assignmentQueryService = new AssignmentQueryServiceImpl(assignmentQueryRepository,
new AssignmentConverter(new AccountConverter()));
}
@Test
public void findingAssignmentsByAccount() {
AccountEntity accountEntity = givenAnAccountEntity();
AssignmentEntity assignmentEntity = givenAnAssignmentEntity(accountEntity);
Account account = givenAnAccount();
Assignment assignment = whenFindingCurrentAssignmentForAccount(account, assignmentEntity);
thenCurrentAssignmentReturned(account.getId(), assignmentEntity, assignment);
}
private Assignment whenFindingCurrentAssignmentForAccount(Account account, AssignmentEntity assignmentEntity) {
when(assignmentQueryRepository.findFirstByAccountIdOrderByStartDateDesc(account.getId())).thenReturn(Optional.of(assignmentEntity));
return assignmentQueryService.findCurrentAssignmentForAccount(account).get();
}
private void thenCurrentAssignmentReturned(Long accountId, AssignmentEntity assignmentEntity, Assignment assignment) {
assertThat(assignment.getAccount(), hasProperty("id", is(assignmentEntity.getAccount().getId())));
assertThat(assignment, hasProperty("id", is(assignmentEntity.getId())));
verify(assignmentQueryRepository).findFirstByAccountIdOrderByStartDateDesc(accountId);
}
}
|
package com.foodaholic.interfaces;
import com.foodaholic.items.ItemCart;
import java.util.ArrayList;
public interface CartListener {
void onStart();
void onEnd(String success, String message, ArrayList<ItemCart> arrayList_menu);
}
|
import javafx.scene.control.Label;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
public class GridTiles extends Label{
private Integer SqNumber;
private Integer GridX;
private Integer GridY;
private GridTiles DestSquare=null;
private Boolean isDestSquare=false;
public GridTiles(int num, int x,int y){
super();
this.SqNumber=num;
this.fontProperty().set(Font.font("Calibri", FontWeight.BOLD, 32));
this.GridX=x;
this.GridY=y;
}
public Integer getGridX(){
return this.GridX;
}
public Integer getGridY(){
return this.GridY;
}
public Integer getSqNumber(){
return this.SqNumber;
}
public void setIsDestSquare(Boolean b){
this.isDestSquare=b;
}
public Boolean getIsDestSquare(){
return this.isDestSquare;
}
public void setDestSquare(GridTiles sq){
this.DestSquare=sq;
}
public GridTiles getDestSquare(){
return this.DestSquare;
}
} |
package aeroportSpring.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import aeroportSpring.model.Aeroport;
import aeroportSpring.model.Ville;
public interface VilleRepository extends JpaRepository<Ville, Long> {
// retourne l'objet ville dont le nom correspond au nom à renseigner
@Query("select distinct v from Ville v where nomVille=:nomVille")
public Ville findByNomVille(@Param("nomVille") String nomVille);
// retourne l'objet ville dans lequel se trouve l'aéroport à renseigner
// "member of" équivaut à un IN en SQL
@Query("select v from Ville v where :aeroport member of v.aeroports")
public Ville findByAeroport(@Param("aeroport") Aeroport aeroport);
// retourne toutes les villes qui possèdent un aéroport du nom à renseigner
@Query("select v from Ville v left join fetch v.aeroports a where a.nomAeroport=:nomAeroport")
public List<Ville> findByNomAeroport(@Param("nomAeroport") String nomAeroport);
}
|
import java.util.Arrays;
public class TheGameOfLife {
public int[][] startSimulation(int[][] matrix, int iteration){
int height = matrix.length;
int width = matrix[0].length;
int[][] result = new int[height][width];
for(int i = 0; i < iteration; i++){
simulate(matrix, result);
//swap
int[][] temp = matrix.clone();
matrix = result.clone();
result = temp.clone();
// swap(matrix, result);
}
return matrix;
}
public void simulate(int[][] matrix, int[][] result){
for(int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
//live or die
if(cellCanLive(matrix, i, j)){
result[i][j] = 1;
}else{
result[i][j] = 0;
}
}
}
}
public boolean cellCanLive(int[][] matrix, int i, int j){
//get neighbors
int aliveNeighbors = countAliveNeighbors(matrix, i, j);
if(aliveNeighbors == 3)
return true;
return matrix[i][j] == 1 && aliveNeighbors == 2;
}
public int countAliveNeighbors(int[][] matrix, int i, int j){
int count = 0;
for(int h = i-1; h <= i+1; h++){
for(int v = j-1; v <= j+1; v++){
//out of bound
if(h < 0 || h >= matrix.length || v < 0 || v >= matrix[h].length) continue;
//current cell
if(h == i && v == j) continue;
//is alive
if(matrix[h][v] == 1) count++;
}
}
return count;
}
public void swap(int[][] matrix, int[][] result){
int[][] temp = matrix.clone();
matrix = result.clone();
result = temp.clone();
}
public void printMatrix(int[][] matrix){
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
System.out.print(matrix[i][j] + " ");
if(j == matrix[i].length - 1){
System.out.println();
}
}
}
}
public static void main(String args[]){
TheGameOfLife runner = new TheGameOfLife();
int[][] matrix = {
{1, 0, 1, 0, 1},
{0, 0, 1, 0, 0},
{1, 1, 0, 1, 1},
{0, 0, 1, 0, 0},
{1, 0, 1, 0, 1},
};
int[][] result = runner.startSimulation(matrix, 3);
// int[][] result = {
// {0, 0, 0, 0, 0},
// {0, 0, 1, 0, 0},
// {0, 1, 1, 1, 0},
// {0, 0, 1, 0, 0},
// {0, 0, 0, 0, 0},
// };
// runner.swapMatrix(matrix, result, 5, 5);
runner.printMatrix(result);
// System.out.println(runner.countAliveNeighbors(testkernel1, 0, 1));
}
}
|
package beehive.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beehive.bean.Report;
import beehive.bean.User;
import beehive.dao.ReportDao;
public class DisplayAction extends HttpServlet {
private ReportDao reportDao = new ReportDao();
public DisplayAction() {
super();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
User user = (User)request.getAttribute("user");
String choice = request.getParameter("choice");
List<Report> reports = null;
if(choice == null)
reports = reportDao.getLatestReport(user.getPhone(), 30);
else if(choice.equals("latest"))
{
request.getParameter("days");
reports = reportDao.getLatestReport(user.getPhone(), 30);
}
else if(choice.equals("all"));
//reports = reportDao.getAll(user.phone);
else if(choice.equals("timed"))
{
Date start = (Date)request.getAttribute("start_time");
Date end = (Date)request.getAttribute("end_time");
reports = reportDao.getTimedReport(user.phone, start.toString(), end.toString());
}
request.setAttribute("reports", reports);
*/
List<Report> reports = getReport(request);
request.getSession().setAttribute("reports", reports);
request.setAttribute("reports", reports);
request.getRequestDispatcher("./display_page.jsp").forward(request, response);
}
private List<Report> getReport(HttpServletRequest request)
{
List<Report> reports = null;
//User user = (User) request.getSession().getAttribute("user");
User user = (User) request.getSession().getAttribute("user");
String choice = request.getParameter("choice");
String phone = user.getPhone();
if(choice == null)
reports = reportDao.getLatestReport(phone, 30);
else if(choice.equals("latest"))
{
request.getParameter("days");
reports = reportDao.getLatestReport(phone, 30);
}
else if(choice.equals("all"));
//reports = reportDao.getAll(user.phone);
else if(choice.equals("timed"))
{
Date start = (Date)request.getAttribute("start_time");
Date end = (Date)request.getAttribute("end_time");
reports = reportDao.getTimedReport(phone, start.toString(), end.toString());
}
return reports;
}
}
|
package uz.pdp.lesson5task1.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import uz.pdp.lesson5task1.entity.template.AbsEntity;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import java.util.UUID;
@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@Entity
public class Turnikit extends AbsEntity {
@ManyToOne
private Company company;
@OneToOne
private User owner;
private String uniqueNumber= UUID.randomUUID().toString();
}
|
package com.aidigame.hisun.imengstar.view;
import com.aidigame.hisun.imengstar.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class CircleView extends ImageView {
int w;
public CircleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CircleView(Context context) {
super(context);
init();
}
private Bitmap bitmap;
private Rect bitmapRect = new Rect();
private PaintFlagsDrawFilter pdf = new PaintFlagsDrawFilter(0,
Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private Paint paint = new Paint();
{
paint.setStyle(Paint.Style.STROKE);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);// 反锯齿效果
}
private Bitmap mDstB = null;
private PorterDuffXfermode xfermode = new PorterDuffXfermode(
PorterDuff.Mode.MULTIPLY);
private void init() {
try {
if (android.os.Build.VERSION.SDK_INT >= 11) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
mDstB = makeDst(getMeasuredWidth(), getMeasuredHeight());
}
public void setImageBitmap(Bitmap path) {
this.bitmap=path;
invalidate();
}
private Bitmap makeDst(int w, int h) {
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.parseColor("#ffffffff"));
c.drawOval(new RectF(0, 0, w, h), p);
return bm;
}
@Override
protected void onDraw(Canvas canvas) {
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=8;
if (null == bitmap) {
options.inSampleSize=1;
bitmap = BitmapFactory
.decodeResource(getResources(), R.drawable.pet_icon,options);
}
if (null == mDstB) {
mDstB = makeDst(getMeasuredWidth(), getMeasuredHeight());
}
bitmapRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
canvas.save();
canvas.setDrawFilter(pdf);
canvas.drawBitmap(mDstB, 0, 0, paint);
this.w=w;
paint.setXfermode(xfermode);
if(bitmap!=null)
canvas.drawBitmap(bitmap, null, bitmapRect, paint);
paint.setXfermode(null);
canvas.restore();
}
/**
* 获取裁剪后的圆形图片
*
* @param radius
* 半径
*/
public Bitmap getCroppedRoundBitmap(Bitmap bmp) {
if(bmp==null||w<=0)return null;
int radius=w/2;
Bitmap scaledSrcBmp;
int diameter = radius * 2;
// 为了防止宽高不相等,造成圆形图片变形,因此截取长方形中处于中间位置最大的正方形图片
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
int squareWidth = 0, squareHeight = 0;
int x = 0, y = 0;
Bitmap squareBitmap;
if (bmpHeight > bmpWidth) {// 高大于宽
squareWidth = squareHeight = bmpWidth;
x = 0;
y = (bmpHeight - bmpWidth) / 2;
// 截取正方形图片
squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
squareHeight);
} else if (bmpHeight < bmpWidth) {// 宽大于高
squareWidth = squareHeight = bmpHeight;
x = (bmpWidth - bmpHeight) / 2;
y = 0;
squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
squareHeight);
} else {
squareBitmap = bmp;
}
if (squareBitmap.getWidth() != diameter
|| squareBitmap.getHeight() != diameter) {
scaledSrcBmp = Bitmap.createScaledBitmap(squareBitmap, diameter,
diameter, true);
} else {
scaledSrcBmp = squareBitmap;
}
Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(),
scaledSrcBmp.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(),
scaledSrcBmp.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(scaledSrcBmp.getWidth() / 2,
scaledSrcBmp.getHeight() / 2, scaledSrcBmp.getWidth() / 2,
paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(scaledSrcBmp, rect, rect, paint);
// bitmap回收(recycle导致在布局文件XML看不到效果)
// bmp.recycle();
// squareBitmap.recycle();
// scaledSrcBmp.recycle();
bmp = null;
squareBitmap = null;
scaledSrcBmp = null;
return output;
}
}
|
package cn.edu.zzti.lm.view.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cn.edu.zzti.lm.R;
import cn.edu.zzti.lm.net.VollleyUtil;
import cn.edu.zzti.lm.pojo.Book;
import cn.edu.zzti.lm.recyclerView.adapter.BookAdapter;
import cn.edu.zzti.lm.recyclerView.adapter.BookAdapterForThree;
import cn.edu.zzti.lm.recyclerView.adapter.MyItemClickListener;
public class MoreBookActivity extends AppCompatActivity {
//recyclerView列表
private RecyclerView moreBookRV;
//书籍数据集合
private List<Book> bookList;
private ActionBar actionBar;
//访问的链接
private String url;
//读数据对象
private SharedPreferences preference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_more_book);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//获取ActionBar
actionBar = getSupportActionBar();
// 设置不显示左侧图标
actionBar.setDisplayShowHomeEnabled(false);
//将默认标题置空
actionBar.setTitle("");
//显示App icon左侧的back键
actionBar.setDisplayHomeAsUpEnabled(true);
//获取其他Activity传递过来的Intent
Intent intent = getIntent();
String pagemName = intent.getStringExtra("paramName");
//实例化,获取只能被本应用读写的对象“MODE_PRIVATE”
preference = getSharedPreferences("MLData", Context.MODE_PRIVATE);
//获取用户帐号
String customerCode = preference.getString("account", "");
//修改actionBar
if (pagemName.equals("hot")) {
actionBar.setTitle("热门精选");
//查询图书,实际要吧请求参数传递过去
url = getString(R.string.serverUrl) +
"/MLtest1/book/findBookOrderByBrowseNum.action";
} else if (pagemName.equals("preson")) {
actionBar.setTitle("个性推荐");
url = getString(R.string.serverUrl) +
"/MLtest1/collecting/findBookByCollecting.action?customerCode="+customerCode;
} else if (pagemName.equals("newbook")) {
actionBar.setTitle("新书推荐");
url = getString(R.string.serverUrl) +
"/MLtest1/book/findBookOrderByPublicationTime.action";
}
//实例化控件
moreBookRV = (RecyclerView) findViewById(R.id.moreBookRV);
//实例化集合
bookList = new ArrayList<Book>();
//为recyclerView设置布局
LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
layoutManager1.setOrientation(RecyclerView.VERTICAL);
moreBookRV.setLayoutManager(layoutManager1);
}
@Override
public void onResume() {
super.onResume();
//刷新界面,图书列表置空
bookList.clear();
queryBook(url);
}
/**
* 查询数据
* @param url
*/
public void queryBook(String url) {
//使用Volley框架发送请求
RequestQueue requestQueue = Volley.newRequestQueue(this);
//设置请求对象
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
/**
* 请求成时,方法回调
* @param response
*/
@Override
public void onResponse(JSONObject response) {
System.out.println(response);
Log.e("response", response.toString());
//封装数据
JSONArray jsonBooks = response.optJSONArray("books");
for (int i = 0; i < jsonBooks.length(); i++) {
Book book = new Book();
JSONObject bookJson = jsonBooks.optJSONObject(i).optJSONObject("book");
book.setId(bookJson.optString("id"));
book.setBookname(bookJson.optString("bookname"));
book.setAuthor(bookJson.optString("author"));
book.setPublisher(bookJson.optString("publisher"));
book.setPublicationTime(bookJson.optString("publicationTime"));
book.setPicture(bookJson.optString("picture"));
book.setPages(bookJson.optString("pages"));
book.setLocation(bookJson.optString("location"));
book.setTotal(bookJson.optString("total"));
book.setRemain(bookJson.optString("remain"));
book.setSummay(bookJson.optString("summay"));
book.setIntroduction(bookJson.optString("introduction"));
book.setContent(bookJson.optString("content"));
book.setBrowseNum(bookJson.optString("browseNum"));
book.setPurchasePrice(bookJson.optString("purchasePrice"));
book.setPrice(bookJson.optString("price"));
book.setRemarks(bookJson.optString("remarks"));
book.setCategory(jsonBooks.optJSONObject(i).optString("category"));
bookList.add(book);
}
//创建图书的适配器
BookAdapter bookAdapter = new BookAdapter(bookList, MoreBookActivity.this);
//为recyclerView指定适配器
moreBookRV.setAdapter(bookAdapter);
bookAdapter.setItemClickListener(new MyItemClickListener() {
@Override
public void onItemClick(View view, int position) {
TextView textView = (TextView) view.findViewById(R.id.bookId);
String bookId = textView.getText().toString();
//System.out.println(bookId);
//定义一个Intent对象
Intent intent = new Intent(MoreBookActivity.this, BookInfoActivity.class);
//传递简单数据类型
intent.putExtra("bookId", bookId);
//启动另一个Activity
startActivity(intent);
}
});
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("MLlog", "响应结果:" + error);
}
});
//设置添加请求对象
requestQueue.add(jsonObjectRequest);
}
//为返回键按钮绑定事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package cn.edu.ncu.collegesecondhand.entity;
import android.net.Uri;
import java.io.Serializable;
/**
* Created by ren lingyun on 2020/4/24 16:56
*/
public class ReleaseImage implements Serializable {
private String localPath;
private Uri uri;
private String uuid;//
private String netPath;
private int imageCount;//
public ReleaseImage() {
}
public ReleaseImage(String localPath, Uri uri, String uuid, String netPath, int imageCount) {
this.localPath = localPath;
this.uri = uri;
this.uuid = uuid;
this.netPath = netPath;
this.imageCount = imageCount;
}
public ReleaseImage(String netPath) {
this.netPath = netPath;
}
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getNetPath() {
return netPath;
}
public void setNetPath(String netPath) {
this.netPath = netPath;
}
public int getImageCount() {
return imageCount;
}
public void setImageCount(int imageCount) {
this.imageCount = imageCount;
}
}
|
package exception.returnException;/**
* Created by DELL on 2018/8/14.
*/
/**
* user is
**/
public class Person {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package exam.iz0_803;
public class Exam_047 {
}
/*
Given a code fragment:
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
String h1 = "HelloWorld";
sb.append("Hello").append("World");
if (h1 == sb.toString()) {
System.out.println("They match");
}
if (sb.equals(h1)) {
System.out.println("They really match");
}
System.out.println("AA");
}
What is the result?
A. They match
They really match
B. They really match
C. They match
D. Nothing is printed to the screen
Answer: D
*/
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vootoo.logging.logback;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import org.apache.solr.logging.LogWatcher;
public class LogbackEventAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private final LogWatcher<ILoggingEvent> watcher;
private final ThresholdFilter thresholdFilter = new ThresholdFilter();
private String threshold;
public LogbackEventAppender(LogWatcher<ILoggingEvent> framework) {
this.watcher = framework;
addFilter(thresholdFilter);
}
@Override
protected void append(ILoggingEvent eventObject) {
watcher.add(eventObject, eventObject.getTimeStamp());
}
@Override
public void start() {
thresholdFilter.start();
super.start();
}
@Override
public void stop() {
watcher.reset();
super.stop();
thresholdFilter.stop();
}
public String getThreshold() {
return threshold;
}
public void setThreshold(String level) {
thresholdFilter.setLevel(level);
threshold = level;
}
}
|
package com.catalyseit;
import java.util.List;
class Agreement {
private String name;
private String callbackUrl;
private List<EstRecipient> recipients;
private Boolean autoSendMailsEnabled;
public Agreement(String name, String callbackUrl, List<EstRecipient> recipients, Boolean autoSendMailsEnabled) {
setName(name);
setCallbackUrl(callbackUrl);
setRecipients(recipients);
setAutoSendMailsEnabled(autoSendMailsEnabled);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public List<EstRecipient> getRecipients() {
return recipients;
}
public void setRecipients(List<EstRecipient> recipients) {
this.recipients = recipients;
}
public Boolean getAutoSendMailsEnabled() {
return autoSendMailsEnabled;
}
public void setAutoSendMailsEnabled(Boolean autoSendMailsEnabled) {
this.autoSendMailsEnabled = autoSendMailsEnabled;
}
}
|
package com.sunny.concurrent.volatilekey;
/**
* <Description> <br>
*
* @author Sunny<br>
* @version 1.0<br>
* @taskId: <br>
* @createDate 2019/02/18 23:06 <br>
* @see com.sunny.concurrent.volatilekey <br>
*/
public class VolatileTest {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (count == 0) {}
}).start();
Thread.sleep(1000);
count = 1;
}
}
|
package kr.co.shop.batch.giftcard.model.master;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import kr.co.shop.batch.giftcard.model.master.base.BaseRvGiftCardComparison;
import kr.co.shop.interfaces.module.payment.nice.NiceGiftUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class RvGiftCardComparison extends BaseRvGiftCardComparison {
public RvGiftCardComparison() {
}
public RvGiftCardComparison(String niceServiceType, String line) {
this.setNiceServiceType(niceServiceType);
log.debug("### niceServiceType: {}", niceServiceType);
this.setProtoGb(line.substring(0, 1));
log.debug("protoGb: {}", line.substring(0, 1).trim());
this.setUpdatecode(line.substring(1, 3));
log.debug("updateCode: {}", line.substring(1, 3).trim());
this.setTranDt(line.substring(3, 11));
log.debug("tranDt: {}", line.substring(3, 11).trim());
this.setTranHms(line.substring(11, 17));
log.debug("tranHms: {}", line.substring(11, 17).trim());
this.setSalesDt(line.substring(17, 25));
log.debug("saleDt: {}", line.substring(17, 25).trim());
this.setCatid(line.substring(25, 35));
log.debug("catId: {}", line.substring(25, 35).trim());
this.setStoreCd(line.substring(35, 41));
log.debug("storeCd: {}", line.substring(35, 41).trim());
this.setSalerCode(line.substring(41, 45));
log.debug("salerCode: {}", line.substring(41, 45).trim());
this.setEventCode(line.substring(45, 55));
log.debug("eventCode: {}", line.substring(45, 55).trim());
this.setVoucherFrom(line.substring(55, 71));
log.debug("voucherFrom: {}", line.substring(55, 71).trim());
if ("0216".equals(niceServiceType)) {
this.setVoucherTo(line.substring(71, 87));
log.debug("voucherTo: {}", line.substring(71, 87).trim());
this.setBarcodeFrom(line.substring(87, 100));
log.debug("barcodeFrom: {}", line.substring(87, 100).trim());
this.setBarcodeTo(line.substring(100, 113));
log.debug("barcodeTo: {}", line.substring(100, 113).trim());
this.setTranKd(line.substring(113, 115));
log.debug("tranKd: {}", line.substring(113, 115).trim());
this.setTransStatus(line.substring(115, 117));
log.debug("transStatus: {}", line.substring(115, 117).trim());
this.setTranType(line.substring(117, 119));
log.debug("tranType: {}", line.substring(117, 119));
this.setPurchaseAmt(Integer.parseInt(line.substring(119, 131)));
log.debug("purchaseAmt: {}", Integer.parseInt(line.substring(119, 131)));
this.setTranAmt(Integer.parseInt(line.substring(131, 143)));
log.debug("tranAmt: {}", Integer.parseInt(line.substring(131, 143)));
this.setSalerKind(line.substring(143, 145));
log.debug("salerKind: {}", line.substring(143, 145).trim());
this.setReturnType(line.substring(145, 147));
log.debug("returnType: {}", line.substring(145, 147).trim());
this.setApprNo(line.substring(147, 155));
log.debug("apprNo: {}", line.substring(147, 155).trim());
this.setOriApprDt(line.substring(155, 163));
log.debug("oriApprDt: {}", line.substring(155, 163).trim());
this.setOriApprNo(line.substring(163, 171));
log.debug("oriApprNo: {}", line.substring(163, 171).trim());
this.setPosNo(line.substring(171, 177));
log.debug("posNo: {}", line.substring(171, 177).trim());
this.setCasherNo(line.substring(177, 184));
log.debug("cacherNo: {}", line.substring(177, 184).trim());
this.setReceipptNo(line.substring(184, 188));
log.debug("receippNo: {}", line.substring(184, 188).trim());
this.setCustId(line.substring(188, 204));
log.debug("custId: {}", line.substring(188, 204).trim());
this.setImgCd(line.substring(204, 214));
log.debug("imgCd: {}", line.substring(204, 214).trim());
this.setIssCd(line.substring(214, 216));
log.debug("issCd: {}", line.substring(214, 216).trim());
this.setPayCd(line.substring(216, 218));
log.debug("payCd: {}", line.substring(216, 218).trim());
this.setCompanyInfo(line.substring(218, 268));
log.debug("companyInfo: {}", line.substring(218, 268).trim());
this.setFiller(line.substring(268, 299));
log.debug("filler: {}", line.substring(268, 299).trim());
} else {
this.setTranKd(line.substring(71, 73));
log.debug("tranKd: {}", line.substring(71, 73).trim());
this.setTransStatus(line.substring(73, 75));
log.debug("transStatus: {}", line.substring(73, 75).trim());
this.setTranType(line.substring(75, 77));
log.debug("tranType: {}", line.substring(75, 77));
this.setPurchaseAmt(Integer.parseInt(NiceGiftUtil.isNullZeroFill(line.substring(77, 89))));
log.debug("purchaseAmt: {}", Integer.parseInt(NiceGiftUtil.isNullZeroFill(line.substring(77, 89))));
this.setTranAmt(Integer.parseInt(NiceGiftUtil.isNullZeroFill(line.substring(89, 101))));
log.debug("tranAmt: {}", Integer.parseInt(NiceGiftUtil.isNullZeroFill(line.substring(89, 101))));
this.setSalerKind(line.substring(101, 103));
log.debug("salerKind: {}", line.substring(101, 103).trim());
this.setReturnType(line.substring(103, 105));
log.debug("returnType: {}", line.substring(103, 105).trim());
this.setApprNo(line.substring(105, 113));
log.debug("apprNo: {}", line.substring(105, 113).trim());
this.setOriApprDt(line.substring(113, 121));
log.debug("oriApprDt: {}", line.substring(113, 121).trim());
this.setOriApprNo(line.substring(121, 129));
log.debug("oriApprNo: {}", line.substring(121, 129).trim());
this.setPosNo(line.substring(129, 135));
log.debug("posNo: {}", line.substring(129, 135).trim());
this.setCasherNo(line.substring(135, 142));
log.debug("cacherNo: {}", line.substring(135, 142).trim());
this.setReceipptNo(line.substring(142, 146));
log.debug("receippNo: {}", line.substring(142, 146).trim());
this.setCustId(line.substring(146, 162));
log.debug("custId: {}", line.substring(146, 162).trim());
this.setImgCd(line.substring(162, 172));
log.debug("imgCd: {}", line.substring(162, 172).trim());
this.setIssCd(line.substring(172, 174));
log.debug("issCd: {}", line.substring(172, 174).trim());
this.setCompanyInfo(line.substring(174, 224));
log.debug("companyInfo: {}", line.substring(174, 224).trim());
}
// this.setLf(line.substring(299));
// convertObj();
}
public static List<RvGiftCardComparison> readPerformanceFile(String niceServiceType) {
// 결과
List<RvGiftCardComparison> result = new ArrayList<>();
try {
// 파일 객체 생성
File file = null;
if ("0215".equals(niceServiceType)) {
file = new File("D:\\performanceData\\OC01_1~1.DAT");
} else if ("0216".equals(niceServiceType)) {
file = new File("D:\\performanceData\\OS01_1~1.DAT");
}
// 입력 스트림 생성
FileReader filereader = new FileReader(file);
// 입력 버퍼 생성
BufferedReader bufReader = new BufferedReader(filereader);
String line = "";
while ((line = bufReader.readLine()) != null) {
// System.out.println(line);
// log.debug("### readLine: {}", line);
RvGiftCardComparison rvGiftCardComparison = new RvGiftCardComparison(niceServiceType, line);
rvGiftCardComparison.setMapngDtm("N");
result.add(rvGiftCardComparison);
}
// .readLine()은 끝에 개행문자를 읽지 않는다.
bufReader.close();
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
|
package com.lfalch.korome;
/**
* @author LFalch
*
*/
public class CircularBody {
protected Vector position;
protected double theta, radius;
public CircularBody(double angle, double x, double y, double radius) {
theta = angle;
position = new Vector(x, y);
this.radius = radius;
}
public void setPosition(Vector pos){
position = pos;
}
public Vector getPosition(){
return position;
}
public static boolean collide(CircularBody a, CircularBody b){
return a.getDistance(b) < a.radius + b.radius;
}
public static double collision(CircularBody a, CircularBody b){
return a.getDistance(b) - (a.radius + b.radius);
}
public double getDistance(CircularBody other){
return this.getPosition().getDistance(other.getPosition());
}
public double getDirection(CircularBody other) {
return this.getPosition().getDirectionTowards(other.getPosition());
}
}
|
package jp.ac.it_college.std.s14011.pdp.observer;
/**
* Created by s14011 on 15/06/16.
*/
public interface Observer {
public abstract void update(NumberGenerator generator);
}
|
package com.sundar.shopping.dialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.sundar.shopping.R;
import com.tuyenmonkey.mkloader.MKLoader;
public class CustomLoader extends Dialog {
// Animation aniRotate;
private CustomLoader d;
// private ImageView loader;
private MKLoader progress_bar;
public CustomLoader(@NonNull Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_custom_loader);
// loader = findViewById(R.id.loader);
// progress_bar = findViewById(R.id.progress_bar);
// aniRotate = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_clockwise);
// loader.startAnimation(aniRotate);
d = CustomLoader.this;
d.setCancelable(false);
}
@Override
public void show() {
super.show();
}
@Override
public void hide() {
super.hide();
// loader.clearAnimation();
}
@Override
protected void onStop() {
super.onStop();
// loader.clearAnimation();
}
@Override
public void onBackPressed() {
super.onBackPressed();
dismiss();
}
}
|
package com.synclab.Challenginator.microservice.challenge.challenge;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
/*
Definizione della Challenge
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Entity
public class Challenge {
@Id //PK
@SequenceGenerator(
name = "challenge_sequence",
sequenceName = "challenge_sequence",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "challenge_sequence")
private Long id;
private LocalDateTime timestamp_creation;
private Long challenger; //sfidante
private Long challenged; //sfidato
private String title;
private String description;
private Long deadline;
@Enumerated(EnumType.STRING)
private ChallengeStatus status;
private LocalDateTime timestamp_acceptance;
private Long evaluator;
@Enumerated(EnumType.STRING)
private ChallengeResult result;
public Challenge(LocalDateTime timestamp_creation,
Long idChallenger,
Long idChallenged,
String title,
String description,
Long deadline,
ChallengeStatus status,
Long evaluator) {
this.timestamp_creation = timestamp_creation;
this.challenger = idChallenger;
this.challenged = idChallenged;
this.title = title;
this.description = description;
this.deadline = deadline;
this.status = status;
this.evaluator = evaluator;
}
}
|
package com.mediafire.sdk.api.responses;
/**
* Created by Chris on 1/19/2015.
*/
public class NotificationsSendMessageResponse extends ApiResponse {
}
|
package com.dodoca.create_image.utils;
import com.dodoca.create_image.constants.ActivityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import static com.dodoca.create_image.constants.ActivityType.PINTUAN;
import static com.dodoca.create_image.constants.ActivityType.SECKILL;
/**
* @description: 处理图片和成
* @author: tianguanghui
* @create: 2019-07-03 13:30
**/
public class BufferedImageUtil {
private static final Logger logger = LoggerFactory.getLogger(BufferedImageUtil.class);
public static String overlapImage(String weChatAvatarPath, String goodsImagePath,
String qrCodePath, String message01, String message02, String goodsTile,
String goodsPrice, String outPutPath, String activity) throws IOException {
//创建一个不带透明色的对象作为背景图
BufferedImage background = new BufferedImage(600, 950, BufferedImage.TYPE_INT_RGB);
//读取微信头像图片到内存
BufferedImage weChatAvatarBufferedImage = getBufferedImageByPath(weChatAvatarPath);
BufferedImage weChatAvatar1 = resizeImage(100, 100, weChatAvatarBufferedImage);
BufferedImage weChatAvatar = transferImgForRoundImage(false, weChatAvatar1);
//读取商品图片
BufferedImage goodsImageBufferedImage = getBufferedImageByPath(goodsImagePath);
BufferedImage goodsImage = resizeImage(580, 580, goodsImageBufferedImage);
//读取二维码图片到内存
BufferedImage qrCodeBufferedImage = getBufferedImageByPath(qrCodePath);
BufferedImage qrCode = resizeImage(132, 132, qrCodeBufferedImage);
Graphics2D g = background.createGraphics();
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setBackground(Color.WHITE);
g.fillRect(0, 0, background.getWidth(), background.getHeight());
int directAxis = 11;
g.drawImage(goodsImage, 10, directAxis, goodsImage.getWidth(), goodsImage.getHeight(), null);
directAxis += goodsImage.getHeight();
g.setColor(Color.black);
g.setFont(new Font("宋体", Font.PLAIN, 28));
directAxis += 38;
if (goodsTile.length() >= 22) {
String subTile1 = goodsTile.substring(0, 22);
String subTile2 = goodsTile.substring(22);
g.drawString(subTile1, 22, directAxis);
directAxis += 38;
g.drawString(subTile2, 22, directAxis);
}else {
g.drawString(goodsTile, 22, directAxis);
}
directAxis += 45;
g.setFont(new Font("微软雅黑", Font.PLAIN, 32));
g.setColor(Color.RED);
g.drawString(goodsPrice, 20, directAxis);
directAxis += 10;
if (activity != null) {
BufferedImage activityImage;
String basePath = ResourceUtils.getURL("classpath:").getPath();
logger.info("basePath : " + basePath);
switch (activity){
case SECKILL :
activityImage = getBufferedImageByPath(basePath + "static/images/miaosha.png");
break;
case PINTUAN :
activityImage = getBufferedImageByPath(basePath + "static/images/pintuan.png");
break;
default:
activityImage = null;
}
if (activityImage != null) {
g.drawImage(activityImage, 20 , directAxis, activityImage.getWidth(), activityImage.getHeight(), null);
}
}
//二维码具体顶端的距离
directAxis = 746;
g.drawImage(weChatAvatar, 24, directAxis + 30, weChatAvatar.getWidth(), weChatAvatar.getHeight(), null);
g.setFont(new Font("宋体", Font.PLAIN, 28));
g.setColor(Color.black);
g.drawString(message01, 44 + weChatAvatar.getWidth(), directAxis + 24 + weChatAvatar.getHeight()/2);
g.setFont(new Font("宋体", Font.PLAIN, 24));
g.setColor(Color.gray);
g.drawString(message02, 44 + weChatAvatar.getWidth(), directAxis + 59 + weChatAvatar.getHeight()/2);
g.drawImage(qrCode, 426, directAxis, qrCode.getWidth(), qrCode.getHeight(), null);
directAxis += qrCode.getHeight();
g.setFont(new Font("宋体", Font.PLAIN, 22));
g.drawString("长按识别二维码", 415, directAxis + 30);
g.dispose();
ImageIO.write(background, "jpg", new File(outPutPath));
return outPutPath;
}
public static BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
//创建一个不带透明色的对象
BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
//获得在图像上绘图的Graphics对象
bufferedImage.getGraphics().drawImage(
bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
return bufferedImage;
}
/**
* 导入本地图片到缓冲区
*
* @param imgPath
* @return
*/
public static BufferedImage loadImageLocal(String imgPath) throws IOException {
return ImageIO.read(new File(imgPath));
}
/**
* 导入网络图片到缓冲区
*
* @param imgName
* @return
*/
public static BufferedImage loadImageUrl(String imgName) throws IOException {
URL url = new URL(imgName);
return ImageIO.read(url);
}
/**
* 将方形图片转换为圆形
* @param bi 图片地址
* @return
* @throws IOException
*/
public static BufferedImage transferImgForRoundImage(boolean isBlank, BufferedImage bi) throws IOException {
// 创建一个带透明色的BufferedImage
BufferedImage image = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
// 创建一个椭圆形的2D图像
Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi.getWidth(), bi.getHeight());
Graphics2D g2 = image.createGraphics();
//控制内切圆外的区域颜色为黑色
if (isBlank) {
g2.setComposite(AlphaComposite.Clear);
}
//设置背景为白色
g2.setBackground(Color.WHITE);
g2.fillRect(0, 0, image.getWidth(), image.getHeight());
g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
g2.setClip(shape);
// 抗锯齿
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawImage(bi, 0, 0, null);
g2.dispose();
return image;
}
/**
* 根据图片全路径 加载图片
* @param imagePath 图片全路径
* @return
* @throws IOException
*/
public static BufferedImage getBufferedImageByPath(String imagePath) throws IOException {
if (imagePath.startsWith("http")) {
return loadImageUrl(imagePath);
}
return loadImageLocal(imagePath);
}
public static void main(String[] args) throws FileNotFoundException {
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
String path2 = ResourceUtils.getURL("classpath:").getPath();
System.out.println("path: " + path);
System.out.println("path2: " + path2);
}
}
|
package xtrus.ex.mci.server;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.common.compress.lzc.LZCInputStream;
import com.esum.framework.common.compress.lzc.LZCOutputStream;
import com.esum.framework.common.util.DateUtil;
import com.esum.framework.common.util.FileUtil;
import com.esum.framework.common.util.SysUtil;
import xtrus.ex.mci.ExMciConfig;
import xtrus.ex.mci.ExMciException;
import xtrus.ex.mci.Utils;
import xtrus.ex.mci.message.MciMessage;
import xtrus.ex.mci.message.Message;
import xtrus.ex.mci.message.NonStdMciMessage;
import xtrus.ex.mci.message.StdMciMessage;
public class MciMessageUtils {
public static Logger logger = LoggerFactory.getLogger(MciMessageUtils.class);
/**
* MCI를 통해 수신한 파일 데이터는 압축되어 있으므로, 특정 디렉토리(ExMciConfig.FILE_RECV_DIRECTORY)에 압축을 풀도록 한다.
* uncompress가 성공적으로 되면 원본 파일은 삭제한다.
*/
public static void extractFile(String filename) throws IOException {
File sourceFile = new File(SysUtil.replacePropertyToValue("${xtrus.home}/repository/exmci"), filename);
File extractDir = new File(SysUtil.replacePropertyToValue(ExMciConfig.FILE_RECV_DIRECTORY));
if(!extractDir.exists())
extractDir.mkdirs();
File extractFile = new File(extractDir, filename);
// Uncompress
byte[] orgBytes = FileUtil.readToByte(sourceFile);
FileUtil.writeToFile(extractFile, uncompress(orgBytes));
// remove original file
FileUtil.deleteQuietly(sourceFile);
logger.info("Compressed File extracted successfully to "+extractDir.getAbsolutePath()+", filename : "+filename);
}
private static MciMessage createNonStdMciResponseMessage(NonStdMciMessage message, String errorCode) throws ExMciException {
if(errorCode!=null)
message.setResponseCode(Message.NON_STD_RESPONSE_T);
return message;
}
private static MciMessage createStdMciResponseMessage(StdMciMessage message, String errorCode) throws ExMciException {
message.setMessageType(Message.MESSAGE_TYPE_R);
if(message.getTradeType().equals(Message.TRADE_F)) {
long total = Long.parseLong(message.getTotalFileSize());
long offset = Long.parseLong(message.getFileOffset());
long size = Long.parseLong(message.getFileSize());
if(total==(offset+size))
message.setSyncType(Message.SYNC_TYPE_S);
else
message.setSyncType(Message.SYNC_TYPE_A);
} else {
message.setSyncType(Message.SYNC_TYPE_S);
}
message.setAcknowledgeDate(DateUtil.getCYMDHMS());
if (errorCode != null) {
message.setHandlingResultCode(Message.HANDLING_RESULT_E);
message.setErrorSystemCode(ExMciConfig.DEFAULT_SYSTEM_CODE); // 표준연계서버코드
message.setErrorCode(Utils.writeToString(errorCode, 10));
} else {
message.setHandlingResultCode(Message.HANDLING_RESULT_N);
message.setErrorSystemCode(" ");
message.setErrorCode(Utils.writeToString(" ", 10));
}
message.setAcknowledgeTypeCode("1"); // 고정
message.setContinueNo(0); // 고정
return message;
}
/**
* 표준 응답 메시지를 생성한다.
*/
public static byte[] createResponseMessage(MciMessage message, ExMciException exception) throws ExMciException {
MciMessage respMessage = null;
if(message.getType().equals(Message.STANDARD_TYPE)) {
respMessage = createStdMciResponseMessage((StdMciMessage)message,
exception!=null?exception.getErrorCode():null);
} else {
respMessage = createNonStdMciResponseMessage((NonStdMciMessage)message,
exception!=null?exception.getErrorCode():null);
}
return respMessage.unmarshal();
}
public static byte[] compress(byte[] message) throws IOException {
ByteArrayInputStream in = null;
ByteArrayOutputStream out = null;
LZCOutputStream lzwOut = null;
try {
in = new ByteArrayInputStream(message);
out = new ByteArrayOutputStream();
lzwOut = new LZCOutputStream(out);
lzwOut.setNoHeader(); // no magic header
byte[] buffer = new byte[128];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) >= 0) {
lzwOut.write(buffer, 0, bytesRead);
}
lzwOut.flush();
lzwOut.end();
return out.toByteArray();
} catch (Exception e) {
return message;
} finally {
IOUtils.closeQuietly(lzwOut);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
public static byte[] uncompress(byte[] message) throws IOException {
ByteArrayInputStream in = null;
ByteArrayOutputStream out = null;
LZCInputStream lzwIn = null;
try {
in = new ByteArrayInputStream(message);
out = new ByteArrayOutputStream();
lzwIn = new LZCInputStream(in);
lzwIn.setNoHeader();
byte[] buffer = new byte[128];
int bytesRead;
while ((bytesRead = lzwIn.read(buffer)) >= 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
return out.toByteArray();
} catch (Exception e) {
return message;
} finally {
IOUtils.closeQuietly(lzwIn);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
/**
* 전문 처리시 오류가 발생하면 오류 정보를 Logging하기 위해 LoggingEvent를 생성하고, 이를 채널로 전송한다.
*
* @param exception 발생한 Exception정보.
* @param rawData 원본 데이터.
*/
// public static void processError(ExMciException exception, byte[] rawData) {
// String messageId = MessageIDGenerator.generateMessageID();
// try {
// String senderTpId = "unknown";
// String recverTpId = "unknown";
//
// if(rawData!=null && rawData.length>52) {
// byte[] senderCode = new byte[6];
// byte[] recverCode = new byte[6];
// System.arraycopy(rawData, 40, senderCode, 0, 6);
// System.arraycopy(rawData, 46, recverCode, 0, 6);
//
// senderTpId = new String(senderCode);
// recverTpId = new String(recverCode);
// }
//
// ExMciInboundHandler handler = new ExMciInboundHandler(ExMciConfig.MODULE_NAME,
// messageId,
// rawData==null?null:rawData,
// null);
// handler.sendError(senderTpId, recverTpId, exception);
//
// logger.error("["+messageId+"] Inbound message processing failed. ");
// logger.error("ErrorCode : "+exception.getErrorCode()+", ErrorDesc : "+exception.getErrorMessage());
// } catch (Exception e) {
// logger.error("Error Logging processing failed.", e);
// }
// }
}
|
package com.coder.form;
import java.util.List;
import com.coder.model.FoodGroup;
import com.coder.model.PaymentMethod;
public class PaymentMethodRegisterForm {
private PaymentMethodForm paymentMethodForm=null;
private PaymentMethod paymentMethod;
private List<PaymentMethod> paymentMethods;
public PaymentMethodForm getPaymentMethodForm() {
return paymentMethodForm;
}
public void setPaymentMethodForm(PaymentMethodForm paymentMethodForm) {
this.paymentMethodForm = paymentMethodForm;
}
public PaymentMethod getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
public List<PaymentMethod> getPaymentMethods() {
return paymentMethods;
}
public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
this.paymentMethods = paymentMethods;
}
}
|
package business;
public class Operations {
public String add(int n1,int n2)
{
int sum=n1+n2;
return String.valueOf(sum);
}
public String sub(int n1,int n2)
{
int diff=n1-n2;
return String.valueOf(diff);
}
public String mul(int n1,int n2)
{
int res=n1*n2;
return String.valueOf(res);
}
public String div(int n1,int n2)
{
float dividend=n1/n2;
return String.valueOf(dividend);
}
}
|
package model;
import java.util.ArrayList;
/**
* Created by Joe on 7/17/2015.
*/
public class Seller {
private String username;
private String password;
private String email;
private String telephone;
private String store_name;
private String store_icon_url;
private String introduction;
private String latitude;
private String longitude;
private String Audio_url;
private int store_type;
private ArrayList<Product> products;
public Seller(){
}
public Seller(String username, String password, String email, String telephone, String store_name,
String store_icon_url, String introduction, String Audio_url, int store_type, String latitude, String longitutde){
this.username = username;
this.password = password;
this.email = email;
this.telephone = telephone;
this.store_name = store_name;
this.store_icon_url = store_icon_url;
this.introduction = introduction;
this.Audio_url = Audio_url;
this.store_type = store_type;
this.products = new ArrayList<Product>();
this.latitude = latitude;
this.longitude = longitutde;
}
public void setters(String username, String password, String email, String telephone, String store_name,
String store_icon_url, String introduction, String Audio_url, int store_type,
String latitude, String longitutde){
this.username = username;
this.password = password;
this.email = email;
this.telephone = telephone;
this.store_name = store_name;
this.store_icon_url = store_icon_url;
this.introduction = introduction;
this.Audio_url = Audio_url;
this.store_type = store_type;
this.latitude = latitude;
this.longitude = longitutde;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
public String getEmail(){
return email;
}
public String getTelephone(){
return telephone;
}
public String getStore_name(){
return store_name;
}
public String getStore_icon_url(){
return store_icon_url;
}
public String get_latitude(){
return latitude;
}
public String get_longitude(){
return longitude;
}
public String getIntroduction(){
return introduction;
}
public int getStore_type(){
return store_type;
}
public ArrayList<Product> getProducts(){
return products;
}
public void Add_a_product(Product product){
products.add(product);
};
public boolean Delete_a_product(String name){
for(int i=0;i<products.size();i++){
if(name.equals(products.get(i).getName())){
products.remove(i);
return true;
}
}
return false;
}
public String toString(){
String seller = "";
seller += "username:" + username + "\n";
seller += "password:" + password + "\n";
seller += "email:" + email + "\n";
seller += "telephone:" + telephone + "\n";
seller += "store_name:" + store_name + "\n";
seller += "store_icon_url:" + store_icon_url + "\n";
seller += "introduction:" + introduction + "\n";
seller += "Audio_url:" + Audio_url + "\n";
seller += "store_type:" + store_type + "\n";
seller += "latitude:" + latitude + "\n";
seller += "longitude:" + longitude + "\n\n";
if (products != null) {
seller += "products:\n";
for (int i = 0; i < products.size(); i++) {
seller += products.get(i).toString() + "\n";
}
}
return seller;
}
public String getAudio() {
return Audio_url;
}
} |
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
/*<applet code="Progressbar" height=200 width=1000>
</applet>*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Progressbar extends JApplet implements ItemListener,ActionListener,ChangeListener{
JProgressBar jp;
JButton b;
TextField tf;
List insert,delete;
public void init(){
Container c=getContentPane();
c.setLayout(new FlowLayout());
createInsertButton(c);
createProgressBar(c);
createInsertList(c);
tf=new TextField(5);
c.add(tf);
}
public void createProgressBar(Container c){
jp=new JProgressBar();
jp.setMaximum(100);
jp.setMinimum(0);
c.add(jp);
jp.setValue(jp.getValue()+5);
}
public void createInsertList(Container c){
insert=new List(3,true);
insert.add("First");
insert.add("Last");
insert.add("Any Other Position");
c.add(insert);
}
public void createInsertButton(Container c){
b=new JButton("CLICK");
c.add(b);
b.addActionListener(this);
}
public void itemStateChanged(ItemEvent e){
int index=insert.getSelectedIndex();
String name=insert.getItem(index);
if(name.equals("First")){
tf.setVisible(true);
}
}
public void actionPerformed(ActionEvent e){
jp.setValue(jp.getValue()+5);
insert.setVisible(true);
}
public void stateChanged(ChangeEvent e){
}
} |
package at.ac.tuwien.sepm.groupphase.backend.endpoint;
import at.ac.tuwien.sepm.groupphase.backend.endpoint.dto.PaginationDto;
import at.ac.tuwien.sepm.groupphase.backend.endpoint.dto.PaginationRequestDto;
import at.ac.tuwien.sepm.groupphase.backend.endpoint.dto.ProductDto;
import at.ac.tuwien.sepm.groupphase.backend.endpoint.dto.ProductSearchDto;
import at.ac.tuwien.sepm.groupphase.backend.endpoint.dto.SimpleProductDto;
import at.ac.tuwien.sepm.groupphase.backend.endpoint.mapper.ProductMapper;
import at.ac.tuwien.sepm.groupphase.backend.entity.Product;
import at.ac.tuwien.sepm.groupphase.backend.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.lang.invoke.MethodHandles;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping(ProductEndpoint.BASE_URL)
public class ProductEndpoint {
static final String BASE_URL = "/api/v1/products";
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final ProductService productService;
private final ProductMapper productMapper;
@Autowired
public ProductEndpoint(ProductService productService, ProductMapper productMapper) {
this.productService = productService;
this.productMapper = productMapper;
}
/**
* Adds a new Product to the database.
*
* @param productDto the dto class containing all necessary field
* @return the newly added product in a dto - format
*/
@Secured("ROLE_ADMIN")
@PostMapping()
@ResponseStatus(HttpStatus.CREATED)
@Operation(summary = "Creates a new product with a given optional category and tax-rate", security = @SecurityRequirement(name = "apiKey"))
public ProductDto createProduct(@RequestBody @Valid ProductDto productDto) {
LOGGER.info("POST newProduct({}) " + BASE_URL, productDto);
return this.productMapper
.entityToDto(this.productService.createProduct(this.productMapper.dtoToEntity(productDto)));
}
/**
* Gets all products form the database in a paginated manner.
*
* @param paginationRequestDto describes the pagination request
* @param productSearchDto describes the product search request
* @return page with all products with all given fields in a dto - format and paginated specified by page and pageCount
*/
@PermitAll
@GetMapping
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "Returns all products that are currently stored in the database", security = @SecurityRequirement(name = "apiKey"))
public PaginationDto<ProductDto> getAllProductsPerPage(@Valid PaginationRequestDto paginationRequestDto, @Valid ProductSearchDto productSearchDto) {
LOGGER.info("GET " + BASE_URL);
int page = paginationRequestDto.getPage();
int pageCount = paginationRequestDto.getPageCount();
long categoryId = productSearchDto.getCategoryId();
String name = productSearchDto.getName();
String sortBy = productSearchDto.getSortBy();
Page<Product> productPage = this.productService.getAllProductsPerPage(page, pageCount, categoryId, sortBy, name);
long productCount = productPage.getTotalElements();
return new PaginationDto<>(productPage.getContent()
.stream()
.map(this.productMapper::entityToDto)
.collect(Collectors.toList()), page, pageCount, productPage.getTotalPages(), productCount);
}
/**
* Gets all simple products from the database, which omits some fields like picture and category.
*
* @return all simple products ( product without picture,category) in a dto - format NOT PAGINATED
*/
@Secured({"ROLE_ADMIN", "ROLE_EMPLOYEE"})
@GetMapping("/simple")
@ResponseStatus(HttpStatus.OK)
@Operation(
summary = "Returns all products that are currently stored in the database without picture and category",
security = @SecurityRequirement(name = "apiKey")
)
public List<SimpleProductDto> getAllSimpleProducts() {
LOGGER.info("GET" + BASE_URL + "/simple");
return this.productService.getAllProducts()
.stream()
.map(this.productMapper::simpleProductEntityToDto)
.collect(Collectors.toList());
}
/**
* Gets all simple products from the database by category, which omits some fields like picture and category.
*
* @param categoryId of category that should be searched for
* @return all simple products ( product without picture,category) in a dto - format NOT PAGINATED
*/
@Secured({"ROLE_ADMIN", "ROLE_EMPLOYEE"})
@GetMapping("/stats")
@ResponseStatus(HttpStatus.OK)
@Operation(
summary = "Returns all products that are currently stored in the database without picture and category",
security = @SecurityRequirement(name = "apiKey")
)
public List<SimpleProductDto> getAllSimpleProductsByCategory(@RequestParam long categoryId) {
LOGGER.info("GET" + BASE_URL + "/stats?category={}", categoryId);
return this.productService.getAllProductsByCategory(categoryId)
.stream()
.map(this.productMapper::simpleProductEntityToDto)
.collect(Collectors.toList());
}
/**
* Updates an already existing product from the database.
*
* @param productId the Id of the product to execute the udpate
* @param productDto the product dto with the updated fields
*/
@Secured("ROLE_ADMIN")
@PutMapping("/{productId}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "Updates an already existing product from the database", security = @SecurityRequirement(name = "apiKey"))
public void updateProduct(@PathVariable Long productId, @RequestBody @Valid ProductDto productDto) {
LOGGER.info("PUT Product{} with Id{}" + BASE_URL, productDto, productId);
this.productService.updateProduct(productId, this.productMapper.dtoToEntity(productDto));
}
/**
* Gets a specific product with the given id.
*
* @param productId the id to search in the database and retrieve the associated product entity
* @return the product entity with the associated Id
*/
@PermitAll
@GetMapping("/{productId}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "Gets a specific product with the give Id", security = @SecurityRequirement(name = "apiKey"))
public ProductDto getProductById(@PathVariable Long productId) {
LOGGER.info("GET Product with id{}" + BASE_URL, productId);
return this.productMapper.entityToDto(this.productService.findById(productId));
}
/**
* Deletes a specific product with the given id.
*
* @param productId the id to search in the database and retrieve the associated product entity
*/
@Secured("ROLE_ADMIN")
@DeleteMapping("/{productId}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "deletes a specific product with the given Id", security = @SecurityRequirement(name = "apiKey"))
public void deleteProductById(@PathVariable Long productId) {
LOGGER.info("DELETE Product with id{}" + BASE_URL, productId);
this.productService.deleteProductById(productId);
}
}
|
package memCache.ring;
import common.Key;
import java.net.InetAddress;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* RMI Interface used by the nodes of the ring to communicate with each other
*/
public interface Reachable extends Remote {
Reachable findSuccessor(Key key)throws RemoteException ;
Reachable findPredecessor(Key key)throws RemoteException;
Reachable closestPrecedingFinger(Key key)throws RemoteException;
void updateFingerTable(Reachable node, int i) throws RemoteException;
Reachable findMax() throws RemoteException;
void transferFilesTo(Reachable responsible) throws RemoteException;
void awakeToReceive(Reachable notifier) throws RemoteException;
void notify(Reachable candidatePredecessor) throws RemoteException;
InetAddress getIp()throws RemoteException;
int getListeningPort()throws RemoteException;
int getFileReceivingPort()throws RemoteException;
Key getNodeKey()throws RemoteException;
Reachable getSuccessor()throws RemoteException;
void setSuccessor(Reachable successor) throws RemoteException;
Reachable getPredecessor()throws RemoteException;
void setPredecessor(Reachable predecessor) throws RemoteException;
void setFinger(Reachable finger, int index) throws RemoteException;
boolean isAlive() throws RemoteException;
void notifyUpdates() throws RemoteException;
}
|
package com.ebayk.data.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class User {
private final Integer id;
private final String name;
private final List<UserRating> ratings;
public User(Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.ratings = builder.ratings;
}
public static Builder newUser() {
return new Builder();
}
public static class Builder {
private Integer id;
private String name;
private List<UserRating> ratings;
private Builder() {}
public Builder id(Integer id) {
this.id = id;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder ratings(List<UserRating> ratings) {
this.ratings = new ArrayList<>(ratings);
return this;
}
public User build() {
return new User(this);
}
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public List<UserRating> getRatings() {
return Collections.unmodifiableList(ratings);
}
} |
package lab.io.rush.base;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/***
*
* @author jd.zeng
* @create date 2016年12月24日
*
*/
//指定bean注入的配置文件
@ContextConfiguration(locations = { "classpath:application.xml" })
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTestCase extends AbstractJUnit4SpringContextTests {
}
|
import controller.Controller;
import view.View;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Controller(new View());
}
}
|
package com.wrathOfLoD.Models.Ability.Abilities.BlastAbilities;
import com.wrathOfLoD.Models.Entity.Character.Character;
import com.wrathOfLoD.Models.RangedEffect.HitBox.HitBoxFactories.FireBallHitBoxFactory;
import com.wrathOfLoD.Models.RangedEffect.REG.CircularREG;
import com.wrathOfLoD.Models.RangedEffect.REG.RangedEffectGenerator;
/**
* Created by matthewdiaz on 4/17/16.
*/
public class RadialBombBlastAbility extends BlastAbility {
public RadialBombBlastAbility(Character character, int windup, int coolDown, int totalDistance, int travelTime) {
super(character, windup, coolDown, totalDistance, travelTime);
}
public RadialBombBlastAbility(int unlockingLevel, Character character, int windup, int coolDown, int totalDistance, int travelTime){
super(unlockingLevel, character, windup, coolDown, totalDistance, travelTime);
}
@Override
public void windUpHook(){
//TODO: CHECK WHETHER THERE IS TARGET. Char.getActiveTarget?
RangedEffectGenerator reg = new CircularREG(
getTotalDistance(),
getCharacter().getPosition(),
calcualteDmg(),
getTravelTime(),
new FireBallHitBoxFactory());
reg.doRangedEffect();
}
} |
package service;
import domain.User;
public interface UserService {
User findUser(User user);
}
|
package com.javarush.task.task22.task2208;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/*
Формируем WHERE
*/
public class Solution {
public static void main(String[] args) {
//Map<String, String> map = new HashMap<>();
//map.put("name", "Ivanov");
//map.put("country", "Ukraine");
//map.put("city", "Kyiv");
//System.out.println(getQuery(map));
}
public static String getQuery(Map<String, String> params) {
params.entrySet().removeIf(stringStringEntry -> stringStringEntry.getValue() == null);
StringBuilder str = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> pair = iterator.next();
str.append(String.format("%s = '%s'", pair.getKey(), pair.getValue()));
if (iterator.hasNext()) str.append(" and ");
}
return str.toString();
}
}
|
package com.example.bannerslider.viewholder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import com.example.bannerslider.Slider;
import com.squareup.picasso.Picasso;
public class ImageSlideViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ImageSlideViewHolder(View itemView) {
super(itemView);
this.imageView = (ImageView) itemView;
}
public void bindImageSlide(String imageUrl) {
if (imageUrl != null) {
Picasso.get().load(imageUrl).into(imageView);
}
}
public void bindImageSlideFromServer(String imageUrl) {
Slider.getImageLoadingService().loadImage(imageUrl, imageView);
}
} |
package com.everysports.domain;
import lombok.Data;
import java.util.Date;
@Data
public class TeacherVO {
private String teacher_ID;
private String teacher_Name;
private String teacher_Email;
private String teacher_Gender;
private Date teacher_Birthday;
private String teacher_Phone;
private String teacher_Content;
private Long teacher_Point;
}
|
package com.gagetalk.gagetalkcustomer.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gagetalk.gagetalkcommon.util.ImageDownloader;
import com.gagetalk.gagetalkcustomer.R;
import com.gagetalk.gagetalkcustomer.data.MarketData;
import com.gagetalk.gagetalkcommon.util.SoundSearcher;
import java.util.ArrayList;
/**
* Created by hyochan on 3/29/15.
*/
public class MarketAdapter extends ArrayAdapter<MarketData>
implements Filterable{
private static final String TAG = "MarketAdapter";
private Context context;
private ArrayList<MarketData> arrayMarket;
private ArrayList<MarketData> arraySearch;
// private ImageLoader imageLoader;
public MarketAdapter(Context context, int resource, ArrayList<MarketData> arrayMarket) {
super(context, resource, arrayMarket);
this.context= context;
this.arrayMarket = arrayMarket;
this.arraySearch = arrayMarket;
}
class ViewHolder{
RelativeLayout relMarket;
ImageView imgMarket;
TextView txtMarketName;
TextView txtMarketCategory;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
LayoutInflater inflater=LayoutInflater.from(context);
convertView=inflater.inflate(R.layout.market_adapter, parent, false);
viewHolder = new ViewHolder();
viewHolder.relMarket = (RelativeLayout) convertView.findViewById(R.id.rel_market);
viewHolder.imgMarket = (ImageView) convertView.findViewById(R.id.img_market);
viewHolder.txtMarketName = (TextView) convertView.findViewById(R.id.txt_name_peer);
viewHolder.txtMarketCategory = (TextView) convertView.findViewById(R.id.txt_market_category);
convertView.setTag(viewHolder);
} else{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtMarketName.setText(arrayMarket.get(position).getMarName());
viewHolder.txtMarketCategory.setText((arrayMarket.get(position).getCategory()));
if(viewHolder.imgMarket != null){
ImageDownloader.getInstance(context).getImage(
arrayMarket.get(position).getImg(),
viewHolder.imgMarket);
}
return convertView;
}
@Override
public int getCount() {
return arrayMarket.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public MarketData getItem(int position) {
return arrayMarket.get(position);
}
@Override
public Filter getFilter() {
return myFilter;
}
Filter myFilter = new Filter() {
@Override
public void publishResults(CharSequence constraint, FilterResults results) {
arrayMarket = (ArrayList<MarketData>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
@Override
public FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<MarketData> tmpArrayMarket = new ArrayList<MarketData>();
if(constraint != null && arraySearch !=null) {
int length = arraySearch.size();
// Log.i("Filtering", "glossaries size" + length);
int i=0;
while(i<length){
MarketData item = arraySearch.get(i);
// Real filtering:
if(item.getMarName() != null &&
(
SoundSearcher.matchString(item.getMarName().toLowerCase(), constraint.toString().toLowerCase()))
){
tmpArrayMarket.add(item);
}
i++;
}
filterResults.values = tmpArrayMarket;
filterResults.count = tmpArrayMarket.size();
// Log.i("Filtering", "Filter result count size"+filterResults.count);
}
return filterResults;
}
};
}
|
package data1.hvl.no;
import java.io.IOException;
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("/DeltagerlisteServlet")
public class DeltagerlisteServlet extends HttpServlet {
// @EJB
// DeltagerEAO deltagerEAO;
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO sjekk om innlogget
// if !(InnloggingUtil.erInnlogget()) {
//
// redirect til /innlogging med feilmelding
//
// } else {
//
// deltagerEAO.hentUtAlleDeltagerne
//
// TODO sortering?
//
//
// TODO formatering?
//
//
//
// ta vare på deltagerliste i request-scope
//
// // Vise frem data fra databasen
// forward til WEB-INF/deltagerliste.jsp
//
// }
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
|
package com.goldenasia.lottery.data;
import com.google.gson.annotations.SerializedName;
/**
* 销售信息奖期信息
* Created by ACE-PC on 2016/1/27.
*/
public class IssueInfoEntity {
/**
* issue_id : 4961609
* issue : 20160122-0816
* end_time : 2016-01-22 14:36:00
* input_time : 2016-01-22 14:36:00
*/
@SerializedName("issue_id")
private String issueid;
private String issue;
@SerializedName("end_time")
private String endtime;
@SerializedName("input_time")
private String inputtime;
public String getIssueid() {
return issueid;
}
public void setIssueid(String issueid) {
this.issueid = issueid;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
public String getInputtime() {
return inputtime;
}
public void setInputtime(String inputtime) {
this.inputtime = inputtime;
}
} |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class Main {
public static void main(String[] args) {
testSimpleUse();
testTwoUses();
testFieldStores(doThrow);
testFieldStoreCycle();
testArrayStores();
testOnlyStoreUses();
testNoUse();
testPhiInput();
testVolatileStore();
doThrow = true;
try {
testInstanceSideEffects();
} catch (Error e) {
// expected
System.out.println(e.getMessage());
}
try {
testStaticSideEffects();
} catch (Error e) {
// expected
System.out.println(e.getMessage());
}
try {
testStoreStore(doThrow);
} catch (Error e) {
// expected
System.out.println(e.getMessage());
}
}
/// CHECK-START: void Main.testSimpleUse() code_sinking (before)
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object
/// CHECK: <<New:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: ConstructorFence [<<New>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testSimpleUse() code_sinking (after)
/// CHECK-NOT: NewInstance
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<Error:l\d+>> LoadClass class_name:java.lang.Error
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object
/// CHECK-NOT: begin_block
/// CHECK: <<New:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: ConstructorFence [<<New>>]
/// CHECK-NOT: begin_block
/// CHECK: NewInstance [<<Error>>]
/// CHECK: Throw
public static void testSimpleUse() {
Object o = new Object();
if (doThrow) {
throw new Error(o.toString());
}
}
/// CHECK-START: void Main.testTwoUses() code_sinking (before)
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object
/// CHECK: NewInstance [<<LoadClass>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testTwoUses() code_sinking (after)
/// CHECK-NOT: NewInstance
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<Error:l\d+>> LoadClass class_name:java.lang.Error
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object
/// CHECK-NOT: begin_block
/// CHECK: NewInstance [<<LoadClass>>]
/// CHECK-NOT: begin_block
/// CHECK: NewInstance [<<Error>>]
/// CHECK: Throw
public static void testTwoUses() {
Object o = new Object();
if (doThrow) {
throw new Error(o.toString() + o.toString());
}
}
/// CHECK-START: void Main.testFieldStores(boolean) code_sinking (before)
/// CHECK: <<Int42:i\d+>> IntConstant 42
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int42>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testFieldStores(boolean) code_sinking (after)
/// CHECK: <<Int42:i\d+>> IntConstant 42
/// CHECK-NOT: NewInstance
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<Error:l\d+>> LoadClass class_name:java.lang.Error
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK-NOT: begin_block
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK-NOT: begin_block
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int42>>]
/// CHECK-NOT: begin_block
/// CHECK: NewInstance [<<Error>>]
/// CHECK: Throw
public static void testFieldStores(boolean doThrow) {
Main m = new Main();
m.intField = 42;
if (doThrow) {
throw new Error(m.toString());
}
}
/// CHECK-START: void Main.testFieldStoreCycle() code_sinking (before)
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK: <<NewInstance1:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: <<NewInstance2:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: InstanceFieldSet [<<NewInstance1>>,<<NewInstance2>>]
/// CHECK: InstanceFieldSet [<<NewInstance2>>,<<NewInstance1>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
// TODO(ngeoffray): Handle allocation/store cycles.
/// CHECK-START: void Main.testFieldStoreCycle() code_sinking (after)
/// CHECK: begin_block
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK: <<NewInstance1:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: <<NewInstance2:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: InstanceFieldSet [<<NewInstance1>>,<<NewInstance2>>]
/// CHECK: InstanceFieldSet [<<NewInstance2>>,<<NewInstance1>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
public static void testFieldStoreCycle() {
Main m1 = new Main();
Main m2 = new Main();
m1.objectField = m2;
m2.objectField = m1;
if (doThrow) {
throw new Error(m1.toString() + m2.toString());
}
}
/// CHECK-START: void Main.testArrayStores() code_sinking (before)
/// CHECK: <<Int1:i\d+>> IntConstant 1
/// CHECK: <<Int0:i\d+>> IntConstant 0
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object[]
/// CHECK: <<NewArray:l\d+>> NewArray [<<LoadClass>>,<<Int1>>]
/// CHECK: ArraySet [<<NewArray>>,<<Int0>>,<<NewArray>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testArrayStores() code_sinking (after)
/// CHECK: <<Int1:i\d+>> IntConstant 1
/// CHECK: <<Int0:i\d+>> IntConstant 0
/// CHECK-NOT: NewArray
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<Error:l\d+>> LoadClass class_name:java.lang.Error
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object[]
/// CHECK-NOT: begin_block
/// CHECK: <<NewArray:l\d+>> NewArray [<<LoadClass>>,<<Int1>>]
/// CHECK-NOT: begin_block
/// CHECK: ArraySet [<<NewArray>>,<<Int0>>,<<NewArray>>]
/// CHECK-NOT: begin_block
/// CHECK: NewInstance [<<Error>>]
/// CHECK: Throw
public static void testArrayStores() {
Object[] o = new Object[1];
o[0] = o;
if (doThrow) {
throw new Error(o.toString());
}
}
// Make sure code sinking does not crash on dead allocations.
public static void testOnlyStoreUses() {
Main m = new Main();
Object[] o = new Object[1]; // dead allocation, should eventually be removed b/35634932.
o[0] = m;
o = null; // Avoid environment uses for the array allocation.
if (doThrow) {
throw new Error(m.toString());
}
}
// Make sure code sinking does not crash on dead code.
public static void testNoUse() {
Main m = new Main();
boolean load = Main.doLoop; // dead code, not removed because of environment use.
// Ensure one environment use for the static field
$opt$noinline$foo();
load = false;
if (doThrow) {
throw new Error(m.toString());
}
}
// Make sure we can move code only used by a phi.
/// CHECK-START: void Main.testPhiInput() code_sinking (before)
/// CHECK: <<Null:l\d+>> NullConstant
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Phi [<<Null>>,<<NewInstance>>]
/// CHECK: Throw
/// CHECK-START: void Main.testPhiInput() code_sinking (after)
/// CHECK: <<Null:l\d+>> NullConstant
/// CHECK-NOT: NewInstance
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: begin_block
/// CHECK: Phi [<<Null>>,<<NewInstance>>]
/// CHECK: <<Error:l\d+>> LoadClass class_name:java.lang.Error
/// CHECK: NewInstance [<<Error>>]
/// CHECK: Throw
public static void testPhiInput() {
Object f = new Object();
if (doThrow) {
Object o = null;
int i = 2;
if (doLoop) {
o = f;
i = 42;
}
throw new Error(o.toString() + i);
}
}
static void $opt$noinline$foo() {}
// Check that we do not move volatile stores.
/// CHECK-START: void Main.testVolatileStore() code_sinking (before)
/// CHECK: <<Int42:i\d+>> IntConstant 42
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int42>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testVolatileStore() code_sinking (after)
/// CHECK: <<Int42:i\d+>> IntConstant 42
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int42>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
public static void testVolatileStore() {
Main m = new Main();
m.volatileField = 42;
if (doThrow) {
throw new Error(m.toString());
}
}
public static void testInstanceSideEffects() {
int a = mainField.intField;
$noinline$changeIntField();
if (doThrow) {
throw new Error("" + a);
}
}
static void $noinline$changeIntField() {
mainField.intField = 42;
}
public static void testStaticSideEffects() {
Object o = obj;
$noinline$changeStaticObjectField();
if (doThrow) {
throw new Error(o.getClass().toString());
}
}
static void $noinline$changeStaticObjectField() {
obj = new Main();
}
// Test that we preserve the order of stores.
/// CHECK-START: void Main.testStoreStore(boolean) code_sinking (before)
/// CHECK: <<Int42:i\d+>> IntConstant 42
/// CHECK: <<Int43:i\d+>> IntConstant 43
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int42>>]
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int43>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testStoreStore(boolean) code_sinking (after)
/// CHECK: <<Int42:i\d+>> IntConstant 42
/// CHECK: <<Int43:i\d+>> IntConstant 43
/// CHECK-NOT: NewInstance
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<Error:l\d+>> LoadClass class_name:java.lang.Error
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:Main
/// CHECK-NOT: begin_block
/// CHECK: <<NewInstance:l\d+>> NewInstance [<<LoadClass>>]
/// CHECK-NOT: begin_block
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int42>>]
/// CHECK-NOT: begin_block
/// CHECK: InstanceFieldSet [<<NewInstance>>,<<Int43>>]
/// CHECK-NOT: begin_block
/// CHECK: NewInstance [<<Error>>]
/// CHECK: Throw
public static void testStoreStore(boolean doThrow) {
Main m = new Main();
m.intField = 42;
m.intField2 = 43;
if (doThrow) {
throw new Error(m.$opt$noinline$toString());
}
}
static native void doStaticNativeCallLiveVreg();
// Test ensures that 'o' has been moved into the if despite the InvokeStaticOrDirect.
//
/// CHECK-START: void Main.testSinkingOverInvoke() code_sinking (before)
/// CHECK: <<Int1:i\d+>> IntConstant 1
/// CHECK: <<Int0:i\d+>> IntConstant 0
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object[]
/// CHECK-NOT: begin_block
/// CHECK: NewArray [<<LoadClass>>,<<Int1>>]
/// CHECK: If
/// CHECK: begin_block
/// CHECK: Throw
/// CHECK-START: void Main.testSinkingOverInvoke() code_sinking (after)
/// CHECK: <<Int1:i\d+>> IntConstant 1
/// CHECK: <<Int0:i\d+>> IntConstant 0
/// CHECK: If
/// CHECK: begin_block
/// CHECK: <<LoadClass:l\d+>> LoadClass class_name:java.lang.Object[]
/// CHECK: NewArray [<<LoadClass>>,<<Int1>>]
/// CHECK: Throw
static void testSinkingOverInvoke() {
Object[] o = new Object[1];
o[0] = o;
doStaticNativeCallLiveVreg();
if (doThrow) {
throw new Error(o.toString());
}
}
public String $opt$noinline$toString() {
return "" + intField;
}
volatile int volatileField;
int intField;
int intField2;
Object objectField;
static boolean doThrow;
static boolean doLoop;
static Main mainField = new Main();
static Object obj = new Object();
}
|
package com.binarysprite.evemat.page;
import org.junit.Test;
public class ProductPageTest {
@Test
public void testGetGroupDisplays() {
}
}
|
package com.accolite.au.services;
import com.accolite.au.dto.EduthrillSessionDTO;
import com.accolite.au.dto.EduthrillTestDTO;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface EduthrillService {
ObjectNode uploadTest(MultipartFile sessionsFile, EduthrillTestDTO eduthrillTestDTO, int batchId);
EduthrillTestDTO getEduthrillTest(int eduthrillTestId);
List<EduthrillTestDTO> getAllEduthrillTest();
List<EduthrillSessionDTO> getAllEduthrillSessionsForTest(int eduthrillTestId);
EduthrillSessionDTO getEduthrillSession(int eduthrillSessionId);
List<EduthrillSessionDTO> getAllEduthrillSessionsForStudent(int studentId);
}
|
/*
* 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.context.annotation;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/**
* @author Andy Wilkinson
* @author Liu Dongmiao
*/
public class AggressiveFactoryBeanInstantiationTests {
@Test
public void directlyRegisteredFactoryBean() {
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
context.register(SimpleFactoryBean.class);
context.addBeanFactoryPostProcessor(factory ->
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(factory, String.class)
);
context.refresh();
}
}
@Test
public void beanMethodFactoryBean() {
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
context.register(BeanMethodConfiguration.class);
context.addBeanFactoryPostProcessor(factory ->
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(factory, String.class)
);
context.refresh();
}
}
@Test
public void checkLinkageError() {
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
context.register(BeanMethodConfigurationWithExceptionInInitializer.class);
context.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
ex.printStackTrace(pw);
pw.flush();
String stackTrace = baos.toString();
assertThat(stackTrace).contains(".<clinit>");
assertThat(stackTrace).doesNotContain("java.lang.NoClassDefFoundError");
}
}
@Configuration
static class BeanMethodConfiguration {
@Bean
public String foo() {
return "foo";
}
@Bean
public AutowiredBean autowiredBean() {
return new AutowiredBean();
}
@Bean
@DependsOn("autowiredBean")
public SimpleFactoryBean simpleFactoryBean(ApplicationContext applicationContext) {
return new SimpleFactoryBean(applicationContext);
}
}
@Configuration
static class BeanMethodConfigurationWithExceptionInInitializer extends BeanMethodConfiguration {
@Bean
@DependsOn("autowiredBean")
@Override
public SimpleFactoryBean simpleFactoryBean(ApplicationContext applicationContext) {
new ExceptionInInitializer();
return new SimpleFactoryBean(applicationContext);
}
}
static class AutowiredBean {
@Autowired
String foo;
}
static class SimpleFactoryBean implements FactoryBean<Object> {
public SimpleFactoryBean(ApplicationContext applicationContext) {
}
@Override
public Object getObject() {
return new Object();
}
@Override
public Class<?> getObjectType() {
return Object.class;
}
}
static class ExceptionInInitializer {
@SuppressWarnings("unused")
private static final int ERROR = callInClinit();
private static int callInClinit() {
throw new UnsupportedOperationException();
}
}
}
|
package com.ideaheap;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class PuzzleTest {
@Test
public void expandBotLeft() throws Exception {
Puzzle puzz = new Puzzle("123456780", 3, 3);
assertEquals(asList("R", "D"), puzz.expandMoves());
}
@Test
public void expandMiddle() throws Exception {
Puzzle puzz = new Puzzle("123405678", 3, 3);
assertEquals(asList("R", "L", "D", "U"), puzz.expandMoves());
}
@Test
public void expandTopRight() throws Exception {
Puzzle puzz = new Puzzle("023415678", 3, 3);
assertEquals(asList("L", "U"), puzz.expandMoves());
}
@Test
public void expandTopLeft() throws Exception {
Puzzle puzz = new Puzzle("120453678", 3, 3);
assertEquals(asList("R", "U"), puzz.expandMoves());
}
@Test
public void expandTopCenter() throws Exception {
Puzzle puzz = new Puzzle("102453678", 3 , 3);
assertEquals(asList("R", "L", "U"), puzz.expandMoves());
}
@Test
public void moveRight() throws Exception {
Puzzle puzz = new Puzzle("123450678", 3, 3);
assertEquals("123405678", puzz.doMove("R").toString());
assertEquals("123405678", puzz.doMove("R").toString());
}
@Test
public void moveDown() throws Exception {
Puzzle puzz = new Puzzle("123450678", 3, 3);
assertEquals("120453678", puzz.doMove("D").toString());
}
@Test
public void moveUp() throws Exception {
Puzzle puzz = new Puzzle("120453678", 3, 3);
assertEquals("123450678", puzz.doMove("U").toString());
}
@Test
public void moveLeft() throws Exception {
Puzzle puzz = new Puzzle("102453678", 3, 3);
assertEquals("120453678", puzz.doMove("L").toString());
assertEquals("120453678", puzz.doMove("L").toString());
}
public List<String> asList(String ... moves) {
return Arrays.asList(moves);
}
}
|
package mf_plus.appmanager;
import org.openqa.selenium.By;
/**
* Created by admin on 27.11.2016.
*/
public class NavigationHelper extends HelperBase {
public NavigationHelper(ApplicationManager app) {
super(app);
}
public void quotationsMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Quotations"));
}
public void surveysMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Surveys"));
}
public void dailyAgendaMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Daily Agenda"));
}
public void tasksMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Tasks"));
}
public void jobsMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Jobs"));
}
public void shipmentsMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Shipments"));
}
public void operationsMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Operations"));
}
public void warehouseMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Warehouse"));
}
public void crmMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("CRM"));
}
public void financialsMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Financials"));
}
public void managementMainViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText("Management"));
}
public void jobSummaryClientViewPage(){
waitForDisappear(By.id("page-preloader"));
click(By.linkText(""));
}
public void fromQuotToHomePage() {
waitForDisappear(By.id("page-preloader"));
waitSimple(500);
click(By.xpath("//div[2]/div/div[1]/div/div/div/a"));
waitForDisappear(By.id("page-preloader"));
waitSimple(1000);
}
public void fromJSToHomePage() {
waitForDisappear(By.id("page-preloader"));
click(By.xpath("//div[2]/div/div[1]/div/div/a"));
waitForDisappear(By.id("page-preloader"));
waitSimple(1000);
}
}
|
package com.szhrnet.taoqiapp.widget;
import android.support.v4.content.FileProvider;
/**
* Created by Administrator on 2018/5/25.
*/
public class MyProvider extends FileProvider {
}
|
package com.egswebapp.egsweb.dto;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public abstract class AbstractCategoryDto {
@NotBlank(message = "category name can not be null")
private String name;
public AbstractCategoryDto() {
}
public AbstractCategoryDto(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
/*
* JBoss, a division of Red Hat
* Copyright 2013, Red Hat Middleware, LLC, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.gatein.wcm.impl.model;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gatein.wcm.api.model.content.WCMObject;
import org.gatein.wcm.api.model.metadata.WCMCategory;
import org.gatein.wcm.api.model.metadata.WCMComment;
import org.gatein.wcm.api.model.publishing.WCMPublishStatus;
import org.gatein.wcm.api.model.security.WCMAcl;
import org.gatein.wcm.api.model.security.WCMPrincipal;
import org.gatein.wcm.api.model.security.WCMUser;
/**
* @see {@link WCMObject}
* @author <a href="mailto:lponce@redhat.com">Lucas Ponce</a>
*
*/
public abstract class WCMObjectImpl implements WCMObject {
protected String id;
protected String parentPath;
protected String path;
protected WCMAcl acl;
protected Date created;
protected Date lastModified;
protected WCMPublishStatus publishStatus;
protected List<WCMPrincipal> publishingRoles;
protected String createdBy;
protected String lastModifiedBy;
protected List<WCMComment> comments;
protected Set<WCMCategory> categories;
protected Map<String, String> properties;
protected boolean locked;
protected WCMUser lockOwner;
protected WCMObjectImpl() {
}
@Override
public String getId() {
return id;
}
@Override
public String getParentPath() {
return parentPath;
}
@Override
public String getPath() {
return path;
}
@Override
public WCMAcl getAcl() {
return acl;
}
@Override
public Date getCreatedOn() {
return created;
}
@Override
public Date getLastModifiedOn() {
return lastModified;
}
@Override
public WCMPublishStatus getPublishStatus() {
return publishStatus;
}
@Override
public List<WCMPrincipal> getPublishingRoles() {
return publishingRoles;
}
@Override
public String getCreatedBy() {
return createdBy;
}
@Override
public String getLastModifiedBy() {
return lastModifiedBy;
}
@Override
public List<WCMComment> getComments() {
return comments;
}
@Override
public Map<String, String> getProperties() {
return properties;
}
@Override
public boolean isLocked() {
return locked;
}
@Override
public WCMUser getLockOwner() {
return lockOwner;
}
protected void setId(String id) {
this.id = id;
}
protected void setParentPath(String parentPath) {
this.parentPath = parentPath;
}
protected void setPath(String path) {
this.path = path;
}
protected void setAcl(WCMAcl acl) {
this.acl = acl;
}
protected void setCreatedOn(Date created) {
this.created = created;
}
protected void setLastModifiedOn(Date lastModified) {
this.lastModified = lastModified;
}
protected void setPublishStatus(WCMPublishStatus publishStatus) {
this.publishStatus = publishStatus;
}
protected void setPublishingRoles(List<WCMPrincipal> publishingRoles) {
this.publishingRoles = publishingRoles;
}
protected void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
protected void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
protected void setComments(List<WCMComment> comments) {
this.comments = comments;
}
protected void setCategories(Set<WCMCategory> categories) {
this.categories = categories;
}
protected void setProperties(Map<String, String> properties) {
this.properties = properties;
}
protected void setLocked(boolean locked) {
this.locked = locked;
}
protected void setLockOwner(WCMUser lockOwner) {
this.lockOwner = lockOwner;
}
@Override
public String toString() {
return "WcmContent [id=" + id + ", parentPath=" + parentPath
+ ", path=" + path + ", acl=" + acl + ", created=" + created + ", lastModified=" + lastModified
+ ", publishStatus=" + publishStatus + ", publishingRoles=" + publishingRoles + ", createdBy=" + createdBy
+ ", lastModifiedBy=" + lastModifiedBy + ", comments=" + comments + ", categories=" + categories
+ ", properties=" + properties + ", locked=" + locked + ", lockOwner=" + lockOwner + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((acl == null) ? 0 : acl.hashCode());
result = prime * result + ((categories == null) ? 0 : categories.hashCode());
result = prime * result + ((comments == null) ? 0 : comments.hashCode());
result = prime * result + ((created == null) ? 0 : created.hashCode());
result = prime * result + ((createdBy == null) ? 0 : createdBy.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((lastModified == null) ? 0 : lastModified.hashCode());
result = prime * result + ((lastModifiedBy == null) ? 0 : lastModifiedBy.hashCode());
result = prime * result + ((lockOwner == null) ? 0 : lockOwner.hashCode());
result = prime * result + (locked ? 1231 : 1237);
result = prime * result + ((parentPath == null) ? 0 : parentPath.hashCode());
result = prime * result + ((path == null) ? 0 : path.hashCode());
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
result = prime * result + ((publishStatus == null) ? 0 : publishStatus.hashCode());
result = prime * result + ((publishingRoles == null) ? 0 : publishingRoles.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WCMObjectImpl other = (WCMObjectImpl) obj;
if (acl == null) {
if (other.acl != null)
return false;
} else if (!acl.equals(other.acl))
return false;
if (categories == null) {
if (other.categories != null)
return false;
} else if (!categories.equals(other.categories))
return false;
if (comments == null) {
if (other.comments != null)
return false;
} else if (!comments.equals(other.comments))
return false;
if (created == null) {
if (other.created != null)
return false;
} else if (!created.equals(other.created))
return false;
if (createdBy == null) {
if (other.createdBy != null)
return false;
} else if (!createdBy.equals(other.createdBy))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastModified == null) {
if (other.lastModified != null)
return false;
} else if (!lastModified.equals(other.lastModified))
return false;
if (lastModifiedBy == null) {
if (other.lastModifiedBy != null)
return false;
} else if (!lastModifiedBy.equals(other.lastModifiedBy))
return false;
if (lockOwner == null) {
if (other.lockOwner != null)
return false;
} else if (!lockOwner.equals(other.lockOwner))
return false;
if (locked != other.locked)
return false;
if (parentPath == null) {
if (other.parentPath != null)
return false;
} else if (!parentPath.equals(other.parentPath))
return false;
if (path == null) {
if (other.path != null)
return false;
} else if (!path.equals(other.path))
return false;
if (properties == null) {
if (other.properties != null)
return false;
} else if (!properties.equals(other.properties))
return false;
if (publishStatus == null) {
if (other.publishStatus != null)
return false;
} else if (!publishStatus.equals(other.publishStatus))
return false;
if (publishingRoles == null) {
if (other.publishingRoles != null)
return false;
} else if (!publishingRoles.equals(other.publishingRoles))
return false;
return true;
}
} |
package com.esum.framework.http;
import com.esum.framework.core.exception.FrameworkException;
public class HttpException extends FrameworkException {
private static final long serialVersionUID = 1L;
public HttpException(String message) {
super(message);
}
public HttpException(Throwable exception) {
super(exception);
}
public HttpException(String location, Throwable exception) {
super(location, exception);
}
public HttpException(String location, String message) {
super(location, message);
}
public HttpException(String location, String message, Throwable cause) {
super(location, message, cause);
}
}
|
package br.com.webstore;
import br.com.webstore.repository.CustomerRepository;
import br.com.webstore.repository.DBUserRepository;
import br.com.webstore.model.Customer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;
import static org.springframework.http.HttpMethod.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Project: api-webstore
*
* @author : Lucas Kanô de Oliveira (lucaskano)
* @since : 23/04/2020
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class CustomerEndpointTokenTest {
@Autowired
private TestRestTemplate restTemplate;
private MockRestServiceServer mockServer;
@Autowired
private MockMvc mockMvc;
@MockBean
private CustomerRepository customerRepository;
@MockBean
private DBUserRepository userRepository;
private HttpEntity<Void> protectedHeader;
private HttpEntity<Customer> adminHeader;
private HttpEntity<Void> wrongHeader;
@BeforeEach
public void configProtectedHeaders() {
String str = "{\"username\": \"kanoteste\", \"password\": \"lucaskano\"}";
HttpHeaders headers = restTemplate.postForEntity("http://localhost:8080/login", str, String.class).getHeaders();
this.protectedHeader = new HttpEntity<>(headers);
}
@BeforeEach
public void configAdminHeaders() {
String str = "{\"username\": \"testeDoTeste\", \"password\": \"lucaskano2\"}";
HttpHeaders headers = restTemplate.postForEntity("http://localhost:8080/login", str, String.class).getHeaders();
this.adminHeader = new HttpEntity<>(headers);
}
@BeforeEach
public void configWrongHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "11111");
this.wrongHeader = new HttpEntity<>(headers);
}
@BeforeEach
public void setup() {
Customer customer = new Customer
.Builder()
.name("Lucas")
.documentNumber("123456789011")
.dateOfBirth("06-03-1998")
.email("lucaskano@email.com")
.phoneNumber("11948729034")
.build();
when(customerRepository.findById(customer.getId())).thenReturn(java.util.Optional.of(customer));
}
@Test
public void whenListCustomerUsingIncorrectToken_thenReturnStatusCode403Forbidden () {
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/", GET, wrongHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(403);
}
@Test
public void whenGetCustomerByIdUsingIncorrectToken_thenReturnStatusCode403Forbidden () {
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/1", GET, wrongHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(403);
}
@Test
public void whenListCustomerUsingCorrectToken_thenReturnStatusCode200OK () {
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/", GET, protectedHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(200);
}
@Test
public void whenFindCustomerByNameUsingIncorrectToken_thenReturnStatusCode403Forbidden () {
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/findByName/kanoteste", GET, wrongHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(403);
}
@Test
public void whenGetCustomerByIdUsingCorrectTokenAndStudentDontExist_thenReturnStatusCode404NotFound () {
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/-1", GET, protectedHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(404);
}
@Test
public void whenSaveCustomerUsingIncorrectToken_thenReturnStatusCode403Forbidden() {
Customer customer = new Customer
.Builder()
.name("Lucas Um")
.documentNumber("123456789021")
.dateOfBirth("06-03-1993")
.email("lucaskano1@email.com")
.phoneNumber("11948729034")
.build();
adminHeader = new HttpEntity<>(customer, adminHeader.getHeaders());
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/protected/customers/", POST, wrongHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(403);
}
@Test
public void whenSaveStudentUsingCorrectToken_thenReturn201Created () {
Customer student = new Customer
.Builder()
.name("Lucas Dois")
.documentNumber("123456789022")
.dateOfBirth("06-03-1999")
.email("lucaskano2@email.com")
.phoneNumber("11948729032")
.build();
adminHeader = new HttpEntity<>(student, adminHeader.getHeaders());
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/protected/customers/", POST, adminHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(201);
}
@Test
public void whenDeleteCustomerUsingIncorrectToken_thenReturnStatusCode403Forbidden () {
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/{id}", DELETE, wrongHeader, String.class, 1L);
assertThat(response.getStatusCodeValue()).isEqualTo(403);
}
@Test
public void whenDeleteCustomerUsingCorrectToken_thenReturnStatusCode200Ok () throws JSONException {
Customer customer = new Customer
.Builder()
.name("Lucas Tres")
.documentNumber("123456789023")
.dateOfBirth("06-03-1991")
.email("lucaskano3@email.com")
.phoneNumber("11948729031")
.build();
adminHeader = new HttpEntity<>(customer, adminHeader.getHeaders());
ResponseEntity<String> response1 = restTemplate.exchange("http://localhost:8080/v1/admin/customers/", POST, adminHeader, String.class);
JSONObject studentJson = new JSONObject(response1.getBody());
doNothing().when(customerRepository).deleteById(studentJson.getLong("id"));
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/{id}", DELETE, adminHeader, String.class, studentJson.getLong("id"));
assertThat(response.getStatusCodeValue()).isEqualTo(200);
}
@Test
public void whenUpdateCustomerUsingCorrectToken_thenReturnStatusCode200Ok () throws JSONException {
Customer customer = new Customer
.Builder()
.name("Lucas Quatro")
.documentNumber("123456789026")
.dateOfBirth("06-03-1998")
.email("lucaskano4@email.com")
.phoneNumber("11948729031")
.build();
adminHeader = new HttpEntity<>(customer, adminHeader.getHeaders());
ResponseEntity<String> response1 = restTemplate.exchange("http://localhost:8080/v1/admin/customers/", POST, adminHeader, String.class);
JSONObject customerJson = new JSONObject(response1.getBody());
doNothing().when(customerRepository).deleteById(customerJson.getLong("id"));
Customer customer1 = new Customer
.Builder()
.name("Lucas Quatro")
.documentNumber("123456789026")
.dateOfBirth("06-03-1998")
.email("lucaskano4@email.com")
.phoneNumber("11948729031")
.build();
adminHeader = new HttpEntity<>(customer1, adminHeader.getHeaders());
restTemplate.exchange("http://localhost:8080/v1/admin/customers/", POST, adminHeader, String.class);
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/", PUT, adminHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(200);
}
@Test
public void whenUpdateCustomerUsingIncorrectToken_thenReturnStatusCode403Forbidden () {
Customer customer = new Customer
.Builder()
.name("Lucas Quatro")
.documentNumber("123456789026")
.dateOfBirth("06-03-1998")
.email("lucaskano4@email.com")
.phoneNumber("11948729031")
.build();
customerRepository.save(customer);
adminHeader = new HttpEntity<>(customer, adminHeader.getHeaders());
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/v1/admin/customers/", PUT, wrongHeader, String.class);
assertThat(response.getStatusCodeValue()).isEqualTo(403);
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"ADMIN"})
public void whenListAllCustomersUsingCorrectRole_thenReturnStatusCode200 () throws Exception {
List<Customer> customers = asList(new Customer
.Builder()
.name("Lucas Cinco")
.documentNumber("123456769026")
.dateOfBirth("06-03-1994")
.email("lucaskano5@email.com")
.phoneNumber("11948729031")
.build(),
new Customer
.Builder()
.name("Lucas Seis")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano6@email.com")
.phoneNumber("11948729032")
.build());
Page<Customer> pagedCustomers = new PageImpl(customers);
when(customerRepository.findAll(isA(Pageable.class))).thenReturn(pagedCustomers);
mockMvc.perform(get("http://localhost:8080/v1/admin/customers/"))
.andExpect(status().isOk())
.andDo(print());
verify(customerRepository).findAll(isA(Pageable.class));
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"ADMIN"})
public void whenGetCustomerByIdUsingCorrectRoleAndStudentDoesntExist_thenReturnStatusCode404 () throws Exception {
Customer customer = new Customer
.Builder()
.name("Lucas Sete")
.documentNumber("123456389021")
.dateOfBirth("06-03-1998")
.email("lucaskano7@email.com")
.phoneNumber("11948729032")
.build();
when(customerRepository.findById(3L)).thenReturn(java.util.Optional.of(customer));
mockMvc.perform(get("http://localhost:8080/v1/admin/students/{id}", 6))
.andExpect(status().isNotFound())
.andDo(print());
verify(customerRepository).findById(6L);
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"ADMIN"})
public void whenFindCustomersByNameUsingCorrectRole_thenReturnStatusCode200 () throws Exception {
List<Customer> students = asList(new Customer
.Builder()
.name("Lucas Oito")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano8@email.com")
.phoneNumber("11948729032")
.build(),
new Customer
.Builder()
.name("Lucas Nove")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano9@email.com")
.phoneNumber("11948729032")
.build(),
new Customer
.Builder()
.name("Lucas Dez")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano10@email.com")
.phoneNumber("11948729032")
.build());
when(customerRepository.findByNameIgnoreCaseContaining("lucas")).thenReturn(students);
mockMvc.perform(get("http://localhost:8080/v1/admin/customers/findByName/legolas"))
.andExpect(status().isOk())
.andDo(print());
verify(customerRepository).findByNameIgnoreCaseContaining("legolas");
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"ADMIN"})
public void whenDeleteUsingCorrectRole_thenReturnStatusCode200 () throws Exception {
Customer customer = new Customer
.Builder()
.name("Lucas Onze")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano11@email.com")
.phoneNumber("11948729032")
.build();
when(customerRepository.findById(customer.getId())).thenReturn(java.util.Optional.of(customer));
doNothing().when(customerRepository).deleteById(customer.getId());
mockMvc.perform(delete("http://localhost:8080/v1/admin/customers/{id}", 3))
.andExpect(status().isOk())
.andDo(print());
verify(customerRepository).deleteById(customer.getId());
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"ADMIN"})
public void whenDeleteHasRoleAdminAndCustomerDontExist_thenReturnStatusCode404 () throws Exception {
doNothing().when(customerRepository).deleteById(3L);
mockMvc.perform(delete("http://localhost:8080/v1/admin/customers/{id}", 1))
.andExpect(status().isNotFound())
.andDo(print());
verify(customerRepository, atLeast(1)).findById(1L);
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"USER"})
public void whenDeleteHasRoleUser_thenReturnStatusCode403 () throws Exception {
doNothing().when(customerRepository).deleteById(1L);
mockMvc.perform(delete("http://localhost:8080/v1/admin/customers/{id}", 1))
.andExpect(status().isForbidden())
.andDo(print());
}
@Test
@WithMockUser(username = "xxx", password = "xxx", roles = {"ADMIN"})
public void whenSaveHasRoleAdminAndCustomerIsNull_thenReturnStatusCode404 () throws Exception {
Customer customer = new Customer
.Builder()
.name("Lucas Doze")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano12@email.com")
.phoneNumber("11948729032")
.build();
when(customerRepository.save(customer)).thenReturn(customer);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(customer);
mockMvc.perform(post("http://localhost:8080/v1/admin/students/").contentType(MediaType.APPLICATION_JSON).content(jsonString))
.andExpect(status().isNotFound())
.andDo(print());
}
@Test
@WithMockUser(username = "xx", password = "xx", roles = "USER")
public void whenListAllStudentsUsingCorrectRole_thenReturnCorrectData () throws Exception {
List<Customer> customers = asList(new Customer
.Builder()
.name("Lucas Treze")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano13@email.com")
.phoneNumber("11948729032")
.build(),
new Customer
.Builder()
.name("Lucas Zero")
.documentNumber("123456789023")
.dateOfBirth("06-03-1998")
.email("lucaskano0@email.com")
.phoneNumber("11948729032")
.build());
Page<Customer> pagedCustomers = new PageImpl(customers);
when(customerRepository.findAll(isA(Pageable.class))).thenReturn(pagedCustomers);
mockMvc.perform(get("http://localhost:8080/v1/protected/students/"))
.andExpect(jsonPath("$.content", hasSize(2)))
.andExpect(jsonPath("$.content[0].id").value("1"))
.andExpect(jsonPath("$.content[0].name").value("Lucas Treze"))
.andExpect(jsonPath("$.content[0].documentNumber").value("123456789023"))
.andExpect(jsonPath("$.content[0].dateOfBirth").value("06-03-1998"))
.andExpect(jsonPath("$.content[0].email").value("lucaskano13@email.com"))
.andExpect(jsonPath("$.content[0].phoneNumber").value("11948729032"))
.andExpect(jsonPath("$.content[0].id").value("1"))
.andExpect(jsonPath("$.content[0].name").value("Lucas Zero"))
.andExpect(jsonPath("$.content[0].documentNumber").value("123456789023"))
.andExpect(jsonPath("$.content[0].dateOfBirth").value("06-03-1998"))
.andExpect(jsonPath("$.content[0].email").value("lucaskano0@email.com"))
.andExpect(jsonPath("$.content[0].phoneNumber").value("11948729032"));
verify(customerRepository).findAll(isA(Pageable.class));
}
} |
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio ( Instituto Nacional de Biodiversidad )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.persistence.identification;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.inbio.ara.persistence.GenericEntity;
/**
*
* @author asanabria
*/
@Entity
@Table(name = "identification_status")
public class IdentificationStatus extends GenericEntity{
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "identification_status_id")
private Long identificationStatusId;
@Basic(optional = false)
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
/*
@OneToMany(cascade = CascadeType.ALL, mappedBy = "identificationStatusId", fetch = FetchType.LAZY)
private Set<Identification> identificationCollection;
*/
public IdentificationStatus() {
}
public IdentificationStatus(Long identificationStatusId) {
this.identificationStatusId = identificationStatusId;
}
public IdentificationStatus(Long identificationStatusId, String name,
String createdBy, Calendar creationDate,
String lastModificationBy, Calendar lastModificationDate) {
this.identificationStatusId = identificationStatusId;
this.name = name;
this.setCreatedBy(createdBy);
this.setCreationDate(creationDate);
this.setLastModificationBy(lastModificationBy);
this.setLastModificationDate(lastModificationDate);
}
public Long getIdentificationStatusId() {
return identificationStatusId;
}
public void setIdentificationStatusId(Long identificationStatusId) {
this.identificationStatusId = identificationStatusId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int hashCode() {
int hash = 0;
hash += (identificationStatusId != null ? identificationStatusId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof IdentificationStatus)) {
return false;
}
IdentificationStatus other = (IdentificationStatus) object;
if ((this.identificationStatusId == null && other.identificationStatusId != null) || (this.identificationStatusId != null && !this.identificationStatusId.equals(other.identificationStatusId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.inbio.ara.persistence.taxonomy.IdentificationStatus[identificationStatusId=" + identificationStatusId + "]";
}
}
|
package model.user;
import model.card.Card;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
class UserTest {
private static User user;
@BeforeAll
static void init() {
user = new User("u", "n", "p");
}
@Test
void getUserByNickname() {
Assertions.assertNull(User.getUserByNickname("boo azar"));
Assertions.assertNotNull(User.getUserByNickname("n"));
}
@Test
void getUserByUsername() {
Assertions.assertNull(User.getUserByUsername("boo azar"));
Assertions.assertNotNull(User.getUserByUsername("u"));
}
@Test
void getAllUsers() {
Assertions.assertNotNull(User.getAllUsers());
ArrayList<User> allUsers = User.getAllUsers();
Assertions.assertEquals(1, allUsers.size());
Assertions.assertSame(user, allUsers.get(0));
}
@Test
void addToAllUsers() {
User user2 = new User("a", "a", "a");
ArrayList<User> allUsers = User.getAllUsers();
Assertions.assertEquals(2, allUsers.size());
User.addToAllUsers(user2);
Assertions.assertEquals(3, allUsers.size());
}
@Test
void setCredit() {
user.setCredit(2000);
Assertions.assertEquals(2000, user.getCredit());
}
@Test
void setNickname() {
user.setNickname("abbas");
Assertions.assertEquals("abbas", user.getNickname());
Assertions.assertNotNull(User.getUserByNickname("abbas"));
user.setNickname("n");
}
@Test
void setUsername() {
user.setUsername("abbas");
Assertions.assertEquals("abbas", user.getUsername());
Assertions.assertNotNull(User.getUserByUsername("abbas"));
user.setUsername("u");
}
@Test
void setScore() {
user.setScore(10);
Assertions.assertEquals(10, user.getScore());
}
@Test
void setPassword() {
user.setPassword("pp");
Assertions.assertEquals("pp", user.getPassword());
user.setPassword("p");
}
@Test
void setActiveDeck() {
Deck deck = new Deck("deck", "u");
user.addDeck("deck", deck);
user.setActiveDeck(deck);
Assertions.assertSame(deck, user.getActiveDeck());
}
@Test
void getNickname() {
Assertions.assertEquals("n", user.getNickname());
}
@Test
void getUsername() {
Assertions.assertEquals("u", user.getUsername());
}
@Test
void getPassword() {
Assertions.assertEquals("p", user.getPassword());
}
@Test
void addCard() {
Card card = new Card();
Assertions.assertNotNull(user.getCards());
user.addCard(card);
Assertions.assertEquals(1, user.getCards().size());
}
@Test
void getDecks() {
Assertions.assertNotNull(user.getDecks());
HashMap<String, Deck> decks = user.getDecks();
Assertions.assertTrue(decks.containsKey("deck"));
user.deleteDeck("deck");
Assertions.assertEquals(0, decks.size());
}
@Test
void setUserLoggedIn() {
Assertions.assertFalse(user.isUserLoggedIn());
user.setUserLoggedIn(true);
Assertions.assertTrue(user.isUserLoggedIn());
}
} |
package com.krish.sorting;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = { 1, 3, 4, 1, 2, 7, 6, 5, 8, 9 };
selectionSort(arr);
}
private static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int minimum = i;
for (int j = i+1; j < arr.length; j++) {
if (arr[minimum] > arr[j]) {
minimum = j;
}
}
int temp = arr[i];
arr[i] = arr[minimum];
arr[minimum] = temp;
}
for (int i : arr) {
System.out.println(i);
}
}
}
|
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.util.Duration;
public class Timer extends HBox {
int count;
int time_left;
String time_str;
Label clock;
Label img;
Timeline animation;
public Timer(){
count = 30;
time_left = count;
time_str = Integer.toString(count);
clock = new Label(time_str);
clock.setFont(javafx.scene.text.Font.font(25));
clock.setPrefSize(40,40);
img = new Label();
Image h = new Image("file:src/main/java/img/timer.png");
ImageView hourglass = new ImageView(h);
img.setGraphic(hourglass);
img.setPadding(new Insets(2.5, 0,0,0));
getChildren().addAll(img, clock);
setSpacing(15);
}
public void start(){
animation = new Timeline(new KeyFrame(Duration.seconds(1), e-> countdown()));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
}
public void stop(){
animation.stop();
}
public void resume(){
animation.play();
}
public void countdown(){
if (time_left > 0){
time_left--;
}
//System.out.println("TIME LEFT: " + time_left);
time_str = Integer.toString(time_left);
clock.setText(time_str);
}
}
|
package com.yea.loadbalancer;
import com.yea.core.loadbalancer.BalancingNode;
import com.yea.core.loadbalancer.IPing;
/**
* No Op Ping
* @author stonse
*
*/
public class NoOpPing implements IPing {
@Override
public boolean isAlive(BalancingNode server) {
return true;
}
}
|
package oracle.ocp.concurrent;
public class MyThread extends Thread {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("In run(), thread name is: %s, id: %d\n", getName(), getId());
}
public static void main(String... args) {
MyThread myThread = new MyThread();
myThread.start();
System.out.printf("In main(), thread name is: %s, id: %s\n", Thread.currentThread().getName(), Thread.currentThread().getId());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.