text stringlengths 10 2.72M |
|---|
package utils;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.BlogPage;
import pages.QuemSomosPage;
import pages.SobrePage;
import java.util.concurrent.TimeUnit;
public class SuperiorBar {
private WebDriver driver;
private By btnConteudodigital = By.className("custom-logo");
private By btnHome = By.cssSelector("#menu-item-63");
private By btnSobre = By.cssSelector("#menu-item-71");
private By btnQuemSomos = By.cssSelector("#menu-item-72");
private By btnBlog = By.cssSelector("#menu-item-116");
private By btnContato = By.cssSelector("#menu-item-191");
public SuperiorBar(WebDriver driver) {
this.driver = driver;
}
public void btnConteudodigitalClick() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
driver.findElement(btnConteudodigital).click();
}
public void btnHomeClick() {
driver.findElement(btnHome).click();
}
public SobrePage btnSobreClick() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(btnSobre)));
driver.findElement(btnSobre).click();
return new SobrePage(driver);
}
public QuemSomosPage btnQuemSomosClick() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(btnQuemSomos)));
driver.findElement(btnQuemSomos).click();
return new QuemSomosPage(driver);
}
public BlogPage btnBlogClick() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(btnBlog)));
driver.findElement(btnBlog).click();
return new BlogPage(driver);
}
public void btnContatoClick() {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(btnContato)));
driver.findElement(btnContato).click();
}
}
|
package com.example.service.impl;
import com.example.dto.TbEmp;
import com.example.dao.mapper.TbEmpMapper;
import com.example.service.TbEmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by sunming on 2019/6/14.
*/
@Service
public class TbEmpServiceImpl implements TbEmpService{
@Autowired
private TbEmpMapper tbEmpMapper;
public List<TbEmp> selectList(){
List<TbEmp> tbEmps = tbEmpMapper.selectList(null);
return tbEmps;
};
}
|
import java.util.*;
public class MyList {
private Vertex head;
private Vertex tail;
public MyList(){
}
public void add(Card card) throws MyException{
if(card==null){
throw new MyException("No card!");
}
else{
if(head==null){
head=new Vertex(card);
head.setNext(tail);
}
else{
int value=card.getValue();
Vertex buf=head;
while(buf.getValue()>value&&buf.getNext()!=null){
buf=buf.getNext();
}
if(buf.getValue()==value){
buf.addCard(card);
if(card.isHandCard()){
buf.setHasHandCard(true);
}
}
else{
if(buf.getPrev()==null){
buf.setPrev(new Vertex(card));
head=buf.getPrev();
head.setNext(buf);
}
else{
Vertex buf2=buf.getPrev();
buf.setPrev(new Vertex(card));
buf2.setNext(buf.getPrev());
buf.getPrev().setPrev(buf2);
}
}
}
}
}
public ArrayList<Card> findFour() throws MyException {
if (head == null) {
return null;
} else {
Vertex buf = head;
while ((buf != null) && !((buf.getNumOfSuits() == 4) && (buf.getHasHandCard()))) {
buf = buf.getNext();
}
if(buf==null){
return null;
}
else{
return buf.getCards();
}
}
}
private Vertex findMaxDouble() throws MyException{
if (head == null) {
return null;
} else{
Vertex buf=head;
while(buf!=null&&buf.getNumOfSuits()!=2){
buf=buf.getNext();
}
if(buf==null){
return null;
}
else{
return buf;
}
}
}
private Vertex findMaxTriple() throws MyException{
if (head == null) {
return null;
} else{
Vertex buf=head;
while(buf!=null&&buf.getNumOfSuits()!=3){
buf=buf.getNext();
}
if(buf==null){
return null;
}
else{
return buf;
}
}
}
private Vertex findMaxHandDouble() throws MyException{
if (head == null) {
return null;
} else{
Vertex buf=head;
while(buf!=null&&!(buf.getNumOfSuits()==2&&buf.getHasHandCard())){
buf=buf.getNext();
}
if(buf==null){
return null;
}
else{
return buf;
}
}
}
private Vertex findMaxHandTriple() throws MyException{
if (head == null) {
return null;
} else{
Vertex buf=head;
while(buf!=null&&!(buf.getNumOfSuits()==3&&buf.getHasHandCard())){
buf=buf.getNext();
}
if(buf==null){
return null;
}
else{
return buf;
}
}
}
public ArrayList<Card> findFullHouse() throws MyException{
if (head == null) {
return null;
} else{
Vertex maxdouble=this.findMaxDouble();
Vertex maxhanddouble=this.findMaxHandDouble();
Vertex maxtriple=this.findMaxTriple();
Vertex maxhandtriple=this.findMaxHandTriple();
if(maxdouble==null){
return null;
}
if(maxtriple==null){
return null;
}
ArrayList<Card> buf1;
ArrayList<Card> buf2;
if(maxhanddouble!=null){
buf1=maxhanddouble.getCards();
buf2=maxtriple.getCards();
buf2.addAll(buf1);
return buf2;
}
else{
if(maxhandtriple!=null){
buf1=maxhandtriple.getCards();
buf2=maxdouble.getCards();
buf1.addAll(buf2);
return buf1;
}
else{
return null;
}
}
}
}
public Card findMaxHandCard() throws MyException{
if (head == null) {
return null;
} else{
Vertex buf=head;
while(buf!=null&&!buf.getHasHandCard()){
buf=buf.getNext();
}
if(buf==null){
return null;
}
else{
return buf.getHandCard();
}
}
}
public ArrayList<Card> findDouble() throws MyException{
return this.findMaxHandDouble().getCards();
}
public ArrayList<Card> findTriple() throws MyException{
return this.findMaxHandTriple().getCards();
}
//public ArrayList<Card> findStreet() throws MyException{}
}
|
package net.budsapps.matchit;
import java.io.Serializable;
import java.text.DecimalFormat;
@SuppressWarnings("serial")
public class StatsData implements Serializable {
private int[] iTotalClicks;
private int[] iTotalGames;
private int[] iMinClicks;
private int[] iMaxClicks;
private int[] iGamesQuit;
private int[] iStatLevel;
public StatsData(){
iTotalClicks = new int[GlobalConstants.NO_OF_LEVELS];
iTotalGames = new int[GlobalConstants.NO_OF_LEVELS];
iMinClicks = new int[GlobalConstants.NO_OF_LEVELS];
iMaxClicks = new int[GlobalConstants.NO_OF_LEVELS];
iGamesQuit = new int[GlobalConstants.NO_OF_LEVELS];
iStatLevel = new int[GlobalConstants.NO_OF_LEVELS];
for (int i = 0; i < GlobalConstants.NO_OF_LEVELS; i++) {
iTotalClicks[i] = 0;
iTotalGames[i] = 0;
iMinClicks[i] = 0;
iMaxClicks[i] = 0;
iGamesQuit[i] = 0;
}
//Not sure the best way to handle this
iStatLevel[0] = GlobalConstants.LVL_VERY_EASY;
iStatLevel[1] = GlobalConstants.LVL_EASY;
iStatLevel[2] = GlobalConstants.LVL_MEDIUM;
iStatLevel[3] = GlobalConstants.LVL_HARD;
iStatLevel[4] = GlobalConstants.LVL_VERY_HARD;
}
public int getTotalClicks(int iLevel) {
int statIdx = getLevelIndex(iLevel);
return iTotalClicks[statIdx];
}
public int getTotalGames(int iLevel) {
int statIdx = getLevelIndex(iLevel);
return iTotalGames[statIdx];
}
public int getMinClicks(int iLevel) {
int statIdx = getLevelIndex(iLevel);
return iMinClicks[statIdx];
}
public int getMaxClicks(int iLevel) {
int statIdx = getLevelIndex(iLevel);
return iMaxClicks[statIdx];
}
public int getGamesQuit(int iLevel) {
int statIdx = getLevelIndex(iLevel);
return iGamesQuit[statIdx];
}
//Only used for display so I can return this as a String
public String getAveClicks(int iLevel){
double dAveClicks;
int statIdx = getLevelIndex(iLevel);
DecimalFormat decForm = new DecimalFormat( "#0.00" );
if (iTotalGames[statIdx] > 0)
dAveClicks = ((double) iTotalClicks[statIdx]) / ((double) iTotalGames[statIdx]);
else
dAveClicks = 0;
return decForm.format(dAveClicks);
}
//Get's the array index of the specified level
private int getLevelIndex(int iLevel){
for (int i = 0; i < GlobalConstants.NO_OF_LEVELS; i++){
if (iStatLevel[i] == iLevel)
return i;
}
//Shouldn't happen
return -1;
}
//take given info and updates the given stat level
public void updateRecord(int iLevel, int iClicks){
int statIdx = getLevelIndex(iLevel);
iTotalClicks[statIdx] = iTotalClicks[statIdx] + iClicks;
iTotalGames[statIdx]++;
if ((iClicks < iMinClicks[statIdx]) || (iMinClicks[statIdx] <=0))
iMinClicks[statIdx] = iClicks;
if ((iClicks > iMaxClicks[statIdx]) || (iMaxClicks[statIdx] <=0))
iMaxClicks[statIdx] = iClicks;
}
//updates games ended field for specified level
public void updateQuits(int iLevel) {
int statIdx = getLevelIndex(iLevel);
iGamesQuit[statIdx]++;
}
//Reset stats for current level
public void resetStats(int iLevel) {
int statIdx = getLevelIndex(iLevel);
iTotalClicks[statIdx] = 0;
iTotalGames[statIdx] = 0;
iMinClicks[statIdx] = 0;
iMaxClicks[statIdx] = 0;
iGamesQuit[statIdx] = 0;
}
}
|
package com.mediafire.sdk;
import java.util.Arrays;
import java.util.Map;
public class MFApiRequest implements MediaFireApiRequest {
private final String path;
private final Map<String, Object> queryParameters;
private final byte[] payload;
private final Map<String, Object> headers;
public MFApiRequest(String path, Map<String, Object> queryParameters, byte[] payload, Map<String, Object> headers) {
this.payload = payload;
this.path = path;
this.queryParameters = queryParameters;
this.headers = headers;
}
@Override
public String getPath() {
return path;
}
@Override
public Map<String, Object> getQueryParameters() {
return queryParameters;
}
@Override
public Map<String, Object> getHeaders() {
return headers;
}
@Override
public byte[] getPayload() {
return payload;
}
@Override
public String toString() {
return "MFApiRequest{" +
"path='" + path + '\'' +
", queryParameters=" + queryParameters +
", payload=" + (payload == null || payload.length == 0 ? "null or empty" : payload.length > 5000 ? "size: " + payload.length : new String(payload)) +
", headers=" + headers +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MFApiRequest that = (MFApiRequest) o;
if (getPath() != null ? !getPath().equals(that.getPath()) : that.getPath() != null) return false;
if (getQueryParameters() != null ? !getQueryParameters().equals(that.getQueryParameters()) : that.getQueryParameters() != null)
return false;
if (!Arrays.equals(getPayload(), that.getPayload())) return false;
return !(getHeaders() != null ? !getHeaders().equals(that.getHeaders()) : that.getHeaders() != null);
}
@Override
public int hashCode() {
int result = getPath() != null ? getPath().hashCode() : 0;
result = 31 * result + (getQueryParameters() != null ? getQueryParameters().hashCode() : 0);
result = 31 * result + (getPayload() != null ? Arrays.hashCode(getPayload()) : 0);
result = 31 * result + (getHeaders() != null ? getHeaders().hashCode() : 0);
return result;
}
}
|
//номер строки которая вызывает метод
package Tasks;
public class Task48 {
public static void main(String[] args) {
method1();
}
public static int method1() {
method2();
System.out.println("Метод 1 вызвал - строка " + Thread.currentThread().getStackTrace()[2].getLineNumber());
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method2() {
method3();
System.out.println("Метод 2 вызвал - строка " + Thread.currentThread().getStackTrace()[2].getLineNumber());
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method3() {
method4();
System.out.println("Метод 3 вызвал - строка " + Thread.currentThread().getStackTrace()[2].getLineNumber());
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method4() {
method5();
System.out.println("Метод 4 вызвал - строка " + Thread.currentThread().getStackTrace()[2].getLineNumber());
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
public static int method5() {
System.out.println("Метод 5 вызвал - строка " + Thread.currentThread().getStackTrace()[2].getLineNumber());
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
}
|
package uquest.com.bo.models.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
@Entity
@Table(name = "institutos")
public class Instituto implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
@NotEmpty
private String nombre;
@Column
@NotEmpty
private String sigla;
@Column
@NotEmpty
private String fono;
@Column
@NotEmpty
private String email;
@ManyToOne
@JoinColumn(name="carrera_id")
private Carrera carrera;
// @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
// @JsonIgnore
// @JoinColumn(name="carrera_id")
// @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
// private Carrera carrera;
// @JsonIgnore
// @ManyToMany(mappedBy = "institutos")
// private List<Persona> usuarios;
@JsonIgnore
public Carrera getCarrera() {
return carrera;
}
@JsonProperty
public void setCarrera(Carrera carrera) {
this.carrera = carrera;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public String getFono() {
return fono;
}
public void setFono(String fono) {
this.fono = fono;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package technology.tabula.json;
import java.lang.reflect.Type;
import java.util.List;
import technology.tabula.RectangularTextContainer;
import technology.tabula.Table;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public final class TableSerializer implements JsonSerializer<Table> {
public static final TableSerializer INSTANCE = new TableSerializer();
private TableSerializer() {
// singleton
}
@Override
public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray data = new JsonArray();
for (List<RectangularTextContainer> srcRow : src.getRows()) {
if (srcRow.get(0).getText().matches("\\d+")){
JsonArray row = new JsonArray();
for (RectangularTextContainer textChunk : srcRow) {
row.add(textChunk.getText().replaceAll("\\s+", " ").trim());
}
data.add(row);
}
}
return data;
}
}
|
package com.java.project.BackEnd.Mapper;
import com.java.project.BackEnd.Model.Customer;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface CustomerMapper {
String register = "INSERT INTO customer (fullname, username, password) VALUES(#{fullname}, #{username}, #{password});";
String checkUser = "SELECT*FROM customer WHERE username=#{username}";
String loginAuth = "SELECT*FROM customer WHERE username=#{username} AND password=#{password}";
@Insert(register)
int register(Customer customer);
@Select(checkUser)
@Results({
@Result(column = "username", property = "username")
})
List<Customer> checkUser(Customer customer);
@Select(loginAuth)
@Results({
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password")
})
List<Customer> loginAuth(Customer customer);
@Select(checkUser)
@Results({
@Result(column = "id_customer",property = "id_customer"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password")
})
Customer getCustomer(Customer customer);
}
|
package choo.edeline.foodrng;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginFragment loginFragment = new LoginFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.loginContainer, loginFragment).commit();
}
} |
package com.redhat.service.bridge.actions;
import java.util.Optional;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
@ApplicationScoped
public class ActionProviderFactory {
@Inject
Instance<ActionProvider> actionProviders;
public ActionProvider getActionProvider(String actionType) {
Optional<ActionProvider> ap = actionProviders.stream().filter((a) -> a.accept(actionType)).findFirst();
if (ap.isPresent()) {
return ap.get();
}
throw new ActionProviderException(String.format("There is no ActionProvider recognised for type '%s'", actionType));
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.engine.events;
import pl.edu.icm.unity.Constants;
import pl.edu.icm.unity.exceptions.InternalException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Describes method invocation. Provides to/from JSON serialization.
* @author K. Benedyczak
*/
public class InvocationEventContents
{
private String method;
private String interfaceName;
private String exception;
private static ObjectMapper mapper = Constants.MAPPER;
public InvocationEventContents(String method, String interfaceName)
{
this.method = method;
this.interfaceName = interfaceName;
}
public InvocationEventContents(String method, String interfaceName, String exception)
{
this.method = method;
this.interfaceName = interfaceName;
this.exception = exception;
}
public InvocationEventContents()
{
}
public String toJson()
{
ObjectNode root = mapper.createObjectNode();
root.put("method", method);
root.put("interfaceName", interfaceName);
root.put("exception", exception);
try
{
return mapper.writeValueAsString(root);
} catch (JsonProcessingException e)
{
throw new InternalException("Can't serialize InvocationEventContents to Json", e);
}
}
public void fromJson(String json)
{
JsonNode root;
try
{
root = mapper.readTree(json);
} catch (Exception e)
{
throw new InternalException("Can't deserialize InvocationEventContents from Json", e);
}
method = root.get("method").asText();
interfaceName = root.get("interfaceName").asText();
JsonNode jn = root.get("exception");
exception = jn == null ? null : jn.asText();
}
public String getMethod()
{
return method;
}
public String getInterfaceName()
{
return interfaceName;
}
public String getException()
{
return exception;
}
}
|
package com.edu.realestate.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.edu.realestate.model.City;
import com.edu.realestate.model.CommercialProperty;
public class CommercialPropertyDaoJDBC extends AbstractDaoJDBC implements CommercialPropertyDao {
@Override
public void create(CommercialProperty cp) {
// TODO Auto-generated method stub
}
@Override
public CommercialProperty read(Integer id) {
CommercialProperty cp = null;
try {
Statement st = getConnection().createStatement();
String req = "SELECT * FROM commercial_property cp " +
" JOIN real_estate r ON r.id = cp.id " +
" WHERE cp.id = " + id;
ResultSet rs = st.executeQuery(req);
if (rs.next()) {
cp = new CommercialProperty();
cp.setId(rs.getInt("id"));
cp.setPrice(rs.getInt("price"));
cp.setArea(rs.getShort("area"));
cp.setAvailable(rs.getString("available").equals("Y"));
CityDao cdao = new CityDaoJDBC();
City city = cdao.read(rs.getInt("city_id"));
cp.setCity(city);
}
} catch (SQLException e) {
System.out.println("CommercialPropertyDaoJDBC error : " + e.getLocalizedMessage());
}
return cp;
}
@Override
public void update(CommercialProperty cp) {
// TODO Auto-generated method stub
}
@Override
public void delete(CommercialProperty cp) {
// TODO Auto-generated method stub
}
}
|
package com.nosae.game.objects;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import com.nosae.game.popo.GameParams;
import com.nosae.game.popo.R;
/**
* Created by eason on 2015/10/31.
*/
public class Life1 extends GameObj {
private static int mLife = 5;
private static int oldLife = mLife;
private int scaleTotal = 10;
private static int scaleOffset = 0;
private int scaleCount = 0;
private Bitmap mNumberImage;
BitmapFactory.Options mOptions;
private static Integer[] mNumberTable = {
R.drawable.s_0,
R.drawable.s_1,
R.drawable.s_2,
R.drawable.s_3,
R.drawable.s_4,
R.drawable.s_5,
R.drawable.s_6,
R.drawable.s_7,
R.drawable.s_8,
R.drawable.s_9
};
public Life1(int destX, int destY, int destWidth, int destHeight, int srcX, int srcY, int srcWidth, int srcHeight) {
super(destX, destY, destWidth, destHeight, srcX, srcY, srcWidth, srcHeight, 0, 0, 0);
mNumberImage = BitmapFactory.decodeResource(GameParams.res, mNumberTable[getLife()]);
}
public static int getLife() {
return mLife;
}
public static void setLife(int mLife) {
Life1.mLife = mLife;
}
public static void addLife(int life) {
if (life != 0)
scaleOffset = 1;
mLife += life;
if (mLife > 5)
mLife = 5;
else if (mLife < 0)
mLife = 0;
}
public void updateLife() {
if (getLife() != oldLife) {
mNumberImage = GameParams.decodeResource(mNumberTable[getLife()]);
oldLife = getLife();
}
}
public void action() {
if (scaleOffset == 0)
return;
if (scaleOffset == 1) {
scale(1, 1);
scaleCount ++;
} else if (scaleOffset == -1) {
scale(-1, -1);
scaleCount--;
}
if (scaleCount >= scaleTotal)
scaleOffset = -1;
else if (scaleCount <= 0)
scaleOffset = 0;
}
public void draw(Canvas canvas) {
if (mNumberImage != null) {
canvas.drawBitmap(mNumberImage, srcRect, destRect, null);
}
}
}
|
package exception;
public class IncorrectNameAndSecondNameException extends RuntimeException {
public IncorrectNameAndSecondNameException(String message) {
super("Wrong format: " + message + ". Correct format: Василий Петров");
}
}
|
package cp.end_of_slides2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
public class ExercisesFromSlides {
/*
Opt: Define a generic class Pair<K,V> that can store pairs of values of any types.
Opt: Create a List of Pair<String, Integer> with some values. For each pair containing a string s and an integer n, we say that s is associated to n.
Opt: For each string (first value of a pair) in the list, print the sum of all integers associated to that string.
*/
public static class Pair<K,V> {
public final K key;
public final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
}
public static void main(String args[]) {
List<Pair<String, Integer>> list = new ArrayList<>();
list.add(new Pair<>("John", 1));
list.add(new Pair<>("John", 2));
list.add(new Pair<>("Paul", 3));
list.add(new Pair<>("Paul", 2));
list.add(new Pair<>("Paul", 4));
list.add(new Pair<>("Ringo", 7));
list.add(new Pair<>("Ringo", 2));
list.add(new Pair<>("Ringo", 5));
list.add(new Pair<>("George", 16));
HashMap<String, Integer> sums = new HashMap<>();
for (Pair<String, Integer> p : list) {
Integer sum_now = sums.get(p.key);
if (sum_now == null) {
sums.put(p.key, p.value);
}
else {
sums.put(p.key, p.value+sum_now);
}
}
for (Entry<String,Integer> e : sums.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
}
}
|
import java.io.*;
class BubbleSort
{
public static void bubbleSort(int arr[])
{
int temp;
int n=arr.length;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(arr[j+1]<arr[j])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void printArray(int arr[])
{
for(int i=0; i<arr.length; i++)
System.out.print(arr[i]+"\t");
System.out.println();
}
public static void main(String args[])
{
int[] arr = {3,60,35,2,45,320,5};
System.out.println("Array Before Bubble sort");
printArray(arr);
bubbleSort(arr);
System.out.println("Array after Bubble sort");
printArray(arr);
}
} |
package bd.ac.du.iit.bsse0516;
public class LOCCounter {
private String code;
private int lOC;
private String updatedCode;
public LOCCounter(String code) {
this.code = code;
this.lOC = 0;
}
public double getKLOC() {
double kloc = ((double) (getLOC()) / 1000.00);
return kloc;
}
public String getUpdatedCode() {
return updatedCode;
}
public int getLOC() {
updatedCode = removeComments(this.code);
updatedCode = removePackageDeclaration(updatedCode);
updatedCode = removeImportDeclaration(updatedCode);
updatedCode = removeAnnotation(updatedCode);
updatedCode = removeBlankLine(updatedCode);
lOC = countLines(updatedCode);
return lOC;
}
private int countLines(String code) {
String[] lines = code.split("\r\n|\r|\n");
return lines.length;
}
private String removeComments(String code) {
String modifiedCode = "(?://.*)|(/\\*(?:.|[\\n\\r])*?\\*/)";
return removeBlankLine(code.replaceAll(modifiedCode, " "));
}
private String removePackageDeclaration(String code) {
String modifiedCode = "(package(.*?)\\;(.*))";
return removeBlankLine(code.replaceAll(modifiedCode, " "));
}
private String removeImportDeclaration(String code) {
String modifiedCode = "(import(.*?)\\;(.*))";
return removeBlankLine(code.replaceAll(modifiedCode, " "));
}
private String removeAnnotation(String code) {
String modifiedCode = "(@(.*?)\\s)";
return removeBlankLine(code.replaceAll(modifiedCode, " "));
}
private String removeBlankLine(String code) {
String modifiedCode = code.replaceAll("(?m)^[ \t]*\r?\n", "");
return modifiedCode;
}
}
|
package com.example.shoppahlicfinal.controllers;
import android.app.Application;
public class ApplicationController extends Application{
String username;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
//setter getters
public void setUsername(String uname){
this.username = uname;
}
public String getUsername(){
return username;
}
}
|
package com.trump.auction.back.push.enums;
import java.util.LinkedHashMap;
import java.util.Map;
public enum NotificationRecordTimeTypeEnum {
//发送时间类型: 1: 立即发送 2:定时发送
NOW(1, "立即发送"),
TIMING(2,"定时发送");
private final Integer type;
private final String name;
public Integer getType() { return type; }
public String getName() { return name; }
NotificationRecordTimeTypeEnum(Integer type, String name) {
this.type = type;
this.name = name;
}
public static String getTypeName(Integer type) {
String name = null;
for (NotificationRecordTimeTypeEnum tmp : values()) {
if (type.intValue() == tmp.getType().intValue()) {
name = tmp.getName();
break;
}
}
return name;
}
public static Map<Integer, String> getAllType() {
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
for (NotificationRecordTimeTypeEnum tmp : values()) {
map.put(tmp.getType(), tmp.getName());
}
return map;
}
}
|
package ehwaz.problem_solving.algorithm.dynamic_programmming.mincostpath;
import java.util.*;
import java.io.*;
/**
* Created by Sangwook on 2016-05-11.
*/
public class MinCostPath {
public static void runSolution(InputStream istream) {
Scanner sc = new Scanner(istream);
int rowSize = sc.nextInt();
int colSize = sc.nextInt();
sc.nextLine();
int[][] board = new int[rowSize][colSize];
String row;
StringTokenizer st;
for (int rowIdx = 0; rowIdx < rowSize; rowIdx++) {
row = sc.nextLine();
st = new StringTokenizer(row);
for (int colIdx = 0; colIdx < colSize; colIdx++) {
board[rowIdx][colIdx] = Integer.parseInt(st.nextToken());
}
}
int[][] memo = new int[rowSize][colSize];
memo[0][0] = board[0][0];
for (int i = 1; i < rowSize; i++) {
memo[i][0] = memo[i-1][0] + board[i-1][0];
}
for (int j = 1; j < colSize; j++) {
memo[0][j] = memo[0][j-1] + board[0][j];
}
List<Integer> minCandidates;
for (int i = 1; i < rowSize; i++) {
for (int j = 1; j < colSize; j++) {
minCandidates = new ArrayList<Integer>();
minCandidates.add(memo[i-1][j-1]);
minCandidates.add(memo[i-1][j]);
minCandidates.add(memo[i][j-1]);
memo[i][j] = board[i][j] + Collections.min(minCandidates);
}
}
System.out.println(memo[rowSize-1][colSize-1]);
}
public static void main(String[] args) {
runSolution(System.in);
}
}
|
package br.com.candleanalyser.matchers.high;
import java.util.logging.Logger;
import br.com.candleanalyser.engine.Candle;
import br.com.candleanalyser.engine.Indicator;
import br.com.candleanalyser.engine.StockPeriod;
import br.com.candleanalyser.matchers.IndicatorMatcher;
import br.com.candleanalyser.matchers.low.HaramiBullishMatcher;
public class DarkCloudCoverBearishMatcher implements IndicatorMatcher {
private static final Logger logger = Logger.getLogger(DarkCloudCoverBearishMatcher.class.getName());
@Override
public Indicator getIndicator() {
return new Indicator("Dark Cloud Cover Bearish",
Indicator.Trend.BEARISH,
Indicator.Pattern.REVERSAL,
Indicator.Reliability.HIGH);
}
@Override
public boolean matches(StockPeriod stockPeriod) {
Candle candle1 = stockPeriod.getLast(1);
Candle candle2 = stockPeriod.getLast(0);
if(stockPeriod.isUpTrend(2)) {
if(stockPeriod.isLongDay(candle1) && candle1.isWhite()) {
if(candle2.isBlack()
&& candle2.getOpen()>=candle1.getMax()) {
if(candle2.getClose()<=candle1.getBodyMidPoint()) {
logger.fine("Found a match (" + candle2 + ")");
return true;
}
}
}
}
return false;
}
}
|
package mapx.util;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
/**
* 用于商业运算的常用计算工具类
* @author Ready
* @date 2012-9-27
*/
public class Arith {
// 禁止创建实例
private Arith() {}
/**
* 表示数值0的BigDecimal静态常量
*/
public static final BigDecimal ZERO = new BigDecimal(0);
/**
* 表示数值1的BigDecimal静态常量
*/
public static final BigDecimal ONE = new BigDecimal(1);
/**
* 商业加法运算
* @param a 加数1
* @param b 加数2
* @return
*/
public static double add(double a, double b) {
return new BigDecimal(Double.toString(a)).add(new BigDecimal(Double.toString(b))).doubleValue();
}
/**
* 商业减法运算
* @param a 被减数
* @param b 减数
* @return
*/
public static double minus(double a, double b) {
return add(a, -b);
}
/**
* 商业乘法运算
* @param a 乘数1
* @param b 乘数2
* @return
*/
public static double multiply(double a, double b) {
return new BigDecimal(Double.toString(a)).multiply(new BigDecimal(Double.toString(b))).doubleValue();
}
/**
* 商业乘法运算(四舍五入)
* @param a 乘数1
* @param b 乘数2
* @param scale 小数部分的精确位数
* @return
*/
public static double multiply(double a, double b, int scale) {
return new BigDecimal(Double.toString(a)).multiply(new BigDecimal(Double.toString(b))).divide(new BigDecimal(1), scale, RoundingMode.HALF_UP).doubleValue();
}
/**
* 商业乘法运算(四舍五入)<br>
* <strong>注意:</strong>此方法的有效位数包含整数部分在内<br>
* 将precision设为long类型只是为了重载的需要
* @param a 乘数1
* @param b 乘数2
* @param precision 包含整数部分的有效位数
* @return
*/
public static double multiply(double a, double b, long precision) {
MathContext context = new MathContext((int) precision, RoundingMode.HALF_UP);
return new BigDecimal(Double.toString(a)).multiply(new BigDecimal(Double.toString(b)), context).doubleValue();
}
/**
* 商业除法运算(四舍五入)
* @param a 被除数
* @param b 除数
* @param scale 小数精确度位数
* @return
*/
public static double divide(double a, double b, int scale) {
Assert.notTrue(scale < 0, "指定的小数位数不能小于0!");
return new BigDecimal(Double.toString(a)).divide(new BigDecimal(Double.toString(b)), scale, RoundingMode.HALF_UP).doubleValue();
}
/**
* 以四舍五入的方式使指定小数精确到指定的小数位数
* @param d 指定的小数
* @param scale 指定的小数精确位数
* @return
*/
public static double round(double d, int scale) {
Assert.notTrue(scale < 0, "四舍五入时,指定的精确小数位数不能小于0!");
return new BigDecimal(Double.toString(d)).divide(ONE, scale, RoundingMode.HALF_UP).doubleValue();
}
/**
* 以指定舍入方式使指定小数精确到指定的小数位数
* @param d 指定的小数
* @param scale 指定的小数精确位数
* @param mode 指定的舍入模式
* @return
*/
public static double truncate(double d, int scale, RoundingMode mode) {
Assert.notTrue(scale < 0, "指定的精确小数位数不能小于0!");
return new BigDecimal(Double.toString(d)).divide(ONE, scale, mode).doubleValue();
}
}
|
/**
* IoTSimulationEngine.java
* @author guochenshen
*
* Performs the simulations
* - increments the system by specified time interval and calculates new state
* - optimization performed using genetic algorithm
*/
package object.simulation;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.w3c.dom.Document;
import object.device.DeciderACBinary;
import object.device.DeciderHeaterBinary;
import object.device.EffectorAirConditioner;
import object.device.EffectorHeater;
import object.device.SensorTemp;
import object.deviceinterface.Decider;
import object.deviceinterface.Effector;
import object.deviceinterface.Sensor;
import object.graph.Cardinality;
import object.graph.Device;
import object.graph.DeviceConnection;
import object.graph.DeviceGraph;
import object.graph.Room;
import object.graph.RoomFactoryBuilder;
import object.graph.RoomGraph;
public class IoTSimulationEngine {
// constants
public static final int SECONDS_PER_MINUTE = 60;
public static final int MINUTES_PER_HOUR = 60;
public static final int HOURS_PER_DAY = 24;
public static final int DAYS_PER_YEAR = 365;
public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
public static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
public static final int SECONDS_PER_YEAR = SECONDS_PER_DAY * DAYS_PER_YEAR;
// algorithm default settings
// iterations of genetic algorithm
private static final int DEFAULT_ITERATIONS = 10000;
// duration of each iteration
private static final double DEFAULT_ITERATION_DURATION = SECONDS_PER_DAY;
private static final double DEFAULT_STEP_DURATION = 1.0;
// number of specimen in the pool
private static final int DEFAULT_POOL_SIZE = 100;
// ratio of specimen selected for elitism
private static final double DEFAULT_ELITISM_PERCENTAGE = 0.05;
// ratio of specimen selected for mutation
private static final double DEFAULT_MUTATION_PERCENTAGE = 0.475;
// ratio of specimen selected for combination
private static final double DEFAULT_COMBINATION_PERCENTAGE = 0.475;
private static final double DEFAULT_ELECTRICITY_COST = 0.12;
// default room graph selection
private int DEFAULT_ROOM_GRAPH_SELECTION = 2;
// program variables
// room graph object
private RoomGraph room_graph;
// device graph object
private DeviceGraph device_graph;
private List<DeviceSpecies> device_segments;
// current time of system in [s]
private double time;
// customization settings, parsed from XML settings document
private Document settings;
// genetic algorithm settings
int iterations = DEFAULT_ITERATIONS;
double iteration_duration = DEFAULT_ITERATION_DURATION;
double step_duration = DEFAULT_STEP_DURATION;
int pool_size = DEFAULT_POOL_SIZE;
double ep = DEFAULT_ELITISM_PERCENTAGE;
double mp = DEFAULT_MUTATION_PERCENTAGE;
double cp = DEFAULT_COMBINATION_PERCENTAGE;
// random object to generate random numbers
Random random;
// generation function settings
int device_count = 50; // max number of devices to place into system
// ******************** CONSTRUCTOR ********************
/**
* Constructor for the IoT Simulation Engine. Instantiates graph objects for
* the Room Graph and the Device Graph.
*
* @throws IOException
* initial configuration files could not be found
*
*/
public IoTSimulationEngine(Document settings) {
// sets initial time to 0
this.time = 0;
// creates and sets up new room_graph
// this.setup_room_graph();
// this.device_graph = new DeviceGraph();
//
// // passes reference to each object
// this.room_graph.set_device_graph(this.device_graph);
// this.device_graph.set_room_graph(this.room_graph);
//
// this.device_segments = new ArrayList<DeviceSpecies>();
//
// // sets up the graphs to initial state
// this.setupDeviceGraph();
this.settings = settings;
// initializes the Random object
this.random = new Random();
}
// ******************** ROOM GRAPH SETUP *********************
/**
* setup the room graph based on default setting
* 1 is for the small room graph
* 2 is for the medium room graph
* 3 is for the large room graph
*/
private void setup_room_graph() {
int room_layout = this.DEFAULT_ROOM_GRAPH_SELECTION;
switch (room_layout) {
case 1:
this.setup_room_graph_small();
break;
case 2:
this.setup_room_graph_medium();
break;
case 3:
this.setup_room_graph_large();
break;
default:
this.setup_room_graph_small();
break;
}
return;
}
/**
* creates a small room setup for the simulation
* generates a sample studio of 50 square meters (~550 square feet)
*
* Overall size 10 x 5 [m]
* room 1 10x5:50 (20, 20, 30, 25) - Studio
*/
private void setup_room_graph_small() {
System.out.println("Generating Small Room Layout");
this.room_graph = new RoomGraph();
this.room_graph.set_max_x(50);
this.room_graph.set_max_y(50);
RoomFactoryBuilder builder = this.room_graph.get_builder();
// creates room 1 10x5:50 (20, 20, 30, 25) - Studio
builder.create_room();
builder.set_x_coor(20);
builder.set_y_coor(20);
builder.set_length(10);
builder.set_width(5);
builder.set_name("Room 1: Studio");
Room room_1 = builder.get_room();
this.room_graph.insert_room(room_1);
}
/**
* creates a medium room setup for the simulation
* generates a sample apartment of 100 square meters (~1000 square feet)
*
* Overall size 13 x 8 [m]
* room 1 8x5:40 (30, 30, 38, 35) - Living Room
* room 2 6x3:18 (30, 35, 36, 38) - Kitchen
* room 3 2x1.5:3 (36, 35, 38, 36.5) - Bathroom 1
* room 4 2x1.5:3 (36, 36.5, 38, 38) - Bathroom 2
* room 5 4x4:16 (38, 30, 42, 34) - Bedroom 1
* room 6 5x4:20 (38, 34, 43, 38) - Bedroom 2
* room 7 1x2:2 (42, 30, 43, 32) - Closet 1
* room 8 1x2:2 (42, 32, 43, 34) - Closet 2
*/
private void setup_room_graph_medium() {
this.room_graph = new RoomGraph();
this.room_graph.set_max_x(50);
this.room_graph.set_max_y(50);
RoomFactoryBuilder builder = this.room_graph.get_builder();
builder.create_room();
builder.set_x_coor(30);
builder.set_y_coor(30);
builder.set_length(8);
builder.set_width(5);
builder.set_height(3);
builder.set_name("Room 1: Living Room");
Room room_1 = builder.get_room();
builder.create_room();
builder.set_x_coor(30);
builder.set_y_coor(35);
builder.set_length(6);
builder.set_width(3);
builder.set_height(3);
builder.set_name("Room 2: Kitchen");
Room room_2 = builder.get_room();
// creates a kitchen
builder.create_room();
builder.set_x_coor(36);
builder.set_y_coor(35);
builder.set_length(2);
builder.set_width(1.5);
builder.set_height(3);
builder.set_name("Room 3: Bathroom 1");
Room room_3 = builder.get_room();
// creates a closet
builder.create_room();
builder.set_x_coor(36);
builder.set_y_coor(36.5);
builder.set_length(2);
builder.set_width(1.5);
builder.set_height(3);
builder.set_name("Room 4: Bathroom 2");
Room room_4 = builder.get_room();
// creates a bedroom
builder.create_room();
builder.set_x_coor(38);
builder.set_y_coor(30);
builder.set_length(4);
builder.set_width(4);
builder.set_height(3);
builder.set_name("Room 5: Bedroom 1");
Room room_5 = builder.get_room();
// creates a bedroom
builder.create_room();
builder.set_x_coor(38);
builder.set_y_coor(34);
builder.set_length(5);
builder.set_width(4);
builder.set_height(3);
builder.set_name("Room 6: Bedroom 2");
Room room_6 = builder.get_room();
// creates a bedroom
builder.create_room();
builder.set_x_coor(42);
builder.set_y_coor(30);
builder.set_length(1);
builder.set_width(2);
builder.set_height(3);
builder.set_name("Room 7: Closet 1");
Room room_7 = builder.get_room();
// creates a bedroom
builder.create_room();
builder.set_x_coor(42);
builder.set_y_coor(32);
builder.set_length(1);
builder.set_width(2);
builder.set_height(3);
builder.set_name("Room 8: Closet 2");
Room room_8 = builder.get_room();
// inserts each room into the room_graph
this.room_graph.insert_room(room_1);
this.room_graph.insert_room(room_2);
this.room_graph.insert_room(room_3);
this.room_graph.insert_room(room_4);
this.room_graph.insert_room(room_5);
this.room_graph.insert_room(room_6);
this.room_graph.insert_room(room_7);
this.room_graph.insert_room(room_8);
this.room_graph.insert_room_connection(room_1, Cardinality.SOUTH, room_2, Cardinality.NORTH);
this.room_graph.insert_room_connection(room_1, Cardinality.SOUTH, room_3, Cardinality.NORTH);
this.room_graph.insert_room_connection(room_1, Cardinality.EAST, room_5, Cardinality.WEST);
this.room_graph.insert_room_connection(room_4, Cardinality.EAST, room_6, Cardinality.WEST);
this.room_graph.insert_room_connection(room_1, Cardinality.EAST, room_6, Cardinality.WEST);
this.room_graph.insert_room_connection(room_5, Cardinality.EAST, room_7, Cardinality.WEST);
this.room_graph.insert_room_connection(room_6, Cardinality.NORTH, room_8, Cardinality.SOUTH);
}
/**
* creates a large multi room setup for the RoomGraph
*/
private void setup_room_graph_large() {
this.room_graph = new RoomGraph();
this.room_graph.set_max_x(50);
this.room_graph.set_max_y(50);
RoomFactoryBuilder builder = this.room_graph.get_builder();
// creates a bathroom
builder.create_room();
builder.set_x_coor(5);
builder.set_y_coor(5);
builder.set_length(10);
builder.set_width(10);
builder.set_height(3);
builder.set_name("Bedroom 1");
Room room_1 = builder.get_room();
// creates a hallway
builder.create_room();
builder.set_x_coor(5);
builder.set_y_coor(15);
builder.set_length(3);
builder.set_width(10);
builder.set_height(10);
builder.set_name("Bedroom 2");
Room room_2 = builder.get_room();
// creates a kitchen
builder.create_room();
builder.set_x_coor(5);
builder.set_y_coor(25.0);
builder.set_length(10);
builder.set_width(10);
builder.set_height(3);
builder.set_name("Bedroom 3");
Room room_3 = builder.get_room();
// creates a closet
builder.create_room();
builder.set_x_coor(15);
builder.set_y_coor(5);
builder.set_length(3);
builder.set_width(30);
builder.set_height(3);
builder.set_name("Hallway");
Room room_4 = builder.get_room();
// creates a bedroom
builder.create_room();
builder.set_x_coor(18);
builder.set_y_coor(5);
builder.set_length(10);
builder.set_width(10);
builder.set_height(3);
builder.set_name("Bathroom");
Room room_5 = builder.get_room();
// creates a living room
builder.create_room();
builder.set_x_coor(18);
builder.set_y_coor(15);
builder.set_length(10);
builder.set_width(10);
builder.set_height(3);
builder.set_name("Middle Room");
Room room_6 = builder.get_room();
// creates a living room
builder.create_room();
builder.set_x_coor(18);
builder.set_y_coor(25);
builder.set_length(10);
builder.set_width(10);
builder.set_height(3);
builder.set_name("closet");
Room room_7 = builder.get_room();
// creates a living room
builder.create_room();
builder.set_x_coor(28);
builder.set_y_coor(5);
builder.set_length(20);
builder.set_width(30);
builder.set_height(3);
builder.set_name("Living Room");
Room room_8 = builder.get_room();
// creates a living room
builder.create_room();
builder.set_x_coor(48);
builder.set_y_coor(5);
builder.set_length(10);
builder.set_width(30);
builder.set_height(3);
builder.set_name("Kitchen");
Room room_9 = builder.get_room();
this.room_graph.insert_room(room_1);
this.room_graph.insert_room(room_2);
this.room_graph.insert_room(room_3);
this.room_graph.insert_room(room_4);
this.room_graph.insert_room(room_5);
this.room_graph.insert_room(room_6);
this.room_graph.insert_room(room_7);
this.room_graph.insert_room(room_8);
this.room_graph.insert_room(room_9);
this.room_graph.insert_room_connection(room_1, Cardinality.EAST, room_4, Cardinality.WEST);
this.room_graph.insert_room_connection(room_2, Cardinality.EAST, room_4, Cardinality.WEST);
this.room_graph.insert_room_connection(room_3, Cardinality.EAST, room_4, Cardinality.WEST);
this.room_graph.insert_room_connection(room_4, Cardinality.EAST, room_5, Cardinality.WEST);
this.room_graph.insert_room_connection(room_4, Cardinality.EAST, room_6, Cardinality.WEST);
this.room_graph.insert_room_connection(room_4, Cardinality.EAST, room_7, Cardinality.WEST);
this.room_graph.insert_room_connection(room_7, Cardinality.EAST, room_8, Cardinality.WEST);
this.room_graph.insert_room_connection(room_8, Cardinality.EAST, room_9, Cardinality.WEST);
}
// ******************** TEST FUNCTIONS ********************
/**
* tests the small test case for the simulation
*/
public void test_small() {
this.setup_room_graph_small();
// this.setup_device_graph_small();
return;
}
/**
* tests benchmark case of the study
* representative of a studio apartment (~550 square feet / ~50 square meters)
* traditional heating setup
*/
private void test_small_benchmark() {
this.setup_room_graph_small();
return;
}
/**
* tests the medium test case for the simulation
*/
private void test_medium() {
System.out.println("Testing Medium");
this.setup_room_graph_medium();
System.out.println("Made Room Graph");
try {
run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void test_medium_benchmark() {
System.out.println("setting up room graph");
this.setup_room_graph_medium();
System.out.println(this.room_graph.get_rooms().size());
System.out.println("generating device graph");
List<SimulationSpecies> pool = null;
List<SimulationSpecies> next_pool = new ArrayList<SimulationSpecies>();
try {
pool = this.setup_device_graph_medium_benchmark();
} catch (IOException e) {
e.printStackTrace();
}
for (int iteration = 0; iteration < iterations; iteration++) {
for (int i = 0; i < pool.size(); i++) {
SimulationSpecies single = pool.get(i);
for (int time = 0; (time * this.step_duration) < this.iteration_duration; time++) {
single.step(this.step_duration);
}
System.out.println("comfort");
System.out.println(single.get_comfort());
System.out.println("energy");
System.out.println((single.get_energy_usage() / 3600000) * (30 * .12));
System.out.println("cost");
System.out.println(single.get_cost());
}
try(FileWriter fw = new FileWriter("log_benchmark_medium.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
for (int printing = 0; printing < pool.size(); printing++) {
out.println(Integer.toString(iteration));
out.println(Integer.toString(printing));
out.println(pool.get(printing).get_comfort());
out.println(pool.get(printing).get_energy_usage());
out.println(pool.get(printing).get_device_graph().get_devices().size());
out.println(pool.get(printing).get_device_graph().getDeviceConnections().size());
SimulationSpecies s = pool.get(printing);
List<Device> devices = new ArrayList<Device>(s.get_device_graph().get_devices());
for (int j = 0; j < devices.size(); j++) {
out.println(devices.get(j).get_name());
out.println(devices.get(j).get_x());
out.println(devices.get(j).get_y());
}
}
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
List<SimulationSpecies> pareto_frontier = pareto(pool);
next_pool.addAll(pareto_frontier);
for (int k = 0; k < pareto_frontier.size(); k++) {
pool.remove(pareto_frontier.get(k));
}
System.out.println(Integer.toString(pool.size()));
for (int mutate = 0; mutate < pool.size(); mutate++) {
pool.get(mutate).mutate_benchmark();
}
next_pool.addAll(pool);
pool = next_pool;
next_pool = new ArrayList<SimulationSpecies>();
}
}
// ******************** DEVICE GRAPH SETUP ********************
private List<SimulationSpecies> setup_device_graph_medium_benchmark() throws IOException {
List<SimulationSpecies> pool = new ArrayList<SimulationSpecies>();
int number_rooms = this.room_graph.get_number_rooms();
List<Room> rooms = new ArrayList<Room>(this.room_graph.get_rooms());
for (int i = 0; i < this.pool_size; i++) {
System.out.println(Integer.toString(i));
RoomGraph room_graph_clone = null;
ObjectOutputStream output = null;
ObjectInputStream input = null;
try {
ByteArrayOutputStream byte_output = new ByteArrayOutputStream();
output = new ObjectOutputStream(byte_output);
output.writeObject(this.room_graph);
output.flush();
ByteArrayInputStream byte_input = new ByteArrayInputStream(byte_output.toByteArray());
input = new ObjectInputStream(byte_input);
room_graph_clone = (RoomGraph) input.readObject();
}
catch (Exception e) {
System.out.println("Exception in Cloning: " + e);
}
finally {
output.close();
input.close();
}
SimulationSpecies species = new SimulationSpecies(room_graph_clone);
DeviceGraph dg = new DeviceGraph();
dg.set_room_graph(room_graph_clone);
System.out.println(room_graph_clone.get_rooms().size());
List<Device> devices = new ArrayList<Device>();
int thermostat_room = random.nextInt(number_rooms);
Device therm = null;
for (int room_count = 0; room_count < number_rooms; room_count++) {
boolean heater_incl = random.nextBoolean();
if (thermostat_room == room_count) {
Device d = new Device();
d.setSensor(new SensorTemp());;
d.setDecider(new DeciderHeaterBinary());
System.out.println(Double.toString(rooms.get(room_count).center_x()));
System.out.println(Double.toString(rooms.get(room_count).center_y()));
d.set_x(rooms.get(room_count).center_x());
d.set_y(rooms.get(room_count).center_y());
dg.insert_device(d);
therm = d;
}
if (heater_incl) {
Device d = new Device();
d.setEffector(new EffectorHeater());
System.out.println(Double.toString(rooms.get(room_count).center_x()));
System.out.println(Double.toString(rooms.get(room_count).center_y()));
d.set_x(rooms.get(room_count).center_x());
d.set_y(rooms.get(room_count).center_y());
dg.insert_device(d);
devices.add(d);
}
}
for (int j = 0; j < devices.size(); j++) {
Device d1 = therm;
Device d2 = devices.get(j);
dg.insertDeviceConnection(d1, d2);
}
species.set_device_graph(dg);
species.reset();
species.get_device_graph().set_room_graph(species.get_room_graph());
species.get_room_graph().set_device_graph(species.get_device_graph());
pool.add(species);
}
return pool;
}
/**
* generates the initial population for the benchmarking simulation
* @param pool
* @param pool_size
* @throws IOException
*/
private void generate_initial_specimen_benchmark(List<SimulationSpecies> pool, int pool_size) throws IOException {
// if the object for storing lists is empty, do nothing
if (pool == null) {
System.out.println("generate_initial_specimen(): pool variable is null, instantiate object before passing into function");
return;
} else {
// empty the list for new specimen in the event something is in the object
pool.clear();
}
// settings for generation algorithm
// adjust maximums for the size of the layout
// studio apartment around 50 sq meter total
double total_area = 0;
for (Room r : this.room_graph.get_rooms()) {
total_area = total_area + r.get_area();
}
// maximum chunks during generation based on total area of the rooms
// maximum 2 chunks per large-ish room of 50 sq meter
// apartments / small homes around 50 - 100 sq meter
// medium homes around 100 - 250 sq meter
// large homes over 250 sq meter
double large_room_area = 50.0;
int max_chunks_per_area = 2;
int max_chunks = (int) Math.round(total_area / large_room_area) * max_chunks_per_area;
int max_devices = 10; // max number of devices per chunk
// generates new specimen
for (int specimen = 0; specimen < pool_size; specimen++) {
System.out.print("Generating specimen ");
System.out.println(Integer.toString(specimen));
ObjectOutputStream output = null;
ObjectInputStream input = null;
RoomGraph room_graph_clone = null;
try {
ByteArrayOutputStream byte_output = new ByteArrayOutputStream();
output = new ObjectOutputStream(byte_output);
output.writeObject(this.room_graph);
output.flush();
ByteArrayInputStream byte_input = new ByteArrayInputStream(byte_output.toByteArray());
input = new ObjectInputStream(byte_input);
room_graph_clone = (RoomGraph) input.readObject();
}
catch (Exception e) {
System.out.println("Exception in Cloning: " + e);
}
finally {
output.close();
input.close();
}
SimulationSpecies species = new SimulationSpecies(room_graph_clone);
// generates a random number of device species to add into the system
int chunk_count = this.random.nextInt(max_chunks) + 1;
for (int chunk = 0; chunk < chunk_count; chunk++) {
DeviceSpecies ds = new DeviceSpecies();
// generates a random number of devices to add into the system
int device_count = this.random.nextInt(max_devices) + 1;
// generates a random number of devices
for (int devices = 0; devices < device_count; devices++) {
// number of choices
int choices = 2;
int device = this.random.nextInt(choices + 1);
Device d = new Device();
switch (device) {
case 0:
Sensor sensor = new SensorTemp();
sensor.randomize();
d.setSensor(sensor);
break;
case 1:
Decider decider = new DeciderHeaterBinary();
decider.randomize();
d.setDecider(decider);
break;
case 2:
Effector effector = new EffectorHeater();
effector.randomize();
d.setEffector(effector);
break;
default:
return;
}
double x = this.random.nextDouble() * 15 + 5; // TODO fix so its based on placement in room, not just absolute room size
double y = this.random.nextDouble() * 15 + 5;
d.set_x(x);
d.set_y(y);
d.set_room_graph(room_graph_clone);
ds.add_device(d);
}
List<Device> all_devices = ds.get_devices();
for (Device d1 : all_devices) {
for (Device d2 : all_devices) {
if (d1 != d2 && this.random.nextDouble() > 0.5) {
DeviceConnection dc = new DeviceConnection(d1, d2);
ds.add_device_connection(dc);
}
}
}
if (ds.get_devices().size() != 0) {
species.add_device_species(ds);
}
}
pool.add(species);
}
}
/**
* generates new specimen using random placement of different objects and systems
* places
*
* @param pool
* object to add specimen to
* @param pool_size
* number of specimen to generate
* @throws IOException
*/
public void generate_initial_specimen(List<SimulationSpecies> pool, int pool_size) throws IOException {
// if the object is empty, do nothing
if (pool == null) {
System.out.println("generate_initial_specimen(): pool variable is null, instantiate object before passing into function");
return;
} else {
// empty the list for new specimen in the event something is in the object
pool.clear();
}
// settings for generation algorithm
// adjust maximums for the size of the layout
// studio apartment around 50 sq meter total
double total_area = 0;
for (Room r : this.room_graph.get_rooms()) {
total_area = total_area + r.get_area();
}
// maximum chunks during generation based on total area of the rooms
// maximum 2 chunks per large-ish room of 50 sq meter
// apartments / small homes around 50 - 100 sq meter
// medium homes around 100 - 250 sq meter
// large homes over 250 sq meter
double large_room_area = 50.0;
int max_chunks_per_area = 2;
int max_chunks = (int) Math.round(total_area / large_room_area) * max_chunks_per_area;
int max_devices = 4; // max number of devices per chunk
// generates new specimen
for (int specimen = 0; specimen < pool_size; specimen++) {
System.out.print("Generating specimen ");
System.out.println(Integer.toString(specimen));
ObjectOutputStream output = null;
ObjectInputStream input = null;
RoomGraph room_graph_clone = null;
try {
ByteArrayOutputStream byte_output = new ByteArrayOutputStream();
output = new ObjectOutputStream(byte_output);
output.writeObject(this.room_graph);
output.flush();
ByteArrayInputStream byte_input = new ByteArrayInputStream(byte_output.toByteArray());
input = new ObjectInputStream(byte_input);
room_graph_clone = (RoomGraph) input.readObject();
}
catch (Exception e) {
System.out.println("Exception in Cloning: " + e);
}
finally {
output.close();
input.close();
}
SimulationSpecies species = new SimulationSpecies(room_graph_clone);
// generates a random number of device species to add into the system
int chunk_count = this.random.nextInt(max_chunks) + 1;
for (int chunk = 0; chunk < chunk_count; chunk++) {
DeviceSpecies ds = new DeviceSpecies();
// generates a random number of devices to add into the system
int device_count = this.random.nextInt(max_devices) + 1;
// generates a random number of devices
for (int devices = 0; devices < device_count; devices++) {
// number of choices
int choices = 2;
int device = this.random.nextInt(choices + 1);
Device d = new Device();
switch (device) {
case 0:
Sensor sensor = new SensorTemp();
sensor.randomize();
d.setSensor(sensor);
break;
case 1:
Decider decider = new DeciderHeaterBinary();
decider.randomize();
d.setDecider(decider);
break;
case 2:
Effector effector = new EffectorHeater();
effector.randomize();
d.setEffector(effector);
break;
default:
return;
}
double x = this.random.nextDouble() * 13 + 30; // TODO fix so its based on placement in room, not just absolute room size
double y = this.random.nextDouble() * 8 + 30;
d.set_x(x);
d.set_y(y);
d.set_room_graph(room_graph_clone);
ds.add_device(d);
}
List<Device> all_devices = ds.get_devices();
for (Device d1 : all_devices) {
for (Device d2 : all_devices) {
if (d1 != d2 && this.random.nextDouble() > 0.5) {
DeviceConnection dc = new DeviceConnection(d1, d2);
ds.add_device_connection(dc);
}
}
}
if (ds.get_devices().size() != 0) {
species.add_device_species(ds);
}
}
pool.add(species);
}
}
List<SimulationSpecies> pareto(List<SimulationSpecies> specimen) {
List<SimulationSpecies> frontier = new ArrayList<SimulationSpecies>();
specimen.sort(new SimulationSpeciesComparator());
List<Integer> frontier_int = new ArrayList<Integer>();
frontier_int.add(0);
for (int current = 0; current < specimen.size(); current++) {
double discomfort = specimen.get(current).get_comfort();
for (int check = (current + 1); check < specimen.size(); check++){
double discomfort_2 = specimen.get(check).get_comfort();
if (discomfort_2 < discomfort) {
frontier_int.add(check);
current = check;
}
}
}
Collections.reverse(frontier_int);
for (int remove = 0; remove < frontier_int.size(); remove++) {
if (specimen.size() > 0) {
frontier.add(specimen.get(frontier_int.get(remove)));
specimen.remove(frontier_int.get(remove));
}
}
return frontier;
}
// ****************************** SIMULATION FUNCTIONS ******************************
/**
* debug_run()
*
* will become the run function once the code is debugged;
* runs the simulation
*/
public void debug_run() {
System.out.println("Beginning Debug Run");
System.out.println("IoT Simulation");
System.out.println("v0.0.2");
System.out.println("");
System.out.println("IoT Simulation - Initialization");
List<SimulationSpecies> current_pool = new ArrayList<SimulationSpecies>();
List<SimulationSpecies> next_pool = new ArrayList<SimulationSpecies>();
try {
debug_generate_population(current_pool);
} catch (IOException e) {
e.printStackTrace();
}
for (int iteration = 0; iteration < 1; iteration++) {
for (SimulationSpecies current : current_pool) {
for (int time = 0; (time * this.step_duration) < this.iteration_duration; time++) {
current.step(this.step_duration);
// try(FileWriter fw = new FileWriter("log_debug.txt", true);
// BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter out = new PrintWriter(bw))
// {
// out.print("Time: ");
// out.println(time * step_duration);
// RoomGraph rg = current.get_room_graph();
// for (Room r : rg.get_rooms()) {
// out.println(r.get_status());
// }
// } catch (IOException e) {
// //exception handling left as an exercise for the reader
// }
}
System.out.println("Iteration");
System.out.println(current.get_comfort());
System.out.println(current.get_energy_usage());
System.out.println(current.get_cost());
for (Room r : current.get_room_graph().get_rooms()) {
System.out.println(r.get_status());
System.out.println(r.get_x());
System.out.println(r.get_x() + r.get_length());
System.out.println(r.get_y() + r.get_width());
System.out.println(r.get_discomfort());
}
for (Device d : current.get_device_graph().get_devices()) {
System.out.println(d.get_status());
System.out.println(d.get_x());
System.out.println(d.get_y());
}
for (int blank_space = 0; blank_space < 3; blank_space++) {
System.out.println("");
}
}
System.out.println("Resetting Specimen");
for (SimulationSpecies current2 : current_pool) {
System.out.println("reset");
current2.reset();
System.out.println("adding");
next_pool.add(current2);
}
}
System.out.println("Transferring Generations");
current_pool = next_pool;
next_pool = new ArrayList<SimulationSpecies>();
System.out.println("Next Generation");
}
/**
* creates a deep clone of the room graph
* @return
* @throws IOException
*/
private RoomGraph clone_room_graph() throws IOException {
ObjectOutputStream output = null;
ObjectInputStream input = null;
RoomGraph room_graph_clone = null;
try {
ByteArrayOutputStream byte_output = new ByteArrayOutputStream();
output = new ObjectOutputStream(byte_output);
output.writeObject(this.room_graph);
output.flush();
ByteArrayInputStream byte_input = new ByteArrayInputStream(byte_output.toByteArray());
input = new ObjectInputStream(byte_input);
room_graph_clone = (RoomGraph) input.readObject();
}
catch (Exception e) {
System.out.println("Exception in Cloning: " + e);
}
finally {
output.close();
input.close();
}
return room_graph_clone;
}
public void debug_generate_population(List<SimulationSpecies> pool) throws IOException {
this.setup_room_graph_medium();
int pool_size = 1;
for (int species_count = 0; species_count < pool_size; species_count++) {
RoomGraph room_graph = clone_room_graph();
SimulationSpecies species = new SimulationSpecies(room_graph);
DeviceGraph dg = new DeviceGraph();
species.set_device_graph(dg);
dg.set_room_graph(room_graph);
Device d1 = new Device();
Device d2 = new Device();
Device d3 = new Device();
Sensor s1 = new SensorTemp();
s1.randomize();
d1.setSensor(s1);
d1.set_name("Sensor");
Effector e1 = new EffectorHeater();
e1.randomize();
d2.setEffector(e1);
d2.set_name("Heater");
Decider de1 = new DeciderHeaterBinary();
de1.randomize();
d3.setDecider(de1);
d3.set_name("Decider");
d1.set_x(this.random.nextDouble() * 13 + 30);
d1.set_y(this.random.nextDouble() * 8 + 30);
d2.set_x(this.random.nextDouble() * 13 + 30);
d2.set_y(this.random.nextDouble() * 8 + 30);
d3.set_x(this.random.nextDouble() * 13 + 30);
d3.set_y(this.random.nextDouble() * 8 + 30);
dg.insert_device(d1);
dg.insert_device(d2);
dg.insert_device(d3);
dg.insertDeviceConnection(d1, d3);
dg.insertDeviceConnection(d2, d3);
pool.add(species);
}
}
/**
* run the simulation using the settings that are in the configuration file
*
*
* default settings used
*
* @param settings
* @throws IOException
*/
public void run() throws IOException {
System.out.println("IoT Simulation");
System.out.println("v0.0.1");
System.out.println("");
System.out.println("IoT Simulation - Initialization");
// stores the current pool of specimen
List<SimulationSpecies> current_pool = new ArrayList<SimulationSpecies>();
// stores the next generation pool of specimen
List<SimulationSpecies> next_generation = new ArrayList<SimulationSpecies>();
// category sizes, ratios relative to each other
double elitism = this.ep;
double mutation = this.mp;
double combination = this.cp;
// scales the values to get the size of each category
double total_ratio = elitism + mutation + combination;
int elitism_count = (int) Math.round(this.pool_size * (elitism / total_ratio));
int mutation_count = (int) Math.round(this.pool_size * (mutation / total_ratio));
int combination_count = (int) Math.round(this.pool_size * (combination / total_ratio));
// elitism void in the search for pareto frontier
setup_room_graph_medium();
// generates initial specimen population
System.out.println("Generating " + Integer.toString(this.pool_size) + " specimen...");
this.generate_initial_specimen(current_pool, this.pool_size);
System.out.println("done.");
// run cycles of the genetic algorithm
for (int i = 0; i < this.iterations; i++) {
System.out.println("Running Iteration " + Integer.toString(i + 1));
for (int sim = 0; sim < current_pool.size(); sim++) {
System.out.println("Species" + Integer.toString(sim + 1));
SimulationSpecies current = current_pool.get(sim);
current.reset();
current.get_device_graph().set_room_graph(current.get_room_graph());
current.get_room_graph().set_device_graph(current.get_device_graph());
for (int time = 0; (time * this.step_duration) < this.iteration_duration; time++) {
current.step(this.step_duration);
}
}
for (SimulationSpecies s : current_pool) {
s.get_energy_usage();
}
List<SimulationSpecies> specimen = new ArrayList<SimulationSpecies>(current_pool);
specimen.sort(new SimulationSpeciesComparator());
next_generation = new ArrayList<SimulationSpecies>();
// calculates the sizes of the groups
int elite_quantity = (int) Math.round(current_pool.size() * elitism);
int mutation_quantity = (int) Math.round(current_pool.size() * mutation);
int combination_quantity = (int) Math.round(current_pool.size() * combination);
// ensures size constraint on the groups
while ((elite_quantity + mutation_quantity + combination_quantity) > specimen.size()) {
if (combination_quantity > 0) {
combination_quantity -= 1;
} else if (mutation_quantity > 0) {
mutation_quantity -= 1;
} else if (elite_quantity > 0) {
elite_quantity -= 1;
}
}
for (int check_info = 0; check_info < specimen.size(); check_info++) {
SimulationSpecies energy_check = specimen.get(check_info);
System.out.println("energy");
System.out.println(energy_check.get_energy_usage());
}
List<SimulationSpecies> pareto_frontier = pareto(specimen);
next_generation.addAll(pareto_frontier);
for (SimulationSpecies s : pareto_frontier) {
specimen.remove(s);
}
Collections.shuffle(specimen);
int group = specimen.size() / 20;
int other_group = specimen.size() - group;
for (int k = 0; k < group; k++) {
SimulationSpecies mutate = specimen.remove(0);
mutate.mutate();
next_generation.add(mutate);
}
if (other_group % 2 == 1) {
SimulationSpecies combine = specimen.remove(0);
next_generation.add(combine);
other_group = other_group - 1;
}
for (int l = 0; l < other_group / 2; l++) {
SimulationSpecies c1 = specimen.remove(0);
SimulationSpecies c2 = specimen.remove(0);
c1.combine(c2);
c2.combine(c1);
next_generation.add(c1);
next_generation.add(c2);
}
current_pool = next_generation;
next_generation = new ArrayList<SimulationSpecies>();
try(FileWriter fw = new FileWriter("log_medium.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
for (int printing = 0; printing < current_pool.size(); printing++) {
out.print("Iteration: ");
out.println(Integer.toString(i));
out.println(Integer.toString(printing));
out.println(current_pool.get(printing).get_comfort());
out.println(current_pool.get(printing).get_energy_usage());
out.println(current_pool.get(printing).get_device_graph().get_devices().size());
out.println(current_pool.get(printing).get_device_graph().getDeviceConnections().size());
SimulationSpecies s = current_pool.get(printing);
List<Device> devices = new ArrayList<Device>(s.get_device_graph().get_devices());
for (int j = 0; j < devices.size(); j++) {
out.println(devices.get(j).get_name());
out.println(devices.get(j).get_x());
out.println(devices.get(j).get_y());
}
out.print("Device Connections: ");
out.println(current_pool.get(printing).get_device_graph().getDeviceConnections().size());
}
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
// prints information about best performing simulation
List<SimulationSpecies> rank = new ArrayList<SimulationSpecies>(current_pool);
rank.sort(new SimulationSpeciesComparator());
return;
}
public void run_once() {
SimulationSpecies single = new SimulationSpecies(this.room_graph);
DeviceGraph dg = new DeviceGraph();
// // LARGE
// dg.set_room_graph(this.room_graph);
//
// Device d1 = new Device();
// d1.setSensor(new SensorTemp());
// d1.set_x(30);
// d1.set_y(10);
// dg.insert_device(d1);
//
// Device d2 = new Device();
// d2.setEffector(new EffectorHeater());
// d2.set_x(32);
// d2.set_y(12);
// dg.insert_device(d2);
//
// Device d3 = new Device();
// d3.setDecider(new DeciderHeaterBinary());
// d3.set_x(31);
// d3.set_y(11);
// dg.insert_device(d3);
//
//
// Device d4 = new Device();
// d4.setEffector(new EffectorHeater());
// d4.set_x(6);
// d4.set_y(6);
// dg.insert_device(d4);
//
// Device d5 = new Device();
// d5.setEffector(new EffectorHeater());
// d5.set_x(6);
// d5.set_y(16);
// dg.insert_device(d5);
//
// Device d6 = new Device();
// d6.setEffector(new EffectorHeater());
// d6.set_x(6);
// d6.set_y(16);
// dg.insert_device(d6);
//
// Device d7 = new Device();
// d6.setEffector(new EffectorHeater());
// d6.set_x(22);
// d6.set_y(6);
// dg.insert_device(d7);
//
// Device d8 = new Device();
// d6.setEffector(new EffectorHeater());
// d6.set_x(22);
// d6.set_y(16);
// dg.insert_device(d8);
//
// Device d9 = new Device();
// d6.setEffector(new EffectorHeater());
// d6.set_x(22);
// d6.set_y(26);
// dg.insert_device(d9);
//
// dg.insertDeviceConnection(d1, d3);
// dg.insertDeviceConnection(d2, d3);
// dg.insertDeviceConnection(d4, d3);
// dg.insertDeviceConnection(d5, d3);
// dg.insertDeviceConnection(d6, d3);
//
// MEDIUM
// dg.set_room_graph(this.room_graph);
// Device d1 = new Device();
// d1.setSensor(new SensorTemp());
// d1.set_x(15);
// d1.set_y(15);
// dg.insert_device(d1);
//
// Device d2 = new Device();
// d2.setEffector(new EffectorHeater());
// d2.set_x(17);
// d2.set_y(17);
// d2.set_room_graph(this.room_graph);
// dg.insert_device(d2);
//
// Device d3 = new Device();
// d3.setDecider(new DeciderHeaterBinary());
// d3.set_x(16);
// d3.set_y(16);
// dg.insert_device(d3);
//
// Device d4 = new Device();
// d4.setEffector(new EffectorHeater());
// d4.set_x(6);
// d4.set_y(6);
// dg.insert_device(d4);
//
// Device d5 = new Device();
// d5.setEffector(new EffectorHeater());
// d5.set_x(6);
// d5.set_y(15);
// dg.insert_device(d5);
//
// Device d6 = new Device();
// d6.setEffector(new EffectorHeater());
// d6.set_x(15);
// d6.set_y(6);
// d5.set_room_graph(this.room_graph);
// dg.insert_device(d6);
//
// dg.insertDeviceConnection(d1, d3);
// dg.insertDeviceConnection(d2, d3);
// dg.insertDeviceConnection(d4, d3);
// dg.insertDeviceConnection(d5, d3);
// dg.insertDeviceConnection(d6, d3);
// SMALL
// dg.set_room_graph(this.room_graph);
// Device d1 = new Device();
// d1.setSensor(new SensorTemp());
// d1.set_x(10);
// d1.set_y(10);
// dg.insert_device(d1);
// Device d2 = new Device();
// d2.setEffector(new EffectorHeater());
// d2.set_x(11);
// d2.set_y(11);
// d2.set_room_graph(this.room_graph);
// dg.insert_device(d2);
// Device d3 = new Device();
// d3.setDecider(new DeciderHeaterBinary());
// d3.set_x(12);
// d3.set_y(12);
// d3.set_room_graph(this.room_graph);
// dg.insert_device(d3);
// dg.insertDeviceConnection(d1, d3);
// dg.insertDeviceConnection(d2, d3);
single.set_device_graph(dg);
single.reset();
single.get_device_graph().set_room_graph(single.get_room_graph());
single.get_room_graph().set_device_graph(single.get_device_graph());
for (int time = 0; (time * this.step_duration) < this.iteration_duration; time++) {
single.step(this.step_duration);
}
System.out.println("comfort");
System.out.println(single.get_comfort());
System.out.println("energy");
System.out.println((single.get_energy_usage() / 3600000) * (30 * .12));
System.out.println("cost");
System.out.println(single.get_cost());
}
// /**
// *
// * runs the simulation without using the GUI
// * performs the genetic algorithm for the specified duration and iterations
// * presents the final data
// *
// * @param ga_iter
// * number of iterations to perform
// * @param pool_size
// * size of the pool of objects for each round
// * @param elitism
// * percentage selected for elitism
// * @param mutation
// * percentage selected for mutation
// * @param combination
// * percentage selected for combination
// * @throws IOException
// */
// public void run(int ga_iter, int pool_size, double elitism, double mutation, double combination) throws IOException {
//
// // stores the current generation of specimen
// List<SimulationSpecies> current_pool = new ArrayList<SimulationSpecies>();
// // stores the next generation of specimen
// List<SimulationSpecies> next_generation = new ArrayList<SimulationSpecies>();
// this.generate_initial_specimen(current_pool, pool_size);
//
// // scales the percentages so they equal 1 if they don't equal 1
// if (elitism + mutation + combination != 1) {
// double total = elitism + mutation + combination;
// elitism /= total;
// mutation /= total;
// combination /= total;
// }
//
// // run cycles of the genetic algorithm
// for (int i = 0; i < ga_iter; i++) {
//
// for (int sim = 0; sim < current_pool.size(); sim++) {
// SimulationSpecies current = current_pool.get(sim);
// current.reset();
// current.get_device_graph().set_room_graph(current.get_room_graph());
// current.get_room_graph().set_device_graph(current.get_device_graph());
// for (int time = 0; time < 3000000; time++) {
// current.step(step_duration);
// System.out.println(current.get_energy_usage());
// }
// }
//
// List<SimulationSpecies> specimen = new ArrayList<SimulationSpecies>(current_pool);
// specimen.sort(new SimulationSpeciesComparator());
//
// next_generation = new ArrayList<SimulationSpecies>();
//
// // calculates the sizes of the groups
// int elite_quantity = (int) Math.round(current_pool.size() * elitism);
// int mutation_quantity = (int) Math.round(current_pool.size() * mutation);
// int combination_quantity = (int) Math.round(current_pool.size() * combination);
//
// // ensures size constraint on the groups
// while ((elite_quantity + mutation_quantity + combination_quantity) > specimen.size()) {
// if (combination_quantity > 0) {
// combination_quantity -= 1;
// } else if (mutation_quantity > 0) {
// mutation_quantity -= 1;
// } else if (elite_quantity > 0) {
// elite_quantity -= 1;
// }
// }
//
//
// for (int j = 0; j < elite_quantity; j++) {
// next_generation.add(specimen.remove(0));
// }
//
// // shuffles the specimen before selecting which get mutated and combined
// Collections.shuffle(specimen);
//
// // selects the quantity desired for mutation
// for (int k = 0; k < mutation_quantity; k++) {
// SimulationSpecies mutate = specimen.remove(0);
// mutate.mutate();
// next_generation.add(mutate);
// }
//
// // allows a single specimen to enter next generation without combination
// // if the amount is odd
// if (combination_quantity % 2 == 1) {
// SimulationSpecies combine = specimen.remove(0);
// next_generation.add(combine);
// }
// // combines pairs of the
// for (int l = 0; l < combination_quantity / 2; l++) {
// SimulationSpecies c1 = specimen.remove(0);
// SimulationSpecies c2 = specimen.remove(0);
// // SimulationSpecies new_c1 = c1.combine(c2);
// // SimulationSpecies new_c2 = c2.combine(c1);
// // next_generation.add(new_c1);
// // next_generation.add(new_c2);
// }
//
// current_pool = next_generation;
// next_generation = new ArrayList<SimulationSpecies>();
// }
//
// // prints information about best performing simulation
// List<SimulationSpecies> rank = new ArrayList<SimulationSpecies>(current_pool);
// rank.sort(new SimulationSpeciesComparator());
// }
// ********** DEVICE GRAPH SETUP ***********
/**
* Sets up DeviceGraph to initial state;
*/
private void setupDeviceGraph() {
this.create_species();
Random r = new Random();
List<SimulationSpecies> ss = new ArrayList<SimulationSpecies>();
int pool_size = 5;
for (int i = 0; i < pool_size; i++) {
SimulationSpecies s = new SimulationSpecies(this.room_graph);
long count = Math.round(Math.abs(r.nextGaussian()) * 3);
if (count > this.device_segments.size()) {
count = this.device_segments.size();
}
for (int j = 0; j < count; j++) {
int select = r.nextInt(this.device_segments.size());
s.add_device_species(this.device_segments.get(select));
}
ss.add(s);
}
this.device_graph = ss.get(r.nextInt(ss.size())).get_device_graph();
}
/**
* creates a large group of connected device samples
*/
private void create_species() {
DeviceSpecies ds1 = new DeviceSpecies();
this.device_graph.set_room_graph(this.room_graph);
// creates a heater
Device device1 = new Device("Heater1", 17, 12);
this.device_graph.insert_device(device1);
EffectorHeater heater = new EffectorHeater();
SensorTemp temp = new SensorTemp();
DeciderHeaterBinary d = new DeciderHeaterBinary();
device1.setEffector(heater);
device1.setSensor(temp);
device1.setDecider(d);
Device device2 = new Device("Heater2", 17, 16);
this.device_graph.insert_device(device2);
EffectorHeater heater2 = new EffectorHeater();
SensorTemp temp2 = new SensorTemp();
DeciderHeaterBinary d2 = new DeciderHeaterBinary();
device2.setEffector(heater2);
device2.setSensor(temp2);
device2.setDecider(d2);
Device device3 = new Device("Temp Sensor1", 14, 11);
this.device_graph.insert_device(device3);
SensorTemp temp3 = new SensorTemp();
device3.setSensor(temp3);
Device device4 = new Device("Temp Sensor2", 11, 18);
this.device_graph.insert_device(device4);
SensorTemp temp4 = new SensorTemp();
device4.setSensor(temp4);
ds1.add_device(device1);
ds1.add_device(device2);
ds1.add_device(device3);
ds1.add_device(device4);
ds1.add_device_connection(device1, device2);
ds1.add_device_connection(device1, device3);
ds1.add_device_connection(device2, device4);
DeviceSpecies ds2 = new DeviceSpecies();
device1 = new Device("Air Conditioner", 17, 12);
EffectorAirConditioner ac = new EffectorAirConditioner();
temp = new SensorTemp();
DeciderACBinary d11 = new DeciderACBinary();
device1.setEffector(ac);
device1.setSensor(temp);
device1.setDecider(d11);
device2 = new Device("Air Conditioner", 17, 16);
EffectorAirConditioner ac2 = new EffectorAirConditioner();
temp2 = new SensorTemp();
DeciderACBinary d12 = new DeciderACBinary();
device2.setEffector(ac2);
device2.setSensor(temp2);
device2.setDecider(d12);
device3 = new Device("Temp Sensor1", 14, 11);
temp3 = new SensorTemp();
device3.setSensor(temp3);
device4 = new Device("Temp Sensor2", 11, 18);
temp4 = new SensorTemp();
device4.setSensor(temp4);
ds2.add_device(device1);
ds2.add_device(device2);
ds2.add_device(device3);
ds2.add_device(device4);
ds2.add_device_connection(device1, device2);
ds2.add_device_connection(device1, device3);
ds2.add_device_connection(device2, device4);
DeviceSpecies ds3 = new DeviceSpecies();
// creates a heater
device1 = new Device("Heater1", 11, 18);
this.device_graph.insert_device(device1);
heater = new EffectorHeater();
temp = new SensorTemp();
d = new DeciderHeaterBinary();
device1.setEffector(heater);
device1.setSensor(temp);
device1.setDecider(d);
device2 = new Device("Heater2", 16, 18);
this.device_graph.insert_device(device2);
heater2 = new EffectorHeater();
temp2 = new SensorTemp();
d2 = new DeciderHeaterBinary();
device2.setEffector(heater2);
device2.setSensor(temp2);
device2.setDecider(d2);
device3 = new Device("Temp Sensor1", 14, 11);
this.device_graph.insert_device(device3);
temp3 = new SensorTemp();
device3.setSensor(temp3);
device4 = new Device("Temp Sensor2", 11, 18);
this.device_graph.insert_device(device4);
temp4 = new SensorTemp();
device4.setSensor(temp4);
ds3.add_device(device1);
ds3.add_device(device2);
ds3.add_device(device3);
ds3.add_device(device4);
ds3.add_device_connection(device1, device2);
ds3.add_device_connection(device1, device3);
ds3.add_device_connection(device2, device4);
this.device_segments.add(ds1);
this.device_segments.add(ds2);
this.device_segments.add(ds3);
}
// ********** GETTER/SETTER FUNCTIONS **********
/**
* returns the room graph
*
* @return the RoomGraph
*/
public RoomGraph getRoomGraph() {
return this.room_graph;
}
/**
* returns the device graph
*
* @return the DeviceGraph
*/
public DeviceGraph getDeviceGraph() {
return this.device_graph;
}
// ********** SIMULATION FUNCTIONS **********
/**
* performs a single step of the simulation using a specific time duration for a step
* objects in the simulation maintain their own internal counter for total time elapsed
*/
public void step(double duration) {
// increments the room graph representation
this.room_graph.step(duration);
// increments the device graph representation
this.device_graph.step(duration);
this.time += duration;
}
// ******************** ANALYSIS FUNCTIONS ********************
/**
* returns the current time of the simulation in [s]
*
* @return time current time of the simulation in [s]
*/
public double get_time() {
return this.time;
}
/**
* get results of the simulation as text
*
* @return the string result of the simulation
*/
public String get_results() {
StringBuilder results = new StringBuilder();
// get all of the data from the device graph
results.append(this.device_graph.get_status());
// get all of the data from the room graph
results.append(this.room_graph.get_status());
return results.toString();
}
} |
package classes;
import interfaces.Invoker;
/**
* @author dylan
*
*/
public class MySQLInvoker implements Invoker {
/*
* (non-Javadoc)
*
* @see interfaces.Invoker#createTable()
*/
@Override
public void createTable() {
System.out.println("creating MySQL table");
}
/*
* (non-Javadoc)
*
* @see interfaces.Invoker#deleteTable()
*/
@Override
public void deleteTable() {
System.out.println("deleting MySQL table");
}
}
|
package com.example.reggiewashington.c196;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CourseDetailActivity extends AppCompatActivity {
int selectedCourseId;
int MY_PERMISSION_REQUEST_SEND_SMS = 1;
String selectedCourse, mNote, selectedCourseTitle, selectedCourseStart, selectedCourseEnd;
TextView CourseTitle, CourseStart, CourseAnticipatedEnd, CourseStatus, CourseMentor, CourseMentorNumber, CourseMentorEmail;
Courses ca;
DatabaseHelper myDb;
EditText mNotes, mNumber;
Button share;
View mView;
private ArrayList<Assessments> assessmentsList = new ArrayList<>();
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.course_detail);
myDb = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.course_assessments);
Intent receivedIntent = getIntent();
selectedCourseId = receivedIntent.getIntExtra("Id", -1);
selectedCourse = receivedIntent.getStringExtra("Course");
CourseTitle = (TextView) findViewById(R.id.c_title);
CourseStart = (TextView) findViewById(R.id.c_start);
CourseAnticipatedEnd = (TextView) findViewById(R.id.c_end);
CourseStatus = (TextView) findViewById(R.id.c_status);
CourseMentor = (TextView) findViewById(R.id.mentor_name);
CourseMentorNumber = (TextView) findViewById(R.id.mentor_number);
CourseMentorEmail = (TextView) findViewById(R.id.mentor_email);
//set data
CourseTitle.setText(selectedCourse);
populateView();
CustomAdapter adapter = new CustomAdapter(this, R.layout.course_assessments, assessmentsList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.course_detail_menu, menu);
return true;
}
public void populateView() {
Cursor data = myDb.getSingleCourse(selectedCourseId);
while (data.moveToNext()) {
selectedCourseTitle = data.getString(1);
selectedCourseStart = data.getString(2);
selectedCourseEnd = data.getString(3);
String status = data.getString(4);
String mentor = data.getString(5);
String mentorNumber = data.getString(6);
String mentorEmail = data.getString(7);
mNote = data.getString(8);
CourseStart.setText("Start Date: " + selectedCourseStart);
CourseAnticipatedEnd.setText("Anticipated End Date: " + selectedCourseEnd);
CourseStatus.setText(status);
CourseMentor.setText(mentor);
CourseMentorNumber.setText(mentorNumber);
CourseMentorEmail.setText(mentorEmail);
}
Cursor data2 = myDb.getCourseAssessmentData(selectedCourseId);
while (data2.moveToNext()) {
String assessmentTitle = data2.getString(3);
assessmentsList.add(new Assessments(assessmentTitle));
}
}
public boolean onOptionsItemSelected(MenuItem item) {
String courseTitle = CourseTitle.getText().toString();
String courseStart = CourseStart.getText().toString();
String courseAntiEnd = CourseAnticipatedEnd.getText().toString();
String courseStatus = CourseStatus.getText().toString();
String courseMentor = CourseMentor.getText().toString();
String courseMNumber = CourseMentorNumber.getText().toString();
String courseMEmail = CourseMentorEmail.getText().toString();
if (item.getItemId() == R.id.course_edit) {
Intent intent = new Intent(CourseDetailActivity.this, EditCourse.class);
intent.putExtra("Id", selectedCourseId);
intent.putExtra("Title", selectedCourseTitle);
intent.putExtra("Start", selectedCourseStart);
intent.putExtra("End", selectedCourseEnd);
intent.putExtra("Status", courseStatus);
intent.putExtra("Mentor", courseMentor);
intent.putExtra("Number", courseMNumber);
intent.putExtra("Email", courseMEmail);
startActivity(intent);
}
if (item.getItemId() == R.id.course_notes) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(CourseDetailActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.notes, null);
TextView mTitle = (TextView) mView.findViewById(R.id.note_title);
mNotes = (EditText) mView.findViewById(R.id.notes);
mNumber = (EditText) mView.findViewById(R.id.phoneNumber);
share = (Button) mView.findViewById(R.id.notes_share_btn);
if(mNotes != null){
mNotes.setText(mNote);
}else {
mNotes.setText("");
}
Button mSave = (Button) mView.findViewById(R.id.notes_save_btn);
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
mSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = selectedCourseId;
final String note = mNotes.getText().toString();
addNotes(id, note);
// finish();
}
});
}
return super.onOptionsItemSelected(item);
}
public void handleShareSms(View view){
final String note = mNotes.getText().toString();
final String telNum = mNumber.getText().toString();
if(ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSION_REQUEST_SEND_SMS);
}else{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(telNum, null, note,null, null);
toastMessage("Message Sent!");
}
}
public class CustomAdapter extends BaseAdapter {
private Context context;
private int layout;
ArrayList<Assessments> courseAssessmentList;
public CustomAdapter(Context context, int layout, ArrayList<Assessments> courseAssessmentList) {
this.context = context;
this.layout = layout;
this.courseAssessmentList = courseAssessmentList;
}
@Override
public int getCount() {
return courseAssessmentList.size();
}
@Override
public Object getItem(int position) {
return courseAssessmentList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView assessmentTitle;
TextView assessmentGoal;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
View row = view;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder = new CustomAdapter.ViewHolder();
holder.assessmentTitle = (TextView) row.findViewById(R.id.assessment_title);
holder.assessmentGoal = (TextView) row.findViewById(R.id.assessment_goal_date);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Assessments assessments = courseAssessmentList.get(position);
holder.assessmentTitle.setText(assessments.getName());
holder.assessmentGoal.setText(assessments.getDate());
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor data = myDb.getCourseAssessmentData(selectedCourseId);
int assessmentId = -1;
String assessmentType = "";
String assessmentName = "";
String assessmentDate = "";
while(data.moveToNext()) {
assessmentId = data.getInt(2);
assessmentName = data.getString(3);
Intent intent = new Intent(CourseDetailActivity.this, AssessmentDetailActivity.class);
intent.putExtra("Id", assessmentId);
intent.putExtra("Name", assessmentName);
startActivity(intent);
}
}
});
return row;
}
}
public void addNotes(int id, String notes) {
final boolean insertData = myDb.addNotes(id, notes);
if (insertData == true) {
toastMessage("Notes inserted!");
} else {
toastMessage("Something went wrong!");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
|
package Problem_12886;
import java.io.IOException;
import java.util.Scanner;
public class Main {
static int a, b, c, d;
static boolean[][] isvisited;
public static void solve(int a, int b) {
if (isvisited[a][b])
return;
isvisited[a][b] = true;
int[] rock = { a, b, d - a - b };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (rock[i] < rock[j]) {
int[] temp = { a, b, d - a - b };
temp[i] += rock[i];
temp[j] -= rock[i];
solve(temp[0], temp[1]);
}
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = a + b + c;
isvisited = new boolean[d][d];
if (d % 3 != 0) {
System.out.println("0");
System.exit(0);
}
solve(a, b);
System.out.println(isvisited[d / 3][d / 3] == false ? "0" : "1");
}
}
|
package view;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import audio.AudioManager;
public class Credits {
private static JFrame mainFrame;
public static void run(Main previous) {
mainFrame = new JFrame("Credits");
mainFrame.setLayout(null);
mainFrame.setResizable(false);
try {
mainFrame.setIconImage(ImageUtils.loadImage("logo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mainFrame.setSize(600, 600);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
AudioManager.stop();
mainFrame.setVisible(false);
previous.resume();
}
});
JPanel contentPanel = new JPanel();
contentPanel.setBackground(Color.BLACK);
mainFrame.setContentPane(contentPanel);
try {
BufferedImage logo = (BufferedImage) ImageUtils.loadImage("logo.png");
JLabel logoLabel = new JLabel(new ImageIcon(logo));
contentPanel.add(logoLabel);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
BufferedImage credits = (BufferedImage) ImageUtils.loadImage("credits.png");
JLabel creditsLabel = new JLabel(new ImageIcon(credits));
contentPanel.add(creditsLabel);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
AudioManager.stop();
mainFrame.setVisible(true);
AudioManager.play("getschwifty");
}
}
|
package com.example.numberplaterecognition;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends AppCompatActivity {
TextView txt_firstname,txt_lastname,txt_mobile,txt_password,txt_confirmpassword;
EditText edit_firstname,edit_lastname,edit_mobile,edit_password,edit_confirmpassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
this.setTitle("Sign Up");
txt_firstname=findViewById(R.id.txt_firstname);
txt_lastname=findViewById(R.id.txt_lastname);
txt_mobile=findViewById(R.id.txt_mobile);
txt_password=findViewById(R.id.txt_password);
txt_confirmpassword=findViewById(R.id.txt_confirmpassword);
}
}
|
/*
* 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.core.env;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Composite {@link PropertySource} implementation that iterates over a set of
* {@link PropertySource} instances. Necessary in cases where multiple property sources
* share the same name, e.g. when multiple values are supplied to {@code @PropertySource}.
*
* <p>As of Spring 4.1.2, this class extends {@link EnumerablePropertySource} instead
* of plain {@link PropertySource}, exposing {@link #getPropertyNames()} based on the
* accumulated property names from all contained sources (as far as possible).
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Phillip Webb
* @since 3.1.1
*/
public class CompositePropertySource extends EnumerablePropertySource<Object> {
private final Set<PropertySource<?>> propertySources = new LinkedHashSet<>();
/**
* Create a new {@code CompositePropertySource}.
* @param name the name of the property source
*/
public CompositePropertySource(String name) {
super(name);
}
@Override
@Nullable
public Object getProperty(String name) {
for (PropertySource<?> propertySource : this.propertySources) {
Object candidate = propertySource.getProperty(name);
if (candidate != null) {
return candidate;
}
}
return null;
}
@Override
public boolean containsProperty(String name) {
for (PropertySource<?> propertySource : this.propertySources) {
if (propertySource.containsProperty(name)) {
return true;
}
}
return false;
}
@Override
public String[] getPropertyNames() {
List<String[]> namesList = new ArrayList<>(this.propertySources.size());
int total = 0;
for (PropertySource<?> propertySource : this.propertySources) {
if (!(propertySource instanceof EnumerablePropertySource<?> enumerablePropertySource)) {
throw new IllegalStateException(
"Failed to enumerate property names due to non-enumerable property source: " + propertySource);
}
String[] names = enumerablePropertySource.getPropertyNames();
namesList.add(names);
total += names.length;
}
Set<String> allNames = new LinkedHashSet<>(total);
namesList.forEach(names -> Collections.addAll(allNames, names));
return StringUtils.toStringArray(allNames);
}
/**
* Add the given {@link PropertySource} to the end of the chain.
* @param propertySource the PropertySource to add
*/
public void addPropertySource(PropertySource<?> propertySource) {
this.propertySources.add(propertySource);
}
/**
* Add the given {@link PropertySource} to the start of the chain.
* @param propertySource the PropertySource to add
* @since 4.1
*/
public void addFirstPropertySource(PropertySource<?> propertySource) {
List<PropertySource<?>> existing = new ArrayList<>(this.propertySources);
this.propertySources.clear();
this.propertySources.add(propertySource);
this.propertySources.addAll(existing);
}
/**
* Return all property sources that this composite source holds.
* @since 4.1.1
*/
public Collection<PropertySource<?>> getPropertySources() {
return this.propertySources;
}
@Override
public String toString() {
return getClass().getSimpleName() + " {name='" + this.name + "', propertySources=" + this.propertySources + "}";
}
}
|
package com.tibco.as.util.compare;
import com.tibco.as.space.DateTime;
import com.tibco.as.space.Tuple;
public class DateTimeComparator extends AbstractFieldComparator<DateTime> {
public DateTimeComparator(String fieldName) {
super(fieldName);
}
@Override
protected int compareFields(DateTime value1, DateTime value2) {
return value1.getTime().compareTo(value2.getTime());
}
@Override
protected DateTime getValue(Tuple tuple, String fieldName) {
return tuple.getDateTime(fieldName);
}
}
|
package be.mxs.common.util.io;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.Date;
import be.openclinic.archiving.DicomUtils;
import be.openclinic.system.SH;
import java.io.File;
import be.mxs.common.util.db.MedwanQuery;
import uk.org.primrose.vendor.standalone.PrimroseLoader;
public class CompressDicom
{
public static void main(final String[] args) {
try {
System.out.println("Database connection url: " + args[0]);
PrimroseLoader.load(args[0],true);
Connection conn=SH.getOpenClinicConnection();
System.out.println("Database connected");
final String SCANDIR_BASE = Connect.getConfigString(conn,"scanDirectoryMonitor_basePath", "/var/tomcat/webapps/openclinic/scan");
System.out.println("SCANDIR_BASE = " + SCANDIR_BASE);
final String SCANDIR_TO = Connect.getConfigString(conn,"scanDirectoryMonitor_dirTo", "to");
int totalfiles = 0,cycles=0;
conn.close();
while (true) {
int n = 0,totalbatch=0;
conn = SH.getOpenClinicConnection();
System.out.println(cycles+++" - Running query....");
PreparedStatement ps = conn.prepareStatement("select * from oc_pacs where oc_pacs_compresseddatetime is null limit 520");
ResultSet rs = ps.executeQuery();
System.out.println("Query executed");
while (rs.next() && n++ < 500) {
String studyuid = rs.getString("oc_pacs_studyuid");
String series = rs.getString("oc_pacs_series");
String sequence = rs.getString("oc_pacs_sequence");
String filename = String.valueOf(SCANDIR_BASE) + "/" + SCANDIR_TO + "/" + rs.getString("oc_pacs_filename");
File file = new File(filename);
if(new java.util.Date().getTime()-file.lastModified()<3600*1000) {
//File is too recent, skip it
continue;
}
totalbatch++;
long decompressedsize = 0L;
if (file.exists()) {
decompressedsize = file.length();
}
else {
System.out.println("File "+filename+" doesn't exist!");
}
if(decompressedsize<64000) {
System.out.println("File "+filename+" smaller than 64K. Not worth compressing...");
PreparedStatement ps2 = conn.prepareStatement("update oc_pacs set oc_pacs_compresseddatetime=? where oc_pacs_studyuid=? and oc_pacs_series=? and oc_pacs_sequence=?");
ps2.setTimestamp(1, new Timestamp(new Date().getTime()));
ps2.setString(2, studyuid);
ps2.setString(3, series);
ps2.setString(4, sequence);
ps2.execute();
ps2.close();
continue;
}
try {
if (decompressedsize > 0L && DicomUtils.compressDicomDefault(filename)) {
System.out.println(String.valueOf(totalfiles++) + ": " + filename + " compressed (gain = " + (decompressedsize - new File(filename).length()) / 1024L + " Kb - " + (decompressedsize - new File(filename).length()) * 100L / decompressedsize + "% compression)");
PreparedStatement ps2 = conn.prepareStatement("update oc_pacs set oc_pacs_compresseddatetime=? where oc_pacs_studyuid=? and oc_pacs_series=? and oc_pacs_sequence=?");
ps2.setTimestamp(1, new Timestamp(new Date().getTime()));
ps2.setString(2, studyuid);
ps2.setString(3, series);
ps2.setString(4, sequence);
ps2.execute();
ps2.close();
}
else {
System.out.println(String.valueOf(totalfiles++) + ": !!!!!!!ERROR!!!!!!! could not compress " + filename);
PreparedStatement ps2 = conn.prepareStatement("update oc_pacs set oc_pacs_compresseddatetime=? where oc_pacs_studyuid=? and oc_pacs_series=? and oc_pacs_sequence=?");
ps2.setTimestamp(1, new Timestamp(new SimpleDateFormat("dd/MM/yyyy").parse("01/01/1900").getTime()));
ps2.setString(2, studyuid);
ps2.setString(3, series);
ps2.setString(4, sequence);
ps2.execute();
ps2.close();
}
}
catch (Exception a) {
a.printStackTrace();
Thread.sleep(100L);
}
}
rs.close();
ps.close();
conn.close();
if(totalbatch==0) {
Thread.sleep(10000L);
}
else {
Thread.sleep(1000L);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
|
package com.zjf.myself.codebase.thirdparty.networkbanner;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import com.zjf.myself.codebase.R;
import com.zjf.myself.codebase.activity.WebviewAct;
import com.zjf.myself.codebase.fragment.BaseFragment;
import com.zjf.myself.codebase.util.AutoTunThread;
import com.zjf.myself.codebase.util.DataUtil;
import com.zjf.myself.codebase.util.ViewUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/2/22.
*/
public class BannerFragment extends BaseFragment implements View.OnClickListener {
private ViewPager mViewPaper;
CirclePageIndicator circlePageIndicator;
private BannerAdapter mFragmentAdapter;
private TextView bannerTitle;
static ArrayList<Banner> bannerList;
private int currentItem;
private AutoTunThread autoTunThread;
private AutoTunThread.AutoRunCallBack autoRunCallBack;
public static BannerFragment newInstance(ArrayList<Banner> bannerList) {
BannerFragment f = new BannerFragment();
BannerFragment.bannerList=bannerList;
return f;
}
@Override
protected void initView() {
if(DataUtil.listIsNull(bannerList))
return;
currentItem=0+bannerList.size()*100;
mViewPaper = (ViewPager) findViewById(R.id.vp);
mFragmentAdapter=new BannerAdapter(bannerList);
mFragmentAdapter.setOnClickListener(this);
mViewPaper.setAdapter(mFragmentAdapter);
circlePageIndicator= (CirclePageIndicator) findViewById(R.id.indicator);
circlePageIndicator.setViewPager(mViewPaper,bannerList.size(),currentItem);
circlePageIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Banner bannerItem=bannerList.get(position%bannerList.size());
bannerTitle.setText(bannerItem.getTile());
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
bannerTitle = (TextView) findViewById(R.id.txtBannerTitle);
bannerTitle.setText(bannerList.get(0).getTile());
}
/**
*
* todo
*
* 优化默认广告,以及广告只有一张的时候的样式
*
* */
@Override
public void onResume() {
super.onResume();
if(!DataUtil.listIsNull(bannerList)&&bannerList.size()>1){
runBanner();
}
}
@Override
public void onStop() {
super.onStop();
if(autoTunThread!=null)
autoTunThread.stopRun();
}
@Override
public void onDestroy() {
super.onDestroy();
if(bannerList!=null)
bannerList=null;
}
private void runBanner(){
if(autoTunThread==null){
autoRunCallBack=new AutoTunThread.AutoRunCallBack() {
@Override
public void onDiong() {
currentItem++;
circlePageIndicator.setCurrentItem(currentItem);
}
@Override
public void onFinish() {
}
};
autoTunThread=new AutoTunThread(true,2000,autoRunCallBack);
}
autoTunThread.start();
}
@Override
protected int layoutId() {
return R.layout.layout_banner;
}
@Override
public void onClick(View view) {
Banner bannerItem= (Banner) view.getTag();
WebviewAct.start("老乐健康",bannerItem.getUrl(),getActivity());
}
public class BannerAdapter extends PagerAdapter {
private List<Banner> banners;
private View.OnClickListener onClickListener;
public BannerAdapter(List<Banner> banners){
this.banners=banners;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public int getCount() {
if(banners.size()==1){
return 1;
}
return banners.size()*1000;
}
public void setOnClickListener(View.OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
@Override
public Object instantiateItem(View arg0, int position) {
Log.d("initItem","init:"+position);
if(banners.size()!=1){
position=position%banners.size();
}
NetworkImageView iv=new NetworkImageView(getActivity());
iv.setLayoutParams(mViewPaper.getLayoutParams());
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setTag(banners.get(position));
if(onClickListener!=null)
iv.setOnClickListener(onClickListener);
Banner banner=banners.get(position);
if(banner.getType()==Banner.BANNER_TYPE_DEFAULT){
ViewUtils.setImageByUrl(iv,banners.get(position).getImgUrl(),banner.getDefImgId());
}else {
ViewUtils.setImageByUrl(iv,banners.get(position).getImgUrl(),R.mipmap.banner_default_bg);
}
((ViewPager) arg0).addView(iv, 0);
return iv;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == (arg1);
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
}
}
|
package loslife;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.asgab.entity.RecordCateService;
import com.asgab.entity.Service;
import com.asgab.entity.ServiceAttrMap;
import com.asgab.service.member.MemberCardCategoryService;
import com.asgab.service.service.ServiceService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:/applicationContext.xml" })
@ActiveProfiles("production")
public class RecordCateServiceCategoryTest {
@Autowired
MemberCardCategoryService memberCardCategoryService;
@Test
public void getServiceByEnterprised() {
List<RecordCateService> services =memberCardCategoryService.getRecordCateServicesByEnterpriseId("100008101411200100");
for (RecordCateService service : services) {
System.out.print(service.getCardCateName()+" ");
System.out.print(service.getServiceName()+" ");
System.out.print(service.getDef_int1()+" ");
System.out.print(service.getDef_int2()+" ");
System.out.print(service.getDef_int3()+" ");
System.out.println();
}
}
}
|
package com.beike.util.security;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import com.beike.util.Base64;
/**
*
* @author wchun
*
* AES128 算法,加密模式为ECB,填充模式为 pkcs7(实际就是pkcs5)
*
*
*/
public class AES {
static final String algorithmStr="AES/ECB/PKCS5Padding";
static private KeyGenerator keyGen;
static private Cipher cipher;
static boolean isInited=false;
//初始化
static private void init()
{
//初始化keyGen
try {
keyGen=KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyGen.init(128);
//初始化cipher
try {
cipher=Cipher.getInstance(algorithmStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
isInited=true;
}
public static byte[] GenKey() {
//如果没有初始化过,则初始化
if (!isInited) {
init();
}
return keyGen.generateKey().getEncoded();
}
public static byte[] Encrypt(byte[] content, byte[] keyBytes) {
byte[] encryptedText=null;
// 为初始化
if (!isInited) {
init();
}
Key key=new SecretKeySpec(keyBytes,"AES");
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
encryptedText=cipher.doFinal(content);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encryptedText;
}
//解密为byte[]
public static byte[] DecryptToBytes(byte[] content, byte[] keyBytes) {
byte[] originBytes=null;
if (!isInited) {
init();
}
Key key=new SecretKeySpec(keyBytes,"AES");
try {
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
//解密
try {
originBytes=cipher.doFinal(content);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return originBytes;
}
public static void main(String[] args) {
try {
System.out.println(new String(Base64.encode(Encrypt("<Message xmlns=\"http://tuan.360buy.com/QueryTeamSellCountRequest\"><VenderTeamId>234</VenderTeamId><SpProdId>242351</SpProdId><SellCount>2</SellCount></Message>".getBytes("UTF-8"),"9987.tuan.360buy".getBytes()))));
System.out.println(new String(DecryptToBytes(Base64.decode("azADvvCDojkTDGtYZgg13uevbfnVrDoAtpPBSJqbnPfzUEd4vMHOpPzXhJceEq/Mes55OKj6KvyVxlevaUjt0BbUjsVfzN839THvilnBBd0pCKb9gZqKKbJEoFxpHuYnbOfuKaDDVRdXlW8X60dYsG84PzZz6Ei6ZzxlpJ5wd7dEO0VDC8slHlLzVLTnUpNHBg7WMrvV8Q/Y8uTdIFsIPg==".getBytes("UTF-8")),"9987.tuan.360buy".getBytes())));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} |
import java.awt.AWTException;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
public class CharacterActions {
private Robot bot;
private Point p;
private int PAUSE;
RobotStuff robtype;
public CharacterActions() throws AWTException {
this.bot = ArkBot.bot;
this.p = ArkBot.p;
this.PAUSE = ArkBot.global.PAUSE;
robtype = new RobotStuff(bot);
}
//--------------------Character Action Functionality-------------------
public int Pickup() {
int success = 0;
while(bot.getPixelColor(720, 440).getGreen() <= 250 && bot.getPixelColor(720, 440).getBlue() <= 250) {
LookDown(3);
}
while(bot.getPixelColor(720, 440).getGreen() >= 250 && bot.getPixelColor(720, 440).getBlue() >= 250) {
bot.delay(PAUSE);
bot.keyPress(KeyEvent.VK_E);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_E);
}
success = 1;
return success;
}
public void CharInvSearch(String type) {
ArkBotGUI.GUIText("[ACTION]: Searching character inventory");
p = MouseInfo.getPointerInfo().getLocation();
ArkBot.drag.set(ArkBot.global.CHAR_INV_SEARCH_BAR);
leftClick();
leftClick();
bot.keyPress(KeyEvent.VK_BACK_SPACE);
leftClick();
leftClick();
bot.keyPress(KeyEvent.VK_BACK_SPACE);
robtype.type(type);
bot.keyPress(KeyEvent.VK_ESCAPE);
bot.delay(Global.PAUSE);
bot.keyRelease(KeyEvent.VK_ESCAPE);
}
public void ExtInvSearch(String type) {
ArkBotGUI.GUIText("[ACTION]: Searching external inventory");
p = MouseInfo.getPointerInfo().getLocation();
ArkBot.drag.set(ArkBot.global.EXT_INV_SEARCHBAR);
leftClick();
leftClick();
bot.keyPress(KeyEvent.VK_BACK_SPACE);
leftClick();
leftClick();
bot.keyPress(KeyEvent.VK_BACK_SPACE);
robtype.type(type);
bot.keyPress(KeyEvent.VK_ESCAPE);
bot.delay(Global.PAUSE);
bot.keyRelease(KeyEvent.VK_ESCAPE);
}
public void Transfer(int count) {
if (count == 0) {
while (itemExists()) {
leftClick();
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyPress(KeyEvent.VK_T);
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyRelease(KeyEvent.VK_T);
}
} else {
while (count > 0) {
leftClick();
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyPress(KeyEvent.VK_T);
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyRelease(KeyEvent.VK_T);
count--;
}
}
}
// Possibly Outdated Function
public void Drop(int count) {
if (count == 0) {
while (itemExists()) {
leftClick();
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyPress(KeyEvent.VK_O);
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyRelease(KeyEvent.VK_O);
}
} else {
while (count > 0) {
leftClick();
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyPress(KeyEvent.VK_O);
ArkBot.bot.delay(PAUSE);
ArkBot.bot.keyRelease(KeyEvent.VK_O);
count--;
}
}
}
public void DropAll(){
ArkBot.drag.set(ArkBot.global.EXT_INV_DROPALL);
ArkBot.bot.delay(PAUSE);
leftClick();
ArkBot.bot.delay(PAUSE);
ArkBot.drag.set(ArkBot.global.DROP_ACCEPT);
ArkBot.bot.delay(PAUSE);
leftClick();
ArkBot.bot.delay(PAUSE);
}
public void CharDropAll(){
ArkBot.drag.set(ArkBot.global.CHAR_INV_DROPALL);
ArkBot.bot.delay(PAUSE);
leftClick();
ArkBot.bot.delay(PAUSE);
ArkBot.drag.set(ArkBot.global.DROP_ACCEPT);
ArkBot.bot.delay(PAUSE);
leftClick();
ArkBot.bot.delay(PAUSE);
}
public boolean itemExists() {
return WhitePixelRange(Global.CHAR_INV_FIRSTSLOT_NAME, 4);
}
// --------------------MOVEMENT FUNCTIONALITY-------------------
public void MoveForward (int duration, boolean sprint) {
if (sprint)
{
bot.delay(PAUSE);
while (duration > 0)
{
bot.keyPress(KeyEvent.VK_SHIFT);
bot.keyPress(KeyEvent.VK_W);
duration-=8;
}
}
while (duration > 0)
{
bot.keyPress(KeyEvent.VK_W);
duration-=8;
}
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_W);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_SHIFT);
}
public void MoveLeft (int duration) {
bot.delay(PAUSE);
while (duration > 0)
{
bot.keyPress(KeyEvent.VK_A);
duration-=8;
}
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_A);
}
public void MoveRight (int duration) {
bot.delay(PAUSE);
while (duration > 0)
{
bot.keyPress(KeyEvent.VK_D);
duration-=8;
}
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_D);
}
public void MoveBackward (int duration) {
bot.delay(PAUSE);
while (duration > 0)
{
bot.keyPress(KeyEvent.VK_S);
duration-=8;
}
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_S);
}
public void LookLeft (int pixels) {
bot.delay(250);
while (pixels > 0)
{
pixels--;
bot.keyPress(KeyEvent.VK_LEFT);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_LEFT);
}
}
public void LookRight (int pixels) {
bot.delay(250);
while (pixels > 0)
{
pixels--;
bot.keyPress(KeyEvent.VK_RIGHT);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_RIGHT);
}
}
public void LookUp (int pixels) {
bot.delay(250);
while (pixels > 0)
{
pixels--;
bot.keyPress(KeyEvent.VK_UP);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_UP);
}
}
public void LookDown (int pixels) {
bot.delay(250);
while (pixels > 0)
{
pixels--;
bot.keyPress(KeyEvent.VK_DOWN);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_DOWN);
}
}
// public int InvSearch(String type) {
// ArkBotGUI.GUIText("[ACTION]: Searching inventory");
// int stackCount = 0;
// p = MouseInfo.getPointerInfo().getLocation();
// drag.move(ArkBot.global.INV_SEARCH_BAR);
// leftClick();
// bot.delay(Global.PAUSE);
// leftClick();
// robtype.type(type);
//
// // Stack Count
// ArkBotGUI.GUIText("[ACTION]: Counting stacks");
// int p = 0;
// int ymod = -18;
// int pixelA = bot.getPixelColor(Global.INV_POINTS[p].x,Global.INV_POINTS[p].y + ymod).getRGB();
// int pixelB = bot.getPixelColor(Global.INV_POINTS[p+1].x, Global.INV_POINTS[p+1].y + ymod).getRGB();
// int pixelC = bot.getPixelColor(Global.INV_POINTS[p].x - 60, Global.INV_POINTS[p].y).getRGB();
// System.out.println("PA: " + pixelA);
// System.out.println("PB: " + pixelB);
// System.out.println("PC: " + pixelC);
// if (pixelA-pixelC > 1000 || pixelA-pixelC < -1000 ) {
// System.out.println("Pass");
// while (p <= 19 && (pixelA-pixelB < 1000 && pixelA-pixelB > -1000)) {
// stackCount++;
// p++;
// if (p == 20) {
// // Scroll Down -- Check Scroll Bar
// p = 15;
// }
// pixelA = bot.getPixelColor(Global.INV_POINTS[p].x,Global.INV_POINTS[p].y + ymod).getRGB();
// pixelB = bot.getPixelColor(Global.INV_POINTS[p+1].x, Global.INV_POINTS[p+1].y + ymod).getRGB();
// System.out.println("P1: " + p + " " + bot.getPixelColor(Global.INV_POINTS[p].x,Global.INV_POINTS[p].y + ymod).getRGB());
// System.out.println("P2: " + p + " " + bot.getPixelColor(Global.INV_POINTS[p+1].x, Global.INV_POINTS[p+1].y + ymod).getRGB());
// }
// stackCount++;
// }
// ArkBotGUI.GUIText("[RESULT]: Stack count: " + stackCount);
// return stackCount;
// }
public void InvScreen() {
Color p1 = bot.getPixelColor(41,211);
Color p2 = bot.getPixelColor(34,224);
Color p3 = bot.getPixelColor(973,474);
if (p1.getBlue() >= 250 && p1.getGreen() >= 250 && p1.getRed() == 0
&& p2.getBlue() >= 250 && p2.getGreen() >= 250 && p2.getRed() == 0
&& p3.getBlue() >= 250 && p3.getGreen() >= 250 && p3.getRed() == 0) {
} else {
ArkBotGUI.GUIText("[ACTION]: Opening inventory");
bot.keyPress(KeyEvent.VK_I);
bot.delay(PAUSE);
bot.keyRelease(KeyEvent.VK_I);
bot.delay(500);
}
}
public boolean CyanPixelRange(Point q, int range) {
boolean found = false;
int i = 0;
Point[] points = {
new Point(q.x,q.y),
new Point(q.x - range,q.y),
new Point(q.x - range,q.y - range),
new Point(q.x,q.y - range),
new Point(q.x + range,q.y - range),
new Point(q.x + range,q.y),
new Point(q.x + range,q.y + range),
new Point(q.x,q.y + range),
new Point(q.x - range,q.y + range),
};
while (!found && i < 9) {
if (bot.getPixelColor(points[i].x, points[i].y).getBlue() >= 250
&& bot.getPixelColor(points[i].x, points[i].y).getGreen() >= 250
&& bot.getPixelColor(points[i].x, points[i].y).getRed() == 0) {
found = true;
}
i++;
}
return found;
}
public boolean WhitePixelRange(Point q, int range) {
boolean found = false;
int i = 32;
Point[] points = {
new Point(q.x,q.y),
new Point(q.x - range,q.y),
new Point(q.x - range,q.y - range),
new Point(q.x,q.y - range),
new Point(q.x + range,q.y - range),
new Point(q.x + range,q.y),
new Point(q.x + range,q.y + range),
new Point(q.x,q.y + range),
new Point(q.x - range,q.y + range),
};
while (!found && i < 9) {
if (bot.getPixelColor(points[i].x, points[i].y).getBlue() >= 250
&& bot.getPixelColor(points[i].x, points[i].y).getGreen() >= 250
&& bot.getPixelColor(points[i].x, points[i].y).getRed() >= 250) {
found = true;
}
i++;
}
return found;
}
public boolean CyanCenter(int gap) {
boolean cyan = false;
int i = Global.CENTER.y - (Global.CENTER.y/6);
while (!cyan && i < (Global.CENTER.y + (Global.CENTER.y/6))) {
Color p = bot.getPixelColor(Global.CENTER.x, i);
if (p.getBlue() >= 250 && p.getGreen() >= 250 && p.getRed() == 0) {
cyan = true;
}
i += gap;
}
return cyan;
}
public boolean CyanBreeder(int gap) {
boolean cyan = false;
int i = Global.ResY - (Global.ResY/3);
while (!cyan && i < (Global.ResY)); {
Color p = bot.getPixelColor(Global.CENTER.x, i);
if (p.getBlue() >= 250 && p.getGreen() >= 250 && p.getRed() == 0) {
cyan = true;
}
i += gap;
}
return cyan;
}
public int invYLocator() {
int Y = 227;
while ((bot.getPixelColor(40, Y).getBlue() < 250
&& bot.getPixelColor(40, Y).getGreen() < 250
&& bot.getPixelColor(40, Y).getRed() != 0)
&& Y <= 560){
Y--;
}
return Y;
}
private void leftClick()
{
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.delay(200);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
bot.delay(200);
}
}
|
package four_target_for_interface_reference_example;
public interface MyInterface {
void prepare();
}
|
package com.stratumn.sdk.adapters;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.stratumn.sdk.FileRecord;
import com.stratumn.sdk.FileWrapper;
import com.stratumn.sdk.model.misc.Identifiable;
/***
* Enables deserialization of Identifiable declared field.
*/
public class IdentifiableGsonAdapter implements JsonDeserializer<Identifiable>, JsonSerializer<Identifiable> {
@Override
public Identifiable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if(json != null && json instanceof JsonObject)
if(((JsonObject) json).get("digest") != null)
return context.deserialize(json, FileRecord.class);
else
return context.deserialize(json, FileWrapper.class);
return null;
}
@Override
public JsonElement serialize(Identifiable src, Type typeOfSrc, JsonSerializationContext context)
{
JsonElement json = context.serialize(src);
return json;
}
} |
package com.example.trina.equilibriumapp;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ViewSchedule extends AppCompatActivity {
ListView listView;
String date;
MyDB db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_schedule);
date = getIntent().getStringExtra("date");
db = new MyDB(this, "Events", null, 1);
listView = findViewById(R.id.eventList);
ArrayList<String> infoList = new ArrayList<>();
Cursor data = db.getAllEvents();
if(data.getCount() == 0){
Toast.makeText(this, "There are currently no events in the database", Toast.LENGTH_SHORT).show();
}
else{
while(data.moveToNext()){
infoList.add("Date: " + data.getString(1) +"\n" + "Start Time: " + data.getString(2) + "\n" + "End Time: "+ data.getString(3) + "\n" + "Event Description: " + data.getString(4) );
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, infoList);
listView.setAdapter(listAdapter);
}
}
}
}
|
import java.util.Scanner;
public class UsaNumero{
public static void main(String[]args){
Scanner Lee=new Scanner(System.in);
Numero n = new Numero();
System.out.print("Ingresa el numero para calcular si es par o impar: ");
n.setNum(Lee.nextInt());
n.Calculaparoimpar();
}
} |
package aeroportSpring;
import java.util.Optional;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import aeroportSpring.model.Login;
import aeroportSpring.repository.LoginRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/application-context.xml" })
public class LoginRepositoryTest {
@Autowired
private LoginRepository loginRepository;
@Test
public void testInsert() {
Login login = new Login("login5");
loginRepository.save(login);
Optional<Login> opt = loginRepository.findById(login.getLoginId());
assertTrue(opt.isPresent());
}
@Test
public void testFindAll() {
Pageable page0Avec2Element = PageRequest.of(0, 1, Sort.by(Order.asc("login")));
Page<Login> page = loginRepository.findAll(page0Avec2Element);
assertEquals(0, page.getContent().size());
System.out.println(page);
}
@Test
public void findByLogin() {
assertNotEquals(0, loginRepository.findByLogin("login1"));
}
}
|
//recursion method has exceed time limit
//So I have to implement dynamic programing
public class Solution {
int cnt[] = new int[100];
public int climbStairs(int n) {
if (n <= 2)
{
cnt[n] = n;
return n;
}
if (cnt[n] != 0)
return cnt[n];
cnt[n] = climbStairs(n-1) + climbStairs(n-2);
return cnt[n];
}
}
//A more simpler way is to use iteration
/*public class Solution {
public int climbStairs(int n) {
if(n==1||n==0)
return n;
int count1=1;
int count2=1;
for(int i=2; i<=n; i++){
int temp = count2;
count2 = temp+count1;
count1 = temp;
}
return count2;
}
}*/ |
/**
* Support classes for the multipart resolution framework.
* Contains property editors for multipart files, and a Servlet filter
* for multipart handling without Spring's Web MVC.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.multipart.support;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package Motif;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import jp.ac.ut.csis.pflow.geom.STPoint;
import DataModify.Over8TimeSlots;
public class MotifFinder3 {
/**
* for motifs
* @10.07.2015
* by Taka Yabe
*
* 1. for each ID-day, delete if it is less than 7 timeslots
* 2. delete points where distance from previous point is >300m
* 3. delete points where start and end points in same staypoint is <10mins@
* 4. get staypoints
* 5. get stay regions by clustering staypoints with r=300m
* 6. check if any stayregions are the same --> change the chain number
*
*/
protected static final SimpleDateFormat SDF_TS = new SimpleDateFormat("HH:mm:ss");//change time format
protected static final SimpleDateFormat SDF_TS2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//change time format
protected static final SimpleDateFormat SDF_TS3 = new SimpleDateFormat("dd");//change time format
public static void getMotif(String in) throws NumberFormatException, ParseException, IOException{
File infile = new File(in);
HashMap<String, ArrayList<STPoint>> alldatamap = sortintoMapY(infile);
HashMap<String, ArrayList<String>> id_days = Over8TimeSlots.OKAY_id_days(in);
}
//infile = data for exp (contains data for all days)
public static HashMap<String, ArrayList<STPoint>> sortintoMapY(File infile) throws ParseException, NumberFormatException, IOException{
HashMap<String, ArrayList<STPoint>> id_count = new HashMap<String, ArrayList<STPoint>>();
BufferedReader br = new BufferedReader(new FileReader(infile));
String line = null;
while ((line=br.readLine())!=null){
String[] tokens = line.split("\t");
String id = tokens[0];
Date dt = SDF_TS2.parse(tokens[3]);
STPoint point = new STPoint(dt,Double.parseDouble(tokens[2]),Double.parseDouble(tokens[1]));
if(id_count.containsKey(id)){
id_count.get(id).add(point);
}
else{
ArrayList<STPoint> list = new ArrayList<STPoint>();
list.add(point);
id_count.put(id, list);
}
}
br.close();
return id_count;
}
}
|
package com.lfalch.korome;
import static org.lwjgl.opengl.GL11.GL_QUADS;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glTexCoord2d;
import static org.lwjgl.opengl.GL11.glVertex2d;
import java.io.IOException;
public class HUDDraw {
public static void number(double x, double y, double number) throws IOException{
if(Double.isNaN(number)){
eDraw(x, y);
return;
}else if(Double.isInfinite(number)){
eDraw(x, y);
eDraw(x+movement, y);
return;
}
//Just making sure the number isn't something weird
/* TODO
* Add better symbols for infinite and NaN
*/
String numberString = "" + number;
int add = 0;
for(char c: numberString.toCharArray()){
switch(c){
case '.':
box(x+2+add, y+12, 2, 2);
break;
case '-':
box(x+1+add, y+8, 5, 2);
break;
case 'e':
case 'E':
eDraw(x+add, y);
break;
default:
singleDraw(x+add, y, Integer.valueOf("" + c));
break;
}
add += movement;
}
Colour.WHITE.glSet();
}
public static void statusBar(double x, double y, double width, double height, float status, Colour background, Colour bar){
background.glSet();
box(x, y, width, height);
bar.glSet();
box(x, y, width*status, height);
}
public static void drawString(double x, double y, String s) throws IOException{
Chars.drawString(s, x, y);
}
public static void box(double x, double y, double w, double h){
glBegin(GL_QUADS);
glVertex2d(x, y);
glVertex2d(x+w, y);
glVertex2d(x+w, y+h);
glVertex2d(x, y+h);
glEnd();
Colour.WHITE.glSet();
}
private static int numberWidth = 6, numberHeight = 14, movement = 7;
private static void singleDraw(double x, double y, int number) throws IOException{
Texture numbers = Draw.getTexture("numbers");
numbers.bind();
glBegin(GL_QUADS);
glTexCoord2d(getTexCoord(number), 0);
glVertex2d(x, y);
glTexCoord2d(getTexCoord(number) + 0.1f, 0);
glVertex2d(x+numberWidth, y);
glTexCoord2d(getTexCoord(number) + 0.1f, 1);
glVertex2d(x+numberWidth, y+numberHeight);
glTexCoord2d(getTexCoord(number), 1);
glVertex2d(x, y+numberHeight);
glEnd();
Texture.unbind();
}
private static void eDraw(double x, double y) throws IOException{
Texture e = Draw.getTexture("e");
e.bind();
glBegin(GL_QUADS);
glTexCoord2d(0, 0);
glVertex2d(x, y);
glTexCoord2d(1, 0);
glVertex2d(x+numberWidth, y);
glTexCoord2d(1, 1);
glVertex2d(x+numberWidth, y+numberHeight);
glTexCoord2d(0, 1);
glVertex2d(x, y+numberHeight);
glEnd();
Texture.unbind();
}
private static float getTexCoord(int part){
return 0.1f * part;
}
}
|
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
/**
* Tests that code runs without throwing exceptions.
*/
@SuppressWarnings("javadoc")
public class IndexExceptionsTest {
@Test
public void testNoArguments() {
String[] args = {};
TestUtilities.testNoExceptions(args);
}
@Test
public void testBadArguments() {
String[] args = { "hello", "world" };
TestUtilities.testNoExceptions(args);
}
@Test
public void testMissingPath() {
String[] args = { "-path" };
TestUtilities.testNoExceptions(args);
}
@Test
public void testInvalidPath() {
// generates a random path name
String path = Long.toHexString(Double.doubleToLongBits(Math.random()));
String[] args = { "-path", path };
TestUtilities.testNoExceptions(args);
}
@Test
public void testNoOutput() throws IOException {
String path = Paths.get("text", "simple", "hello.txt").toString();
String[] args = { "-path", path };
// make sure to delete old index.json if it exists
Path output = Paths.get("index.json");
Files.deleteIfExists(output);
TestUtilities.testNoExceptions(args);
// make sure a new index.json was not created
assertFalse(Files.exists(output));
}
@Test
public void testDefaultOutput() throws IOException {
String path = Paths.get("text", "simple", "hello.txt").toString();
String[] args = { "-path", path, "-index" };
// make sure to delete old index.json if it exists
Path output = Paths.get("index.json");
Files.deleteIfExists(output);
TestUtilities.testNoExceptions(args);
// make sure a new index.json was created
assertTrue(Files.exists(output));
}
@Test
public void testEmptyOutput() throws IOException {
String[] args = { "-index" };
// make sure to delete old index.json if it exists
Path output = Paths.get("index.json");
Files.deleteIfExists(output);
TestUtilities.testNoExceptions(args);
// make sure a new index.json was created
assertTrue(Files.exists(output));
}
@Test
public void testSwitchedOrder() throws IOException {
String path = Paths.get("text", "simple", "hello.txt").toString();
String[] args = { "-index", "-path", path };
// make sure to delete old index.json if it exists
Path output = Paths.get("index.json");
Files.deleteIfExists(output);
TestUtilities.testNoExceptions(args);
// make sure a new index.json was created
assertTrue(Files.exists(output));
}
}
|
package com.redrocket.photoeditor.screens.presentation.crop.view;
/**
* @TODO Class Description ...
*/
public interface CropView {
}
|
package com.example.spring05.service.board;
import java.util.List;
import com.example.spring05.model.board.dto.ReplyDTO;
public interface ReplyService {
public List<ReplyDTO> list(int bno);
public int count(int bno);
public void create(ReplyDTO dto);
}
|
package be.openclinic.util;
import java.util.Comparator;
public class ClusterDataSortByCount implements Comparator{
public int compare(Object arg0, Object arg1) {
// TODO Auto-generated method stub
return new Double(((ClusterData)arg1).getCount()-((ClusterData)arg0).getCount()).intValue();
}
}
|
package com.cqut.dto;
import com.cqut.util.BeanUtil;
public class CallRecorderDTO {
private String tcdId;
private String userId;
private String callPhowNum;
private String callerPhNum;
private int talkTime;
private String callTime;
private double usedMoney;
private String callType;
public CallRecorderDTO toModel() {
CallRecorderDTO model = new CallRecorderDTO();
BeanUtil.convert(this, model);
return model;
}
public String getTcdId() {
return tcdId;
}
public void setTcdId(String tcdId) {
this.tcdId = tcdId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCallPhowNum() {
return callPhowNum;
}
public void setCallPhowNum(String callPhowNum) {
this.callPhowNum = callPhowNum;
}
public String getCallerPhNum() {
return callerPhNum;
}
public void setCallerPhNum(String callerPhNum) {
this.callerPhNum = callerPhNum;
}
public int getTalkTime() {
return talkTime;
}
public void setTalkTime(int talkTime) {
this.talkTime = talkTime;
}
public String getCallTime() {
return callTime;
}
public void setCallTime(String callTime) {
this.callTime = callTime;
}
public double getUsedMoney() {
return usedMoney;
}
public void setUsedMoney(double usedMoney) {
this.usedMoney = usedMoney;
}
public String getCallType() {
return callType;
}
public void setCallType(String callType) {
this.callType = callType;
}
}
|
package Service;
import persistance.model.Contest;
import persistance.model.Person;
import persistance.model.Team;
import java.util.Set;
/**
* Created by tkachdan on 04-Dec-14.
*/
public interface ContestService {
public boolean saveContest(Contest contest);
public boolean updateContest(Contest contest);
public boolean promoteTeam(Team team, Contest fromContest, Contest toContest);
public boolean registerTeam(Team team, Set<Person> teamMembers, Contest contest, Person coach);
public boolean setManager(Contest contest, Person manager);
}
|
package com.tpg.brks.ms.expenses.service.converters;
import com.tpg.brks.ms.expenses.domain.Expense;
import com.tpg.brks.ms.expenses.domain.ExpenseReport;
import com.tpg.brks.ms.expenses.persistence.entities.ExpenseEntity;
import com.tpg.brks.ms.expenses.persistence.entities.ExpenseReportEntity;
import org.springframework.core.convert.converter.Converter;
public interface ExpenseConverting extends Converter<ExpenseEntity, Expense> {
@Override
Expense convert(ExpenseEntity expenseEntity);
}
|
package in.msmartpay.agent.utility;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class MyWebChromeClient extends WebChromeClient {
private ProgressListener mListener;
public MyWebChromeClient(ProgressListener listener) {
mListener = listener;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
mListener.onUpdateProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
public interface ProgressListener {
public void onUpdateProgress(int progressValue);
}
} |
package kr.aleks.project_1.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.UUID;
import kr.aleks.project_1.Constr;
import kr.aleks.project_1.ConstrLab;
import kr.aleks.project_1.R;
public class ConstrFragment extends Fragment {
private static final String ARG_CONSTR_ID = "constr_id";
private Constr mConstr;
private ImageView mImageView;
private TextView mTitleView;
private TextView mGrowthView;
private TextView mDescriptionView;
private TextView mPlusTheIncreaseView;
private TextView mTimerView;
private Button mBuildingButton;
public static ConstrFragment newInstance(UUID constrId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CONSTR_ID, constrId);
ConstrFragment fragment = new ConstrFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID constrId = (UUID) getArguments().getSerializable(ARG_CONSTR_ID);
mConstr = ConstrLab.get(getActivity()).getConstr(constrId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_constr, container, false);
mTitleView = (TextView) v.findViewById(R.id.constr_title);
mTitleView.setText(mConstr.getTitle());
mImageView = (ImageView) v.findViewById(R.id.constr_image);
mImageView.setImageResource(mConstr.getImage());
mGrowthView = (TextView) v.findViewById(R.id.growth);
mGrowthView.setText(mConstr.getGrowth());
mDescriptionView = (TextView) v.findViewById(R.id.description);
mDescriptionView.setText(mConstr.getDescription());
mPlusTheIncreaseView = (TextView) v.findViewById(R.id.plus_the_increase);
mTimerView = (TextView) v.findViewById(R.id.times_building);
mBuildingButton = (Button) v.findViewById(R.id.building);
mBuildingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(timeTick, 0);*/
}
});
return v;
}
private Runnable timeTick = new Runnable() {
@Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff - timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = (secs / 60);
int hour = (int) (mins * 60);
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
mTimerView.setText(""
+ String.format("%02d", hour) + ":"
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
}
|
package com.meehoo.biz.core.basic.concurrency.task;
import java.util.List;
/**
* @author zc
* @date 2020-12-26
*/
public interface ITask<T> {
List<T> getResource();
String getId();
String getName();
}
|
class File_Terminal
{
int outer_x = 100;
public void Write_File()
{
for(int i=0;i<10;i++)
{
class Open_Tab
{
public void read_file()
{
System.out.println("outer_class file: " + outer_x);
}
}
Open_Tab ob = new Open_Tab();
ob.read_file();
}
}
}
public class BoxDemo18
{
public static void main(String[]args)
{
File_Terminal TF = new File_Terminal();
TF.Write_File();
}
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
/*
* Sleep.java
*
* Created on June 7, 2013, 9:12:33 PM
*/
package pwnbrew.network.control.messages;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import pwnbrew.misc.Constants;
import pwnbrew.network.ControlOption;
/**
*
*
*/
public final class Sleep extends ControlMessage {
private static final byte OPTION_SLEEP_TIME = 17;
private static final byte OPTION_SENDER_TIME = 19;
private String senderTime = "";
private String sleepTime = "";
//Class name
private static final String NAME_Class = Sleep.class.getSimpleName();
public static final short MESSAGE_ID = 0x4e;
// ==========================================================================
/**
* Constructor
*
* @param dstHostId
* @param passedTime
* @param passedSenderTime
* @throws java.io.UnsupportedEncodingException
*/
public Sleep( int dstHostId, String passedTime, String... passedSenderTime ) throws UnsupportedEncodingException {
super( MESSAGE_ID, dstHostId);
senderTime = Constants.CHECKIN_DATE_FORMAT.format( new Date() );
if( passedSenderTime != null && passedSenderTime.length > 0 )
senderTime = passedSenderTime[0];
byte[] strBytes = senderTime.getBytes("US-ASCII");
ControlOption aTlv = new ControlOption(OPTION_SENDER_TIME, strBytes);
addOption(aTlv);
sleepTime = passedTime;
strBytes = passedTime.getBytes("US-ASCII");
aTlv = new ControlOption(OPTION_SLEEP_TIME, strBytes);
addOption(aTlv);
}
//===============================================================
/**
* Returns the number of seconds to sleep before trying to connect to the server.
*
* @return
*/
public String getSleepTime() {
return sleepTime;
}
//===============================================================
/**
* Returns the time the message was sent as referenced by the sender.
*
* @return
*/
public String getSenderTime() {
return senderTime;
}
}/* END CLASS Sleep */
|
package dnswithfriends.serverside.data;
import java.util.Calendar;
import java.util.Date;
/**
* Describes a know server friend
*/
public class Friend{
private String ip = null;
private int port;
private Date lastUpdated = null;
/**
* Creates a friend
*/
public Friend(String ip, int port){
this.ip = ip;
this.port = port;
this.lastUpdated = Calendar.getInstance().getTime();
}
public String getIp(){
return this.ip;
}
public Friend newest(Friend other){
if(this.lastUpdated.after(other.getLastUpdate())){
return this;
}else{
return other;
}
}
public Date getLastUpdate(){
return this.lastUpdated;
}
public void replaceIp(String ip){
this.ip = ip;
this.lastUpdated = Calendar.getInstance().getTime();
}
public int getPort(){
return this.port;
}
public boolean equals(Friend other){
return this.ip.equalsIgnoreCase(other.getIp()) && this.port == other.getPort() && this.lastUpdated.compareTo(other.getLastUpdate()) == 0;
}
}
|
package kr.co.shop.batch.sample.job;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ClassifierCompositeItemWriter;
import org.springframework.classify.Classifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import kr.co.shop.batch.sample.model.master.Sample1;
import kr.co.shop.batch.sample.model.master.SampleBatchData;
import kr.co.shop.common.util.UtilsText;
import kr.co.shop.constant.MappersSample;
import kr.co.shop.support.BatchReaderAndWriter;
import lombok.extern.slf4j.Slf4j;
@Slf4j // log 사용을 위한 lombok 어노테이션
@Configuration
public class SampleMultiWriterConfiguration extends BatchReaderAndWriter {
public static final String JOB_NAME = "sampleMultiWriter";
public static final String STEP_NAME_SAMPLE_BATCH_DATA = UtilsText.concat(JOB_NAME,"-","sampleMultiWriterStep");
public static final int CHUNK_SIZE = 1000;
@Bean
public Job sampleMultiWriterJob() {
return getJobBuilderFactory(JOB_NAME)
.start(sampleMultiWriterStep())
.build();
}
@Bean
@JobScope
public Step sampleMultiWriterStep() {
ItemProcessor<Sample1, SampleBatchData> processor = new ItemProcessor<Sample1,SampleBatchData> () {
@Override
public SampleBatchData process(Sample1 item) throws Exception {
SampleBatchData sampleBatchData = new SampleBatchData();
sampleBatchData.setSeq(item.getId());
sampleBatchData.setData1(item.getName());
return sampleBatchData;
}
};
String xmlWriterPath = "D:\\project\\abc\\workspace\\abc-framework-sts4\\common\\generator\\generator2.xml";
return getStepBuilderFactory(STEP_NAME_SAMPLE_BATCH_DATA)
// .allowStartIfComplete(true)
.<Sample1,SampleBatchData>chunk(1000)
.reader(newMyBatisPagingItemReader(MappersSample.SAMPLE_1_DAO_SEARCH_SAMPLE_DATA,CHUNK_SIZE,(s,p)->{
log.debug("ssssssssss : {}",s);
p.put("startDtime", s.getString("startDtime"));
p.put("endDtime", s.getString("endDtime"));
log.debug("ppppppppppp : {}",p);
return p;
}))
.processor(processor)
.writer(newMyBatisBatchItemWriter(MappersSample.SAMPLE_BATCH_DATA_DAO_INSERT))
.writer(newXmlItemWriter(xmlWriterPath,"samples",SampleBatchData.class))
.build();
}
} |
package se.ju.student.android_mjecipes;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import se.ju.student.android_mjecipes.CacheHandlers.CacheHandler;
import se.ju.student.android_mjecipes.MjepicesAPIHandler.Entities.JWToken;
import se.ju.student.android_mjecipes.MjepicesAPIHandler.Entities.Recipe;
import se.ju.student.android_mjecipes.MjepicesAPIHandler.Errors;
import se.ju.student.android_mjecipes.MjepicesAPIHandler.Handler;
import se.ju.student.android_mjecipes.MjepicesAPIHandler.Entities.Account;
import se.ju.student.android_mjecipes.UserAgent.UserAgent;
public class SignupActivity extends AppCompatActivity {
EditText username;
EditText hiddenpassword;
EditText hiddenpasswordcheck;
EditText latitude;
EditText longitude;
TextView tvResults;
Button bsign;
RelativeLayout relativeLayout;
private boolean hasLocation = true;
CheckBox checkBox ;
final Account a = new Account();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign__in);
relativeLayout= (RelativeLayout) findViewById(R.id.sign_up);
bsign= (Button) findViewById(R.id.bsignin);
a.latitude = 0.0;
a.longitude = 0.0;
checkBox=(CheckBox) findViewById(R.id.checkBox);
if(!(isConnectionAvailable())){
Snackbar.make(relativeLayout, "No internet connection. You can't create an account.", Snackbar.LENGTH_LONG).show();
bsign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View var) {Snackbar.make(relativeLayout, "No internet connection!", Snackbar.LENGTH_LONG).show();
}
});
}else{
signup();
}
}
private void requestLocationPermission() {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
}
private void setLocation(final Account a) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestLocationPermission();
return;
}
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String providerName = locationManager.getBestProvider(criteria, false);
Location location;
if(locationManager.isProviderEnabled(providerName))
location = locationManager.getLastKnownLocation(providerName);
else {
Toast.makeText(this, "Enable location providers", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
return;
}
if(location == null) {
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateLocation(location,a);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
locationManager.requestSingleUpdate(providerName, locationListener, Looper.myLooper());
} else
updateLocation(location,a);
}
private void updateLocation(Location location,Account a) {
a.latitude = location.getLatitude();
a.longitude = location.getLongitude();
}
public void selectitem(View view){
boolean checked=((CheckBox) view).isChecked();
switch (view.getId()){
case R.id.checkBox:
if(checked)
setLocation(a);
break;
default:
a.latitude = 0.0;
a.longitude = 0.0;
}
}
void signup(){
bsign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View var) {
var.setClickable(true);
username = (EditText) findViewById(R.id.enterusername);
hiddenpassword = (EditText) findViewById(R.id.hiddenpassword);
hiddenpasswordcheck = (EditText) findViewById(R.id.hiddenpasswordcorrection);
a.userName = username.getText().toString();
a.password = hiddenpassword.getText().toString();
if (hiddenpassword.getText().toString().equals(hiddenpasswordcheck.getText().toString())) {
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
Errors e = Handler.getTokenHandler().getErrors();
return Handler.getAccountHandler().postAccount(a);
}
@Override
protected void onPostExecute(Boolean aBoolean) {
Errors e = new Errors();
checkerror(aBoolean);
}
}.execute();
//}
}
else{
bsign.setClickable(true);
hiddenpassword.setError("Passwords are not equal");
hiddenpassword.requestFocus();
}
}
});
}
void checkerror(Boolean aBoolean){
if (aBoolean) {
//error yok
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
finish();
} else {
bsign.setClickable(true);
//error var
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_USERNAME_MISSING)) {
username.setError("Username missing");
username.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_DUPLICATE_USERNAME)) {
username.setError("Username exist");
username.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_INVALID_USERNAME)) {
username.setError("Invalid username");
username.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_LATIDUTE_MISSING)) {
latitude.setError("Latitude missing");
latitude.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_LONGITUDE_MISSING)) {
longitude.setError("Longitude missing");
longitude.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_PASSWORD_MISSING)) {
hiddenpassword.setError("Password missing");
hiddenpassword.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_PASSWORD_REQUIRES_DIGIT)) {
hiddenpassword.setError("Password requires digit");
hiddenpassword.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_PASSWORD_REQUIRES_LOWER)) {
hiddenpassword.setError("Password requires lowercase letter");
hiddenpassword.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_PASSWORD_REQUIRES_NON_ALPHANUM)) {
hiddenpassword.setError("Password requires non alphanum");
hiddenpassword.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_PASSWORD_REQUIRES_UPPER)) {
hiddenpassword.setError("Password requires uppercase letter");
hiddenpassword.requestFocus();
}
if (Handler.getAccountHandler().getErrors().hasError(Errors.ACCOUNT_PASSWORD_TOO_SHORT)) {
hiddenpassword.setError("Password too short");
hiddenpassword.requestFocus();
}
}
}
private boolean isConnectionAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni !=null && ni.isConnected();
}
}
|
/*
* Copyright (c) 2008-2019 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.haulmont.reports.gui.report.history;
import com.haulmont.cuba.gui.WindowParam;
import com.haulmont.cuba.gui.components.Component;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.gui.components.actions.BaseAction;
import com.haulmont.cuba.gui.export.ExportDisplay;
import com.haulmont.cuba.gui.icons.CubaIcon;
import com.haulmont.cuba.gui.model.CollectionLoader;
import com.haulmont.cuba.gui.screen.*;
import com.haulmont.reports.entity.Report;
import com.haulmont.reports.entity.ReportExecution;
import org.springframework.util.CollectionUtils;
import javax.inject.Inject;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
@UiController("report$ReportExecution.browse")
@UiDescriptor("report-execution-browse.xml")
public class ReportExecutionBrowser extends StandardLookup {
public static final String REPORTS_PARAMETER = "reports";
@Inject
protected CollectionLoader<ReportExecution> executionsDl;
@Inject
protected Table<ReportExecution> executionsTable;
@Inject
protected MessageBundle messageBundle;
@Inject
protected ExportDisplay exportDisplay;
@WindowParam(name = REPORTS_PARAMETER)
protected List<Report> filterByReports;
protected Function<Long, String> durationFormatter = new SecondsToTextFormatter();
@Subscribe
protected void onInit(InitEvent event) {
executionsTable.addAction(new DownloadDocumentAction());
}
@Subscribe
protected void onBeforeShow(BeforeShowEvent event) {
initDataLoader();
if (filterByReports != null && !filterByReports.isEmpty()) {
String caption = messageBundle.formatMessage("report.executionHistory.byReport", getReportsNames());
getWindow().setCaption(caption);
}
}
protected void initDataLoader() {
StringBuilder query = new StringBuilder("select e from report$ReportExecution e");
if (!CollectionUtils.isEmpty(filterByReports)) {
query.append(" where e.report.id in :reportIds");
executionsDl.setParameter("reportIds", filterByReports);
}
query.append(" order by e.startTime desc");
executionsDl.setQuery(query.toString());
executionsDl.load();
}
@Install(to = "executionsTable.executionTimeSec", subject = "formatter")
protected String formatExecutionTimeSec(Long value) {
String text = durationFormatter.apply(value);
return text;
}
protected String getReportsNames() {
if (CollectionUtils.isEmpty(filterByReports)) {
return "";
}
return filterByReports.stream()
.map(Report::getName)
.collect(Collectors.joining(", "));
}
public class DownloadDocumentAction extends BaseAction {
public DownloadDocumentAction() {
super("download");
}
@Override
protected boolean isApplicable() {
if (executionsTable.getSelected().size() != 1) {
return false;
}
ReportExecution execution = executionsTable.getSingleSelected();
return execution != null && execution.getOutputDocument() != null;
}
@Override
public String getCaption() {
return messageBundle.getMessage("report.executionHistory.download");
}
@Override
public String getIcon() {
return CubaIcon.DOWNLOAD.source();
}
@Override
public void actionPerform(Component component) {
ReportExecution execution = executionsTable.getSingleSelected();
if (execution != null && execution.getOutputDocument() != null) {
exportDisplay.show(execution.getOutputDocument(), null);
}
}
}
}
|
package de.trispeedys.resourceplanning.messaging;
import de.trispeedys.resourceplanning.entity.Event;
import de.trispeedys.resourceplanning.entity.Helper;
import de.trispeedys.resourceplanning.entity.MessagingType;
import de.trispeedys.resourceplanning.entity.misc.MessagingFormat;
import de.trispeedys.resourceplanning.interaction.HelperInteraction;
import de.trispeedys.resourceplanning.util.HtmlGenerator;
public class DeactivationRecoveryMailTemplate extends AbstractMailTemplate
{
public DeactivationRecoveryMailTemplate(Helper aHelper, Event aEvent)
{
super(aHelper, aEvent, null);
}
public String constructBody()
{
String link =
HelperInteraction.getBaseLink() +
"/DeactivationRecoveryReceiver.jsp?helperId=" + getHelper().getId() + "&eventId=" + getEvent().getId();
return new HtmlGenerator(true).withParagraph("Hallo " + getHelper().getFirstName() + "!")
.withParagraph(
"Leider hast du auf keine unserer Nachfragen reagiert, ob du uns beim Event '"+getEvent().getDescription()+"' helfen kannst."
+ " Nach Ablauf von 4 Wochen wird dein Helfer-Account deshalb deaktiviert. Mit dem Klicken auf den unten stehenden"
+ " Link kannst du die Deaktivierung verhindern und wirst weiterhin als aktiver Helfer geführt:")
.withLink(link, "Deaktivierung verhindern")
.withLinebreak()
.withParagraph("Deine Tri-Speedys.")
.render();
}
public String constructSubject()
{
return "Nachfrage vor Deaktivierung";
}
public MessagingFormat getMessagingFormat()
{
return MessagingFormat.HTML;
}
public MessagingType getMessagingType()
{
return MessagingType.DEACTIVATION_REQUEST;
}
} |
package seedu.project.model.project;
import static java.util.Objects.requireNonNull;
import static seedu.project.commons.util.CollectionUtil.requireAllNonNull;
import java.util.Iterator;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.project.model.project.exceptions.DuplicateGroupTagException;
import seedu.project.model.project.exceptions.GroupTagNotFoundException;
import seedu.project.model.tag.GroupTag;
/**
* A list of GroupTags that enforces uniqueness between its elements and does
* not allow nulls. A GroupTag is considered unique by comparing using
* {@code GroupTag#isSameGroupTag(GroupTag)}. As such, adding and updating of
* tasks uses GroupTag#isSameGroupTag(GroupTag) for equality so as to ensure
* that the task being added or updated is unique in terms of identity in the
* UniqueGroupTagList. However, the removal of a GroupTag uses
* GroupTag#equals(Object) so as to ensure that the task with exactly the same
* fields will be removed.
*
* Supports a minimal set of list operations.
*
* @see GroupTag#isSameGroupTag(GroupTag)
*/
public class UniqueGroupTagList implements Iterable<GroupTag> {
private final ObservableList<GroupTag> internalList = FXCollections.observableArrayList();
private final ObservableList<GroupTag> internalUnmodifiableList = FXCollections
.unmodifiableObservableList(internalList);
/**
* Returns true if the list contains an equivalent task as the given argument.
*/
public boolean contains(GroupTag toCheck) {
requireNonNull(toCheck);
return internalList.stream().anyMatch(toCheck::isSameGroupTag);
}
/**
* Adds a GroupTag to the list. The GroupTag must not already exist in the list.
*/
public void add(GroupTag toAdd) {
requireNonNull(toAdd);
if (contains(toAdd)) {
throw new DuplicateGroupTagException();
}
internalList.add(toAdd);
}
/**
* Replaces the GroupTag {@code target} in the list with {@code editedGroupTag}.
* {@code target} must exist in the list. The GroupTag identity of
* {@code editedTask} must not be the same as another existing task in the list.
*/
public void setGroupTag(GroupTag target, GroupTag editedGroupTag) {
requireAllNonNull(target, editedGroupTag);
int index = internalList.indexOf(target);
if (index == -1) {
throw new GroupTagNotFoundException();
}
if (!target.isSameGroupTag(editedGroupTag) && contains(editedGroupTag)) {
throw new DuplicateGroupTagException();
}
internalList.set(index, editedGroupTag);
}
/**
* Removes the equivalent GroupTag from the list. The GroupTag must exist in the
* list.
*/
public void remove(GroupTag toRemove) {
requireNonNull(toRemove);
if (!internalList.remove(toRemove)) {
throw new GroupTagNotFoundException();
}
}
/**
* Replaces the contents of this list with {@code tasks}. {@code tasks} must not
* contain duplicate tasks.
*/
public void setGroupTags(List<GroupTag> groupTags) {
requireAllNonNull(groupTags);
if (!groupTagsAreUnique(groupTags)) {
throw new DuplicateGroupTagException();
}
internalList.setAll(groupTags);
}
/**
* Returns the backing list as an unmodifiable {@code ObservableList}.
*/
public ObservableList<GroupTag> asUnmodifiableObservableList() {
return internalUnmodifiableList;
}
@Override
public Iterator<GroupTag> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueGroupTagList // instanceof handles nulls
&& internalList.equals(((UniqueGroupTagList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
/**
* Returns true if {@code tasks} contains only unique tasks.
*/
private boolean groupTagsAreUnique(List<GroupTag> groupTags) {
for (int i = 0; i < groupTags.size() - 1; i++) {
for (int j = i + 1; j < groupTags.size(); j++) {
if (groupTags.get(i).isSameGroupTag(groupTags.get(j))) {
return false;
}
}
}
return true;
}
}
|
package net.edoxile.bettermechanics.listeners;
import net.edoxile.bettermechanics.MechanicsType;
import net.edoxile.bettermechanics.exceptions.*;
import net.edoxile.bettermechanics.mechanics.*;
import net.edoxile.bettermechanics.utils.MechanicsConfig;
import net.edoxile.bettermechanics.utils.SignUtil;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import java.util.logging.Logger;
/**
* Created by IntelliJ IDEA.
* User: Edoxile
*/
public class MechanicsPlayerListener extends PlayerListener {
private static final Logger log = Logger.getLogger("Minecraft");
private MechanicsConfig config;
private MechanicsConfig.PermissionConfig permissions;
public MechanicsPlayerListener(MechanicsConfig c) {
config = c;
permissions = c.getPermissionConfig();
}
public void setConfig(MechanicsConfig c) {
config = c;
}
public void onPlayerJoin(PlayerJoinEvent event) {
Pen.clear(event.getPlayer());
}
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (SignUtil.isSign(event.getClickedBlock())) {
Sign sign = SignUtil.getSign(event.getClickedBlock());
if (sign != null) {
if (SignUtil.getActiveMechanicsType(sign) != null) {
switch (SignUtil.getActiveMechanicsType(sign)) {
case BRIDGE:
case SMALL_BRIDGE:
if (!permissions.check(event.getPlayer(), SignUtil.getActiveMechanicsType(sign).name().toLowerCase().concat(".use"), event.getClickedBlock(), false))
return;
Bridge bridge = new Bridge(config, sign, event.getPlayer());
try {
if (!bridge.map())
return;
if (bridge.isClosed()) {
bridge.toggleOpen();
} else {
bridge.toggleClosed();
}
} catch (InvalidMaterialException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Bridge not made of an allowed Material!");
} catch (BlockNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Bridge is too long or sign on the other side was not found!");
} catch (ChestNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "No chest found near signs!");
} catch (NonCardinalDirectionException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Sign is not in a cardinal direction!");
}
break;
case GATE:
case SMALL_GATE:
if (!permissions.check(event.getPlayer(), SignUtil.getActiveMechanicsType(sign).name().toLowerCase().concat(".use"), event.getClickedBlock(), false))
return;
Gate gate = new Gate(config, sign, event.getPlayer());
try {
if (!gate.map())
return;
if (gate.isClosed()) {
gate.toggleOpen();
} else {
gate.toggleClosed();
}
} catch (ChestNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "No chest found near signs!");
} catch (NonCardinalDirectionException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Sign is not in a cardinal direction!");
} catch (OutOfBoundsException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Gate too long or too wide!");
} catch (BlockNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "No fences were found close to bridge!");
}
break;
case DOOR:
case SMALL_DOOR:
if (!permissions.check(event.getPlayer(), SignUtil.getActiveMechanicsType(sign).name().toLowerCase().concat(".use"), event.getClickedBlock(), false))
return;
Door door = new Door(config, sign, event.getPlayer());
try {
if (!door.map())
return;
if (door.isClosed()) {
door.toggleOpen();
} else {
door.toggleClosed();
}
} catch (InvalidMaterialException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Door not made of an allowed Material!");
} catch (BlockNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Door is too long or sign on the other side was not found!");
} catch (ChestNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "No chest found near signs!");
} catch (NonCardinalDirectionException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Sign is not in a cardinal direction!");
}
break;
case LIFT:
if (!permissions.check(event.getPlayer(), SignUtil.getActiveMechanicsType(sign).name().toLowerCase().concat(".use"), event.getClickedBlock(), true, false))
return;
Lift lift = new Lift(config, sign, event.getPlayer());
try {
if (!lift.map()) {
return;
}
lift.movePlayer();
} catch (BlockNotFoundException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Lift is too high or signs are not aligned!");
}
break;
case TELELIFT:
if (!permissions.check(event.getPlayer(), SignUtil.getActiveMechanicsType(sign).name().toLowerCase().concat(".use"), event.getClickedBlock(), true, false))
return;
TeleLift tlift = new TeleLift(config, sign, event.getPlayer());
try {
if (!tlift.map()) {
return;
}
tlift.movePlayer();
} catch (NumberFormatException e) {
event.getPlayer().sendMessage(ChatColor.RED + "Non-numbers found as location!");
}
break;
}
} else if (event.getPlayer().getItemInHand().getType() == config.getPenConfig().penMaterial) {
if (permissions.check(event.getPlayer(), "pen", event.getClickedBlock(), false)) {
String[] text = Pen.getLines(event.getPlayer());
if (text != null) {
String firstline = ((Sign)sign.getBlock().getState()).getLine(0);
Boolean LocketteSign = firstline.equals("[Private]") || firstline.equals("[More Users]");
if(!LocketteSign) {
SignChangeEvent evt = new SignChangeEvent(sign.getBlock(), event.getPlayer(), text);
event.getPlayer().getServer().getPluginManager().callEvent(evt);
if (!evt.isCancelled()) {
for (int i = 0; i < text.length; i++) {
sign.setLine(i, text[i]);
}
sign.update(true);
event.getPlayer().sendMessage(ChatColor.GOLD + "You edited the sign!");
}
} else {
event.getPlayer().sendMessage(ChatColor.GOLD + "I'm not changing lockette signs!");
event.getPlayer().sendMessage(ChatColor.GOLD + "use /lockette!");
}
} else {
text = sign.getLines();
Pen.setText(event.getPlayer(), text);
event.getPlayer().sendMessage(ChatColor.GOLD + "Loaded sign text in memory.");
}
}
}
}
} else if (event.getClickedBlock().getTypeId() == Material.REDSTONE_WIRE.getId() && event.getPlayer().getItemInHand().getTypeId() == Material.COAL.getId()) {
if (!permissions.check(event.getPlayer(), "ammeter", event.getClickedBlock(), true)) {
return;
}
Ammeter ammeter = new Ammeter(config, event.getClickedBlock(), event.getPlayer());
ammeter.measure();
} else if (event.getClickedBlock().getTypeId() == Material.CHEST.getId() && event.getPlayer().getItemInHand().getTypeId() == Material.WOOD_HOE.getId()) {
if(!Cycler.cycle(event.getPlayer(), event.getClickedBlock(), config)){
event.getPlayer().sendMessage(ChatColor.DARK_RED + "You don't have permissions to cycle chests here!");
return;
} else {
event.setCancelled(true);
return;
}
} else {
if (!event.getPlayer().getItemInHand().getType().isBlock() || event.getPlayer().getItemInHand().getType() == Material.AIR) {
Cauldron cauldron = Cauldron.preCauldron(event.getClickedBlock(), config, event.getPlayer());
if (cauldron != null) {
if (permissions.check(event.getPlayer(), "cauldron", event.getClickedBlock(), false)) {
cauldron.performCauldron();
} else {
return;
}
}
}
if (isRedstoneBlock(event.getClickedBlock().getTypeId()))
return;
// BlockFace[] toCheck = {BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH, BlockFace.NORTH, BlockFace.DOWN, BlockFace.UP};
BlockFace[] toCheck = {BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH, BlockFace.NORTH};
for (BlockFace b : toCheck) {
if (SignUtil.isSign(event.getClickedBlock().getRelative(b))) {
Sign sign = SignUtil.getSign(event.getClickedBlock().getRelative(b));
if (SignUtil.getMechanicsType(sign) == MechanicsType.HIDDEN_SWITCH) {
if (permissions.check(event.getPlayer(), "hidden_switch.use", event.getClickedBlock(), true, false)) {
HiddenSwitch hiddenSwitch = new HiddenSwitch(config, sign, event.getPlayer());
if (hiddenSwitch.map())
hiddenSwitch.toggleLevers();
}
}
}
}
}
}
}
/**
* Returns true if a block uses redstone in some way.
* Shamelessly stolen from sk89q's craftbook
*
* @param id
* @return
*/
public static boolean isRedstoneBlock(int id) {
return id == Material.LEVER.getId()
|| id == Material.STONE_PLATE.getId()
|| id == Material.WOOD_PLATE.getId()
|| id == Material.REDSTONE_TORCH_ON.getId()
|| id == Material.REDSTONE_TORCH_OFF.getId()
|| id == Material.STONE_BUTTON.getId()
|| id == Material.REDSTONE_WIRE.getId()
|| id == Material.WOODEN_DOOR.getId()
|| id == Material.IRON_DOOR.getId();
}
}
|
package com.doohong.shoesfit.board.dto;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class BoardResponse {
private Long boardNo;
private String boardTitle;
private String boardContent;
}
|
/*
* MVC패턴으로 개발하다보면, 늘어나는 컨트롤러에 대해 일일이 매핑과정을 진행해야한다.
* 이때 너무 많은 매핑은 관리하기가 까다롭다. 따라서 유지보수성이 높지 못하다.
* 현실과 유사하게 어플리케이션에서도 대형 업무처리시 클라이언트의 요청을 곧바로 해당 컨트롤러에게
* 처리하게 하지 않고, 중간에 메인 컨트롤러를 두고, 모든 요청을 이 메인 컨트롤러에서 처리하여
* 적절한 하위 컨트롤러에게 전담시키는 방식을 이용한다..
*
* 이 컨트롤러는 웹어플리케이션의 모~~든 요청을 1차적으로 받는다.
* */
package com.controller;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import blood.controller.BloodController;
import movie.controller.MovieController;
import movie.model.MovieAdvisor;
public class DispatcherServlet2 extends HttpServlet{
FileInputStream fis;
Properties props;
//init은 서블릿의 생명주기에서, 최초 접속자에 의해 톰켓이 인스턴스를 생성하며, 이와 동시에 초기화 메서드로서
//호출된다.
@Override
public void init(ServletConfig config) throws ServletException {
//getRealPath는 jsp의 내장객체 중 application에 대한 정보를 갖는 application내장객체에서 지원
ServletContext context = config.getServletContext();
String contextConfigLocation=config.getInitParameter("contextConfigLocation");
String savePath = context.getRealPath(contextConfigLocation);
System.out.println(savePath);
try {
fis = new FileInputStream(savePath);
props = new Properties();
props.load(fis); //스트림과 프로퍼티스 연결
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}
//get이건 post이건 상관없이 모든 요청을 이 메서드에서 처리하자!
public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//파라미터에 대한 인코딩
//1단계: 요청받기
System.out.println("제가 받았어요 그 요청!");
//클라이언트가 영화를 원하면 ? -->영화담당 컨트롤러에게 전가
//클라이언트가 혈액형을 원하면 ? -->혈액형담당 컨트롤러에게 전가
//2단계: 요청을 분석하여, 알맞는 컨트롤러에게 요청을 전달한다.
//글쓰기?, 삭제?, 혈액형?, 영화? 핸드폰수리?..
//클라이언트가 무엇을 원하는지 알아야 한다.
//해답은 클라이언트 요청 자체에 있다.. 즉 요청시 사용된 URI가 곧 요청 구분값이다
String uri = request.getRequestURI();
System.out.println("지금 들어온 요청은 "+uri);
Controller controller = null;
String className = null;
/*----------------------------------------> if문을 대신하는 다른 파일로 대체
if(uri.equals("/movie.do")) {
className="movie.controller.MovieController";
//System.out.println("영화전문 컨트롤러인 MovieController에게 전달할게요");
//하위 컨트롤러 생성하기
//controller = new MovieController();
//3단계 : 알맞는 로직 객체에게 일 시킨다.
//->3단계,4단계는 controller -> MovieController,BloodController에서 실행
//5단계: 클라이언트에게 알맞는 결과를 보여준다.
//클라이언트로 하여금 지정한 url로 재접속을 유도하자!!명령하자
//response.sendRedirect("/movie/movie_result.jsp");
}else if(uri.equals("/blood.do")) {
className="blood.controller.BloodController";
//System.out.println("혈액형전문 컨트롤러인 BloodController에게 전달할게요");
//controller = new BloodController();
}
* */
//if문 대신에, 프로퍼티스 객체를 이용하여 key값으로 메모리에 올려질 컨트롤러에 이름을 value로 반환받자.
className = props.getProperty(uri);
try {
Class controllerClass = Class.forName(className); //클래스 로드
//인스턴스 생성
controller=(Controller)controllerClass.newInstance();
//여기까지 2단계
controller.execute(request, response); //다형적으로 실행된다..(다형성)
//5단계: 클라이언트에게 알맞는 결과를 보여준다.
//response.sendRedirect(하위컨트롤러에게 물어본값);
response.sendRedirect(controller.getViewPage());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
//서블릿의 생명주기 메서드 중 서블릿이 소멸할 때 호출되는 메서드인 destory()에, 스트림 등의 자원을
//닫는 처리를 하자
@Override
public void destroy() {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.Point;
/**
*
* <p>Title: AccessoryDAO.java</p>
* <p>Description: 邀请活动管理类DAO</p>
* <p>Copyright: Copyright (c) 2014</p>
* <p>Company: 沈阳网之商科技有限公司 www.koala.com</p>
* @author erikzhang
* @date 2014-4-24
* @version koala_b2b2c v2.0 2015版
*/
@Repository("pointDAO")
public class PointDAO extends GenericDAO<Point> {
}
|
package view.customized_widgets;
import javax.swing.*;
import view.StyleParameters;
public class CustomizedLabel extends JLabel {
public CustomizedLabel(String text) {
super(text);
initialize();
}
public CustomizedLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
initialize();
}
public void initialize() {
setBackground(StyleParameters.defaultBackgroundColor);
setForeground(StyleParameters.defaultTextColor);
setBorder(BorderFactory.createLineBorder(StyleParameters.defaultBackgroundColor, 5));
setFont(StyleParameters.defaultImportantFont);
}
}
|
package com.example.ktgiuaky.Adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.ktgiuaky.Entity.Product;
import com.example.ktgiuaky.MainActivity;
import com.example.ktgiuaky.R;
import java.util.ArrayList;
import java.util.List;
public class ProductAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<Product> productList;
public ProductAdapter(Context context, int layout, List<Product> productList) {
this.context = context;
this.layout = layout;
this.productList = productList;
}
@Override
public int getCount() {
return productList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
private class ViewHolder{
TextView txtId,txtTenSp,txtCost;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view==null){
holder=new ViewHolder();
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(layout,null);
holder.txtId=(TextView)view.findViewById(R.id.txvID);
holder.txtTenSp=(TextView)view.findViewById(R.id.txvName);
holder.txtCost=(TextView)view.findViewById(R.id.txvCost);
view.setTag(holder);
}else {
holder=(ViewHolder)view.getTag();
}
Product product=productList.get(i);
holder.txtId.setText("id:"+product.getId());
holder.txtTenSp.setText("ten sp:"+product.getTenSP());
Double cost=product.getCost();
holder.txtCost.setText("gia:"+cost.toString()+"$");
return view;
}
}
|
/*
* 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 test;
import domain.*;
/**
*
* @author Marcos
*/
public class testReservacion {
public static void main(String[] args) {
Reservacion reservacion = new Reservacion();
reservacion.setIdReservacion(7895642);
reservacion.setFechaIngreso("12/10/2020");
reservacion.setFechaSalida("20/10/2020");
reservacion.setCantidaPersonas(1);
reservacion.setTipoHabitacion(obtnerTipoHabitacionBDD());
reservacion.setCliente(obtenerClienteBDD());
System.out.println("reservacion = " + reservacion.toString());
}
public static Cliente obtenerClienteBDD(){
Cliente cliente = new Cliente();
cliente.setIdCliente(1000);
cliente.setNombre("Marcos");
cliente.setApellido("Guzmán");
cliente.setDireccion("Cochapamba Sur");
cliente.setEmail("marcosguzzz@gmail.com");
cliente.setGenero(obtenerGeneroBDD());
cliente.setNacionalidad(obtenerNacionalidadBDD());
cliente.setEstadoCivil(obtenerEstadoCivilBDD());
return cliente;
}
public static Genero obtenerGeneroBDD(){
Genero genero = new Genero();
genero.setIdGenero(0);
genero.setNombreGenero("Masculino");
return genero;
}
public static Nacionalidad obtenerNacionalidadBDD(){
Nacionalidad nacionalidad = new Nacionalidad();
nacionalidad.setIdNacionalida(47801);
nacionalidad.setTipoNacionalida("Ecuador");
return nacionalidad;
}
public static EstadoCivil obtenerEstadoCivilBDD(){
EstadoCivil estadoCivil = new EstadoCivil();
estadoCivil.setIdEstadoCivil(1245678);
estadoCivil.setTipoEstadoCivil("Soltero");
return estadoCivil;
}
public static TipoHabitacion obtnerTipoHabitacionBDD(){
TipoHabitacion tipoHabitacion = new TipoHabitacion();
tipoHabitacion.setIdTipoHabitacion(1478965);
tipoHabitacion.setEstado(true);
tipoHabitacion.setDescripcion("Habitacion con vista panorámica 270°, frente al mar");
tipoHabitacion.setNombreHabitacion("Suit");
return tipoHabitacion;
}
public static Habitacion obtnerHabitacionBDD(){
Habitacion habitacion = new Habitacion();
habitacion.setIdHabitacion(10);
habitacion.setCaracteristicas("Suit de lujo");
habitacion.setPrecio(1500.00);
return habitacion;
}
}
|
package com.pavietnam.mvprxjava.data;
import com.pavietnam.mvprxjava.data.remote.RetrofitApi;
import com.pavietnam.mvprxjava.data.remote.RetrofitClient;
import com.pavietnam.mvprxjava.data.remote.model.User;
import java.util.List;
import io.reactivex.Observable;
public class Repository implements IRepository{
private RetrofitApi api = RetrofitClient.getClient();
@Override
public Observable<List<User>> getAllUser() {
return api.getAllUser().toObservable();
}
}
|
package by.bytechs.ndcParser.enums;
/**
* @author Romanovich Andrei
*/
public enum OperatingBufferDescription {
CASH_WITHDRAWAL(1, 'A', "Снятие наличных"),
BALANCE_INQ(1, 'B', "Баланс счета"),
MINI_STATEMENTS(1, 'C', "Мини выписка"),
FUNDS_TRANSFER(1, 'D', "Оплата услуг"),
ATM_SERVICE(1, 'G', "Операции с использованием сервистных карт"),
END_OF_DAY(1, 'H', "Инкассация банкомата"),
CURRENCY_BYN(2, 'A', "Беларуские рубли"),
CURRENCY_USD(2, 'B', "Доллары США"),
CURRENCY_EUR(2, 'C', "Евро"),
CURRENCY_USD2(2, 'D', "Доллары США"),
CURRENCY_BYN2(2, 'F', "Беларуские рубли"),
CURRENCY_EUR2(2, 'G', "Евро"),
DEFAULT(4, ' ', "Основной счет"),
CHEQUE(4, 'B', "Контрольный счет"),
CREDIT(4, 'C', "Кредитный счет"),
SAVINGS(4, 'D', "Сохраненный счет"),
UNIVERSAL(4, 'F', "Универсальный счет"),
FUNDS_TRANSFER_A(7, 'A', "Оплата мобильного оператора VELCOM"),
FUNDS_TRANSFER_B(7, 'B', "Оплата мобильного оператора MTC"),
FUNDS_TRANSFER_C(7, 'C', "Перевод средств с карты на карту"),
FUNDS_TRANSFER_D(7, 'D', "Оплата мобильного оператора БЕЛСЕЛ"),
FUNDS_TRANSFER_F(7, 'F', "Коммунальные платежи (за квартиру)"),
FUNDS_TRANSFER_G(7, 'G', "Перевод средств с карты на карту"),
FUNDS_TRANSFER_H(7, 'H', "Пололнение депозита"),
FUNDS_TRANSFER_I(7, 'I', "Погашения кредита"),
LANGUAGE_RU(8, 'A', "Русский язык"),
LANGUAGE_EN(8, 'B', "Английский язык"),
LANGUAGE_BE(8, 'C', "Беларуский язык"),
LANGUAGE_DE(8, 'D', "Немецкий язык");
final int numberBit;
final char value;
final String description;
OperatingBufferDescription(final int numberBit, final char value, final String description) {
this.numberBit = numberBit;
this.value = value;
this.description = description;
}
public static OperatingBufferDescription getObject(int bit, char valueBit) {
for (OperatingBufferDescription description : OperatingBufferDescription.values()) {
if (description.getNumberBit() == bit && description.getValue() == valueBit) {
return description;
}
}
return null;
}
public int getNumberBit() {
return numberBit;
}
public char getValue() {
return value;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "OperatingBufferDescription{" +
", description='" + description + '\'' +
'}';
}
} |
package za.co.vzap.dto;
import java.io.Serializable;
public class ClientDTO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String clientName;
private String clientSurname;
private String clientTitle;
private String clientPhoneNumber;
private String clientEmail;
private String department;
public ClientDTO(String clientName,String clientSurname,String clientTitle,String clientPhoneNumber,String clientEmail,String department){
setClientName(clientName);
setClientSurname(clientSurname);
setClientTitle(clientTitle);
setClientPhoneNumber(clientPhoneNumber);
setClientEmail(clientEmail);
setDepartment(department);
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientSurname() {
return clientSurname;
}
public void setClientSurname(String clientSurname) {
this.clientSurname = clientSurname;
}
public String getClientTitle() {
return clientTitle;
}
public void setClientTitle(String clientTitle) {
this.clientTitle = clientTitle;
}
public String getClientPhoneNumber() {
return clientPhoneNumber;
}
public void setClientPhoneNumber(String clientPhoneNumber) {
this.clientPhoneNumber = clientPhoneNumber;
}
public String getClientEmail() {
return clientEmail;
}
public void setClientEmail(String clientEmail) {
this.clientEmail = clientEmail;
}
@Override
public String toString() {
return "ClientDTO [clientName=" + clientName + ", clientSurname=" + clientSurname + ", clientTitle="
+ clientTitle + ", clientPhoneNumber=" + clientPhoneNumber + ", clientEmail=" + clientEmail
+ ", department=" + department+ "]";
}
}
|
package net.acomputerdog.advplugin.cmd;
public interface CmdHandler {
void runCommand(Cmd cmd);
}
|
package cn.lytcom.cameraview;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import java.io.File;
import java.util.Set;
public class CameraView extends FrameLayout {
CameraImpl mCameraImpl;
CameraListenerWrapper mCameraListenerWrapper;
AutoFitTextureView mTextureView;
public CameraView(@NonNull Context context) {
this(context, null);
}
public CameraView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CameraView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
mCameraListenerWrapper = new CameraListenerWrapper();
mTextureView = new AutoFitTextureView(context);
addView(mTextureView);
mCameraImpl = createCameraImpl();
TypedArray typedArray = context.obtainStyledAttributes(
attrs,
R.styleable.CameraView,
defStyleAttr,
R.style.Widget_CameraView);
setFacing(typedArray.getInt(R.styleable.CameraView_facing, CameraConstants.FACING_BACK));
String aspectRatio = typedArray.getString(R.styleable.CameraView_aspectRatio);
if (!TextUtils.isEmpty(aspectRatio)) {
setAspectRatio(AspectRatio.parse(aspectRatio));
} else {
setAspectRatio(CameraConstants.DEFAULT_ASPECT_RATIO);
}
setAutoFocus(typedArray.getBoolean(R.styleable.CameraView_autoFocus, true));
setFlash(typedArray.getInt(R.styleable.CameraView_flash, CameraConstants.FLASH_AUTO));
typedArray.recycle();
}
public CameraImpl createCameraImpl() {
CameraImpl cameraImpl;
if (Build.VERSION.SDK_INT < 21) {
cameraImpl = new Camera1(mCameraListenerWrapper, mTextureView);
} else {
cameraImpl = new Camera2(mCameraListenerWrapper, mTextureView);
}
return cameraImpl;
}
private class CameraListenerWrapper implements CameraListener {
private CameraListener cameraListener;
void setCameraListener(CameraListener cameraListener) {
this.cameraListener = cameraListener;
}
@Override
public void onCameraOpened() {
if (cameraListener != null) {
cameraListener.onCameraOpened();
}
}
@Override
public void onCameraClosed() {
if (cameraListener != null) {
cameraListener.onCameraClosed();
}
}
@Override
public void onPictureTaken(byte[] jpeg) {
if (cameraListener != null) {
cameraListener.onPictureTaken(jpeg);
}
}
@Override
public void onVideoTaken(File video) {
if (cameraListener != null) {
cameraListener.onVideoTaken(video);
}
}
}
public void setCameraListener(CameraListener cameraListener) {
mCameraListenerWrapper.setCameraListener(cameraListener);
}
public void start() {
if (!mCameraImpl.start()) {
mCameraImpl = new Camera1(mCameraListenerWrapper, mTextureView);
mCameraImpl.start();
}
}
public void stop() {
mCameraImpl.stop();
}
public boolean isCameraOpened() {
return mCameraImpl.isCameraOpened();
}
public Set<AspectRatio> getSupportedAspectRatios() {
return mCameraImpl.getSupportedAspectRatios();
}
public void setAspectRatio(AspectRatio ratio) {
mCameraImpl.setAspectRatio(ratio);
}
public AspectRatio getAspectRatio() {
return mCameraImpl.getAspectRatio();
}
public void setFacing(int facing) {
mCameraImpl.setFacing(facing);
}
public int getFacing() {
return mCameraImpl.getFacing();
}
public void setAutoFocus(boolean autoFocus) {
mCameraImpl.setAutoFocus(autoFocus);
}
public boolean getAutoFocus() {
return mCameraImpl.getAutoFocus();
}
public void setFlash(int flash) {
mCameraImpl.setFlash(flash);
}
public int getFlash() {
return mCameraImpl.getFlash();
}
public void takePicture() {
mCameraImpl.takePicture();
}
public boolean isRecordingVideo() {
return mCameraImpl.isRecordingVideo();
}
public void startRecordingVideo() {
mCameraImpl.startRecordingVideo();
}
public void stopRecordingVideo() {
mCameraImpl.stopRecordingVideo();
}
}
|
/*
* 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.transaction.event;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ApplicationListenerMethodAdapter;
import org.springframework.context.event.EventListener;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.Assert;
/**
* {@link GenericApplicationListener} adapter that delegates the processing of
* an event to a {@link TransactionalEventListener} annotated method. Supports
* the exact same features as any regular {@link EventListener} annotated method
* but is aware of the transactional context of the event publisher.
*
* <p>Processing of {@link TransactionalEventListener} is enabled automatically
* when Spring's transaction management is enabled. For other cases, registering
* a bean of type {@link TransactionalEventListenerFactory} is required.
*
* @author Stephane Nicoll
* @author Juergen Hoeller
* @since 5.3
* @see TransactionalEventListener
* @see TransactionalApplicationListener
* @see TransactionalApplicationListenerAdapter
*/
public class TransactionalApplicationListenerMethodAdapter extends ApplicationListenerMethodAdapter
implements TransactionalApplicationListener<ApplicationEvent> {
private final TransactionPhase transactionPhase;
private final boolean fallbackExecution;
private final List<SynchronizationCallback> callbacks = new CopyOnWriteArrayList<>();
/**
* Construct a new TransactionalApplicationListenerMethodAdapter.
* @param beanName the name of the bean to invoke the listener method on
* @param targetClass the target class that the method is declared on
* @param method the listener method to invoke
*/
public TransactionalApplicationListenerMethodAdapter(String beanName, Class<?> targetClass, Method method) {
super(beanName, targetClass, method);
TransactionalEventListener eventAnn =
AnnotatedElementUtils.findMergedAnnotation(getTargetMethod(), TransactionalEventListener.class);
if (eventAnn == null) {
throw new IllegalStateException("No TransactionalEventListener annotation found on method: " + method);
}
this.transactionPhase = eventAnn.phase();
this.fallbackExecution = eventAnn.fallbackExecution();
}
@Override
public TransactionPhase getTransactionPhase() {
return this.transactionPhase;
}
@Override
public void addCallback(SynchronizationCallback callback) {
Assert.notNull(callback, "SynchronizationCallback must not be null");
this.callbacks.add(callback);
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (TransactionalApplicationListenerSynchronization.register(event, this, this.callbacks)) {
if (logger.isDebugEnabled()) {
logger.debug("Registered transaction synchronization for " + event);
}
}
else if (this.fallbackExecution) {
if (getTransactionPhase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
}
processEvent(event);
}
else {
// No transactional event execution at all
if (logger.isDebugEnabled()) {
logger.debug("No transaction is active - skipping " + event);
}
}
}
}
|
package com.news.dao;
import java.util.List;
import com.news.pojo.Topic;
public interface TopicDao {
List<Topic> getAllTopic() throws Exception;
}
|
package com.soa.display;
import com.soa.ws.category.WSCave;
import com.soa.ws.category.WSForest;
import com.soa.ws.category.WSTower;
import com.soa.ws.hero.WSDragon;
import com.soa.ws.hero.WSElf;
import com.soa.ws.hero.WSMag;
public class ConsoleDisplayer implements Displayer {
@Override
public void display(WSForest wsForest) {
System.out.println(wsForest);
}
@Override
public void display(WSForest[] wsForests) {
if (wsForests.length > 0) {
System.out.println("|\tId\t|\tTrees amount\t|\tElves amount\t");
}
StringBuilder builder = new StringBuilder();
for (WSForest wsForest : wsForests) {
builder.append("|\t").append(wsForest.getId()).append("\t")
.append("|\t").append(wsForest.getAmountOfTrees()).append("\t")
.append("|\t").append(wsForest.getElfs().size()).append("\t|\n");
}
System.out.println(builder.toString());
}
@Override
public void display(WSTower wsTower) {
System.out.println(wsTower);
}
@Override
public void display(WSDragon[] wsDragons) {
if (wsDragons.length > 0) {
System.out.println("|\tId\t|\tName\t|\tGold\t|\tPower\t|\tColor\t|\tCave id\t|");
}
StringBuilder builder = new StringBuilder();
for (WSDragon wsDragon : wsDragons) {
builder.append("|\t").append(wsDragon.getId()).append("\t")
.append("|\t").append(wsDragon.getName()).append("\t")
.append("|\t").append(wsDragon.getGold()).append("\t")
.append("|\t").append(wsDragon.getPower()).append("\t")
.append("|\t").append(wsDragon.getColor()).append("\t")
.append("|\t").append(wsDragon.getCaveId()).append("\t|\n");
}
System.out.println(builder.toString());
}
@Override
public void display(WSElf[] wsElves) {
if (wsElves.length > 0) {
System.out.println("|\tId\t|\tName\t|\tArrows amount\t|\tPower\t|\tBow type\t|\tForest id\t|");
}
StringBuilder builder = new StringBuilder();
for (WSElf wsElve : wsElves) {
builder.append("|\t").append(wsElve.getId()).append("\t")
.append("|\t").append(wsElve.getName()).append("\t")
.append("|\t").append(wsElve.getArrowCount()).append("\t")
.append("|\t").append(wsElve.getPower()).append("\t")
.append("|\t").append(wsElve.getBowType()).append("\t")
.append("|\t").append(wsElve.getForestId()).append("\t|\n");
}
System.out.println(builder.toString());
}
@Override
public void display(WSMag[] wsMags) {
if (wsMags.length > 0) {
System.out.println("|\tId\t|\tName\t|\tMana\t|\tPower\t|\tElement\t|\tTOwer id\t|");
}
StringBuilder builder = new StringBuilder();
for (WSMag wsMag : wsMags) {
builder.append("|\t").append(wsMag.getId()).append("\t")
.append("|\t").append(wsMag.getName()).append("\t")
.append("|\t").append(wsMag.getMana()).append("\t")
.append("|\t").append(wsMag.getPower()).append("\t")
.append("|\t").append(wsMag.getElement()).append("\t")
.append("|\t").append(wsMag.getTowerId()).append("\t|\n");
}
System.out.println(builder.toString());
}
@Override
public void display(WSDragon wsDragon) {
System.out.println(wsDragon);
}
@Override
public void display(WSElf wsElves) {
System.out.println(wsElves);
}
@Override
public void display(WSMag wsMag) {
System.out.println(wsMag);
}
@Override
public void display(WSCave wsCave) {
System.out.println(wsCave);
}
@Override
public void display(WSTower[] wsTowers) {
if (wsTowers.length > 0) {
System.out.println("|\tId\t|\tHeight\t|\tMags amount\t");
}
StringBuilder builder = new StringBuilder();
for (WSTower wsTower : wsTowers) {
builder.append("|\t").append(wsTower.getId()).append("\t")
.append("|\t").append(wsTower.getHeight()).append("\t")
.append("|\t").append(wsTower.getMags().size()).append("\t|\n");
}
System.out.println(builder.toString());
}
@Override
public void display(WSCave[] wsCaves) {
if (wsCaves.length > 0) {
System.out.println("|\tId\t|\tSquare\t|\tDragons amount\t");
}
StringBuilder builder = new StringBuilder();
for (WSCave wsCave : wsCaves) {
builder.append("|\t").append(wsCave.getId()).append("\t")
.append("|\t").append(wsCave.getSquare()).append("\t")
.append("|\t").append(wsCave.getDragons().size()).append("\t|\n");
}
System.out.println(builder.toString());
}
}
|
public class notCom implements BetterBehavior
{
public void comIs()
{
System.out.println("This is not comparative.");
}
} |
package com.javiermarsicano.algorithms.hackerrank;
import java.util.Scanner;
public class SolutionRotation {
public static void rotate(int[] in, int[] result, int n, int k) {
for (int i = n - 1; i >= 0; i--) {
if (i < k)
result[n-k+i] = in[i];
else
result[i-k] = in[i];
}
}
public static int[] arrayLeftRotation(int[] a, int n, int k) {
int[] result = new int[n];
rotate(a, result, n, k);
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
int[] output = new int[n];
output = arrayLeftRotation(a, n, k);
for(int i = 0; i < n; i++)
System.out.print(output[i] + " ");
System.out.println();
}
}
|
package lab4;
/**
*
* @author hugo
*/
public class Model {
private static double L = 1;
private Particle[] particleArray;
public Model(int particleNum) {
particleArray = new Particle[particleNum];
for (int i = 0; i < particleNum; i++) {
particleArray[i] = new Particle();
}
}
public void updateTotalPosition() {
for (int i = 0; i < particleArray.length; i++) {
particleArray[i].updatePosition();
}
}
public double[] getTotalPosition() {
double[] positionArray = new double[particleArray.length * 2];
int index = 0;
for (int i = 0; i < particleArray.length*2; i = i + 2) {
positionArray[i] = particleArray[index].getX();
positionArray[i + 1] = particleArray[index].getY();
index++;
}
return positionArray;
}
public void setLength(double argL) {
L = argL;
}
public double getLength() {
return L;
}
private class Particle {
private double x;
private double y;
public Particle(double xIn, double yIn) {
x = xIn;
y = yIn;
}
public Particle() {
this(Math.random(), Math.random());
}
public void updatePosition() {
double theta = Math.random() * 2 * 3.1415;
x = x + 0.01 * L * Math.cos(theta); //multiplicerar L med 0.01 eftersom i slidern i Controller måste det vara en int och jag vill ha ett litet tal.
y = y + 0.01 * L * Math.sin(theta);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
}
|
package HillyerNilesTempestini;
import java.io.*;
import java.util.*;
import java.beans.*;
import org.json.simple.*;
public class MemberWriter implements Serializable{
public static void writeMembersToScreen(ArrayList<Member> members) {
for (Member m : members) {
System.out.println(m);
System.out.println("-----------------------------");
}
}
public static boolean writeTextFile(ArrayList<Member> members, String filename) {
try {
PrintWriter pw = new PrintWriter(new BufferedWriter(
new FileWriter(new File(filename))));
for (Member m: members) {
pw.println(m);
}
pw.close();
return true;
} catch (Exception ex) {
return false;
}
}
public static boolean writeBinaryFile(ArrayList<Member> members, String filename) throws IOException {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(new File(filename)));
oos.writeObject(members);
oos.close();
return true;
} catch(Exception ex) {
return false;
}
}
public static boolean writeXmlFile(ArrayList<Member> members, String filename) {
try {
XMLEncoder xml = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream(filename)));
xml.writeObject(members);
xml.close();
return true;
} catch (Exception ex) {
return false;
}
}
public static boolean writeJSONFile(ArrayList<Member> members,
String fname) {
try {
PrintWriter pw = new PrintWriter(new BufferedWriter(
new FileWriter(fname)));
JSONArray array = new JSONArray();
JSONObject obj;
for (Member member : members) {
obj = new JSONObject();
obj.put("first name", member.getFirstName());
obj.put("last name", member.getLastName());
obj.put("age", member.getAge());
obj.put("height", member.getHeight());
obj.put("weight", member.getWeight());
obj.put("BP Syst", member.getBpSyst());
obj.put("BP Dias", member.getBpDias());
obj.put("cancer", member.getCancer());
obj.put("diabetes", member.getDiabeties());
obj.put("alzheimers", member.getAlzheimers());
array.add(obj);
}
JSONObject gradeList = new JSONObject();
gradeList.put("member", array);
pw.println(gradeList.toJSONString());
pw.close();
return true;
} catch (Exception ex) {
return false;
}
}
}
|
package com.wxt.designpattern.singleton.test03;
/*********************************
* @author weixiaotao1992@163.com
* @date 2018/10/21 13:39
* QQ:1021061446
*
*********************************/
/**
* 使用枚举来实现单例模式的示例
*
* Java规范中规定,每一个枚举类型极其定义的枚举变量在JVM中都是唯一的,因此在枚举类型的序列化和反序列化上,
* Java做了特殊的规定。
* 在序列化的时候Java仅仅是将枚举对象的name属性输出到结果中,反序列化的时候则是
* 通过 java.lang.Enum 的 valueOf() 方法来根据名字查找枚举对象。
* 也就是说,以下面枚举为例,序列化的时候只将 DATASOURCE 这个名称输出,
* 反序列化的时候再通过这个名称,查找对于的枚举类型,因此反序列化后的实例也会和之前被序列化的对象实例相同。
* 枚举天生保证序列化单例。
* 原文:https://blog.csdn.net/gavin_dyson/article/details/70832185
*
*/
public enum DataSourceEnum {
/**
* 定义一个枚举的元素,它就代表了 DataSourceEnum 的一个实例
*/
DATASOURCE;
private DBConnection connection;
DataSourceEnum(){
connection = new DBConnection();
}
public DBConnection getConnection(){
return connection;
}
}
|
import specificSiteControllers.RabotaUA_Controller;
import specificSiteControllers.WorkUA_Controller;
public class MainController {
public static void main(String[] args) throws InterruptedException {
RabotaUA_Controller.searchOnRabota("Developer","brosinskiy@gmail.com","Bogdan","Rosinskiy","C1");
WorkUA_Controller.searchOnWork("Developer","brosinskiy@gmail.com","Bogdan Rosinskiy");
//TODO: Full parametrisation
//TODO: GUI
}
}
|
package com.fanfte.java8.stream;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
/**
* Created by dell on 2018/8/1
**/
public class TestStream {
public static void main(String[] args) {
List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH) );
// stream使用例子
List<String> collect = menu.stream().filter(d -> {
System.out.println("filtering " + d.getName());
return d.getCalories() > 300;
})
.map(d -> {
System.out.println("mapping " + d.getName());
return d.getName();
})
.limit(3)
.collect(toList());
System.out.println(collect);
// 流只能被消费一次
List<String> strings = Arrays.asList("Java8", "In", "Action");
Stream<String> stream = strings.stream();
stream.forEach(System.out::println);
// 抛出IllegalStateException: stream has already been operated upon or closed
// stream.forEach(System.out::println);
// streams测验
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> collect1 = integers.stream()
.map(n -> n * n)
.collect(toList());
System.out.println(collect1);
// 数对
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
List<int[]> collect2 = numbers1.stream()
.flatMap(i -> numbers2.stream()
.filter(j -> (i + j) % 3 == 0)
.map(j -> new int[]{i, j})
)
.collect(toList());
System.out.println(collect2);
System.out.println("use stream--------");
Trader raoul = new Trader("Raoul", "Cambridge");
Trader mario = new Trader("Mario","Milan");
Trader alan = new Trader("Alan","Cambridge");
Trader brian = new Trader("Brian","Cambridge");
List<Transaction> transactions = Arrays.asList(
new Transaction(brian, 2011, 300),
new Transaction(raoul, 2012, 1000),
new Transaction(raoul, 2011, 400),
new Transaction(mario, 2012, 710),
new Transaction(mario, 2012, 700),
new Transaction(alan, 2012, 950)
);
List<Transaction> test1 = transactions.stream()
.filter(t -> t.getYear() == 2011)
.sorted(Comparator.comparing(Transaction::getValue))
.collect(toList());
System.out.println(test1);
List<String> test2 = transactions.stream()
.map(transaction -> transaction.getTrader().getCity())
.distinct()
.collect(toList());
System.out.println("test2 " + test2);
List<Trader> test3 = transactions.stream()
.map(Transaction::getTrader)
.filter(trader -> trader.getCity().equals("Cambridge"))
.distinct()
.collect(toList());
System.out.println(test3);
System.out.println("test4------------------");
String test4 = transactions.stream()
.map(transaction -> transaction.getTrader().getName())
.distinct()
.sorted()
.reduce("", (a, b) -> a + b);
System.out.println(test4);
boolean b = transactions.stream()
.anyMatch(t -> t.getTrader().getCity().equals("Milan"));
System.out.println(b);
transactions.stream()
.filter(t -> "Cambridge".equals(t.getTrader().getCity()))
.map(Transaction::getValue)
.forEach(System.out::println);
System.out.println("------------------------");
Optional<Integer> max = transactions.stream()
.map(Transaction::getValue)
.reduce(Integer::max);
System.out.println(max.get());
System.out.println("------------------------");
Optional<Transaction> min = transactions.stream()
.min(Comparator.comparing(Transaction::getValue));
System.out.println(min.get());
System.out.println("------------------");
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
OptionalInt max1 = intStream.max();
System.out.println(max1.getAsInt());
// Stream<Integer> boxed = intStream.boxed();
IntStream evenStream = IntStream.range(1, 100).filter(n -> n % 2 == 0);
System.out.println(evenStream.count());
System.out.println("---------------------------------");
Stream<int[]> gougu = IntStream.rangeClosed(1, 100).boxed()
.flatMap(a -> IntStream.rangeClosed(a, 100)
.filter(b1 -> Math.sqrt(a * a + b1 * b1) % 1 == 0)
.mapToObj(b1 -> new int[]{a, b1, (int) Math.sqrt(a * a + b1 * b1)})
);
gougu.limit(7)
.forEach(tg -> System.out.println(tg[0] + " " + tg[1] + " " + tg[2]));
}
}
|
package com.binarysprite.evemat.page.product;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.util.ListModel;
import com.binarysprite.evemat.Constants;
import com.binarysprite.evemat.component.ExternalImage;
import com.binarysprite.evemat.page.FramePage;
import com.binarysprite.evemat.page.product.data.Group;
import com.binarysprite.evemat.page.product.data.Material;
import com.binarysprite.evemat.page.product.data.Product;
import com.binarysprite.evemat.util.EveImageService;
import com.google.inject.Inject;
/**
*
* @author Tabunoki
*
*/
public class ProductPage extends FramePage {
/**
*
*/
private static final long serialVersionUID = -7851075248525677171L;
/**
*
*/
public static final String WICKET_ID_GROUP_LIST_VIEW = "groupListView";
/**
*
*/
public static final String WICKET_ID_GROUP_LINK = "groupLink";
/**
*
*/
public static final String WICKET_ID_CHARACTER_NAME_LABEL = "characterNameLabel";
/**
*
*/
public static final String WICKET_ID_GROUP_NAME_LABEL = "groupNameLabel";
/**
*
*/
public static final String WICKET_ID_PRODUCT_LIST_VIEW = "productListView";
/**
*
*/
public static final String WICKET_ID_MATERIAL_LIST_VIEW = "materialListView";
/**
*
*/
public static final String WICKET_ID_ICON_IMAGE = "iconImage";
/**
*
*/
public static final String WICKET_ID_TYPE_NAME_LABEL = "typeNameLabel";
/**
*
*/
public static final String WICKET_ID_QUANTITY_LABEL = "quantityLabel";
/**
*
*/
public static final String WICKET_ID_SALES_LABEL = "salesLabel";
/**
*
*/
public static final String WICKET_ID_COSTS_LABEL = "costsLabel";
/**
*
*/
public static final String WICKET_ID_TOTAL_SALES_LABEL = "totalSalesLabel";
/**
*
*/
public static final String WICKET_ID_TOTAL_COSTS_LABEL = "totalCostsLabel";
/**
*
*/
public static final String WICKET_ID_PROFIT_LABEL = "profitLabel";
/**
*
*/
public static final String WICKET_ID_RATIO_LABEL = "ratioLabel";
/**
* グループ一覧のモデルオブジェクトです。
*/
private final List<Group> groupList = new ArrayList<Group>();
/**
* プロダクトグループのモデルオブジェクトです。
*/
private Group group = new Group();
/**
*
*/
private final ListView<Group> groupListView = new ListView<Group>(WICKET_ID_GROUP_LIST_VIEW,
new ListModel<Group>(groupList)) {
@Override
protected void populateItem(ListItem<Group> item) {
final Group group = (Group) item.getModelObject();
/*
* コンポーネントの生成
*/
final Link<Void> groupLink = new Link<Void>(WICKET_ID_GROUP_LINK) {
@Override
public void onClick() {
final List<Product> products = group.getProducts();
final List<Material> materials = group.getMaterials();
products.clear();
materials.clear();
products.addAll(productPageService.getProduct(group.getId()).getProducts());
materials.addAll(productPageService.getProduct(group.getId()).getMaterials());
}
};
final Label groupNameLabel =
new Label(WICKET_ID_GROUP_NAME_LABEL, group.getGroupName());
final Label characterNameLabel =
new Label(WICKET_ID_CHARACTER_NAME_LABEL, group.getCharacterName());
/*
* コンポーネントの組み立て
*/
item.add(groupLink);
groupLink.add(groupNameLabel);
groupLink.add(characterNameLabel);
}
};
/**
*
*/
final ListView<Product> productListView = new ListView<Product>(
WICKET_ID_PRODUCT_LIST_VIEW,
new ListModel<Product>(group.getProducts())) {
@Override
protected void populateItem(ListItem<Product> item) {
final Product product = item.getModelObject();
item.add(new ExternalImage(WICKET_ID_ICON_IMAGE, EveImageService.getTypeIcon(
product.getId(),
EveImageService.TypeIconSize.PIXEL_32)));
item.add(new Label(WICKET_ID_TYPE_NAME_LABEL,
product.getName()) {
@Override
protected void onComponentTag(
ComponentTag tag) {
super.onComponentTag(tag);
tag.put("onclick", "CCPEVE.showMarketDetails(" + product.getId() + ")");
}
});
item.add(new Label(WICKET_ID_QUANTITY_LABEL,
Constants.QUANTITY_FORMAT.format(product.getQuantity())));
item.add(new Label(WICKET_ID_SALES_LABEL,
Constants.PRICE_FORMAT.format(product.getSales())));
}
};
/**
*
*/
final ListView<Material> materialListView = new ListView<Material>(
WICKET_ID_MATERIAL_LIST_VIEW,
new ListModel<Material>(group.getMaterials())) {
@Override
protected void populateItem(ListItem<Material> item) {
final Material material = item.getModelObject();
item.add(new ExternalImage(WICKET_ID_ICON_IMAGE, EveImageService.getTypeIcon(
material.getId(),
EveImageService.TypeIconSize.PIXEL_32)));
item.add(new Label(WICKET_ID_TYPE_NAME_LABEL,
material.getName()) {
@Override
protected void onComponentTag(
ComponentTag tag) {
super.onComponentTag(tag);
tag.put("onclick", "CCPEVE.showMarketDetails(" + material.getId() + ")");
}
});
item.add(new Label(WICKET_ID_QUANTITY_LABEL,
Constants.QUANTITY_FORMAT.format(material.getQuantity())));
item.add(new Label(WICKET_ID_COSTS_LABEL,
Constants.PRICE_FORMAT.format(material.getCosts())));
}
};
/**
*
*/
@Inject
ProductPageService productPageService;
/**
*
*/
public ProductPage() {
super();
groupList.addAll(productPageService.getGroups());
group = productPageService.getProduct(groupList.get(0).getId());
/*
* コンポーネントの生成
*/
final Label title = new Label(WICKET_ID_PAGE_TITLE_LABEL, "Product");
final Label totalSalesLabel = new Label(WICKET_ID_TOTAL_SALES_LABEL, productPageService.getTotalSale(group));
final Label totalCostsLabel = new Label(WICKET_ID_TOTAL_COSTS_LABEL, productPageService.getTotalCost(group));
final Label profitLabel = new Label(WICKET_ID_PROFIT_LABEL, productPageService.getProfit(group));
final Label ratioLabel = new Label(WICKET_ID_RATIO_LABEL, productPageService.getRatio(group));
/*
* コンポーネントの編集
*/
/*
* コンポーネントの追加
*/
this.add(title);
this.add(groupListView);
this.add(productListView);
this.add(materialListView);
this.add(totalSalesLabel);
this.add(totalCostsLabel);
this.add(profitLabel);
this.add(ratioLabel);
}
} |
package org.camunda.bpm.cockpit.plugin.centaur.resources;
import org.camunda.bpm.cockpit.db.QueryParameters;
import org.camunda.bpm.cockpit.plugin.centaur.db.ProcessStatisticsDto;
import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* Resource returning the max and avg duration of a process definiton id.
*
* @version 1.0
*/
public class ProcessStatisticsResource extends AbstractCockpitPluginResource {
private String procDefId;
/**
* Constructor for this resource.
*
* @param engineName The engine currently being used by the platform.
* @param procDefId A process definition id.
*/
ProcessStatisticsResource(String engineName, String procDefId) {
super(engineName);
this.procDefId = procDefId;
}
/**
* A JAX-RS function when a GET request is made to the {engineName}/order-statistics path.
*
* @return A list containing the max and the avg of the running instances
* of the given process definition id.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<ProcessStatisticsDto> getOrderStatistics() {
QueryParameters<ProcessStatisticsDto> queryParameters = new QueryParameters<>();
queryParameters.setParameter(procDefId);
configureTenantCheck(queryParameters);
return getQueryService().executeQuery(
"cockpit.query.selectProcessStatistics", queryParameters);
}
}
|
package db;
public class TestData {
public static String HTitle="Bankrate";
}
|
package com.luthfi.taxcalculator.common.calculator;
import com.luthfi.taxcalculator.common.model.Tax;
public class FoodTaxCalculator implements TaxCalculator {
@Override
public Long calculate(Tax tax, Long price) {
System.out.println(" from FoodTaxCalculator ");
return tax.getTaxRate() * price;
}
}
|
package org.ohdsi.webapi.security;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.info.ConfigurationInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class SecurityConfigurationInfo extends ConfigurationInfo {
private static final String KEY = "security";
public SecurityConfigurationInfo(@Value("${security.provider}") String securityProvider) {
boolean enabled = !Objects.equals(securityProvider, Constants.SecurityProviders.DISABLED);
properties.put("enabled", enabled);
}
@Override
public String getKey() {
return KEY;
}
}
|
package net.mv.dao;
import javax.inject.Inject;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository("loginDao")
@Component
public class LoginDAO {
@Inject
private SessionFactory sessionFactory;
@Transactional
public boolean authenticate(String user, String pwd) {
Login login = (Login)this.sessionFactory.getCurrentSession().get(Login.class, user);
if(login == null){
return false;//username doesn't exist
}else{
if(pwd.equals(login.getPassword()) ) //passwords match
return true;
}
return false; //passwords don't match
}
}
|
package com.example.shoji.bakingapp.utils;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
public class LoaderCallBackUtils {
public static void initOrRestartLoader(int loaderId,
Bundle args,
LoaderManager loaderManager,
LoaderManager.LoaderCallbacks callback) {
if(null == loaderManager.getLoader(loaderId)) {
loaderManager.initLoader(loaderId,
args, callback);
}
else {
loaderManager.restartLoader(loaderId,
args, callback);
}
}
}
|
package com.alibaba.uilearning.activity;
import com.alibaba.uilearning.R;
import com.alibaba.uilearning.view.WidgetAutoTextView;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ScrollLightActivity extends Activity implements OnClickListener {
private TextView mScrollLightTv = null;
private TextView mMyScrollLightTv = null;
private Button mScrollLightBtn = null;
private Button mBtnNext;
private Button mBtnPrev;
private WidgetAutoTextView mTextView02 = null;
private static int sCount = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_light);
mScrollLightTv = (TextView)findViewById(R.id.scroll_light_tv);
mScrollLightBtn = (Button)findViewById(R.id.scroll_light_btn);
mMyScrollLightTv = (TextView)findViewById(R.id.my_scroll_light_tv);
mScrollLightTv.setText("111111112222222222222333333333334");
mMyScrollLightTv.setText("8888888888888888999999999999999999");
mScrollLightBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mScrollLightTv.setText("广东省广大法国大师法撒旦法士大夫地方上东方四大防盗锁");
mMyScrollLightTv.setText("广东省广大法国大师法撒旦法士大夫地方上东方四大防盗锁");
}
});
init();
}
private void init() {
// TODO Auto-generated method stub
mBtnNext = (Button) findViewById(R.id.next);
mBtnPrev = (Button) findViewById(R.id.prev);
mTextView02 = (WidgetAutoTextView) findViewById(R.id.switcher02);
mTextView02.setText("Hello world!");
mBtnPrev.setOnClickListener(this);
mBtnNext.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.next:
mTextView02.next();
sCount++;
break;
case R.id.prev:
mTextView02.previous();
sCount--;
break;
}
mTextView02.setText(sCount%2==0 ?
sCount+"AAFirstAA" :
sCount+"BBBBBBB");
System.out.println("getH: ["+mTextView02.getHeight()+"]");
}
}
|
import java.io.*;
import java.util.*;
class skate
{
public static void main(String [] args)
{
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int count=0;
if(n>0&&n<1001)
{
for(int i=0;i<n;i++)
{
int a=kb.nextInt();
int b=kb.nextInt();
if(a<b)
count++;
}
System.out.println(count);
}
}
}
|
/**
* Liquibase specific code.
*/
package edu.erlm.epi.config.liquibase;
|
package z2;
public class CalculatorTester2 {
public static void main(String args[]) {
int numbers[]= {23,54,88,98,23,54,7,72,35,22};
System.out.println("The average is"+Calculator.calculateAverage(numbers));
System.out.println("The maximum is"+Calculator.findMaximum(numbers));
}
}
|
package com.example.user.mycalender;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
public class IntroActivity extends AppCompatActivity {
private Handler handler;
private Runnable mRunnable;
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
String name = "scheduleDatabase.db";
// SQLiteDatabase Database = openOrCreateDatabase(name,MODE_WORLD_WRITEABLE,null);
mRunnable = new Runnable(){
public void run(){
Intent intent = new Intent(getApplicationContext(),CalenderActivity.class);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
};
handler = new Handler();
handler.postDelayed(mRunnable, 1300);
}
protected void onDestroy(){
handler.removeCallbacks(mRunnable);
super.onDestroy();
}
}
|
package com.example.yuanping.todolist.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.yuanping.todolist.R;
public class NewEvent extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_event);
}
}
|
/**
*/
package iso20022.impl;
import org.eclipse.emf.ecore.EClass;
import iso20022.BusinessElementType;
import iso20022.Iso20022Package;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Business Element Type</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public abstract class BusinessElementTypeImpl extends RepositoryTypeImpl implements BusinessElementType {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BusinessElementTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getBusinessElementType();
}
} //BusinessElementTypeImpl
|
package com.gws.services.ucloud;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 【功能描述】
*
* @author wangdong
*/
public interface UcloudService {
/**
* 上传单个文件
* @param file
* @param bucket
* @return
*/
String uploadFile(MultipartFile file, String bucket);
/**
* 上传多个文件
* @param files
* @param bucket
* @return
*/
List<String> uploadFiles(MultipartFile[] files, String bucket);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.