text
stringlengths
10
2.72M
package cuc.edu.cn.hynnsapp02.ui.pageViewers_fragement3; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import cuc.edu.cn.hynnsapp02.R; public class PageViewers_action extends Fragment implements ViewPager.OnPageChangeListener { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.pageviewers_action, container, false); return view; } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { } @Override public void onPageScrollStateChanged(int i) { } }
package com.zhongyp.algorithm; /** * Created by Administrator on 2017/8/13. */ public class ExchangeSort { /** * * 冒泡排序,这个就不说啦,应该都会 */ public static void bubbleSort(){ // int[] arr = {3,5,7,1,4}; int[] arr = {1,2,3,4,5}; int i,j,temp,len=arr.length; //是否已经完成排序的标志 boolean flag; //排序 for(i=0;i<arr.length-1;i++){ flag = true; for(j=i+1;j<arr.length;j++){ if(arr[j]<arr[i]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; flag = false; } } if(flag){ System.out.println("第" + (i+1) + "趟结束了"); break; } } //遍历输出数组 for(int o:arr){ System.out.print(" " + o); } } /** * 快速排序 * 1.在数组中选取一个数作为基数 * 2.将大于这个数的书放在这个数的右边,小于的放在左边 * 3.然后对左右子区间重复步骤1,2,直到子区间就一个数 * * @param num * @param start * @param end */ public static void quickSort(int[] num,int start, int end){ int sys = num[start];// 选取基数 int left = start; int right = end; while(start<end){ while(sys<num[end]&end>left){// 从右端开始,找到一个比基数小的 end--; } if(sys>num[end]){// 找到后替换 num[start] = num[end]; start++; } while(sys>num[start]&&start<right){// 然后再从左端开始,找到一个比基数大的 start++; } if(sys<num[start]){// 判断比基数大,替换 num[end] = num[start]; end--; } } num[start] = sys;// 当start==end时,说明已经给替换完了,把基数放到中间。 if(left<start-1){// 递归左边的 quickSort(num,left,start-1); } if(right>start+1){// 递归右边的 quickSort(num,start+1,right); } } public static void main(String[] args){ int[] arr = {3,5,7,1,4,2,8,6,9}; quickSort(arr,0,arr.length-1); for(int a:arr){ System.out.print(a + " "); } } }
package com.tarea.entidades; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Cliente { @Id @GeneratedValue private int id; private String nombre; private String apellidoP; private String apellidoM; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="PAis_ID") private Pais pais; public Cliente() { } public Cliente(String nombre, String apellidoP, String apellidoM, Pais pais) { super(); this.nombre = nombre; this.apellidoP = apellidoP; this.apellidoM = apellidoM; this.pais = pais; } public Pais getPais() { return pais; } public void setPais(Pais pais) { this.pais = pais; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidoP() { return apellidoP; } public void setApellidoP(String apellidoP) { this.apellidoP = apellidoP; } public String getApellidoM() { return apellidoM; } public void setApellidoM(String apellidoM) { this.apellidoM = apellidoM; } }
package com.castis.util; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Value; /** * @author Leftie */ public class FilePolling { static final Log log = LogFactory.getLog(FilePolling.class); static final String DIR_SEPARATOR = File.separator; static final int INIT_SCHEDULE_TIME = 1000; // 매 1000 ms 마다 초기화를 시도한다. final ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1); @Value("#{propertyConfigurer['fileSizeCheckInterval']}") private long fileSizeCheckInterval; String targetFileDirectory; String backupFileDirectory; String faildFileDirectory; boolean moveFile = true; String filter; String categorySubDirectory; String allCategorySubDirectory; String channelSubDirectory; String viewCountSubDirectiory; public void setCategorySubDir(String categorySubDir){ this.categorySubDirectory = categorySubDir; } public void setAllCategorySubDir(String allCategorySubDir){ this.allCategorySubDirectory = allCategorySubDir; } public void setChannelSubDir(String channelSubDir){ this.channelSubDirectory = channelSubDir; } public void setViewCountSubDir(String viewCountSubDir){ this.viewCountSubDirectiory = viewCountSubDir; } public void setFilter(String filter) { this.filter = filter; } public void setMoveFile(boolean moveFile) { this.moveFile = moveFile; } public void setTargetFileDirectory(String targetFileDirectory) { this.targetFileDirectory = getValidFileDirectory(targetFileDirectory); } public void setBackupFileDirectory(String backupFileDirectory) { this.backupFileDirectory = getValidFileDirectory(backupFileDirectory); } public void setFaildFileDirectory(String faildFileDirectory) { this.faildFileDirectory = getValidFileDirectory(faildFileDirectory); } void triggerInitialization() { final Runnable initializer = new Runnable() { public void run() { initialize(); } }; scheduler.schedule(initializer, INIT_SCHEDULE_TIME, TimeUnit.MILLISECONDS); } void initialize() { } public boolean checkMadeFolder(){ try{ String temp = targetFileDirectory + "/temp/"; File tempDir = new File(CiFileUtil.getReplaceFullPath(temp)); if(!tempDir.isDirectory()){ CiFileUtil.createDirectory(temp); } String region = targetFileDirectory + "/region/"; File regionDir = new File(CiFileUtil.getReplaceFullPath(region)); if(!regionDir.isDirectory()){ CiFileUtil.createDirectory(region); } String viewCount = targetFileDirectory + "/viewCount/"; File viewCountDir = new File(CiFileUtil.getReplaceFullPath(viewCount)); if(!viewCountDir.isDirectory()){ CiFileUtil.createDirectory(viewCount); } String viewCountSubDir [] = viewCountSubDirectiory.split(","); for(int i=0; i<viewCountSubDir.length; i++){ String dir = viewCount + viewCountSubDir[i]; File viewCountSub = new File(CiFileUtil.getReplaceFullPath(dir)); if(!viewCountSub.isDirectory()){ CiFileUtil.createDirectory(dir); } } String content = targetFileDirectory + "/content/"; File contentDir = new File(CiFileUtil.getReplaceFullPath(content)); if(!contentDir.isDirectory()){ CiFileUtil.createDirectory(content); } String clientUI = targetFileDirectory + "/clientUI/"; File clientUIDir = new File(CiFileUtil.getReplaceFullPath(clientUI)); if(!clientUIDir.isDirectory()){ CiFileUtil.createDirectory(clientUI); } String channel = targetFileDirectory + "/channel/"; File channelDir = new File(CiFileUtil.getReplaceFullPath(channel)); if(!channelDir.isDirectory()){ CiFileUtil.createDirectory(channel); } String channelSubDir [] = channelSubDirectory.split(","); for(int i=0; i<channelSubDir.length; i++){ String dir = channel + channelSubDir[i]; File channelSub = new File(CiFileUtil.getReplaceFullPath(dir)); if(!channelSub.isDirectory()){ CiFileUtil.createDirectory(dir); } } String category = targetFileDirectory + "/category/"; File categoryDir = new File(CiFileUtil.getReplaceFullPath(category)); if(!categoryDir.isDirectory()){ CiFileUtil.createDirectory(category); } String categorySubDir [] = categorySubDirectory.split(","); for(int i=0; i<categorySubDir.length; i++){ String dir = category + categorySubDir[i]; File categorySub = new File(CiFileUtil.getReplaceFullPath(dir)); if(!categorySub.isDirectory()){ CiFileUtil.createDirectory(dir); } } String allCategory = targetFileDirectory + "/allCategory/"; File allCategoryDir = new File(CiFileUtil.getReplaceFullPath(allCategory)); if(!allCategoryDir.isDirectory()){ CiFileUtil.createDirectory(allCategory); } String allCategorySubDir [] = allCategorySubDirectory.split(","); for(int i=0; i<allCategorySubDir.length; i++){ String dir = allCategory + allCategorySubDir[i]; File allCategorySub = new File(CiFileUtil.getReplaceFullPath(dir)); if(!allCategorySub.isDirectory()){ CiFileUtil.createDirectory(dir); } } return true; }catch (Exception e) { log.error("make directory fail :" + e.getMessage()); return false; } } public List<File> folderFileList(String targetDir) { try { List<File> fileList = new ArrayList<File>(); if (targetDir == null) return null; File directory = new File(CiFileUtil.getReplaceFullPath(targetDir)); if (!directory.isDirectory()) { log.error(targetDir + " is not directory. cannot getting file list."); return null; } if(filter == null || filter.length() == 0){ filter = "*.*"; } FileFilter filefilter = new WildcardFileFilter(filter); if(directory.getName().equals("temp")){ File fileNDirList[] = directory.listFiles(filefilter); Arrays.sort(fileNDirList, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR); for (File file : fileNDirList) { if (file.isFile() == true) { fileList.add(file); } } }else{ File soFolderList[] = directory.listFiles(); for(File soFolder : soFolderList){ if(soFolder.isDirectory() == true && soFolder.getName().equals("temp") == false){ File fileNDirList[] = soFolder.listFiles(filefilter); Arrays.sort(fileNDirList, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR); for (File file : fileNDirList) { if (file.isFile() == true) { fileList.add(file); }else if(file.isDirectory() == true){ File subFileList [] = file.listFiles(); for(File subFile : subFileList){ if (subFile.isFile() == true) { fileList.add(subFile); } } } } } } } return fileList; } catch (Exception e) { log.error("Fail to get Folder File List. Dir = " + targetDir); return null; } } public List<File> getTargetFileList() { String tempDir = CiFileUtil.getReplaceFullPath(targetFileDirectory) + "temp/"; //타겟 경로의 파일 조회 List<File> fileList = folderFileList(targetFileDirectory); List<File> oldTempfileList = folderFileList(tempDir); List<File> resultTempFileList = null; if (fileList == null && oldTempfileList == null) { return null; } //타겟 경로의 파일이 있는 경우 if(fileList.size() > 0){ //임시 경로의 파일이 있으면 임시경로의 파일을 먼저 처리 if(oldTempfileList!=null && oldTempfileList.size() > 0){ //임시경로의 파일을 반환 resultTempFileList = oldTempfileList; } else { //타겟 경로의 파일을 임시 경로로 옮긴다. if(fileList!=null){ for (File file : fileList) { String subName = ""; String parentName = ""; try { subName = file.getParentFile().getName(); if(subName.equals("temp") == true){ subName = ""; }else{ String categorySubDir [] = categorySubDirectory.split(","); String allCategorySubDir [] = allCategorySubDirectory.split(","); String channelSubDir [] = channelSubDirectory.split(","); String viewCountSubDir [] = viewCountSubDirectiory.split(","); boolean found = false; for(int i=0; i<categorySubDir.length; i++){ if( categorySubDir[i].equals(subName) ){ found = true; break; } } if(found == false){ for(int i=0; i<allCategorySubDir.length; i++){ if( allCategorySubDir[i].equals(subName) ){ found = true; break; } } } if(found == false){ for(int i=0; i<channelSubDir.length; i++){ if( channelSubDir[i].equals(subName) ){ found = true; break; } } } if(found == false){ for(int i=0; i<viewCountSubDir.length; i++){ if( viewCountSubDir[i].equals(subName) ){ found = true; break; } } } if(found == true) parentName = file.getParentFile().getParentFile().getName(); } String curDate = DateUtil.date2String( new Date(System.currentTimeMillis()), "yyyyMMddHHmmss"); if(fileSizeCheck(file, fileSizeCheckInterval ) == false){ log.info(file.getName() + " file is writing.."); continue; } String fileName = file.getName(); String newFileName = fileName; int index = fileName.lastIndexOf("."); if (index != -1) { String fileHeader = fileName.substring(0, index); String ext = fileName.substring(index + 1); newFileName = parentName+"-"+subName+"_" + curDate + "_" + fileHeader; newFileName = newFileName + "." + ext; } CiFileUtil.renameFile(file, tempDir, newFileName); } catch (Exception e) { log.error(e.getMessage()); return null; } } } resultTempFileList = folderFileList(tempDir); } } //타겟 경로의 파일이 없고 임시 경로의 파일이 있는 경우 else{ //임시경로의 파일을 반환 resultTempFileList = oldTempfileList; } return resultTempFileList; } //fileSize 비교. public boolean fileSizeCheck(File f1, long fileSizeCheckInterval) throws Exception { long beforeFileSize = getFileSize(f1); Thread.sleep(fileSizeCheckInterval); long afterFileSize = getFileSize(f1); if(beforeFileSize==afterFileSize) return true; else return false; } // fileSize(byte 단위) public long getFileSize(File f1) throws Exception { if(f1.exists()) return f1.length(); else throw new Exception("file not Exist"); } public void moveProcessedFile(File file, String resultDir, String cause) { if (moveFile == false) { log.info("file move cancel " + file.getName()); return; } // 파일이름에 작업일추가 String curDate = DateUtil.date2String( new Date(System.currentTimeMillis()), "yyyyMMddHHmmss"); String fileType = ""; String fileName = file.getName(); if(fileName.startsWith("-")){ int fileIndex = fileName.indexOf("-"); if(fileIndex != -1){ fileName = fileName.substring(fileIndex+1, fileName.length()); } }else if(fileName.startsWith("channel-")){ int fileIndex = fileName.indexOf("-"); if(fileIndex != -1){ fileName = fileName.substring(fileIndex+1, fileName.length()); } fileType = "channel"; }else if(fileName.startsWith("category-")){ int fileIndex = fileName.indexOf("-"); if(fileIndex != -1){ fileName = fileName.substring(fileIndex+1, fileName.length()); } fileType = "category"; }else if(fileName.startsWith("allCategory-")){ int fileIndex = fileName.indexOf("-"); if(fileIndex != -1){ fileName = fileName.substring(fileIndex+1, fileName.length()); } fileType = "allCategory"; }else if(fileName.startsWith("viewCount-")){ int fileIndex = fileName.indexOf("-"); if(fileIndex != -1){ fileName = fileName.substring(fileIndex+1, fileName.length()); } fileType = "viewCount"; } String parentName = file.getParentFile().getParentFile().getName(); if(parentName.equals("channel")){ fileType = "channel"; }else if(parentName.equals("category")){ fileType = "category"; }else if(parentName.equals("allCategory")){ fileType = "allCategory"; }else if(parentName.equals("viewCount")){ fileType = "viewCount"; } String newFileName = fileName; int index = fileName.indexOf("_"); if( index != -1 ){ String directory = fileName.substring(0, index); fileName = fileName.substring(index+1); if(fileType.equals("channel")){ resultDir += "channel/" + directory; }else if(fileType.equals("category")){ resultDir += "category/" + directory; }else if(fileType.equals("allCategory")){ resultDir += "allCategory/" + directory; }else if(fileType.equals("viewCount")){ resultDir += "viewCount/" + directory; }else{ resultDir += directory; } } File targetDirectory = new File(CiFileUtil.getReplaceFullPath(resultDir)); if(!targetDirectory.isDirectory()){ CiFileUtil.createDirectory(resultDir); } index = fileName.lastIndexOf("."); if (index != -1) { String name = fileName.substring(0, index); String ext = fileName.substring(index + 1); if(cause == null || cause.length() == 0) newFileName = name + "_" + curDate; else newFileName = name + "_error_" + cause +"_"+ curDate; newFileName = newFileName + "." + ext; } file.setLastModified(System.currentTimeMillis()); // Move file to new directory try { CiFileUtil.renameFile(file, resultDir, newFileName); } catch (Exception e) { log.error(e.getMessage()); } } public String getValidFileDirectory(String dirName) { // dirName의 끝에 디렉토리 구분자('/' 또는 '\')가 붙지 않았으면 이를 추가한다. if (dirName.length() > 0 && dirName.substring(dirName.length() - 1) .equals(DIR_SEPARATOR) == false) { dirName += DIR_SEPARATOR; } return dirName; } public void moveSuccessFile(File file) { moveProcessedFile(file, backupFileDirectory, null); } public void moveFailFile(File file, String cause, String resultDir) { moveProcessedFile(file, faildFileDirectory, cause); File resultFile = new File(CiFileUtil.getReplaceFullPath(resultDir), file.getName()); resultFile.delete(); } }
package com.example.canyetismis.runningtracker; import android.net.Uri; public class DBProviderContract { final static String AUTHORITY = "com.example.canyetismis.runningtracker.DBContentProvider"; final static Uri URI_MAIN = Uri.parse("content://" + AUTHORITY); public static final String TABLE_NAME = "myList"; public static final String _ID = "_id"; public static final String AVG_SPEED = "avgSpeed"; public static final String MAX_SPEED = "maxSpeed"; public static final String TOTAL_DISTANCE = "totalDistance"; public static final String TOTAL_DURATION = "totalDuration"; public static final String DATE = "date"; public static final String TIME = "time"; }
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.secretsmanager.caching.cache; import java.util.concurrent.ThreadLocalRandom; import com.amazonaws.secretsmanager.caching.SecretCacheConfiguration; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; /** * Basic secret caching object. */ public abstract class SecretCacheObject<T> { /** The number of milliseconds to wait after an exception. */ private static final long EXCEPTION_BACKOFF = 1000; /** The growth factor of the backoff duration. */ private static final long EXCEPTION_BACKOFF_GROWTH_FACTOR = 2; /** * The maximum number of milliseconds to wait before retrying a failed * request. */ private static final long BACKOFF_PLATEAU = EXCEPTION_BACKOFF * 128; /** * When forcing a refresh using the refreshNow method, a random sleep * will be performed using this value. This helps prevent code from * executing a refreshNow in a continuous loop without waiting. */ private static final long FORCE_REFRESH_JITTER_SLEEP = 5000; /** The secret identifier for this cached object. */ protected final String secretId; /** A private object to synchronize access to certain methods. */ protected final Object lock = new Object(); /** The AWS Secrets Manager client to use for requesting secrets. */ protected final SecretsManagerClient client; /** The Secret Cache Configuration. */ protected final SecretCacheConfiguration config; /** A flag to indicate a refresh is needed. */ private boolean refreshNeeded = true; /** The result of the last AWS Secrets Manager request for this item. */ private Object data = null; /** * If the last request to AWS Secrets Manager resulted in an exception, * that exception will be thrown back to the caller when requesting * secret data. */ protected RuntimeException exception = null; /** * The number of exceptions encountered since the last successfully * AWS Secrets Manager request. This is used to calculate an exponential * backoff. */ private long exceptionBackoffPower = 0; /** * The time to wait before retrying a failed AWS Secrets Manager request. */ private long nextRetryTime = 0; /** * Construct a new cached item for the secret. * * @param secretId * The secret identifier. This identifier could be the full ARN * or the friendly name for the secret. * @param client * The AWS Secrets Manager client to use for requesting the secret. * @param config * The secret cache configuration. */ public SecretCacheObject(final String secretId, final SecretsManagerClient client, final SecretCacheConfiguration config) { this.secretId = secretId; this.client = client; this.config = config; } /** * Execute the actual refresh of the cached secret state. * * @return The result of the refresh */ protected abstract T executeRefresh(); /** * Execute the actual refresh of the cached secret state. * * @param result * The AWS Secrets Manager result for the secret state. * @return The cached GetSecretValue result based on the current * cached state. */ protected abstract GetSecretValueResponse getSecretValue(T result); public abstract boolean equals(Object obj); public abstract int hashCode(); public abstract String toString(); /** * Return the typed result object * * @return the result object */ @SuppressWarnings("unchecked") private T getResult() { if (null != this.config.getCacheHook()) { return (T)this.config.getCacheHook().get(this.data); } return (T)this.data; } /** * Store the result data. */ private void setResult(T result) { if (null != this.config.getCacheHook()) { this.data = this.config.getCacheHook().put(result); } else { this.data = result; } } /** * Determine if the secret object should be refreshed. * * @return True if the secret item should be refreshed. */ protected boolean isRefreshNeeded() { if (this.refreshNeeded) { return true; } if (null != this.exception) { // If we encountered an exception on the last attempt // we do not want to keep retrying without a pause between // the refresh attempts. // // If we have exceeded our backoff time we will refresh // the secret now. if (System.currentTimeMillis() >= this.nextRetryTime) { return true; } // Don't keep trying to refresh a secret that previously threw // an exception. return false; } return false; } /** * Refresh the cached secret state only when needed. */ private void refresh() { if (!this.isRefreshNeeded()) { return; } this.refreshNeeded = false; try { this.setResult(this.executeRefresh()); this.exception = null; this.exceptionBackoffPower = 0; } catch (RuntimeException ex) { this.exception = ex; // Determine the amount of growth in exception backoff time based on the growth // factor and default backoff duration. Long growth = 1L; if (this.exceptionBackoffPower > 0) { growth = (long)Math.pow(EXCEPTION_BACKOFF_GROWTH_FACTOR, this.exceptionBackoffPower); } growth *= EXCEPTION_BACKOFF; // Add in EXCEPTION_BACKOFF time to make sure the random jitter will not reduce // the wait time too low. Long retryWait = Math.min(EXCEPTION_BACKOFF + growth, BACKOFF_PLATEAU); if ( retryWait < BACKOFF_PLATEAU ) { // Only increase the backoff power if we haven't hit the backoff plateau yet. this.exceptionBackoffPower += 1; } // Use random jitter with the wait time retryWait = ThreadLocalRandom.current().nextLong(retryWait / 2, retryWait + 1); this.nextRetryTime = System.currentTimeMillis() + retryWait; } } /** * Method to force the refresh of a cached secret state. * * @return True if the refresh completed without error. * @throws InterruptedException * If the thread is interrupted while waiting for the refresh. */ public boolean refreshNow() throws InterruptedException { this.refreshNeeded = true; // When forcing a refresh, always sleep with a random jitter // to prevent coding errors that could be calling refreshNow // in a loop. long sleep = ThreadLocalRandom.current() .nextLong( FORCE_REFRESH_JITTER_SLEEP / 2, FORCE_REFRESH_JITTER_SLEEP + 1); // Make sure we are not waiting for the next refresh after an // exception. If we are, sleep based on the retry delay of // the refresh to prevent a hard loop in attempting to refresh a // secret that continues to throw an exception such as AccessDenied. if (null != this.exception) { long wait = this.nextRetryTime - System.currentTimeMillis(); sleep = Math.max(wait, sleep); } Thread.sleep(sleep); // Perform the requested refresh synchronized (lock) { refresh(); return (null == this.exception); } } /** * Return the cached result from AWS Secrets Manager for GetSecretValue. * * @return The cached GetSecretValue result. */ public GetSecretValueResponse getSecretValue() { synchronized (lock) { refresh(); if (null == this.data) { if (null != this.exception) { throw this.exception; } } return this.getSecretValue(this.getResult()); } } }
package dnswithfriends.util; import java.util.regex.Pattern; /** * Librarie of utilities */ public class Util{ public static final String ipv4_format = "\\b((25[0–5]|2[0–4]\\d|[01]?\\d\\d?)(\\.)){3}(25[0–5]|2[0–4]\\d|[01]?\\d\\d?)\\b"; public static final int port_top = 65535; /** * Just check if the IP is in the right format (0-255].[0-255].[0-255].[0-255] * @param ip to check */ static public boolean validateIp(String ip){ return Pattern.matches(ipv4_format, ip); } /** * Just check if the port it the right range (0,65535] * @param port to check */ static public boolean validatePort(int port){ return (port <= port_top) && (port > 0); } }
package hello.configs; import java.io.IOException; import org.springframework.context.ApplicationContextAware; import org.springframework.context.MessageSourceAware; import javafx.fxml.Initializable; import javafx.scene.Node; public interface BootInitializable extends Initializable, ApplicationContextAware, MessageSourceAware { public Node initView() throws IOException; // public void setStage(Stage stage); public void initConstuct(); // public void initIcons(); }
package com.madrapps.dagger.qualifiers; import com.madrapps.dagger.models.Cycle; import com.madrapps.dagger.models.Road; import com.madrapps.dagger.models.Truck; import com.madrapps.dagger.models.Vehicle; import dagger.Module; import dagger.Provides; @Module public class QualifierModule { @Provides static Road mountainRoad(@Red Vehicle one, @Green Vehicle two) { return new MountainRoad(one, two); } @Provides @Red static Vehicle red() { return new Truck(); } @Provides @Red static Truck truck() { return new Truck(); } @Provides @Green static Vehicle green() { return new Cycle(); } }
package com.david.secretsanta.models; import java.util.Objects; public class SecretSantaRelationship { private final PersonFamily personFamily; private final PersonFamily secretSanta; public SecretSantaRelationship(PersonFamily personFamily, PersonFamily secretSanta) { this.personFamily = personFamily; this.secretSanta = secretSanta; } public PersonFamily getPersonFamily() { return personFamily; } public PersonFamily getSecretSanta() { return secretSanta; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SecretSantaRelationship that = (SecretSantaRelationship) o; return Objects.equals(personFamily, that.personFamily) && Objects.equals(secretSanta, that.secretSanta); } @Override public int hashCode() { return Objects.hash(personFamily, secretSanta); } @Override public String toString() { return "SecretSantaRelationship{" + "personFamily=" + personFamily + ", secretSanta=" + secretSanta + '}'; } }
package cl.laPalmera.DTO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.apache.log4j.Logger; import cl.laPalmera.connection.ConnectionLaPalmera; public class AreaDTO { private static final Logger LOGGER = Logger.getLogger(AreaDTO.class); private String codigoArea=""; private String nombreArea=""; public void grabar() { try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "insert into Area values ("; sql = sql + "'"+codigoArea +"',"; sql = sql + "'"+nombreArea +"')"; //LOGGER.debug(sql); int i = stmt.executeUpdate(sql); if (i == 1) LOGGER.debug("OK"); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } } public void modificar() { try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "update area set "; sql = sql + "codigoarea = '"+codigoArea +"', "; sql = sql + "nombrearea = "+"'"+nombreArea +"' where codigoarea = '"+codigoArea+"'"; //LOGGER.debug(sql); int i = stmt.executeUpdate(sql); if (i == 1) LOGGER.debug("OK"); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } } public void eliminar() { try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "delete from area where "; sql = sql + "codigoarea = '"+codigoArea +"'"; //LOGGER.debug(sql); int i = stmt.executeUpdate(sql); if (i == 1) LOGGER.debug("OK"); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } } public boolean buscar() { boolean resultado = false; try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "select * from area where codigoarea = '"+codigoArea+"'"; //LOGGER.debug(sql); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { LOGGER.debug("Lo encontro"); codigoArea= rs.getString(1); nombreArea= rs.getString(2); resultado = true; } rs.close(); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } return resultado; } public String getCodigoArea() { return codigoArea; } public void setCodigoArea(String codigoArea) { this.codigoArea = codigoArea; } public String getNombreArea() { return nombreArea; } public void setNombreArea(String nombreArea) { this.nombreArea = nombreArea; } }
package seedu.project.logic.commands; import static java.util.Objects.requireNonNull; import javafx.collections.ObservableList; import seedu.project.commons.core.Messages; import seedu.project.logic.CommandHistory; import seedu.project.logic.LogicManager; import seedu.project.logic.commands.exceptions.CommandException; import seedu.project.model.Model; import seedu.project.model.project.Project; import seedu.project.model.tag.Tag; import seedu.project.model.task.Task; /** * Finds and lists all completed tasks in project. */ public class AnalyseCommand extends Command { public static final String COMMAND_WORD = "analyse"; public static final String COMMAND_ALIAS = "an"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all completed tasks of a project and displays them as a list with index numbers.\n" + "Example: " + COMMAND_WORD; @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { requireNonNull(model); ObservableList<Project> filteredProjects = model.getFilteredProjectList(); String toPrint = ""; if (!LogicManager.getState()) { for (Project project: filteredProjects) { int countCompleted = 0; int numTasksPerProject = 0; float percentageCompleted; toPrint += project.getName().toString() + ": "; ObservableList<Task> filteredTasks = project.getTaskList(); for (Task task : filteredTasks) { if (task.getTags().contains(new Tag("completed"))) { countCompleted += 1; } numTasksPerProject += 1; } toPrint += countCompleted + " tasks completed. "; if (numTasksPerProject == 0) { percentageCompleted = 0; } else { percentageCompleted = ((float) countCompleted / (float) numTasksPerProject) * 100; } toPrint += "(Percentage of project completed: " + String.format("%.1f", percentageCompleted) + "%)\n"; } return new CommandResult(toPrint); } else { throw new CommandException(String.format(Messages.MESSAGE_RETURN_TO_PROJECT_LEVEL, COMMAND_WORD)); } } }
package com.example.adimn.myapplication; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class ResetPassword extends AppCompatActivity { EditText et_newpassword,et_confirmpassword; Button bt_confirm; String mobile,password; ImageView img_logo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reset_password); img_logo=(ImageView)findViewById(R.id.img_logo); img_logo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(ResetPassword.this ,VerifyOtp.class); startActivity(i); } }); SharedPreferences pref = getApplicationContext().getSharedPreferences("forgot",0); mobile = pref.getString("mobile","No Mobile was stored"); et_newpassword = (EditText)findViewById(R.id.et_newpassword); et_confirmpassword = (EditText)findViewById(R.id.et_confirmpassword); bt_confirm = (Button)findViewById(R.id.bt_Confirm); bt_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (et_newpassword.getText().toString().equals("")) { Validations.MyAlertBox(ResetPassword.this, "Please Enter Password"); et_newpassword.requestFocus(); } else if (et_confirmpassword.getText().toString().equals("")) { Validations.MyAlertBox(ResetPassword.this, "Please Re-Enter Password"); et_confirmpassword.requestFocus(); } String password = et_newpassword.getText().toString(); String newpassword = et_confirmpassword.getText().toString(); if (password.equals(newpassword)){ Validations.MyAlertBox(ResetPassword.this,"Password Match"); } else { Validations.MyAlertBox(ResetPassword.this,"Password Does Not Match "); } // new ResetPassword.newpassword(et_newpassword.getText().toString()).execute(); reset(); Intent i = new Intent(ResetPassword.this,LoginForm.class); startActivity(i); } }); } public void reset() { password = et_newpassword.getText().toString(); RequestQueue queue = Volley.newRequestQueue(ResetPassword.this); String url = "https://www.nandikrushi.in/services/forgotpassword.php"; final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONArray jsonArray = new JSONArray(); JSONObject object = new JSONObject(response); JSONObject jsonObject=object.getJSONObject("forgotstatus"); String status=jsonObject.getString("status"); if (status.contains("1")) { // String farmerid= jsonObject.getString("farmerid"); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ResetPassword.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Password Has Changed Successfully"); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(ResetPassword.this, LoginForm.class)); dialogInterface.dismiss(); /* Intent login = new Intent(ForgetPassword.this, VerifyOtp.class); startActivity(login); finish();*/ } }).show(); }else { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ResetPassword.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Password Entered Mismatch"); builder.setPositiveButton(R.string.ok, null).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mprocessingdialog.dismiss(); // Snackbar.make(linear, "Error in Connection", Snackbar.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { int request=3; String request_id= Integer.toString(request); Map<String, String> params = new HashMap<>(); params.put("mobile", mobile); params.put("password",password); params.put("request_id",request_id); Log.d("mobile", mobile); Log.d("request_id", request_id); return params; } }; int socketTimeout = 60000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); stringRequest.setRetryPolicy(policy); queue.add(stringRequest); } /* private class newpassword extends AsyncTask<String, String,JSONObject> { private ArrayList<NameValuePair> nameValuePairs; private JSONObject json; String password; int request=3; String request_id= Integer.toString(request); public newpassword(String password){ this.password= password; } protected void onPreExecute() { super.onPreExecute(); } @Override protected JSONObject doInBackground(String... strings) { nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("password", password)); nameValuePairs.add(new BasicNameValuePair("mobile", mobile)); nameValuePairs.add(new BasicNameValuePair("request_id",request_id)); json = JSONParser.makeServiceCall("https://www.nandikrushi.in/services/forgotpassword.php", 2, nameValuePairs); return json; } @Override protected void onPostExecute(JSONObject jsonObject) { String status = "1"; // super.onPostExecute(jsonObject); // Toast.makeText(getBaseContext(),jsonObject.toString(), Toast.LENGTH_SHORT).show(); try { JSONArray jsonArray = new JSONArray(); JSONObject data = jsonObject.getJSONObject("forgotstatus"); status = data.getString("status"); System.out.println("jsonarray is" + jsonObject); if (status.equalsIgnoreCase("1")) { System.out.println("status is " + status) ; Toast.makeText(getBaseContext(), data.toString(), Toast.LENGTH_SHORT).show(); *//*Log.d("password",data.getString("password").toString()); Log.d("mobile",data.getString("mobile").toString()); Log.d("request_id",data.getString("request_id").toString());*//* *//*Intent signup = new Intent(NewPassword.this, LoginScreen.class); startActivity(signup); finish();*//* overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ResetPassword.this); builder.setTitle("Nandi Krushi...!"); builder.setMessage("Password Has Changed Successfully"); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(ResetPassword.this, LoginForm.class)); dialogInterface.dismiss(); } }).show(); } else { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ResetPassword.this); builder.setTitle("Nandi Krushi...!"); builder.setMessage("Password Entered Mismatch"); builder.setPositiveButton(R.string.ok, null).show(); } }catch (JSONException e){ e.printStackTrace(); } } } */ //******* HIDING KEYBOARD ********** @Override public boolean dispatchTouchEvent(MotionEvent ev) { View v = getCurrentFocus(); if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText && !v.getClass().getName().startsWith("android.webkit.")) { int scrcoords[] = new int[2]; v.getLocationOnScreen(scrcoords); float x = ev.getRawX() + v.getLeft() - scrcoords[0]; float y = ev.getRawY() + v.getTop() - scrcoords[1]; if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) Validations.hideKeyboard(this); } return super.dispatchTouchEvent(ev); } boolean doubleBackToExitPressedOnce = false; @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } }
package com.twofactorauth.control.rest.user; import com.twofactorauth.entity.MessageModel; import com.twofactorauth.entity.UserModel; import io.swagger.v3.oas.annotations.tags.Tag; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/users") @Tag(name = "Users") /** * Flow * 1.Login * 2.Check if 2FA enabled * 3.If true 2 above iniate2FA and watch request * 4.If response true 3 above, terminate watch and move to next */ public interface UserRestFacadeI { /** * * @param userModel model * @return */ @POST @Consumes(value = {MediaType.APPLICATION_JSON}) @Produces(value = {MediaType.APPLICATION_JSON}) MessageModel createUser(UserModel userModel); /** * * @param userName userName * @param pwd pwd * @return */ @POST @Consumes(value = {MediaType.APPLICATION_JSON}) @Produces(value = {MediaType.APPLICATION_JSON}) @Path("/login/{username}/{pwd}") MessageModel getUser(@PathParam("username")String userName,@PathParam("pwd") String pwd); /** * Update user token * @param id userId * @param token token * @return */ @POST @Consumes(value = {MediaType.APPLICATION_JSON}) @Produces(value = {MediaType.APPLICATION_JSON}) @Path("/updateToken/{id}/{token}") MessageModel updateToken(@PathParam("id")Long id,@PathParam("token") String token); /** * * @param id userId * @param isAllowed true or false * @return */ @POST @Consumes(value = {MediaType.APPLICATION_JSON}) @Produces(value = {MediaType.APPLICATION_JSON}) @Path("/updateAccess/{id}/{isAllowed}") MessageModel updateAccess(@PathParam("id")Long id,@PathParam("isAllowed") boolean isAllowed); /** * * @param id userId * @return */ @GET @Path("/requestStatus/{id}") @Produces(value = {MediaType.APPLICATION_JSON}) MessageModel requestStatus(@PathParam("id")Long id); /** * * @param id * @param token * @return */ @POST @Consumes(value = {MediaType.APPLICATION_JSON}) @Produces(value = {MediaType.APPLICATION_JSON}) @Path("/iniate2FA/{id}/{token}") MessageModel iniate2FA(@PathParam("id") Long id,@PathParam("token") String token); }
package com.vpt.pw.demo.model.FormCrf3a; import com.vpt.pw.demo.model.PregnantWoman; import com.vpt.pw.demo.model.Studies; import com.vpt.pw.demo.model.Team; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Entity @Table(name = "FORM_CRF_3A") public class FormCrf3a { @Id @GeneratedValue( strategy = GenerationType.AUTO, generator = "native" ) @GenericGenerator( name = "native", strategy = "native" ) @Column(name = "form_crf_3a_id") private Integer id; @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "assis_id") private PregnantWoman pregnantWoman; @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "team_id") private Team team; @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "study_id") private Studies studies; @Column(name = "pw_crf_3a_2") private String q02; @Column(name = "pw_crf_3a_3") private String q03; @Column(name = "pw_crf_3a_4") private String q4; @Column(name = "pw_crf_3a_14") private String q14; @Column(name = "pw_crf_3a_15") private String q15; @Column(name = "pw_crf_3a_16") private String q16; @Column(name = "pw_crf_3a_17") private String q17; @Column(name = "pw_crf_3a_18") private String q18; @Column(name = "pw_crf_3a_19") private String q19; @Column(name = "pw_crf_3a_20") private String q20; @Column(name = "pw_crf_3a_21") private String q21; @Column(name = "pw_crf_3a_22") private String q22; @Column(name = "pw_crf_3a_23") private String q23; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public PregnantWoman getPregnantWoman() { return pregnantWoman; } public void setPregnantWoman(PregnantWoman pregnantWoman) { this.pregnantWoman = pregnantWoman; } public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } public String getQ02() { return q02; } public void setQ02(String q02) { this.q02 = q02; } public String getQ03() { return q03; } public void setQ03(String q03) { this.q03 = q03; } public String getQ4() { return q4; } public void setQ4(String q4) { this.q4 = q4; } public String getQ14() { return q14; } public void setQ14(String q14) { this.q14 = q14; } public String getQ15() { return q15; } public void setQ15(String q15) { this.q15 = q15; } public String getQ16() { return q16; } public void setQ16(String q16) { this.q16 = q16; } public String getQ17() { return q17; } public void setQ17(String q17) { this.q17 = q17; } public String getQ18() { return q18; } public void setQ18(String q18) { this.q18 = q18; } public String getQ19() { return q19; } public void setQ19(String q19) { this.q19 = q19; } public String getQ20() { return q20; } public void setQ20(String q20) { this.q20 = q20; } public String getQ21() { return q21; } public void setQ21(String q21) { this.q21 = q21; } public String getQ22() { return q22; } public void setQ22(String q22) { this.q22 = q22; } public String getQ23() { return q23; } public void setQ23(String q23) { this.q23 = q23; } public Studies getStudies() { return studies; } public void setStudies(Studies studies) { this.studies = studies; } }
package String_Level1.Programming_Questions; import java.util.Scanner; public class P19 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String S=""; for(int j=0;j<s.length();j++) { if(j==0) { char ch=Character.toTitleCase(s.charAt(j)); S=S.concat(Character.toString(ch)); } else if( s.charAt(j)==' ') { S=S+" "; char ch=Character.toTitleCase(s.charAt(j+1)); S=S.concat(Character.toString(ch)); j++; } else { S=S+s.charAt(j); } } System.out.println(S); } }
package com.company.controllers; import java.util.Scanner; public class Menu { private Scanner sn; private String word; private boolean show = true; public Menu() { Scanner _sn = new Scanner(System.in); this.sn = _sn; } public void Show() { while (show) { System.out.println("********************"); System.out.println("1. Cambiar primera y ultima letra"); System.out.println("2. Revolver todas las letras"); System.out.println("3. Salir"); System.out.println("********************"); int opt = sn.nextInt(); this.sn.nextLine(); this.Choose(opt); } } private void InputWord() { System.out.println("Ingrese una palabra"); this.word = this.sn.nextLine(); // Obtener el input del usuario } private void Choose(int opt) { switch (opt) { case 1: this.InputWord(); Words.SwapFirstLastLetters(word); break; case 2: this.InputWord(); Words.ScrambleLetters(word); break; case 3: this.show = false; break; default: System.out.println("Seleccione una opción: "); break; } } }
package com.apress.prospring4.ch4; import org.springframework.context.ApplicationEvent; /** * Class of event * */ public class MessageEvent extends ApplicationEvent { private String msg; /** * Constructor * * @source - link for event source * @msg - some message, I think */ public MessageEvent(Object source, String msg) { super(source); this.msg = msg; } // for print public String getMessage() { return msg; } }
package com.atguigu.lgl; /** .请根据以下代码自行定义能满足需要的MyDate类, 在MyDate类中覆盖equals方法, 使其判断当两个MyDate类型对象的年月日都相同时,结果为true,否则为false。 public boolean equals(Object o) * public class EqualsTest { public static void main(String[] args) { MyDate m1 = new MyDate(14, 3, 1976); MyDate m2 = new MyDate(14, 3, 1976); if (m1 == m2) { System.out.println("m1==m2"); } else { System.out.println("m1!=m2"); // m1 != m2 } if (m1.equals(m2)) { System.out.println("m1 is equal to m2");// m1 is equal to m2 } else { System.out.println("m1 is not equal to m2"); } } } */ public class MyDate { public static void main(String[] args) { MyDate day1 = new MyDate(2019, 8, 9); System.out.println(day1.equals(new MyDate(2019, 8, 8))); } private int year; private int month; private int day; public MyDate(int year, int month, int day) { super(); this.year = year; this.month = month; this.day = day; } @Override public boolean equals(Object arg0) { if (this == arg0) { return true; } if (arg0 instanceof MyDate) { MyDate dd = (MyDate) arg0; return this.year == dd.year && this.month == dd.month && this.day == dd.day; } return false; } }
package com.bofsoft.laio.customerservice.DataClass.db; import com.bofsoft.laio.data.BaseData; /** * 9 培训类型 laio_class_type * * @author admin */ public class ClassTypeData extends BaseData implements Comparable<ClassTypeData> { private int Id; private String Name; // 初学培训、补训、复训 private int IsDel; // public ClassTypeData() { } public ClassTypeData(int id, String name, int isDel) { super(); Id = id; Name = name; IsDel = isDel; } public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getIsDel() { return IsDel; } public void setIsDel(int isDel) { IsDel = isDel; } @Override public int compareTo(ClassTypeData another) { if (another == null) { return -1; } return Integer.valueOf(this.Id).compareTo(Integer.valueOf(another.Id)); } }
package com.git.cloud.resmgt.common.model.vo; import com.git.cloud.common.model.base.BaseBO; /** * * @author 王成辉 * @Description 物理机表 * @date 2014-12-17 * */ public class CmHostVo extends BaseBO implements java.io.Serializable{ // Fields /** * */ private static final long serialVersionUID = 1275281277058176675L; private String id; private String cpu; private String mem; private String disk; private String cpuUsed; private String memUsed; private String clusterId; private String isInvc ; private String isBare ; private String cmHostName; private String clusterName; private String resPoolName; private String hostCpuUsed; private String hostMemUsed; private String remainingCpu; private String remainingMem; private String bmSrVmNum; private String vmNum; private String resPoolId; private String cdpId; private String hostIp; // Constructors public String getHostIp() { return hostIp; } public void setHostIp(String hostIp) { this.hostIp = hostIp; } public String getBmSrVmNum() { return bmSrVmNum; } public void setBmSrVmNum(String bmSrVmNum) { this.bmSrVmNum = bmSrVmNum; } public String getResPoolId() { return resPoolId; } public void setResPoolId(String resPoolId) { this.resPoolId = resPoolId; } public String getCdpId() { return cdpId; } public void setCdpId(String cdpId) { this.cdpId = cdpId; } public String getVmNum() { return vmNum; } public void setVmNum(String vmNum) { this.vmNum = vmNum; } public String getCmHostName() { return cmHostName; } private String ipmiPwd; private String ipmiUser; private String ipmiUrl; private String ipmiVer; public void setCmHostName(String cmHostName) { this.cmHostName = cmHostName; } /** default constructor */ public CmHostVo() { } /** minimal constructor */ public CmHostVo(String id) { this.id = id; } /** full constructor */ public CmHostVo(String id, String cpu, String mem, String disk, String cpuUsed, String memUsed, String clusterId, String duId,String isInvc,String isBare,String ipmiPwd, String ipmiUser,String ipmiUrl,String ipmiVer) { this.id = id; this.cpu = cpu; this.mem = mem; this.disk = disk; this.cpuUsed = cpuUsed; this.memUsed = memUsed; this.clusterId = clusterId; this.isBare = isBare ; this.isInvc = isInvc ; this.ipmiPwd= ipmiPwd; this.ipmiUser =ipmiUser; this.ipmiUrl=ipmiUrl; this.ipmiVer=ipmiVer; } // Property accessors public String getIpmiVer() { return ipmiVer; } public void setIpmiVer(String ipmiVer) { this.ipmiVer = ipmiVer; } public String getIpmiPwd() { return ipmiPwd; } public void setIpmiPwd(String ipmiPwd) { this.ipmiPwd = ipmiPwd; } public String getIpmiUser() { return ipmiUser; } public void setIpmiUser(String ipmiUser) { this.ipmiUser = ipmiUser; } public String getIpmiUrl() { return ipmiUrl; } public void setIpmiUrl(String ipmiUrl) { this.ipmiUrl = ipmiUrl; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } // public Integer getCpu() { // return this.cpu; // } // // public void setCpu(Integer cpu) { // this.cpu = cpu; // } // // public Integer getMem() { // return this.mem; // } // // public void setMem(Integer mem) { // this.mem = mem; // } // // public Integer getDisk() { // return this.disk; // } // // public void setDisk(Integer disk) { // this.disk = disk; // } // // public Integer getCpuUsed() { // return this.cpuUsed; // } // // public void setCpuUsed(Integer cpuUsed) { // this.cpuUsed = cpuUsed; // } // // public Integer getMemUsed() { // return this.memUsed; // } // // public void setMemUsed(Integer memUsed) { // this.memUsed = memUsed; // } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getMem() { return mem; } public void setMem(String mem) { this.mem = mem; } public String getDisk() { return disk; } public void setDisk(String disk) { this.disk = disk; } public String getCpuUsed() { return cpuUsed; } public void setCpuUsed(String cpuUsed) { this.cpuUsed = cpuUsed; } public String getMemUsed() { return memUsed; } public void setMemUsed(String memUsed) { this.memUsed = memUsed; } public String getClusterId() { return this.clusterId; } public void setClusterId(String clusterId) { this.clusterId = clusterId; } @Override public String getBizId() { // TODO Auto-generated method stub return null; } public String getIsBare() { return isBare; } public void setIsBare(String isBare) { this.isBare = isBare; } public String getIsInvc() { return isInvc; } public void setIsInvc(String isInvc) { this.isInvc = isInvc; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getResPoolName() { return resPoolName; } public void setResPoolName(String resPoolName) { this.resPoolName = resPoolName; } public String getHostCpuUsed() { return hostCpuUsed; } public void setHostCpuUsed(String hostCpuUsed) { this.hostCpuUsed = hostCpuUsed; } public String getHostMemUsed() { return hostMemUsed; } public void setHostMemUsed(String hostMemUsed) { this.hostMemUsed = hostMemUsed; } public String getRemainingCpu() { return remainingCpu; } public void setRemainingCpu(String remainingCpu) { this.remainingCpu = remainingCpu; } public String getRemainingMem() { return remainingMem; } public void setRemainingMem(String remainingMem) { this.remainingMem = remainingMem; } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ //TabPanel.java //Defines a 'tab-strip' component organizing selectable Tab objects. //Revised and enhanced by Davis Herring and Yong Tze Chi //Updated February 11 2004 //Version 3.0.6 package org.webtop.component; import java.awt.*; import java.util.*; import java.awt.event.*; public class TabPanel extends WComponent implements ActionListener { private Vector<Tab> tabs=new Vector<Tab>(4,2); private Tab active; private ActionListener listeners; public TabPanel() { setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); prefSize=new Dimension(0,0); minSize=new Dimension(0,0); } public void addTab(String title) {addTab(new Tab(title),tabs.size());} public void addTab(Tab tab) {addTab(tab,tabs.size());} public void addTab(Tab tab,int place) { if(tab==null) return; //Can't add past end of tabs if(place>tabs.size()||place<0) place=tabs.size(); tabs.insertElementAt(tab,place); tab.addActionListener(this); if(active==null) { active = tab; active.setActive(true); } super.add(tab,place); Dimension d = tab.getPreferredSize(); minSize.setSize(minSize.width+d.width, Math.max(minSize.height,d.height)); if(prefSize.width<minSize.width) prefSize.width = minSize.width; if(prefSize.height<minSize.height) prefSize.height = minSize.height; } public void removeTab(String title) {removeTab(getTab(title));} public void removeTab(int index) {removeTab(getTab(index));} public void removeTab(Tab tab) { if(tab==null) return; tabs.removeElement(tab); tab.removeActionListener(this); if(active==tab) { if(tabs.isEmpty()) active=null; else active=(Tab)tabs.firstElement(); } super.remove(tab); if(tabs.isEmpty()) prefSize=minSize=new Dimension(0,0); else { int maxHeight=0,curHeight; Enumeration ts=tabs.elements(); while(ts.hasMoreElements()) if(maxHeight<(curHeight=((Tab)ts.nextElement()).getPreferredSize().height)) maxHeight=curHeight; prefSize.setSize(prefSize.width-tab.getPreferredSize().width, maxHeight); if(minSize.height>prefSize.height) minSize.height=prefSize.height; if(minSize.width>prefSize.width) minSize.width=prefSize.width; } } //We have Container.getComponentCount() for public access... ...But that's //an implementation detail. Tabs could just be data, and we could be //painting the things. public int getTabCount() {return tabs.size();} public Tab getActiveTab() {return active;} public int getActiveIndex() {return tabs.indexOf(active);} public int indexOf(Tab tab) {return tabs.indexOf(tab);} public int indexOf(String title) { int i=0; for(;i<tabs.size()&&!((Tab)tabs.elementAt(i)).getLabel().equals(title);i++); return i==tabs.size()?-1:i; } public void setActiveTab(String title) {setActiveTab(getTab(title));} public void setActiveTab(int index) {setActiveTab((Tab)tabs.elementAt(index));} public void setActiveTab(Tab tab) { if(!tabs.contains(tab)) return; if(active!=null) active.setActive(false); active = tab; active.setActive(true); } public Tab getTab(int index) {return (Tab)tabs.elementAt(index);} public Tab getTab(String title) { Enumeration ts=tabs.elements(); while(ts.hasMoreElements()) { Tab t=(Tab)ts.nextElement(); if(t.getLabel().equals(title)) return t; } return null; } public void setTabAlignment(int alignment) { setLayout(new FlowLayout(alignment, 0, 0)); } public void addActionListener(ActionListener listener) { listeners = AWTEventMulticaster.add(listeners, listener);} public void removeActionListener(ActionListener listener) { listeners = AWTEventMulticaster.remove(listeners, listener);} public void actionPerformed(ActionEvent e) { Tab t=(Tab)e.getSource(); if(active!=t && listeners!=null) { setActiveTab(t); listeners.actionPerformed(e); } else setActiveTab(t); } public String toString() { return getClass().getName()+'['+ tabs.size()+" tab"+(tabs.size()==1?"":"s")+',' +(active==null?"none": "#"+tabs.indexOf(active)+'['+ active.getLabel()+']') +" selected]"; } }
package com.jpeng.demo.add; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.support.design.widget.Snackbar; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import com.bumptech.glide.Glide; import com.githang.statusbar.StatusBarCompat; import com.jpeng.demo.ActivityCollector; import com.jpeng.demo.CarmeraAndGall; import com.jpeng.demo.Image; import com.jpeng.demo.MyApplication; import com.jpeng.demo.NoteTool; import com.jpeng.demo.R; import com.jpeng.demo.TextChange; import com.jpeng.demo.diarys.Music; import com.jpeng.demo.notes.Learn; import com.jpeng.demo.notes.Note; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; public class LearningNotes extends CarmeraAndGall implements View.OnClickListener, MediaPlayer.OnCompletionListener { RelativeLayout toolbarLin; EditText inContent; Dialog dialog,dialog1,dialog2; LinearLayout back,linearLayout; TextView titleText; TextView title; ImageView save; TextView time; TextView labelText; ImageView label; List<String> labels=new ArrayList<>(); ImageView add,galleryOpen,carmaOpen,video,music; View gallery,carma,videoView,musicView; boolean isOpen=true,isAdd; private InputMethodManager mInputMethodManager; int musicId=-1,videoId=-1; MediaPlayer mediaPlayer=new MediaPlayer(); private LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_learning_notes); final Context context=this; Intent intent=getIntent(); isAdd=intent.getBooleanExtra("isAdd",false); cancel(); StatusBarCompat.setStatusBarColor(this, MyApplication.getPeople().getToolbarColor(), true); ActivityCollector.addActivity(this); MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().getAbsolutePath() }, null, null); mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); localBroadcastManager=LocalBroadcastManager.getInstance(this); if (NoteTool.getMusics().size()==0){ new Thread(new Runnable() { @Override public void run() { NoteTool.scanAllAudioFiles(context); } }).start(); } if (NoteTool.getVideoInfos().size()==0){ new Thread(new Runnable() { @Override public void run() { NoteTool.getVideoFile(NoteTool.getVideoInfos(),Environment.getExternalStorageDirectory());// 获得视频文件 } }).start(); } toolbarLin=(RelativeLayout)findViewById(R.id.toolbar_lin); toolbarLin.setBackgroundColor(MyApplication.getPeople().getToolbarColor()); title=(TextView)findViewById(R.id.title_tooolbar); save=(ImageView)findViewById(R.id.save_toolbar); save.setImageResource(R.drawable.save_white); save.setOnClickListener(this); time=(TextView)findViewById(R.id.time_event); Date date = new Date(); time.setText(date.toLocaleString()); titleText=(TextView)findViewById(R.id.title_text); titleText.setOnClickListener(this); back=(LinearLayout) findViewById(R.id.back_toolbar); back.setOnClickListener(this); labelText=(TextView)findViewById(R.id.label_text); label=(ImageView)findViewById(R.id.label_event); label.setOnClickListener(this); if (!MyApplication.getPeople().getLearnLabel().isEmpty()){ for (String str:MyApplication.getPeople().getLearnLabel().split(",")){ labels.add(str); } } mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); add=(ImageView)findViewById(R.id.add); galleryOpen=(ImageView) findViewById(R.id.gallery_open); carmaOpen=(ImageView) findViewById(R.id.carma_open); video=(ImageView) findViewById(R.id.video); music=(ImageView) findViewById(R.id.music); gallery=(View) findViewById(R.id.openG); carma=(View) findViewById(R.id.openC); videoView=(View) findViewById(R.id.openV); musicView=(View) findViewById(R.id.openM); gallery.setVisibility(View.GONE); carma.setVisibility(View.GONE); galleryOpen.setVisibility(View.GONE); carmaOpen.setVisibility(View.GONE); video.setVisibility(View.GONE); music.setVisibility(View.GONE); videoView.setVisibility(View.GONE); musicView.setVisibility(View.GONE); linearLayout=(LinearLayout)findViewById(R.id.linear); add.setOnClickListener(this); gallery.setOnClickListener(this); carma.setOnClickListener(this); videoView.setOnClickListener(this); musicView.setOnClickListener(this); if (isAdd){ title.setText("新建笔记"); linearLayout.addView(getEditext(linearLayout,"")); }else { title.setText("笔记详情"); detailDisplay(); } } private void detailDisplay(){ String []sigh=NoteTool.learn.getSigh().split("&"); String []content=NoteTool.learn.getContentLearn().split("&"); String []picture=NoteTool.learn.getPricesLearn().split(";"); String []music=NoteTool.learn.getMusicPath().split(";"); String []video=NoteTool.learn.getVideoPath().split(";"); List<String> contents= new ArrayList<>(Arrays.asList(content)); List<String> pictures= new ArrayList<>(Arrays.asList(picture)); List<String> musics= new ArrayList<>(Arrays.asList(music)); List<String> videos= new ArrayList<>(Arrays.asList(video)); time.setText(NoteTool.learn.getCreateTime()); titleText.setText(NoteTool.learn.getTitle()); labelText.setText(NoteTool.learn.getLabelLearn()); if (!NoteTool.learn.getLabelLearn().equals("未选择")){ label.setImageResource(R.drawable.icn_label_two); } for (int i=0;i<sigh.length;i++){ switch (Integer.valueOf(sigh[i])){ case 0: if (contents.size()==0){ linearLayout.addView(getEditext(linearLayout,"")); }else { linearLayout.addView(getEditext(linearLayout,contents.get(0))); contents.remove(0); } break; case 1: linearLayout.addView(getImageView(linearLayout,pictures.get(0))); pictures.remove(0); break; case 2: String []musicInfo=musics.get(0).split(","); Music music1=new Music(0,musicInfo[1],"",musicInfo[2],musicInfo[0],0,null,null); linearLayout.addView(getMusicView(linearLayout,music1,NoteTool.getMusicView().size())); musics.remove(0); break; case 3: VideoInfo videoInfo=new VideoInfo(); videoInfo.setPath(videos.get(0)); videoInfo.setBitmap(NoteTool.getVideoPricute(videos.get(0))); linearLayout.addView(getVideoView(linearLayout,videoInfo,NoteTool.getVideoView().size())); videos.remove(0); break; default:break; } } } public View getEditext(LinearLayout root,String content){ View view= LayoutInflater.from(this).inflate(R.layout.editext_layout,root,false); EditText editText=(EditText) view.findViewById(R.id.editext); if (!content.isEmpty()){ editText.setText(content); } editText.setFocusable(true);//设置输入框可聚集 editText.setFocusableInTouchMode(true);//设置触摸聚焦 editText.requestFocus();//请求焦点 editText.findFocus();//获取焦点 mInputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);// 显示输入法 editText.addTextChangedListener(new TextChange(editText,root)); editText.setTag(NoteTool.getIdEditext()); NoteTool.getEdis().add(editText); TypeSign typeSign=new TypeSign(); typeSign.setId(0); typeSign.setIdEditext(NoteTool.getIdEditext()); view.setTag(typeSign); NoteTool.getEditTexts().add(view); NoteTool.setIdEditext(NoteTool.getIdEditext()+1); NoteTool.setNumberE(NoteTool.getNumberE()+1); return view; } public View getImageView(LinearLayout root,String url){ View view= LayoutInflater.from(this).inflate(R.layout.image_layout,root,false); ImageView imageView=(ImageView)view.findViewById(R.id.image); Glide.with(this).load(url).into(imageView); Image image=new Image(NoteTool.getIdImage(),url); TypeSign typeSign=new TypeSign(); typeSign.setId(1); typeSign.setImage(image); view.setTag(typeSign); NoteTool.getImages().add(view); NoteTool.setIdImage(NoteTool.getIdImage()+1); NoteTool.setNumberI(NoteTool.getNumberI()+1); return view; } public View getMusicView(LinearLayout root, Music music, int id){ View view= LayoutInflater.from(this).inflate(R.layout.music_layout,root,false); ImageView control=(ImageView) view.findViewById(R.id.control_music); TextView name=(TextView) view.findViewById(R.id.name_music); TextView singer=(TextView) view.findViewById(R.id.singer_music); name.setText(music.getTitle()); singer.setText(music.getArtist()); control.setOnClickListener(this); control.setTag(id); TypeSign typeSign=new TypeSign(); typeSign.setId(2); typeSign.setMusic(music); view.setTag(typeSign); NoteTool.getMusicView().add(view); return view; } public View getVideoView(LinearLayout root,VideoInfo videoInfo,int id){ View view= LayoutInflater.from(this).inflate(R.layout.video_layout,root,false); View stop=(View) view.findViewById(R.id.stop_video); VideoView videoView=(VideoView) view.findViewById(R.id.video); ImageView imageView=(ImageView) view.findViewById(R.id.cover_video); ImageView play=(ImageView) view.findViewById(R.id.video_play); ImageView full=(ImageView) view.findViewById(R.id.full_screen_play); videoView.setOnCompletionListener(this); imageView.setImageBitmap(videoInfo.getBitmap()); play.setTag(id); stop.setTag(id); full.setTag(id); full.setOnClickListener(this); stop.setOnClickListener(this); play.setOnClickListener(this); stop.setVisibility(View.GONE); full.setVisibility(View.GONE); TypeSign typeSign=new TypeSign(); typeSign.setId(3); typeSign.setVideoInfo(videoInfo); view.setTag(typeSign); NoteTool.getVideoView().add(view); return view; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.back_toolbar: finish(); ActivityCollector.removeActivity(this); break; case R.id.title_text: setTitleTextDialog(); break; case R.id.label_event: labelChoiceDialog(); break; case R.id.add: setAdd(); break; case R.id.openG: goGallery(); break; case R.id.openC: goCarmera(); break; case R.id.openV: if (NoteTool.getMusics().size()==0){ Toast.makeText(this,"还没有搜索到相应的视频文件",Toast.LENGTH_SHORT).show(); }else { choiceDialog(false); } break; case R.id.openM: if (NoteTool.getMusics().size()==0){ Toast.makeText(this,"还没有搜索到相应的音乐文件",Toast.LENGTH_SHORT).show(); }else { choiceDialog(true); } break; case R.id.linear_iteam_music: linearLayout.addView(getMusicView(linearLayout,NoteTool.getMusics().get((int) v.getTag()),NoteTool.getMusicView().size())); linearLayout.addView(getEditext(linearLayout,"")); dialog.dismiss(); break; case R.id.rela_video: linearLayout.addView(getVideoView(linearLayout,NoteTool.getVideoInfos().get((int) v.getTag()),NoteTool.getVideoView().size())); linearLayout.addView(getEditext(linearLayout,"")); dialog.dismiss(); break; case R.id.control_music: startMusic((int) v.getTag()); break; case R.id.stop_video: case R.id.video_play: startVideo((int) v.getTag()); break; case R.id.full_screen_play: setFullPlay((int) v.getTag()); break; case R.id.determine_button: titleText.setText(inContent.getText().toString()); dialog2.dismiss(); break; case R.id.child_radio: labelText.setText(labels.get((int) v.getTag())); label.setImageResource(R.drawable.icn_label_two); dialog1.dismiss(); break; case R.id.save_toolbar: saveLearn(); finish(); ActivityCollector.removeActivity(this); break; default:break; } } private void saveLearn(){ Date date = new Date(); String content = "",prices="",musicPath="",videoPath="",sign=""; for (EditText editText:NoteTool.getEdis()){ content=content+editText.getText().toString()+"&"; } for (View view:NoteTool.getImages()){ TypeSign typeSign=(TypeSign) view.getTag(); prices=prices+typeSign.getImage().getPath()+";"; } for (int i=1;i<linearLayout.getChildCount();i++){ TypeSign typeSign=(TypeSign) linearLayout.getChildAt(i).getTag(); switch (typeSign.getId()){ case 2: Music music=typeSign.getMusic(); musicPath=musicPath+typeSign.getMusic().getUrl()+","+music.getTitle()+","+music.getArtist()+";"; break; case 3: VideoInfo videoInfo=typeSign.getVideoInfo(); videoPath=videoPath+videoInfo.getPath()+";"; break; default:break; } sign=sign+String.valueOf(typeSign.getId())+"&"; } if (!sign.isEmpty()){ sign=sign.substring(0,sign.length()-1); } if (!content.isEmpty()){ content=content.substring(0,content.length()-1); } if (!musicPath.isEmpty()){ musicPath=musicPath.substring(0,musicPath.length()-1); } if (!videoPath.isEmpty()){ videoPath=videoPath.substring(0,videoPath.length()-1); } if (!prices.isEmpty()){ prices=prices.substring(0,prices.length()-1); } if (isAdd){ Learn learn=new Learn(); learn.setCreateTime(date.toLocaleString()); learn.setLabelLearn(labelText.getText().toString()); learn.setTitle(titleText.getText().toString()); learn.setContentLearn(content); learn.setPricesLearn(prices); learn.setMusicPath(musicPath); learn.setVideoPath(videoPath); learn.setSigh(sign); learn.save(); Intent intent=new Intent("com.jpeng.demo.ADDSUCCESSLEARN"); localBroadcastManager.sendBroadcast(intent); Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show(); }else { NoteTool.learn.setCreateTime(date.toLocaleString()); NoteTool.learn.setLabelLearn(labelText.getText().toString()); NoteTool.learn.setTitle(titleText.getText().toString()); NoteTool.learn.setContentLearn(content); NoteTool.learn.setPricesLearn(prices); NoteTool.learn.setMusicPath(musicPath); NoteTool.learn.setVideoPath(videoPath); NoteTool.learn.setSigh(sign); NoteTool.learn.save(); Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show(); NoteTool.isRevise=true; } } public void cancel(){ NoteTool.setIdEditext(0); NoteTool.setIdImage(0); NoteTool.setNumberE(0); NoteTool.setNumberI(0); if (NoteTool.getEditTexts().size()>0){ NoteTool.getEditTexts().removeAll(NoteTool.getEditTexts()); } if (NoteTool.getImages().size()>0){ NoteTool.getImages().removeAll(NoteTool.getImages()); } if (NoteTool.getEdis().size()>0){ NoteTool.getEdis().removeAll(NoteTool.getEdis()); } if (NoteTool.getMusics().size()>0){ NoteTool.getMusics().removeAll(NoteTool.getMusics()); } if (NoteTool.getVideoInfos().size()>0){ NoteTool.getVideoInfos().removeAll(NoteTool.getVideoInfos()); } if (NoteTool.getMusicView().size()>0){ NoteTool.getMusicView().removeAll(NoteTool.getMusicView()); } if (NoteTool.getVideoView().size()>0){ NoteTool.getVideoView().removeAll(NoteTool.getVideoView()); } } @Override protected void onResume() { super.onResume(); if (!path.isEmpty()){ linearLayout.addView(getImageView(linearLayout,path)); linearLayout.addView(getEditext(linearLayout,"")); path=""; } } private void setAdd(){ if (isOpen){ galleryOpen.setVisibility(View.VISIBLE); carmaOpen.setVisibility(View.VISIBLE); gallery.setVisibility(View.VISIBLE); carma.setVisibility(View.VISIBLE); video.setVisibility(View.VISIBLE); music.setVisibility(View.VISIBLE); videoView.setVisibility(View.VISIBLE); musicView.setVisibility(View.VISIBLE); NoteTool.setTranslateAnimation(galleryOpen,carmaOpen,video,music,add); isOpen=false; }else { galleryOpen.setVisibility(View.GONE); carmaOpen.setVisibility(View.GONE); gallery.setVisibility(View.GONE); carma.setVisibility(View.GONE); video.setVisibility(View.GONE); music.setVisibility(View.GONE); videoView.setVisibility(View.GONE); musicView.setVisibility(View.GONE); NoteTool.clearAnimate(galleryOpen); NoteTool.clearAnimate(carmaOpen); NoteTool.clearAnimate(video); NoteTool.clearAnimate(music); NoteTool.clearAnimate(add); isOpen=true; } } private void setFullPlay(int id){ TypeSign typeSign=(TypeSign) NoteTool.getVideoView().get(id).getTag(); String videoUrl=typeSign.getVideoInfo().getPath(); Intent openVideo = new Intent(Intent.ACTION_VIEW); openVideo.setDataAndType(Uri.parse(videoUrl), "video/*"); startActivityForResult(openVideo,3); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case 1: if (resultCode==RESULT_OK){ if (Build.VERSION.SDK_INT>=19){ path= handleImageOnKitKat(photoUri); }else { path=handleImageBeforeKitKat(photoUri); } } break; case 2: if (resultCode==RESULT_OK){ photoUri=data.getData(); if (Build.VERSION.SDK_INT>=19){ path=handleImageOnKitKat(photoUri); }else { path=handleImageBeforeKitKat(photoUri); } } break; case 3: if (resultCode==RESULT_OK){ handleFrontVideo(); } default:break; } } private void handleFrontVideo() { View viewFront=NoteTool.getVideoView().get(videoId); ImageView playFront=(ImageView) viewFront.findViewById(R.id.video_play); ImageView coverFront=(ImageView) viewFront.findViewById(R.id.cover_video); VideoView videoViewFront=(VideoView) viewFront.findViewById(R.id.video); View stopFront=(View) viewFront.findViewById(R.id.stop_video); ImageView fullFront=(ImageView) viewFront.findViewById(R.id.full_screen_play); videoViewFront.suspend(); playFront.setVisibility(View.VISIBLE); coverFront.setVisibility(View.VISIBLE); stopFront.setVisibility(View.GONE); fullFront.setVisibility(View.GONE); } private void startMusic(int id){ View view=NoteTool.getMusicView().get(id); ImageView imageView=(ImageView) view.findViewById(R.id.control_music); TypeSign typeSign=(TypeSign) view.getTag(); Music music=typeSign.getMusic(); if (musicId==-1){ imageView.setImageResource(R.drawable.stop_music); prepareMusic(music.getUrl()); mediaPlayer.start(); }else { if (musicId==id){ if (mediaPlayer.isPlaying()){ mediaPlayer.pause(); imageView.setImageResource(R.drawable.play_music); }else { mediaPlayer.start(); imageView.setImageResource(R.drawable.stop_music); } }else { mediaPlayer.reset(); prepareMusic(music.getUrl()); mediaPlayer.start(); imageView.setImageResource(R.drawable.stop_music); ImageView imageView1=(ImageView) NoteTool.getMusicView().get(musicId).findViewById(R.id.control_music); imageView1.setImageResource(R.drawable.play_music); } } musicId=id; } private void startVideo(int id){ View view=NoteTool.getVideoView().get(id); View stop=(View) view.findViewById(R.id.stop_video); ImageView full=(ImageView) view.findViewById(R.id.full_screen_play); ImageView play=(ImageView) view.findViewById(R.id.video_play); ImageView cover=(ImageView) view.findViewById(R.id.cover_video); VideoView videoView=(VideoView)view.findViewById(R.id.video); TypeSign typeSign=(TypeSign) view.getTag(); VideoInfo videoInfo=typeSign.getVideoInfo(); if (videoId==-1){ videoView.setVideoPath(videoInfo.getPath()); play.setVisibility(View.GONE); cover.setVisibility(View.GONE); stop.setVisibility(View.VISIBLE); full.setVisibility(View.VISIBLE); videoView.start(); }else { if (videoId==id){ if (videoView.isPlaying()){ videoView.pause(); play.setVisibility(View.VISIBLE); cover.setVisibility(View.VISIBLE); stop.setVisibility(View.GONE); full.setVisibility(View.GONE); }else { videoView.start(); play.setVisibility(View.GONE); cover.setVisibility(View.GONE); stop.setVisibility(View.VISIBLE); full.setVisibility(View.VISIBLE); } }else { handleFrontVideo(); videoView.setVideoPath(videoInfo.getPath()); play.setVisibility(View.GONE); cover.setVisibility(View.GONE); stop.setVisibility(View.VISIBLE); full.setVisibility(View.VISIBLE); videoView.start(); } } videoId=id; } private void prepareMusic(String url){ File file=new File(url); try { mediaPlayer.setDataSource(file.getPath()); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } } private void labelChoiceDialog() { dialog1=new Dialog(this,R.style.ActionSheetDialogStyle); View inflate = LayoutInflater.from(this).inflate(R.layout.learn_label_choice, null); LinearLayout linearLayout=(LinearLayout)inflate.findViewById(R.id.linear_choice); int i=0; if (labels.size()>0){ for (String str:labels){ linearLayout.addView(getChildView(str,i)); i++; } }else { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); TextView textView = new TextView(this); layoutParams.setMargins(0, 5, 10, 5); textView.setTextSize(20); textView.setText("你还没有一个笔记标签~请去添加一个"); textView.setLayoutParams(layoutParams); linearLayout.addView(textView); } //将布局设置给Dialog dialog1.setContentView(inflate); //获取当前Activity所在的窗体 Window dialogWindow = dialog1.getWindow(); //设置Dialog从窗体底部弹出 dialogWindow.setGravity( Gravity.CENTER); //获得窗体的属性 WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.y = 20;//设置Dialog距离底部的距离 // 将属性设置给窗体 dialogWindow.setAttributes(lp); dialog1.show();//显示对话框 } private View getChildView(String strName,int id){ View view= LayoutInflater.from(this).inflate(R.layout.child_learn_choice,null); RadioButton radioButton=(RadioButton)view.findViewById(R.id.child_radio); radioButton.setText(strName); radioButton.setTag(id); radioButton.setOnClickListener(this); return view; } private void setTitleTextDialog() { dialog2 = new Dialog(this,R.style.ActionSheetDialogStyle); //填充对话框的布局 View inflate = LayoutInflater.from(this).inflate(R.layout.in_content, null); //初始化控件 TextView titleContent=(TextView)inflate.findViewById(R.id.title_content); inContent=(EditText)inflate.findViewById(R.id.in_content); Button determineButton=(Button)inflate.findViewById(R.id.determine_button); titleContent.setText("设置标题"); determineButton.setOnClickListener(this); //将布局设置给Dialog dialog2.setContentView(inflate); //获取当前Activity所在的窗体 Window dialogWindow = dialog2.getWindow(); //设置Dialog从窗体底部弹出 dialogWindow.setGravity( Gravity.CENTER); //获得窗体的属性 WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.y = 20;//设置Dialog距离底部的距离 // 将属性设置给窗体 dialogWindow.setAttributes(lp); dialog2.show();//显示对话框 } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer!=null){ mediaPlayer.stop(); mediaPlayer.release(); } } private void choiceDialog(boolean isMusic){ dialog=new Dialog(this,R.style.ActionSheetDialogStyle); View view = LayoutInflater.from(this).inflate(R.layout.all_music_create, null); LinearLayout linearLayout=(LinearLayout) view.findViewById(R.id.linear_create); int i=0; if (isMusic){ for (Music music:NoteTool.getMusics()){ linearLayout.addView(NoteTool.getIteamMusic(this,linearLayout,music,i,this)); i++; } }else { for (VideoInfo videoInfo:NoteTool.getVideoInfos()){ linearLayout.addView(NoteTool.getIteamVideo(this,linearLayout,videoInfo,i,this)); i++; } } //将布局设置给Dialog dialog.setContentView(view); Window window = dialog.getWindow(); window.setGravity(Gravity.BOTTOM); window.setWindowAnimations(R.style.dialog_animation); window.getDecorView().setPadding(0, 0, 0, 0); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; window.setAttributes(lp); dialog.show();//显示对话框 } @Override public void onCompletion(MediaPlayer mp) { View view=NoteTool.getVideoView().get(videoId); ImageView play=(ImageView) view.findViewById(R.id.video_play); ImageView cover=(ImageView) view.findViewById(R.id.cover_video); VideoView videoView=(VideoView)view.findViewById(R.id.video); play.setVisibility(View.VISIBLE); cover.setVisibility(View.VISIBLE); videoView.suspend(); } }
package fr.ssm.maquette; import org.springframework.statemachine.StateMachineContext; import org.springframework.statemachine.StateMachinePersist; import java.util.HashMap; /** * pris de l'exemple spring voir : http://docs.spring.io/spring-statemachine/docs/1.2.0.RELEASE/reference/htmlsingle/#sm-persist * il faudra voir ensutie pour un vrai context de persistance via une base de données par exemple * * Created by broblin on 10/01/17. */ public class InMemoryStateMachinePersist implements StateMachinePersist<States, Events, String> { private final HashMap<String, StateMachineContext<States, Events>> contexts = new HashMap<>(); @Override public void write(StateMachineContext<States, Events> context, String contextObj) throws Exception { contexts.put(contextObj, context); } @Override public StateMachineContext<States, Events> read(String contextObj) throws Exception { return contexts.get(contextObj); } }
package com.example.aizat.homework2; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; /** * Created by Aizat on 19.09.2017. */ public class FinishActivity extends FragmentHostActivity { private final String KEY = "key"; @Override protected Fragment getFragment() { return FinishFragment.newInstance(getData()); } private Bundle getData() { Intent intent = getIntent(); int result = intent.getIntExtra(KEY,0); Bundle dataForFragment = new Bundle(); dataForFragment.putInt(KEY,result); return dataForFragment; } @Override public void onBackPressed() {} }
package com.teamkassvi.ascend; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.hardware.Camera; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.os.StrictMode; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.microsoft.projectoxford.face.FaceServiceClient; import com.microsoft.projectoxford.face.contract.Emotion; import com.microsoft.projectoxford.face.contract.Face; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class GameActivity extends AppCompatActivity { private Uri mUriPhotoTaken; private static final int REQUEST_TAKE_PHOTO = 0; ProgressDialog mProgressDialog; ArrayList<String> emotionNamesList; ArrayList<Integer> emotionImagesList; int mode = 0; int score = 0; TextView tvScore, tvEmoName; ImageView ivEmoPic,ivMyPic; //mode 0 = happy, mode 1 = sad, mode 2 = angry, mode 3 = surprise // The image selected to detect. private Bitmap mBitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_game); relativeLayout.getBackground().setAlpha(30); mProgressDialog = new ProgressDialog(this); mProgressDialog.setTitle(getString(R.string.progress_dialog_title)); tvScore = findViewById(R.id.tv_result); tvEmoName = findViewById(R.id.tv_emo_name); ivEmoPic = findViewById(R.id.iv_emo_pic); ivMyPic = findViewById(R.id.iv_my_pic); emotionNamesList = new ArrayList<>(); emotionImagesList = new ArrayList<>(); emotionNamesList.add("HAPPY"); emotionNamesList.add("NEUTRAL"); emotionNamesList.add("SURPRISE"); emotionNamesList.add("SAD"); emotionNamesList.add("ANGER"); emotionImagesList.add(R.drawable.img_em_happy); emotionImagesList.add(R.drawable.img_em_neutral); emotionImagesList.add(R.drawable.img_em_surprise); emotionImagesList.add(R.drawable.img_em_sad); emotionImagesList.add(R.drawable.img_em_angry); initializeMode(); } public void initializeMode(){ mode = 0; tvEmoName.setText(emotionNamesList.get(0)); ivEmoPic.setImageResource(emotionImagesList.get(0)); } public void onClickNext(View v){ mode++; if(mode==5){ mode = 0; } tvEmoName.setText(emotionNamesList.get(mode)); ivEmoPic.setImageResource(emotionImagesList.get(mode)); ivMyPic.setImageResource(R.drawable.com_facebook_profile_picture_blank_portrait); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable("ImageUri", mUriPhotoTaken); } // Recover the saved state when the activity is recreated. @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mUriPhotoTaken = savedInstanceState.getParcelable("ImageUri"); } private class DetectionTask extends AsyncTask<InputStream, String, Face[]> { private boolean mSucceed = true; @Override protected Face[] doInBackground(InputStream... params) { // Get an instance of face service client to detect faces in image. FaceServiceClient faceServiceClient = SampleApp.getFaceServiceClient(); if(faceServiceClient==null){ Log.d("GameErr", "null"); } try { publishProgress("Detecting..."); // Start detection. return faceServiceClient.detect( params[0], /* Input stream of image to detect */ true, /* Whether to return face ID */ true, /* Whether to return face landmarks */ /* Which face attributes to analyze, currently we support: age,gender,headPose,smile,facialHair */ new FaceServiceClient.FaceAttributeType[] { FaceServiceClient.FaceAttributeType.Age, FaceServiceClient.FaceAttributeType.Gender, FaceServiceClient.FaceAttributeType.Smile, FaceServiceClient.FaceAttributeType.Glasses, FaceServiceClient.FaceAttributeType.FacialHair, FaceServiceClient.FaceAttributeType.Emotion, FaceServiceClient.FaceAttributeType.HeadPose, FaceServiceClient.FaceAttributeType.Accessories, FaceServiceClient.FaceAttributeType.Blur, FaceServiceClient.FaceAttributeType.Exposure, FaceServiceClient.FaceAttributeType.Hair, FaceServiceClient.FaceAttributeType.Makeup, FaceServiceClient.FaceAttributeType.Noise, FaceServiceClient.FaceAttributeType.Occlusion }); } catch (Exception e) { mSucceed = false; publishProgress(e.getMessage()); // addLog(e.getMessage()); return null; } } private void customToast(String message, int duration) { LayoutInflater inflater = getLayoutInflater(); View customView = inflater.inflate(R.layout.dialog_custom_toast, null); TextView tvMsg = customView.findViewById(R.id.tv_msg); tvMsg.setText(message+""); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(duration); toast.setView(customView); toast.show(); } private void setUiAfterDetection(Face[] result, boolean succeed) { mProgressDialog.dismiss(); if (succeed) { // The information about the detection result. String detectionResult; if (result != null) { detectionResult = result.length + " face" + (result.length != 1 ? "s" : "") + " detected"; // Show the detected faces on original image. ImageView ivMyPic = (ImageView) findViewById(R.id.iv_my_pic); ivMyPic.setImageBitmap(ImageHelper.drawFaceRectanglesOnBitmap( mBitmap, result, true)); String emotionDetected = getEmotion(result[0].faceAttributes.emotion); if(emotionDetected.equals(emotionNamesList.get(mode))){ customToast("+10 (Correct)",Toast.LENGTH_SHORT); score+=10; } else{ customToast("-5 (Wrong)",Toast.LENGTH_SHORT); score-=5; } tvScore.setText("Score : " + score); Log.d("GAMERES", emotionDetected); } } // else { // detectionResult = "0 face detected"; // } // setInfo(detectionResult); } @Override protected void onPreExecute() { mProgressDialog.show(); // addLog("Request: Detecting in image " + mImageUri); } @Override protected void onProgressUpdate(String... progress) { mProgressDialog.setMessage(progress[0]); // setInfo(progress[0]); } @Override protected void onPostExecute(Face[] result) { if (mSucceed) { // addLog("Response: Success. Detected " + (result == null ? 0 : result.length) // + " face(s) in " + mImageUri); } // Show the result on screen when detection is done. setUiAfterDetection(result, mSucceed); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_TAKE_PHOTO: if (resultCode == RESULT_OK) { // If image is selected successfully, set the image URI and bitmap. Uri imageUri; if (data == null || data.getData() == null) { imageUri = mUriPhotoTaken; } else { imageUri = data.getData(); } mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri( imageUri, getContentResolver()); if (mBitmap != null) { // Show the image on screen. ImageView ivMyPic = findViewById(R.id.iv_my_pic); ivMyPic.setImageBitmap(mBitmap); checkAnswer(); // Add detection log. // addLog("Image: " + mImageUri + " resized to " + mBitmap.getWidth() // + "x" + mBitmap.getHeight()); } // Clear the detection result. // FaceListAdapter faceListAdapter = new FaceListAdapter(null); // ListView listView = (ListView) findViewById(R.id.list_detected_faces); // listView.setAdapter(faceListAdapter); // Clear the information panel. // setInfo(""); // Enable button "detect" as the image is selected and not detected. // setDetectButtonEnabledStatus(true); } break; default: break; } } private String getEmotion(Emotion emotion) { String emotionType = ""; double emotionValue = 0.0; if (emotion.anger > emotionValue) { emotionValue = emotion.anger; emotionType = "ANGER"; } if (emotion.contempt > emotionValue) { emotionValue = emotion.contempt; emotionType = "Contempt"; } if (emotion.disgust > emotionValue) { emotionValue = emotion.disgust; emotionType = "Disgust"; } if (emotion.fear > emotionValue) { emotionValue = emotion.fear; emotionType = "Fear"; } if (emotion.happiness > emotionValue) { emotionValue = emotion.happiness; emotionType = "HAPPY"; } if (emotion.neutral > emotionValue) { emotionValue = emotion.neutral; emotionType = "NEUTRAL"; } if (emotion.sadness > emotionValue) { emotionValue = emotion.sadness; emotionType = "SAD"; } if (emotion.surprise > emotionValue) { emotionValue = emotion.surprise; emotionType = "SURPRISE"; } return String.format("%s",emotionType); // return String.format("%s: %f", emotionType, emotionValue); } public void checkAnswer() { ByteArrayOutputStream output = new ByteArrayOutputStream(); mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output); ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray()); // Start a background task to detect faces in the image. if(inputStream!=null) { new DetectionTask().execute(inputStream); } // Prevent button click during detecting. // setAllButtonsEnabledStatus(false); } public void takePhoto(View view) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(intent.resolveActivity(getPackageManager()) != null) { // Save the photo taken to a temporary file. File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); try { File file = File.createTempFile("IMG_", ".jpg", storageDir); mUriPhotoTaken = Uri.fromFile(file); intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1); } else { intent.putExtra("android.intent.extras.CAMERA_FACING", 1); } startActivityForResult(intent, REQUEST_TAKE_PHOTO); } catch (IOException e) { Log.d("GameExc : ", e + ""); } } } }
package com.mustafayuksel.notificationapplication.domain; import javax.persistence.Entity; @Entity public class Application extends BaseEntity { private String name; private String mnemonic; private String applicationOneSignalId; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMnemonic() { return mnemonic; } public void setMnemonic(String mnemonic) { this.mnemonic = mnemonic; } public String getApplicationOneSignalId() { return applicationOneSignalId; } public void setApplicationOneSignalId(String applicationOneSignalId) { this.applicationOneSignalId = applicationOneSignalId; } }
package com.edasaki.rpg.spells; import com.edasaki.rpg.spells.assassin.DoubleStab; import com.edasaki.rpg.spells.assassin.ShadowAcrobat; import com.edasaki.rpg.spells.assassin.ShadowStab; import com.edasaki.rpg.spells.assassin.ShadowWarp; import com.edasaki.rpg.spells.assassin.Shuriken; import com.edasaki.rpg.spells.assassin.SinisterStrike; import com.edasaki.rpg.spells.assassin.Stealth; public class SpellbookAssassin extends Spellbook { public static final Spell DOUBLE_STAB = new Spell("Double Stab", 2, 25, 1, 0, new String[] { "Quickly stab twice on your next attack, dealing 60% damage each hit.", "Quickly stab twice on your next attack, dealing 70% damage each hit.", "Quickly stab twice on your next attack, dealing 80% damage each hit.", "Quickly stab twice on your next attack, dealing 90% damage each hit.", "Quickly stab twice on your next attack, dealing 100% damage each hit.", "Quickly stab twice on your next attack, dealing 110% damage each hit.", "Quickly stab twice on your next attack, dealing 120% damage each hit.", "Quickly stab twice on your next attack, dealing 130% damage each hit.", "Quickly stab twice on your next attack, dealing 140% damage each hit.", "Quickly stab twice on your next attack, dealing 150% damage each hit.", "Quickly stab twice on your next attack, dealing 160% damage each hit.", "Quickly stab twice on your next attack, dealing 170% damage each hit.", "Quickly stab twice on your next attack, dealing 180% damage each hit.", "Quickly stab twice on your next attack, dealing 190% damage each hit.", "Quickly stab twice on your next attack, dealing 200% damage each hit.", "Quickly stab twice on your next attack, dealing 210% damage each hit.", "Quickly stab twice on your next attack, dealing 220% damage each hit.", "Quickly stab twice on your next attack, dealing 230% damage each hit.", "Quickly stab twice on your next attack, dealing 240% damage each hit.", "Quickly stab twice on your next attack, dealing 250% damage each hit.", "Quickly stab twice on your next attack, dealing 260% damage each hit.", "Quickly stab twice on your next attack, dealing 270% damage each hit.", "Quickly stab twice on your next attack, dealing 280% damage each hit.", "Quickly stab twice on your next attack, dealing 290% damage each hit.", "Quickly stab twice on your next attack, dealing 300% damage each hit.", }, null, new DoubleStab()); public static final Spell SINISTER_STRIKE = new Spell("Sinister Strike", 5, 5, 1, 1, new String[] { "Perform a cruel strike on your next attack that deals 110% damage. Enemy players are crippled for 2 seconds, receiving 75% less healing from all sources.", "Perform a cruel strike on your next attack that deals 120% damage. Enemy players are crippled for 3 seconds, receiving 75% less healing from all sources.", "Perform a cruel strike on your next attack that deals 130% damage. Enemy players are crippled for 4 seconds, receiving 75% less healing from all sources.", "Perform a cruel strike on your next attack that deals 140% damage. Enemy players are crippled for 5 seconds, receiving 75% less healing from all sources.", "Perform a cruel strike on your next attack that deals 150% damage. Enemy players are crippled for 6 seconds, receiving 75% less healing from all sources.", }, null, new SinisterStrike()); public static final Spell STEALTH = new Spell("Stealth", 4, 6, 2, 0, new String[] { "Turn invisible for 10 seconds. Stealth is broken when you attack.", "Turn invisible for 20 seconds. Stealth is broken when you attack.", "Turn invisible for 30 seconds. Stealth is broken when you attack.", "Turn invisible for 40 seconds. Stealth is broken when you attack.", "Turn invisible for 50 seconds. Stealth is broken when you attack.", "Turn invisible for 60 seconds. Stealth is broken when you attack.", }, null, new Stealth()); public static final Spell SHADOW_STAB = new Spell("Shadow Stab", 3, 20, 2, 1, new String[] { "Attack from the shadows on your next attack, dealing 300% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 320% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 340% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 360% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 380% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 400% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 420% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 440% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 460% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 480% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 500% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 520% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 540% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 560% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 580% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 600% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 620% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 640% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 660% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", "Attack from the shadows on your next attack, dealing 680% damage. Spell can only be used while stealthed. Does not stack with Double Stab.", }, new Object[] { DOUBLE_STAB, 1, STEALTH, 1 }, new ShadowStab()); public static final Spell SHADOW_ACROBAT = new Spell("Shadow Acrobat", 3, 5, 2, 2, new String[] { "Gain extreme speed and jump capabilities for 5 seconds. Spell can only be used while stealthed.", "Gain extreme speed and jump capabilities for 7 seconds. Spell can only be used while stealthed.", "Gain extreme speed and jump capabilities for 9 seconds. Spell can only be used while stealthed.", "Gain extreme speed and jump capabilities for 11 seconds. Spell can only be used while stealthed.", "Gain extreme speed and jump capabilities for 13 seconds. Spell can only be used while stealthed.", }, new Object[] { STEALTH, 1 }, new ShadowAcrobat()); public static final Spell SHADOW_WARP = new Spell("Shadow Warp", 2, 1, 2, 3, new String[] { "Teleport behind a nearby enemy target. Spell can only be used while stealthed.", }, new Object[] { STEALTH, 1 }, new ShadowWarp()); public static final Spell SHURIKEN = new Spell("Shuriken", 1, 10, 3, 0, new String[] { "Throw a shuriken that deals 120% damage.", "Throw a shuriken that deals 140% damage.", "Throw a shuriken that deals 160% damage.", "Throw a shuriken that deals 180% damage.", "Throw a shuriken that deals 200% damage.", "Throw a shuriken that deals 220% damage.", "Throw a shuriken that deals 240% damage.", "Throw a shuriken that deals 260% damage.", "Throw a shuriken that deals 280% damage.", "Throw a shuriken that deals 300% damage.", }, null, new Shuriken()); public static final Spell DARK_HARMONY = new Spell("Dark Harmony", 0, 1, 1, 8, new String[] { "Increase Mana Regen rate by 50% while in Stealth.", }, null, new PassiveSpellEffect()); public static final Spell DAGGER_MASTERY = new Spell("Dagger Mastery", 0, 5, 2, 8, new String[] { "Deal 2% increased base damage.", "Deal 4% increased base damage.", "Deal 6% increased base damage.", "Deal 8% increased base damage.", "Deal 10% increased base damage.", }, null, new PassiveSpellEffect()); private static final Spell[] SPELL_LIST = { DOUBLE_STAB, SINISTER_STRIKE, STEALTH, SHADOW_STAB, SHADOW_ACROBAT, SHADOW_WARP, SHURIKEN, DARK_HARMONY, DAGGER_MASTERY }; // DON'T FORGET TO ADD TO SPELL_LIST public static final Spellbook INSTANCE = new SpellbookAssassin(); @Override public Spell[] getSpellList() { return SPELL_LIST; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cput.codez.angorora.eventstar.model; /** * * @author allen */ public final class OwnerStaff { private String id; private String ownerId; private String staffName; private String staffId; private String contId; private OwnerStaff() { } private OwnerStaff(Builder build) { this.id=build.id; this.staffId= build.staffId; this.ownerId=build.ownerId; this.staffName= build.staffName; this.contId=build.contId; } public String getId() { return id; } public String getOwnerId() { return ownerId; } public String getStaffName() { return staffName; } public String getStaffId() { return staffId; } public String getCont() { return contId; } public static class Builder{ private String id; private String staffName; private String staffId; private String ownerId; private String contId; public Builder(String staffId) { this.staffId= staffId; } public Builder id(String id){ this.id=id; return this; } public Builder owner(String ownerId){ this.ownerId=ownerId; return this; } public Builder staffName(String staffName){ this.staffName= staffName; return this; } public Builder staffContactCard( String contactCard){ this.contId=contactCard; return this; } public OwnerStaff build(){ return new OwnerStaff(this); } public Builder copier(OwnerStaff staff){ this.id=staff.id; this.staffId= staff.staffId; this.ownerId=staff.ownerId; this.staffName= staff.staffName; this.contId=staff.contId; return this; } } @Override public int hashCode() { int hash = 7; hash = 17 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OwnerStaff other = (OwnerStaff) obj; if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) { return false; } return true; } }
package com.ca.rs; import com.ca.rs.steps.AbstractSeleniumSteps; import com.ca.rs.models.SeleniumDriverContainer; import cucumber.api.Scenario; import cucumber.api.java.After; import cucumber.api.java.Before; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriverException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Hooks extends AbstractSeleniumSteps { private static final Logger LOG = LoggerFactory.getLogger(Hooks.class); public Hooks(SeleniumDriverContainer seleniumDriverContainer) { super(seleniumDriverContainer); } @Before public void beforeScenario(Scenario scenario) throws Exception { LOG.debug("##### Starting Scenario : {} #####", scenario.getName() + "******status******" + scenario.getStatus()); LOG.debug("******status before******" + scenario.getStatus()); } @After public void afterScenario(Scenario scenario) { LOG.debug("******status after******" + scenario.getStatus()); if (scenario.isFailed() && seleniumDriverContainer.isInstantiated()) { try { scenario.write("Current Page URL is " + webDriver().getCurrentUrl()); byte[] screenShot; screenShot = ((TakesScreenshot) webDriver()) .getScreenshotAs(OutputType.BYTES); scenario.embed(screenShot, "image/png"); } catch (WebDriverException platformNotSupportedException) { LOG.error(platformNotSupportedException .getMessage(), platformNotSupportedException); } } try { seleniumDriverContainer.clear(); LOG.debug("Web driver connection closed"); } catch (Exception e) { LOG.error("***Driver already closed afterScenario method***", e); } finally { seleniumDriverContainer.clear(); } LOG.debug("** End Scenario - " + scenario.getName() + " Status - " + scenario.getStatus() + " **"); LOG.debug("****************************************************************"); } }
package BlockingQueue; public class ThreadPoolDemo2 { public static void main(String[] args) { //缓存线程池 /** * 特点: * 1.没有核心线程 * 2,全部都是临时线程 * 3,能够处理任意多的线程 * 4,工作对列时同步队列 * * 场景: * 适用于高并发的短任务场景, */ } }
package com.sheygam.loginarchitectureexample.data.repositories.addContact.prefstore; /** * Created by Kate on 17.02.2018. */ public interface IAddContactStoreRepository { String getAuthToken(); }
package dynamic.programing; import java.util.Arrays; public class MaximumXORSubArray_TrieAlgorithm { public static void main(String[] args) { // int[] array = {8,1,2,12}; // int[] array = {11,13,14,8,14}; int[] array = {Integer.valueOf("1111111011111111111111111111111", 2), Integer.valueOf("1111111111111111111111111111101", 2), Integer.valueOf("1111111111111111111011111111111", 2), Integer.valueOf("1111101111111111111111111111111", 2)}; int[] result = new MaximumXORSubArray_TrieAlgorithm().calculate(array); System.out.println(Arrays.toString(result)); } public int[] calculate(int[] array) { Node root = new Node(); insert(root,0,-1); int maxValue = Integer.MIN_VALUE; int maxStart = -1; int maxEnd = -1; int calculated = 0; for(int i=0 ; i<array.length;i++){ calculated ^= array[i]; insert(root,calculated,i); int[] result = query(root,calculated); if(maxValue<result[0]){ maxValue = result[0]; maxStart = result[1]+1; maxEnd = i; } } return new int[] {maxValue,maxStart,maxEnd}; } private int[] query(Node root, int value) { for(int i= Integer.SIZE-2; i>=0 ; i--){ if((value & 1<<i) == 1<<i){ if(root.zero!=null){ root = root.zero; } else{ root = root.one; } } else{ if(root.one!=null){ root = root.one; } else{ root = root.zero; } } } return new int[] {root.value^value,root.position}; } private void insert(Node root, int value,int index) { for(int i= Integer.SIZE-2; i>=0 ; i--){ if((value & 1<<i) == 1<<i){ if(root.one==null){ root.one = new Node(); } root = root.one; } else{ if(root.zero==null){ root.zero = new Node(); } root = root.zero; } } root.value = value; root.position = index; } public static class Node{ public int value; public int position; public Node one; public Node zero; } }
package com.cs160fall2020.teampikachu.farm2table.service; import org.springframework.stereotype.Service; @Service public class Constants { public static final String FIREBASE_SDK_JSON ="./app-farm2table-firebase-adminsdk-x9rm3-161fe6a8d5.json";//copy the sdk-config file root address, if its in root ,filename is enough public static final String FIREBASE_BUCKET = "app-farm2table.appspot.com";//enter your bucket name public static final String FIREBASE_PROJECT_ID ="app-farm2table";//enter your project id public static final String URL = "https://app-farm2table.firebaseio.com"; }
package at.ac.tuwien.sepm.groupphase.backend.endpoint.dto; import at.ac.tuwien.sepm.groupphase.backend.entity.Permissions; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Objects; public class OverviewOperatorDto { private Long id; @NotNull(message = "Name darf nicht null sein") @NotBlank @Size(max = 255) private String name; @NotNull(message = "Benutzername darf nicht null sein") @NotBlank @Size(max = 128) private String loginName; @NotNull(message = "Email darf nicht null sein") @NotBlank @Email private String email; @NotNull(message = "Berechtigungslevel darf nicht null sein") @Enumerated(EnumType.STRING) private Permissions permissions; public OverviewOperatorDto(){ } public OverviewOperatorDto(long id, String name, String loginName, String email, Permissions permissions) { this.id = id; this.name = name; this.loginName = loginName; this.email = email; this.permissions = permissions; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Permissions getPermissions() { return permissions; } public void setPermissions(Permissions permissions) { this.permissions = permissions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof OverviewOperatorDto)) { return false; } OverviewOperatorDto overviewOperatorDto = (OverviewOperatorDto) o; return Objects.equals(id, overviewOperatorDto.id) && Objects.equals(name, overviewOperatorDto.name) && Objects.equals(loginName, overviewOperatorDto.loginName) && Objects.equals(email, overviewOperatorDto.email) && Objects.equals(permissions, overviewOperatorDto.permissions); } @Override public int hashCode() { return Objects.hash(id, name, loginName, email, permissions); } @Override public String toString() { return "OverviewOperatorDto{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", login_name='" + loginName + '\'' + ", email='" + email + '\'' + ", permissions='" + permissions + '\'' + '}'; } }
package com.radius.sodalityUser.response; import java.util.Date; public class UnitResponsejson { private String uuid; private String unitNo; private String unitDescription; private String unitType; private Date createdDate; private Date lastModifiedDate; private String soldStatus; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getUnitNo() { return unitNo; } public void setUnitNo(String unitNo) { this.unitNo = unitNo; } public String getUnitDescription() { return unitDescription; } public void setUnitDescription(String unitDescription) { this.unitDescription = unitDescription; } public String getUnitType() { return unitType; } public void setUnitType(String unitType) { this.unitType = unitType; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Date getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public String getSoldStatus() { return soldStatus; } public void setSoldStatus(String soldStatus) { this.soldStatus = soldStatus; } }
package ro.pastia.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Properties; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * A Simple Multi-Threaded HTTP Server * <p> * Implements a simple Multi-Threaded HTTP Server with a very limited set of functionality. * Supports basic directory listings and streaming files. * </p> */ public class MultiThreadedServer implements Runnable { /** * Name of the server as it will be used in headers and server signature. */ public static final String NAME = "Simple Server/1.0"; public static final String PROPERTY_PORT = "server.port"; public static final String PROPERTY_BASEPATH = "server.basePath"; public static final String PROPERTY_MULTITHREAD_MAXTHREADS = "server.multithread.maxThreads"; private static final Logger logger = LoggerFactory.getLogger(MultiThreadedServer.class); private int serverPort; private ServerSocket serverSocket; private boolean isStopped = false; private ExecutorService threadPool; private String basePath; private Properties serverConfig; /** * Constructs a MultiThreadedServer * * @param port the port that the server should listen on * @param maxThreads the number of threads the server should use to handle requests; the server also keep a queue * of requests if all worker threads are busy with a size of <code>maxThreads * 4</code> * @param basePath the base path out of which documents will be server (root of the server) * @param serverConfig contains other configuration parameters */ public MultiThreadedServer(int port, int maxThreads, String basePath, Properties serverConfig) { threadPool = new ThreadPoolExecutor( maxThreads, maxThreads, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(maxThreads*4)); this.serverPort = port; this.basePath = basePath; this.serverConfig = serverConfig; } public void run() { openServerSocket(); logger.info("Server started on port {}", serverPort); while (!isStopped()) { Socket clientSocket; try { clientSocket = serverSocket.accept(); } catch (IOException e) { if (isStopped()) { logger.info("Server Stopped."); return; } else { throw new RuntimeException("Error accepting client connection", e); } } threadPool.execute( new RequestHandler(clientSocket, MimeTypeResolver.getInstance(), basePath, serverConfig)); } threadPool.shutdown(); logger.info("Server Stopped."); } private synchronized boolean isStopped() { return this.isStopped; } public synchronized void stop() { logger.info("Stopping server..."); isStopped = true; try { serverSocket.close(); } catch (IOException e) { throw new RuntimeException("Error closing server", e); } } private void openServerSocket() { try { serverSocket = new ServerSocket(serverPort); } catch (IOException e) { throw new RuntimeException("Cannot open port " + serverPort, e); } } }
package com.qa.testscripts; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import com.qa.pages.AjioPages; public class TestBase { protected static WebDriver driver; protected static AjioPages ajio; @Parameters({"Browser","url"}) @BeforeClass public void setUp(String Browser,String url) { if(Browser.equalsIgnoreCase("Chrome")) { System.setProperty("webdriver.chrome.driver","C:\\Users\\Priti\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe"); driver= new ChromeDriver(); } else if(Browser.equalsIgnoreCase("edge")) { System.setProperty("webdriver.edge.driver","C:\\Users\\Priti\\Desktop\\Drivers\\edgedriver_win64\\msedgedriver.exe"); driver= new EdgeDriver(); } else if(Browser.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver","C:\\Users\\Priti\\Desktop\\Drivers\\geckodriver-v0.29.1-win64\\geckodriver.exe"); driver= new FirefoxDriver(); } driver.manage().window().maximize(); ajio = new AjioPages(driver); driver.get(url); } @AfterClass public void tearDown() { driver.close(); } public void captureScreenShot(WebDriver driver,String tname) throws IOException { TakesScreenshot screenShot=(TakesScreenshot) driver; File Sources=screenShot.getScreenshotAs(OutputType.FILE); String Dest= System.getProperty("user.dir")+"/Screenshots/"+tname+".png"; FileUtils.copyFile(Sources,new File(Dest)); } }
package db; import java.io.File; import java.sql.Connection; import java.sql.SQLException; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.sqlite.SQLiteConfig; import org.sqlite.SQLiteConfig.JournalMode; import org.sqlite.SQLiteConfig.LockingMode; import org.sqlite.SQLiteConfig.SynchronousMode; import org.sqlite.SQLiteConfig.TempStore; public abstract class DbConnection { private final static String CONNECTION_PREFIX = "jdbc:sqlite:"; public File dbFile; public Connection connection; public DSLContext context; static { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static SQLiteConfig getDefaultConfig(boolean readOnly) { SQLiteConfig config = new SQLiteConfig(); config.setPageSize(4096); config.setCacheSize(10000); config.setLockingMode(LockingMode.EXCLUSIVE); config.setSynchronous(SynchronousMode.OFF); config.setJournalMode(JournalMode.WAL); config.setTempStore(TempStore.MEMORY); config.enforceForeignKeys(false); config.setReadOnly(readOnly); return config; } protected SQLiteConfig createConfig(boolean readOnly) { return getDefaultConfig(readOnly); } public DbConnection(File dbFile, boolean readOnly) { this.dbFile = dbFile; boolean newDb = !dbFile.exists(); SQLiteConfig config = this.createConfig(readOnly); try { this.connection = config.createConnection(CONNECTION_PREFIX + dbFile.getAbsolutePath()); this.context = DSL.using(this.connection, SQLDialect.SQLITE); } catch (SQLException e) { e.printStackTrace(); } if (newDb) { this.createTables(); this.initialPrepare(); } this.prepare(); } public DbConnection(File dbFile) { this(dbFile, false); } public void close() { try { this.context.close(); this.connection.close(); } catch (SQLException e) { e.printStackTrace(); } } protected void createTables() {} protected void initialPrepare() {} protected void prepare() {} }
package com.giladkz.verticalEnsemble.Data; import java.io.Serializable; /** * Created by giladkatz on 11/02/2016. */ public class NumericColumn implements Column,Serializable { private double[] values; public NumericColumn(int size) { values = new double[size]; } public Object getValue(int i) { return values[i]; } public void setValue(int i, Object obj) { values[i] = (Double)obj; } public columnType getType() {return columnType.Numeric;} public int getNumOfInstances() { return values.length; } public void setValue(int i, double v) { values[i] = v; } public void setAllValues(Object v) { values = (double[])v; } public Object getValues() {return values;} }
package io.breen.socrates.util; public final class Left<L, R> extends Either<L, R> { private L value; public Left(L value) { this.value = value; } @Override public L getLeft() { return value; } public String toString() { return "Left(" + value + ")"; } }
package com.demo.decorator.login; /** * @author: Maniac Wen * @create: 2020/4/6 * @update: 20:51 * @version: V1.0 * @detail: **/ public class loginServiceImpl implements loginService{ public ResultMsg regist(String name, String psw) { return new ResultMsg(200,"注册成功",new User()); } public ResultMsg login(String name, String psw) { return null; } }
package ivge; public class Triangle implements Figure{ }
import java.util.ArrayDeque; public class Tree { private static class Node { private int value; private Node lChild; private Node rChild; public Node(int v, Node l, Node r) { value = v; lChild = l; rChild = r; } public Node(int v) { value = v; lChild = null; rChild = null; } } private Node root; public Tree() { root = null; } public void levelOrderBinaryTree(int[] arr) { root = levelOrderBinaryTree(arr, 0); } public Node levelOrderBinaryTree(int[] arr, int start) { int size = arr.length; Node curr = new Node(arr[start]); int left = 2 * start + 1; int right = 2 * start + 2; if (left < size) curr.lChild = levelOrderBinaryTree(arr, left); if (right < size) curr.rChild = levelOrderBinaryTree(arr, right); return curr; } public void InsertNode(int value) { root = InsertNode(value, root); } private Node InsertNode(int value, Node node) { if (node == null) { node = new Node(value, null, null); } else { if (node.value > value) { node.lChild = InsertNode(value, node.lChild); } else { node.rChild = InsertNode(value, node.rChild); } } return node; } public void PrintPreOrder() { PrintPreOrder(root); } private void PrintPreOrder(Node node)/* pre order */ { if (node != null) { System.out.print(" " + node.value); PrintPreOrder(node.lChild); PrintPreOrder(node.rChild); } } public void NthPreOrder(int index) { int[] counter = { 0 }; NthPreOrder(root, index, counter); } private void NthPreOrder(Node node, int index, int[] counter)/* pre order */ { if (node != null) { counter[0]++; if (counter[0] == index) { System.out.print(node.value); } NthPreOrder(node.lChild, index, counter); NthPreOrder(node.rChild, index, counter); } } public void PrintPostOrder() { PrintPostOrder(root); } private void PrintPostOrder(Node node)/* post order */ { if (node != null) { PrintPostOrder(node.lChild); PrintPostOrder(node.rChild); System.out.print(" " + node.value); } } public void NthPostOrder(int index) { int[] counter = { 0 }; NthPostOrder(root, index, counter); } private void NthPostOrder(Node node, int index, int[] counter)/* post order */ { if (node != null) { NthPostOrder(node.lChild, index, counter); NthPostOrder(node.rChild, index, counter); counter[0]++; if (counter[0] == index) { System.out.print(node.value); } } } public void PrintInOrder() { PrintInOrder(root); } private void PrintInOrder(Node node)/* In order */ { if (node != null) { PrintInOrder(node.lChild); System.out.print(" " + node.value); PrintInOrder(node.rChild); } } public void NthInOrder(int index) { int[] counter = { 0 }; NthInOrder(root, index, counter); } private void NthInOrder(Node node, int index, int[] counter) { if (node != null) { NthInOrder(node.lChild, index, counter); counter[0]++; if (counter[0] == index) { System.out.print(node.value); } NthInOrder(node.rChild, index, counter); } } public void PrintBredthFirst() { ArrayDeque<Node> que = new ArrayDeque<Node>(); Node temp; if (root != null) que.add(root); while (que.isEmpty() == false) { temp = que.remove(); System.out.println(temp.value); if (temp.lChild != null) que.add(temp.lChild); if (temp.rChild != null) que.add(temp.rChild); } } public void PrintDepthFirst() { ArrayDeque<Node> stk = new ArrayDeque<Node>(); Node temp; if (root != null) stk.push(root); while (stk.isEmpty() == false) { temp = stk.pop(); System.out.println(temp.value); if (temp.lChild != null) stk.push(temp.lChild); if (temp.rChild != null) stk.push(temp.rChild); } } public boolean Find(int value) { Node curr = root; while (curr != null) { if (curr.value == value) { return true; } else if (curr.value > value) { curr = curr.lChild; } else { curr = curr.rChild; } } return false; } public boolean Find2(int value) { Node curr = root; while (curr != null && curr.value != value) curr = (curr.value > value) ? curr.lChild : curr.rChild; return curr != null; } public int FindMin() { Node node = root; if (node == null) { return Integer.MAX_VALUE; } while (node.lChild != null) { node = node.lChild; } return node.value; } public int FindMax() { Node node = root; if (node == null) { return Integer.MIN_VALUE; } while (node.rChild != null) { node = node.rChild; } return node.value; } public Node FindMax(Node curr) { Node node = curr; if (node == null) { return null; } while (node.rChild != null) { node = node.rChild; } return node; } public Node FindMin(Node curr) { Node node = curr; if (node == null) { return null; } while (node.lChild != null) { node = node.lChild; } return node; } public void Free() { root = null; } public void DeleteNode(int value) { root = DeleteNode(root, value); } private Node DeleteNode(Node node, int value) { Node temp = null; if (node != null) { if (node.value == value) { if (node.lChild == null && node.rChild == null) { return null; } else { if (node.lChild == null) { temp = node.rChild; return temp; } if (node.rChild == null) { temp = node.lChild; return temp; } Node maxNode = FindMax(node.lChild); int maxValue = maxNode.value; node.value = maxValue; node.lChild = DeleteNode(node.lChild, maxValue); } } else { if (node.value > value) { node.lChild = DeleteNode(node.lChild, value); } else { node.rChild = DeleteNode(node.rChild, value); } } } return node; } public int TreeDepth() { return TreeDepth(root); } private int TreeDepth(Node root) { if (root == null) return 0; else { int lDepth = TreeDepth(root.lChild); int rDepth = TreeDepth(root.rChild); if (lDepth > rDepth) return lDepth + 1; else return rDepth + 1; } } public boolean isEqual(Tree T2) { return Identical(root, T2.root); } private boolean Identical(Node node1, Node node2) { if (node1 == null && node2 == null) return true; else if (node1 == null || node2 == null) return false; else return (Identical(node1.lChild, node2.lChild) && Identical(node1.rChild, node2.rChild) && (node1.value == node2.value)); } public Node Ancestor(int first, int second) { if (first > second) { int temp = first; first = second; second = temp; } return Ancestor(root, first, second); } private Node Ancestor(Node curr, int first, int second) { if (curr == null) { return null; } if (curr.value > first && curr.value > second) { return Ancestor(curr.lChild, first, second); } if (curr.value < first && curr.value < second) { return Ancestor(curr.rChild, first, second); } return curr; } public Tree CopyTree() { Tree tree2 = new Tree(); tree2.root = CopyTree(root); return tree2; } private Node CopyTree(Node curr) { Node temp; if (curr != null) { temp = new Node(curr.value); temp.lChild = CopyTree(curr.lChild); temp.rChild = CopyTree(curr.rChild); return temp; } else return null; } public Tree CopyMirrorTree() { Tree tree2 = new Tree(); tree2.root = CopyMirrorTree(root); return tree2; } private Node CopyMirrorTree(Node curr) { Node temp; if (curr != null) { temp = new Node(curr.value); temp.rChild = CopyMirrorTree(curr.lChild); temp.lChild = CopyMirrorTree(curr.rChild); return temp; } else return null; } public int numNodes() { return numNodes(root); } public int numNodes(Node curr) { if (curr == null) return 0; else return (1 + numNodes(curr.rChild) + numNodes(curr.lChild)); } public int numFullNodesBT() { return numNodes(root); } public int numFullNodesBT(Node curr) { int count; if (curr == null) return 0; count = numFullNodesBT(curr.rChild) + numFullNodesBT(curr.lChild); if (curr.rChild != null && curr.lChild != null) count++; return count; } public int maxLengthPathBT() { return maxLengthPathBT(root); } private int maxLengthPathBT(Node curr)// diameter { int max; int leftPath, rightPath; int leftMax, rightMax; if (curr == null) return 0; leftPath = TreeDepth(curr.lChild); rightPath = TreeDepth(curr.rChild); max = leftPath + rightPath + 1; leftMax = maxLengthPathBT(curr.lChild); rightMax = maxLengthPathBT(curr.rChild); if (leftMax > max) max = leftMax; if (rightMax > max) max = rightMax; return max; } public int numLeafNodes() { return numLeafNodes(root); } private int numLeafNodes(Node curr) { if (curr == null) return 0; if (curr.lChild == null && curr.rChild == null) return 1; else return (numLeafNodes(curr.rChild) + numLeafNodes(curr.lChild)); } public int sumAllBT() { return sumAllBT(root); } private int sumAllBT(Node curr) { int sum, leftSum, rightSum; if (curr == null) return 0; rightSum = sumAllBT(curr.rChild); leftSum = sumAllBT(curr.lChild); sum = rightSum + leftSum + curr.value; return sum; } public void iterativePreOrder() { ArrayDeque<Node> stk = new ArrayDeque<Node>(); Node curr; if (root != null) stk.add(root); while (stk.isEmpty() == false) { curr = stk.pop(); System.out.print(curr.value + " "); if (curr.rChild != null) stk.push(curr.rChild); if (curr.lChild != null) stk.push(curr.lChild); } } public void iterativePostOrder() { ArrayDeque<Node> stk = new ArrayDeque<Node>(); ArrayDeque<Integer> visited = new ArrayDeque<Integer>(); Node curr; int vtd; if (root != null) { stk.add(root); visited.add(0); } while (stk.isEmpty() == false) { curr = stk.pop(); vtd = visited.pop(); if (vtd == 1) { System.out.print(curr.value + " "); } else { stk.push(curr); visited.push(1); if (curr.rChild != null) { stk.push(curr.rChild); visited.push(0); } if (curr.lChild != null) { stk.push(curr.lChild); visited.push(0); } } } } public void iterativeInOrder() { ArrayDeque<Node> stk = new ArrayDeque<Node>(); ArrayDeque<Integer> visited = new ArrayDeque<Integer>(); Node curr; int vtd; if (root != null) { stk.add(root); visited.add(0); } while (stk.isEmpty() == false) { curr = stk.pop(); vtd = visited.pop(); if (vtd == 1) { System.out.print(curr.value + " "); } else { if (curr.rChild != null) { stk.push(curr.rChild); visited.push(0); } stk.push(curr); visited.push(1); if (curr.lChild != null) { stk.push(curr.lChild); visited.push(0); } } } } public boolean isBST3(Node root) { if (root == null) return true; if (root.lChild != null && FindMax(root.lChild).value > root.value) return false; if (root.rChild != null && FindMin(root.rChild).value <= root.value) return false; return (isBST3(root.lChild) && isBST3(root.rChild)); } public boolean isBST() { return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } public boolean isBST(Node curr, int min, int max) { if (curr == null) return true; if (curr.value < min || curr.value > max) return false; return isBST(curr.lChild, min, curr.value) && isBST(curr.rChild, curr.value, max); } class counter { int value; } public boolean isBST2() { counter c = new counter(); return isBST2(root, c); } private boolean isBST2(Node root, counter count)/* in order traversal */ { boolean ret; if (root != null) { ret = isBST2(root.lChild, count); if (!ret) return false; if (count.value > root.value) return false; count.value = root.value; ret = isBST2(root.rChild, count); if (!ret) return false; } return true; } // void DFS(Node head) // { // Node curr = head, prev; // int count = 0; // while (curr && ! curr.visited) // { // count++; // if (curr.lChild && ! curr.lChild.visited) // { // curr= curr.lChild; // } // else if (curr.rChild && ! curr.rChild.visited) // { // curr= curr.rChild; // } // else // { // System.out.print((" " + curr.value); // curr.visited = 1; // curr = head; // } // } // System.out.print(("count is : " + count); // } public Node treeToListRec() { Node head = treeToListRec(root); Node temp = head; return temp; } private Node treeToListRec(Node curr) { Node Head = null, Tail = null; if (curr == null) return null; if (curr.lChild == null && curr.rChild == null) { curr.lChild = curr; curr.rChild = curr; return curr; } if (curr.lChild != null) { Head = treeToListRec(curr.lChild); Tail = Head.lChild; curr.lChild = Tail; Tail.rChild = curr; } else Head = curr; if (curr.rChild != null) { Node tempHead = treeToListRec(curr.rChild); Tail = tempHead.lChild; curr.rChild = tempHead; tempHead.lChild = curr; } else Tail = curr; Head.lChild = Tail; Tail.rChild = Head; return Head; } public void printAllPath() { ArrayDeque<Integer> stk = new ArrayDeque<Integer>(); printAllPath(root, stk); } private void printAllPath(Node curr, ArrayDeque<Integer> stk) { if (curr == null) return; stk.push(curr.value); if (curr.lChild == null && curr.rChild == null) { System.out.println(stk); stk.pop(); return; } printAllPath(curr.rChild, stk); printAllPath(curr.lChild, stk); stk.pop(); } public int LCA(int first, int second) { Node ans = LCA(root, first, second); if (ans != null) return ans.value; else return Integer.MIN_VALUE; } private Node LCA(Node curr, int first, int second) { Node left, right; if (curr == null) return null; if (curr.value == first || curr.value == second) return curr; left = LCA(curr.lChild, first, second); right = LCA(curr.rChild, first, second); if (left != null && right != null) return curr; else if (left != null) return left; else return right; } public int LcaBST(int first, int second) { return LcaBST(root, first, second); } private int LcaBST(Node curr, int first, int second) { if (curr == null) { return Integer.MAX_VALUE; } if (curr.value > first && curr.value > second) { return LcaBST(curr.lChild, first, second); } if (curr.value < first && curr.value < second) { return LcaBST(curr.rChild, first, second); } return curr.value; } public void trimOutsideRange(int min, int max) { trimOutsideRange(root, min, max); } private Node trimOutsideRange(Node curr, int min, int max) { if (curr == null) return null; curr.lChild = trimOutsideRange(curr.lChild, min, max); curr.rChild = trimOutsideRange(curr.rChild, min, max); if (curr.value < min) { return curr.rChild; } if (curr.value > max) { return curr.lChild; } return curr; } public void printInRange(int min, int max) { printInRange(root, min, max); } private void printInRange(Node root, int min, int max) { if (root == null) return; printInRange(root.lChild, min, max); if (root.value >= min && root.value <= max) System.out.print(root.value + " "); printInRange(root.rChild, min, max); } public int FloorBST(int val) { Node curr = root; int floor = Integer.MAX_VALUE; while (curr != null) { if (curr.value == val) { floor = curr.value; break; } else if (curr.value > val) { curr = curr.lChild; } else { floor = curr.value; curr = curr.rChild; } } return floor; } public int CeilBST(int val) { Node curr = root; int ceil = Integer.MIN_VALUE; while (curr != null) { if (curr.value == val) { ceil = curr.value; break; } else if (curr.value > val) { ceil = curr.value; curr = curr.lChild; } else { curr = curr.rChild; } } return ceil; } public int findMaxBT() { int ans = findMaxBT(root); return ans; } private int findMaxBT(Node curr) { int left, right; if (curr == null) return Integer.MIN_VALUE; int max = curr.value; left = findMaxBT(curr.lChild); right = findMaxBT(curr.rChild); if (left > max) max = left; if (right > max) max = right; return max; } public boolean searchBT(Node root, int value) { boolean left, right; if (root == null) return false; if (root.value == value) return true; left = searchBT(root.lChild, value); if (left) return true; right = searchBT(root.rChild, value); if (right) return true; return false; } public void CreateBinaryTree(int[] arr) { root = CreateBinaryTree(arr, 0, arr.length - 1); } private Node CreateBinaryTree(int[] arr, int start, int end) { Node curr = null; if (start > end) return null; int mid = (start + end) / 2; curr = new Node(arr[mid]); curr.lChild = CreateBinaryTree(arr, start, mid - 1); curr.rChild = CreateBinaryTree(arr, mid + 1, end); return curr; } public static void main(String[] args) { Tree t = new Tree(); int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; t.levelOrderBinaryTree(arr); t.NthInOrder(4); t.NthPostOrder(4); t.NthPreOrder(4); /* * t.PrintPostOrder(); System.out.println(); t.iterativePostOrder(); */ // t.PrintBredthFirst(); // t.treeToListRec(); // t.printAllPath(); // System.out.println(t.LCA(10, 3)); // System.out.println(t.()); // t.iterativePreOrder(); // t.PrintPreOrder(); // t.CreateBinaryTree(arr); // System.out.println(t.isBST2()); } }
package pl.edu.agh.cyberwej.web.beans.views.user; import java.util.List; import javax.annotation.PostConstruct; import pl.edu.agh.cyberwej.business.services.api.InvitationService; import pl.edu.agh.cyberwej.data.objects.Invitation; import pl.edu.agh.cyberwej.data.objects.User; import pl.edu.agh.cyberwej.web.beans.common.BaseBean; import pl.edu.agh.cyberwej.web.beans.common.SessionContextBean; public class NotificationBean extends BaseBean { private SessionContextBean sessionContextBean; private User loggedUser; private List<Invitation> invitations; private InvitationService invitationService; public SessionContextBean getSessionContextBean() { return sessionContextBean; } public void setSessionContextBean(SessionContextBean sessionContextBean) { this.sessionContextBean = sessionContextBean; } public User getLoggedUser() { return loggedUser; } public void setLoggedUser(User loggedUser) { this.loggedUser = loggedUser; } public List<Invitation> getInvitations() { return invitations; } public void setInvitations(List<Invitation> invitations) { this.invitations = invitations; } public InvitationService getInvitationService() { return invitationService; } public void setInvitationService(InvitationService invitationService) { this.invitationService = invitationService; } @PostConstruct public void init() { this.loggedUser = sessionContextBean.getLoggedUser(); this.invitations = invitationService.getInviationsForUser(loggedUser, true); } public String acceptInvitation() { String parameter = getParameter("invitationId"); this.invitationService.acceptInvitationById(Integer.parseInt(parameter), true); return "main"; } }
package com.expriceit.maserven.mismodelos; /** * Created by stalyn on 16/1/2018. */ public class MsDetallesPedidos { }
package pt.joja; import java.util.Arrays; import java.util.Random; public class Shell { // h -> 1,4,13,40... public static void main(String[] args) { int nums = 100; Random rand = new Random(47); int[] eles = new int[nums]; int[] eles2 = new int[nums]; for (int i = 0; i < nums; i++) { eles[i] = rand.nextInt(1000); } System.arraycopy(eles, 0, eles2, 0, nums); System.out.println(Arrays.toString(eles)); sort(eles); // sortWithDifferentH(eles); System.out.println(Arrays.toString(eles)); } public static void sort(int[] nums) { int h = 1; while (h < nums.length) { h = h * 3 + 1; } int compCtr = 0; int swapCtr = 0; while (h > 0) { for (int i = 0; i < h; i++) { for (int j = i + h; j < nums.length; j += h) { for (int k = j; k >= h; k -= h) { compCtr++; if (nums[k - h] > nums[k]) { int temp = nums[k - h]; nums[k - h] = nums[k]; nums[k] = temp; swapCtr++; } else { break; } } } } h = h / 3; } // From《算法4》: // 交换次数和比较次数和↑一样的 // while (h > 0) { // for (int i = h; i < nums.length; i++) { // for (int j = i; j >= h; j -= h) { // compCtr++; // if (nums[j - h] > nums[j]) { // int temp = nums[j - h]; // nums[j - h] = nums[j]; // nums[j] = temp; // swapCtr++; // } else { // break; // } // } // } // h = h / 3; // } System.out.println("[Shell.sort] compared: " + compCtr); System.out.println("[Shell.sort] swaped : " + swapCtr); } public static void sortWithDifferentH(int[] nums) { int h = nums.length / 2; int compCtr = 0; int swapCtr = 0; while (h > 0) { for (int i = 0; i < h; i++) { for (int j = i + h; j < nums.length; j += h) { for (int k = j; k >= h; k -= h) { compCtr++; if (nums[k - h] > nums[k]) { int temp = nums[k - h]; nums[k - h] = nums[k]; nums[k] = temp; swapCtr++; } else { break; } } } } h = h / 2; } System.out.println("[Shell.sort] compared: " + compCtr); System.out.println("[Shell.sort] swaped : " + swapCtr); } }
/** page object for page after choosing a product type from white menu (blouses form WOMEN menu). **/ package com.AutoPractice_Selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.interactions.Actions; public class BlousesPage { WebDriver driver; WebElement blouseLink; WebElement categoryName; public BlousesPage(WebDriver driver){ this.driver = driver; this.blouseLink = driver.findElement(By.xpath("//h5/a[@title='Blouse']")); this.categoryName = driver.findElement(By.className("cat-name")); } public void clickOnBlouseLink(){ this.blouseLink.click(); } public String getCategoryName(){ return this.categoryName.getText(); } public void scrollToBlouseLink(){ JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("scroll(0,500)"); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h5/a[@title='Blouse']"))); } }
package com.coreconcepts; public class EnumDemo { enum CoffeeSize { BIG(8),HUGE(12),OVERWHELMING(20); CoffeeSize(int ounces) { this.ounces=ounces; } int ounces; } public static void main(String[] args) { CoffeeSize cs=CoffeeSize.BIG; System.out.println(cs+"Size is: "+cs.ounces); } }
/** * @author TATTYPLAY * @date Jun 15, 2018 * @created 6:46:06 PM * @filename ManagerBan.java * @project Reporter * @package com.tattyhost.reporter.Manager * @copyright 2018 */ package com.tattyhost.reporter.Manager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.mysql.jdbc.PreparedStatement; public class ManagerBan { private ManagerMySQL mysql; private UUID uniqueId; public ManagerBan(ManagerMySQL mysql) { this.mysql = mysql; } /** * @param uniqueId */ public boolean isUserExist() { PreparedStatement ps; ResultSet rs; try { ps = (PreparedStatement) mysql.getConnection(false) .prepareStatement("SELECT * FROM `reportsfinished` WHERE `uuid` = ?"); ps.setString(1, uniqueId.toString()); rs = ps.executeQuery(); return rs.next(); } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean removeEntry() { PreparedStatement ps; try { if (getPlayerInfo().getLong("time") != -1) { if (getRemainingTimeInLong() < 0) { ps = (PreparedStatement) mysql.getConnection(false) .prepareStatement("UPDATE `reportsfinished` SET `banned`='false' WHERE `uuid`=?"); ps.setString(1, uniqueId.toString()); ps.executeUpdate(); return true; } else { return false; } } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } /** * @return * @throws SQLException */ public long getRemainingTimeInLong() throws SQLException { long current = System.currentTimeMillis(); long end = getPlayerInfo().getLong("time"); return end - current; } /** * @return the mysql */ public ManagerMySQL getMysql() { return mysql; } /** * @param mysql * the mysql to set */ public ManagerBan setMysql(ManagerMySQL mysql) { this.mysql = mysql; return this; } /** * @return the playerInfo */ public ResultSet getPlayerInfo() { PreparedStatement ps; ResultSet rs; try { ps = (PreparedStatement) mysql.getConnection(false) .prepareStatement("SELECT * FROM `reportsfinished` WHERE `uuid` = ?"); ps.setString(1, uniqueId.toString()); rs = ps.executeQuery(); rs.next(); return rs; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * @return * @throws SQLException */ public String getRemainingTime() throws SQLException { long current = System.currentTimeMillis(); long end = getPlayerInfo().getLong("time"); long different = end - current; return this.getRemainingTime(different); } /** * @param different * @return */ public String getRemainingTime(long different) { if (different <= -1) { return "Permanent"; } int secounds = 0; int minuts = 0; int hours = 0; int days = 0; int weeks = 0; int months = 0; while (different > 1000) { different -= 1000; secounds++; } while (secounds > 60) { secounds -= 60; minuts++; } while (minuts > 60) { minuts -= 60; hours++; } while (hours > 24) { hours -= 24; days++; } while (days > 7) { days -= 7; weeks++; } while (weeks > 4) { weeks -= 4; months++; } String rm = ""; if (months != 0) { rm += months + " Month/s(4 Weeks) "; } if (weeks != 0) { rm += weeks + " Week/s "; } if (days != 0) { rm += days + " Day/s "; } if (hours != 0) { rm += hours + " Hour/s "; } if (minuts != 0) { rm += minuts + " Minut/s "; } if (secounds != 0) { rm += secounds + " Secound/s "; } if (different != 0) { // rm += different +"Millis "; } return rm; } /** * @return the uniqueId */ public UUID getUniqueId() { return uniqueId; } /** * @param uniqueId * the uniqueId to set */ public ManagerBan setUniqueId(UUID uniqueId) { this.uniqueId = uniqueId; return this; } /** * @param force */ public boolean removeEntry(boolean force) { PreparedStatement ps; try { if(force) { ps = (PreparedStatement) mysql.getConnection(false) .prepareStatement("DELETE FROM `reportsfinished` WHERE `uuid`=?"); ps.setString(1, uniqueId.toString()); ps.executeUpdate(); return true; } else this.removeEntry(); } catch (SQLException e) { e.printStackTrace(); } return false; } /** * @return */ public boolean isBanned() { try { if (getPlayerInfo().getBoolean("banned")) return true; } catch (SQLException e) { e.printStackTrace(); } return false; } }
package com.sry4hacking.partymanager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import java.util.Arrays; public class MainActivity extends AppCompatActivity { LoginButton loginButton; private TextView username; //private UiLifecycleHelper uiHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize Facebook sdk FacebookSdk.sdkInitialize(getApplicationContext()); // Initialize Facebook CallBackManager CallbackManager callbackManager = CallbackManager.Factory.create(); // Initialize Facebook login button and username username = (TextView)findViewById(R.id.tvUsername); loginButton = (LoginButton)findViewById(R.id.login_button); loginButton.setReadPermissions(Arrays.asList("email")); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { } @Override public void onCancel() { } @Override public void onError(FacebookException error) { } }); } }
package cz.malanius.escqrs.escqrsdemo.events; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Date; import java.util.UUID; @Data @EqualsAndHashCode(of = "id") public abstract class Event { protected final UUID id = UUID.randomUUID(); protected final Date created = new Date(); }
package com.dz.service; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.dz.dao.DzImageMainDao; import com.dz.entity.DzImageMain; @RunWith(SpringJUnit4ClassRunner.class) @Transactional @Service("KSellService") @ContextConfiguration({ "classpath:spring/spring-dao.xml" , "classpath:spring/spring-service.xml"}) public class DzImageMainServiceImpl implements DzImageMainService { @Autowired private DzImageMainDao ddao; @Override public DzImageMain getDzImageMainById(String img_id) { return ddao.getDzImageMainById(img_id); } }
package com.flyingh.moguard; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; import com.flyingh.moguard.util.Const; import com.flyingh.moguard.util.LocaleUtils; public class SettingsActivity extends Activity { private static final int DEFAULT = 2; private SharedPreferences sp; private RadioButton chineseRadioButton; private RadioButton englishRadioButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); sp = getSharedPreferences(Const.CONFIG_FILE_NAME, MODE_PRIVATE); chineseRadioButton = (RadioButton) findViewById(R.id.chinese); englishRadioButton = (RadioButton) findViewById(R.id.english); setRadioButtonState(); } private void setRadioButtonState() { int language = sp.getInt(Const.LANGUAGE, DEFAULT); if (language == DEFAULT) { chineseRadioButton.setChecked(false); englishRadioButton.setChecked(false); } else { chineseRadioButton.setChecked(language == 0); englishRadioButton.setChecked(language == 1); } } public void changeLang(View view) { int position = getPosition(view.getId()); if (hasChanged(position)) { showConfirmDialog(position); } } private boolean hasChanged(int position) { return sp.getInt(Const.LANGUAGE, DEFAULT) != position; } private int getPosition(int checkedRadioButtonId) { return checkedRadioButtonId == R.id.chinese ? 0 : 1; } private void showConfirmDialog(final int position) { new AlertDialog.Builder(SettingsActivity.this).setTitle(R.string.confirm_).setMessage(R.string.confirm_to_change_the_display_language_) .setPositiveButton(R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sp.edit().putInt(Const.LANGUAGE, position).commit(); LocaleUtils.changeLocale(SettingsActivity.this); ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); am.killBackgroundProcesses(getPackageName()); Intent intent = new Intent(SettingsActivity.this, SplashActivity.class); startActivity(intent); } }).setNegativeButton(R.string.cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setRadioButtonState(); } }).show(); } }
package baraja; public class Carta { private char simbolo; private char tipo; public void setSimb(char sim) { this.simbolo = sim; } public void setTipo(char tip) { this.tipo = tip; } public char getSimb() { return this.simbolo; } public char getTipo() { return this.tipo; } public int valor() { if(this.simbolo=='T') return 10; else if (this.simbolo == 'J') { return 11; } else if (this.simbolo == 'Q') { return 12; } else if (this.simbolo == 'K') { return 13; } else if (this.simbolo == 'A') { return 1; } else { return Integer.parseInt(this.simbolo + ""); } } public String toString() { return this.simbolo + "" + this.tipo; } }
package com.detect.db; public class AbstractDataAccessObject { public AbstractDataAccessObject() { new ConnectionFactory().getConnection(); } }
package org.qw3rtrun.aub.engine.vectmath; import org.junit.Test; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.qw3rtrun.aub.engine.Matchers.EPSILON; import static org.qw3rtrun.aub.engine.Matchers.nearTo; import static org.qw3rtrun.aub.engine.vectmath.Matrix4f.matr; import static org.qw3rtrun.aub.engine.vectmath.Matrix4f.rows; import static org.qw3rtrun.aub.engine.vectmath.Vector4f.*; public class Vector4fTest { @Test public void testComponent() { assertThat(vect4f(1, 3, -5, 5), nearTo(vect4f().x(1).y(3).z(-5).w(5))); assertThat(vect4f(1, 3, -5), nearTo(vect4f(1, 1, 1).add(0, 2, -6))); assertThat(vect4f(1, 3, -5), nearTo(vect4f(1, 1, 1).addX(0).addY(2).addZ(-6))); assertThat(vect4f(1, 3, -5, 5), nearTo(vect4f(1, 1, 1).addX(0).addY(2).addZ(-6).addW(5))); } @Test public void testBound() { assertEquals(0, ZERO.bound(), EPSILON); assertEquals(1, X.bound(), EPSILON); assertEquals(1, Y.bound(), EPSILON); assertEquals(1, Z.bound(), EPSILON); assertEquals(1, XY.bound(), EPSILON); assertEquals(1, XZ.bound(), EPSILON); assertEquals(1, YZ.bound(), EPSILON); assertEquals(1, XYZ.bound(), EPSILON); assertEquals(3, vect4f(3, -3, 3).bound(), EPSILON); assertEquals(3, vect4f(-1, -3, -3).bound(), EPSILON); assertEquals(100, vect4f(-1, -3, -3, 100).bound(), EPSILON); assertEquals(3, vect4f(-1, -3, -3, 1).bound(), EPSILON); } @Test public void testDistanceBound() { assertEquals(0, ZERO.distanceBound(ZERO), EPSILON); assertEquals(0, Y.distanceBound(Y), EPSILON); assertEquals(0, XZ.distanceBound(XZ), EPSILON); assertEquals(0, vect4f(5, -3, 4).distanceBound(vect4f(5, -3, 4)), EPSILON); } @Test public void testDotProduct() { assertEquals(0, ZERO.dotProduct(vect4f(5, 0, 1)), EPSILON); assertEquals(0, ZERO.dotProduct(ZERO), EPSILON); assertEquals(1, X.length(), EPSILON); assertEquals(1, Y.length(), EPSILON); assertEquals(1, Z.length(), EPSILON); assertEquals(Math.sqrt(1 + 1), XY.length(), EPSILON); assertEquals(Math.sqrt(1 + 1), XZ.length(), EPSILON); assertEquals(Math.sqrt(1 + 1), YZ.length(), EPSILON); assertEquals(Math.sqrt(1 + 1 + 1), XYZ.length(), EPSILON); } @Test public void testLength() { assertEquals(0, ZERO.length(), EPSILON); assertEquals(1, X.length(), EPSILON); assertEquals(1, Y.length(), EPSILON); assertEquals(1, Z.length(), EPSILON); assertEquals(Math.sqrt(1 + 1), XY.length(), EPSILON); assertEquals(Math.sqrt(1 + 1), XZ.length(), EPSILON); assertEquals(Math.sqrt(1 + 1), YZ.length(), EPSILON); assertEquals(Math.sqrt(1 + 1 + 1), XYZ.length(), EPSILON); assertEquals(Math.sqrt(9 + 9 + 9), vect4f(3, -3, 3).length(), EPSILON); assertEquals(Math.sqrt(1 + 9 + 9), vect4f(-1, -3, -3).length(), EPSILON); assertEquals(Math.sqrt(1 + 9 + 9 + 1), vect4f(-1, -3, -3, 1).length(), EPSILON); assertEquals(Math.sqrt(1 + 9 + 9 + 1), vect4f(-1, -3, -3, -1).length(), EPSILON); } @Test public void testEqual() { assertThat(ZERO, not(nearTo(X))); assertThat(X, not(nearTo(Y))); assertThat(X, not(nearTo(XY))); assertThat(ZERO, not(nearTo(YZ))); assertEquals(ZERO, vect4f(0, 0, 0)); assertEquals(X, vect4f(1, 0, 0)); assertEquals(X, vect4f(1, 0, -0)); assertEquals(XW, vect4f(1, 0, 0, 1)); } @Test public void testInverse() { assertThat(X.inverse(), nearTo(vect4f(-1, -0f, -0f))); assertThat(X.inverse(), nearTo(vect4f(-1, 0, 0))); assertThat(vect4f(-5, -4, -3).inverse(), nearTo(vect4f(5, 4, 3))); } @Test public void testSimpleScale() { Vector4f v = vect4f(1, 0, -2); assertThat(v.multiply(1), nearTo(v)); assertThat(v.multiply(0), nearTo(ZERO)); assertThat(v.multiply(2.5f), nearTo(vect4f(2.5f, 0, -5))); assertThat(v.multiply(-3f), nearTo(vect4f(-3, 0, 6))); } @Test public void testAddAll() { Vector4f v = vect4f(1, 0, -2); assertThat(v.addAll(), nearTo(v)); assertThat(v.add(1, 2, 3), nearTo(v.addAll(vect4f(1, 2, 3)))); assertThat(v.add(1, 2, 3).add(4, 2, 0), nearTo(v.addAll(vect4f(1, 2, 3), vect4f(4, 2, 0)))); } @Test public void normalize() throws Exception { float norm = (float) (1 / Math.sqrt(3)); assertThat(vect4f(norm, norm, norm), nearTo(vect4f(3, 3, 3).normalize())); assertThat(vect4f(norm, -norm, norm), nearTo(vect4f(3, -3, 3).normalize())); } @Test public void multiply() throws Exception { assertThat(X.multiply(Y), nearTo(rows(Y, ZERO, ZERO, ZERO))); assertThat(X.multiply(X), nearTo(rows(X, ZERO, ZERO, ZERO))); assertThat(Z.multiply(X), nearTo(rows(ZERO, ZERO, X, ZERO))); assertThat(XYZW.multiply(ZERO), nearTo(rows(ZERO, ZERO, ZERO, ZERO))); assertThat(ZERO.multiply(XYZW.inverse()), nearTo(rows(ZERO, ZERO, ZERO, ZERO))); assertThat(vect4f(1, 2, 3).multiply(vect4f(3, 2, 1)), nearTo(matr(3, 2, 1, 0, 6, 4, 2, 0, 9, 6, 3, 0, 0, 0, 0, 0))); } @Test public void product() { // Base right-hand coordinate system rule assertThat(X.product(Y), nearTo(Z)); assertThat(Y.product(Z), nearTo(X)); assertThat(Z.product(X), nearTo(Y)); assertThat(ZERO.product(XYZ), nearTo(ZERO)); assertThat(vect4f(2, 1, 3).product(vect4f(3, 2, 1)), nearTo(vect4f(-5, 7, 1))); } }
package com.fanfte.listener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * Created by tianen on 2018/9/7 * * @author fanfte * @date 2018/9/7 **/ @Component public class DemoPublisher { @Autowired private ApplicationContext applicationContext; public void publish(String message) { applicationContext.publishEvent(new DemoEvent(this, message)); } }
package quiz.model; import java.time.LocalDate; public class Match { private String opponent; private int runsScored; private int ballsTaken; private int runsConceded; private int ballsbowled; private Ground venue; private int matchNumber; private LocalDate matchDate; private String team1Name; private boolean day; public Match(String opponent, int runsScored, int ballsTaken, int runsConceded, int ballsbowled, Ground venue, int matchNumber, LocalDate matchDate, String team1Name, boolean day) { super(); this.opponent = opponent; this.runsScored = runsScored; this.ballsTaken = ballsTaken; this.runsConceded = runsConceded; this.ballsbowled = ballsbowled; this.venue = venue; this.matchNumber = matchNumber; this.matchDate = matchDate; this.team1Name = team1Name; this.day = day; } public String getOpponent() { return opponent; } public int getRunsScored() { return runsScored; } public int getBallsTaken() { return ballsTaken; } public int getRunsConceded() { return runsConceded; } public int getBallsbowled() { return ballsbowled; } public Ground getVenue() { return venue; } public int getMatchNumber() { return matchNumber; } public LocalDate getMatchDate() { return matchDate; } public String getTeam1Name() { return team1Name; } public int getTotalRunsScored() { return runsConceded + runsScored; } public boolean isDay() { return day; } @Override public String toString() { return "Match [opponent=" + opponent + ", runsScored=" + runsScored + ", ballsTaken=" + ballsTaken + ", runsConceded=" + runsConceded + ", ballsbowled=" + ballsbowled + ", venue=" + venue + ", matchNumber=" + matchNumber + ", matchDate=" + matchDate + ", team1Name=" + team1Name + ", day=" + day + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((matchDate == null) ? 0 : matchDate.hashCode()); result = prime * result + matchNumber; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Match other = (Match) obj; if (matchDate == null) { if (other.matchDate != null) return false; } else if (!matchDate.equals(other.matchDate)) return false; if (matchNumber != other.matchNumber) return false; return true; } }
package com.small.lx_0116; import com.google.gson.Gson; public class CartModel { public void ShopCart(final CartModelCallBack cartModelCallBack) { HttpUtils httpsUtils = HttpUtils.getHttpUtils(); httpsUtils.doGet(Constant.SHOPPINGCART_URL, new HttpUtils.IOKHttpUtilsCallBack() { @Override public void onFailure(String error) { cartModelCallBack.getFaid(error); } @Override public void onResponse(String json) { ShoppingCartBean shoppingCartBean = new Gson().fromJson(json, ShoppingCartBean .class); if (shoppingCartBean.getCode().equals("0")) { cartModelCallBack.getSuccess(shoppingCartBean); } else { cartModelCallBack.getFaid("未加载"); } } }); } //接口回调 public interface CartModelCallBack { void getSuccess(ShoppingCartBean shoppingCartBean); void getFaid(String error); } }
/* * Created on 2004-11-18 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.aof.component.helpdesk; /** * @author shilei * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class DetailAttachment extends Attachment { private byte[] content; /** * @return Returns the pic. */ public byte[] getContent() { return content; } /** * @param pic The pic to set. */ public void setContent(byte[] content) { this.content = content; } }
package cogent.demo.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import cogent.demo.model.Row; @Repository public interface RowDao extends JpaRepository<Row, Integer> { List<Row> findByFloor(int floor); }
package com.dg.android.lcp.activities; import java.util.List; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.dg.android.lcp.objects.SessionManager; import com.dg.android.lcp.utils.MapMarker; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; import com.google.android.maps.Projection; public class GoogleMapActivity extends MapActivity { GeoPoint eventPoint, centerPoint, centrePintUser; Context context; String TAG = "Google map"; MapView mapView; GeoPoint point; Projection projection; double latitude; double longitude; String cityName; String address; String zipCode; Bundle extras; Location myLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; setContentView(R.layout.google_maps); Log.i(TAG, "Activity called"); extras = getIntent().getExtras(); latitude = extras.getDouble("latitude"); longitude = extras.getDouble("longitude"); address = extras.getString("address"); Log.i("information is ----------", "name" + cityName + " addrsess" + address + "zip code" + zipCode); mapView = (MapView) findViewById(R.id.mapView); mapView.setSatellite(false); mapView.setBuiltInZoomControls(true); Log.i("Latitu-----------", "Lat is " + latitude + " long is " + longitude); eventPoint = new GeoPoint((int) (latitude), (int) (longitude)); centerPoint = new GeoPoint((int) (latitude * 1e6), (int) (longitude * 1e6)); List<Overlay> mapOverlays = mapView.getOverlays(); Drawable drawable = this.getResources().getDrawable(R.drawable.map_default_marker); MapMarker mapMarker = new MapMarker(drawable, this, LAYOUT_INFLATER_SERVICE, findViewById(R.id.layout_root), address); OverlayItem overlayitem = new OverlayItem(centerPoint, "Map", "test"); mapMarker.addOverlay(overlayitem); mapOverlays.add(mapMarker); mapView.getController().setCenter(centerPoint); mapView.getController().setZoom(17); projection = mapView.getProjection(); mapView.invalidate(); } @Override protected boolean isRouteDisplayed() { return true; } private void updateWithNewLocation(Location location) { if (location != null) { myLocation = location; } } /** * Menu items are created here */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.aroma_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menulocations: showLocations(); return true; case R.id.menurewards: showRewards(); return true; case R.id.menuwall: showWall(); return true; case R.id.menuinfo: showInfo(); return true; default: return false; } } public void showLocations() { Intent i = new Intent(this, LocationListingActivity.class); startActivity(i); } public void showRewards() { if (!SessionManager.isUserLoggedIn(this)) { Intent i = new Intent(this, LoginSignupActivity.class); SessionManager.setNextActivity(context, "2"); startActivity(i); return; } Intent i = new Intent(this, RewardListActivity.class); startActivity(i); } public void showInfo() { Intent i = new Intent(this, InfoActivity.class); startActivity(i); } public void showWall() { Intent i = new Intent(this, FaceBookTabActivity.class); startActivity(i); } }
package bn.commandline.distributions; import java.io.PrintStream; import java.util.HashMap; import java.util.regex.Pattern; import util.Parser.ParserException; import util.Parser.ParserFunction; import bn.BNException; import bn.distributions.DiscreteCPTUC; import bn.distributions.Distribution; import bn.commandline.distributions.CPDCreator.ICPDCreator; class DiscreteCPTUCCreator implements ICPDCreator { static DiscreteCPTUCCreator getFactory() { return new DiscreteCPTUCCreator(null,null,0); } private DiscreteCPTUCCreator(HashMap<String, Distribution> distmap, String name, int cardinality) { this.distmap = distmap; this.name = name; this.cardinality = cardinality; } public void finish() throws ParserException{} public ParserFunction parseLine(String[] args, PrintStream str) throws ParserException { try { String [] ps = args[0].split("\\s+"); if(ps.length!=this.cardinality) throw new ParserException("Expected " + this.cardinality + " probabilities"); double[] vec = new double[this.cardinality]; try { for(int i = 0; i < this.cardinality; i++) vec[i] = Double.parseDouble(ps[i]); } catch(NumberFormatException e) { throw new ParserException("Invalid probability..."); } DiscreteCPTUC dist = new DiscreteCPTUC(vec); this.distmap.put(name, dist); return null; } catch(BNException e) { throw new ParserException(e.getMessage()); } } public ICPDCreator newCreator(String name, String argstr, HashMap<String, Distribution> distMap) throws ParserException { try{ return new DiscreteCPTUCCreator(distMap,name,Integer.parseInt(argstr)); } catch(NumberFormatException e) { throw new ParserException("Expected argument to probability vector to be the cardinality."); } } public String name(){return "PV";} public String description(){return "Creates a distribution that is a probability vector. A node with this distribution" + " cannot have any parents, and is selected as a multinomial from the parameters.\n\nEx:\n\tA<PV(3)\n.3 .5 .2\n\n" + "This creates a probability distribution that selects 0 with probability .3, etc. and names it A";} private String name; private int cardinality; public final int[] getGroups() {return groups;} public final Pattern getRegEx() {return patt;} public final String getPrompt() {return "Enter probability vector: ";} private HashMap<String,Distribution> distmap; private static int[] groups = new int[]{1}; private static Pattern patt = Pattern.compile("\\[?\\s*(([\\.e\\-0-9E]+\\s*)+)\\]?"); }
package com.thomson.dp.principle.zen.lsp; import com.thomson.dp.principle.zen.lsp.domain.AUG; import com.thomson.dp.principle.zen.lsp.domain.Snipper; /** * 狙击枪业务场景类 * 可以体现里氏替换原则中"子类可以有自己的特定方法"的含义。 * * @author Thomson Tang */ public class SnipperClient { public static void main(String[] args) { //生成三毛狙击手 Snipper sanMao = new Snipper(); //杀敌 sanMao.killEnemy(new AUG()); //这里系统直接调用了子类,一个狙击手是很依赖枪支的 } }
import java.io.*; import javax.servlet.*; public class PRINT_TABLE extends GeniricServlet { int t,i,num; public void init(){ num=2; } public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { for(i=1;i<=10;i++){ t=num*i; out.println(+num+"*"+i+"="+t); } } finally { out.close(); } } }
package org.sunshinelibrary.turtle.utils; /** * Created with IntelliJ IDEA. * User: solomon * Date: 14-3-20 * Time: PM5:26 */ public class RemoteCookie { public String cookieDomain; public String cookiePath; public String value; public String name; public boolean isSecure; public int cookieVersion; }
package com.legaoyi.client.messagebody.encoder; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import com.legaoyi.protocol.exception.IllegalMessageException; import com.legaoyi.protocol.message.MessageBody; import com.legaoyi.protocol.message.encoder.MessageBodyEncoder; import com.legaoyi.client.up.messagebody.Tjsatl_2017_0900_MessageBody; import com.legaoyi.protocol.util.ByteUtils; import com.legaoyi.protocol.util.MessageBuilder; /** * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2018-08-07 */ @Component(MessageBodyEncoder.MESSAGE_BODY_ENCODER_BEAN_PREFIX + "0900_tjsatl" + MessageBodyEncoder.MESSAGE_BODY_ENCODER_BEAN_SUFFIX) public class Tjsatl_2017_0900_MessageBodyEncoder implements MessageBodyEncoder { @Override public byte[] encode(MessageBody message) throws IllegalMessageException { try { Tjsatl_2017_0900_MessageBody messageBody = (Tjsatl_2017_0900_MessageBody) message; MessageBuilder mb = new MessageBuilder(); mb.addByte(messageBody.getType()); List<Map<String, Object>> list = messageBody.getMessageList(); mb.addByte(list.size()); if (messageBody.getType() == 0xf7) { for (Map<String, Object> map : list) { mb.addByte((int) map.get("deviceId")); mb.addByte(5); mb.addByte((int) map.get("state")); mb.addDword((int) map.get("alarm")); } } else if (messageBody.getType() == 0xf8) { for (Map<String, Object> map : list) { mb.addByte((int) map.get("deviceId")); MessageBuilder mb1 = new MessageBuilder(); byte[] bytes = ByteUtils.ascii2bytes((String) map.get("enterpriseName")); mb1.addByte(bytes.length); mb1.append(bytes); bytes = ByteUtils.ascii2bytes((String) map.get("productType")); mb1.addByte(bytes.length); mb1.append(bytes); bytes = ByteUtils.ascii2bytes((String) map.get("hardwareVersion")); mb1.addByte(bytes.length); mb1.append(bytes); bytes = ByteUtils.ascii2bytes((String) map.get("softwareVersion")); mb1.addByte(bytes.length); mb1.append(bytes); bytes = ByteUtils.ascii2bytes((String) map.get("deviceId")); mb1.addByte(bytes.length); mb1.append(bytes); bytes = ByteUtils.ascii2bytes((String) map.get("clientCode")); mb1.addByte(bytes.length); mb1.append(bytes); mb.append(mb1.getBytes()); } } return mb.getBytes(); } catch (Exception e) { throw new IllegalMessageException(e); } } }
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * android.text.TextUtils */ package com.ideabus.contec_sdk.verify; import android.text.TextUtils; public class ContecFoetalEncryptUtils { private native int getDeviceKey(byte[] var1, byte[] var2, byte[] var3); private native int getAppKey(byte[] var1, byte[] var2, byte[] var3); public int a(byte[] arrby, byte[] arrby2, String string) { if (TextUtils.isEmpty((CharSequence)string)) { return -3; } byte[] arrby3 = string.getBytes(); if (arrby3.length > 7) { return -6; } byte[] arrby4 = new byte[7]; if (arrby3.length == 7) { arrby4 = arrby3; } else if (arrby3.length < 7) { for (int i = 0; i < arrby3.length; ++i) { arrby4[i] = arrby3[i]; } } return this.getAppKey(arrby, arrby2, arrby4); } public int b(byte[] arrby, byte[] arrby2, String string) { if (TextUtils.isEmpty((CharSequence)string)) { return -3; } byte[] arrby3 = string.getBytes(); if (arrby3.length > 7) { return -6; } byte[] arrby4 = new byte[7]; if (arrby3.length == 7) { arrby4 = arrby3; } else if (arrby3.length < 7) { for (int i = 0; i < arrby3.length; ++i) { arrby4[i] = arrby3[i]; } } return this.getDeviceKey(arrby, arrby2, arrby4); } static { System.loadLibrary("ContecFoetalEncrypt-1.0"); } }
package com.newbig.im.model.dto; import javax.validation.constraints.NotNull; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * User: Haibo * Date: 2018-06-03 15:50:00 * Desc: */ @Setter @Getter @ToString public class SysOrgDeleteDto { @ApiModelProperty("id") @NotNull(message = "id不能为空") private Long id; }
package juego; import java.awt.Rectangle; import java.lang.Math; public class Racket extends Actor { public int w; public int h; public Racket(int x, int y, int w, int h, double dx, double dy) { super(x, y, dx, dy); this.w = w; this.h = h; } public boolean colision(Model b) { return (Math.sqrt(Math.pow(this.x+this.dx - b.c.x, 2) + Math.pow(this.y+this.dy - b.c.y, 2)) >( b.c.r)); } public boolean colision2(Model b) { return Math.sqrt(Math.pow(this.w+x+this.dx - b.c.x, 2) + Math.pow(this.h+y+this.dy - b.c.y, 2)) >( b.c.r); } public boolean colision3(Model b) { return Math.sqrt(Math.pow(this.x+w+this.dx - b.c.x, 2) + Math.pow(this.y+this.dy - b.c.y, 2)) >( b.c.r); } public boolean colision4(Model b) { return Math.sqrt(Math.pow(this.x+this.dx - b.c.x, 2) + Math.pow(this.y+h+this.dy - b.c.y, 2)) >( b.c.r); } @Override public void move(Model m) { if(colision(m) || colision2(m) || colision3(m) || colision4(m)){ dx=0; dy=0; } x += dx; y += dy; } public int getW() { return w; } public int getH() { return h; } public Rectangle getBounds() { return new Rectangle(x, y, w, w); } }
class Solution { public boolean containsDuplicate(int[] nums) { boolean result = false; Arrays.sort (nums); for (int i = 1; i < nums.length; i++){ if(nums[i] == nums[i-1]){ result = true; } } return result; } }
package com.example.hgv; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Random; public class admin extends AppCompatActivity { public Button insert; private ListView driverlistview; private EditText driversedit; public EditText names; public TextView current; String drivers; // private String[] driversnamelist={"Murugan--------234567823---243","Suresh---------7635363738---423","Ramesh---------6536384763---987"}; private ArrayList<String> list = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(getWindow().FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_admin); getSupportActionBar().hide(); list.add("Murugan--------234567823---243"); list.add("Suresh---------7635363738---423"); insert=(Button)findViewById(R.id.insert); driverlistview=(ListView)findViewById(R.id.driverlistview); names=(EditText)findViewById(R.id.insertname); final ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list); insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drivers=names.getText().toString(); list.add(drivers); savearraylist(); adapter.notifyDataSetChanged(); names.setText(""); Toast.makeText(admin.this,"Inserted",Toast.LENGTH_LONG).show(); } }); driverlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view,final int j, long l) { AlertDialog.Builder msgbox = new AlertDialog.Builder(admin.this); msgbox.setTitle("Deletion"); msgbox.setMessage("Are you sure you want to Remove this Driver"); msgbox.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { list.remove(j); savearraylist(); adapter.notifyDataSetChanged(); Toast.makeText(admin.this,"deleted",Toast.LENGTH_SHORT).show(); } }); msgbox.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); msgbox.setCancelable(true); msgbox.create().show(); } }); driverlistview.setAdapter(adapter); loadarraylist(getApplicationContext()); } private void savearraylist(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor =sharedPreferences.edit(); editor.putInt("no.of.drivers",list.size()); for (int i =0;i<list.size();i++){ editor.remove("drivers"+i); editor.putString("drivers"+i,list.get(i)); } editor.commit(); } private void loadarraylist(Context context){ SharedPreferences sharedPreferences2 = PreferenceManager.getDefaultSharedPreferences(context); list.clear(); int size = sharedPreferences2.getInt("no.of.drivers",0); for (int i=0;i<size;i++){ list.add(sharedPreferences2.getString("drivers"+i,null)); } } }
package com.javarush.task.task04.task0443; /* Как назвали, так назвали */ import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); String name = scanner.next(); int y = scanner.nextInt(); int m = scanner.nextInt(); int d = scanner.nextInt(); System.out.printf("Меня зовут %s.\nЯ родился %d.%d.%d",name,d,m,y); } }
package org.lazywizard.localmp.controllers.joypad.buttonmaps; import com.fs.starfarer.api.Global; import org.apache.log4j.Level; import org.lwjgl.LWJGLException; import org.lwjgl.input.Controller; import org.lwjgl.input.Controllers; public class Xbox360 { public static final int BUTTON_A = 0; public static final int BUTTON_B = 1; public static final int BUTTON_X = 2; public static final int BUTTON_Y = 3; public static final int BUTTON_LB = 4; public static final int BUTTON_RB = 5; public static final int BUTTON_BACK = 6; public static final int BUTTON_START = 7; public static final int BUTTON_LSTICK = 8; public static final int BUTTON_RSTICK = 9; public static final int AXIS_LEFT_Y = 0; public static final int AXIS_LEFT_X = 1; public static final int AXIS_RIGHT_Y = 2; public static final int AXIS_RIGHT_X = 3; public static final int AXIS_TRIGGER = 4; public static Controller findValid360Controller() { if (!Controllers.isCreated()) { try { Global.getLogger(Xbox360.class).log(Level.INFO, "Initializing controllers..."); Controllers.create(); } catch (LWJGLException ex) { throw new RuntimeException("Failed to initiate controllers!", ex); } } // Search for Xbox 360 controllers // TODO: Extend this to all valid joypad controllers // Needs 10 buttons and 3 axes to be compatible for (int x = 0; x < Controllers.getControllerCount(); x++) { Controller tmp = Controllers.getController(x); if (tmp.getName().contains("360")) { Global.getLogger(Xbox360.class).log(Level.INFO, "Found valid 360 controller: " + tmp.getName()); // Set controller deadzones for (int y = 0; y < tmp.getAxisCount(); y++) { tmp.setDeadZone(y, .1f); } return tmp; } } // No controller found Global.getLogger(Xbox360.class).log(Level.ERROR, "Failed to find a compatible 360 controller!"); return null; } private Xbox360() { } }
package com.qa.jira_api; import static io.restassured.RestAssured.given; import java.io.File; import org.testng.Assert; import org.testng.annotations.Test; import io.cucumber.java.en.Given; import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; import io.restassured.builder.ResponseSpecBuilder; import io.restassured.filter.session.SessionFilter; import io.restassured.http.ContentType; import io.restassured.path.json.JsonPath; import io.restassured.specification.RequestSpecification; import io.restassured.specification.ResponseSpecification; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; //--------------------login to jira application(session id is created) and create issue in jira application------------------------// public class CreateIssue { // Login, then create session object // @Test public void createSessionId() { //-------------------------- Below lines are common for all test scripts -------------------------------// RestAssured.baseURI = "http://localhost:8080/"; // "session filter" object record the session id returned from the server and automatically apply this session id in subsequent requests.// SessionFilter session = new SessionFilter(); RequestSpecification reqs = new RequestSpecBuilder().setContentType(ContentType.JSON).addFilter(session).build(); ResponseSpecification resp = new ResponseSpecBuilder().expectContentType(ContentType.JSON).build(); //-----------------------------------------------------------------------------------------------------// File file1 = new File("jsonPayloads/createSessionId.json"); RequestSpecification reqs1 = given().spec(reqs).body(file1); // passing json file as data in body() method // String response1 = reqs1.when().post("rest/auth/1/session") .then().spec(resp).assertThat().statusCode(200).extract().response().asString(); JsonPath jsp1 = new JsonPath(response1); String sessionId = jsp1.getString("session.value"); System.out.println("-------------------------------"); System.out.println("Session Id is :- "+sessionId); System.out.println("-------------------------------"); System.out.println("***********************************************************************************************"); //create new issue using session id // RequestSpecification reqs2 = given().spec(reqs).body(new File("jsonPayloads/createIssue.json")); String response2 = reqs2.when().post("rest/api/2/issue") .then().spec(resp).assertThat().statusCode(201).extract().response().asString(); System.out.println("-------------------------------"); System.out.println(response2); JsonPath jsp2 = new JsonPath(response2); String issueId = jsp2.getString("id"); System.out.println("Issue id is :- "+issueId); System.out.println("-------------------------------"); System.out.println("***********************************************************************************************"); // Adds comments to an existing issue // RequestSpecification reqs3 = given().spec(reqs).body(new File("jsonPayloads/addcomment.json")).pathParam("key",issueId); // issue id through path parameter// String response3 = reqs3.when().post("rest/api/2/issue/{key}/comment") .then().spec(resp).assertThat().statusCode(201).extract().response().asString(); System.out.println("-------------------------------"); System.out.println(response3); JsonPath jsp3 = new JsonPath(response3); int commentId = jsp3.getInt("id"); String comment = jsp3.getString("body"); System.out.println("Comment id is :- "+commentId); System.out.println("-------------------------------"); System.out.println("***********************************************************************************************"); // adds attachment to an existing issue using multipart(), header("Content-Type","multipart/form-data") // RequestSpecification reqs4 = given().spec(reqs).header("X-Atlassian-Token","no-check").pathParam("key", issueId) .header("Content-Type","multipart/form-data") // .multiPart("file",new File("jira-bug-attachments/Untitled3.png")) .multiPart("file", new File("jira-bug-attachments/exceptions.docx")); String response4 = reqs4.when().post("rest/api/2/issue/{key}/attachments") .then().assertThat().statusCode(200).extract().response().asString(); // if we declare response as json, error will show // System.out.println("-------------------------------"); System.out.println(response4); JsonPath jsp4 = new JsonPath(response4); String attachmentId = jsp4.getString("id"); System.out.println("Attachment id is :- "+attachmentId); System.out.println("-------------------------------"); System.out.println("***********************************************************************************************"); //Get issue details and verify if added comment and attachment exist or not // RequestSpecification reqs5 = given().spec(reqs).pathParam("key", issueId).queryParam("fields", "comment"); String response5 = reqs5.when().get("rest/api/2/issue/{key}") .then().extract().response().asString(); System.out.println("-------------------------------"); System.out.println(response5); JsonPath jsp5 = new JsonPath(response5); int commentsSize = jsp5.getInt("fields.comment.comments.size()"); for(int i=0; i<commentsSize; i++) { int actualCommentId = jsp5.getInt("fields.comment.comments["+i+"].id"); if(commentId == actualCommentId) { String actualComment = jsp5.getString("fields.comment.comments["+i+"].body"); Assert.assertEquals(actualComment, comment); System.out.println("Excepted comment - "+comment); System.out.println("actual comment - "+actualComment); break; } } System.out.println("-------------------------------"); System.out.println("***********************************************************************************************"); // verify added attachment exist or not // RequestSpecification reqs6 = given().spec(reqs).pathParam("key", issueId).queryParam("fields", "attachment"); String response6 = reqs6.when().get("rest/api/2/issue/{key}") .then().extract().response().asString(); System.out.println("-------------------------------"); System.out.println(response6); JsonPath jsp6 = new JsonPath(response6); int attachmentSize = jsp6.getInt("fields.attachment.size()"); for(int j=0; j<attachmentSize; j++) { String actualAttachmentId = jsp6.getString("fields.attachment["+j+"].id"); System.out.println(attachmentId); System.out.println(actualAttachmentId); if((actualAttachmentId.equals(attachmentId))) { String actualAttachmentName = jsp6.getString("fields.attachment["+j+"].filename"); Assert.assertEquals(actualAttachmentName, "exceptions.docx"); System.out.println("Expected attachemnt name - "+"exceptions.docx"); System.out.println("Actual attachemnt name - "+actualAttachmentName); break; } } System.out.println("-------------------------------"); System.out.println("***********************************************************************************************"); } }
package cn.test.java8.java8Optional; import lombok.Data; /** * Created by xiaoni on 2018/12/17. */ @Data public class City { private String name; }
package CPS261SetBasics; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; public class TryOutSetInterface { public static void main(String[] args) { //HashSet iterates in a random fashion //Set<String> set = new HashSet<String>(); //LinkedHashSet maintains the ordering of the insertion //Set<String> set = new LinkedHashSet<String>(); //TreeSet maintains the ordering sorted by "Natural Ordering" Set<String> set = new TreeSet<String>(); set.add("one"); set.add("two"); //set.add(null); // Yes some of the Set implementations allow a null ... but only one if (set.add("three")) System.out.println("three was added"); if (!set.add("three")) System.out.println("three was not added again because it is a duplicate"); if (set.contains("two")) System.out.println("set should contain two"); if (!set.contains("fifty")) System.out.println("set should not contain fifty"); set.add("four"); set.add("five"); set.add("six"); set.add("seven"); set.add("eight"); System.out.println("******* iteration dump ********"); Iterator<String> iter = set.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }
package com.keomala.stattracker.dao; import com.keomala.stattracker.domain.StatInfo; import org.springframework.stereotype.Repository; @Repository public class RetrieveDao { public StatInfo getStatInfoById(int anyInt) { return null; } }
package com.artogrid.framework.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.GenericGenerator; /** * LoginLog entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "idb_login_log", catalog = "idb_center") public class LoginLog implements java.io.Serializable { // Fields private String id; private String loginStatusId; private String accountId; private String username; private String displayName; private String clientType; private String ip; private Date startTime; private Date endTime; private String status; // Constructors /** default constructor */ public LoginLog() { } /** full constructor */ public LoginLog(String loginStatusId, String accountId, String username, String displayName, String clientType, String ip, Date startTime, Date endTime, String status) { this.loginStatusId = loginStatusId; this.accountId = accountId; this.username = username; this.displayName = displayName; this.clientType = clientType; this.ip = ip; this.startTime = startTime; this.endTime = endTime; this.status = status; } // Property accessors @GenericGenerator(name = "generator", strategy = "uuid.hex") @Id @GeneratedValue(generator = "generator") @Column(name = "ID", unique = true, nullable = false, length = 32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name = "LOGIN_STATUS_ID", length = 32) public String getLoginStatusId() { return this.loginStatusId; } public void setLoginStatusId(String loginStatusId) { this.loginStatusId = loginStatusId; } @Column(name = "ACCOUNT_ID", length = 32) public String getAccountId() { return this.accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } @Column(name = "USERNAME", length = 32) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Column(name = "DISPLAY_NAME", length = 32) public String getDisplayName() { return this.displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @Column(name = "CLIENT_TYPE", length = 1) public String getClientType() { return this.clientType; } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "IP", length = 50) public String getIp() { return this.ip; } public void setIp(String ip) { this.ip = ip; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "START_TIME", length = 19) public Date getStartTime() { return this.startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "END_TIME", length = 19) public Date getEndTime() { return this.endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @Column(name = "STATUS", length = 1) public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } }
package org.nhnnext.restaurant.lab1.menu; public class Menu { private MenuItem [] coffees; public Menu(MenuItem [] coffees) { this.coffees = coffees; } public MenuItem choose(String name) { for(MenuItem coffee : coffees) { if (coffee.getName().equals(name)) { return coffee; } } return null; } }
package creational.builder.my.components; public class A { private String name; public A(String name) { this.name = name; } @Override public String toString() { return name; } }
package CATChinaRetail.TestAutomation.Core; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class ReadXML { public static String NodeName(String ElementName) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { String Value = null; // XML Read Options File fXmlFile = new File("./src/main/resources/Elements.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(fXmlFile); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//*[local-name()='" + ElementName + "']"); Value = expr.evaluate(doc); return Value; } }
package utils; import java.util.Arrays; import java.util.List; public class ParseString { public static List<String> parseHeaderData(String line) { String[] lines = line.split("\r\n"); return Arrays.asList(lines); } public static String[] parseFirstLine(String firstLine) { return firstLine.split(" "); } }
package com.rumpel.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfig implements WebMvcConfigurer { @Value("${upload.path}") private String uploadPath; public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/img/**") .addResourceLocations("file://" + uploadPath + "/"); registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/");//что при обращении по путь "/static/** файловые ресурсы будут искаться не гдето в файловой системе а в дереве проекта. От корня проекта ищит в списке классов либо в списке ресурсов. } }
package br.mg.puc.sica.security.server.config; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Component; /** * <p>Classe responsável por armazenar as URLs publicas do sistema.</p> * * @author rafael.altagnam * */ @Component public class URLAllows { private List<String> urls; public URLAllows() { this.urls = Arrays.asList( "/", "/_authorization/**", "csrf", "/error", "/v2/api-docs", "/swagger-resources", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**", "favicon.ico", "/favicon.ico" ); } /** * Retorna a lista de URL's permitidas * @return */ public String[] getUrls () { return (String[]) this.urls.toArray(); } /** * Valida se a requisição tem como endereço paginas de documentaçao do swagger * @param param * @return */ public boolean isSwagger (String param) { if (param.equals("/favicon.ico") || param.equals("csrf") || param.equals("/csrf") || param.equals("/") || param.contains("swagger") || param.contains("v2/api-docs")) { return Boolean.TRUE; } return false; } }
package clientControl; import bean.*; import clientIO.Sender; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Exchange { private ClientJSON clientJSON; public Exchange() { clientJSON = new ClientJSON(); } public void setCommand(String command) { this.clientJSON.setCommand(command); } public void setServerList(String[] serverList) { this.clientJSON.setServerList(serverList); } public void sendRequest() { JSONObject exchangeItems = new JSONObject(); String[] serverLists = clientJSON.getServerList(); JSONArray value = new JSONArray(); for (String serverList : serverLists) { String[] server = serverList.split(":"); exchangeItems.put("hostname", server[0]); exchangeItems.put("port", server[1]); value.add(exchangeItems); } Sender sender = new Sender(); sender.sendRequest(exchangeItems); } }
package com.lexlang.ImageUtil.cut; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * @author lexlang * @version 2019年7月17日 上午9:45:08 * */ public class BulkStatistics { private Map<String,BufferedImage> map=new HashMap<String,BufferedImage>(); /** * 添加数据到块状体内 * @param startX * @param startY * @param endX * @param endY * @param img */ public void addImage(int startX,int startY,int endX,int endY,BufferedImage img){ map.put(startX+"_"+startY+"_"+endX+"_"+endY, img.getSubimage(startX+1, startY+1, endX-startX-2, endY-startY-2)); } /** * 判断坐标是否在块体内 * @param x * @param y * @return */ public boolean checkInBox(int x,int y){ Set<String> keys = map.keySet(); for(String key:keys){ String[] arr=key.split("_"); if(x<Integer.parseInt(arr[2]) && y<Integer.parseInt(arr[3])){ return true; } } return false; } /** * * @return */ public JSONArray getStore(){ JSONArray item=new JSONArray(); Set<String> keys = copySet(map.keySet()); ArrayList<String> list=new ArrayList<String>();//排序结果 while(keys.size()>0 && list.size()<keys.size()){ int maxX=10000; int maxY=10000; String curTemp=""; for(String key:keys){ String[] arr=key.split("_"); if(list.contains(key)){ continue; } if(maxY>Integer.parseInt(arr[1])){ maxX=Integer.parseInt(arr[0]); maxY=Integer.parseInt(arr[1]); curTemp=key; }else if(maxY==Integer.parseInt(arr[1]) && maxX>=Integer.parseInt(arr[0])){ maxX=Integer.parseInt(arr[0]); maxY=Integer.parseInt(arr[1]); curTemp=key; } } list.add(curTemp); } for(int index=0;index<list.size();index++){ int coun=1; JSONArray array=new JSONArray(); if(! (index==list.size()-1)){ while(checkYiHang(list.get(index),list.get(index+coun))){ coun++; if(index+coun>=list.size()-1){ break; } } } if(coun==1){ array.add(map.get(list.get(index))); }else{ for(int i=0;i<coun;i++){ array.add(map.get(list.get(index+i))); } index+=coun-1; } item.add(array); } return item; } public boolean checkYiHang(String aKey,String bKey){ String[] aArr=aKey.split("_"); String[] bArr=bKey.split("_"); int flag=Math.abs(Integer.parseInt(aArr[1])-Integer.parseInt(bArr[1])); if(flag<5){ return true; }else{ return false; } } public Set<String> copySet(Set<String> keys){ Set<String> set=new HashSet<String>(); for(String key:keys){ set.add(key); } return set; } }
package com.utng.course.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.utng.course.entity.Menu; import com.utng.course.service.IMenuService; @Controller @RequestMapping("/menu") public class MenuController { @Autowired private IMenuService menuService; @RequestMapping(value= {"/list", "/"}) public String showmenu(Model model) { List<Menu> lista = menuService.getAll(); return "listMenu"; } }
import java.util.ArrayList; public class TransactionController { private static TransactionController instance = new TransactionController(); private double birthdayDiscount = 0.95; public static TransactionController getInstance() { return instance; } public double completeTransaction(Customer customer) throws BalanceIsNotEnoughException, NoItemInShoppingTrolleyException { ArrayList<TrolleyItem> itemList = customer.getTrolley(); itemList.removeIf(item -> { Company itemCompany = item.getCompany(); Product itemProduct = item.getProduct(); if (!itemCompany.checkExistProduct(itemProduct)) { System.out.printf("%s has been sold out. Automatically removed.\n", itemProduct.getName()); return true; } else { return false; } }); Membership membership = customer.getMembership(); boolean isBirthdayToday = customer.isBirthdayToday(); double totalAmount = calculateProductAmount(itemList, membership,isBirthdayToday); if (customer.getBalance() < totalAmount) throw new BalanceIsNotEnoughException(); if (itemList.isEmpty()) { throw new NoItemInShoppingTrolleyException(); } customer.withdraw(totalAmount); recordTransaction(customer, itemList,membership,isBirthdayToday); updateStockStatus(itemList); if (isBirthdayToday) { System.out .println("You are enjoying your birthday discount! " + (100 - birthdayDiscount * 100) + " % off!"); } System.out.println("You are enjoying your " + membership.toString() + " membership discount! " + (100 - membership.getDiscount() * 100) + " % off!"); System.out.println("You have spent $" + totalAmount + " in total."); itemList.forEach(item -> { System.out.println(itemList.indexOf(item) + 1 + ". " + item.toString()); }); customer.emptyTrolley(); return totalAmount; } private void recordTransaction(Customer customer, ArrayList<TrolleyItem> itemList,Membership membership,boolean isBirthdayToday) { for (TrolleyItem item : itemList) { Company company = item.getCompany(); double totalAmount = item.getTotal() * membership.getDiscount(); if (isBirthdayToday) { totalAmount *= birthdayDiscount; } SaleRecord saleRecord = new SaleRecord(customer,item,totalAmount); company.recordTransaction(saleRecord); } } public double calculateProductAmount(ArrayList<TrolleyItem> itemList, Membership membership,boolean isBirthdayToday) { double totalAmount = 0; for (TrolleyItem item : itemList) { totalAmount += item.getTotal(); } if (isBirthdayToday) { totalAmount *= birthdayDiscount; } return membership.getDiscount() * totalAmount; } public void updateStockStatus(ArrayList<TrolleyItem> itemList) { for (TrolleyItem item : itemList) { Product product = item.getProduct(); int quantity = item.getQuantity(); product.soldProduct(quantity); } } }
package com.appspot.smartshop.utils; import org.json.JSONException; import org.json.JSONObject; public abstract class JSONParser { public static final int SMART_SHOP_JSON = 0; public static final int GOOGLE_DIRECTION_JSON = 1; protected int jsonType = SMART_SHOP_JSON; public abstract void onSuccess(JSONObject json) throws JSONException; public abstract void onFailure(String message); }
package com.fest.pecfestBackend.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.stereotype.Repository; import com.fest.pecfestBackend.entity.EventUsers; @Repository @EnableJpaRepositories public interface EventUsersRepo extends JpaRepository<EventUsers, Long>, JpaSpecificationExecutor<EventUsers>{ @Query("select c from EventUsers c where c.id is ?1") EventUsers findEventById(String id); }
/** * @Author: Joakim Olsson <lomo133> * @Date: 2018-11-04T23:10:15+01:00 * @Last modified by: lomo133 * @Last modified time: 2018-11-04T23:10:49+01:00 */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = 1; while (scan.hasNext()) { System.out.println(n + " " + scan.nextLine()); n++; } } }
package com.redhat.service.bridge.manager; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class CustomerIdResolverImpl implements CustomerIdResolver { @Override public String resolveCustomerId() { return "jrota"; } }
/* * (C) Copyright 2010 Marvell International Ltd. * All Rights Reserved * * MARVELL CONFIDENTIAL * Copyright 2008 ~ 2010 Marvell International Ltd All Rights Reserved. * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Marvell International Ltd or its * suppliers or licensors. Title to the Material remains with Marvell International Ltd * or its suppliers and licensors. The Material contains trade secrets and * proprietary and confidential information of Marvell or its suppliers and * licensors. The Material is protected by worldwide copyright and trade secret * laws and treaty provisions. No part of the Material may be used, copied, * reproduced, modified, published, uploaded, posted, transmitted, distributed, * or disclosed in any way without Marvell's prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Marvell in writing. * */ package com.marvell.cmmb.activity; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.util.Calendar; import org.apache.http.HttpStatus; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Base64; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.marvell.cmmb.R; import com.marvell.cmmb.aidl.LogMask; import com.marvell.cmmb.common.AppBase; import com.marvell.cmmb.common.Util; import com.marvell.cmmb.manager.ModeManager; import com.marvell.cmmb.resolver.PreviewDataItem; import com.marvell.cmmb.service.MBBMSService; import com.marvell.cmmb.view.dialog.ConfirmDialog; import com.marvell.cmmb.view.dialog.ConfirmDialogCallBack; public class ProgramDetailActivity extends AppBase implements ConfirmDialogCallBack { private TextView mDateTextView; private TextView mDayTextView; private TextView mPlayTimeTextView; private TextView mProgramNameTextView; private TextView mInfoDetailTextView; private ImageButton mDetailImageButton; private Button mViewButton; private String mChooseDay; private String mChooseDate; private String mPlaybackTime; private String mPlaybackProgram; private String mChooseChannel; private String mDescription; private long mPreviewId; private int mFlag; private int mChannelStatus = -1; private int isForfree = -1; private int mFreeStatus = -1; private ConfirmDialog mConfirmDialog = null; private static final String TAG = "ProgramDetail"; private static final int CONNECTION_TIMEOUT = 500; public void confirmDialogCancel(int type) { // TODO Auto-generated method stub } public void confirmDialogOk(int type) { if (type == DIALOG_CONFIRM_PROGRAM_EXPIRE || type == DIALOG_CONFIRM_PROGRAM_FUTURE) { Intent viewIntent = new Intent(); viewIntent.setAction("com.marvell.cmmb.VIEW_DETAIL_ACTION"); viewIntent.putExtra("ChooseChannel", mChooseChannel); startActivity(viewIntent); ProgramDetailActivity.this.finish(); } else if (type == DIALOG_CONFIRM_SUB) { Intent subIntent = new Intent(); subIntent.putExtra("SubscribeStatus", 0); subIntent.setClass(ProgramDetailActivity.this, PurchaseManageActivity.class); startActivity(subIntent); } } private String getChooseDate(Context context, String chooseDay) { String chooseDate = ""; Calendar calendar = Calendar.getInstance(); if (chooseDay.equals(context.getResources().getString(R.string.today))) { chooseDate = Util.sDateFormater.format(calendar.getTime()); } else if (chooseDay.equals(context.getResources().getString(R.string.tomorrow))) { calendar.add(Calendar.DATE, 1); chooseDate = Util.sDateFormater.format(calendar.getTime()); } else if (chooseDay.equals(context.getResources().getString(R.string.aftertomorrow))) { calendar.add(Calendar.DATE, 2); chooseDate = Util.sDateFormater.format(calendar.getTime()); } else { } return chooseDate; } private void getInfomation() { Intent intent = getIntent(); mChooseDay = intent.getExtras().getString("ChooseDay"); mChooseDate = getChooseDate(this, mChooseDay); mChooseChannel = intent.getExtras().getString("ChooseChannel"); try { mPlaybackTime = intent.getExtras().getString("StartTime").substring(11, 16) + "-" + intent.getExtras().getString("EndTime").substring(11, 16); } catch (Exception e) { mPlaybackTime = ""; } mDescription = intent.getExtras().getString("Description"); mPlaybackProgram = intent.getExtras().getString("PlaybackProgram"); mFlag = intent.getExtras().getInt("ViewFlag"); mChannelStatus = intent.getExtras().getInt("ChannelStatus"); isForfree = intent.getExtras().getInt("ForFree"); mFreeStatus = intent.getExtras().getInt("FreeStatus"); mPreviewId = intent.getExtras().getLong("PreviewId"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.program_detail); initViews(); setupViews(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); updateDate(); updateViews(); } private Bitmap post(String pictureUri) { Bitmap bt = null; try { URL imageURL = new URL(pictureUri); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( ModeManager.getInstance(this).getProxy(), ModeManager.getInstance(this).getPort())); HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection(proxy); conn.setDoInput(true); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == HttpStatus.SC_OK) { InputStream is = conn.getInputStream(); BitmapFactory.Options ops = new BitmapFactory.Options(); ops.inJustDecodeBounds = true; bt = BitmapFactory.decodeStream(is); is.close(); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return bt; } private void setImage() { LogMask.LOGM(TAG, LogMask.LOG_APP_COMMON, LogMask.getLineInfo(), "setImage() called", LogMask.APP_COMMON); PreviewDataItem previewdata = mResolver.getPreviewData(mPreviewId); if (previewdata != null) { if (previewdata.getPictureType() == 1) { Bitmap bt = post(previewdata.getPictureUri()); mDetailImageButton.setImageBitmap(bt); } else if (previewdata.getPictureType() == 2) { byte[] b = Base64.decode(previewdata.getPictureUri(), Base64.DEFAULT); if (b.length != 0) { mDetailImageButton.setImageBitmap(BitmapFactory .decodeByteArray(b, 0, b.length)); } } else { mDetailImageButton.setImageResource(R.drawable.detail_content); } } else { mDetailImageButton.setImageResource(R.drawable.detail_content); } } /** * show confirm dialog ,the message displayed depends on the type. */ private void showConfirmDialog(int type) { String promptMsg = " "; String channelName = " "; if (type == DIALOG_CONFIRM_SUB) { promptMsg = getResources().getString(R.string.promptsubscribestart) + " '" + mChooseChannel + "' " + getResources().getString(R.string.promptsubscribeend); } else if (type == DIALOG_CONFIRM_PROGRAM_EXPIRE) { promptMsg = this.getResources().getString(R.string.promgramexpire); } else if (type == DIALOG_CONFIRM_PROGRAM_FUTURE) { promptMsg = this.getResources().getString(R.string.promgramnotstart); } if (mConfirmDialog != null) { mConfirmDialog.dismiss(); mConfirmDialog = null; } mConfirmDialog = new ConfirmDialog(this, R.drawable.dialog_hint, getResources().getString(R.string.hint), promptMsg); mConfirmDialog.setCallBack(this, type); if (!mConfirmDialog.isShowing()) { mConfirmDialog.show(); } } @Override public void initViews() { mDateTextView = (TextView) findViewById(R.id.tv_date); mDayTextView = (TextView) findViewById(R.id.tv_day); mPlayTimeTextView = (TextView) findViewById(R.id.tv_playbacktime); mProgramNameTextView = (TextView) findViewById(R.id.tv_playbackprogram); mInfoDetailTextView = (TextView) findViewById(R.id.tv_infodetail); mDetailImageButton = (ImageButton) findViewById(R.id.iv_detail); mViewButton = (Button) findViewById(R.id.bt_viewprogram); } @Override public void setupViews() { mViewButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mChannelStatus == 0 && isForfree == 0 && mFreeStatus == 0 && MBBMSService.sCurrentMode == MBBMS_MODE) { showConfirmDialog(DIALOG_CONFIRM_SUB); } else { if (mFlag == -1) { showConfirmDialog(DIALOG_CONFIRM_PROGRAM_EXPIRE); } else if (mFlag == 1) { showConfirmDialog(DIALOG_CONFIRM_PROGRAM_FUTURE); } else { Intent intent = new Intent(); intent.setAction("com.marvell.cmmb.VIEW_DETAIL_ACTION"); intent.putExtra("ChooseChannel", mChooseChannel); startActivity(intent); ProgramDetailActivity.this.finish(); } } } }); } @Override public void updateDate() { getInfomation(); } @Override public void updateViews() { mDayTextView.setText(mChooseDay); mDateTextView.setText(mChooseDate); mPlayTimeTextView.setText(mPlaybackTime); mProgramNameTextView.setText(mPlaybackProgram); mInfoDetailTextView.setText(mDescription); setImage(); } }
package com.grocery.codenicely.vegworld_new.cart; import com.grocery.codenicely.vegworld_new.cart.model.data.CartData; /** * Created by ramya on 17/10/16. */ public interface CartListRequestCallback { void onSuccess(CartData cartData); void onFailure(); }
/* * ViewCounter * Version 1.0 * * October 2, 2017 * Copyright (c) 2017 Team X, CMPUT301, University of Alberta-All Right Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta. * You can find a copy of the license in this project. Otherwisw please contant contant@abc.ca. */ package com.example.xgao1_countbook; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; /* * Created by gaoxin on 2017/9/30. */ public class ViewCounter extends MainActivity{ CounterInfo x; TextView details; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_counter); details = (TextView) findViewById(R.id.View); Intent intent = getIntent(); final int current_pos = intent.getIntExtra("ViewClass", 0); } protected void onStart() { super.onStart(); int current_pos; Intent intent = getIntent(); current_pos = intent.getIntExtra("ViewClass", 0); details.setText(Counters.get(current_pos).toString()); } }
package com.beike.util.cache.cachedriver.service.impl; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.beike.util.PropertiesReader; import com.beike.util.cache.cachedriver.service.MemCacheService; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; /** * Memcached工具类 * */ public class MemCached implements MemCacheService { private static Log log = LogFactory.getLog(MemCached.class); // 创建全局的唯一实例 private static MemCachedClient mcc = new MemCachedClient(); // 服务器列表 private static String servers = PropertiesReader.getValue("memcache", "server1"); // "192.168.172.10:15000 192.168.172.10:16000"; // 默认有效时间(一天) private static int defaultTime = 60 * 60 * 24; // 重试次数 private static int retry = 3; // 设置与缓存服务器的连接池 static { if (StringUtils.isBlank(servers)) { throw new NullArgumentException( "memcache property servers is not null"); } // 获取socke连接池的实例对象 SockIOPool pool = SockIOPool.getInstance(); // 设置服务器信息 pool.setServers(servers.split(" +")); // 设置初始连接数、最小和最大连接数以及最大处理时间 pool.setInitConn(5); pool.setMinConn(5); pool.setMaxConn(250); pool.setMaxIdle(1000 * 60 * 60 * 6); // 设置主线程的睡眠时间 pool.setMaintSleep(0); // 是否使用Nagle算法,socket的读取等待超时值,socket的连接等待超时值,设置hash算法 ,连接心跳监测开关 pool.setNagle(false); pool.setSocketTO(3000); pool.setSocketConnectTO(0); pool.setHashingAlg(3); pool.setAliveCheck(false); // 连接失败恢复开关,容错开关 pool.setFailback(true); pool.setFailover(false); // 初始化连接池 pool.initialize(); } private static MemCached memCached = new MemCached(); private MemCached() { } public static MemCacheService getInstance() { return memCached; } /** * 添加缓存值(有效期一天) * * @param key * @param value * @return */ @Override public boolean set(String key, Object value) { return set(key, value, defaultTime); } /** * 添加缓存值(单位:秒 expirt=0 永久) * * @param key * @param value * @param expiry * @return */ public boolean set(String key, Object value, int expiry) { boolean _result = false; try { if (StringUtils.isBlank(key) || value == null) { return false; } long l = expiry > 0 ? System.currentTimeMillis() + expiry * 1000 : 0; for (int i = 1; i <= retry; i++) { _result = mcc.set(key, value, new Date(l)); if (_result) { break; } log.error("[FAIL] set obj[key:" + key + " value:" + value.getClass() + " expiry:" + expiry + "] to cache failed begin to retry " + i + " times"); } } catch (Exception e) { log.error("[FAIL] set obj[key:" + key + " value:" + value.getClass() + " expiry:" + expiry + "] to cache failed"); e.printStackTrace(); } return _result; } /** * 从缓存中取值 * * @param key * @return */ public Object get(String key) { if (StringUtils.isBlank(key)) { return null; } Object _result = null; try { for (int i = 1; i <= retry; i++) { _result = mcc.get(key); if (null == _result) { // log.error("[FAIL] get obj[key:" + key // + "] failed from cache retry " + i + " times"); continue; } break; } } catch (Exception e) { log.error("[FAIL] get obj[key:" + key + "] failed from cache"); e.printStackTrace(); } if(_result!=null){ if(_result instanceof Collection<?>){ //log.info("[OK] get obj[key:" + key+",size:"+((Collection)_result).size()); } if(_result instanceof Map){ //log.info("[OK] get obj[key:" + key+",size:"+((Map)_result).size()); } } return _result; } /** * 从缓存中删除 * * @param key */ public boolean remove(String key) { Object object = get(key); if (null == object) { return true; } boolean _result = false; for (int i = 1; i <= retry; i++) { _result = mcc.delete(key); if (_result) { break; } log.error("[FAIL] remove obj[key:" + key + "] from cache failed begin to retry " + i + " times"); } return _result; } @Override public Map<String, Object> getBulk(Set<String> keys) { Map<String, Object> map = new HashMap<String, Object>(); if (keys == null) { return map; } for (String key : keys) { map.put(key, get(key)); } return map; } public static void main(String[] args) { MemCacheService old = MemCacheServiceImpl.getInstance(); MemCacheService newS = MemCached.getInstance(); Map<String, Integer> map = new HashMap<String,Integer>(); newS.remove("LOGIN_IP"); } }
package com.tntdjs.midi.controllers.data.config; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import com.tntdjs.midi.controllers.MidiControllerDefMgr; import com.tntdjs.midi.controllers.data.config.objects.ButtonSet; import com.tntdjs.midi.controllers.data.config.objects.MidiButton; import com.tntdjs.midi.controllers.data.config.objects.MidiDevices; import com.tntdjs.midi.controllers.data.config.objects.MidiDevices.Device; import com.tntdjs.midi.controllers.data.config.objects.MidiDevices.Device.ButtonGroups; /** * * Copyright (c) 2017, Todd M. Senauskas and/or its affiliates. All rights reserved. * @author tsenauskas * */ public class MidiDeviceXMLHelper implements IMidiDeviceXMLHelper { private static final Logger LOGGER = LogManager.getLogger(MidiDeviceXMLHelper.class.getName()); private JAXBContext jaxbContext; private Unmarshaller jaxbUnmarshaller; private MidiDevices midiDevices; private boolean dirty = false; private static ApplicationContext CONTEXT = null; private static MidiDeviceXMLHelper INSTANCE; private MidiControllerDefMgr midiDefMgr = null; /** * Constructor * @param appContext */ public MidiDeviceXMLHelper(ApplicationContext appContext) { super(); CONTEXT = appContext; midiDefMgr = (MidiControllerDefMgr) CONTEXT.getBean("midiControllerDefMgr"); LOGGER.info("\r\nCurrent Controller is: " + midiDefMgr.getMidiControllerDef().getMidiControllerPath() + midiDefMgr.getMidiControllerDef().getMidiControllerName() + "\r\nXML Configuration is:" + midiDefMgr.getMidiControllerDef().getXmlConfiguration()); File file = new File(getXMLFileName()); LOGGER.info("MIDI XML device configuration file [" +getXMLFileName()+ "] - exists? " + file.exists()); try { jaxbContext = JAXBContext.newInstance(MidiDevices.class); jaxbUnmarshaller = jaxbContext.createUnmarshaller(); midiDevices = (MidiDevices) jaxbUnmarshaller.unmarshal(file); } catch (JAXBException e) { LOGGER.fatal("Error parsing XML file (" + getXMLFileName() + ")", e); } } /** * getInstance with an Application Context initially * @param CONTEXT * @return */ public static MidiDeviceXMLHelper getInstance(ApplicationContext appContext) { if (null != appContext) { INSTANCE = new MidiDeviceXMLHelper(appContext); } else { LOGGER.error("Class requires ApplicationContext CONTEXT to initialize."); } return INSTANCE; } public static MidiDeviceXMLHelper getInstance() { if (null == INSTANCE) { LOGGER.error("Class requires ApplicationContext CONTEXT to initialize."); } return INSTANCE; } /** * */ public String getXMLFileName() { return midiDefMgr.getMidiControllerDef().getXmlConfiguration(); // return "config/midi/controllers/akai/lpd8/LPD8Config.xml"; } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#isDirty() */ @Override public boolean isDirty() { return dirty; } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#setDirty(boolean) */ @Override public void setDirty(boolean dirty) { this.dirty = dirty; } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#getDevice() */ @Override public Device getDevice() { return midiDevices.getDevice(); } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#getButtonGroups() */ @Override public ButtonGroups getButtonGroups() { ButtonGroups buttonGroups = getDevice().getButtonGroups(); return buttonGroups; } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#getButtonSets() */ @Override public List<ButtonSet> getButtonSets() { List<ButtonSet> buttonList = getButtonGroups().getButtonSet(); return buttonList; } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#getMidiButtonSet(int) */ @Override public List<MidiButton> getMidiButtonSet(int bank) { List<MidiButton> mButtonList = new ArrayList<MidiButton>(); if (!getButtonSets().isEmpty() && getButtonSets().size() >= bank) { mButtonList = getButtonSets().get(bank).getMidiButtons(); } return mButtonList; } /* (non-Javadoc) * @see com.tntdjs.midi.controllers.data.config.IMidiDeviceXMLHelper#getXMLFileName() */ // @Override // public abstract String getXMLFileName(); }
package cn.itheima.day_06.demoSummary; public class ArrayContentCompare { /* 判断两个数组中的内容是否相同 */ public static void main(String[] args) { int[] arr1 = {11, 22, 33, 44, 55, 66}; int[] arr2 = {11, 22, 33, 44, 55, 66}; System.out.println(contentCompare(arr1, arr2)); } //返回值类型为boolean,两个参数为int[] arr1,int[] arr2 private static boolean contentCompare(int[] arr1, int[] arr2) { //判断两个数组的长度是否相同,若不同则直接返回false if (arr1.length != arr2.length) { return false; } //逐个判断数组中的每一个元素是否相同,但凡有一个不同则返回false for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } /* 如果在if后方加上else语句会导致遇到第一个相同的元素的时候返回true, 方法直接中断。 */ } //若以上两个条件都不满足,则返回true return true; } }