text
stringlengths 10
2.72M
|
|---|
package com.knoldus.actors;
import akka.actor.AbstractLoggingActor;
import akka.actor.Props;
import akka.japi.pf.ReceiveBuilder;
import javaslang.collection.List;
import com.knoldus.models.User;
import scala.PartialFunction;
import scala.runtime.BoxedUnit;
/**
* Created by Harmeet Singh(Taara) on 29/9/16.
*
* This actor is used to print the users only. We are never creating actors, which are not pass the message
* to another actor. This is used of our demo purpose.
*/
public class PrintUserActor extends AbstractLoggingActor {
public static final String ACTOR_NAME = "printUserActor";
private PrintUserActor() {}
/**
* This method is used for create the Pops of PrintUserActor actor.
* @return PrintUserActor actor props
* @see PrintUserActor
*/
public static Props props(){
return Props.create(PrintUserActor.class);
}
/**
* This method is used for handle received message of actor.
* @return
*/
@Override
public PartialFunction<Object, BoxedUnit> receive() {
return ReceiveBuilder.
match(PrintUser.class, printUsers -> {
log().info("Message Match... {}", PrintUser.class.getSimpleName());
printUsers.getUsers().forEach(System.out::println);
}).
matchAny(msg -> log().error("unknown message {}", msg)).
build();
}
/**
* This is class for handling message of PrintUserActor.
* @see PrintUserActor
*/
public static class PrintUser {
private final List<User> users;
public PrintUser(final List<User> users) {
this.users = users;
}
public final List<User> getUsers() {
return this.users;
}
}
}
|
package model;
import java.util.ArrayList;
/**
* Created by Nhozip on 6/15/2016.
*/
public class Page {
public ArrayList<ItemTT> getVnExpress() {
ArrayList<ItemTT> list = new ArrayList<>();
list.add(new ItemTT("Trang Chủ", "http://vnexpress.net/rss/tin-moi-nhat.rss"));
list.add(new ItemTT("Thời sự", "http://vnexpress.net/rss/thoi-su.rss"));
list.add(new ItemTT("Thế giới", "http://vnexpress.net/rss/the-gioi.rss"));
list.add(new ItemTT("Kinh doanh", "http://vnexpress.net/rss/kinh-doanh.rss"));
list.add(new ItemTT("Giải Trí", "http://vnexpress.net/rss/giai-tri.rss"));
list.add(new ItemTT("Pháp Luật", "http://vnexpress.net/rss/phap-luat.rss"));
list.add(new ItemTT("Sức khỏe", "http://vnexpress.net/rss/suc-khoe.rss"));
list.add(new ItemTT("Gia Đình", "http://vnexpress.net/rss/gia-dinh.rss"));
list.add(new ItemTT("Du Lịch", "http://vnexpress.net/rss/du-lich.rss"));
list.add(new ItemTT("Khoa Học", "http://vnexpress.net/rss/khoa-hoc.rss"));
list.add(new ItemTT("Số Hóa", "http://vnexpress.net/rss/so-hoa.rss"));
list.add(new ItemTT("Ô tô-Xe Máy", "http://vnexpress.net/rss/oto-xe-may.rss"));
list.add(new ItemTT("Cộng Đồng", "http://vnexpress.net/rss/cong-dong.rss"));
list.add(new ItemTT("Tâm Sự", "http://vnexpress.net/rss/tam-su.rss"));
list.add(new ItemTT("Giải Trí", "http://vnexpress.net/rss/cuoi.rss"));
return list;
}
public ArrayList<ItemTT> getVietNamNet() {
ArrayList<ItemTT> list = new ArrayList<>();
list.add(new ItemTT("Trang Chủ", "http://vietnamnet.vn/rss/home.rss"));
list.add(new ItemTT("Pháp Luật", "http://vietnamnet.vn/rss/phap-luat.rss"));
list.add(new ItemTT("Công Nghệ", "http://vietnamnet.vn/rss/cong-nghe.rss"));
list.add(new ItemTT("Kinh Doanh", "http://vietnamnet.vn/rss/kinh-doanh.rss"));
list.add(new ItemTT("Giáo Dục", "http://vietnamnet.vn/rss/giao-duc.rss"));
list.add(new ItemTT("Thời Sự", "http://vietnamnet.vn/rss/thoi-su.rss"));
list.add(new ItemTT("Giải Trí", "http://vietnamnet.vn/rss/giai-tri.rss"));
list.add(new ItemTT("Sức Khỏe", "http://vietnamnet.vn/rss/suc-khoe.rss"));
list.add(new ItemTT("Thể Thao", "http://vietnamnet.vn/rss/the-thao.rss"));
list.add(new ItemTT("Đời Sống", "http://vietnamnet.vn/rss/doi-song.rss"));
list.add(new ItemTT("Thế Giới", "http://vietnamnet.vn/rss/the-gioi.rss"));
list.add(new ItemTT("Bất Động Sản", "http://vietnamnet.vn/rss/bat-dong-san.rss"));
list.add(new ItemTT("Bạn Đọc", "http://vietnamnet.vn/rss/ban-doc.rss"));
list.add(new ItemTT("Tin Mới Nóng", "http://vietnamnet.vn/rss/moi-nong.rss"));
list.add(new ItemTT("Tin Nổi Bật", "http://vietnamnet.vn/rss/tin-noi-bat.rss"));
list.add(new ItemTT("Tuần Việt Nam", "http://vietnamnet.vn/rss/tuanvietnam.rss"));
list.add(new ItemTT("Góc Nhìn Thẳng", "http://vietnamnet.vn/rss/goc-nhin-thang.rss"));
return list;
}
public ArrayList<ItemTT> getTienPhong() {
ArrayList<ItemTT> list = new ArrayList<>();
list.add(new ItemTT("Xã Hội", "http://www.tienphong.vn/rss/xa-hoi-2.rss"));
list.add(new ItemTT("Kinh Tế", "http://www.tienphong.vn/rss/kinh-te-3.rss"));
list.add(new ItemTT("Thế Giới", "http://www.tienphong.vn/rss/the-gioi-5.rss"));
list.add(new ItemTT("Giới Trẻ", "http://www.tienphong.vn/rss/gioi-tre-4.rss"));
list.add(new ItemTT("Pháp Luật", "http://www.tienphong.vn/rss/phap-luat-12.rss"));
list.add(new ItemTT("Thể Thao", "http://www.tienphong.vn/rss/the-thao-11.rss"));
list.add(new ItemTT("Văn Nghệ", "http://www.tienphong.vn/rss/van-nghe-7.rss"));
list.add(new ItemTT("Giải Trí", "http://www.tienphong.vn/rss/giai-tri-36.rss"));
list.add(new ItemTT("Giáo Dục", "http://www.tienphong.vn/rss/giao-duc-71.rss"));
list.add(new ItemTT("Công Nghệ", "http://www.tienphong.vn/rss/cong-nghe-45.rss"));
return list;
}
public ArrayList<ItemTT> getNgoiSao() {
ArrayList<ItemTT> list = new ArrayList<>();
list.add(new ItemTT("Hậu Trường", "http://ngoisao.net/rss/hau-truong.rss"));
list.add(new ItemTT("Bên Lề", " http://ngoisao.net/rss/ben-le.rss"));
list.add(new ItemTT(" Thời cuộc", "http://ngoisao.net/rss/thoi-cuoc.rss"));
list.add(new ItemTT("Phong cách", "http://ngoisao.net/rss/phong-cach.rss"));
list.add(new ItemTT(" Thư giãn", "http://ngoisao.net/rss/thu-gian.rss"));
list.add(new ItemTT(" Cưới", "http://ngoisao.net/rss/cuoi-hoi.rss"));
list.add(new ItemTT(" Showbiz Việt", "http://ngoisao.net/rss/showbiz-viet.rss"));
list.add(new ItemTT(" Châu Á", "http://ngoisao.net/rss/chau-a.rss"));
list.add(new ItemTT("Hollywood", "http://ngoisao.net/rss/hollywood.rss"));
list.add(new ItemTT(" Clip", "http://ngoisao.net/rss/clip.rss"));
list.add(new ItemTT("Khỏe Đẹp", "http://ngoisao.net/rss/khoe-dep.rss"));
list.add(new ItemTT("24h", "http://ngoisao.net/rss/24h.rss"));
list.add(new ItemTT("Chuyện Lạ", "http://ngoisao.net/rss/chuyen-la.rss"));
list.add(new ItemTT(" Thương Truờng", "http://ngoisao.net/rss/thuong-truong.rss"));
list.add(new ItemTT(" Hình Sự", "http://ngoisao.net/rss/hinh-su.rss"));
list.add(new ItemTT(" Thời Trang", "http://ngoisao.net/rss/thoi-trang.rss"));
list.add(new ItemTT("Làm Đẹp", "http://ngoisao.net/rss/lam-dep.rss"));
list.add(new ItemTT("Trắc Nghiệm", "http://ngoisao.net/rss/trac-nghiem.rss"));
list.add(new ItemTT("Ăn Chơi", "http://ngoisao.net/rss/an-choi.rss"));
list.add(new ItemTT("Dân Chơi", "http://ngoisao.net/rss/dan-choi.rss"));
list.add(new ItemTT("Cười", "http://ngoisao.net/rss/cuoi.rss"));
list.add(new ItemTT("Game", "http://ngoisao.net/rss/game.rss"));
return list;
}
}
|
package com.project.service;
public interface IAdministratorService {
}
|
package com.minamid.accessiblememorygame.model;
import android.content.Context;
import android.util.AttributeSet;
public class MemoryCard extends android.support.v7.widget.AppCompatImageView {
private String imageId;
private String src;
private String description;
private boolean isFound;
private boolean isRevealed;
private int rowPosition;
private int colPosition;
private boolean shouldAnnounce;
public MemoryCard(Context context) {
super(context);
}
public MemoryCard(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MemoryCard(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public String getImageId() { return imageId; }
public void setImageId(String imageId) { this.imageId = imageId; }
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public boolean isRevealed() {
return isRevealed;
}
public void setRevealed(boolean revealed) { isRevealed = revealed; }
public int getColPosition() {
return colPosition;
}
public void setColPosition(int colPosition) {
this.colPosition = colPosition;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getRowPosition() {
return rowPosition;
}
public void setRowPosition(int rowPosition) {
this.rowPosition = rowPosition;
}
public boolean isFound() { return isFound; }
public void setFound(boolean found) { isFound = found; }
public boolean isShouldAnnounce() { return shouldAnnounce; }
public void setShouldAnnounce(boolean shouldAnnounce) { this.shouldAnnounce = shouldAnnounce; }
}
|
package ydtak.grapeguice.juice;
import com.google.inject.AbstractModule;
public class JuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(Juice.class).to(GrapeJuice.class);
}
}
|
package com.codingchili.instance.model.skills;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* Learned when leveling up a skill.
*/
public class Perk {
// perks may apply to only the given classes.
private Set<String> classes = new HashSet<>();
private String id = UUID.randomUUID().toString();
private String description;
private String icon;
private int level;
private Float effectiveness;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Float getEffectiveness() {
return effectiveness;
}
public void setEffectiveness(Float effectiveness) {
this.effectiveness = effectiveness;
}
public Set<String> getClasses() {
return classes;
}
public void setClasses(Set<String> classes) {
this.classes = classes;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
|
/**
*/
package Metamodell.model.metamodell;
import org.eclipse.emf.ecore.EFactory;
/**
* <!-- begin-user-doc -->
* The <b>Factory</b> for the model.
* It provides a create method for each non-abstract class of the model.
* <!-- end-user-doc -->
* @see Metamodell.model.metamodell.MetamodellPackage
* @generated
*/
public interface MetamodellFactory extends EFactory {
/**
* The singleton instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
MetamodellFactory eINSTANCE = Metamodell.model.metamodell.impl.MetamodellFactoryImpl.init();
/**
* Returns a new object of class '<em>System</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>System</em>'.
* @generated
*/
System createSystem();
/**
* Returns a new object of class '<em>Hardware</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Hardware</em>'.
* @generated
*/
Hardware createHardware();
/**
* Returns a new object of class '<em>Software</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Software</em>'.
* @generated
*/
Software createSoftware();
/**
* Returns a new object of class '<em>Brick</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Brick</em>'.
* @generated
*/
Brick createBrick();
/**
* Returns a new object of class '<em>Motor</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Motor</em>'.
* @generated
*/
Motor createMotor();
/**
* Returns a new object of class '<em>Sensor</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Sensor</em>'.
* @generated
*/
Sensor createSensor();
/**
* Returns a new object of class '<em>OSEK System</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>OSEK System</em>'.
* @generated
*/
OSEKSystem createOSEKSystem();
/**
* Returns a new object of class '<em>Event</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Event</em>'.
* @generated
*/
Event createEvent();
/**
* Returns a new object of class '<em>Task</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Task</em>'.
* @generated
*/
Task createTask();
/**
* Returns a new object of class '<em>Alarm</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Alarm</em>'.
* @generated
*/
Alarm createAlarm();
/**
* Returns a new object of class '<em>Connection</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Connection</em>'.
* @generated
*/
Connection createConnection();
/**
* Returns a new object of class '<em>SWC</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>SWC</em>'.
* @generated
*/
SWC createSWC();
/**
* Returns a new object of class '<em>Triggerport</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Triggerport</em>'.
* @generated
*/
Triggerport createTriggerport();
/**
* Returns a new object of class '<em>Sender Receiverport</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Sender Receiverport</em>'.
* @generated
*/
SenderReceiverport createSenderReceiverport();
/**
* Returns a new object of class '<em>Runnable</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Runnable</em>'.
* @generated
*/
Runnable createRunnable();
/**
* Returns the package supported by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the package supported by this factory.
* @generated
*/
MetamodellPackage getMetamodellPackage();
} //MetamodellFactory
|
package unalcol.termites.World;
import java.util.Hashtable;
import unalcol.termites.VM.TermitesInterpreterBinaryImpl;
import unalcol.termites.VM.TermitesVMBinaryImpl;
import unalcol.agents.Agent;
import unalcol.agents.AgentProgram;
import unalcol.termites.Runnable.AppMain;
/**
*
* @author ARODRIGUEZ
*/
public class Termite extends Agent {
private int type = 0;
/**
*
*/
public static final int SEEKING = 0;
/**
*
*/
public static final int CARRYING = 1;
/**
*
*/
public static final int DIAGNOSE = 2;
/**
*
*/
public static final int OVERDIAGNOSE = 3;
/**
*
*/
public static final int STARTDIAGNOSE = 4;
/**
*
*/
public static final int NOTDIAGNOSE = 5;
private float pheromone;
private int mystatus;
private int diagnoseStatus;
private int id;
/**
*
*/
public int voteAboutProgram = 0;
/**
*
*/
public int diagnoseNumber = 0;
/**
*
*/
public boolean putPheromone = true;
private int ImGoodCounter = 0;
/**
*
*/
public double persProb = 0.5;
/**
*
*/
public double diagProb = 0.5;
/**
*
*/
public int votesThreshold = 20;
/**
*
*/
public int foodIteration;
/**
*
*/
public int lastTime;
/**
*
*/
public int lostCounter;
/* This two variables are for the voting threshold */
private double lambda = 0.5;
/**
*
*/
public int votesStatus;
/**
*
*/
public int totalVotes;
private int x;
private int y;
private int round;
private int nMsgSend;
private int nMsgRecv;
private Hashtable phHistory;
private Hashtable infHistory;
private int roundsWithoutNewInfo;
private int exploredTerrain;
private Hashtable infi;
//Relative coordinate system
private int minx;
private int miny;
private int maxx;
private int maxy;
//DS Simulator
/**
*
*/
protected Hashtable<String, Object> properties = new Hashtable<>();
//LinkedBlockingQueue<Object> mbuffer = new LinkedBlockingQueue<Object>();
/**
*
* @param program
* @param id
*/
public Termite(AgentProgram program, int id) {
super(program);
if (AppMain.getMode().equals("oneph") || AppMain.getMode().equals("onephevap") || AppMain.getMode().equals("lwphevap") || AppMain.getMode().equals("hybrid") || AppMain.getMode().equals("hybrid2") || AppMain.getMode().equals("hybrid3") || AppMain.getMode().equals("hybrid4") || AppMain.getMode().equals("lwphevap2") || AppMain.getMode().equals("turnoncontact") || AppMain.getMode().equals("lwphevapMap")) {
this.mystatus = CARRYING;
this.pheromone = (float) 1;
} else {
this.mystatus = SEEKING;
if (AppMain.getMode().equals("lwphclwevap")) {
this.pheromone = (float) 1;
} else {
this.pheromone = (float) 0;
}
}
this.id = id;
this.diagnoseStatus = NOTDIAGNOSE;
//GaussianGenerator g = new GaussianGenerator(20.0, 3.0);
this.votesThreshold = 20; // (int)g.next();
this.foodIteration = 0;
this.lastTime = 0;
this.votesStatus = 0;
this.totalVotes = 0;
this.round = 0;
this.nMsgRecv = 0;
this.nMsgSend = 0;
this.phHistory = new Hashtable();
this.infHistory = new Hashtable();
this.roundsWithoutNewInfo = 0;
this.exploredTerrain = 0;
this.minx = Integer.MAX_VALUE;
this.miny = Integer.MAX_VALUE;
this.maxx = Integer.MIN_VALUE;
this.maxy = Integer.MIN_VALUE;
}
/**
* @return the status
*/
public int getStatus() {
return mystatus;
}
/**
* @param status the status to set
*/
public void setStatus(int status) {
this.mystatus = status;
}
/**
* @return the pheromone
*/
public float getPheromone() {
return pheromone;
}
/**
* @param pheromone the pheromone to set
*/
public void setPheromone(float pheromone) {
this.pheromone = pheromone;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the diagnoseStatus
*/
public int getDiagnoseStatus() {
return diagnoseStatus;
}
/**
* @param diagnoseStatus the diagnoseStatus to set
*/
public void setDiagnoseStatus(int diagnoseStatus) {
this.diagnoseStatus = diagnoseStatus;
}
/**
*/
public void increaseVoteProgram() {
voteAboutProgram++;
}
/**
*
*/
public void decreaseVoteProgram() {
voteAboutProgram--;
}
/**
*
* @return
*/
public String printVotes() {
String sVotes = "";
sVotes = id + ";" + voteAboutProgram;
return sVotes;
}
/**
*
* @return
*/
public int getVoteAboutProgram() {
return voteAboutProgram;
}
/**
*
* @param voteAboutProgram
*/
public void setVoteAboutProgram(int voteAboutProgram) {
this.voteAboutProgram = voteAboutProgram;
}
/**
*
*/
public void increaseImGoodCounter() {
this.ImGoodCounter++;
}
/**
*
* @param ImGoodCounter
*/
public void setImGoodCounter(int ImGoodCounter) {
this.ImGoodCounter = ImGoodCounter;
}
/**
*
* @return
*/
public int getImGoodCounter() {
return ImGoodCounter;
}
/**
* @return the lambda
*/
public double getLambda() {
return lambda;
}
/**
* @param lambda the lambda to set
*/
public void setLambda(double lambda) {
this.lambda = lambda;
}
/**
*
*/
public void votesplus() {
this.votesStatus++;
}
/**
*
*/
public void votesneg() {
this.votesStatus--;
}
/**
* @return the x
*/
public int getX() {
return x;
}
/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @return the y
*/
public int getY() {
return y;
}
/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
/**
*
* @param t
*/
public void setType(int t) {
this.type = t;
}
/**
* @return the type
*/
public int getType() {
return type;
}
//DS Part
/**
*
* @param key
* @param value
*/
public void setAttribute(String key, Object value) {
properties.put(key, value);
}
/**
*
* @param key
* @return
*/
public Object getAttribute(String key) {
return properties.get(key);
}
/**
*
* @param key
* @return
*/
public boolean removeAttribute(String key) {
if (properties.remove(key) != null) {
return true;
} else {
return (false);
}
}
// public void putMessage(Object message) {
// mbuffer.add(message);
// }
// public Object getMessage() {
// return mbuffer.poll();
// }
/**
* @return the round round is defined as the number of iteration by
* distributed Asynchronous Round-Based Computation Differently from
* synchronous sys -tems, the rounds are not given for free in an
* asynchronous system. Each process pi has to handle a local variable ri
* which denotes its current round number. We first consider that, in each
* round r it executes, a process sends a message to each of its neighbors,
* and receives a message from each of them.
*/
public int getRound() {
return round;
}
/**
* @param round the round to set
*/
public void setRound(int round) {
this.round = round;
}
/**
*
* @param msg
*/
public void log(String msg) {
System.out.println("Agent: " + this.getAttribute("ID") + " : " + msg);
}
/**
* @return the nMsgSend
*/
public int getnMsgSend() {
return nMsgSend;
}
/**
* @param nMsgSend the nMsgSend to set
*/
public void setnMsgSend(int nMsgSend) {
this.nMsgSend = nMsgSend;
}
/**
* @return the nMsgRecv
*/
public int getnMsgRecv() {
return nMsgRecv;
}
/**
* @param nMsgRecv the nMsgRecv to set
*/
public void setnMsgRecv(int nMsgRecv) {
this.nMsgRecv = nMsgRecv;
}
/**
*
*/
public void incMsgSend() {
synchronized (Termite.class) {
nMsgSend++;
}
}
/**
*
*/
public void incMsgRecv() {
synchronized (Termite.class) {
nMsgRecv++;
}
}
/**
* @return the phHistory
*/
public Hashtable getPhHistory() {
return phHistory;
}
/**
* @param phHistory the phHistory to set
*/
public void setPhHistory(Hashtable phHistory) {
this.phHistory = phHistory;
}
/**
* @return the infHistory
*/
public Hashtable getInfHistory() {
return infHistory;
}
/**
* @param infHistory the infHistory to set
*/
public void setInfHistory(Hashtable infHistory) {
this.infHistory = infHistory;
}
/**
*
* @return
*/
public int getAmountInfo() {
int aminfo = 0;
float[][] inf = (float[][]) this.getAttribute("infi");
for (float[] inf1 : inf) {
for (int j = 0; j < inf[0].length; j++) {
if (inf1[j] != -1) {
aminfo++;
}
}
}
return aminfo;
}
/**
* @return the roundsWithoutNewInfo
*/
public int getRoundsWithoutNewInfo() {
return roundsWithoutNewInfo;
}
/**
* @param infDelta the roundsWithoutNewInfo to set
*/
public void setRoundsWithoutNewInfo(int infDelta) {
this.roundsWithoutNewInfo = infDelta;
}
/**
*/
public void addRoundsWithoutNewInfo() {
this.roundsWithoutNewInfo++;
}
/**
* @return the exploredTerrain
*/
public int getExploredTerrain() {
return exploredTerrain;
}
/**
* @param exploredTerrain the exploredTerrain to set
*/
public void setExploredTerrain(int exploredTerrain) {
this.exploredTerrain = exploredTerrain;
}
/**
*/
public void incExploredTerrain() {
exploredTerrain++;
}
/**
* @return the infi
*/
public Hashtable getInfi() {
return infi;
}
/**
* @param infi the infi to set
*/
public void setInfi(Hashtable infi) {
this.infi = infi;
}
/**
* @return the minx
*/
public int getMinx() {
return minx;
}
/**
* @param minx the minx to set
*/
public void setMinx(int minx) {
this.minx = minx;
}
/**
* @return the miny
*/
public int getMiny() {
return miny;
}
/**
* @param miny the miny to set
*/
public void setMiny(int miny) {
this.miny = miny;
}
/**
* @return the maxx
*/
public int getMaxx() {
return maxx;
}
/**
* @param maxx the maxx to set
*/
public void setMaxx(int maxx) {
this.maxx = maxx;
}
/**
* @return the maxy
*/
public int getMaxy() {
return maxy;
}
/**
* @param maxy the maxy to set
*/
public void setMaxy(int maxy) {
this.maxy = maxy;
}
}
|
package com.penglai.haima.ui.charge;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;
import com.lzy.okgo.OkGo;
import com.penglai.haima.R;
import com.penglai.haima.base.BaseActivity;
import com.penglai.haima.base.Constants;
import com.penglai.haima.bean.WeChatPayResponse;
import com.penglai.haima.callback.DialogCallback;
import com.penglai.haima.okgomodel.CommonReturnData;
import com.penglai.haima.utils.SharepreferenceUtil;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
public class ChargePayActivity extends BaseActivity {
@BindView(R.id.tv_charge)
TextView tvCharge;
@BindView(R.id.et_pay_money)
EditText etPayMoney;
private IWXAPI weChatApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitleMiddleText("充值");
}
@Override
public int setBaseContentView() {
return R.layout.activity_charge_pay;
}
@Override
public void init() {
weChatApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID);
}
@OnClick(R.id.tv_charge)
public void onViewClicked() {
String payMoney = etPayMoney.getText().toString().trim();
if (TextUtils.isEmpty(payMoney)) {
showToast("请输入充值金额");
return;
}
if (Integer.parseInt(payMoney) <= 0) {
showToast("充值金额需大于0");
return;
}
charge_pay(payMoney);
}
/**
* 生成订单并支付
*
* @param cashnum
*/
private void charge_pay(String cashnum) {
OkGo.<CommonReturnData<WeChatPayResponse>>post(Constants.BASE_URL + "order/pay")
.params("cashnum", cashnum)
.params("mobile", SharepreferenceUtil.getString(Constants.MOBILE))
.params("mercid", "001")
.execute(new DialogCallback<CommonReturnData<WeChatPayResponse>>(this) {
@Override
public void onSuccess(CommonReturnData<WeChatPayResponse> commonReturnData) {
if (isWeChatInstalled(ChargePayActivity.this)) {
weChat_pay(commonReturnData.getData());
} else {
showToast("未安装微信,尝试其他支付");
}
}
});
}
/**
* 进行微信支付
*
* @param response
*/
private void weChat_pay(WeChatPayResponse response) {
weChatApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APP_ID);
weChatApi.registerApp(Constants.WECHAT_APP_ID);
boolean isPaySupported = weChatApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
if (isPaySupported) {
PayReq req = new PayReq();
req.appId = Constants.WECHAT_APP_ID;
req.partnerId = response.getPartnerid();
req.nonceStr = response.getNoncestr();
req.prepayId = response.getPrepayid();
req.timeStamp = String.valueOf(response.getTimestamp());
req.sign = response.getSign();
req.packageValue = response.getPackageValue();
weChatApi.sendReq(req);
}
}
/**
* 是否安装了微信
*/
public static boolean isWeChatInstalled(Context context) {
final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
List<PackageInfo> packages = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
if (packages != null) {
for (int i = 0, length = packages.size(); i < length; i++) {
String pn = packages.get(i).packageName;
if (pn.equals("com.tencent.mm")) {
return true;
}
}
}
return false;
}
}
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.limegroup.gnutella.gui;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import org.limewire.i18n.I18nMarker;
import com.frostwire.gui.theme.SkinMenuItem;
import com.frostwire.gui.theme.SkinPopupMenu;
/**
* A better JTextField.
*/
public class LimeTextField extends JTextField {
/**
*
*/
private static final long serialVersionUID = -1994520183255049424L;
/**
* The undo action.
*/
private static Action UNDO_ACTION = new FieldAction(I18nMarker.marktr("Undo")) {
/**
*
*/
private static final long serialVersionUID = 675409703997007078L;
public void actionPerformed(ActionEvent e) {
getField(e).undo();
}
};
/**
* The cut action
*/
private static Action CUT_ACTION = new FieldAction(I18nMarker.marktr("Cut")) {
/**
*
*/
private static final long serialVersionUID = 5342970192703043838L;
public void actionPerformed(ActionEvent e) {
getField(e).cut();
}
};
/**
* The copy action.
*/
private static Action COPY_ACTION = new FieldAction(I18nMarker.marktr("Copy")) {
/**
*
*/
private static final long serialVersionUID = -3484207766103231841L;
public void actionPerformed(ActionEvent e) {
getField(e).copy();
}
};
/**
* The paste action.
*/
private static Action PASTE_ACTION = new FieldAction(I18nMarker.marktr("Paste")) {
/**
*
*/
private static final long serialVersionUID = -967931044746884556L;
public void actionPerformed(ActionEvent e) {
getField(e).paste();
}
};
/**
* The delete action.
*/
private static Action DELETE_ACTION = new FieldAction(I18nMarker.marktr("Delete")) {
/**
*
*/
private static final long serialVersionUID = -1239306786560704952L;
public void actionPerformed(ActionEvent e) {
getField(e).replaceSelection("");
}
};
/**
* The select all action.
*/
private static Action SELECT_ALL_ACTION = new FieldAction(I18nMarker.marktr("Select All")) {
/**
*
*/
private static final long serialVersionUID = 4783056991868525860L;
public void actionPerformed(ActionEvent e) {
getField(e).selectAll();
}
};
/**
* The sole JPopupMenu that's shared among all the text fields.
*/
private static final JPopupMenu POPUP = createPopup();
/**
* Our UndoManager.
*/
private UndoManager undoManager;
/**
* Constructs a new LimeTextField.
*/
public LimeTextField() {
super();
init();
}
/**
* Constructs a new LimeTextField with the given text.
*/
public LimeTextField(String text) {
super(text);
init();
}
/**
* Constructs a new LimeTextField with the given amount of columns.
*/
public LimeTextField(int columns) {
super(columns);
init();
}
/**
* Constructs a new LimeTextField with the given text & number of columns.
*/
public LimeTextField(String text, int columns) {
super(text, columns);
init();
}
/**
* Constructs a new LimeTextField with the given document, text, and columns.
*/
public LimeTextField(Document doc, String text, int columns) {
super(doc, text, columns);
init();
}
/**
* Undoes the last action.
*/
public void undo() {
try {
if(undoManager != null)
undoManager.undoOrRedo();
} catch(CannotUndoException ignored) {
} catch(CannotRedoException ignored) {
}
}
/**
* Sets the UndoManager (but does NOT add it to the document).
*/
public void setUndoManager(UndoManager undoer) {
undoManager = undoer;
}
/**
* Gets the undo manager.
*/
public UndoManager getUndoManager() {
return undoManager;
}
/**
* Intercept the 'setDocument' so that we can null out our manager
* and possibly assign a new one.
*/
public void setDocument(Document doc) {
if(doc != getDocument())
undoManager = null;
super.setDocument(doc);
}
/**
* Initialize the necessary events.
*/
private void init() {
setComponentPopupMenu(POPUP);
undoManager = new UndoManager();
undoManager.setLimit(1);
getDocument().addUndoableEditListener(undoManager);
}
/**
* Creates the JPopupMenu that all LimeTextFields will share.
*/
private static JPopupMenu createPopup() {
JPopupMenu popup;
// initialize the JPopupMenu with necessary stuff.
popup = new SkinPopupMenu() {
/**
*
*/
private static final long serialVersionUID = -6004124495511263059L;
public void show(Component invoker, int x, int y) {
((LimeTextField)invoker).updateActions();
super.show(invoker, x, y);
}
};
popup.add(new SkinMenuItem(UNDO_ACTION));
popup.addSeparator();
popup.add(new SkinMenuItem(CUT_ACTION));
popup.add(new SkinMenuItem(COPY_ACTION));
popup.add(new SkinMenuItem(PASTE_ACTION));
popup.add(new SkinMenuItem(DELETE_ACTION));
popup.addSeparator();
popup.add(new SkinMenuItem(SELECT_ALL_ACTION));
return popup;
}
/**
* Updates the actions in each text just before showing the popup menu.
*/
private void updateActions() {
String selectedText = getSelectedText();
if(selectedText == null)
selectedText = "";
boolean stuffSelected = !selectedText.equals("");
boolean allSelected = selectedText.equals(getText());
UNDO_ACTION.setEnabled(isEnabled() && isEditable() && isUndoAvailable());
CUT_ACTION.setEnabled(isEnabled() && isEditable() && stuffSelected);
COPY_ACTION.setEnabled(isEnabled() && stuffSelected);
PASTE_ACTION.setEnabled(isEnabled() && isEditable() && isPasteAvailable());
DELETE_ACTION.setEnabled(isEnabled() && stuffSelected);
SELECT_ALL_ACTION.setEnabled(isEnabled() && !allSelected);
}
/**
* Determines if an Undo is available.
*/
private boolean isUndoAvailable() {
return getUndoManager() != null && getUndoManager().canUndoOrRedo();
}
/**
* Determines if paste is currently available.
*/
private boolean isPasteAvailable() {
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
return clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor);
} catch(UnsupportedOperationException he) {
return false;
} catch(IllegalStateException ise) {
return false;
}
}
/**
* Base Action that all LimeTextField actions extend.
*/
private static abstract class FieldAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = -2088365927213389348L;
/**
* Constructs a new FieldAction looking up the name from the MessagesBundles.
*/
public FieldAction(String name) {
super(I18n.tr(name));
}
/**
* Gets the LimeTextField for the given ActionEvent.
*/
protected LimeTextField getField(ActionEvent e) {
JMenuItem source = (JMenuItem)e.getSource();
JPopupMenu menu = (JPopupMenu)source.getParent();
return (LimeTextField)menu.getInvoker();
}
}
}
|
package com.zjj.dao;
import com.zjj.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import java.util.List;
/**
* @auth yunsll
* @date 2020/3/17 19:11
* @Descripiton 测试类
*/
public class UserDao extends BaseDao {
//
public List<User> listAll(){
String sql = "select * from sys_user ";
return template.query(sql,new BeanPropertyRowMapper<User>(User.class));
}
}
|
package com.example.widget.color_seekbar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import com.example.widget.R;
/**
* 带有渐变颜色的seekbar
*/
public class ColorSeekBar extends View {
private float minThumbRadius = 16f;
private int[] colorSeeds;
private int canvasHeight = 40;
private int barHeight = 20;
private RectF rectF = new RectF();
private Paint rectPaint = new Paint();
private int mMax = 255;
private int mMin = 0;
private Paint thumbInnerPaint = new Paint();
private Paint thumbPaint = new Paint();
private LinearGradient colorGradient;
private float thumbX = 24f;
private float thumbY = (float)canvasHeight / 2;
private float thumbBorder = 8f;
private float thumbRadius = 16f;
private float thumbBorderRadius = thumbRadius + thumbBorder;
private int thumbInnerColor = Color.BLACK;
private float paddingStart = 30f;
private float paddingEnd = 30f;
private float barCornerRadius = 8f;
private float barLeft;
private float barRight;
private float barTop;
private float barBottom;
private int currentValue = -1;
private boolean hasCurrentValue;
private int mType = TYPE_ALPHA;
/**
* 透明度
*/
public static final int TYPE_ALPHA = 0x01;
/**
* 饱和度
*/
public static final int TYPE_SATURATION = 0x02;
private OnColorChangeListener colorChangeListener;
public void setOnColorChangeListener(OnColorChangeListener l) {
this.colorChangeListener = l;
}
interface OnColorChangeListener {
void onColorChangeListener(int color);
}
public ColorSeekBar(Context context) {
super(context , null);
init(context , null);
}
public ColorSeekBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context , attrs);
}
private void init(Context context , AttributeSet attrs){
TypedArray typedArray = context.obtainStyledAttributes(attrs , R.styleable.ColorSeekBar);
barCornerRadius = typedArray.getDimension(R.styleable.ColorSeekBar_cornerRadius, 8f);
barHeight = (int)typedArray.getDimension(R.styleable.ColorSeekBar_barHeight, 20f);
thumbBorder = typedArray.getDimension(R.styleable.ColorSeekBar_thumbBorder, 8f);
thumbInnerColor = typedArray.getColor(R.styleable.ColorSeekBar_thumbBorderColor, Color.WHITE);
typedArray.recycle();
rectPaint.setAntiAlias(true);
thumbInnerPaint.setAntiAlias(true);
thumbInnerPaint.setColor(thumbInnerColor);
thumbPaint.setAntiAlias(true);
if(thumbRadius < minThumbRadius){
thumbRadius = minThumbRadius;
}else {
thumbRadius = (float)barHeight / 2;
}
thumbBorderRadius = thumbRadius + thumbBorder;
canvasHeight = (int) (thumbBorderRadius * 3);
thumbY = (float)canvasHeight / 2;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
getParent().requestDisallowInterceptTouchEvent(true);
thumbX = event.getX();
invalidate();
if (colorChangeListener != null) {
colorChangeListener.onColorChangeListener(getColor());
}
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//如果类型为透明度
if (mType == TYPE_ALPHA) {
colorSeeds = new int[]{rgbWithAlpha(thumbPaint.getColor(), mMax), rgbWithAlpha(thumbPaint.getColor(), mMin)};
colorGradient = new LinearGradient(0f, 0f, w, 0f, colorSeeds, null, Shader.TileMode.CLAMP);
} else {
colorSeeds = new int[]{rgbWithSaturation(thumbPaint.getColor(), mMax), rgbWithSaturation(thumbPaint.getColor(), mMin)};
colorGradient = new LinearGradient(0f, 0f, w, 0f, colorSeeds, null, Shader.TileMode.CLAMP);
}
//设置渐变效果
rectPaint.setShader(colorGradient);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, canvasHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
barLeft = paddingStart;
barRight = getWidth() - paddingEnd;
barTop = (float)((canvasHeight / 2 ) - (barHeight / 2));
barBottom = (float)((canvasHeight / 2) + (barHeight / 2));
rectF.set(barLeft , barTop , barRight , barBottom);
canvas.drawRoundRect(rectF , barCornerRadius, barCornerRadius, rectPaint);
//如果有设置当前值,调用setCurrentValue()
if(hasCurrentValue){
thumbX = (int)((float)currentValue / 255.0 * (barRight - barLeft));
hasCurrentValue = false;
}else {
if (thumbX < barLeft) {
thumbX = barLeft;
} else if (thumbX > barRight) {
thumbX = barRight;
}
}
int color = pickColor(thumbX, getWidth());
thumbPaint.setColor(color);
// 画滑块
canvas.drawCircle(thumbX, thumbY, thumbBorderRadius, thumbPaint);
canvas.drawCircle(thumbX, thumbY, thumbRadius, thumbInnerPaint);
}
/**
* 获取颜色
* @param position
* @param canvasWidth
* @return
*/
private int pickColor(float position , int canvasWidth){
//value 的范围为 min 到 max
float value = mMax - ((position - paddingStart) / (canvasWidth - (paddingStart + paddingEnd)) * mMax);
if(mType == TYPE_ALPHA){
if(value <= mMin){
return rgbWithAlpha(thumbPaint.getColor() , mMin);
}else if(value >= mMax){
return rgbWithAlpha(thumbPaint.getColor() , mMax);
}else {
return rgbWithAlpha(thumbPaint.getColor() , (int) value);
}
}else {
if(value <= mMin){
return rgbWithSaturation(thumbPaint.getColor() , mMin);
}else if(value >= mMax){
return rgbWithSaturation(thumbPaint.getColor() , mMax);
}else {
return rgbWithSaturation(thumbPaint.getColor() , (int) value);
}
}
}
/**
* 修改透明度
*
* @param color
* @param currentAlpha
* @return 修改后的颜色值
*/
private int rgbWithAlpha(int color, int currentAlpha) {
if (currentAlpha < 0) {
currentAlpha = 0;
} else if (currentAlpha > 255) {
currentAlpha = 255;
}
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int argb = Color.argb(currentAlpha, red, green, blue);
return argb;
}
/**
* 修改饱和度
*
* @param color
* @param currentSaturation
* @return 修改后的颜色值
*/
private int rgbWithSaturation(int color, int currentSaturation) {
if (currentSaturation < 0) {
currentSaturation = 0;
} else if (currentSaturation > 255) {
currentSaturation = 255;
}
float[] hsv = {0, 0, 0};
Color.colorToHSV(color, hsv);
float saturation = (float) currentSaturation / 255;
hsv[1] = saturation;
int newColor = Color.HSVToColor(hsv);
return newColor;
}
public int getColor(){
return thumbPaint.getColor();
}
/**
* 设置类型
*
* @param type
*/
public void setType(int type) {
this.mType = type;
invalidate();
}
public void setColor(int color) {
thumbPaint.setColor(color);
invalidate();
}
public void setMin(int min) {
if(min <= 0){
this.mMin = 0;
}else {
this.mMin = min;
}
invalidate();
}
/**
* 设置当前值
* @param value
*/
public void setCurrentValue(int value){
hasCurrentValue = true;
if(value < 0){
currentValue = 0;
}else if(value > 255){
currentValue = 255;
}else {
currentValue = value;
}
invalidate();
}
public void setMax(int max) {
if(max >= 255){
this.mMax = 255;
}else {
this.mMax = max;
}
invalidate();
}
}
|
package com.thoughtworks.shoppingweb.service;
import com.thoughtworks.shoppingweb.domain.History;
import com.thoughtworks.shoppingweb.domain.User;
import com.thoughtworks.shoppingweb.persistence.HistoryMapper;
import com.thoughtworks.shoppingweb.persistence.UserMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class HistoryService {
@Autowired
HistoryMapper historyMapper;
@Autowired
UserMapper userMapper;
private final static Logger logPrint = Logger.getLogger(HistoryService.class);
public HistoryMapper getHistoryMapper() {
return historyMapper;
}
public void setHistoryMapper(HistoryMapper historyMapper) {
this.historyMapper = historyMapper;
}
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public List<History> getHistoryByUser(String userName) {
return historyMapper.getHistoryByUser(userName);
}
public boolean insertHistory(User user,History history){
try {
if(userMapper.findUserByName(user) != null) {
if(historyMapper.findHistory(history) != null){
return historyMapper.updateTime(history) > 0;
}
else{
return historyMapper.insertHistory(history)>0;
}
}
else {
return (userMapper.insertUser(user)>0 && historyMapper.insertHistory(history)>0);
}
}catch (Exception e) {
logPrint.error(e);
}
return false;
}
}
|
/*
* 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.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
/**
* The root interface for accessing a Spring bean container.
*
* <p>This is the basic client view of a bean container;
* further interfaces such as {@link ListableBeanFactory} and
* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
* are available for specific purposes.
*
* <p>This interface is implemented by objects that hold a number of bean definitions,
* each uniquely identified by a String name. Depending on the bean definition,
* the factory will return either an independent instance of a contained object
* (the Prototype design pattern), or a single shared instance (a superior
* alternative to the Singleton design pattern, in which the instance is a
* singleton in the scope of the factory). Which type of instance will be returned
* depends on the bean factory configuration: the API is the same. Since Spring
* 2.0, further scopes are available depending on the concrete application
* context (e.g. "request" and "session" scopes in a web environment).
*
* <p>The point of this approach is that the BeanFactory is a central registry
* of application components, and centralizes configuration of application
* components (no more do individual objects need to read properties files,
* for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and
* Development" for a discussion of the benefits of this approach.
*
* <p>Note that it is generally better to rely on Dependency Injection
* ("push" configuration) to configure application objects through setters
* or constructors, rather than use any form of "pull" configuration like a
* BeanFactory lookup. Spring's Dependency Injection functionality is
* implemented using this BeanFactory interface and its subinterfaces.
*
* <p>Normally a BeanFactory will load bean definitions stored in a configuration
* source (such as an XML document), and use the {@code org.springframework.beans}
* package to configure the beans. However, an implementation could simply return
* Java objects it creates as necessary directly in Java code. There are no
* constraints on how the definitions could be stored: LDAP, RDBMS, XML,
* properties file, etc. Implementations are encouraged to support references
* amongst beans (Dependency Injection).
*
* <p>In contrast to the methods in {@link ListableBeanFactory}, all of the
* operations in this interface will also check parent factories if this is a
* {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance,
* the immediate parent factory will be asked. Beans in this factory instance
* are supposed to override beans of the same name in any parent factory.
*
* <p>Bean factory implementations should support the standard bean lifecycle interfaces
* as far as possible. The full set of initialization methods and their standard order is:
* <ol>
* <li>BeanNameAware's {@code setBeanName}
* <li>BeanClassLoaderAware's {@code setBeanClassLoader}
* <li>BeanFactoryAware's {@code setBeanFactory}
* <li>EnvironmentAware's {@code setEnvironment}
* <li>EmbeddedValueResolverAware's {@code setEmbeddedValueResolver}
* <li>ResourceLoaderAware's {@code setResourceLoader}
* (only applicable when running in an application context)
* <li>ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
* (only applicable when running in an application context)
* <li>MessageSourceAware's {@code setMessageSource}
* (only applicable when running in an application context)
* <li>ApplicationContextAware's {@code setApplicationContext}
* (only applicable when running in an application context)
* <li>ServletContextAware's {@code setServletContext}
* (only applicable when running in a web application context)
* <li>{@code postProcessBeforeInitialization} methods of BeanPostProcessors
* <li>InitializingBean's {@code afterPropertiesSet}
* <li>a custom {@code init-method} definition
* <li>{@code postProcessAfterInitialization} methods of BeanPostProcessors
* </ol>
*
* <p>On shutdown of a bean factory, the following lifecycle methods apply:
* <ol>
* <li>{@code postProcessBeforeDestruction} methods of DestructionAwareBeanPostProcessors
* <li>DisposableBean's {@code destroy}
* <li>a custom {@code destroy-method} definition
* </ol>
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @since 13 April 2001
* @see BeanNameAware#setBeanName
* @see BeanClassLoaderAware#setBeanClassLoader
* @see BeanFactoryAware#setBeanFactory
* @see org.springframework.context.EnvironmentAware#setEnvironment
* @see org.springframework.context.EmbeddedValueResolverAware#setEmbeddedValueResolver
* @see org.springframework.context.ResourceLoaderAware#setResourceLoader
* @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher
* @see org.springframework.context.MessageSourceAware#setMessageSource
* @see org.springframework.context.ApplicationContextAware#setApplicationContext
* @see org.springframework.web.context.ServletContextAware#setServletContext
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
* @see InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor#postProcessBeforeDestruction
* @see DisposableBean#destroy
* @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
*/
public interface BeanFactory {
/**
* Used to dereference a {@link FactoryBean} instance and distinguish it from
* beans <i>created</i> by the FactoryBean. For example, if the bean named
* {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
* will return the factory, not the instance returned by the factory.
*/
String FACTORY_BEAN_PREFIX = "&";
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the
* Singleton or Prototype design pattern. Callers may retain references to
* returned objects in the case of Singleton beans.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @return an instance of the bean.
* Note that the return value will never be {@code null} but possibly a stub for
* {@code null} returned from a factory method, to be checked via {@code equals(null)}.
* Consider using {@link #getBeanProvider(Class)} for resolving optional dependencies.
* @throws NoSuchBeanDefinitionException if there is no bean with the specified name
* @throws BeansException if the bean could not be obtained
*/
Object getBean(String name) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
* safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
* required type. This means that ClassCastException can't be thrown on casting
* the result correctly, as can happen with {@link #getBean(String)}.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean.
* Note that the return value will never be {@code null}. In case of a stub for
* {@code null} from a factory method having been resolved for the requested bean, a
* {@code BeanNotOfRequiredTypeException} against the NullBean stub will be raised.
* Consider using {@link #getBeanProvider(Class)} for resolving optional dependencies.
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
*/
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
Object getBean(String name, Object... args) throws BeansException;
/**
* Return the bean instance that uniquely matches the given object type, if any.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the single bean matching the required type
* @throws NoSuchBeanDefinitionException if no bean of the given type was found
* @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
* @throws BeansException if the bean could not be created
* @since 3.0
* @see ListableBeanFactory
*/
<T> T getBean(Class<T> requiredType) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 4.1
*/
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
/**
* Return a provider for the specified bean, allowing for lazy on-demand retrieval
* of instances, including availability and uniqueness options.
* <p>For matching a generic type, consider {@link #getBeanProvider(ResolvableType)}.
* @param requiredType type the bean must match; can be an interface or superclass
* @return a corresponding provider handle
* @since 5.1
* @see #getBeanProvider(ResolvableType)
*/
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
/**
* Return a provider for the specified bean, allowing for lazy on-demand retrieval
* of instances, including availability and uniqueness options. This variant allows
* for specifying a generic type to match, similar to reflective injection points
* with generic type declarations in method/constructor parameters.
* <p>Note that collections of beans are not supported here, in contrast to reflective
* injection points. For programmatically retrieving a list of beans matching a
* specific type, specify the actual bean type as an argument here and subsequently
* use {@link ObjectProvider#orderedStream()} or its lazy streaming/iteration options.
* <p>Also, generics matching is strict here, as per the Java assignment rules.
* For lenient fallback matching with unchecked semantics (similar to the ´unchecked´
* Java compiler warning), consider calling {@link #getBeanProvider(Class)} with the
* raw type as a second step if no full generic match is
* {@link ObjectProvider#getIfAvailable() available} with this variant.
* @return a corresponding provider handle
* @param requiredType type the bean must match; can be a generic type declaration
* @since 5.1
* @see ObjectProvider#iterator()
* @see ObjectProvider#stream()
* @see ObjectProvider#orderedStream()
*/
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
/**
* Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name?
* <p>If the given name is an alias, it will be translated back to the corresponding
* canonical bean name.
* <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
* be found in this factory instance.
* <p>If a bean definition or singleton instance matching the given name is found,
* this method will return {@code true} whether the named bean definition is concrete
* or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
* return value from this method does not necessarily indicate that {@link #getBean}
* will be able to obtain an instance for the same name.
* @param name the name of the bean to query
* @return whether a bean with the given name is present
*/
boolean containsBean(String name);
/**
* Is this bean a shared singleton? That is, will {@link #getBean} always
* return the same instance?
* <p>Note: This method returning {@code false} does not clearly indicate
* independent instances. It indicates non-singleton instances, which may correspond
* to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly
* check for independent instances.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean corresponds to a singleton instance
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @see #getBean
* @see #isPrototype
*/
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
/**
* Is this bean a prototype? That is, will {@link #getBean} always return
* independent instances?
* <p>Note: This method returning {@code false} does not clearly indicate
* a singleton object. It indicates non-independent instances, which may correspond
* to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly
* check for a shared singleton instance.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean will always deliver independent instances
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.3
* @see #getBean
* @see #isSingleton
*/
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
/**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code ResolvableType})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 4.2
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
/**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code Class})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.1
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
/**
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}. This may lead to the initialization
* of a previously uninitialized {@code FactoryBean} (see {@link #getType(String, boolean)}).
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 1.1.2
* @see #getBean
* @see #isTypeMatch
*/
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
/**
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}. Depending on the
* {@code allowFactoryBeanInit} flag, this may lead to the initialization of a previously
* uninitialized {@code FactoryBean} if no early type information is available.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param allowFactoryBeanInit whether a {@code FactoryBean} may get initialized
* just for the purpose of determining its object type
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 5.2
* @see #getBean
* @see #isTypeMatch
*/
@Nullable
Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
/**
* Return the aliases for the given bean name, if any.
* <p>All of those aliases point to the same bean when used in a {@link #getBean} call.
* <p>If the given name is an alias, the corresponding original bean name
* and other aliases (if any) will be returned, with the original bean name
* being the first element in the array.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the bean name to check for aliases
* @return the aliases, or an empty array if none
* @see #getBean
*/
String[] getAliases(String name);
}
|
package com.power.thin.downloadmanager.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unused")
public class SQLiteUtils {
private DatabaseHelper mDatabaseHelper;
public SQLiteUtils(Context context) {
mDatabaseHelper = new DatabaseHelper(context);
}
public SQLiteUtils(Context context, String name, CursorFactory cursorFactory, int version) {
mDatabaseHelper = new DatabaseHelper(context, name, cursorFactory, version);
}
/**
* 保存下载任务信息到数据库
*
* @param downloadInfoBean 下载信息描述类
*/
public void saveDownloadInfo(DownloadInfoBean downloadInfoBean) {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DownloadInfoTable.REQUEST_ID, downloadInfoBean.getRequestId());
cv.put(DownloadInfoTable.DOWNLOAD_URL, downloadInfoBean.getDownloadUrl());
cv.put(DownloadInfoTable.DESTINATION_FILE_PATH, downloadInfoBean.getDestinationPath());
cv.put(DownloadInfoTable.TOTAL_SIZE, downloadInfoBean.getTotalSize());
cv.put(DownloadInfoTable.DOWNLOAD_SIZE, downloadInfoBean.getDownloadSize());
Cursor cursor = null;
try {
cursor = db.rawQuery(
"SELECT * FROM " + DownloadInfoTable.TABLE_NAME
+ " WHERE " + DownloadInfoTable.REQUEST_ID + "=?",
new String[]{String.valueOf(downloadInfoBean.getRequestId())});
if (cursor != null && cursor.moveToFirst()) {
db.update(DownloadInfoTable.TABLE_NAME, cv, DownloadInfoTable.REQUEST_ID + "= ?",
new String[]{String.valueOf(downloadInfoBean.getRequestId())});
} else {
db.insert(DownloadInfoTable.TABLE_NAME, null, cv);
}
} finally {
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
}
public DownloadInfoBean getDownloadInfo(int requestId) {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
DownloadInfoBean bean = null;
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM" + DownloadInfoTable.TABLE_NAME
+ " WHERE " + DownloadInfoTable.REQUEST_ID + " = ?",
new String[]{String.valueOf(requestId)});
if (cursor != null && cursor.moveToFirst()) {
bean = new DownloadInfoBean();
bean.setRequestId(requestId);
bean.setDownloadUrl(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.DOWNLOAD_URL)));
bean.setDestinationPath(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.DESTINATION_FILE_PATH)));
bean.setTotalSize(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.TOTAL_SIZE)));
bean.setDownloadSize(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.DOWNLOAD_SIZE)));
}
} finally {
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return bean;
}
public List<DownloadInfoBean> getAllDownloadInfo() {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
Cursor cursor = null;
List<DownloadInfoBean> downloadInfoBeanList = new ArrayList<DownloadInfoBean>();
try {
cursor = db.rawQuery("SELECT * FROM" + DownloadInfoTable.TABLE_NAME, null);
if (cursor != null && cursor.moveToFirst()) {
DownloadInfoBean bean = new DownloadInfoBean();
bean.setRequestId(cursor.getInt(
cursor.getColumnIndex(DownloadInfoTable.REQUEST_ID)));
bean.setDownloadUrl(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.DOWNLOAD_URL)));
bean.setDestinationPath(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.DESTINATION_FILE_PATH)));
bean.setTotalSize(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.TOTAL_SIZE)));
bean.setDownloadSize(cursor.getString(
cursor.getColumnIndex(DownloadInfoTable.DOWNLOAD_SIZE)));
downloadInfoBeanList.add(bean);
}
} finally {
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return downloadInfoBeanList;
}
public int deleteDownloadInfo(int requestId) {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
int affectedNum = 0;
try {
affectedNum = db.delete(
DownloadInfoTable.TABLE_NAME,
DownloadInfoTable.REQUEST_ID + " = ?",
new String[]{String.valueOf(requestId)});
} finally {
if (db != null) {
db.close();
}
}
return affectedNum;
}
public int deleteAllDownloadInfo() {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
int affectedNum = 0;
try {
affectedNum = db.delete(DownloadInfoTable.TABLE_NAME, null, null);
} finally {
if (db != null) {
db.close();
}
}
return affectedNum;
}
}
|
package f.star.iota.milk.ui.moe005tv.moe;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import f.star.iota.milk.R;
import f.star.iota.milk.base.BaseAdapter;
public class MOE005TVAdapter extends BaseAdapter<MOE005TVViewHolder, MOE005TVBean> {
@Override
public MOE005TVViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MOE005TVViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description_with_tag, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((MOE005TVViewHolder) holder).bindView(mBeans.get(position));
}
}
|
package com.next.apps.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.*;
import java.math.BigDecimal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.next.apps.repo.query.RepoORDR;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OCRDServiceTest extends ServiceTestBase
{
@Autowired
private ORDRService svcOrder;
@MockBean
private OCRDService svcOCRD;
@Test
public void test() throws Exception
{
/*given(this.svcOCRD.checkBalance())
.willReturn(BigDecimal.ONE)
.willReturn(BigDecimal.valueOf(2));*/
when(this.svcOCRD.checkBalance())
.thenReturn(BigDecimal.ONE)
.thenReturn(BigDecimal.valueOf(2));
BigDecimal credit = svcOrder.checkCredit();
assertThat(credit).isEqualTo(BigDecimal.valueOf(3));
}
}
|
package moon_lander;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* Landing area where rocket will land.
*
* @author www.gametutorial.net
*/
public class lunarSoil {
/**
* X coordinate of the landing area.
*/
public static int x;
/**
* Y coordinate of the landing area.
*/
public static int y;
/**
* Image of landing area.
*/
private BufferedImage lunarSoilImg;
/**
* Width of landing area.
*/
public static int lunarSoilImgWidth;
public static int lunarSoilImgHeight;
public lunarSoil()
{
Initialize();
LoadContent();
}
private void Initialize()
{
//lunarSoilImgHeight = lunarSoilImg.getHeight();
x = 0;
y = Framework.frameHeight - 62;
}
private void LoadContent()
{
try
{
URL landingAreaImgUrl = this.getClass().getResource("/moon_lander/resources/images/lunarSoil.png");
lunarSoilImg = ImageIO.read(landingAreaImgUrl);
lunarSoilImg.getScaledInstance(100, 95, Image.SCALE_DEFAULT);
lunarSoilImgWidth = lunarSoilImg.getWidth();
lunarSoilImgHeight = lunarSoilImg.getHeight();
}
catch (IOException ex) {
Logger.getLogger(lunarSoil.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void Draw(Graphics2D g2d)
{
g2d.drawImage(lunarSoilImg, x, y, null);
}
}
|
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import reactor.core.publisher.Flux;
import reactor.core.publisher.GroupedFlux;
/*
* This Java source file was generated by the Gradle 'init' task.
*/
public class Library {
public boolean someLibraryMethod() {
return true;
}
public static List<JsonObject> getActivity() {
Gson gson = new Gson();
JsonReader reader;
List<JsonObject> data = null;
Type REVIEW_TYPE = new TypeToken<List<JsonObject>>() {
}.getType();
try {
reader = new JsonReader(new FileReader("db.json"));
JsonObject jdata = gson.fromJson(reader, JsonObject.class); // convert response to JsonObject
data = gson.fromJson(jdata.get("eventlist"), REVIEW_TYPE); /// get the event list and convert to list
/// collection type
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
public static void main(String args[]) {
/*Flux<JsonObject> seq2 = Flux.fromIterable(getActivity());
seq2.subscribe(i -> {
//System.out.println("Flux from iterable example :" + i); do something
});*/
/*Flux.just(1, 3, 5, 2, 4, 6, 11, 12, 13).groupBy(i -> i % 2 == 0 ? "even" : "odd")
.concatMap(g -> g.defaultIfEmpty(-1) // if empty groups, show them
.map(String::valueOf) // map to string
.startWith(g.key()));// start with the group's key
*/
System.out.println(System.currentTimeMillis());
Flux.just("range1").map(i -> {return getActivity(i);}) // this is the starting point where you loop the ranges , add some meta data if you want
.subscribe( i -> { // this is the subscribe used in WebScocket . each item is a chunck
System.out.println(i.size());
for(Session s:i) {
System.out.println("+++++++++++++++++++++++++++++++");
for(Event e : s.getEventsList()) {
System.out.println(e.getSessionID());
}
}
}, error -> {} , () -> {/*on complete at the end of all chuncks , we can send this to UI to update events*/});
System.out.println(System.currentTimeMillis());
}
// getting activity from service as independent function
private static List<Session> getActivity( String tr){
List<Session> sessions = new ArrayList();
Flux.fromIterable(getActivity()).map(i -> {
return buildEvent(i);
}).groupBy(i -> i.getSessionID()).map(i -> {
return buildSession(i);
}).subscribe( i -> {if(i!=null) sessions.add(i);});
return sessions;
}
private static Event buildEvent(JsonObject obj) {
Event ev = new Event();
ev.setEventID(obj.get("eventID").toString());
ev.setSessionID(obj.get("sessionID").toString());
ev.setTimeStamp(obj.get("timestamp").toString());
ev.setEventName(obj.get("eventName").toString());
return ev;
}
private static Session buildSession(GroupedFlux<String, Event> i) {
Session ses = new Session();
List<Event> events= new ArrayList<Event>();
i.subscribe( j ->{ events.add(j) ;});
ses.setEventsList(events);
//check this group has AuthCLogin if not present return null ,add it to Orphan list
//if (has AuthC login ) then return TODO
return ses;
//else add it to Orphan list and return null TODO
}
}
class Session {
public String getSessionID() {
return sessionID;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public List<Event> getEventsList() {
return eventsList;
}
public void setEventsList(List eventsList) {
this.eventsList = eventsList;
}
String sessionID;
List eventsList;
}
class Event {
public String getEventID() {
return eventID;
}
public void setEventID(String eventID) {
this.eventID = eventID;
}
public String getSessionID() {
return sessionID;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
String eventID;
String sessionID;
String timeStamp;
String eventName;
}
|
package day0224;
import java.awt.Frame;
/**
* Container : Window, Frame, Pannel, Dialog..
* Component : Button, Radio, TextArea, TextField ..
* +add ~~Listener 메소드를 통해 UI와 Event연결
* Event : Event interface(~~Listener)를 이용하여 구현
* @author sist
*
*/
public class FrameTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
// FrameObject2 fr = new FrameObject2();
// FrameObject3 fr2 = new FrameObject3();
// FrameObject4 fr3 = new FrameObject4();
// FrameObject5 fr4 = new FrameObject5();
// FrameObject6 fr5 = new FrameObject6();
FrameObject7 fr6 = new FrameObject7();
}
}
|
package SpaceShoother;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseInput implements MouseListener {
/*
public Rectangle play=new Rectangle(250,250,200,60);
public Rectangle instructions=new Rectangle(250,350,200,60);
public Rectangle quit=new Rectangle(250,450,200,60);
*/
@Override
public void mouseClicked(MouseEvent e) {
int mX = e.getX();
int mY = e.getY();
if ((mX >= 250) && (mX <= 450))
if ((mY >= 250) && (mY <= 310)) {
MainFrame.state = MainFrame.STATE.GAME;
PowerUp.timer = System.currentTimeMillis();
Player.invincibleTime = true;
Player.timer = System.currentTimeMillis();
Controller.enemies_down = 0;
}
if ((mX >= 250) && (mX <= 450))
if ((mY >= 450) && (mY <= 510)) {
System.exit(1);
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
|
package com.mycompany.persistencia;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author elias
*/
@Entity
@Table(name = "RECEPCIONISTA")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Recepcionista.findAll", query = "SELECT r FROM Recepcionista r")
, @NamedQuery(name = "Recepcionista.findByRecId", query = "SELECT r FROM Recepcionista r WHERE r.recId = :recId")
, @NamedQuery(name = "Recepcionista.findByRecContra", query = "SELECT r FROM Recepcionista r WHERE r.recContra = :recContra")
, @NamedQuery(name = "Recepcionista.findByRecEmail", query = "SELECT r FROM Recepcionista r WHERE r.recEmail = :recEmail")
, @NamedQuery(name = "Recepcionista.findByRecNom", query = "SELECT r FROM Recepcionista r WHERE r.recNom = :recNom")
, @NamedQuery(name = "Recepcionista.findByRecApat", query = "SELECT r FROM Recepcionista r WHERE r.recApat = :recApat")
, @NamedQuery(name = "Recepcionista.findByRecAmat", query = "SELECT r FROM Recepcionista r WHERE r.recAmat = :recAmat")
, @NamedQuery(name = "Recepcionista.findByRecFna", query = "SELECT r FROM Recepcionista r WHERE r.recFna = :recFna")
, @NamedQuery(name = "Recepcionista.findByRecTelm", query = "SELECT r FROM Recepcionista r WHERE r.recTelm = :recTelm")
, @NamedQuery(name = "Recepcionista.findByRecTelc", query = "SELECT r FROM Recepcionista r WHERE r.recTelc = :recTelc")
, @NamedQuery(name = "Recepcionista.findByRecStatus", query = "SELECT r FROM Recepcionista r WHERE r.recStatus = :recStatus")})
public class Recepcionista implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "REC_ID")
private Integer recId;
@Basic(optional = false)
@Column(name = "REC_CONTRA")
private String recContra;
@Basic(optional = false)
@Column(name = "REC_EMAIL")
private String recEmail;
@Basic(optional = false)
@Column(name = "REC_NOM")
private String recNom;
@Basic(optional = false)
@Column(name = "REC_APAT")
private String recApat;
@Basic(optional = false)
@Column(name = "REC_AMAT")
private String recAmat;
@Basic(optional = false)
@Column(name = "REC_FNA")
@Temporal(TemporalType.DATE)
private Date recFna;
@Basic(optional = false)
@Column(name = "REC_TELM")
private String recTelm;
@Basic(optional = false)
@Column(name = "REC_TELC")
private String recTelc;
@Column(name = "REC_STATUS")
private Integer recStatus;
@OneToMany(mappedBy = "trRecid")
private List<TransaccionesRecep> transaccionesRecepCollection;
public Recepcionista() {
}
public Recepcionista(Integer recId) {
this.recId = recId;
}
public Recepcionista(Integer recId, String recContra, String recEmail, String recNom, String recApat, String recAmat, Date recFna, String recTelm, String recTelc) {
this.recId = recId;
this.recContra = recContra;
this.recEmail = recEmail;
this.recNom = recNom;
this.recApat = recApat;
this.recAmat = recAmat;
this.recFna = recFna;
this.recTelm = recTelm;
this.recTelc = recTelc;
}
public Integer getRecId() {
return recId;
}
public void setRecId(Integer recId) {
this.recId = recId;
}
public String getRecContra() {
return recContra;
}
public void setRecContra(String recContra) {
this.recContra = recContra;
}
public String getRecEmail() {
return recEmail;
}
public void setRecEmail(String recEmail) {
this.recEmail = recEmail;
}
public String getRecNom() {
return recNom;
}
public void setRecNom(String recNom) {
this.recNom = recNom;
}
public String getRecApat() {
return recApat;
}
public void setRecApat(String recApat) {
this.recApat = recApat;
}
public String getRecAmat() {
return recAmat;
}
public void setRecAmat(String recAmat) {
this.recAmat = recAmat;
}
public Date getRecFna() {
return recFna;
}
public void setRecFna(Date recFna) {
this.recFna = recFna;
}
public String getRecTelm() {
return recTelm;
}
public void setRecTelm(String recTelm) {
this.recTelm = recTelm;
}
public String getRecTelc() {
return recTelc;
}
public void setRecTelc(String recTelc) {
this.recTelc = recTelc;
}
public Integer getRecStatus() {
return recStatus;
}
public void setRecStatus(Integer recStatus) {
this.recStatus = recStatus;
}
@OneToOne(mappedBy = "recepcionista",
fetch = FetchType.LAZY, optional = false)
private Direccion_REC direccionrec;
public Direccion_REC getDireccionrec() {
return direccionrec;
}
public void setDireccionrec(Direccion_REC direccionrec) {
this.direccionrec = direccionrec;
}
@XmlTransient
public List<TransaccionesRecep> getTransaccionesRecepCollection() {
return transaccionesRecepCollection;
}
public void setTransaccionesRecepCollection(List<TransaccionesRecep> transaccionesRecepCollection) {
this.transaccionesRecepCollection = transaccionesRecepCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (recId != null ? recId.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 Recepcionista)) {
return false;
}
Recepcionista other = (Recepcionista) object;
if ((this.recId == null && other.recId != null) || (this.recId != null && !this.recId.equals(other.recId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.mycompany.persistencia.Recepcionista[ recId=" + recId + " ]";
}
}
|
package org.minicastle.jce.provider;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactorySpi;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.minicastle.asn1.ASN1Sequence;
import org.minicastle.asn1.ASN1TaggedObject;
import org.minicastle.asn1.BERInputStream;
import org.minicastle.asn1.DERInputStream;
import org.minicastle.asn1.DERObjectIdentifier;
import org.minicastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.minicastle.asn1.pkcs.SignedData;
import org.minicastle.asn1.x509.CertificateList;
import org.minicastle.asn1.x509.X509CertificateStructure;
import org.minicastle.util.encoders.Base64;
/**
* class for dealing with X509 certificates.
* <p>
* At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----"
* base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7
* objects.
*/
public class JDKX509CertificateFactory
extends CertificateFactorySpi
{
private SignedData sData = null;
private int sDataObjectCount = 0;
private String readLine(
InputStream in)
throws IOException
{
int c;
StringBuffer l = new StringBuffer();
while (((c = in.read()) != '\n') && (c >= 0))
{
if (c == '\r')
{
continue;
}
l.append((char)c);
}
if (c < 0)
{
return null;
}
return l.toString();
}
private Certificate readDERCertificate(
InputStream in)
throws IOException
{
DERInputStream dIn = new DERInputStream(in);
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof DERObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = new SignedData(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true));
return new X509CertificateObject(
X509CertificateStructure.getInstance(
sData.getCertificates().getObjectAt(sDataObjectCount++)));
}
}
return new X509CertificateObject(
X509CertificateStructure.getInstance(seq));
}
/**
* read in a BER encoded PKCS7 certificate.
*/
private Certificate readPKCS7Certificate(
InputStream in)
throws IOException
{
BERInputStream dIn = new BERInputStream(in);
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof DERObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = new SignedData(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true));
return new X509CertificateObject(
X509CertificateStructure.getInstance(
sData.getCertificates().getObjectAt(sDataObjectCount++)));
}
}
return new X509CertificateObject(
X509CertificateStructure.getInstance(seq));
}
private Certificate readPEMCertificate(
InputStream in)
throws IOException
{
String line;
StringBuffer pemBuf = new StringBuffer();
while ((line = readLine(in)) != null)
{
if (line.equals("-----BEGIN CERTIFICATE-----")
|| line.equals("-----BEGIN X509 CERTIFICATE-----"))
{
break;
}
}
while ((line = readLine(in)) != null)
{
if (line.equals("-----END CERTIFICATE-----")
|| line.equals("-----END X509 CERTIFICATE-----"))
{
break;
}
pemBuf.append(line);
}
if (pemBuf.length() != 0)
{
ByteArrayInputStream bIn = new ByteArrayInputStream(Base64.decode(pemBuf.toString()));
return readDERCertificate(bIn);
}
return null;
}
private CRL readDERCRL(
InputStream in)
throws IOException
{
DERInputStream dIn = new DERInputStream(in);
return new X509CRLObject(new CertificateList((ASN1Sequence)dIn.readObject()));
}
private CRL readPEMCRL(
InputStream in)
throws IOException
{
String line;
StringBuffer pemBuf = new StringBuffer();
while ((line = readLine(in)) != null)
{
if (line.equals("-----BEGIN CRL-----")
|| line.equals("-----BEGIN X509 CRL-----"))
{
break;
}
}
while ((line = readLine(in)) != null)
{
if (line.equals("-----END CRL-----")
|| line.equals("-----END X509 CRL-----"))
{
break;
}
pemBuf.append(line);
}
if (pemBuf.length() != 0)
{
ByteArrayInputStream bIn = new ByteArrayInputStream(Base64.decode(pemBuf.toString()));
return readDERCRL(bIn);
}
return null;
}
/**
* Generates a certificate object and initializes it with the data
* read from the input stream inStream.
*/
public Certificate engineGenerateCertificate(
InputStream in)
throws CertificateException
{
if (sData != null && sDataObjectCount != sData.getCertificates().size())
{
return new X509CertificateObject(
X509CertificateStructure.getInstance(
sData.getCertificates().getObjectAt(sDataObjectCount++)));
}
if (!in.markSupported())
{
in = new BufferedInputStream(in);
}
try
{
in.mark(10);
int tag = in.read();
if (tag == -1)
{
return null;
}
if (tag != 0x30) // assume ascii PEM encoded.
{
in.reset();
return readPEMCertificate(in);
}
else if (in.read() == 0x80) // assume BER encoded.
{
in.reset();
return readPKCS7Certificate(in);
}
else
{
in.reset();
return readDERCertificate(in);
}
}
catch (IOException e)
{
throw new CertificateException(e.toString());
}
}
/**
* Returns a (possibly empty) collection view of the certificates
* read from the given input stream inStream.
*/
public Collection engineGenerateCertificates(
InputStream inStream)
throws CertificateException
{
Certificate cert;
ArrayList certs = new ArrayList();
while ((cert = engineGenerateCertificate(inStream)) != null)
{
certs.add(cert);
}
return certs;
}
/**
* Generates a certificate revocation list (CRL) object and initializes
* it with the data read from the input stream inStream.
*/
public CRL engineGenerateCRL(
InputStream inStream)
throws CRLException
{
if (!inStream.markSupported())
{
inStream = new BufferedInputStream(inStream);
}
try
{
inStream.mark(10);
if (inStream.read() != 0x30) // assume ascii PEM encoded.
{
inStream.reset();
return readPEMCRL(inStream);
}
else
{
inStream.reset();
return readDERCRL(inStream);
}
}
catch (IOException e)
{
throw new CRLException(e.toString());
}
}
/**
* Returns a (possibly empty) collection view of the CRLs read from
* the given input stream inStream.
*
* The inStream may contain a sequence of DER-encoded CRLs, or
* a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the
* only signficant field being crls. In particular the signature
* and the contents are ignored.
*/
public Collection engineGenerateCRLs(
InputStream inStream)
throws CRLException
{
return null;
}
public Iterator engineGetCertPathEncodings()
{
return PKIXCertPath.certPathEncodings.iterator();
}
public CertPath engineGenerateCertPath(
InputStream inStream)
throws CertificateException
{
return engineGenerateCertPath( inStream, "PkiPath" );
}
public CertPath engineGenerateCertPath(
InputStream inStream,
String encoding)
throws CertificateException
{
return new PKIXCertPath( inStream, encoding );
}
public CertPath engineGenerateCertPath(
List certificates)
throws CertificateException
{
Iterator iter = certificates.iterator();
Object obj;
while ( iter.hasNext() )
{
obj = iter.next();
if ( obj != null ) {
if ( ! ( obj instanceof X509Certificate ) )
{
throw new CertificateException( "list contains none X509Certificate object while creating CertPath\n" + obj.toString() );
}
}
}
return new PKIXCertPath( certificates );
}
}
|
/*
* 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 agh.musicapplication.mappdao;
import agh.musicapplication.mappdao.interfaces.MBandRepositoryInterface;
import agh.musicapplication.mappmodel.MBand;
import java.io.Serializable;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author ag
*/
@Repository
@Transactional
public class MBandRepository extends AbstractCrudRepository<MBand> implements Serializable,MBandRepositoryInterface{
@Override
public MBand findBandByName(String band) {
Query query = getSession().createQuery("from MBand where name = :band");
query.setParameter("band", band);
return (MBand) query.uniqueResult();
}
}
|
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.test.base.Solution;
/**
* https://www.acwing.com/solution/leetcode/content/4699/
*
* 1,假设最大的长度为a,则比它大的长度,一定是没有结果的;因此,可以用二分法,求出这个a。
*
* 2,固定长度,则移动1位,利用hash求值,避免全部比较。
*
* - 先寻找length
* - length 对应的长度hash值进行比较
* 时间复杂度:O(n*logn)
*
* @author YLine
*
* 2019年11月21日 下午6:00:19
*/
public class SolutionC implements Solution
{
private static final int MOD = 838_4287; // 找到的一个很大的质数了
@Override
public String longestDupSubstring(String S)
{
HashPlugin plugin = new HashPlugin(S.length());
String mResult = null;
int left = 0, right = S.length() - 1;
while (left < right)
{
int mid = (left + right) >>> 1;
mResult = getDupSubstring(S, plugin, mid + 1);
if (null == mResult)
{
right = mid;
}
else
{
left = mid + 1;
}
}
int length = left;
if (length == 0)
{
return "";
}
if (null != mResult && length == mResult.length())
{
return mResult;
}
else
{
return getDupSubstring(S, plugin, length);
}
}
/**
* .计算当前长度,是否有重复的字符串
* @param S
* @param plugin
* @param length 长度
* @return
*/
private String getDupSubstring(String S, HashPlugin plugin, int length)
{
int startHash = plugin.getHash(S, 0, length);
// 添加hash 到 index的关联
HashMap<Integer, List<Integer>> cacheMap = new HashMap<>();
List<Integer> list = new ArrayList<>(2);
list.add(0);
cacheMap.put(startHash, list);
int preHash = startHash;
final int endIndex = S.length() - length;
for (int i = 1; i <= endIndex; i++)
{
// int hash = plugin.getHash(S, i, length);
int hash = plugin.getHashByPre(S, preHash, i - 1, length);
if (cacheMap.containsKey(hash))
{
if (isEqual(S, cacheMap.get(hash), i, length))
{
return S.substring(i, i + length);
}
else
{
cacheMap.get(hash).add(i);
}
}
else
{
List<Integer> tempList = new ArrayList<>(2);
tempList.add(i);
cacheMap.put(hash, tempList);
}
preHash = hash;
}
return null;
}
/**
* .判断两个字符串是否相等
* @param S
* @param tempList
* @param index
* @return
*/
private boolean isEqual(String S, List<Integer> tempList, int index, int length)
{
for (int i = 0; i < tempList.size(); i++)
{
int preStart = tempList.get(i);
boolean isEqual = true;
for (int k = 0; k < length; k++)
{
// 不相等
if (S.charAt(index + k) != S.charAt(preStart + k))
{
isEqual = false;
break;
}
}
if (isEqual)
{
return true;
}
}
return false;
}
private static class HashPlugin
{
private final int[] power;
/**
* .对于String hash值计算公式为: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
*
* .针对于当前的情况,系数反过来,会比较合适;因此,公式为:
* hash[n] = s[0]*31^0 + s[1]*31^1 + ... + s[n-1]*31^(n-1)
*
* .换成通用式,对于长度为n,起点为i的hash值
* hash[i, n] = s[i]*31^0 + s[i+1]*31^1 + ... + s[i+n-1]*31^(n-1)
* hash[i+1, n] = s[i+1]*31^0 + ... + s[i+n-1]*31^(n-2) + s[i+n]*31^(n-1)
*
* .则可以得到递推式:
* hash[i+1, n] = (hash[i, n] - s[i]*31^0) / 31 + s[i+n]*31^(n-1)
*
* .由于存在,Integer的越界,因此,递推式,失效。
*
* .改善方案:引入一个较大的质数,不能太大,避免乘法直接越界,1_1134_7293,mod
* mod < MAX_VALUE / 256
* mod < 8 388 607,因此,选取的质数为:838_4287
*
* @param length 总的长度
*/
public HashPlugin(int size)
{
power = new int[size];
power[0] = 1;
for (int i = 1; i < size; i++)
{
power[i] = 31 * power[i - 1];
power[i] /= MOD;
}
}
/**
* .计算第一个 hash值
* @param S 字符串
* @param start 起始位置
* @param length 长度
* @return hash值
*/
public int getHash(String S, int start, int length)
{
int hash = 0;
for (int i = 0; i < length; i++)
{
hash += (S.charAt(i + start) * power[i]);
hash /= MOD;
}
return hash;
}
/**
* .依据前一个值,计算下一个的hash值
*
* @param S 字符串
* @param preHash 前一个hash值
* @param preStart 前一个hash开始的位置
* @param length 长度
* @return hash值
*/
public int getHashByPre(String S, int preHash, int preStart, int length)
{
int diffA = (preHash - S.charAt(preStart) + MOD) / 31;
int diffB = S.charAt(preStart + length) * power[length - 1];
return (diffA + diffB / MOD) / MOD;
}
}
}
|
package com.oheers.fish.competition;
import com.oheers.fish.EvenMoreFish;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class JoinChecker implements Listener {
// Gives the player the active fishing bar if there's a fishing event cracking off
@EventHandler
public void onJoin(PlayerJoinEvent event) {
if (EvenMoreFish.active != null) {
EvenMoreFish.active.getBar().addPlayer(event.getPlayer());
}
}
// Removes the player from the bar list if they leave the server
@EventHandler
public void onLeave(PlayerQuitEvent event) {
if (EvenMoreFish.active != null) {
EvenMoreFish.active.getBar().removePlayer(event.getPlayer());
}
}
}
|
package com.example.jiaheng.mapsensor;
/**
* Created by Jiaheng on 4/2/17.
*/
public class Calc {
public static double calculateAngle(double lat1, double lon1, double lat2, double lon2) {
double dLon = (lon2 - lon1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return brng;
}
}
|
package com.sinodynamic.hkgta.dao.mms;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.dto.mms.GuestRequestDto;
import com.sinodynamic.hkgta.entity.crm.CustomerProfile;
import com.sinodynamic.hkgta.entity.crm.Member;
import com.sinodynamic.hkgta.entity.mms.SpaMemberSync;
import com.sinodynamic.hkgta.util.CommUtil;
import com.sinodynamic.hkgta.util.constant.Constant;
@Repository
public class SpaMemberSyncDaoImpl extends GenericDao<SpaMemberSync> implements SpaMemberSyncDao {
@Override
public List<GuestRequestDto> getMemberInfoList2Synchronize(String status) {
String sql = "select "
+ "sms.sys_id as sysId, "
+ "(select sms1.spa_guest_id from spa_member_sync sms1 where sms1.customer_id = sms.customer_id and sms1.action = 'INSERT' and sms1.status = 'CMP') as guestId, "
+ "sms.action as action, "
+ "me.academy_no as guestCode, "
+ "cp.given_name as firstName, "
+ "cp.surname as lastName, "
+ "cp.phone_mobile as mobilePhone, "
+ "cp.contact_email as email, "
+ "cp.gender as gender, "
+ "cp.postal_address1 as address1, "
+ "cp.postal_address2 as address2 "
+ "from spa_member_sync sms "
+ "inner join member me on me.customer_id = sms.customer_id "
+ "inner join customer_profile cp on sms.customer_id = cp.customer_id "
+ "where sms.status = ?";
List<Serializable> params = new ArrayList<Serializable>();
params.add(status);
return getDtoBySql(sql, params, GuestRequestDto.class);
}
@Override
public List<SpaMemberSync> getSpecificSpaMemberSync(Long customerId, String status) {
String hql = "from SpaMemberSync where customerId = ? and status = ?";
List<Serializable> params = new ArrayList<Serializable>();
params.add(customerId);
params.add(status);
return getByHql(hql, params);
}
@Override
public void addSpaMemberSyncWhenInsert(Member member) {
SpaMemberSync entity = new SpaMemberSync();
entity.setCustomerId(member.getCustomerId());
entity.setAction(Constant.MEMBER_SYNCHRONIZE_INSERT);
entity.setCreateDate(new Date());
entity.setRetryCount(0);
entity.setStatus(Constant.STATUS_WAITING_TO_SYNCHRONIZE);
save(entity);
}
@Override
public void addSpaMemberSyncWhenUpdate(CustomerProfile oldThis, CustomerProfile newThis) {
if (oldThis == null || newThis == null) return;
String surName = CommUtil.nvl(newThis.getSurname());
String givenName = CommUtil.nvl(newThis.getGivenName());
String contactEmail = CommUtil.nvl(newThis.getContactEmail());
String phoneMobile = CommUtil.nvl(newThis.getPhoneMobile());
String gender = CommUtil.nvl(newThis.getGender());
if (surName.equals(oldThis.getSurname()) && givenName.equals(oldThis.getGivenName())
&& contactEmail.equals(oldThis.getContactEmail())
&& phoneMobile.equals(oldThis.getPhoneMobile())
&& gender.equals(oldThis.getGender())) return;
SpaMemberSync entity = new SpaMemberSync();
entity.setCustomerId(oldThis.getCustomerId());
entity.setAction(Constant.MEMBER_SYNCHRONIZE_UPDATE);
entity.setCreateDate(new Date());
entity.setRetryCount(0);
entity.setStatus(Constant.STATUS_WAITING_TO_SYNCHRONIZE);
save(entity);
}
}
|
package com.example.dylanodekirk.zeldaapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class EquipmentActivity extends AppCompatActivity {
ListAdapater mListAdapter;
ListView mItemListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_equipment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Start copy
//list of items
ArrayList<Item> itemList = new ArrayList<Item>();
//create items to be passed to list
Item item1 = new Item("Wooden Sword", R.mipmap.e9,
"The wooden sword is given to you by Rusl. This item is used in a short tutorial at the beginning of the game" +
" teaching the player how to fight as Link shows the children how to use a sword. " +
"After this Talo takes it, so it's never used on anything other than bucket-headed practice dummies.");
Item item2 = new Item("Ordon Sword", R.mipmap.e7,
"he Ordon Sword is obtained in Ordon Village the first time you are a wolf. It is in Rusl's house after you get the shield.");
Item item3 = new Item("Master Sword", R.mipmap.e5,
"Before you get the Master Sword you must have saved Midna after Lakebed Temple," +
"spoken to Zelda, and returned to Faron Woods. It is obtained by defeating the Skull Kid for the first time in the Sacred Grove." +
"This sword can be upgraded into the Light Sword, which can repel fog, deliver light to some sacred orbs, and kill Twilight with a single blow.");
Item item4 = new Item("Ordon Sheild", R.mipmap.e6,
"The Ordon Shield is the first shield you will get in the game. It is found in Jaggle's house in Ordon Village. " +
"It is susceptible to fire and can be destroyed. There is only one Ordon Shield, but it can be replaced by the Hylian Shield or Wooden Shield");
Item item5 = new Item("Wooden Sheild", R.mipmap.e8,
"The Wooden Shield can be purchased from either the Malo Mart in Kakariko Village or the Goron Shop on Death Mountain. " +
"It is identical to the Ordon Shield except in appearance and can only be purchased if the Ordon Shield has been destroyed by fire.");
Item item6 = new Item("Hylian Shield", R.mipmap.e4,
"The Hylian Sheild can be purchased at the Malo Mart in Kakariko Village for 200 Rupees. Unlike the Ordon Shield and Wooden Shield, the Hylian Shield is impervious to fire," +
" and can also deflect magical attacks. It is very useful to have before you enter the goron mines.");
Item item7 = new Item("Hero's Clothes", R.mipmap.e2,
" Link's traditional green tunic, this armor provides a little bit of defense compared to the Ordonian Outfit or Wolf Form. " +
"Link gets this outfit from Faron after restoring light to the Faron Province. " +
"These clothes are the same ones that the Link from Ocarina of Time and Majora's Mask wore.");
Item item8 = new Item("Zora Armor", R.mipmap.e1,
"Link will get this outfit at the end of the escort mission before heading to Lakebed Temple. Refer to the After Goron Mines section for help and where you can find it." +
" This armor will enable you to swim, dive and breathe underwater just like a Zora. However, you will be more vulnerable to fire and ice attacks while wearing it.");
Item item9 = new Item("Magic Armor", R.mipmap.e3,
"This armor is magical, and not only because of the rate at which it depletes your rupees. " +
"That's right, this armor runs on money, and while it may not be cheap, it'll keep you well protected." +
"So how do you get this armor, you may ask? Begin by donating 1,000 rupees to the elder Goron in Malo Mart in Kakariko Village. " +
"Afterward, provide them with 2,000 more so they can open a store in Castle Town. Visit the shop in the southwest corner of Castle Town Square and purchase the armor for 598 rupees." +
"Alternatively, after donating 1,000 rupees, go to the goron elder in FRONT, not inside, the Malo Mart, and he will give you a mission," +
" and you have to deliver a barrel of hot spring water to the Goron on the bridge at the west side of the Castle Town." +
"I suggest you trailing near the south edge of the field, because it attracts the least number of Leevers " +
"(flower enemies that pop up from the ground) Bulblins, and Kargarocs." +
"Once you bring it to the Goron, he asks you to throw it on him. Do so, and he will restart the Spring Water business (buy one and drink it immediately to regain all health), " +
"give you a heart piece, and then, " + "most importantly, reduces the 2,000 rupee fee to a mere 200! Afterwards, buy the armor to save exactly 1,202 rupees.");
//add each item to the list
itemList.add(item1);
itemList.add(item2);
itemList.add(item3);
itemList.add(item4);
itemList.add(item5);
itemList.add(item6);
itemList.add(item7);
itemList.add(item8);
itemList.add(item9);
mListAdapter = new ListAdapater(EquipmentActivity.this, itemList);
mItemListView = (ListView) findViewById(R.id.EquipmentListView);
mItemListView.setAdapter(mListAdapter);
//end copy
mItemListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
Item item = (Item) parent.getItemAtPosition(position);
Intent i = new Intent(EquipmentActivity.this, DisplayInformationActivity.class);
i.putExtra("itemName", item.getItemName());
i.putExtra("itemPicture", item.getImageSource());
i.putExtra("description", item.itemdescription);
startActivity(i);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
|
package dev.liambloom.softwareEngineering.chapter16;
import dev.liambloom.softwareEngineering.chapter4.Ask;
public class FirstSecondLargestSmallest {
public static void main(String[] args) {
Ask.seperator = ':';
boolean over = false;
// This is my own implementation of LinkedList
LinkedList<Integer> list = new LinkedList<>();
while (!over) {
final int n = Ask.forInt("Enter a number");
if (n == -1)
over = true;
else
list.addSorted(n);
System.out.printf("L1 = %d, L2 = %d, S1 = %d, S2 = %d%n",
list.get(0), list.get(Math.min(1, list.size() - 1)),
list.get(list.size() - 1), list.get(Math.max(list.size() - 2, 0)));
}
System.out.println("GOOD BYE!!");
}
}
|
package com.qst.chapter03;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
/**
* 演示ToggleButton的用法
*/
public class ToggleButtonDemoActivity extends AppCompatActivity {
private ToggleButton mToggleButton;
private TextView tvSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.togglebutton_demo);
mToggleButton = findViewById(R.id.tglSound);
tvSound = findViewById(R.id.tvSound);
initView();
}
private void initView() {
mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
tvSound.setText("已开启");
} else {
tvSound.setText("已关闭");
}
}
});
}
}
|
package com.phila.samergigabyte.philabooksx;
/**
* Created by SamerGigaByte on 15/01/2016.
*/
public class Saved {
String Saved;
}
|
package net.lantrack.framework.sysbase.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.lantrack.framework.core.entity.ReturnEntity;
import net.lantrack.framework.springplugin.controller.BaseController;
import net.lantrack.framework.sysbase.enm.SysConfigEnum;
import net.lantrack.framework.sysbase.entity.LoginInfo;
import net.lantrack.framework.sysbase.entity.SysConfig;
import net.lantrack.framework.sysbase.entity.SysUser;
import net.lantrack.framework.sysbase.model.user.LoginParm;
import net.lantrack.framework.sysbase.service.LoginInfoService;
import net.lantrack.framework.sysbase.service.SysConfigService;
import net.lantrack.framework.sysbase.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 登录管理
*
* @date 2019年1月21日
*/
@RestController
@RequestMapping("/otherlogin")
public class LoginOtherController extends BaseController {
@Autowired
private LoginInfoService loginInfoService;
@Autowired
private SysConfigService sysConfigService;
@Autowired
private SysUserService sysUserService;
// 刷脸登录后认证 /otherlogin/facelogin
@RequestMapping("/facelogin")
public ReturnEntity facelogin(ReturnEntity info, String userId) {
try {
Map<String, Object> map = loginInfoService.faceLogin(userId);
info.success("登录成功");
info.setResult(map);
} catch (Exception e) {
info.failed("登录失败:",e.getMessage());
}
return info;
}
// 前台二维码状态查询 /otherlogin/scanStatus
@RequestMapping("/scanStatus")
public ReturnEntity scanStatus(ReturnEntity info, HttpServletRequest req, String authCode) {
Map<String, Object> resultMap = new HashMap<>();
// System.out.println(authCode+"----");
try {
Map<String, String> map = loginInfoService.hasAllowLogin(req, authCode);
if (map.get("loginName") != null) {
info.success("登录成功");
resultMap.put("currentUser", map.get("loginName"));
resultMap.put("sn", map.get("sn"));
} else {
String has = map.get("submit");
if("yes".equals(has)) {
info.failed("登录失败,请重新扫描二维码");
}
if("no".equals(has)) {
info.failed("等待APP确认");
}
resultMap.put("button", has);
}
} catch (Exception e) {
info.failed("登录失败:"+e.getMessage());
}
info.setResult(resultMap);
return info;
}
// APP扫码确认 /otherlogin/allow
@RequestMapping("/allow")
public ReturnEntity allow(ReturnEntity info, String loginName, String authCode, String functionFlag) {
try {
loginInfoService.allowAppScanCode(loginName, authCode);
info.success("确认成功");
info.setResult(loginName);
} catch (Exception e) {
info.failed("确认失败");
}
return info;
}
// 返回二维码信息 /otherlogin/scancode
@RequestMapping("/scancode")
public ReturnEntity scanCode(ReturnEntity info) {
try {
String scanCodeAuth = loginInfoService.getAppScanCode();
info.success("生成成功");
Map<String, String> resultMap = new HashMap<>();
resultMap.put("key", scanCodeAuth);
resultMap.put("function", "scanLogin");
info.setResult(resultMap);
} catch (Exception e) {
info.failed("生成失败");
}
return info;
}
// 获取登录方式 /otherlogin/logintype
@RequestMapping("/logintype")
public ReturnEntity loginType(ReturnEntity info) {
try {
SysConfig loginType = sysConfigService.getConfigByName(SysConfigEnum.LOGINTYPE.getConfName());
info.setResult(loginType.getConfValue());
} catch (Exception e) {
info.failed("获取登录方式失败");
}
return info;
}
// 短信验证码登录 校验短信验证码 /otherlogin/validmsgcode
@RequestMapping("/validmsgcode")
public ReturnEntity validMsgcode(ReturnEntity info, String deviceType,String code, String phone) {
try {
Map<String, Object> validMsgCode = this.loginInfoService.validMsgCodeToLogin(code, phone,deviceType);
info.success("登录成功");
info.setResult(validMsgCode);
} catch (Exception e) {
info.failed(e.getMessage());
}
return info;
}
// 获取短信验证码 /otherlogin/getmsgcode
@RequestMapping("/getmsgcode")
public ReturnEntity getMsgCode(ReturnEntity info, String phone) {
try {
this.loginInfoService.getMsgCodeByPhone(phone);
info.success("发送成功");
} catch (Exception e) {
info.failed("发送失败:" + e.getMessage());
}
return info;
}
// APP账号密码登录 /otherlogin/byapp
@RequestMapping(value = "/byapp")
public ReturnEntity byApp(ReturnEntity info, HttpServletRequest request, @RequestBody LoginParm login) {
try {
// LoginParm login = getFromJson(json, LoginParm.class);
Map<String, Object> appLogin = this.loginInfoService.appLogin(request, login.getUsername(),
login.getPassword(), login.getDeviceType());
if (appLogin.get("sn") == null) {
info.failed("登录失败,剩余次数" + appLogin.get("remainCount"));
} else {
info.success("登录成功");
info.setResult(appLogin);
}
} catch (Exception e) {
info.failed("登录失败:" + e.getMessage());
}
return info;
}
// 校验短信验证码 /otherlogin/validmsg
@RequestMapping("/validmsg")
public ReturnEntity validmsg(ReturnEntity info, String code, String phone) {
try {
this.loginInfoService.validMsgCode(code, phone);
info.success("校验成功");
} catch (Exception e) {
info.failed(e.getMessage());
}
return info;
}
// 验证图片验证码符合后再发送短信验证码
@RequestMapping("/validCodeAndPhoneToPc")
public ReturnEntity validCodeAndPhoneToPc(ReturnEntity info, String phone,
String validateCode,String imgToken) {
// 校验参数信息
if (StringUtils.isBlank(phone) || StringUtils.isBlank(validateCode) || StringUtils.isBlank(imgToken)) {
info.failed("参数不能为空");
return info;
}
try {
this.loginInfoService.validImgCode(imgToken, validateCode);
// 验证成功发送短信验证码
this.loginInfoService.getMsgCodeByPhone(phone);
info.success("发送成功");
} catch (Exception e) {
info.failed(e.getMessage());
}
return info;
}
// 获取手机号和密码 保存密码
@RequestMapping("/resetPassword")
public ReturnEntity resetPassword(ReturnEntity info, String password, String phone) {
Map<String, String> map = new HashMap<String, String>();
// 校验参数信息
if (StringUtils.isBlank(password) || StringUtils.isBlank(phone)) {
info.failed("手机号或密码不能为空");
return info;
}
try {
// 获得验证码与手机号
SysUser sysUser = this.sysUserService.updataPassworByPhone(password, phone);
if (sysUser.getId() == null) {
info.failed("重置密码失败");
return info;
}
info.success("重置密码成功");
map.put("loginName", sysUser.getLoginName());
//密码重置后清空之前所有登录的APP和PC的session
LoginInfo loginInfo = this.loginInfoService.getInfo(sysUser.getLoginName());
if(loginInfo!=null) {
String appToken = loginInfo.getStand1();
String pcToken = loginInfo.getStand2();
this.loginInfoService.deleteSession(appToken);
this.loginInfoService.deleteSession(pcToken);
}
info.setResult(map);
} catch (Exception e) {
info.failed(e.getMessage());
}
return info;
}
}
|
package javaclasses;
import java.util.ArrayList;
import java.util.List;
public class StudentList {
private List<Student> students = new ArrayList<>();
public void addStudent(Student a) {
students.add(a);
}
public void printStudentsByFaculty(Faculty faculty) {
for (Student student : students) {
if (student.getFaculty().equals(faculty)) {
System.out.println(student);
}
}
}
public void printStudentsForEachFacultyAndCourse() {
for (int i = 0; i < Faculty.values().length; i++) {
int count = 0;
int courseMax = 6;
for (int j = 1; j <= courseMax; j++) {
System.out.println("Факультет " + Faculty.values()[i] + " Курс " + j);
for (Student student : students) {
if (student.getFaculty().equals(Faculty.values()[i]) & student.getCourse() == j) {
System.out.println(student);
count++;
}
}
if (count == 0) {
System.out.println("В базе студентов нет");
}
count = 0;
}
}
}
public void printStudentsByYearAfter(int year) {
for (Student student : students) {
if (Integer.parseInt(student.getBirthday().substring(6)) > year) {
System.out.println(student);
}
}
}
public void printStudentsByGroup(int group) {
for (Student student : students) {
if (student.getGroup() == (group)) {
System.out.println(student);
}
}
}
}
|
import java.util.*;
class Solution {
public static String longestPalindrom(String s) {
boolean[][] dp = new boolean[s.length()][s.length()];
int max_len = Integer.MIN_VALUE;
String ans = "";
int n = s.length();
for (int i = n-1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = (s.charAt(i) == s.charAt(j)) && (j <= i+1 || dp[i+1][j-1]);
if (dp[i][j] && j-i+1 > max_len) {
max_len = j-i+1;
ans = s.substring(i, j+1);
}
}
}
return ans;
}
public static String longestPalindrom2(String s) {
int n = s.length();
int max_len = Integer.MIN_VALUE;
String ans = "";
for (int i = 0; i < n; i++) {
int len1 = expandFromCenter(s, i, i);
if (len1 > max_len) { max_len = len1; ans = s.substring(i-len1/2, i+len1/2+1); }
int len2 = expandFromCenter(s, i, i+1);
if (len2 > max_len) { max_len = len2; ans = s.substring(i-(len2-2)/2, i+(len2-2)/2+2); }
}
return ans;
}
private static int expandFromCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right-left-1;
}
public static void main(String[] args) {
String s = args[0];
System.out.println(longestPalindrom2(s));
}
}
|
package com.example.twitter;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import com.google.common.collect.Lists;
import com.twitter.hbc.ClientBuilder;
import com.twitter.hbc.core.Client;
import com.twitter.hbc.core.Constants;
import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint;
import com.twitter.hbc.core.processor.StringDelimitedProcessor;
import com.twitter.hbc.httpclient.auth.Authentication;
import com.twitter.hbc.httpclient.auth.OAuth1;
import com.example.twitter.AuthConstants;
public class TwitterKafkaProducer {
private static final String topic = "twitter-topic";
public kafka.javaapi.producer.Producer<String, String> initialize(){
Properties properties = new Properties();
properties.put("metadata.broker.list", "localhost:9092");
properties.put("serializer.class", "kafka.serializer.StringEncoder");
properties.put("client.id","camus");
ProducerConfig producerConfig = new ProducerConfig(properties);
kafka.javaapi.producer.Producer<String, String> producer = new kafka.javaapi.producer.Producer<String, String>(
producerConfig);
return producer;
}
public void publishMessage(kafka.javaapi.producer.Producer<String, String> producer) throws InterruptedException {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
// add some track terms
endpoint.trackTerms(Lists.newArrayList("#ipl",
"#TNElections"));
Authentication auth = new OAuth1(AuthConstants.consumerKey,AuthConstants.consumerSecret, AuthConstants.token,
AuthConstants.secret);
// Authentication auth = new BasicAuth(username, password);
// Create a new BasicClient. By default gzip is enabled.
Client client = new ClientBuilder().hosts(Constants.STREAM_HOST)
.endpoint(endpoint).authentication(auth)
.processor(new StringDelimitedProcessor(queue)).build();
// Establish a connection
client.connect();
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 10000; msgRead++) {
KeyedMessage<String, String> message = null;
try {
message = new KeyedMessage<String, String>(topic, queue.take());
System.out.println("Message 123:" + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
producer.send(message);
}
client.stop();
}
public static void main(String[] args) {
try {
TwitterKafkaProducer kafkaproducer = new TwitterKafkaProducer();
//Initialize Producer
kafka.javaapi.producer.Producer<String, String> producer = kafkaproducer.initialize();
//Publish Message
kafkaproducer.publishMessage(producer);
//Close Producer
producer.close();
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
|
package com.controller;
import org.hibernate.NonUniqueObjectException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ExceptionCntroller {
@ExceptionHandler(NonUniqueObjectException.class)
public String handleCustomException(String ex,ModelMap model ) {
model.addAttribute("productInCart", "Already in cart");
return "redirect:/allProduct";
}
}
|
package com.unisports.entities;
import java.util.UUID;
public class UserInscription {
private UUID id;
private boolean confirmed;
private UUID userId;
private UUID teamInscriptionId;
public UserInscription(){
this.id = UUID.randomUUID();
}
public UserInscription(UUID id){
this.id = id;
}
public UUID getId(){
return this.id;
}
public void setConfirmed(boolean confirmed){
this.confirmed = confirmed;
}
public boolean getConfirmed(){
return this.confirmed;
}
public void setUserId(UUID userId){
this.userId = userId;
}
public UUID getUserId(){
return this.userId;
}
public void setTeamInscriptionId(UUID inscriptionId){
this.teamInscriptionId = inscriptionId;
}
public UUID getTeamInscriptionId(){
return this.teamInscriptionId;
}
}
|
package Java三.数字操作类;
//大数字操作类:BigInteger、BigDecimal
import java.math.BigInteger;
public class BigInteger1 {
public static void main(String[] args) {
BigInteger A = new BigInteger("123456789987654321") ;
BigInteger B = new BigInteger("123456789");
System.out.println("加法:"+A.add(B));
System.out.println("减法:"+A.subtract(B));
System.out.println("乘法:"+A.multiply(B));
System.out.println("除法:"+A.divide(B));
//求余数,第一个元素为商,第二个为余数
BigInteger res[] = A.divideAndRemainder(B);
System.out.println("商、"+res[0]+"\n余、"+res[1]);
}
//Math的处理使用的是基本数据类型,所以性能高于大数字处理类
}
|
package entity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author pelo
*/
public class Validator
{
public static final String OK = "OK"; // Used for the validation of user information
/**
* Checking to see if it is a valid date
* @param date String must be in format of HHmm
* @return OK if its a valid data, error message otherwise
*/
public static String checkDate(String date)
{
String res = OK;
//Attempting to parse the HHmm to a Date format:
SimpleDateFormat format = new SimpleDateFormat("HHmm");
try { format.parse(date); }
catch (ParseException e)
{ res = "Not a start time. Must be in HHmm format\n"; }
return res;
}
/**
* Checks to see if input is a valid call duration.
* @param duration mm must be a positive integer greate than 0.
* @return OK value or error message otherwise.
*/
public static String checkDuration(String duration)
{
String res = OK;
int intDur = 0;
//Case empty string:
if (duration.isEmpty())
{ res = "Duration cannot be empty\n"; }
//Easter egg:
if (duration.equals("TM"))
{ res = "Darth Exception said.. I am your Rootfolder! Programmer: NOOOO\n"; }
//Case not number:
try { intDur = Integer.parseInt(duration); }
catch (NumberFormatException e)
{ res = "Only numbers are accepted\n"; }
//Case negative call duration:
if ( intDur <= 0 )
{ res = "Durations must be positive and over 0\n"; }
return res;
}
}
|
package com.estiam.ott_estiam;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.net.Uri;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.android.exoplayer2.util.Util;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class PlayerActivity extends AppCompatActivity {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private Context mContext;
private final Handler mHideHandler = new Handler();
private PlayerView mPlayerView;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private View mControlsView;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
hide();
}
};
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
/******Player part************/
Handler mainHandler;
SimpleExoPlayer player;
String type;
private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
mContext = this;
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mPlayerView = findViewById(R.id.fullscreen_content);
// Set up the user interaction to manually show or hide the system UI.
mPlayerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);
type="HLS";
try {
initializePlayer();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
@Override
protected void onPause() {
super.onPause();
player.release();
}
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
@SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
private void initializePlayer() throws Exception {
// 1. Create a default TrackSelector
mainHandler = new Handler();
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector =
new DefaultTrackSelector(videoTrackSelectionFactory);
// 2. Create the player
player = ExoPlayerFactory.newSimpleInstance(getBaseContext(), trackSelector);
// 3. Bind the player to the view
mPlayerView.setPlayer(player);
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = buildDataSourceFactory(true);
MediaSource videoSource;
//trackSelector.
switch (type){
case "DASH":
videoSource = new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(dataSourceFactory), buildHttpDataSourceFactory(false))
.createMediaSource(Uri.parse("http://dash.edgesuite.net/akamai/bbb_30fps/bbb_30fps.mpd"));
break;
case "HLS":
videoSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse("http://192.168.10.3/live/racine.m3u8"));//"http://www.streambox.fr/playlists/test_001/stream.m3u8"));
break;
default:
throw new Exception("Unreconigzed type");
}
// Prepare the player with the source.
player.prepare(videoSource);
}
/**
* Returns a new DataSource factory.
*
* @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
* DataSource factory.
* @return A new DataSource factory.
*/
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return ((DemoApplication) getApplication())
.buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
}
/**
* Returns a new HttpDataSource factory.
*
* @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
* DataSource factory.
* @return A new HttpDataSource factory.
*/
private HttpDataSource.Factory buildHttpDataSourceFactory(boolean useBandwidthMeter) {
return ((DemoApplication) getApplication())
.buildHttpDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
}
}
|
package com.show.comm.restful;
/**
* Restful异常
*
* @author heyuhua
* @date 2017年12月18日
*/
public class RestfulEx extends RuntimeException {
private static final long serialVersionUID = 1L;
/** 状态 */
private RestfulStatus s;
/** 消息 */
private String m;
public RestfulEx(RestfulStatus s) {
this.s = s;
this.m = s.getVal();
}
public RestfulEx(int s, String m) {
this(RestfulStatus.parse(s), m);
}
public RestfulEx(RestfulStatus s, String m) {
this.s = s;
this.m = null != m ? m : s.getVal();
}
/**
* 构造参数错误异常
*
* @param paramName
* 参数名称
*/
public RestfulEx(String paramName) {
this(paramName, null);
}
/**
* 构造参数错误异常
*
* @param paramName
* 参数名称
* @param paramMsg
* 参数错误提示
*/
public RestfulEx(String paramName, String paramMsg) {
this.s = RestfulStatus.H400;
if (null == paramMsg) {
this.m = paramName;
} else {
this.m = paramName + "#" + paramMsg;
}
}
@Override
public String getMessage() {
return m;
}
/**
* @return 状态
*/
public RestfulStatus getS() {
return s;
}
/**
* @param s
* 状态
*/
public void setS(RestfulStatus s) {
this.s = s;
}
/**
* @return 消息
*/
public String getM() {
return m;
}
/**
* @param m
* 消息
*/
public void setM(String m) {
this.m = m;
}
}
|
package com.ipartek.pojo;
public class ExcepcionListaNegra extends Exception{
private int codigoError = 0;
// Constructor
///////////////////////////////////////
public ExcepcionListaNegra(int codigoError) {
super();
this.codigoError = codigoError;
}
//Getters y Setters
public int getCodigoError() {
return codigoError;
}
public void setNombre(int codigoError) {
this.codigoError = codigoError;
}
//toString
@Override
public String toString() {
return "ExcepcionListaNegra [codigoError=" + codigoError + "]";
}
}
|
package ru.client;
import org.sql2o.Sql2o;
public class DbSource {
private static Sql2o sql2o;
static {
sql2o = new Sql2o("jdbc:oracle:thin:@//10.4.0.119:1521/xe", "gladkikh13204", "gladkikh13204");
}
public static Sql2o getSql2o() {
return sql2o;
}
}
|
package com.mx.cdmx.cacho.partnersample;
class Finalize {
// the finalize() method will be called when the object is garbage collected (it takes time)
public void finalize() {
System.out.println("Finalize is called");
}
public static void main(String args[])
{
Finalize f1 = new Finalize();
Finalize f2 = new Finalize();
f1 = null;
f2 = null;
System.gc();
}
}
|
package doomsday.mummy.shivababa.doomsday;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
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 java.util.Calendar;
import java.util.GregorianCalendar;
public class MainActivity extends AppCompatActivity {
TextView week_day;
EditText day_string,month_string,year_string;
Button find_day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
day_string = (EditText)findViewById(R.id.editText);
month_string = (EditText)findViewById(R.id.editText2);
year_string = (EditText)findViewById(R.id.editText3);
week_day = (TextView)findViewById(R.id.textView);
find_day = (Button)findViewById(R.id.button);
find_day.setOnClickListener(m);
}
private void Doomsday_find(int day, int month, int year) {
Calendar calendar = new GregorianCalendar(year, month-1, day); // Note that Month value is 0-based. e.g., 0 for January.
int result = calendar.get(Calendar.DAY_OF_WEEK);
switch (result) {
case Calendar.SUNDAY:
week_day.setText("SUNDAY");
break;
case Calendar.MONDAY:
week_day.setText("MONDAY");
break;
case Calendar.TUESDAY:
week_day.setText("TUESDAY");
break;
case Calendar.WEDNESDAY:
week_day.setText("WEDNESDAY");
break;
case Calendar.THURSDAY:
week_day.setText("THURSDAY");
break;
case Calendar.FRIDAY:
week_day.setText("FRIDAY");
break;
case Calendar.SATURDAY:
week_day.setText("SATURDAY");
break;
}
}
View.OnClickListener m = new View.OnClickListener(){
@Override
public void onClick(View v) {
int day = Integer.parseInt(day_string.getText().toString());
int month = Integer.parseInt(month_string.getText().toString());
int year = Integer.parseInt(year_string.getText().toString());
Doomsday_find(day, month, year);
}
};
}
|
package com.legaoyi.protocol.server;
import java.util.HashMap;
import java.util.Map;
import com.legaoyi.common.message.ExchangeMessage;
import com.legaoyi.common.disruptor.DisruptorEventProducer;
/**
* disruptor处理消息
*
* @author gaoshengbo
*
*/
public class ServerUpMessageHandler implements ServerMessageHandler {
private DisruptorEventProducer producer;
private String routingKey;
public void setProducer(DisruptorEventProducer producer) {
this.producer = producer;
}
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
@Override
public void handle(ExchangeMessage message) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
data.put("routingKey", routingKey);
data.put("message", message);
producer.produce(data);
}
}
|
package com.spring.scrapper.users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring.scrapper.users.vo.UserVO;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public UserVO selectUser(UserVO vo) {
UserVO result = null;
try {
result = userDAO.selectUser(vo);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public boolean insertUser(UserVO vo) {
boolean result = false;
try {
result = userDAO.insertUser(vo);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|
package com.cognixia.jump.djk.firstjavaproject;
import java.util.InputMismatchException;
import java.util.Scanner;
import com.cognixia.jump.djk.firstjavaproject.data.InvalidIntException;
public class InputScanner {
private static final Scanner SCANNER = new Scanner(System.in);
static {
SCANNER.useDelimiter(System.lineSeparator()); // source: https://www.reddit.com/r/javahelp/wiki/scanner
}
public static String getLinePreface() {
return " >> ";
}
public static int getIntInput() throws InvalidIntException, Exception {
return getIntInput(true);
}
public static int getIntInput(boolean shouldAdvanceInputOnFail) throws Exception {
try {
int intInput = SCANNER.nextInt();
return intInput;
} catch(InputMismatchException e) {
if (shouldAdvanceInputOnFail) SCANNER.next();
throw new InvalidIntException(e);
} catch(Exception e) {
if (shouldAdvanceInputOnFail) SCANNER.next();
throw e;
}
}
public static String getInput() {
return SCANNER.next();
}
public static void close() {
SCANNER.close();
}
}
|
package com.zeal.smartdo.transformer;
import com.zeal.common.log.Logger;
import com.zeal.smartdo.base.BaseHttpResponse;
import com.zeal.smartdo.exception.ExceptionHandle;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
/**
* @作者 廖伟健
* @创建时间 2017/3/27 16:25
* @描述 错误 Transformer
*/
public class ErrorTransformer<T> implements ObservableTransformer<BaseHttpResponse<T>, T> {
private static ErrorTransformer sErrorTransformer = null;
private ErrorTransformer() {
}
@Override
public ObservableSource<T> apply(Observable<BaseHttpResponse<T>> upstream) {
return upstream.map(new Function<BaseHttpResponse<T>, T>() {
@Override
public T apply(@NonNull BaseHttpResponse<T> httpResult) throws Exception {
if(httpResult == null) {
throw new RuntimeException("解析对象为空");
}
Logger.e(httpResult.toString());
if(httpResult.isError()) {
throw new RuntimeException("server 500 异常");
}
if(httpResult.getData() == null) {
throw new RuntimeException("实体数据解析异常");
}
return httpResult.getData();
}
}).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends T>>() {
@Override
public ObservableSource<? extends T> apply(@NonNull Throwable throwable) throws
Exception {
throwable.printStackTrace();
//TODO 需要处理失败问题
return Observable.error(ExceptionHandle.handleException(throwable));
}
});
}
/**
* @return 线程安全, 双层校验
*/
public static <T> ErrorTransformer<T> getInstance() {
if(sErrorTransformer == null) {
synchronized (ErrorTransformer.class) {
if(sErrorTransformer == null) {
sErrorTransformer = new ErrorTransformer<>();
}
}
}
return sErrorTransformer;
}
}
|
package ProjectManagement;
import java.util.ArrayList;
public class Project {
int entry_time = 0;
String name = null;
int priority = 0;
int budget = 0;
ArrayList<JobReport_> kaam = new ArrayList<JobReport_>();
public Project(String name, String priority, String budget)
{
this.name = name;
this.priority = Integer.parseInt(priority);
this.budget = Integer.parseInt(budget);
}
public int compareTo(Project x)
{
int ans = x.priority - this.priority;
if(ans==0)
ans = this.entry_time - x.entry_time;
return ans;
}
public String toString()
{
return this.name;
}
}
|
package br.com.softplan.services;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.softplan.domain.Feedback;
import br.com.softplan.domain.Procedure;
import br.com.softplan.domain.User;
import br.com.softplan.domain.enums.UserType;
import br.com.softplan.repositories.FeedbackRepository;
import br.com.softplan.repositories.ProcedureRepository;
import br.com.softplan.repositories.UserRepository;
import br.com.softplan.security.CryptographySHA256;
@Service
public class DBService {
@Autowired
private UserRepository userRepository;
@Autowired
private ProcedureRepository procedureRepository;
@Autowired
private FeedbackRepository feedbackRepository;
@Autowired
private CryptographySHA256 crypto;
public void instantiateDataBase() {
User user1 = new User(UserType.ADMINITRADOR.getIdType(), "userAdmin", crypto.encode("123abc"), null);
User user2 = new User(UserType.TRIADOR.getIdType(), "userTriador", crypto.encode("123qwerty"), user1);
User user3 = new User(UserType.FINALIZADOR.getIdType(), "userFinalizador", crypto.encode("123qlkj"), user1);
User user4 = new User(UserType.FINALIZADOR.getIdType(), "userFinalizadorDois", crypto.encode("123qlkj"), user1);
userRepository.save(Arrays.asList(user1, user2, user3, user4));
Procedure proc1 = new Procedure("Processo xyz", true, user2);
proc1.getUsers().add(user2);
proc1.getUsers().add(user3);
Procedure proc2 = new Procedure("Processo abc", true, user2);
proc2.getUsers().add(user3);
Procedure proc3 = new Procedure("Processo tre", false, user2);
proc3.getUsers().add(user3);
Procedure proc4 = new Procedure("Processo qwerty", false, user2);
proc4.getUsers().add(user3);
procedureRepository.save(Arrays.asList(proc1, proc2, proc3, proc4));
Feedback feed1 = new Feedback("parecer 1", proc3, user3);
Feedback feed2 = new Feedback("parecer 2", proc4, user3);
feedbackRepository.save(Arrays.asList(feed1, feed2));
}
}
|
package strings_stringbuffer;
import java.util.*;
public class Program4 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
if(str.length()%2 !=0)
System.out.println("null");
else
System.out.println(str.substring(0,str.length()/2));
}
}
|
package org.example.codingtest.oneLevel;
import java.util.Arrays;
/**
* 물품을 구매해 줄 때는 각 부서가 신청한 금액만큼을 모두 지원해 줘야 합니다.
* 예를 들어 1,000원을 신청한 부서에는 정확히 1,000원을 지원해야 하며, 1,000원보다 적은 금액을 지원해 줄 수는 없습니다.
* <p>
* 부서별로 신청한 금액이 들어있는 배열 d와 예산 budget이 매개변수로 주어질 때,
* 최대 몇 개의 부서에 물품을 지원할 수 있는지 return 하도록 solution 함수를 완성해주세요.
**/
public class Budget {
public static void main(String[] args) {
int[] d = {1, 2, 3, 4, 5};
int budget = 9;
solution(d, budget);
}
public static int solution(int[] d, int budget) {
int answer = 0;
int sum = 0;
Arrays.sort(d);
for (int num : d){
sum += num;
if (sum<=budget){
answer++;
} else {
break;
}
}
System.out.println(answer);
return answer;
}
}
|
import java.util.Comparator;
/**
* This class represents a comparator for a comparison of two states.
* The comparison is done according to several criteria by levels:
* First, compare with the value of the f() function (Which is the cost up to this state plus the value of the heuristic function of this state),
* the state with the lower value will appear first.
* If it is equal then compare by the discovery time of the two states,
* that is, compares the iterations in which the two states were created,
* if it is equal compare in the order of the development of the states in the same iteration, the state created first will appear first.
* @author Ori Ben-Hamo
*
*/
public class State_Comparator implements Comparator<State> {
/**
* Compare between two states.
*/
@Override
public int compare(State s1, State s2) {
int f1 = s1.f();
int f2 = s2.f();
if (f1 != f2) {
int diff = f1 - f2;
return diff;
}else if(s1.getIteration()!=s2.getIteration()) {
return s1.getIteration()-s2.getIteration();
}else {
return s1.getMoveID()-s2.getMoveID();
}
}
}
|
package jp.ac.kyushu_u.csce.modeltool.vdmslEditor.editor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jface.text.rules.*;
/**
* VDM単語ルールクラス
*
* @author KBK yoshimura
*/
public class VdmslWordRule extends SingleLineRule {
/**
* コンストラクタ
* @param sequence
* @param token
* @param escapeCharacter
* @param breaksOnEOF
* @param escapeContinuesLine
*/
protected VdmslWordRule(String sequence, IToken token, char escapeCharacter, boolean breaksOnEOF, boolean escapeContinuesLine) {
super(sequence, "", token, escapeCharacter, breaksOnEOF, escapeContinuesLine); //$NON-NLS-1$
}
/**
* コンストラクタ
* @param sequence
* @param token
* @param escapeCharacter
* @param breaksOnEOF
*/
protected VdmslWordRule(String sequence, IToken token, char escapeCharacter, boolean breaksOnEOF) {
super(sequence, "", token, escapeCharacter, breaksOnEOF); //$NON-NLS-1$
}
/**
* コンストラクタ
* @param sequence
* @param token
* @param escapeCharacter
*/
protected VdmslWordRule(String sequence, IToken token, char escapeCharacter) {
super(sequence, "", token, escapeCharacter); //$NON-NLS-1$
}
/**
* コンストラクタ
* @param sequence
* @param token
*/
protected VdmslWordRule(String sequence, IToken token) {
super(sequence, "", token); //$NON-NLS-1$
}
/**
* 終端文字列の検索
* @see PatternRule#endSequenceDetected(ICharacterScanner)
*/
protected boolean endSequenceDetected(ICharacterScanner scanner) {
return true;
}
/**
* ルールに合致するかを評価する
* @see PatternRule#doEvaluate(ICharacterScanner, boolean)
*/
protected IToken doEvaluate(ICharacterScanner scanner, boolean resume) {
// デフォルトトークン
IToken token = Token.UNDEFINED;
int adjust = 0;
boolean searchFlg = false;
StringBuffer sb = new StringBuffer();
// スキャナ位置が先頭でない場合
if(scanner.getColumn() > 0) {
scanner.unread();
adjust = 1;
}
// スキャナ位置-1から検索文字列+2文字分、文字列を取得
for(int i = 0; i <= fStartSequence.length + adjust; i++) {
int c = scanner.read();
sb.append((char)c);
}
// スキャナ位置を元に戻す
for(int i = 0; i <= fStartSequence.length; i++) {
scanner.unread();
}
// 検査用正規表現(検索文字列の前後に単語境界(\W))
Pattern pattern = Pattern.compile(
(scanner.getColumn() <= 0 ? "" : "\\W") + String.valueOf(fStartSequence) + "\\W"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Matcher matcher = pattern.matcher(sb.toString());
searchFlg = matcher.matches();
if(searchFlg) {
super.doEvaluate(scanner, resume);
token = fToken;
}
return token;
}
}
|
package com.crutchclothing.controllers;
import java.security.Principal;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.crutchclothing.cart.model.Cart;
import com.crutchclothing.cart.model.CartProduct;
import com.crutchclothing.inventory.Inventory;
import com.crutchclothing.orders.model.Order;
import com.crutchclothing.users.model.Address;
import com.crutchclothing.users.model.User;
import com.crutchclothing.users.service.UserService;
import com.crutchclothing.util.AddressType;
import com.crutchclothing.util.OrderNumber;
@Controller
public class OrderController {
//@Autowired
//@Qualifier("userService")
private UserService userService;
//@Autowired
//@Qualifier("userValidator")
//private Validator validator;
//@InitBinder("user")
//private void initBinder(WebDataBinder binder) {
//binder.setValidator(validator);
//}
private Order order;
@RequestMapping(value="/checkout")
public String checkout(ModelMap model, Principal auth) {
//ModelAndView model = new ModelAndView("checkout");
System.out.println("Hello checkout");
if(order == null) {
order = new Order();
}
String name = "anonymoususer";
if (auth != null) {
name = auth.getName();
}
model.addAttribute("name", capitalizeName(name));
//System.out.println(name);
if(!name.equalsIgnoreCase("anonymoususer")) {
// ArrayList<CartProduct> cartProducts =
User user = userService.findUser(name);
Cart cart = user.getUserCart();
model.addAttribute("order", order);
model.addAttribute("user", user);
model.addAttribute("cartQty", cart.getTotalQuantity());
model.addAttribute("cartProducts", new ArrayList<CartProduct>(cart.getCartProducts()));
model.addAttribute("addressList", user.getAddresses());
model.addAttribute("subtotal", cart.getTotal());
}
return "checkout";
}
@RequestMapping(value="/verify-billing-info")
public String verifyBillingInfo(/*@ModelAttribute("order")*/ Order order/*, BindingResult userResult, */,ModelMap model, RedirectAttributes redir) {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
order.setBillingAddress(userService.findAddress(order.getBillingAddress().getId()));
model.addAttribute("name", capitalizeName(name));
User foundUser = userService.findUser(name);
model.addAttribute("user", foundUser);
model.addAttribute("cartQty", foundUser.getUserCart().getTotalQuantity());
model.addAttribute("cartProducts", new ArrayList<CartProduct>(foundUser.getUserCart().getCartProducts()));
model.addAttribute("addressList", foundUser.getAddresses());
model.addAttribute("order", order);
System.out.println();
/*
if(userResult.hasErrors()) {
return "checkout";
}
*/
//userService.updateUserAddressType(user.getNewAddress().getAddressId(), com.crutchclothing.util.AddressType.BILLING);
//model.addAttribute("user", user);
return "checkout";
}
@RequestMapping(value="/verify-shipping-info")
public String verifyShippingInfo(/*@ModelAttribute("order") */Order order,/* BindingResult shipAddressResult,*/ ModelMap model, RedirectAttributes redir) {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
model.addAttribute("name", capitalizeName(name));
User foundUser = userService.findUser(name);
model.addAttribute("user", foundUser);
model.addAttribute("cartQty", foundUser.getUserCart().getTotalQuantity());
model.addAttribute("cartProducts", new ArrayList<CartProduct>(foundUser.getUserCart().getCartProducts()));
model.addAttribute("addressList", foundUser.getAddresses());
System.out.println();
/*
if(shipAddressResult.hasErrors()) {
return "checkout";
}
*/
//userService.updateUserAddressType(user.getShipAddress().getAddressId(), AddressType.SHIPPING);
///model.addAttribute("user", user);
return "checkout";
}
public String createOrder(){
Order order = new Order();
long orderNumber = OrderNumber.getID();
return null;
}
private String capitalizeName(String name) {
String formattedName = name.substring(0,1).toUpperCase() + name.substring(1, name.length()).toLowerCase();
return formattedName;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
//public void setValidator(Validator validator) {
//this.validator = validator;
//}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.MicrositeConfigurationMicrositehistoryRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class MicrositeConfigurationMicrositehistory extends TableImpl<MicrositeConfigurationMicrositehistoryRecord> {
private static final long serialVersionUID = 376221731;
/**
* The reference instance of <code>bitnami_edx.microsite_configuration_micrositehistory</code>
*/
public static final MicrositeConfigurationMicrositehistory MICROSITE_CONFIGURATION_MICROSITEHISTORY = new MicrositeConfigurationMicrositehistory();
/**
* The class holding records for this type
*/
@Override
public Class<MicrositeConfigurationMicrositehistoryRecord> getRecordType() {
return MicrositeConfigurationMicrositehistoryRecord.class;
}
/**
* The column <code>bitnami_edx.microsite_configuration_micrositehistory.id</code>.
*/
public final TableField<MicrositeConfigurationMicrositehistoryRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.microsite_configuration_micrositehistory.created</code>.
*/
public final TableField<MicrositeConfigurationMicrositehistoryRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.microsite_configuration_micrositehistory.modified</code>.
*/
public final TableField<MicrositeConfigurationMicrositehistoryRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.microsite_configuration_micrositehistory.key</code>.
*/
public final TableField<MicrositeConfigurationMicrositehistoryRecord, String> KEY = createField("key", org.jooq.impl.SQLDataType.VARCHAR.length(63).nullable(false), this, "");
/**
* The column <code>bitnami_edx.microsite_configuration_micrositehistory.values</code>.
*/
public final TableField<MicrositeConfigurationMicrositehistoryRecord, String> VALUES = createField("values", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
/**
* The column <code>bitnami_edx.microsite_configuration_micrositehistory.site_id</code>.
*/
public final TableField<MicrositeConfigurationMicrositehistoryRecord, Integer> SITE_ID = createField("site_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>bitnami_edx.microsite_configuration_micrositehistory</code> table reference
*/
public MicrositeConfigurationMicrositehistory() {
this("microsite_configuration_micrositehistory", null);
}
/**
* Create an aliased <code>bitnami_edx.microsite_configuration_micrositehistory</code> table reference
*/
public MicrositeConfigurationMicrositehistory(String alias) {
this(alias, MICROSITE_CONFIGURATION_MICROSITEHISTORY);
}
private MicrositeConfigurationMicrositehistory(String alias, Table<MicrositeConfigurationMicrositehistoryRecord> aliased) {
this(alias, aliased, null);
}
private MicrositeConfigurationMicrositehistory(String alias, Table<MicrositeConfigurationMicrositehistoryRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<MicrositeConfigurationMicrositehistoryRecord, Integer> getIdentity() {
return Keys.IDENTITY_MICROSITE_CONFIGURATION_MICROSITEHISTORY;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<MicrositeConfigurationMicrositehistoryRecord> getPrimaryKey() {
return Keys.KEY_MICROSITE_CONFIGURATION_MICROSITEHISTORY_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<MicrositeConfigurationMicrositehistoryRecord>> getKeys() {
return Arrays.<UniqueKey<MicrositeConfigurationMicrositehistoryRecord>>asList(Keys.KEY_MICROSITE_CONFIGURATION_MICROSITEHISTORY_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<MicrositeConfigurationMicrositehistoryRecord, ?>> getReferences() {
return Arrays.<ForeignKey<MicrositeConfigurationMicrositehistoryRecord, ?>>asList(Keys.MICROSITE_CONFIGURATI_SITE_ID_6977A04D3625A533_FK_DJANGO_SITE_ID);
}
/**
* {@inheritDoc}
*/
@Override
public MicrositeConfigurationMicrositehistory as(String alias) {
return new MicrositeConfigurationMicrositehistory(alias, this);
}
/**
* Rename this table
*/
public MicrositeConfigurationMicrositehistory rename(String name) {
return new MicrositeConfigurationMicrositehistory(name, null);
}
}
|
package xml;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.io.IOException;
public class Validator {
private SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
public void validate(StreamSource xmlStreamSource, String schemaPath) throws SAXException, IOException {
Schema schema = schemaFactory.newSchema(new File(schemaPath));
javax.xml.validation.Validator validator = schema.newValidator();
validator.validate(xmlStreamSource);
}
}
|
package org.nistagram.campaignmicroservice.data.model;
import org.nistagram.campaignmicroservice.data.enums.Gender;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import java.util.Date;
import java.util.List;
@Entity
@DiscriminatorValue("CONTINUOUS_CAMPAIGN")
public class ContinuousCampaign extends Campaign {
@Column(name = "exposure_start")
private Date exposureStart;
@Column(name = "exposure_end")
private Date exposureEnd;
@Column(name = "required_daily_displays")
private int requiredDailyDisplays;
@Column(name = "lastUpdate")
private Date lastUpdate;
public static final int TWENTY_FOUR_HOURS = 86400000;
public ContinuousCampaign() {
}
public ContinuousCampaign(String agentAccountUsername, boolean deleted, Gender gender, Integer maxAge, Integer minAge, List<HireRequest> hireRequests, Advertisement advertisement, Date exposureStart, Date exposureEnd, int requiredDailyDisplays) {
super(agentAccountUsername, deleted, gender, maxAge, minAge, hireRequests, advertisement);
this.exposureStart = exposureStart;
this.exposureEnd = exposureEnd;
this.requiredDailyDisplays = requiredDailyDisplays;
var date = new Date();
date.setTime(date.getTime()- TWENTY_FOUR_HOURS -1);
this.lastUpdate = date;
}
public Date getExposureStart() {
return exposureStart;
}
public void setExposureStart(Date exposureStart) {
this.exposureStart = exposureStart;
}
public Date getExposureEnd() {
return exposureEnd;
}
public void setExposureEnd(Date exposureEnd) {
this.exposureEnd = exposureEnd;
}
public int getRequiredDailyDisplays() {
return requiredDailyDisplays;
}
public void setRequiredDailyDisplays(int requiredDailyDisplays) {
this.requiredDailyDisplays = requiredDailyDisplays;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
|
package com.webserver.shoppingmall.post.model;
import com.webserver.shoppingmall.member.model.Member;
import com.webserver.shoppingmall.shared.BaseTimeEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Getter
@NoArgsConstructor
@Entity
public class Comment extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String comment;
@ManyToOne
@JoinColumn(name = "member_id")
private Member member;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
@Builder
public Comment(Long id, String comment, Member member, Post post) {
this.id = id;
this.comment = comment;
this.member = member;
this.post = post;
}
public Comment addComment(Post post) {
post.getComments().add(this);
return this;
}
}
|
package handin02;
/**
* StringManipulator manipulates string.
*
* @author Peter Tolstrup Aagesen
*
* handin #2
*/
public class StringManipulator
{
//Variables for storing the number of times the methods are used
private static int numToCamelCaseUsed = 0;
private static int numOddOrEvenLengthUsed = 0;
private static int numInitialsFromNameUsed = 0;
/**
* SubstringManipulator constructor
*/
public StringManipulator ()
{
}
/**
* toCamelCase takes two String parameters and concatenates them into a camel cased String.
*
* @param First String.
* @param Second String.
* @return Returns a camel cased String.
*/
public static String toCamelCase(String s1, String s2)
{
//Add one to the variable storing the number of times this method has been used
numToCamelCaseUsed += 1;
//Create String for return result
String camelCasedWord = "";
//Convert words to lower case and store the result in variables
String s1LowerCased = s1.toLowerCase();
String s2LowerCased = s2.toLowerCase();
//create new variable for the second string with first letter capitalized
String s2FirstLetterCapitalized = s2LowerCased.substring(0,1).toUpperCase() +
s2LowerCased.substring(1);
//Concatenate the strings in return result
camelCasedWord = s1LowerCased + s2FirstLetterCapitalized;
//Return result
return camelCasedWord;
}
/**
* oddOrEventLength test if the length of a String is odd or event.
*
* @param s String to be tested.
* @return Returns 1 if the length of the String is odd otherwise 0.
*/
public static int oddOrEventLength(String s)
{
//Add one to the variable storing the number of times this method has been used
numOddOrEvenLengthUsed ++;
//Use modulus 2 on the length of the string to return 0 for even length and 1 odd length
return s.length()%2;
}
/**
* initialsFromName creates capitalized initials from two Strings
*
* @param firstName First String
* @param secondName Second String
* @return Returns initials as capitals separated by a dot.
*/
public static String initialsFromName(String firstName, String secondName)
{
//Add one to the variable storing the number of times this method has been used
numInitialsFromNameUsed ++;
//Create a String for the return result
String returnInitials = "";
//Add the first letter of the first name as a capital to return result
returnInitials += firstName.substring(0, 1).toUpperCase();
//Add dot and space
returnInitials += ". ";
//Add the first letter of the first name as a capital to return result
returnInitials += secondName.substring(0, 1).toUpperCase();
//Add final dot
returnInitials += ".";
//Return result
return returnInitials;
}
/**
* generateUsageRepport prints a report the number of times the methods of the class has been used.
*/
public static void generateUsageReport()
{
System.out.println("Following classes been used:");
//Print number of times toCamelCase has been used
System.out.println("toCamelCase:" + numToCamelCaseUsed + " times");
//Print number of times oddOrEvenLength has been used
System.out.println("oddOrEvenLength:" + numOddOrEvenLengthUsed + " times");
//Print number of times initialsFromName has been used
System.out.println("initialsFromName:" + numInitialsFromNameUsed + " times");
}
}
|
package com.shangdao.phoenix.entity.companyApplyForm;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author duyiting
* @date 2018/03/30
*/
public interface CompanyApplyFormFileRepository extends JpaRepository<CompanyApplyFormFile, Long> {
}
|
package com.manu.webviewdemo.activity;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.manu.webviewdemo.R;
/**
* 加载完整网页
*/
public class WebViewActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl("https://www.baidu.com");
// webView.loadUrl("http://blog.csdn.net/");
// webView.setWebViewClient(new WebViewClient());
// webView.loadUrl("http://www.qq.com/");
}
}
|
package Courier.CourierService.Services;
import java.util.Date;
import java.util.List;
import Courier.CourierService.Models.GenericDAO;
import Courier.CourierService.Models.Route;
import Courier.CourierService.Models.RouteDAO;
import Courier.CourierService.Models.RouteInformation;
import Courier.CourierService.Models.RouteInformationDAO;
import Courier.CourierService.Models.User;
public class RouteServiceImpl implements RouteService{
private RouteInformationDAO routeInformationDAO = new RouteInformationDAO();
private RouteDAO routeDAO = new RouteDAO();
public List<RouteInformation> getAllRoutes() {
List<RouteInformation> routes = routeInformationDAO.findAll();
return routes;
}
public void addOrUpdateRoute(Route route) {
routeDAO.save(route);
}
public void addRouteInstance(RouteInformation info) {
routeInformationDAO.save(info);
}
public List<RouteInformation> getRoutesForDriver(User user) {
List<RouteInformation> informationList = null;
if (user.getRouteInformations().isEmpty())
{
informationList = routeInformationDAO.findByUser(user);
}
else
{
informationList.addAll(user.getRouteInformations());
}
return informationList;
}
public List<RouteInformation> getRoutesForDriver(Integer userId) {
return routeInformationDAO.findByUserId(userId);
}
public void addRoute(String start, String koniec, Date startDate,
Date endDate, double distance, float fuel, int userId) {
// TODO Auto-generated method stub
}}
|
package de.minestar.syncchest.utils;
public enum PlayerState {
NONE,
CHEST_ADD,
CHEST_REMOVE,
CHEST_INFO
}
|
package com.company;
import java.util.Scanner;
import java.util.Stack;
public class Expression {
public static int calculator(char[] ch,int n) throws Exception {
Stack<Integer> operands=new Stack<Integer>();
Stack<Character> operators=new Stack<Character>();
for(int i=0;i<n;i++)
{
if((ch[i] >='0') && (ch[i] <='9'))
{
StringBuffer sb=new StringBuffer();
while(i<n && ch[i]>='0'&& ch[i]<='9')
sb.append(ch[i++]);
String s1=sb.toString();
operands.push(Integer.parseInt(s1));
}
if(ch[i]=='(')
{
operators.push(ch[i]);
}
if(ch[i]==')')
{
while(operators.peek()!='(') {
int temp = operands.pop();
int temp1 = operands.pop();
char op = operators.pop();
operands.push(evaluation(temp, temp1, op));
}
operators.pop();
}
if(ch[i]=='+' || ch[i]=='-' || ch[i]=='*' || ch[i]=='/' || ch[i]=='%')
{
while(!operators.empty() && OpPrecedence(ch[i],operators.peek())) {
int temp=operands.pop();
int temp1=operands.pop();
char op=operators.pop();
operands.push(evaluation(temp,temp1,op));
}
operators.push(ch[i]);
}
}
while(!operators.empty()) {
int temp=operands.pop();
int temp1=operands.pop();
char op=operators.pop();
operands.push(evaluation(temp,temp1,op));
}
//System.out.println(operands.pop());
return operands.pop();
}
public static boolean OpPrecedence(char op1,char op2)
{
if(op2=='(' || op2 == ')')
return false;
if((op1=='*' || op1=='/') && (op2=='+' || op2=='-'))
return false;
else
return true;
}
public static int evaluation(int b,int a,char operator) throws Exception {
if (operator == '+') {
return a + b;
} else if (operator == '-') {
return a - b;
} else if (operator == '*') {
return a * b;
} else if (operator == '/') {
if (b == 0)
throw new Exception("operation cannot be done");
return a / b;
} else if (operator == '%') {
if (b == 0)
throw new Exception("operation cannot be done");
return a % b;
}
throw new Exception("other operations cannot be done");
}
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
String s= sc.nextLine();
char[] ch=s.toCharArray();
int n=ch.length;
int result=calculator(ch,n);
System.out.println(result);
}
}
|
package com.sevael.lgtool.utils;
public interface UtilConstants {
public static final String[] DATA_FIELD_COLUMN_NAMES ={"Cell1","Cell2","Cell3","Cell4","Cell5","Cell6","Cell7","Cell8","Cell9","Cell10","Cell11","Cell12","Cell13","Cell14","Cell15"};
public static final String MSG_SUCCESS ="success";
public static final String MSG_FAILURE ="failure";
public static final String MSG_NA ="NA";
public static final String RS_MESSAGE ="message";
public static final String RS_STATUS ="status";
public static final String RS_USERID ="userid";
public static final String ADD_SERVICE_SUCCESS= "Service created successfully";
public static final String ADD_COMMON_SUCCESS= "Added successfully";
public static final String ADD_UPDATECOMMON_SUCCESS= "Updated successfully";
public static final String ADD_COMMON_EXISTS = "Already exists";
public static final String ADD_WRONG = "Something went wrong";
public static final String ADD_CONTACT_SUCCESS= "Contact created successfully";
public static final String ADD_TRAINING_SUCCESS= "Training created successfully";
public static final String ADD_BUSINESS_SUCCESS= "Business created successfully";
public static final String ADD_BUSINESS_EMPLOYEE= "Employee added successfully";
public static final String ADD_CONTACT_EXISTS = "Contact already exists";
public static final String ADD_BUSINESS_EXISTS = "Business already exists";
public static final String ADD_SERVICE_EXISTS = "Service already exists";
public static final String DELETE_SERVICE = "Service deleted successfully";
public static final String PAGE_COUNT ="pageCount";
}
|
package com.danerdaner.simple_voca;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.danerdaner.Items.ListItem;
import com.danerdaner.activity.MainActivity;
import androidx.annotation.Nullable;
public class GridItemView extends LinearLayout {
TextView word;
TextView announce;
TextView mean;
Context context;
String url = "https://blog.kakaocdn.net/dn/bo3KaK/btquRMFtTMq/aqjWG83rTIrEXWKpCEjFgK/%EB%9D%A0%EB%A7%81.mp3?attach=1&knm=tfile.mp3";
public GridItemView(Context context) {
super(context);
this.context = context;
init(context);
}
public GridItemView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
init(context);
}
private void init(Context context) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.voca_gridview_adapter_item, this, true);
word = (TextView) findViewById(R.id.textView);
announce = (TextView) findViewById(R.id.textView2);
mean = (TextView) findViewById(R.id.textView3);
ImageButton btn = (ImageButton)findViewById(R.id.imageButton);
btn.setOnClickListener(new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
try {
// MainActivity.player = MediaPlayer.create(context, Uri.parse(url));
// MainActivity.player.start();
MainActivity.tts.speak(word.getText().toString(),TextToSpeech.QUEUE_FLUSH, null);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public void setData(ListItem listItem){
String[] data = listItem.getData();
word.setText(data[0]);
announce.setText(data[1]);
mean.setText(data[2]);
}
}
|
package com.example.ajays.dirac.Choice;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.ajays.dirac.Chat.ChatActivity;
import com.example.ajays.dirac.R;
public class ChoiceViewHolder extends RecyclerView.ViewHolder{
TextView item_choice_tv1;
TextView item_choice_tv2;
LinearLayout item_choice_layout;
public ChoiceViewHolder(@NonNull final View itemView) {
super(itemView);
item_choice_tv1 = itemView.findViewById(R.id.item_choice_name);
item_choice_tv2 = itemView.findViewById(R.id.item_choice_description);
item_choice_layout = itemView.findViewById(R.id.item_choice_layout);
}
}
|
package com.t.logger;
/**
* @author tb
* @date 2018/12/17 14:54
*/
public class JobLoggerException extends RuntimeException {
public JobLoggerException() {
super();
}
public JobLoggerException(String message) {
super(message);
}
public JobLoggerException(String message, Throwable cause) {
super(message, cause);
}
}
|
package com.cqut.service;
import java.util.List;
import java.util.Map;
import com.cqut.dto.OperatorDTO;
import com.cqut.dto.LimitShowExtraDTO;
import com.cqut.dto.LoginInfoDTO;
public interface IOperatorService {
public long count(LoginInfoDTO loginInfoDTO, OperatorDTO operatorDTO, LimitShowExtraDTO limiShowExtraDTO);
// 查询重复的运营中心名
int duplicateCheckingUserUserName(String validationNickName,String id);
int checkArea(String area,String id);
// 获取所有符合条件的运营中心
List<Map<String, Object>> getLimitList(OperatorDTO operatorDTO, LimitShowExtraDTO limitDTO);
// 添加一个运营中心
boolean addUser(OperatorDTO operatorDTO);
// 根据ID获取一个运营中心的详细信息
Map<String, Object> findUserById(String id);
// 更新运营中心的信息
boolean updateUser(OperatorDTO OperatorDTO);
// 删除数据(可批量删除也可只删除一条记录)
boolean batchDelete(String[] primaryKeys);
List<Map<String,Object>> findList(LimitShowExtraDTO limitShowDTO, OperatorDTO operatorDTO);
public long getCounts(OperatorDTO operatorDTO);
//结算收入
boolean updateMoney(String id);
}
|
/*
* generated by Xtext
*/
package org.yazgel.snow.notation.text.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.yazgel.snow.notation.text.services.SnowGrammarAccess;
public class SnowParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private SnowGrammarAccess grammarAccess;
@Override
protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}
@Override
protected org.yazgel.snow.notation.text.parser.antlr.internal.InternalSnowParser createParser(XtextTokenStream stream) {
return new org.yazgel.snow.notation.text.parser.antlr.internal.InternalSnowParser(stream, getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "DomainModel";
}
public SnowGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(SnowGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
|
package com.example.breno.pokemobile.modelo;
import java.io.Serializable;
/**
* Created by Breno on 02/11/2016.
*/
public class Jogador implements Serializable {
private Long idJogador;
private String usuario;
private String senha;
public Jogador() {}
public Jogador(String usuario, String senha) {
this.usuario = usuario;
this.senha = senha;
}
public Long getIdJogador() {
return idJogador;
}
public void setIdJogador(Long idJogador) {
this.idJogador = idJogador;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
|
class DemoBox
{
double width;
double height;
double depth;
//This is constructor DemoBox
DemoBox()//new DemoBox is responsible to call
{
System.out.println("Constructing DemoBox");
width = 10;
height = 12;
depth = 5.6;
}
//compute and return volume
public double volume()
{
return width * height * depth;
}
}
public class BoxDemo6
{
public static void main(String[]args)
{
//reference to object
DemoBox box1 = new DemoBox();
DemoBox box2 = new DemoBox();
double vol;
//get value from volume
vol = box1.volume();
System.out.println("Box1: ");
System.out.println(vol);
vol = box2.volume();
System.out.println("Box2: ");
System.out.println(vol);
}
}
|
package com.jfinalExt;
import java.util.List;
import org.apache.log4j.Logger;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.utils.ZJ_JacksonUtils;
public class ZJ_DbPro extends DbPro {
Logger logger = Logger.getLogger(Object.class);
public <T> T queryFirst(String tableName, String fieldName, String fieldValue) {
String sql = String.format("select * from %s where %s=?", tableName, fieldName);
List<T> result = query(sql, fieldValue);
return (result.size() > 0 ? result.get(0) : null);
}
public Record findFirst(String tableName, String fieldName, Object fieldValue) {
String sql = String.format("select * from %s where %s=?", tableName, fieldName);
List<Record> result = find(sql, fieldValue);
return result.size() > 0 ? result.get(0) : null;
}
/**
*
* @author 张剑
*
* @param tableName
* @param fieldList
* @param valueList
* @return
*/
public Record findFirst(String tableName, List<String> fieldList, List<Object> valueList) {
List<Record> result = findAll(tableName, fieldList, valueList);
return result.size() > 0 ? result.get(0) : null;
}
public List<Record> findAll(String tableName, List<String> fieldList, List<Object> valueList) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("select * from %s where 1=1 ", tableName));
for (String field : fieldList) {
stringBuilder.append(String.format(" and %s =? ", field));
}
logger.info("Sql:" + stringBuilder.toString());
logger.info("pars:" + ZJ_JacksonUtils.toJson(valueList));
List<Record> result = find(stringBuilder.toString(), valueList.toArray());
return result;
}
public Record findFirst(String tableName, String fieldName, Object fieldValue, String sqlExt) {
String sql = String.format("select * from %s where %s=? %s", tableName, fieldName, sqlExt);
List<Record> result = find(sql, fieldValue);
return result.size() > 0 ? result.get(0) : null;
}
public List<Record> findAll(String tableName, String fieldName, String fieldValue, String sqlExt) {
if (null == sqlExt) {
sqlExt = "";
}
String sql = String.format("select * from %s where %s=? %s ", tableName, fieldName, sqlExt);
List<Record> result = find(sql, fieldValue);
return result;
}
public List<Record> findAll(String tableName, String sqlExt) {
if (null == sqlExt) {
sqlExt = "";
}
String sql = String.format("select * from %s %s ", tableName, sqlExt);
List<Record> result = find(sql);
return result;
}
}
|
/*
* Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms.
*/
package com.yahoo.cubed.util;
import org.testng.annotations.Test;
/**
* Unit test ZipUtil.
*/
public class ZipUtilTest {
/**
* Zip a test folder.
*/
@Test
public void testZipSrcFolder() throws Exception {
ZipUtil.zipDir("./target/src.zip", "./src");
}
}
|
/*
William Presley
To run and compile from directory above ('-classpath' can be shortened to '-cp'):
compile: javac -classpath . /himmelblau/himmelblau_WilliamPrelsey.java
run: java -classpath . /himmelblau/himmelblau_WilliamPresley
*/
package himmelblau;
public class himmelblau_WilliamPresley {
public static void main(String args[]) {
Population pop = new Population();
pop.run_himmelblau();
// //Doesn't show output/errors in terminal
// CMD.runSingleCommand("./himmelblau/runPython.sh");
}
}
|
package egovframework.com.aja.alg.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.com.aja.service.CommonAjaxManageService;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
/**
* 중복체크관련 처리
*/
@Controller
public class AutoLoginLogAjaxController {
/** log */
protected static final Log LOG = LogFactory.getLog(AutoLoginLogAjaxController.class);
/** EgovPropertyService */
@Resource(name = "propertiesService")
protected EgovPropertyService propertiesService;
/** EgovMessageSource */
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
/** AJAX 공통 서비스*/
@Resource(name = "commonAjaxManageService")
private CommonAjaxManageService commonAjaxManageService;
/**
* AutoLogin 로그 저장
*
* @param HttpServletResponse
* response, HttpServletRequest request, Map commandMap
* @return
* @exception Exception
*/
@RequestMapping(value = "/com/aja/alg/insertAutoLoginLog.do")
public ModelAndView insertAutoLoginLog( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap) throws Exception {
Object result = null;
ModelAndView modelAndView = new ModelAndView();
commonAjaxManageService.insertCommonAjaxManageInt(commandMap, "commonAjaxDAO.insertAutoLoginLog");
Map resultMap = new HashMap();
resultMap.put("result", result);
modelAndView.addAllObjects(resultMap);
modelAndView.setViewName("jsonView");
return modelAndView;
}
}
|
package exercises.chapter2.ex5;
/**
* @author Volodymyr Portianko
* @date.created 01.03.2016
*/
public class Exercise5 {
int i;
double d;
boolean b;
public static void main(String[] args) {
Exercise5 exercise = new Exercise5();
exercise.i = 47;
exercise.d = 1.1;
exercise.b = false;
System.out.println(exercise.i);
System.out.println(exercise.d);
System.out.println(exercise.b);
}
}
|
package com.leeheejin.pms.handler;
import java.util.List;
import com.leeheejin.pms.domain.Other;
import com.leeheejin.util.Prompt;
public class OtherAddHandler extends AbstractOtherHandler {
public OtherAddHandler(List<Other> otherList) {
super(otherList);
}
@Override
public void service() {
System.out.println("[ 홈 > 관리자 메뉴 > 구조동물목록 > 신규등록 > 신규기타동물등록* ]");
try {
Other o = new Other();
o.setIds(otherList.size() + 1);
System.out.printf("[%d]\n",o.getIds());
o.setSpecies(Prompt.inputString("종류? "));
o.setPhotos(Prompt.inputString("사진? "));
o.setBreeds(Prompt.inputString("품종? "));
o.setGenders(Prompt.inputString("성별? "));
o.setAges(Prompt.inputInt("나이? "));
o.setDates(Prompt.inputDate("구조일? "));
o.setPlaces(Prompt.inputString("구조장소? "));
o.setStatus("신규");
otherList.add(o);
System.out.println("- 등록이 완료되었습니다. ");
System.out.println();
} catch (Exception e) {
System.out.println("---------------------");
System.out.println(" 잘못된 입력입니다. ");
System.out.println("---------------------");
}
}
}
|
class JoinMethod extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);
}
catch(Exception e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]){
JoinMethod t1=new JoinMethod();
JoinMethod t2=new JoinMethod();
JoinMethod t3=new JoinMethod();
t1.start();
try{
t1.join(1500);
}
catch(Exception e){
System.out.println(e);
}
t2.start();
t3.start();
}
}
|
/*
* 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.messaginghub.pooled.jms;
import jakarta.jms.JMSConsumer;
import jakarta.jms.JMSException;
import jakarta.jms.JMSRuntimeException;
import jakarta.jms.Message;
import jakarta.jms.MessageListener;
import org.messaginghub.pooled.jms.util.JMSExceptionSupport;
/**
* JMSConsumer implementation backed by a pooled Connection.
*/
public class JmsPoolJMSConsumer implements JMSConsumer, AutoCloseable {
private final JmsPoolMessageConsumer consumer;
public JmsPoolJMSConsumer(JmsPoolMessageConsumer consumer) {
this.consumer = consumer;
}
@Override
public void close() {
try {
consumer.close();
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
//----- MessageConsumer Property Methods ---------------------------------//
@Override
public MessageListener getMessageListener() {
try {
return consumer.getMessageListener();
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
@Override
public String getMessageSelector() {
try {
return consumer.getMessageSelector();
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
@Override
public void setMessageListener(MessageListener listener) {
try {
consumer.setMessageListener(listener);
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
//----- Receive Methods --------------------------------------------------//
@Override
public Message receive() {
try {
return consumer.receive();
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
@Override
public Message receive(long timeout) {
try {
return consumer.receive(timeout);
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
@Override
public Message receiveNoWait() {
try {
return consumer.receiveNoWait();
} catch (JMSException e) {
throw JMSExceptionSupport.createRuntimeException(e);
}
}
@Override
public <T> T receiveBody(Class<T> desired) {
throw new JMSRuntimeException("Pooled JMSConsumer does not support receiveBody");
}
@Override
public <T> T receiveBody(Class<T> desired, long timeout) {
throw new JMSRuntimeException("Pooled JMSConsumer does not support receiveBody");
}
@Override
public <T> T receiveBodyNoWait(Class<T> desired) {
throw new JMSRuntimeException("Pooled JMSConsumer does not support receiveBody");
}
@Override
public String toString() {
return getClass().getSimpleName() + " { " + consumer + " }";
}
}
|
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException{
int n = readInt(), k = readInt(), arr[] = new int[n];
for(int i = 0; i<n; i++)arr[i] = readInt();
long[]psa = new long[n+1];
for(int i = 0; i<n; i++){
psa[i+1] = psa[i]+(long)arr[i];
}
int ans = n+1;
Deque<Integer>Q = new LinkedList<>();
for(int i = 0; i<psa.length; i++){
while(!Q.isEmpty()&&psa[i]<=psa[Q.getLast()]){
Q.removeLast();
}
while(!Q.isEmpty()&&psa[i]>=psa[Q.getFirst()]+k){
ans = Math.min(ans, i-Q.removeFirst());
}
Q.addLast(i);
}
if(ans<n+1)pr.println(ans);
else pr.println(-1);
pr.close();
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine().trim());
return st.nextToken();
}
static long readLong () throws IOException {
return Long.parseLong(next());
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
static double readDouble () throws IOException {
return Double.parseDouble(next());
}
static char readChar () throws IOException {
return next().charAt(0);
}
static String readLine () throws IOException {
return input.readLine().trim();
}
}
|
package sr.hakrinbank.intranet.api.controller;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sr.hakrinbank.intranet.api.dto.InterestSavingsAccountDto;
import sr.hakrinbank.intranet.api.dto.ResponseDto;
import sr.hakrinbank.intranet.api.model.Interest;
import sr.hakrinbank.intranet.api.model.InterestSavingsAccount;
import sr.hakrinbank.intranet.api.service.InterestSavingsAccountService;
import sr.hakrinbank.intranet.api.util.Constant;
import java.util.ArrayList;
import java.util.List;
/**
* Created by clint on 6/15/17.
*/
@RestController
@RequestMapping(value = "/api/interestsavingsaccount")
public class InterestSavingsAccountController {
@Autowired
private InterestSavingsAccountService interestSavingsAccountService;
//-------------------Retrieve All InterestSavingsAccount--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listAllInterestSavingsAccount() {
List<InterestSavingsAccount> interestSavingsAccount = interestSavingsAccountService.findAllActiveInterestSavingsAccount();
if(interestSavingsAccount.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT);
}
return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(interestSavingsAccount), null), HttpStatus.OK);
}
//-------------------Retrieve All InterestSavingsAccount By Search--------------------------------------------------------
@RequestMapping(value = "search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listInterestSavingsAccountBySearchQuery(@RequestParam String qry) {
List<InterestSavingsAccount> interestSavingsAccount = interestSavingsAccountService.findAllActiveInterestSavingsAccountBySearchQuery(qry);
if(interestSavingsAccount.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT);
}
return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(interestSavingsAccount), mapModelToDto(interestSavingsAccount).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK);
}
//-------------------Retrieve All InterestSavingsAccount With Pagination--------------------------------------------------------
// @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// public ResponseEntity<Page<InterestSavingsAccount>> listAllInterestSavingsAccount(Pageable pageable) {
// Page<InterestSavingsAccount> interestSavingsAccount = interestSavingsAccountService.findAllInterestSavingsAccountByPage(pageable);
// return new ResponseEntity<Page<InterestSavingsAccount>>(interestSavingsAccount, HttpStatus.OK);
// }
//-------------------Retrieve Single InterestSavingsAccount--------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<InterestSavingsAccount> getInterestSavingsAccount(@PathVariable("id") long id) {
System.out.println("Fetching InterestSavingsAccount with id " + id);
InterestSavingsAccount interestSavingsAccount = interestSavingsAccountService.findById(id);
if (interestSavingsAccount == null) {
System.out.println("InterestSavingsAccount with id " + id + " not found");
return new ResponseEntity<InterestSavingsAccount>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<InterestSavingsAccount>(interestSavingsAccount, HttpStatus.OK);
}
//-------------------Create a InterestSavingsAccount--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> createInterestSavingsAccount(@RequestBody InterestSavingsAccountDto interestSavingsAccountBasisDto) {
System.out.println("Creating InterestSavingsAccount with description " + interestSavingsAccountBasisDto.getAccountType());
if (interestSavingsAccountBasisDto.getId() != null) {
System.out.println("A InterestSavingsAccount with id " + interestSavingsAccountBasisDto.getId() + " already exist");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "A InterestSavingsAccount with id " + interestSavingsAccountBasisDto.getId() + " already exist"), HttpStatus.CONFLICT);
}
ModelMapper modelMapper = new ModelMapper();
interestSavingsAccountService.updateInterestSavingsAccount(modelMapper.map(interestSavingsAccountBasisDto, InterestSavingsAccount.class));
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_SAVED), HttpStatus.CREATED);
}
//------------------- Update a InterestSavingsAccount --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> updateInterestSavingsAccount(@PathVariable("id") long id, @RequestBody InterestSavingsAccountDto interestSavingsAccountBasisDto) {
System.out.println("Updating InterestSavingsAccount " + id);
InterestSavingsAccount currentInterestSavingsAccount = interestSavingsAccountService.findById(id);
if (currentInterestSavingsAccount == null) {
System.out.println("InterestSavingsAccount with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "InterestSavingsAccount with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
ModelMapper modelMapper = new ModelMapper();
interestSavingsAccountService.updateInterestSavingsAccount(modelMapper.map(interestSavingsAccountBasisDto, InterestSavingsAccount.class));
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_UPDATED), HttpStatus.OK);
}
//------------------- Delete a InterestSavingsAccount --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<ResponseDto> deleteInterestSavingsAccount(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting InterestSavingsAccount with id " + id);
InterestSavingsAccount interestSavingsAccount = interestSavingsAccountService.findById(id);
if (interestSavingsAccount == null) {
System.out.println("Unable to delete. InterestSavingsAccount with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "Unable to delete. InterestSavingsAccount with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
interestSavingsAccount.setDeleted(true);
interestSavingsAccountService.updateInterestSavingsAccount(interestSavingsAccount);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_DELETED), HttpStatus.OK);
}
//------------------- HELPER METHODS --------------------------------------------------------
public List<InterestSavingsAccountDto> mapModelToDto(List<InterestSavingsAccount> interestSavingsAccount) {
List<InterestSavingsAccountDto> interestSavingsAccountBasisDtoList = new ArrayList<>();
ModelMapper modelMapper = new ModelMapper();
for(Interest interestSavingsAccountItem: interestSavingsAccount){
if(interestSavingsAccountItem instanceof InterestSavingsAccount) {
InterestSavingsAccountDto interestSavingsAccountBasisDto = modelMapper.map(interestSavingsAccountItem, InterestSavingsAccountDto.class);
interestSavingsAccountBasisDtoList.add(interestSavingsAccountBasisDto);
}
}
return interestSavingsAccountBasisDtoList;
}
}
|
package payments.model;
import java.io.Serializable;
public class PaymentResponse implements Serializable {
private static final long serialVersionUID = -8145871365210148355L;
private String status;
private String errorCode;
private String errorMessage;
private String paymentId;
private String accountNumber;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
}
|
/*
* 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 ImpresionDocumentos;
import static Formuarios.Inicio.Pane1;
import java.awt.Dimension;
/**
*
* @author jluis
*/
public class GestionesPiso extends javax.swing.JInternalFrame {
/**
* Creates new form GestionesPiso
*/
public GestionesPiso() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
setTitle("GESTIONES DE PISO");
jPanel1.setBackground(new java.awt.Color(153, 204, 255));
jButton1.setText("SOLICITUD DE TRASLADO DE PERSONAL");
jButton2.setText("DETECCION DE NECESIDADES DE CAPACITACION");
jButton3.setText("LISTADO DE ASISTENCIA DE CAPACITACION");
jButton4.setText("LISTADO INFORMATIVO");
jButton5.setText("HISTORIAL DEL TRABAJADOR");
jButton6.setText("INDUCCION GENERAL SSO");
jButton7.setText("CONCEPTOS ISO");
jButton8.setText("PRESENTACION MIL-STD 981");
jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
jButton9.setText("CANCELAR");
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(55, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton9)
.addGap(134, 134, 134))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton9, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
ImpresionDoc tra = new ImpresionDoc();
Pane1.add(tra);
Dimension desktopSize = Pane1.getSize();
Dimension FrameSize = tra.getSize();
tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2);
tra.show();
try {
this.dispose();
} catch (Exception e) {System.out.println("F "+e);
}
}//GEN-LAST:event_jButton9ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
package nesto.taptap;
import android.annotation.SuppressLint;
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.Rect;
import android.view.View;
import java.util.Random;
@SuppressLint("ViewConstructor")
public class TapView extends View {
private int b;
private int size;
private boolean catOrCats = true;
private boolean catsOrWords = true;
private final static String[] charA = {"呵"};
private final static String[] charB = {"何"};
private final static int CHAR_NUM = charA.length;
public static final int CATS_NUM = 29;
private Random rd = new Random();
private Paint paint;
private Rect imSize;
private Rect imPos;
private Bitmap[] cats;
private int width;
public TapView(Context context, int width, int block, int size, boolean catOrCats, boolean catsOrWords) {
super(context);
setMinimumWidth(width);
//noinspection SuspiciousNameCombination
setMinimumHeight(width);
setFocusable(true);
b = block;
this.size = size;
this.catOrCats = catOrCats;
this.catsOrWords = catsOrWords;
this.width = width;
initThings();
}
private void initThings() {
paint = new Paint();
paint.setTextSize(width / size);
paint.setColor(Color.BLACK);
imPos = new Rect();
imSize = new Rect(0, 0, width / size, width / size);
cats = new Bitmap[CATS_NUM];
for (int i = 0; i < CATS_NUM; i++) {
cats[i] = BitmapFactory.decodeResource(getResources(), R.drawable.pic1 + i);
}
}
public void setCatOrCats(boolean cocs) {
catOrCats = cocs;
}
public void setCatsOrWords(boolean cow) {
catsOrWords = cow;
}
/**
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getSuggestedMinimumWidth(),
getSuggestedMinimumHeight());
}
/**
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
int num = rd.nextInt(CHAR_NUM);
canvas.drawColor(Color.argb(100, 240, 240, 100));
// paint.setStrokeWidth(1);
for (int i = 0; i < size + 1; i++) {
canvas.drawLine(getWidth() / size * i, 0, getWidth() / size * i,
getWidth(), paint);
canvas.drawLine(0, getWidth() / size * i, getWidth(), getWidth()
/ size * i, paint);
}
int picA = rd.nextInt(CATS_NUM);
int picB = rd.nextInt(CATS_NUM);
while (picA == picB) {
picB = rd.nextInt(CATS_NUM);
}
int xAxis = b / size;
int yAxis = b % size;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
imPos.set(getWidth() / size * i,
getWidth() / size * j,
getWidth() / size * (i + 1),
getWidth() / size * (j + 1));
if (xAxis == i && yAxis == j) {
if (catsOrWords) {
canvas.drawBitmap(cats[picA], imSize, imPos, paint);
} else {
canvas.drawText(charA[num], getWidth() / size * i,
(float) (getWidth() / size * (j + 0.85)), paint);
}
} else {
if (catOrCats) {
if (catsOrWords) {
canvas.drawBitmap(cats[picB], imSize, imPos, paint);
} else {
canvas.drawText(charB[num], getWidth() / size * i,
(float) (getWidth() / size * (j + 0.85)),
paint);
}
}
}
}
}
}
}
|
package model;
import java.util.Date;
import javax.persistence.*;
@Entity
@Table(name = "SupportingMaterials")
public class SupportingMaterial {
@Id
@Column(name = "url")
private String url; // Mandatory fields
@Column(name = "description")
private String description;
@Column(name = "type")
private String type; // Doc / PDF / Excel
@Column(name = "addedBy")
private String addedBy; // Current User (email)
@Column(name = "addedDate")
private Date addedDate = new Date(); // Current date
@Column(name = "isActive")
private boolean isActive = true; // 1 (true): Active - 2 (false): In Active
public SupportingMaterial() {
}
public SupportingMaterial(String url, String description, String type,
String addedBy, Date addedDate, boolean isActive) {
super();
this.url = url;
this.description = description;
this.type = type;
this.addedBy = addedBy;
this.addedDate = addedDate;
this.isActive = isActive;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAddedBy() {
return addedBy;
}
public void setAddedBy(String addedBy) {
this.addedBy = addedBy;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Date addedDate) {
this.addedDate = addedDate;
}
public boolean getIsActive() {
return isActive;
}
public void setIsActive(boolean isActive) {
this.isActive = isActive;
}
}
|
package com.oldschool.ejb;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless(name="EjbGenerico", mappedName="ejb/EjbGenerico")
public class EjbGenerico implements EjbGenericoLocal {
@PersistenceContext(unitName = "ProjectHistoryJPA")
EntityManager em;
public EjbGenerico() {
}
@SuppressWarnings("unchecked")
@Override
public List<Object> listarTodo(Object instanciaClase) throws Exception {
List<Object> lista = new ArrayList<Object>();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + ".findAll");
lista = query.getResultList();
return lista;
} catch (Exception e) {
throw new Exception(e);
}
}
@SuppressWarnings("unchecked")
@Override
public List<Object> listarTodoLazy(Object instanciaClase, int firstRecord, int maxResult) throws Exception {
List<Object> lista = new ArrayList<Object>();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + ".findAll");
query.setFirstResult(firstRecord);
query.setMaxResults(maxResult);
lista = query.getResultList();
return lista;
} catch (Exception e) {
throw new Exception(e);
}
}
@SuppressWarnings("unchecked")
@Override
public List<Object> listarPorQuery(Object instanciaClase, String nombreQuery, Map<String, Object> parametros)
throws Exception {
List<Object> lista = new ArrayList<Object>();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery, instanciaClase.getClass());
for (Map.Entry<String, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
lista = query.getResultList();
return lista;
} catch (Exception e) {
throw new Exception(e);
}
}
@SuppressWarnings("unchecked")
@Override
public List<Object> listarPorNativeQuery(Object instanciaClase, String nombreQuery, Map<Integer, Object> parametros)
throws Exception {
List<Object> lista = new ArrayList<Object>();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery, instanciaClase.getClass());
for (Map.Entry<Integer, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
lista = query.getResultList();
return lista;
} catch (Exception e) {
throw new Exception(e);
}
}
@SuppressWarnings("unchecked")
@Override
public List<Object> listarPorQueryLazy(Object instanciaClase, String nombreQuery, Map<String, Object> parametros,
int firstRecord, int maxResult) throws Exception {
List<Object> lista = new ArrayList<Object>();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery, instanciaClase.getClass());
for (Map.Entry<String, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
query.setFirstResult(firstRecord);
query.setMaxResults(maxResult);
lista = query.getResultList();
return lista;
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public boolean agregarObjeto(Object instanciaClase) throws Exception{
try {
// em.clear();
em.persist(instanciaClase);
em.flush();
return true;
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public boolean actualizarObjeto(Object instanciaClase) throws Exception{
try {
em.merge(instanciaClase);
em.flush();
return true;
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public boolean EjecutarActualizacionPorQuery(Object instanciaClase, String nombreQuery,
Map<String, Object> parametros) throws Exception {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery);
for (Map.Entry<String, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
int resultado = query.executeUpdate();
if (resultado > 0) {
return true;
} else {
return false;
}
}
@Override
public boolean eliminarObjeto(Object instanciaClase) throws Exception {
try {
instanciaClase = em.merge(instanciaClase);
em.remove(instanciaClase);
return true;
} catch (Exception e) {
// throw new Exception(e);
return false;
}
}
@Override
public boolean eliminarObjectoPorQuery(Object instanciaClase, long id) throws Exception {
try {
String queryGeneral = "eliminarPorId";
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + queryGeneral);
query.setParameter("ID", Long.valueOf(id));
int resultado = query.executeUpdate();
if (resultado > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public boolean eliminarObjectoPorQuery(Object instanciaClase, int id) throws Exception {
try {
String queryGeneral = "eliminarPorId";
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + queryGeneral);
query.setParameter("ID", Integer.valueOf(id));
int resultado = query.executeUpdate();
if (resultado > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public boolean eliminarObjectoPorQuery(Object instanciaClase, String nombreQuery, Map<String, Object> parametros)
throws Exception {
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery);
for (Map.Entry<String, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
int resultado = query.executeUpdate();
if (resultado > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
// throw new Exception(e);
return false;
}
}
@Override
public boolean eliminarObjetoSinMerge(Object instanciaClase) throws Exception {
try {
em.remove(instanciaClase);
return true;
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public Object obtenerObjetoPorId(Object instanciaClase, Object id) throws Exception {
Object objeto = new Object();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + ".findById");
query.setParameter("id", id);
objeto = query.getSingleResult();
return objeto;
} catch (Exception e) {
throw new Exception(e);
}
}
@SuppressWarnings("rawtypes")
@Override
public Object obtenerObjetoPorQuery(Object instanciaClase, String nombreQuery, Map<String, Object> parametros)
throws Exception {
Object objeto = new Object();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery);
for (Map.Entry<String, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
List lista = query.getResultList();
if (!lista.isEmpty()) {
objeto = query.getSingleResult();
} else {
return null;
}
return objeto;
} catch (Exception e) {
throw new Exception(e);
}
}
@SuppressWarnings("rawtypes")
@Override
public Object obtenerObjetoPorNativeQuery(Object instanciaClase, String nombreQuery, Map<Integer, Object> parametros) throws Exception {
Object objeto = new Object();
try {
String nombreEntidad = nombreInstanciaClase(instanciaClase);
Query query = em.createNamedQuery(nombreEntidad + "." + nombreQuery);
for (Map.Entry<Integer, Object> parametro : parametros.entrySet()) {
query.setParameter(parametro.getKey(), parametro.getValue());
}
List lista = query.getResultList();
if (lista!=null && !lista.isEmpty()) {
objeto = lista.get(0);
} else {
return null;
}
return objeto;
} catch (Exception e) {
throw new Exception(e);
}
}
private String nombreInstanciaClase(Object instanciaClase) {
String[] claseSplit = instanciaClase.getClass().getName().toString().split("\\.");
String nombreEntidad = claseSplit[claseSplit.length - 1];
return nombreEntidad;
}
@Override
public void limpiarCacheJPA() throws Exception {
try {
// VACIAR CAHE DE JPA
em.getEntityManagerFactory().getCache().evictAll();
} catch (Exception e) {
throw new Exception(e);
}
}
}
|
package de.amr.games.pacman.model.common;
import static de.amr.games.pacman.lib.Logging.log;
import java.util.BitSet;
import de.amr.games.pacman.lib.V2i;
import de.amr.games.pacman.model.world.PacManGameWorld;
/**
* Data comprising a game level.
*
* @author Armin Reichert
*/
public class GameLevel {
private static float percent(Object value) {
return ((Integer) value) / 100f;
}
/** 1, 2, 3... */
public final int number;
public final PacManGameWorld world;
public String bonusSymbol;
public float playerSpeed;
public float ghostSpeed;
public float ghostSpeedTunnel;
public int elroy1DotsLeft;
public float elroy1Speed;
public int elroy2DotsLeft;
public float elroy2Speed;
public float playerSpeedPowered;
public float ghostSpeedFrightened;
public int ghostFrightenedSeconds;
public int numFlashes;
// food in game world
private BitSet eaten = new BitSet();
public int totalFoodCount;
public int foodRemaining;
public int numGhostsKilled;
/** Ms. Pac-Man: maze number (1, 2, ..., 6) */
public int mazeNumber;
public GameLevel(int number, PacManGameWorld world, Object[] data) {
this.number = number;
this.world = world;
setData(data);
totalFoodCount = 0;
int energizerCount = 0;
for (int x = 0; x < world.numCols(); ++x) {
for (int y = 0; y < world.numRows(); ++y) {
V2i tile = new V2i(x, y);
if (world.isFoodTile(tile)) {
++totalFoodCount;
if (world.isEnergizerTile(tile)) {
energizerCount++;
}
}
}
}
eaten.clear();
foodRemaining = totalFoodCount;
log("Total food: %d (%d pellets, %d energizers)", totalFoodCount, totalFoodCount - energizerCount,
energizerCount);
}
private void setData(Object[] levelData) {
bonusSymbol = (String) levelData[0];
playerSpeed = percent(levelData[1]);
ghostSpeed = percent(levelData[2]);
ghostSpeedTunnel = percent(levelData[3]);
elroy1DotsLeft = (Integer) levelData[4];
elroy1Speed = percent(levelData[5]);
elroy2DotsLeft = (Integer) levelData[6];
elroy2Speed = percent(levelData[7]);
playerSpeedPowered = percent(levelData[8]);
ghostSpeedFrightened = percent(levelData[9]);
ghostFrightenedSeconds = (Integer) levelData[10];
numFlashes = (Integer) levelData[11];
}
public int eatenFoodCount() {
return totalFoodCount - foodRemaining;
}
public boolean isFoodRemoved(V2i tile) {
return eaten.get(world.index(tile));
}
public boolean containsFood(V2i tile) {
return world.isFoodTile(tile) && !isFoodRemoved(tile);
}
public void removeFood(V2i tile) {
if (containsFood(tile)) {
eaten.set(world.index(tile));
--foodRemaining;
}
}
}
|
package at.fhv.itm14.fhvgis.webservice.app.exceptions;
/**
* Author: Philip Heimböck
* Date: 06.11.15.
*/
public class WrongCredentialsException extends Exception {
public WrongCredentialsException() {
}
public WrongCredentialsException(String message) {
super(message);
}
public WrongCredentialsException(String message, Throwable cause) {
super(message, cause);
}
public WrongCredentialsException(Throwable cause) {
super(cause);
}
public WrongCredentialsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
package net.imglib2.trainable_segmention;
import net.imagej.ops.OpService;
import net.imagej.ops.Ops;
import net.imagej.ops.cached.CachedOpEnvironment;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.ImagePlusAdapter;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.real.FloatType;
import org.junit.Ignore;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.cache.CacheService;
import java.util.Objects;
import static org.junit.Assert.assertSame;
/**
* Test if {@link CachedOpEnvironment} is suitable to cache once calculated
* features like gaussian etc.
*
* @author Matthias
*/
public class CachedOpEnvironmentTest {
@Ignore("CachedOpEnvironment is not working yet.")
@Test
public void test() {
Context context = new Context(OpService.class, CacheService.class);
OpService ops = context.service(OpService.class);
CachedOpEnvironment cachedOps = new CachedOpEnvironment(ops);
Img<FloatType> img = ImagePlusAdapter.convertFloat(Utils.loadImage("nuclei.tif"));
UnaryFunctionOp<RandomAccessibleInterval, RandomAccessibleInterval> func =
Functions.unary(cachedOps, Ops.Filter.Gauss.class, RandomAccessibleInterval.class,
RandomAccessibleInterval.class, new double[] { 8, 8 });
RandomAccessibleInterval<FloatType> result1 = func.calculate(img);
RandomAccessibleInterval<FloatType> result2 = func.calculate(img);
assertSame(result1, result2);
}
@Test
public void testHashOfNull() {
Objects.hashCode(null);
}
}
|
package tata.operaciones;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import tata.operaciones.opera.Operaciones;
public class OperacionesTests {
private Operaciones opes;
@Before
public void setUp() throws Exception {
this.opes=new Operaciones();
}
@Test
public void testcuando15mas20entonces35() {
int resultado= this.opes.sumar(15, 20);
assertEquals(35,resultado);
}
@Test
public void cuandoA0Entonces0() {
int resultado= this.opes.sumar(0, 20);
assertEquals(0,resultado);
}
@Test
public void cuandoB0Entonces0() {
int resultado= this.opes.sumar(15, 0);
assertEquals(0,resultado);
}
@Test
public void laSumaDeMaxMasMaxesMenos2() {
int resultado=this.opes.sumar(Integer.MAX_VALUE, Integer.MAX_VALUE);
assertEquals(-2, resultado);
}
}
|
/*
* Copyright (c) 2020 Nikifor Fedorov
* 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.
* SPDX-License-Identifier: Apache-2.0
* Contributors:
* Nikifor Fedorov and others
*/
package ru.krivocraft.tortoise.android.player;
import android.support.v4.media.session.MediaSessionCompat;
import ru.krivocraft.tortoise.core.rating.Rating;
public class MediaSessionCallback extends MediaSessionCompat.Callback {
private final PlaybackManager playback;
private final OnStopCallback onStopCallback;
private final Rating rating;
public MediaSessionCallback(PlaybackManager playback, OnStopCallback onStopCallback, Rating rating) {
this.playback = playback;
this.onStopCallback = onStopCallback;
this.rating = rating;
}
@Override
public void onPlay() {
playback.play();
}
@Override
public void onPause() {
playback.pause();
}
@Override
public void onSkipToNext() {
rating.rate(playback.selected(), -1);
playback.next();
}
@Override
public void onSkipToPrevious() {
rating.rate(playback.selected(), -1);
playback.previous();
}
@Override
public void onSeekTo(long pos) {
playback.seekTo((int) pos);
}
@Override
public void onSkipToQueueItem(long id) {
playback.skipTo((int) id);
}
@Override
public void onStop() {
onStopCallback.onStop();
}
interface OnStopCallback {
void onStop();
}
}
|
package com.redsun.platf.entity.sys;
import com.redsun.platf.entity.BaseEntity;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 2012/8/10
* Time: 下午 3:41
* To change this template use File | Settings | File Templates.
*/
public class CostCenter extends BaseEntity {
private String costCenterName;
public String getCostCenterName() {
return costCenterName;
}
public void setCostCenterName(String costCenterName) {
this.costCenterName = costCenterName;
}
}
|
/*
* Here comes the text of your license
* Each line should be prefixed with *
*/
package pcs.is.domain;
/**
*
* @author AngelD
*/
class Curso {
}
|
package ahmet.com.eatitserver.ui.shipper;
import android.widget.Button;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import ahmet.com.eatitserver.callback.IShipperCallBackListener;
import ahmet.com.eatitserver.common.Common;
import ahmet.com.eatitserver.model.Order;
import ahmet.com.eatitserver.model.Shipper;
public class ShipperViewModel extends ViewModel implements IShipperCallBackListener {
private MutableLiveData<List<Shipper>> mutableListShipper;
private MutableLiveData<String> mutabMessageError;
private IShipperCallBackListener shipperListener;
public ShipperViewModel() {
if (mutableListShipper == null){
mutableListShipper = new MutableLiveData<>();
mutabMessageError = new MutableLiveData<>();
}
shipperListener = this;
}
public MutableLiveData<List<Shipper>> getMutableListShipper() {
return mutableListShipper;
}
public MutableLiveData<String> getMutabMessageError() {
loadAllShippers();
return mutabMessageError;
}
public void loadAllShippers() {
FirebaseDatabase.getInstance().getReference()
.child(Common.KEY_SHIPPER_REFERANCE)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Shipper> mListShipper = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Shipper shipper = snapshot.getValue(Shipper.class);
shipper.setKey(snapshot.getKey());
mListShipper.add(shipper);
}
shipperListener.onLoadOrderSuccess(mListShipper);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
shipperListener.onLoadOrderFaield(databaseError.getMessage());
}
});
}
@Override
public void onLoadOrderSuccess(List<Shipper> mListShippers) {
if (mutableListShipper != null)
mutableListShipper.setValue(mListShippers);
}
@Override
public void onLoadOrderSuccess(int position, Order order, List<Shipper> mListShippers, AlertDialog dialog, Button btnOk, Button btnCancel, RadioButton radioShipping, RadioButton radioShipped, RadioButton radioCancelled, RadioButton radioDelete, RadioButton radiorestorePlaced) {
}
@Override
public void onLoadOrderFaield(String error) {
mutabMessageError.setValue(error);
}
}
|
package com.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Token {
private static final int SECRET_HASH_KEY=47686128;
private String username;
private Date expirationTime;
private String hash;
public Token(String username, Date expirationTime) {
this.username=username;
this.expirationTime=expirationTime;
try {
String hashString=username+expirationTime.toString();
this.hash = encrypt(hashString);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isValid() {
try {
Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date now=new Date(t);
if(this.expirationTime.compareTo(now)<0) {
return false;
}
String hashString=this.username+this.expirationTime.toString();
String hashTest = encrypt(hashString);
if(hashTest.equals(this.hash)) {
return true;
}else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public String toJson() {
String json="{";
json+="\"hash\":\""+this.hash+"\",";
json+="\"expirationTime\":\""+this.expirationTime.toString()+"\",";
json+="\"username\":\""+this.username+"\"";
json+="}";
return json;
}
private static final String ALGORITHM = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };
private String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = Base64.getEncoder().encodeToString(encValue);
return encryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public static byte[] getKeyvalue() {
return keyValue;
}
}
|
package forkjoinV2;
/**
* Task, to be executed by a fork-join {@link Pool}.
* <p>
* This is an abstract class. To use this, override the {@link Task#compute()} method
* with the implementation of the task to be executed.
* <p>
* Usually, a task will spawn sub-tasks. To do this, the implemention of the
* {@link Task#compute()} method will create new {@link Task} objects associated with
* these sub-tasks, calling {@link Task#fork()} to run them asynchronously, and calling
* {@link Task#join()} to obtain the results of these asynchronous computations.
*
* @param <V> the type of the computation result; may be Void if no result returned
*/
abstract public class Task<V> {
private V result;
private boolean isComplete = false;
/**
* Executes the task.
* This overridable method is a description of the task to be executed.
* This method may be called explicitly in order to run the task synchronously.
* <p>
* (To run the task asynchronously within a {@Pool}, you should instead
* call {Task#fork()} to schedule it for execution, and call
* {Task#join()} to obtain the result.)
*
* @return result of executing the task
*/
abstract protected V compute();
void asyncCompute() {
result = compute();
Pool pool = ((Worker) Thread.currentThread()).getPool();
synchronized (pool.getLock()) {
isComplete = true;
pool.getLock().notifyAll();
}
}
V externalInvoke(Pool pool) {
synchronized (pool.getLock()) {
pool.addExternalTask(this);
pool.getLock().notifyAll();
while (!isComplete) {
try {
pool.getLock().wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
return result;
}
}
/**
* Executes the task asynchronously.
* Calling this method places the task on a queue, from where it will be
* retrieved by pool workers.
* <p>
* This method be called from within a fork-join {@Pool}.
* It must not be called more than once.
*/
public void fork() {
Pool pool = ((Worker) Thread.currentThread()).getPool();
synchronized (pool.getLock()) {
pool.addTask(this);
pool.getLock().notifyAll();
}
}
/**
* Obtains the result of an asynchronous execution of the task.
* If the result is not available when this method is called,
* the calling thread will take other tasks from the pool's queue to work on
* until the result for this task is available.
* <p>
* This method must be called from within a fork-join {@link Pool}.
* It must not be called more than once.
* The call must happen after the {@link Task#fork()} method has been called,
* and it must happen from within the same fork-join {@link Pool} where
* {@link Task#fork()} was called.
*
* @return result of executing the task
*/
public V join() {
Pool pool = ((Worker) Thread.currentThread()).getPool();
while (true) {
Task<?> otherTask;
synchronized (pool.getLock()) {
while (!(isComplete || pool.hasTask())) {
try {
pool.getLock().wait();
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
if (isComplete) {
return result;
} else {
otherTask = pool.getTask();
}
}
otherTask.asyncCompute();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.