text
stringlengths 10
2.72M
|
|---|
package VSMSerialization;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Set;
import VSMConstants.VSMContant;
public class VSMSerializeFeatureVectorBeanTraining {
private static int treeCount;
private static int count;
private static int fileNum;
private static int index;
/*
* No args constructor
*/
public VSMSerializeFeatureVectorBeanTraining() {
treeCount = 0;
// count = 0;
}
/*
* Constructor with arguments, fetch the count map and send it to this
* constructor, so that the count can start making files from where we left
* off in the previous iteration
*/
public VSMSerializeFeatureVectorBeanTraining(int treeCount) {
VSMSerializeFeatureVectorBeanTraining.treeCount = treeCount;
}
public void serializeVectorBean(VSMFeatureVectorBean vectorBean,
int treeCount, int nodeCount) {
VSMSerializeFeatureVectorBeanTraining.treeCount = treeCount;
/*
*
*/
System.out.println("***Forming the file***");
File file = new File(VSMContant.SICK_TRIAL_BINARY_SENT_VECS_FOLDER
+ treeCount + "/" + vectorBean.getLabel());
if (!file.exists()) {
file.mkdirs();
}
/*
* The .ser file name. The file in which the feature vectors are
* serialized
*/
String filename = file.getAbsolutePath() + "/" + vectorBean.getLabel()
+ "_" + nodeCount + ".ser";
// String filename =
// "/Users/sameerkhurana10/Documents/testserialization/"
// + phiBean.getLabel() + "_1.ser";
/*
* Serializing the object
*/
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename, false);
out = new ObjectOutputStream(fos);
out.writeObject(vectorBean);
out.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void serializeVectorBeanSem(VSMWordFeatureVectorBean vectorBean,
int treeCount, int nodeCount) {
count++;
VSMSerializeFeatureVectorBeanTraining.treeCount = treeCount;
/*
*
*/
System.out.println("***Forming the file***");
File file = new File(
"/afs/inf.ed.ac.uk/group/project/vsm/BLIPPsentencevectors/S_"
+ treeCount + "/" + vectorBean.getLabel());
if (!file.exists()) {
file.mkdirs();
}
/*
* The .ser file name. The file in which the feature vectors are
* serialized
*/
String filename = file.getAbsolutePath() + "/" + vectorBean.getLabel()
+ "_" + nodeCount + "sem.ser";
// String filename =
// "/Users/sameerkhurana10/Documents/testserialization/"
// + phiBean.getLabel() + "_1.ser";
/*
* Serializing the object
*/
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename, false);
out = new ObjectOutputStream(fos);
out.writeObject(vectorBean);
out.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void serializeVectorBeanBLLIP(VSMFeatureVectorBean vectorBean,
int treeCount, int nodeCount) {
VSMSerializeFeatureVectorBeanTraining.treeCount = treeCount;
/*
*
*/
/*
* Updating the file count
*/
fileNum = fileNum + 1;
File file = null;
if (fileNum <= 5000) {
file = new File(VSMContant.BINARY_SENTENCE_VECS_BLLIP + "/folder_"
+ index + "/S_" + fileNum + "/" + vectorBean.getLabel()
+ "/" + vectorBean.getLabel() + "_" + nodeCount + ".ser");
} else {
index++;
fileNum = 0;
fileNum = fileNum + 1;
file = new File(VSMContant.BINARY_SENTENCE_VECS_BLLIP + "/folder_"
+ index + "/S_" + fileNum + "/" + vectorBean.getLabel()
+ "/" + vectorBean.getLabel() + "_" + nodeCount + ".ser");
}
if (!file.exists()) {
file.getParentFile().mkdirs();
System.out.println("***Forming the file***");
} else {
System.err.println("****The file Already Exists*****"
+ file.getName());
}
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(file.getAbsoluteFile(), false);
System.err.println(file.canWrite());
out = new ObjectOutputStream(fos);
out.writeObject(vectorBean);
out.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void serializeEmbeddedVectorBeanWords(
VSMFeatureVectorBeanEmbedded vectorBean, String nonTerminal,
String word, int wordCount, int nodeCount) {
// VSMSerializeFeatureVectorBeanTraining.treeCount = treeCount;
// ArrayList<String> words = new ArrayList<String>();
boolean flag = false;
String alreadyExistingWordPath = null;
File[] files = new File(VSMContant.WORD_FEATURE_VECS_EMBEDDED)
.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
// TODO Auto-generated method stub
return !file.isHidden();
}
});
/*
* If there are files and the array is not an empty one, form the list
* of words that already have a directory, this should be a very fast
* loop, no worries here
*/
if (files != null && files.length > 0) {
main: for (File file : files) {
if (file.isDirectory()) {
File[] wordDirecs = file.listFiles();
if (wordDirecs != null) {
for (File fileWord : wordDirecs) {
if (word.equalsIgnoreCase(fileWord.getName())) {
flag = true;
alreadyExistingWordPath = fileWord
.getAbsolutePath();
break main;
}
}
}
}
}
}
/*
*
*/
/*
* Updating the file count
*/
// fileNum = fileNum + 1;
File file = null;
/*
* Forming the appropriate directory structure
*/
if (wordCount < 30000) {
// index = 1;
// file = new File(VSMContant.BINARY_SENTENCE_VECS_BLLIP +
// "/folder_"
// + index + "/S_" + fileNum + "/" + vectorBean.getLabel());
if (flag == false) {
file = new File(VSMContant.WORD_FEATURE_VECS_EMBEDDED
+ "/folder_" + index + "/" + word + "/" + nonTerminal
+ "/" + nonTerminal + "_" + nodeCount + ".ser");
} else {
System.out.println("****The word already exists***"
+ alreadyExistingWordPath);
file = new File(alreadyExistingWordPath + "/" + nonTerminal
+ "/" + nonTerminal + "_" + nodeCount + ".ser");
}
} else {
// fileNum = 0;
// fileNum = fileNum + 1;
if (flag == false) {
index++;
file = new File(VSMContant.WORD_FEATURE_VECS_EMBEDDED
+ "/folder_" + index + "/" + word + "/" + nonTerminal
+ "/" + nonTerminal + "_" + nodeCount + ".ser");
} else {
System.out.println("****The word already exists***"
+ alreadyExistingWordPath);
file = new File(alreadyExistingWordPath + "/" + nonTerminal
+ "/" + nonTerminal + "_" + nodeCount + ".ser");
}
}
// /BLLIPBinarySentenceVecs/folder_1/S_12642/JJ
// File file = new File(
// "/afs/inf.ed.ac.uk/group/project/vsm.restored/BLLIPSentenceVecs/S_"
// + treeCount + "/" + vectorBean.getLabel());
if (!file.exists()) {
file.getParentFile().mkdirs();
System.out.println("***Forming the file***");
} else {
System.err.println("****The file Already Exists*****"
+ file.getName());
}
/*
* The .ser file name. The file in which the feature vectors are
* serialized
*/
// String filename = file.getAbsolutePath() + "/" +
// vectorBean.getLabel()
// + "_" + nodeCount + ".ser";
// String filename =
// "/Users/sameerkhurana10/Documents/testserialization/"
// + phiBean.getLabel() + "_1.ser";
/*
* Serializing the object
*/
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(file.getAbsoluteFile(), false);
System.err.println(file.canWrite());
out = new ObjectOutputStream(fos);
out.writeObject(vectorBean);
out.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
*
* @param vectorBean
* @param path
*/
public void serializeVectorBeanSentenceRand(
VSMRandomSentenceBean vectorBean, String path) {
/*
*
*/
System.out.println("***Forming the file***");
File file = new File(path);
if (!file.exists()) {
file.getParentFile().mkdirs();
}
/*
* The .ser file name. The file in which the feature vectors are
* serialized
*/
String filename = file.getAbsolutePath();
// String filename =
// "/Users/sameerkhurana10/Documents/testserialization/"
// + phiBean.getLabel() + "_1.ser";
/*
* Serializing the object
*/
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename, false);
out = new ObjectOutputStream(fos);
out.writeObject(vectorBean);
out.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/*
* Method that returns the count map, used to retrieve the count map at the
* end of the operation on one particular file, so that we can serialize the
* count map for the next operation
*/
public static int getTreeCount() {
return treeCount;
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class jv extends b {
public a bTL;
public jv() {
this((byte) 0);
}
private jv(byte b) {
this.bTL = new a();
this.sFm = false;
this.bJX = null;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.trivee.fb2pdf;
import java.util.HashMap;
import java.util.LinkedList;
/**
*
* @author vzeltser
*/
public class LinkPageNumTemplateMap extends HashMap<String, LinkedList<LinkPageNumTemplate>> {
public void put(String key, LinkPageNumTemplate value) {
LinkedList<LinkPageNumTemplate> bucket;
if (super.containsKey(key)) {
bucket = get(key);
} else {
bucket = new LinkedList<LinkPageNumTemplate>();
put(key, bucket);
}
bucket.add(value);
}
}
|
package org.acme.qute;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
@Path("/hello")
public class HelloResource {
@Inject
Template hello;
@GET
@Produces(MediaType.TEXT_HTML)
public Response get(@QueryParam("name") String name) {
return Response
.status(Response.Status.CREATED)
.type(MediaType.TEXT_HTML)
.entity(hello.data("name", name))
.build();
}
}
|
package aprivate.oo.cusplib.cuspiocore;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.util.Log;
import aprivate.oo.cusplib.SystemGattCallback;
import aprivate.oo.cusplib.connectcore.ConnectResultCatcher;
import aprivate.oo.cusplib.interfaces.BleIOInteraction;
import aprivate.oo.cusplib.models.CuspDevice;
/**
* Created by zhuxiaolong on 16/6/28.
*/
public class CuspIOCore implements BleIOInteraction,BleIOInteraction.BleIOInteractionResult{
private static CuspIOCore ourInstance;
private ConnectResultCatcher mConnectResultCatcher;
public static CuspIOCore getInstance(Context context) {
if (ourInstance == null) {
ourInstance = new CuspIOCore(context);
}
return ourInstance;
}
private Context mContext;
private CuspIOCore(Context context) {
this.mContext = context;
mGattCallback = SystemGattCallback.getInstance().setCuspIOCore(this);
mConnectResultCatcher= ConnectResultCatcher.getInstance(context);
}
private SystemGattCallback mGattCallback;
@Override
public void writeValue(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
gatt.writeCharacteristic(characteristic);
}
@Override
public void readValue(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
gatt.readCharacteristic(characteristic);
}
@Override
public void notification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i(TAG, "setnofification :" + gatt.setCharacteristicNotification(characteristic,true));
}
@Override
public void onWrited(BluetoothGatt gatt, String result) {
Log.i(TAG, "device :" + gatt.getDevice().getName() + "onWrited :" + result);
CuspDevice device=mConnectResultCatcher.getConnectDevice(gatt);
device.setDeviceState(CuspDevice.STATE_OK);
device.getWRNCallback().onReadValue(result);
}
@Override
public void onReaded(BluetoothGatt gatt, String result) {
Log.i(TAG, "device :" + gatt.getDevice().getName() + "onRead :" + result);
CuspDevice device=mConnectResultCatcher.getConnectDevice(gatt);
device.setDeviceState(CuspDevice.STATE_OK);
device.getWRNCallback().onWriteValue(result);
}
@Override
public void onNotification(BluetoothGatt gatt, String result) {
Log.i(TAG, "device :" + gatt.getDevice().getName() + "onNotification :" + result);
CuspDevice device=mConnectResultCatcher.getConnectDevice(gatt);
device.getWRNCallback().onValueNotification(result);
}
private final String TAG = "CuspIOCore";
}
|
package com.example.demo.repository;
import java.util.List;
import javax.websocket.server.PathParam;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.Student;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long>{
@Query("SELECT student FROM Student student where upper(student.firstName) like upper(concat('%',:firstName,'%')) "
+ " and upper(student.lastName) like upper(concat('%',:lastName,'%'))" )
List<Student> findBySearchFirstNameAndLastName(String firstName, String lastName);
//search nhìu đk
@Query("SELECT student FROM Student student where upper(student.firstName) like upper(concat('%',:name,'%')) "
+ " or upper(student.lastName) like upper(concat('%',:name,'%'))" )
List<Student> findBySearchName(@PathParam("name") String name);
//1 field nhưng search trên nhiều field
}
|
package lucene;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;
/**
*
* 提供对索引的查询功能
*
*/
public class Searcher {
private IndexSearcher searcher;
private QueryParser contentQueryParser;
@SuppressWarnings("deprecation")
public Searcher(String indexDir) throws IOException {
searcher = new IndexSearcher(IndexReader.open(FSDirectory.open(new File(indexDir))));
IKAnalyzer analyzer = new IKAnalyzer(true);
String[] fields = {IndexItem.TITLE,IndexItem.ABSTRACT,IndexItem.CONTENT};
contentQueryParser = new MultiFieldQueryParser(Version.LUCENE_44, fields, analyzer);
}
/**
* 实现分页查询
* ScoreDoc实例化时需两个参数,两个参数值为list最后一条记录中docid,score对值 的value值
* @param queryString 被查询的字符串
* @param pageSize 返回的记录条数
* @param pageNumber 页数
*/
public Map<String,Object> findByPage(String queryString, int pageSize,int pageNumber) throws ParseException, IOException {
Map<String,Object> reMap = new HashMap<String,Object>();
Query query = contentQueryParser.parse(queryString);
//获取最后一个ScoreDoc
ScoreDoc afterDoc = null;
if(pageNumber>1){
int num = pageSize * (pageNumber-1);
afterDoc = searcher.search(query,num).scoreDocs[num-1];
}
TopDocs queryResult = searcher.searchAfter(afterDoc,query, pageSize);
ScoreDoc[] queryResults = queryResult.scoreDocs;
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for (ScoreDoc scoreDoc : queryResults) {
int docID = scoreDoc.doc;
float score = scoreDoc.score;
Document document = searcher.doc(docID) ;
Map<String,Object> map = documentToMap(document);
map.put("docid",docID);
map.put("score",score);
list.add(map);
}
reMap.put("total",queryResult.totalHits);
reMap.put("rows",list);
return reMap;
}
/**
* 将Document转化成Map
* @param document
* @return
*/
private static Map<String,Object> documentToMap(Document document){
Map<String,Object> map = new HashMap<String,Object>();
List<IndexableField> fields = document.getFields();
for (IndexableField indexableField : fields) {
map.put(indexableField.name(), document.get(indexableField.name()));
}
return map;
}
}
|
public class HelloWorld {
public static void main(String[] args) {
// Print "Hello, 世界" to the terminal window.
System.out.println("Hello, 世界");
}
}
|
package my.app.platform.domain;
/**
* @author 夏之阳
* 创建时间:2016-08-16 11:23
* 创建说明:用户列表(管理员、教师、学生)
*/
public class User {
//用户名
private String username;
//密码
private String password;
//姓名
private String name;
//角色
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
package pl.edu.wat.wcy.pz.project.server.listener;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Component
public class Subscribers {
private Map<String, Set<String>> subscriptionMap = new HashMap<>();
public void addSubscriptions(String user, Set<String> subscriptions) {
subscriptions.forEach(s -> addSubscription(user, s));
}
public void addSubscription(String user, String subscription) {
if (subscriptionMap.containsKey(user)) {
subscriptionMap.get(user).add(subscription);
} else {
Set<String> setToAdd = new HashSet<>();
setToAdd.add(subscription);
subscriptionMap.put(user, setToAdd);
}
}
public String updateAndReturnDifference(String user, Set<String> subscriptions) {
String unsubscribed = null;
if (!subscriptionMap.containsKey(user)) {
addSubscriptions(user, subscriptions);
return null;
}
Set<String> oldSubs = subscriptionMap.get(user);
oldSubs.removeAll(subscriptions);
if (oldSubs.size() == 1) {
unsubscribed = oldSubs.iterator().next();
}
oldSubs.clear();
addSubscriptions(user, subscriptions);
return unsubscribed;
}
public void removeSubscriptions(String user) {
subscriptionMap.remove(user);
}
}
|
/**
* Copyright 2013 Cloudera Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kitesdk.data.filesystem;
import java.io.IOException;
import java.util.Arrays;
import org.apache.avro.Schema;
import org.apache.avro.io.parsing.ResolvingGrammarGenerator;
import org.apache.avro.io.parsing.Symbol;
// TODO: replace with AVRO-1315 when generally available
class SchemaValidationUtil {
public static boolean canRead(Schema writtenWith, Schema readUsing) {
try {
return !hasErrors(new ResolvingGrammarGenerator().generate(
writtenWith, readUsing));
} catch (IOException e) {
return false;
}
}
/**
* Returns true if the Parser contains any Error symbol, indicating that it may fail
* for some inputs.
*/
private static boolean hasErrors(Symbol symbol) {
switch(symbol.kind) {
case ALTERNATIVE:
return hasErrors(((Symbol.Alternative) symbol).symbols);
case EXPLICIT_ACTION:
return false;
case IMPLICIT_ACTION:
return symbol instanceof Symbol.ErrorAction;
case REPEATER:
Symbol.Repeater r = (Symbol.Repeater) symbol;
return hasErrors(r.end) || hasErrors(r.production);
case ROOT:
return hasErrors(Arrays.copyOfRange(symbol.production, 1, symbol.production.length));
case SEQUENCE:
return hasErrors(symbol.production);
case TERMINAL:
return false;
default:
throw new RuntimeException("unknown symbol kind: " + symbol.kind);
}
}
private static boolean hasErrors(Symbol[] symbols) {
if(null != symbols) {
for(Symbol s: symbols) {
if (hasErrors(s)) {
return true;
}
}
}
return false;
}
}
|
package de.jmda.app.uml.icon.settings;
import java.io.InputStream;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class SettingsIconFactory
{
public enum IconType { DIRECTORY }
private static Image directory_icon;
private static final String DIRECTORY_ICON_FILENAME = "directory.png";
public static Node createIcon(IconType iconType, int size)
{
Node result;
if (iconType == IconType.DIRECTORY)
{
result = createIconTypeDirectory(size);
}
else
{
throw new IllegalStateException("unexpected icon type: " + iconType);
}
return result;
}
private static Node createIconTypeDirectory(int size)
{
if (null == directory_icon)
{
InputStream resourceAsStream = SettingsIconFactory.class.getResourceAsStream(DIRECTORY_ICON_FILENAME);
directory_icon = new Image(resourceAsStream, size, size, true, true);
}
return new ImageView(directory_icon);
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] visit;
int F,S,G,U,D,count = 0;
F = sc.nextInt();
S = sc.nextInt();
G = sc.nextInt();
U = sc.nextInt();
D = sc.nextInt();
visit = new int[F + 1];
while((S != G) && (visit[S] == 0)){
visit[S] = 1;
if(S < G && S + U <= F){
S += U;
count++;
}
else if(S - D >= 1){
S -= D;
count++;
}
}
if(S == G) System.out.println(count);
else System.out.println("use the stairs");
}
}
|
package edu.hyc.core;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import edu.hyc.core.arithmetic.ArithmeticCore;
/**
* Calculator Core
* 計算機核心
* 封裝計算邏輯及結果
* 提供
* 1.基本四則運算
* 2.開根號,倒數,取餘數
* 3.正負反向,小數點操作,backspace,CE,Clear功能
* @author leo_Chen
* @version 1.0
*/
public class CalculatorCore {
/**
* 計算值清單
*/
private List<InputValueFunction> values;
/**
* 計算結果 輸出
*/
private double outputValue;
/**
* 輸入計算值
*/
private double inputValue;
/**
* 是否為小數點狀態
*/
private boolean isDot;
/**
* 初始化
*/
public CalculatorCore() {
reset();
}
/**
* 輸入數字0~9
* @param value
* @return 輸入計算值inputValue
*/
public double inputNumber(int value) {
if (checkIsTheNewInputNumber()) {
reset();
}
if (isDot) {
inputValue = this.doDotValue(inputValue, value);
} else {
inputValue = inputValue * 10 + value;
}
return inputValue;
}
/**
* 使用修改輸入值的功能
* 1.DOT小數點
* 2.CE清除此次輸入值
* 3.C清除並重設計算器
* 4.BACKSPACE 刪除最後一個數字
* 5.REVERSE 數字正負反向
* @param function
* @return 輸入計算值inputValue
*/
public double useModifyInputValueFunction(MODIFY_INPUT_FUNC function) {
isDot = false;
switch (function) {
case DOT:
isDot = true;
break;
case CE:
inputValue = 0;
break;
case C:
reset();
break;
case BACKSPACE:
doBackspace();
break;
case REVERSE:
inputValue *= -1;
break;
default:
break;
}
return inputValue;
}
/**
* 使用計算結果的功能
* 1.四則運算
* 2.開根號
* 3.倒數
* 4.等於
* @param function
* @return 計算結果 輸出outputValue
*/
public double useCountOutputValueFunction(COUNT_OUTPUT_FUNC function) {
isDot = false;
switch (function) {
case SQRT:
case RECIPROCAL:
case EQUAL:
countOutputValueByIsImmediateFunction(function,null);
break;
default:
countOutputValueByNextStepFunction(function,null);
break;
}
return outputValue;
}
/**
* 使用計算結果的功能
* for 客制擴充之計算邏輯
* @param function
* @return 計算結果 輸出outputValue
*/
public double useCountOutputValueFunction(ArithmeticCore arithmeticCore) {
isDot = false;
if(arithmeticCore.isImmediate()){
countOutputValueByIsImmediateFunction(arithmeticCore);
}else{
countOutputValueByNextStepFunction(arithmeticCore);
}
return outputValue;
}
/**
* 計算需要馬上得到結果的功能
* 如開根號,倒數,等於
* @param function
*/
private void countOutputValueByIsImmediateFunction(
COUNT_OUTPUT_FUNC function,ArithmeticCore arithmeticCore) {
InputValueFunction inputValueFunction = new InputValueFunction(inputValue, function, true);
inputValueFunction.setArithmeticCore(arithmeticCore);
values.add(inputValueFunction);
outputValue = count();
inputValue = outputValue;
}
/**
* 計算需要馬上得到結果的功能
* for 客制擴充之計算邏輯
* @param function
*/
private void countOutputValueByIsImmediateFunction(ArithmeticCore arithmeticCore) {
countOutputValueByIsImmediateFunction(COUNT_OUTPUT_FUNC.OTHER_ARITHMETIC, arithmeticCore);
}
/**
* 計算上一筆總和,此次輸入值待下次計算
* 如四則運算
* @param function
*/
private void countOutputValueByNextStepFunction(COUNT_OUTPUT_FUNC function,ArithmeticCore arithmeticCore) {
InputValueFunction inputValueFunction = new InputValueFunction(inputValue, function, false);
inputValueFunction.setArithmeticCore(arithmeticCore);
values.add(inputValueFunction);
outputValue = count();
inputValue = 0;
}
/**
* 計算上一筆總和,此次輸入值待下次計算
* for 客制擴充之計算邏輯
* @param function
*/
private void countOutputValueByNextStepFunction(ArithmeticCore arithmeticCore) {
countOutputValueByNextStepFunction(COUNT_OUTPUT_FUNC.OTHER_ARITHMETIC, arithmeticCore);
}
/**
* 重置計算器
*/
public void reset() {
outputValue = 0;
inputValue = 0;
isDot = false;
values = new ArrayList<InputValueFunction>();
}
/**
* 開始計算
* @return 計算結果
*/
private double count() {
double finalValue = 0;
Iterator<InputValueFunction> valuesIt = values.iterator();
InputValueFunction firstValue = valuesIt.next();
finalValue = firstValue.getValue();
InputValueFunction beforeValue = firstValue;
if (firstValue.isImmediate()) {
for (InputValueFunction valueFunc : values) {
finalValue = countMethodCore(finalValue, beforeValue, valueFunc);
beforeValue = valueFunc;
}
} else {
while (valuesIt.hasNext()) {
InputValueFunction valueFunc = valuesIt.next();
finalValue = countMethodCore(finalValue, beforeValue, valueFunc);
beforeValue = valueFunc;
}
}
return finalValue;
}
/**
* 計算器核心
* @param finalValue
* @param beforeValue
* @param nowValue
* @return 計算結果
*/
private double countMethodCore(double finalValue,
InputValueFunction beforeValue, InputValueFunction nowValue) {
if (beforeValue != null && !beforeValue.isImmediate()) {
finalValue = arithmeticCore(finalValue, nowValue.getValue(),
beforeValue);
}
if (nowValue.isImmediate()) {
finalValue = arithmeticCore(finalValue, nowValue.getValue(),
nowValue);
}
return finalValue;
}
/**
* 算法邏輯
* @param finalValue
* @param newValue
* @param inputValueFunction
* @return
*/
private double arithmeticCore(double finalValue, double newValue,
InputValueFunction inputValueFunction) {
COUNT_OUTPUT_FUNC function = inputValueFunction.getFunction();
switch (function) {
case PLUS:
finalValue += newValue;
break;
case REDUCE:
finalValue -= newValue;
break;
case MULITPLY:
finalValue *= newValue;
break;
case DIVIDE:
if (newValue != 0)
finalValue /= newValue;
break;
case REMAINDER:
if (newValue != 0)
finalValue %= newValue;
break;
case SQRT:
if (finalValue >= 0)
finalValue = Math.sqrt(finalValue);
break;
case RECIPROCAL:
if (finalValue != 0)
finalValue = 1 / finalValue;
break;
case EQUAL:
break;
case OTHER_ARITHMETIC:
if(inputValueFunction.getArithmeticCore()!=null){
ArithmeticCore arithmeticCore = inputValueFunction.getArithmeticCore();
finalValue = arithmeticCore.arithmeticCore(finalValue, newValue);
}
break;
default:
break;
}
return finalValue;
}
/**
* 處理小數點輸入數值
* @param inputValue
* @param value
* @return
*/
private double doDotValue(double inputValue, int value) {
String newValueStr = String.valueOf(inputValue);
if (inputValue % 1 != 0) {
newValueStr += String.valueOf(value);
inputValue = Double.parseDouble(newValueStr);
} else {
inputValue += (double) value / 10;
}
return inputValue;
}
/**
* 處理刪除鍵數值
*/
private void doBackspace() {
String newValueStr = String.valueOf(inputValue);
if (newValueStr.indexOf("E") > -1) {
inputValue = inputValue / 10;
} else if (inputValue % 1 == 0) {
inputValue = inputValue / 10;
newValueStr = String.valueOf(inputValue);
newValueStr = newValueStr.substring(0, newValueStr.length() - 1);
inputValue = Double.parseDouble(newValueStr);
} else {
newValueStr = newValueStr.substring(0, newValueStr.length() - 1);
inputValue = Double.parseDouble(newValueStr);
}
}
/**
* 檢核是否為新的一筆輸入值
* @return
*/
private boolean checkIsTheNewInputNumber() {
return values.size() > 0 && values.get(values.size() - 1).isImmediate();
}
/**
* 取得計算輸出結果
* @return
*/
public double getOutputValue() {
return outputValue;
}
/**
* 取得輸入之計算值
* @return
*/
public double getInputValue() {
return inputValue;
}
/**
* 留給想以鍵盤輸入的方式設值使用
* @param inputValue
*/
public void setInputValue(double inputValue) {
this.inputValue = inputValue;
}
/**
* 計算值物件
* 包含計算的方法
*/
private class InputValueFunction {
/**
* 輸入值
*/
private double value;
/**
* 計算方法
*/
private COUNT_OUTPUT_FUNC function;
/**
* 是否馬上計算
*/
private boolean isImmediate;
private ArithmeticCore arithmeticCore;
public InputValueFunction(double value, COUNT_OUTPUT_FUNC function,
boolean isImmediate) {
super();
this.value = value;
this.function = function;
this.isImmediate = isImmediate;
}
public double getValue() {
return value;
}
public COUNT_OUTPUT_FUNC getFunction() {
return function;
}
public boolean isImmediate() {
return isImmediate;
}
public ArithmeticCore getArithmeticCore() {
return arithmeticCore;
}
public void setArithmeticCore(ArithmeticCore arithmeticCore) {
this.arithmeticCore = arithmeticCore;
}
}
/**
* 提供的計算功能
*/
public enum COUNT_OUTPUT_FUNC {
PLUS("+"), REDUCE("-"), MULITPLY("*"), DIVIDE("/"), REMAINDER("%"), EQUAL(
"="), RECIPROCAL("1/x*"), SQRT("sqrt"),OTHER_ARITHMETIC("other_arithmetic");
private String value;
COUNT_OUTPUT_FUNC(String value) {
this.value = value;
}
public String value() {
return value;
}
}
/**
* 提供的修改輸入值功能
*/
public enum MODIFY_INPUT_FUNC {
DOT("."), REVERSE("-1*"), BACKSPACE("Backspace"), CE("CE"), C("C"),OTHER_ARITHMETIC("other_arithmetic");
private String value;
MODIFY_INPUT_FUNC(String value) {
this.value = value;
}
public String value() {
return value;
}
}
}
|
package com.huyikang.design.pattern.abstractfactory;
/**
* 工厂生成器
*
* @author InsaneBeans
*
*/
public class FactoryProducer {
/**
* 根据选择的需要,生成一个功能工厂
*
* @param choice
* @return
*/
public static AbstractFactory getFactory(String choice) {
if (choice.equalsIgnoreCase("color")) {
return new ColorFactory();
} else if (choice.equalsIgnoreCase("shape")) {
return new ShapeFactory();
} else {
return null;
}
}
}
|
package com.tencent.mm.plugin.remittance.bankcard.ui;
import com.tencent.mm.plugin.remittance.bankcard.ui.BankRemitBankcardInputUI.24;
class BankRemitBankcardInputUI$24$1 implements Runnable {
final /* synthetic */ 24 mvn;
BankRemitBankcardInputUI$24$1(24 24) {
this.mvn = 24;
}
public final void run() {
BankRemitBankcardInputUI.k(this.mvn.mve);
}
}
|
package ru.android.messenger.presenter.implementation;
import android.support.annotation.NonNull;
import java.util.List;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Response;
import ru.android.messenger.model.Model;
import ru.android.messenger.model.PreferenceManager;
import ru.android.messenger.model.Repository;
import ru.android.messenger.model.callbacks.CallbackWithoutAlerts;
import ru.android.messenger.model.dto.User;
import ru.android.messenger.model.utils.UserUtils;
import ru.android.messenger.presenter.IncomingRequestsPresenter;
import ru.android.messenger.view.interfaces.ViewWithUsersRecyclerView;
public class IncomingRequestsPresenterImplementation implements IncomingRequestsPresenter {
private ViewWithUsersRecyclerView view;
private Repository repository;
public IncomingRequestsPresenterImplementation(ViewWithUsersRecyclerView view) {
this.view = view;
repository = Model.getRepository();
}
@Override
public void fillIncomingRequestsList() {
String authenticationToken = PreferenceManager.getAuthenticationToken(view.getContext());
repository.getIncomingRequests(authenticationToken)
.enqueue(new CallbackWithoutAlerts<List<User>>() {
@Override
public void onResponse(@NonNull Call<List<User>> call,
@NonNull Response<List<User>> response) {
if (response.isSuccessful()) {
List<User> users = Objects.requireNonNull(response.body());
UserUtils.convertAndSetUsersToView(users, view);
}
}
});
}
}
|
package com.google.android.gms.common;
final class j$j {
static final j$a[] aQo = new j$a[]{new 1(j$a.bm("0\u0003Í0\u0002µ \u0003\u0002\u0001\u0002\u0002\t\u0000ì/]í|B0")), new 2(j$a.bm("0\u0003Í0\u0002µ \u0003\u0002\u0001\u0002\u0002\t\u0000Eqâ0"))};
}
|
package ctci.chap1;
/*
* Note: I have assumed that the length of str fits the new string exactly.
*/
public class URLify{
public static void main(String args[]){
String[] testStrings = {"hello","this is a test", ""}
printResult()
}
public static void toURL(char[] str, int length){
if(str.length == 0 || length == 0){ return; }
int urlStringPosition = str.length-1;
int rawStringPosition = length-1;
while(rawStringPosition >= 0){
char currChar = str[rawStringPosition];
if(currChar == ' '){
insertURLSpace(str,urlStringPosition-2);
urlStringPosition -= 3;
}else{
str[urlStringPosition] = currChar;
urlStringPosition -= 1;
}
rawStringPosition -= 1;
}
}
public static void insertURLSpace(char[] str, int startPosition){
str[startPosition] = '%';
str[startPosition+1] = '2';
str[startPosition+2] = '0';
}
}
|
package org.globsframework.sqlstreams.accessors;
import org.globsframework.streams.accessors.LongAccessor;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.util.Date;
public class DateTimeLongSqlAccessor extends SqlAccessor implements LongAccessor {
public Long getLong() {
Timestamp date = getSqlMoStream().getTimeStamp(getIndex());
if (date == null) {
return null;
}
return date.getTime();
}
public long getValue(long valueIfNull) {
Long value = getLong();
return value == null ? valueIfNull : value;
}
public boolean wasNull() {
return getLong() == null;
}
public Object getObjectValue() {
return getLong();
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class SnsStrangerCommentDetailUI$5 implements OnMenuItemClickListener {
final /* synthetic */ SnsStrangerCommentDetailUI obC;
SnsStrangerCommentDetailUI$5(SnsStrangerCommentDetailUI snsStrangerCommentDetailUI) {
this.obC = snsStrangerCommentDetailUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
SnsStrangerCommentDetailUI.b(this.obC);
return true;
}
}
|
/**
*
*/
package collections;
import java.util.LinkedList;
/**
* @author Ashish
*
* The following program demonstrates the use of Linked List without the Iterator
*
* The internal structure of Linked List is Double Linked List.
*
* The List interface allows duplicate value and the output is based on insertion order.
*
*/
public class List2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<String> obj=new LinkedList<>(); // New Linked List is created of type String.
obj.add("A");
obj.add("B");
obj.add("C");
obj.add("D"); // String value are added to the Linked List.
obj.add("E");
obj.add("F");
obj.add("G");
obj.add("H");
for(String i:obj) // Enhanced for loop is used to iterate through the Linked List
{
System.out.println(i); // Values are printed to the console.
}
}
}
|
import java.util.*;
import java.io.*;
public class DeviceInfo implements Serializable{
private HashMap<String,String> map = new HashMap<String,String>();
private HashMap<String,String> mapId_type = new HashMap<String,String>();
public class Device implements Serializable{
protected String deviceId,arduinoId;
protected String type;
protected boolean on;
public Device(){
deviceId="null";
arduinoId="null";
type="null";
on = false;
//cmd="null";
}
public String getID(){
return deviceId;
}
public String getArdID(){
return arduinoId;
}
public String getType(){
return type;
}
public void setDevice(String deviceId,String arduinoId,String type){
this.deviceId=new String(deviceId);
this.arduinoId=new String(arduinoId);
this.type=new String(type);
}
}
public class Television extends Device{
private String brand;
public Television(String deviceId,String arduinoId,String type,String brand){
this.deviceId=new String(deviceId);
this.arduinoId=new String(arduinoId);
this.type=new String(type);
this.brand=new String(brand);
}
public void setBrand(String B){
this.brand=new String(B);
}
}
public class AirConditioner extends Device{
private String brand;
public AirConditioner(String deviceId,String arduinoId,String type,String brand){
this.deviceId=new String(deviceId);
this.arduinoId=new String(arduinoId);
this.type=new String(type);
this.brand=new String(brand);
}
public void setBrand(String B){
this.brand=new String(B);
}
}
public class Light extends Device{
private String motionSensor;
public Light(String deviceId,String arduinoId,String type,String motionSensor){
this.deviceId=new String(deviceId);
this.arduinoId=new String(arduinoId);
this.type=new String(type);
this.motionSensor=new String(motionSensor);
}
public void setMotionSensor(String MS){
this.motionSensor=new String(MS);
}
}
private Device deviceList[];
private int deviceCnt;
public DeviceInfo(int maxAmount){
deviceList=new Device[maxAmount];
deviceCnt=0;
}
//AddAppliance[MC ID][Device type][Arduino ID][Device ID][cmd]
public void addDeviceInfo(String type,String ardId,String id,String cmd){
Device newDevice;
if(type.equals("light")){
newDevice = new Light(id,ardId,type,cmd);
deviceList[deviceCnt]=newDevice;
deviceCnt++;
}
if(type.equals("AC")){
newDevice = new AirConditioner(id,ardId,type,cmd);
deviceList[deviceCnt]=newDevice;
deviceCnt++;
}
if(type.equals("TV")){
newDevice = new Television(id,ardId,type,cmd);
deviceList[deviceCnt]=newDevice;
deviceCnt++;
}
map.put(id,ardId);
mapId_type.put(id,type);
//System.out.println((String)map.get(id));
//System.out.println(getArdIDFromMap(id));
//System.out.println("add complete2");
}
int getDeviceIndex(String arduinoId){
for(int i=0;i<deviceCnt;i++){
if(arduinoId.equals(deviceList[i].arduinoId))
return i;
}
return 0;
}
boolean getDeviceStatus(int index){
return deviceList[index].on;
}
public String getDeviceId(int index){
return deviceList[index].deviceId;
}
public String getArdIDFromMap(String deviceId){
String returnString = map.get(deviceId);
if (returnString!=null)
return returnString;
else
return null;
}
public String getTypeFromMap(String deviceId){
String returnString = mapId_type.get(deviceId);
if (returnString!=null)
return returnString;
else
return null;
}
}
|
package com.lingnet.vocs.service.monit;
import java.util.HashMap;
import java.util.List;
import com.lingnet.common.service.BaseService;
import com.lingnet.util.Pager;
import com.lingnet.vocs.entity.ConstantData;
public interface MonitoringService extends BaseService<ConstantData, String> {
/**
* 根据盒子唯一标识查找数据库中20组数据(n个监控点)
* @Title: findConstantData
* @param boxId 盒子唯一标识
* @param uid 监控点
* @return
* List<Object[]>
* @author duanjj
* @since 2017年7月6日 V 1.0
*/
public List<Object[]> findConstantData(String boxId,String uid);
public List<Object[]> findConstantDataNew(String boxId,String uid);
/**
* 根据盒子唯一标识查找数据库中时间最大的一条数据
* @Title: findLastData
* @param boxId
* @param string
* @return
* Object[]
* @author duanjj
* @since 2017年7月7日 V 1.0
*/
public Object[] findLastData(String boxId, String string);
/**
* 查询分页数据,按创建时间倒叙排列,
* @Title: findPagerData
* @param pager
* @param map
* @return
* List<HashMap<String,Object>>
* @author duanjj
* @since 2017年7月21日 V 1.0
*/
public List<HashMap<String, Object>> findPagerData(Pager pager,HashMap<String,Object> map);
public String getDuData(String boxId);
}
|
package com.example.gebruiker.parceltracer.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class AftershipResource {
/** Pages to show (Default: 1) */
@SerializedName("page")
@Expose(serialize = false, deserialize = false)
private int page;
/** Number of trackings each page contain (Default: 100) */
@SerializedName("limit")
@Expose(serialize = false, deserialize = false)
private int limit;
/** Total number of matched trackings (Max: 10.000) */
@SerializedName("count")
@Expose(serialize = false)
private int count;
/** Main keyword of the trackings */
@SerializedName("keyword")
@Expose(serialize = false)
private String keyword;
/** Unique code of each courier */
@SerializedName("slug")
@Expose(serialize = false, deserialize = false)
private String slug;
/** Origin countries of the trackings */
@SerializedName("origin")
@Expose(serialize = false, deserialize = false)
private List<String> origins;
/** Destination countries of the trackings */
@SerializedName("destination")
@Expose(serialize = false, deserialize = false)
private List<String> destinations;
/** Status of the trackings */
@SerializedName("tag")
@Expose(serialize = false, deserialize = false)
private String tag;
/** Custom fields of the trackings */
@SerializedName("fields")
@Expose(serialize = false, deserialize = false)
private String fields;
/** Earliest creation date of the trackings */
@SerializedName("created_at_min")
@Expose(serialize = false, deserialize = false)
private String createdAtMin;
/** Latest creation date of the trackings */
@SerializedName("created_at_max")
@Expose(serialize = false, deserialize = false)
private String createdAtMax;
/** Last update date of the trackings */
@SerializedName("last_updated_at")
@Expose(serialize = false, deserialize = false)
private String lastUpdatedAt;
/** List of Trackings */
@SerializedName("trackings")
@Expose(serialize = false)
private List<Tracking> trackings;
/** Single Trackings */
@SerializedName("tracking")
@Expose
private Tracking tracking;
/** List of Couriers */
@SerializedName("couriers")
@Expose(serialize = false)
private List<Courier> couriers;
public AftershipResource(Tracking tracking) {
this.tracking = tracking;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public List<String> getOrigins() {
return origins;
}
public void setOrigins(List<String> origins) {
this.origins = origins;
}
public List<String> getDestinations() {
return destinations;
}
public void setDestinations(List<String> destinations) {
this.destinations = destinations;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getFields() {
return fields;
}
public void setFields(String fields) {
this.fields = fields;
}
public String getCreatedAtMin() {
return createdAtMin;
}
public void setCreatedAtMin(String createdAtMin) {
this.createdAtMin = createdAtMin;
}
public String getCreatedAtMax() {
return createdAtMax;
}
public void setCreatedAtMax(String createdAtMax) {
this.createdAtMax = createdAtMax;
}
public String getLastUpdatedAt() {
return lastUpdatedAt;
}
public void setLastUpdatedAt(String lastUpdatedAt) {
this.lastUpdatedAt = lastUpdatedAt;
}
public List<Tracking> getTrackings() {
return trackings;
}
public void setTrackings(List<Tracking> trackings) {
this.trackings = trackings;
}
public Tracking getTracking() {
return tracking;
}
public void setTracking(Tracking tracking) {
this.tracking = tracking;
}
public List<Courier> getCouriers() {
return couriers;
}
public void setCouriers(List<Courier> couriers) {
this.couriers = couriers;
}
}
|
package com.android.lvxin.videos;
import android.content.Context;
import com.android.lvxin.BasePresenter;
import com.android.lvxin.BaseView;
import com.android.lvxin.data.VideoInfo;
import java.util.List;
/**
* @ClassName: VideosContract
* @Description: TODO
* @Author: lvxin
* @Date: 6/12/16 15:48
*/
public interface VideosContract {
interface View extends BaseView<Presenter> {
void showVideos(List<VideoInfo> videos);
void showNoVideos();
void openVideoDetailUi(List<VideoInfo> videos);
void showLoadingVideosError();
String getProjectDir();
Context getContext();
}
interface Presenter extends BasePresenter {
void loadVideos();
void openVideo(VideoInfo requestedVideo);
void openVideos(List<VideoInfo> requestedVideos);
}
}
|
package mapper;
import beans.PurchasingCardForm;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface PurchasingCardFormMapper extends BasicMapper<PurchasingCardForm> {
/**
*
* @param id
* @return
*/
@Select("SELECT * FROM PURCHASING_CARD_FORM WHERE ID = #{id}")
PurchasingCardForm getById(@Param("id")String id);
/**
*
* @return
*/
@Select("SELECT * FROM PURCHASING_CARD_FORM")
List<PurchasingCardForm> getAll();
/**
*
* @param
* private String id;
private String rowstamp;
private String companyPurchasing;
private String address;
private String city;
private String zipcode;
private String phone;
private String nameDeliver;
private String mocode;
private String approverName;
private String submittedBy;
private java.sql.Timestamp submitted;
private String isactive;
*/
@Insert("INSERT INTO \"WORKFLOW\".\"PURCHASING_CARD_FORM\" (\"ID\", \"ROWSTAMP\", \"COMPANY_PURCHASING\", \"ADDRESS\"," +
" \"CITY\", \"ZIPCODE\", \"PHONE\", \"NAME_DELIVER\", \"MOCODE\",\"APPROVER_NAME\",\"SUBMITTED\", \"ISACTIVE\") " +
"VALUES (PURCHASING_CARD_FORM_IDSEQ.nextval ,#{rowstamp},#{companyPurchasing},#{address},#{city},#{zipcode},#{phone},#{nameDeliver},#{mocode},#{approverName}" +
",#{submittedBy},#{submitted}, #{isactive})")
void insert(PurchasingCardForm purchasingCardForm);
/**
*
* @param purchasingCardForm
*/
@Update("UPDATE \"WORKFLOW\".\"PURCHASING_CARD_FORM\" t SET" +
" t.\"ROWSTAMP\" = #{rowstamp}, t.\"COMPANY_PURCHASING\" = #{companyPurchasing}," +
" t.\"ADDRESS\" = #{address}, t.\"CITY\" = #{city}, " +
"t.\"ZIPCODE\" = #{zipcode}, t.\"PHONE\" = #{phone}, t.\"NAME_DELIVER\" = #{nameDeliver}, t.\"MOCODE\" = #{mocode}, t.\"APPROVER_NAME\" = #{approverName}," +
"t.\"SUBMITTED_BY\" = #{submittedBy}, " +
"t.\"SUBMITTED\" = #{submitted}, " +
"t.\"ISACTIVE\" = #{isactive} WHERE t.\"ID\" = #{id}")
void updateById(PurchasingCardForm purchasingCardForm);
/**
*
* @param id
*/
@Delete("")
void softDeleteById(String id);
/**
*
* @param id
*/
@Delete("DELETE FROM \"WORKFLOW\".\"PURCHASING_CARD_FORM\" WHERE \"ID\" = #{id}")
void forceDeleteByID(String id);
/**
*
*/
@Update("")
void createTable();
/**
*
*/
@Update("")
void dropTable();
}
|
package jie.android.ip.common.actor;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds;
import com.badlogic.gdx.graphics.g2d.BitmapFontCache;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
public class LabelActor extends Actor {
private String text;
private BitmapFontCache cache;
private boolean wrap = false;
private float wrapWidth;
private HAlignment lineAlign = HAlignment.CENTER;//.LEFT;
private final float oldX, oldY;
private boolean sizeInvalid = true;
private final TextBounds bounds = new TextBounds();
public LabelActor(final String text, final BitmapFont font) {
oldX = font.getScaleX();
oldY = font.getScaleY();
this.text = text;
this.cache = new BitmapFontCache(font, true);
}
@Override
public void draw(Batch batch, float parentAlpha) {
if (sizeInvalid) {
this.getBounds();
}
final BitmapFont font = cache.getFont();
font.setScale(super.getScaleX(), super.getScaleY());
cache.setColor(super.getColor());
//cache.setText(text, getX(), getY());
if (!wrap) {
cache.setMultiLineText(text, getX(), getY());
} else {
cache.setWrappedText(text, getX(), getY(), wrapWidth, lineAlign);
}
cache.draw(batch, super.getColor().a * parentAlpha);
font.setScale(oldX, oldY);
}
public void setText(final String text) {
this.text = text;
}
private void computeSize() {
final BitmapFont font = cache.getFont();
font.setScale(super.getScaleX(), super.getScaleY());
if (!wrap) {
bounds.set(font.getMultiLineBounds(text));// cache.setText(text, getX(), getY());
} else {
bounds.set(font.getWrappedBounds(text, wrapWidth));
}
font.setScale(oldX, oldY);
super.setWidth(bounds.width);
super.setHeight(bounds.height);
sizeInvalid = false;
}
public final TextBounds getBounds() {
if (sizeInvalid) {
computeSize();
}
return this.bounds;
}
@Override
public void setPosition(float x, float y) {
super.setPosition(x, y + getHeight());
}
public void setWrap(boolean wrap) {
this.wrap = wrap;
sizeInvalid = true;
}
public void setWrapWidth(float width) {
this.wrapWidth = width;
sizeInvalid = true;
}
public void setTextAlign(final HAlignment align) {
this.lineAlign = align;
}
@Override
public float getWidth() {
if (sizeInvalid) {
computeSize();
}
return super.getWidth();
}
@Override
public float getHeight() {
if (sizeInvalid) {
computeSize();
}
return super.getHeight();
}
}
|
package com.spqa.wefun.listener;
/**
* Created by MyPC on 23/04/2017.
*/
public interface OnLoadMoreListener {
void onLoadMore();
}
|
package listaExercicios2;
import java.util.Scanner;
public class exercicio5_indicaIndicePoluicao {
public static void main(String[] args) {
Scanner leia = new Scanner(System.in);
double indicePoluicao;
System.out.print("Digite o índice de poluição atual: ");
indicePoluicao = leia.nextDouble();
if (indicePoluicao >= 0.5) {
System.out.printf("O índice de poluição é de " + indicePoluicao
+ ". Todas as indústrias do 1º, 2º e 3º grupo devem suspender suas atividades.\n");
} else if (indicePoluicao >= 0.4) {
System.out.printf("O índice de poluição é de " + indicePoluicao
+ ". Todas as indústrias do 1º e 2º grupo devem suspender suas atividades.\n");
} else if (indicePoluicao >= 0.3) {
System.out.printf("O índice de poluição é de " + indicePoluicao
+ ". Todas as indústrias do 1º grupo devem suspender suas atividades.\n");
} else if (indicePoluicao <= 0.25) {
System.out.printf("O índice de poluição está dentro dos limites aceitos.\n");
}
}
}
|
package prj.betfair.api.betting.operations;
import prj.betfair.api.betting.datatypes.TimeRange;
import prj.betfair.api.betting.datatypes.CurrentOrderSummaryReport;
import prj.betfair.api.betting.datatypes.SimpleTypes.OrderProjection;
import prj.betfair.api.betting.datatypes.SimpleTypes.OrderBy;
import prj.betfair.api.betting.datatypes.SimpleTypes.SortDir;
import java.util.Set;
import prj.betfair.api.betting.exceptions.APINGException;
import prj.betfair.api.common.Executor;
/***
* Returns a list of your current orders. Optionally you can filter and sort your current orders
* using the various parameters, setting none of the parameters will return all of your current
* orders, up to a maximum of 1000 bets, ordered BY_BET and sorted EARLIEST_TO_LATEST. To retrieve
* more than 1000 orders, you need to make use of the fromRecord and recordCount parameters.
*/
public class ListCurrentOrdersOperation {
private final OrderBy orderBy;
private final SortDir sortDir;
private final int recordCount;
private final TimeRange dateRange;
private final TimeRange placedDateRange;
private final Set<String> marketIds;
private final Set<String> customerOrderRefs;
private final Executor executor;
private final OrderProjection orderProjection;
private final Set<String> betIds;
private final int fromRecord;
public ListCurrentOrdersOperation(Builder builder) {
this.orderBy = builder.orderBy;
this.sortDir = builder.sortDir;
this.recordCount = builder.recordCount;
this.dateRange = builder.dateRange;
this.placedDateRange = builder.placedDateRange;
this.marketIds = builder.marketIds;
this.customerOrderRefs = builder.customerOrderRefs;
this.executor = builder.executor;
this.orderProjection = builder.orderProjection;
this.betIds = builder.betIds;
this.fromRecord = builder.fromRecord;
}
/**
* @return betIds Optionally restricts the results to the specified bet IDs.
*/
public Set<String> getBetIds() {
return this.betIds;
}
/**
* @return marketIds Optionally restricts the results to the specified market IDs.
*/
public Set<String> getMarketIds() {
return this.marketIds;
}
/**
*
* @return customerOrderRefs Optionally restricts the results to the specified customer Order Refs.
*/
public Set<String> getCustomerOrderRefs() {
return customerOrderRefs;
}
/**
* @return orderProjection Optionally restricts the results to the specified order status.
*/
public OrderProjection getOrderProjection() {
return this.orderProjection;
}
/**
* @return placedDateRange @Deprecated use dateRange instead. Optionally restricts the results to
* be from/to the specified placed date. This date is inclusive, i.e. if an order was
* placed on exactly this date (to the millisecond) then it will be included in the
* results. If the from is later than the to, no results will be returned.
*/
public TimeRange getPlacedDateRange() {
return this.placedDateRange;
}
/**
* @return dateRange Replacement for placedDateRange to allow filtering by other date fields
* rather than just placedDate. Optionally restricts the results to be from/to the
* specified date, these dates are contextual to the orders being returned and therefore
* the dates used to filter on will change to placed, matched, voided or settled dates
* depending on the orderBy. This date is inclusive, i.e. if an order was placed on
* exactly this date (to the millisecond) then it will be included in the results. If the
* from is later than the to, no results will be returned.
*/
public TimeRange getDateRange() {
return this.dateRange;
}
/**
* @return orderBy Specifies how the results will be ordered. If no value is passed in, it
* defaults to BY_BET. Also acts as a filter such that only orders with a valid value in
* the field being ordered by will be returned (i.e. BY_VOID_TIME returns only voided
* orders, BY_SETTLED_TIME returns only settled orders and BY_MATCH_TIME returns only
* orders with a matched date (voided, settled, matched orders)).
*/
public OrderBy getOrderBy() {
return this.orderBy;
}
/**
* @return sortDir Specifies the direction the results will be sorted in. If no value is passed
* in, it defaults to EARLIEST_TO_LATEST.
*/
public SortDir getSortDir() {
return this.sortDir;
}
/**
* @return fromRecord Specifies the first record that will be returned. Records start at index
* zero, not at index one.
*/
public int getFromRecord() {
return this.fromRecord;
}
/**
* @return recordCount Specifies how many records will be returned, from the index position
* 'fromRecord'. Note that there is a page size limit of 1000. A value of zero indicates
* that you would like all records (including and from 'fromRecord') up to the limit.
*/
public int getRecordCount() {
return this.recordCount;
}
public CurrentOrderSummaryReport execute() throws APINGException {
return executor.execute(this);
}
public static class Builder {
private OrderBy orderBy;
private SortDir sortDir;
private int recordCount;
private TimeRange dateRange;
private TimeRange placedDateRange;
private Set<String> marketIds;
private Set<String> customerOrderRefs;
private OrderProjection orderProjection;
private Set<String> betIds;
private int fromRecord;
private Executor executor;
public Builder() {}
/**
* Use this function to set betIds
*
* @param betIds Optionally restricts the results to the specified bet IDs.
* @return Builder
*/
public Builder withBetIds(Set<String> betIds) {
this.betIds = betIds;
return this;
}
/**
* Use this function to set marketIds
*
* @param marketIds Optionally restricts the results to the specified market IDs.
* @return Builder
*/
public Builder withMarketIds(Set<String> marketIds) {
this.marketIds = marketIds;
return this;
}
/**
* Use this function to set customerOrderRefs
*
* @param customerOrderRefs Optionally restricts the results to the specified Customer Order Refs.
* @return Builder
*/
public Builder withCustomerOrderRefs(Set<String> customerOrderRefs) {
this.customerOrderRefs = customerOrderRefs;
return this;
}
/**
* Use this function to set orderProjection
*
* @param orderProjection Optionally restricts the results to the specified order status.
* @return Builder
*/
public Builder withOrderProjection(OrderProjection orderProjection) {
this.orderProjection = orderProjection;
return this;
}
/**
* @deprecated Use this function to set placedDateRange
* @param placedDateRange use dateRange instead. Optionally restricts the results to be from/to
* the specified placed date. This date is inclusive, i.e. if an order was placed on
* exactly this date (to the millisecond) then it will be included in the results. If the
* from is later than the to, no results will be returned.
* @return Builder
*/
@Deprecated
public Builder withPlacedDateRange(TimeRange placedDateRange) {
this.placedDateRange = placedDateRange;
return this;
}
/**
* Use this function to set dateRange
*
* @param dateRange Replacement for placedDateRange to allow filtering by other date fields
* rather than just placedDate. Optionally restricts the results to be from/to the
* specified date, these dates are contextual to the orders being returned and therefore
* the dates used to filter on will change to placed, matched, voided or settled dates
* depending on the orderBy. This date is inclusive, i.e. if an order was placed on
* exactly this date (to the millisecond) then it will be included in the results. If the
* from is later than the to, no results will be returned.
* @return Builder
*/
public Builder withDateRange(TimeRange dateRange) {
this.dateRange = dateRange;
return this;
}
/**
* Use this function to set orderBy
*
* @param orderBy Specifies how the results will be ordered. If no value is passed in, it
* defaults to BY_BET. Also acts as a filter such that only orders with a valid value in
* the field being ordered by will be returned (i.e. BY_VOID_TIME returns only voided
* orders, BY_SETTLED_TIME returns only settled orders and BY_MATCH_TIME returns only
* orders with a matched date (voided, settled, matched orders)).
* @return Builder
*/
public Builder withOrderBy(OrderBy orderBy) {
this.orderBy = orderBy;
return this;
}
/**
* Use this function to set sortDir
*
* @param sortDir Specifies the direction the results will be sorted in. If no value is passed
* in, it defaults to EARLIEST_TO_LATEST.
* @return Builder
*/
public Builder withSortDir(SortDir sortDir) {
this.sortDir = sortDir;
return this;
}
/**
* Use this function to set fromRecord
*
* @param fromRecord Specifies the first record that will be returned. Records start at index
* zero, not at index one.
* @return Builder
*/
public Builder withFromRecord(int fromRecord) {
this.fromRecord = fromRecord;
return this;
}
/**
* Use this function to set recordCount
*
* @param recordCount Specifies how many records will be returned, from the index position
* 'fromRecord'. Note that there is a page size limit of 1000. A value of zero indicates
* that you would like all records (including and from 'fromRecord') up to the limit.
* @return Builder
*/
public Builder withRecordCount(int recordCount) {
this.recordCount = recordCount;
return this;
}
/**
* @param executor Executor for this operation
* @return Builder
*/
public Builder withExecutor(Executor executor) {
this.executor = executor;
return this;
}
public ListCurrentOrdersOperation build() {
return new ListCurrentOrdersOperation(this);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package math;
import java.util.Arrays;
import java.util.NoSuchElementException;
import math.exc.ExpressionException;
import java.util.Vector;
/**
* Creates a generic standard math expression.
* This class lets you to write, change, read and compute math expression.
* Computation is only available for expressions containing the following specifications:
* - Range limit for numbers are:
* - double primitive type for decimal expressions.
* - long primitive type for other expressions.
* - Accepted operators are: +,-,*,/,^,RADQ.
* - Accepted brackets are: (, ), [, ], {, }.
* It is permitted to use a type of brackets inside the same brackets argument.
* For example: (2*(8-5))^2
* Instead of the previous example it is recommended to use the this form:
* [2*(8-5)]^2.
* It is computable this expression form:
* [2*(8-5)+(6*2)]^2.
* In case of omitted brackets, computations will be solved with the standard
* math priority rules of operators.
* For example:
* 2+3*5^2*RADQ4 will be solved as:
* 2+3*25*RADQ4; 2+3*50; 2+150; 152;
* @see ExpressionConstants class
* @author fabio
*/
public abstract class Expression extends Vector<String> implements Comparable<Expression>, Computable {
protected String ris;
public Expression(){
super();
ris = "";
}
public Expression(Expression expression){
super(expression);
ris = "";
}
/**
* Returns the result of this expression
* @see calculte(); genericCalc(); methods
* @return
*/
public String getRis(){
return ris;
}
/**
* Sets a new value to the result of this expression
* @param ris
*/
public void setRis(String ris){
this.ris = ris;
}
/**
* Calculates this expression according to the
* priority order of computations in standard math rules.
* This methods return the result of the computation as a String object.
* Result is also saved in the global field of this object
* @return the computation of this expression
* @throws math.exc.ExpressionException
*/
public String calculate() throws ExpressionException {
Expression exp = (Expression) this.clone();
try {
while(exp.size()>1){ //finche l'espressione non sarà risolta
int startIndex = 0;
int endIndex = exp.size();
for(String[] pars : ExpressionConstants.PRIORITY_PARENTHESIS){ //Guardo se contiene parentesi
if(exp.contains(pars[0])){ //se le contiene, il vettore ha nuovi indici di inizio e fine
startIndex = exp.lastIndexOf(pars[0]);
exp.removeElementAt(startIndex);
endIndex = exp.indexOf(pars[1]);
exp.removeElementAt(endIndex);
break;
}
}
for(String[] ops : ExpressionConstants.PRIORITY_OPERATORS){ //per ogni array di operatori prioritari (in ordine)
for(int i=startIndex;i<endIndex;i++){ //dall'indice di inzio all'indice di fine attuale
String value = exp.elementAt(i); //mi ricavo l'elemento corrente
int index = Arrays.binarySearch(ops, value);
if(index>=0){ //se è un operatore che rientra tra gli l'array di operatori prioritari attuale
String operator = exp.elementAt(i); //mi ricavo operatori e operandi
String op1, op2;
int start = i-1, end = i+1;
switch(operator){
case ExpressionConstants.RADQ:
op1 = "";
start = i;
break;
default:
op1 = exp.elementAt(start);
break;
}
op2 = exp.elementAt(end);
String subtot = this.computation(op1, op2, operator); //eseguo l'operazione
for(int count=start;count<=end;count++){ //elimino gli elementi dell'operazione dal vettore
exp.removeElementAt(start);
}
exp.add(start, subtot); //aggiungo il risultato al vettore
i--;
endIndex = endIndex-2;
}
}
}
}
ris = exp.firstElement();
}catch(NumberFormatException | ArrayIndexOutOfBoundsException ex){
throw new ExpressionException(ex.getMessage());
}
catch(NoSuchElementException e){
ris = "";
}
return ris;
}
public static String genericCalc(Expression exp) throws ExpressionException{
return exp.calculate();
}
/**
* Compares two expressions for their result:
* Returns:
* * 1 if this expression has a higher result then the other
* * -1 if this expression has a lower result then the other
* * 0 if the two expression gives both the same result.
* @param expression
* @return
*/
@Override
public int compareTo(Expression expression){
return (ris.compareTo(expression.ris));
}
/**
* Returns true if the two expression are the exactly the same.
* Which it means that every element of this expression has the same value
* of the expression specified by parameter
* @param expression
* @return
*/
public boolean equals(Expression expression){
return super.equals(expression);
}
/**
* Returns a string representation of the expression.
* The string representation is composed by each element of the expression
* @return
*/
@Override
public String toString(){
String output="";
for(String value : this){
output+=value;
}
return output;
}
}
|
package com.puxtech.reuters.rfa.Consumer;
import com.puxtech.reuters.rfa.Common.QuoteSource;
public interface ConsumerConfig {
public void setQuoteSource(QuoteSource quoteSource);
public void shutdown();
public void restart();
}
|
package tv.skimo.meeting.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tv.skimo.meeting.model.Annotation;
import java.util.List;
import java.util.Optional;
@Service
public class AnnotationService {
private final AnnotationRepository annotationRespository;
@Autowired
public AnnotationService(AnnotationRepository annotationRepository) {
this.annotationRespository = annotationRepository;
}
public List<Annotation> findAll() {
return annotationRespository.findAll();
}
public Optional<Annotation> findById(Long id) {
return annotationRespository.findById(id);
}
public Annotation save(Annotation stock) {
return annotationRespository.save(stock);
}
public void deleteById(Long id) {
annotationRespository.deleteById(id);
}
}
|
package com.e.jobkwetu.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import com.e.jobkwetu.Register_User.LoginActivity;
public class OpenActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Save state to our app
SharedPreferences sharedPreferences=getSharedPreferences("sharedPrefs", MODE_PRIVATE);
final SharedPreferences.Editor editor=sharedPreferences.edit();
final boolean isDarkModeOn =sharedPreferences.getBoolean("isDarkModeOn",false);
//check the state on opening the app
if (isDarkModeOn){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//set switch off TODO
//switch1.setChecked(true);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
//set switch on TODO
//switch1.setChecked(false);
}
startActivity(new Intent(OpenActivity.this, LoginActivity.class));
finish();
//setContentView(R.layout.activity_open);
}
}
|
package com.tencent.mm.plugin.record.ui.b;
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.plugin.record.ui.a.b;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.ui.widget.b.a;
class d$1 implements OnLongClickListener {
final /* synthetic */ d mtI;
final /* synthetic */ b mtz;
d$1(d dVar, b bVar) {
this.mtI = dVar;
this.mtz = bVar;
}
public final boolean onLongClick(View view) {
final TextView textView = (TextView) view;
CharSequence spannableString = new SpannableString(textView.getText());
spannableString.setSpan(new BackgroundColorSpan(this.mtI.context.getResources().getColor(R.e.light_blue_bg_color)), 0, textView.getText().length(), 33);
textView.setText(spannableString);
a aVar = new a(this.mtI.context, textView);
aVar.uKW = new 1(this);
aVar.ofq = new 2(this, textView);
aVar.uCi = new OnDismissListener() {
public final void onDismiss() {
textView.setText(d$1.this.mtz.bOz.desc);
j.g(textView, 1);
}
};
if (view.getTag(R.h.touch_loc) instanceof int[]) {
int[] iArr = (int[]) view.getTag(R.h.touch_loc);
aVar.bU(iArr[0], iArr[1]);
} else {
aVar.bU(this.mtI.hpr, this.mtI.hps);
}
return true;
}
}
|
package org.fuserleer.serialization;
/**
* Dummy class to include serializer field in output if required.
*/
public enum SerializerDummy {
/**
* One and only value assigned to instances of
* {@link SerializerDummy}.
*/
DUMMY;
}
|
package com.zhonghuilv.shouyin.result;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.zhonghuilv.shouyin.enums.ErrorMsgEnum;
import com.zhonghuilv.shouyin.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class CallResult implements Serializable {
private static final long serialVersionUID = -4421283742208745358L;
public int code = 1;
public String desc = "调用成功";
public void setErrorMsg(ErrorMsgEnum errorMsg) {
this.code = errorMsg.getErrorCode();
this.desc = errorMsg.getErrorDesc();
}
public CallResult() {
}
public CallResult(ErrorMsgEnum errorMsgEnum) {
this.code = errorMsgEnum.getErrorCode();
this.desc = errorMsgEnum.getErrorDesc();
}
public void setErrorMsg(BusinessException e) {
this.code = e.getErrCode();
this.desc = e.getErrDesc();
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Object results;
@Override
public String toString() {
return String.format("CallBackMsg=====>code:%s,desc:%s", code, desc);
}
}
|
package com.google.android.exoplayer2.h;
public interface r$d {
void lb();
}
|
package cache.inmemorycache;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class CacheRequest implements Serializable {
private String commandId;
private String transactionId;
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
List<String> options = new ArrayList<>();
public String getCommandId() {
return commandId;
}
public void setCommandId(String commandId) {
this.commandId = commandId;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
|
import java.io.File;
import java.util.HashMap;
import org.newdawn.slick.Image;
import org.newdawn.slick.Sound;
/**
* @author Anders Hagward
* @author Fredrik Hillnertz
* @version 2010-05-06
*/
public class ResourceLoader {
private static ResourceLoader instance;
private HashMap<String, Image> images;
private HashMap<String, Sound> sounds;
private ResourceLoader() {
images = new HashMap<String, Image>();
}
public static ResourceLoader getInstance() {
if (instance == null) {
instance = new ResourceLoader();
}
return instance;
}
public void loadImages(String folderPath) {
File path = new File(folderPath);
File[] files = path.listFiles();
for (File file : files) {
try {
images.put(file.getName(), new Image(file.getPath()));
} catch (Exception e) {
System.err.println("Failed to create image object from file: "
+ file.getPath());
}
}
}
public void loadSounds(String folderPath) {
File path = new File(folderPath);
File[] files = path.listFiles();
for (File file : files) {
try {
sounds.put(file.getName(), new Sound(file.getPath()));
} catch (Exception e) {
System.err.println("Failed to create sound object from file: "
+ file.getPath());
}
}
}
public Image getImage(String name) {
try {
return images.get(name);
} catch (NullPointerException e) {
System.err.println("Failed to find image: " + name);
return null;
}
}
public Sound getSound(String name) {
try {
return sounds.get(name);
} catch (NullPointerException e) {
System.err.println("Failed to find sound: " + name);
return null;
}
}
}
|
package util;
public class DurationUtil {
public static String inHours(long milis){
long mi=0;
long sec=0;
long min=0;
long hour=0;
String result="";
sec=milis/1000;//dibagi 1000 dapet detik
mi=milis % 1000;//sisa pembagian ke milisecond
if(sec>0){
min=sec/60;
sec=sec % 60;
}
if(min>0){
hour=min/60;
min=min % 60;
}
return String.format("%d:%d:%d.%d", hour,min,sec,mi);
}
public static String avgInHours(long total, long size){
if(size<=0) return "";
long avg=total/size;
return inHours(avg);
}
}
|
package de.madjosz.adventofcode.y2016;
import static org.junit.jupiter.api.Assertions.assertEquals;
import de.madjosz.adventofcode.AdventOfCodeUtil;
import java.util.List;
import org.junit.jupiter.api.Test;
class Day20Test {
@Test
void day20() {
List<String> lines = AdventOfCodeUtil.readLines(2016, 20);
Day20 day20 = new Day20(lines);
assertEquals(32259706L, day20.a1());
assertEquals(113L, day20.a2());
}
@Test
void day20_exampleinput() {
List<String> lines = AdventOfCodeUtil.readLines(2016, 20, "test");
Day20 day20 = new Day20(lines);
assertEquals(3L, day20.a1());
assertEquals((1L << 32) - 8, day20.a2());
}
}
|
package com.mango.leo.zsproject.login;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import com.mango.leo.zsproject.R;
import com.mango.leo.zsproject.ZsActivity;
import com.mango.leo.zsproject.base.BaseActivity;
import com.mango.leo.zsproject.industrialservice.createrequirements.util.ProjectsJsonUtils;
import com.mango.leo.zsproject.login.bean.UserMessageBean;
import com.mango.leo.zsproject.utils.ACache;
import com.mango.leo.zsproject.utils.AppUtils;
import com.mango.leo.zsproject.utils.NetUtil;
import org.greenrobot.eventbus.EventBus;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class StartActivity extends BaseActivity {
@Bind(R.id.start)
Button start;
@Bind(R.id.res)
Button res;
private Intent intent;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private UserMessageBean bean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_start);
ButterKnife.bind(this);
Log.v("ssssssssss","ooo");
sharedPreferences = getSharedPreferences("CIFIT",MODE_PRIVATE);
editor = sharedPreferences.edit();
if (sharedPreferences.getString("isOk","no").equals("yes")){
Log.v("ssssssssss"," ");
ACache mCache = ACache.get(this);
bean = ProjectsJsonUtils.readJsonUserMessageBeans(mCache.getAsString("message"));
EventBus.getDefault().postSticky(bean);
editor.putString("where",String.valueOf(bean.getResponseObject().getLocation().getProvince())+String.valueOf(bean.getResponseObject().getLocation().getCity())+String.valueOf(bean.getResponseObject().getLocation().getDistrict())).commit();
if (bean.getResponseObject().getTenant() == null){
editor.putString("type", "no").commit();
}else {
editor.putString("type", "yes").commit();
}
Log.v("ssssssssss",sharedPreferences.getString("type","www")+"**"+sharedPreferences.getString("where","广东省深圳市南山区")+"___"+mCache.getAsString("message"));
Intent intent = new Intent(this, ZsActivity.class);
startActivity(intent);
finish();
}
}
@OnClick({R.id.start, R.id.res})
public void onViewClicked(View view) {
/* if (!NetUtil.isNetConnect(this)){
AppUtils.showToast(this,"请连接网络");
return;
}*/
switch (view.getId()) {
case R.id.start:
intent = new Intent(this, PhoneLoginActivity.class);
startActivity(intent);
finish();
break;
case R.id.res:
intent = new Intent(this, ResActivity.class);
startActivity(intent);
finish();
break;
}
}
}
|
package org.browsexml.timesheetjob.model;
import static org.apache.commons.lang.StringUtils.left;
import static org.apache.commons.lang.StringUtils.right;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.security.Authentication;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.ldap.LdapAuthenticationProvider;
public class Constants implements MessageSourceAware {
private static Log log = LogFactory.getLog(Constants.class);
private static MessageSource messageSource = null;
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
FULLTIME_STRING = messageSource.getMessage("people.employee",
null, Locale.getDefault());
STUDENT_STRING = messageSource.getMessage("people.student",
null, Locale.getDefault());
BOTH_STRING = messageSource.getMessage("people.both",
null, Locale.getDefault());
CWS = messageSource.getMessage("export.cws",
null, Locale.getDefault());
NCWS = messageSource.getMessage("export.ncws",
null, Locale.getDefault());
}
public static DecimalFormatSymbols decimalSymbols = new DecimalFormatSymbols();
public static int MAX_HOURS_PER_WEEK_IN_HUNDREDS = 4000; // 40.00
public final static int NEITHER = 0;
public final static int STUDENT = 1;
public final static int FULLTIME = 2;
public final static int BOTH = 3;
public static String yearTermSeparator = ":";
/* number of days past end of a pay period that you can still edit time*/
/* This only applies to students
if it is the last pay period he will work in a department */
/* after this grace period, the person will disappear from a supervisor's roster*/
public static int PAYPERIOD_GRACE_PERIOD = 10;
public static String FULLTIME_STRING = "Employee";
public static String STUDENT_STRING = "Student";
public static String BOTH_STRING = "Entire Database";
public static String OVERTIME_CODE = "constants.overtime";
public static String SUPERROLE = "ROLE_TIMESHEET";
public static String BUS_SUPERROLE = "ROLE_TIMESHEETBUSOFF";
public static String FULLTIME_ROLE = "ROLE_FULLTIME_MANAGER";
public static String PARTTIME_ROLE = "ROLE_STUDENT_MANAGER";
public static Integer MAX_TABLE_RETURN_SIZE = 20;
public static Integer MIN_WAGE = 0; // In cents (hundreds)
public static String USER_CODE;
public static String PASS_CODE;
public static String displayTimeFormat = "hh:mm a";
public static String displayDateFormat = "MM/dd/yyyy";
public static SimpleDateFormat displayTime = getDateFormat(displayTimeFormat);
public static SimpleDateFormat displayDate = getDateFormat(displayDateFormat);
public static SimpleDateFormat excelDateFormat = getDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
public static String dbDateFormat = "yyyy-MM-dd HH:mm:ss:SSS";
public static String CWS = "cwsp";
public static String NCWS = "ncwsp";
public static Pattern phoneMatch = Pattern
.compile("(\\d{3})?(\\d{3})(\\d{4})");
public static Pattern pennyMatch = Pattern
.compile("\\A *\\$?(\\d*)?(?:\\.(\\d*))? *\\Z");
public static SimpleDateFormat getDateFormat(String format) {
SimpleDateFormat displayDate = new SimpleDateFormat(format);
displayDate.setLenient(false);
return displayDate;
}
private static HashMap<String, String> procs = new HashMap();
/**
* Add a number of days to date; truncate hour, minute, and second
*
* @param date
* @param days
* @return
*/
public static String strDayadd(Date date, Integer days) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
return format.format(addField(Calendar.DAY_OF_MONTH, days, date));
}
public static Date dayadd(Date date, Integer days) {
return addField(Calendar.DAY_OF_MONTH, days, date);
}
public static String formatDate(Date date) {
return displayDate.format(date);
}
public static String formatTime(Date date) {
return displayTime.format(date);
}
public static Integer unformatPennies(String pennies) {
log.debug("unformat input = '" + pennies + "'");
if (pennies == null)
return null;
Matcher matcher = pennyMatch.matcher(pennies);
if (matcher.matches()) {
log.debug("format phone MATCH group 0 = " + matcher.group(0));
String onlyPennies = matcher.group(2);
if (onlyPennies == null)
onlyPennies = "";
log.debug("pennies = '" + onlyPennies + "'");
String onlyDollars = matcher.group(1);
if (onlyDollars == null)
onlyDollars = "";
log.debug("dollars = '" + onlyDollars + "'");
return Integer.parseInt(onlyDollars + left(onlyPennies + "00", 2));
}
return 0;
}
public static String formatPennies(Integer pennies) {
return decimalSymbols.getCurrencySymbol() + formatFixed(pennies);
}
public static String formatFixed(Integer rate) {
if (rate == null)
return "0.00";
return ((rate / 100) + "." + right("00" + rate % 100, 2));
}
public static String formatPhone(String phone) {
log.debug("format phone = " + phone);
if (phone == null)
return null;
Matcher matcher = phoneMatch.matcher(phone);
if (matcher.matches()) {
log.debug("format phone MATCH group 0 = " + matcher.group(0));
return "(" + matcher.group(1) + ") " + matcher.group(2) + "-"
+ matcher.group(3);
}
log.debug("format phone return = " + phone);
return phone;
}
public static String unformatPhone(String phone) {
log.debug("unformat phone = " + phone);
if (phone == null)
return null;
log.debug("unformat phone return = " + phone);
return phone.replaceAll("\\D", "");
}
public static Integer year(Date date) {
return getField(Calendar.YEAR, date);
}
/**
* Add date fields working with Date rather than Calendar
*
* @param field
* @param value
* @param date
* @return
*/
public static Date addField(int field, int value, Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
c.set(field, c.get(field) + value);
return c.getTime();
}
public static void setField(int field, int value, Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
c.set(field, value);
}
public static Integer getField(int field, Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
return c.get(field);
}
/**
* Given a format for a date and a date string, parse the date string and
* return a java.sql.Date object
*
* @param format
* @param date
* @return
* @throws ParseException
*/
public static java.sql.Date getSqlDate(String format, String date)
throws ParseException {
return new java.sql.Date(getDate(format, date).getTime());
}
/**
* Given a format for a date and a date string, parse the date string and
* return a java.util.Date object
*
* @param format
* @param date
* @return
* @throws ParseException
*/
public static Date getDate(String format, String date)
throws ParseException {
return new SimpleDateFormat(format).parse(date);
}
/**
* The 'process' stored procedure implemented in Java for testing with the
* Hypersonic database.
*
* @param conn
* @return
*/
public static Integer process(Connection conn) {
System.err.println("Process called");
int recordCount = 0;
try {
Statement stmt = conn.createStatement();
recordCount = stmt
.executeUpdate("insert into log values (current_timestamp, 'test..')");
System.err.println("run select 1");
ResultSet rs = stmt
.executeQuery("select people_id, job, "
+ " begin_date as periodBegin, "
+ " hours_worked_id, term, pp_year "
+ "from hours_worked day "
+ " join code_jobs on code_jobs.department = day.job "
+ " join payper p on punched > Begin_date and punched < \"org.browsexml.timesheetjob.model.Constants.dayadd\"(End_date, 1) "
+ "where processed is null and approved is not null "
+ "order by people_id, job ");
while (rs.next()) {
String peopleId = rs.getString("people_id");
String job = rs.getString("job");
// Date period = rs.getDate("periodBegin");
Integer id = rs.getInt("hours_worked_id");
String term = rs.getString("term");
String pp_year = rs.getString("pp_year");
System.err.println("run select 2");
PreparedStatement ps = conn
.prepareStatement("select top 1 g.ident "
+ "from awarded w "
+ " join agreements g on w.ident = g.AwardId "
+ " join code_jobs j on j.id = g.job and j.department = ? "
+ " left join timesheets t on t.agreementid = g.ident "
+ "where (1=1) "
+ " and w.people_id = ? "
+ " and w.year = ? "
+ " and w.term = ? "
+ "group by people_id, year, term, \"Award Code\", w.amount, g.ident, g.amount "
+ "having case when g.amount = -1 then w.amount else g.amount end - "
+ " sum(case when t.hours*t.rate is null then 0 else t.hours*t.rate end) > 0 "
+ "order by case \"Award Code\" when 'FWN651' then 1 when 'SWN751' then 2 else 3 end "
+ " ");
ps.setString(1, job);
ps.setString(2, peopleId);
ps.setString(3, pp_year);
ps.setString(4, term);
System.err.println("job = " + job);
System.err.println("peopleId = " + peopleId);
System.err.println("pp_year = " + pp_year);
System.err.println("term = " + term);
ResultSet rsIdent = ps.executeQuery();
while (rsIdent.next()) {
Integer agreement = rsIdent.getInt(1);
System.err.println("Agreement = " + agreement);
String query = "update hours_worked set processed = "
+ agreement + " where hours_worked_id = " + id;
System.err.println("run select 3 query = " + query);
stmt.executeUpdate(query);
}
System.err.println("run select 4");
stmt
.executeUpdate("insert into timesheets(agreementId, hours, rate, entryDate, periodBegin) "
+ "select "
+ " processed, "
+ " sum (datediff('mi', punched, punched_out))/60.0 as hours, "
+ " g.rate as rate, "
+ " current_date as entryDate, "
+ " payId as periodBegin "
+ "from hours_worked day "
+ " left join code_jobs on code_jobs.department = day.job "
+ " join payper p on punched > Begin_date and punched < \"org.browsexml.timesheetjob.model.Constants.dayadd\"(End_date, 1) "
+ " join agreements g on processed = g.ident "
+ "where processed is not null and approved is not null and timesheet_id is null "
+ "group by processed, g.rate, approved, payId "
+ " ");
System.err.println("run select 5");
ResultSet rsUpdate = stmt
.executeQuery("select w.hours_worked_id, t.ident "
+ "from hours_worked w "
+ " join timesheets t on w.processed = t.agreementId "
+ "where w.timesheet_id is null and w.processed is not null ");
while (rsUpdate.next()) {
Integer hoursWorkedId = rsUpdate.getInt("hours_worked_id");
Integer timesheet = rsUpdate.getInt("ident");
stmt
.executeUpdate("update hours_worked set timesheet_id = "
+ timesheet
+ "where hours_worked_id = "
+ hoursWorkedId + " ");
}
ps.close();
}
stmt.close();
} catch (SQLException e) {
recordCount = -e.getErrorCode();
e.printStackTrace();
}
System.err.println("DONE...");
return recordCount;
}
public static void addProc(String name, String query) {
procs.put(name, query);
}
public static String getProc(String name) {
addProc("process", "exec dbo.process");
addProc("emp_process", "exec dbo.emp_process");
// addProc("process",
// "call \"org.browsexml.timesheetjob.model.Constants.process\"()");
return procs.get(name);
}
public static String toReflexString(Object o) {
return ToStringBuilder.reflectionToString(o,
ToStringStyle.MULTI_LINE_STYLE);
}
public static void printParameters(HttpServletRequest request) {
log.debug("PARAMETERS");
for (Enumeration params = request.getParameterNames(); params
.hasMoreElements();) {
String name = (String) params.nextElement();
log.debug(name + " = " + request.getParameter(name));
}
log.debug("PARAMETERS END");
}
public static boolean sameDay(Date d1, Date d2) {
if (d1 == null || d2 == null)
return false;
Calendar date1 = new GregorianCalendar();
date1.setTime(d1);
Calendar date2 = new GregorianCalendar();
date2.setTime(d2);
return date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR)
&& date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH)
&& date1.get(Calendar.DATE) == date2.get(Calendar.DATE);
}
/**
* Log on as me for testing only
* @param ctx
* @return
*/
public Authentication getAuthentication(ConfigurableApplicationContext ctx) {
String user = Constants.USER_CODE;
String pass = Constants.PASS_CODE;
AuthenticationProvider provider = (LdapAuthenticationProvider)ctx.getBean("secondLdapProvider");
Authentication auth = provider.authenticate(
new UsernamePasswordAuthenticationToken(user, pass));
return auth;
}
public static String getCws() {
return "CWSP";
}
public static String getNcws() {
return "NCWSP";
}
public void setPassCode(String pass) {
this.PASS_CODE = pass;
}
public void setUserCode(String code) {
this.USER_CODE = code;
}
public void setOvertimeCode(String code) {
this.OVERTIME_CODE = code;
}
public void setMinWage(Integer min_wage) {
MIN_WAGE = min_wage;
}
public void setCws(String cws) {
this.CWS = cws;
}
public void setNcws(String ncws) {
this.NCWS = ncws;
}
public void setDisplayTimeFormat(String displayTimeFormat) {
this.displayTimeFormat = displayTimeFormat;
displayTime = getDateFormat(displayTimeFormat);
}
public void setDisplayDateFormat(String displayDateFormat) {
this.displayDateFormat = displayDateFormat;
displayDate = getDateFormat(displayDateFormat);
}
public void setExcelDateFormat(String excelDateFormat) {
this.excelDateFormat = getDateFormat(excelDateFormat);
}
public void setPhoneMatch(String pattern) {
this.phoneMatch = Pattern.compile(pattern);
}
public void setPennyMatch(String pattern) {
this.pennyMatch = Pattern.compile(pattern);
}
public void setYearTermSeparator(String sep) {
this.yearTermSeparator = sep;
}
public void setPayperiodGracePeriod(Integer period) {
this.PAYPERIOD_GRACE_PERIOD = period;
}
public void setMaxHoursPerWeek(Integer hours) {
this.MAX_HOURS_PER_WEEK_IN_HUNDREDS = hours * 100;
}
public void setMaxTablePageSize(Integer size) {
this.MAX_TABLE_RETURN_SIZE = size;
}
public static String getBreadCrumbs(HttpServletRequest request, HttpSession session) {
if (messageSource == null)
return "";
String key = request.getServletPath();
log.debug("key = " + key);
Path path = (Path) session.getAttribute("path");
if (path == null) {
path = new Path();
String index = "/index.jsp";
String title = messageSource.getMessage(index,
null, index, Locale.getDefault());
session.setAttribute("path", path);
if (!"/logon.jsp".equals(key) || !index.equals(key)) {
path.push(index, "/index.jsp", request.getParameterMap(),
title, request.getContextPath());
path.push(index, "/index.jsp", request.getParameterMap(),
title, request.getContextPath());
}
}
String title = messageSource.getMessage(key,
null, key, Locale.getDefault());
path.push(key, request.getQueryString(), request.getParameterMap(), title,
request.getContextPath());
return path.out(key);
}
}
|
package com.imesne.office.excel.model;
import com.imesne.assistant.common.validation.Verifier;
import com.imesne.office.excel.utils.ExcelKitUtils;
/**
* Created by liyd on 17/7/4.
*/
public class ExcelRange {
private Integer sheetNum;
private Integer beginRowNum;
private Integer endRowNum;
private Integer beginCellNum;
private Integer endCellNum;
private Integer placeholderRow;
public ExcelRange() {
this.sheetNum = 1;
this.beginRowNum = 1;
this.endRowNum = Integer.MAX_VALUE;
this.beginCellNum = 1;
this.endCellNum = Integer.MAX_VALUE;
placeholderRow = 0;
}
public Integer getSheetNum() {
return sheetNum;
}
public Integer getBeginRowNum() {
return beginRowNum;
}
public Integer getEndRowNum() {
return endRowNum;
}
public Integer getBeginCellNum() {
return beginCellNum;
}
public Integer getEndCellNum() {
return endCellNum;
}
public Integer getPlaceholderRow() {
return placeholderRow;
}
public static RangeBuilder builder() {
return new RangeBuilder();
}
public static class RangeBuilder {
/**
* 程序中索引从0开始,减1
*/
ExcelRange excelRange = new ExcelRange();
public RangeBuilder sheetNum(int sheetNum) {
this.excelRange.sheetNum = sheetNum;
return this;
}
public RangeBuilder beginRowNum(int beginRowNum) {
this.excelRange.beginRowNum = beginRowNum;
return this;
}
public RangeBuilder endRowNum(int endRowNum) {
this.excelRange.endRowNum = endRowNum;
return this;
}
public RangeBuilder beginCellNum(int beginCellNum) {
this.excelRange.beginCellNum = beginCellNum;
return this;
}
public RangeBuilder beginCellNum(String beginCellNum) {
int num = ExcelKitUtils.columnToNum(beginCellNum);
this.excelRange.beginCellNum = num;
return this;
}
public RangeBuilder endCellNum(int endCellNum) {
this.excelRange.endCellNum = endCellNum;
return this;
}
public RangeBuilder endCellNum(String endCellNum) {
int num = ExcelKitUtils.columnToNum(endCellNum);
this.excelRange.endCellNum = num;
return this;
}
public RangeBuilder placeholderRow(int placeholderRow) {
this.excelRange.placeholderRow = placeholderRow;
return this;
}
public ExcelRange build() {
Verifier.init()
.notNull(this.excelRange.sheetNum, "sheetNum")
.notNull(this.excelRange.beginRowNum, "beginRowNum")
.notNull(this.excelRange.endRowNum, "endRowNum")
.notNull(this.excelRange.beginCellNum, "beginCellNum")
.notNull(this.excelRange.endCellNum, "endCellNum")
.validate();
return this.excelRange;
}
}
}
|
package net.cupmouse.minecraft.eplugin.database;
import net.cupmouse.minecraft.eplugin.EPlugin;
import net.cupmouse.minecraft.eplugin.EPluginComponent;
import org.spongepowered.api.Sponge;
import java.nio.ByteBuffer;
import java.sql.*;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.*;
import java.util.concurrent.*;
/**
* @since 2016/01/30
*/
public class DatabaseManager extends EPluginComponent {
public static DateTimeFormatter SQL_DATETIME_FORMAT = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS").withResolverStyle(ResolverStyle.STRICT);
private Map<Thread, Connection> connections = new HashMap<>();
private ExecutorService multiThreadExecutor;
public DatabaseManager(EPlugin plugin) {
super(plugin, "データベース");
this.multiThreadExecutor = Executors.newFixedThreadPool(2);
}
<V> Future<V> submitToExecutor(Callable<V> callable) {
return this.multiThreadExecutor.submit(callable);
}
void closeConnectionFor(Thread thread) {
plugin.getLogger().info("DBコネクションクローズ:" + thread.getName());
Connection removed = connections.remove(thread);
try {
removed.rollback();
removed.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
void closeConnection() throws SQLException {
closeConnectionFor(Thread.currentThread());
}
Connection getConnectionFor(Thread thread) throws SQLException {
Connection connection = connections.get(thread);
if (connection != null) {
if (connection.isValid(3000)) {
return connection;
} else {
closeConnectionFor(thread);
}
}
plugin.getLogger().info("新しいDBコネクション:" + thread.getName());
connection = DriverManager.getConnection(plugin.config.getDatabaseURL(), plugin.config.getDatabaseUser(), plugin.config.getDatabasePassword());
connection.setAutoCommit(false);
connections.put(thread, connection);
return connection;
}
public Connection getConnection() throws SQLException {
return getConnectionFor(Thread.currentThread());
}
public DatabaseSession createSession() {
return new DatabaseSession(this);
}
public static byte[] uuidToBytes(UUID uuid) {
return ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array();
}
public static UUID bytesToUUID(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(16).put(bytes);
return new UUID(buffer.getLong(0), buffer.getLong(8));
}
@Override
public void onFinishDisable() throws Exception {
plugin.getLogger().info("クエリエグゼキューターが終了するのを待っています。");
multiThreadExecutor.shutdown();
multiThreadExecutor.awaitTermination(20, TimeUnit.SECONDS);
List<Runnable> remain = multiThreadExecutor.shutdownNow();
if (remain.size() > 0) {
for (Runnable runnable : remain) {
plugin.getLogger().warn(runnable.toString());
}
}
HashSet<Thread> threads = new HashSet<>(connections.keySet());
for (Thread thread : threads) {
closeConnectionFor(thread);
}
plugin.getLogger().info("すべてのDBコネクションを正常に閉じました。");
}
@Override
public void registerListeners() {
Sponge.getEventManager().registerListeners(plugin, this);
}
}
|
package com.lbsp.promotion.util.http.request;
public enum ResponseType {
//a=1&b=2&c=3
urlParam,
//{"a":"1","b":"2","c":"3"}
json
}
|
import java.util.ArrayList;
import java.rmi.Remote;
public interface Servidor extends Remote {
public ArrayList<Resultado> imprimir (ArrayList<Trabajo> trabajos);
public ArrayList<Trabajo> consultar (int idUsuario);
public ArrayList<Resultado> cancelar (ArrayList<Trabajo> trabajos);
public boolean reiniciar (int idUsuario);
}
|
package com.jk.jkproject;
import com.jk.jkproject.ui.entity.BaseInfo;
import java.util.List;
/**
* @author fansan
* @version 12/3/20
*/
public class UserGameListBean extends BaseInfo {
public List<DataBean> data;
public static class DataBean{
/**
* "video_duration": "5",
* "introduce": "你们都在想我的!你说你的生活方式的不同阶段都有自己的想法去去感受一下",
* "sex": 1,
* "count": 34,
* "order_price": 2000,
* "video": "http://qn.zbjlife.cn/a498a6c384eb661fab1698053e403e94.mp3",
* "units": "小时",
* "dan_name": "新锐",
* "userId": "1020820",
* "picture": "http://qn.zbjlife.cn/f9c17a5e83d4dcb28ec298af3cd1b5bb.png",
* "play_id": 1,
* "name": "cf",
* "nickname": "Kae的直播"
*/
public String video_duration;
public String introduce;
public String userId;
public int sex;
public int count;
public int order_price;
public String video;
public String units;
public String dan_name;
public String picture;
public int play_id;
public String name;
public String nickname;
public String img;
public int events_one_buy;
}
}
|
package webmail.managers.userManagers;
import webmail.managers.Manager;
import webmail.managers.otherManagers.SQLManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by JOKER on 12/2/14.
*/
public class EditFolderManager extends Manager {
public EditFolderManager(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Override
public void run(){
String id= request.getParameter("fid");
int fid = Integer.parseInt(id);
String name = request.getParameter("name");
SQLManager.updateFolderSQL(fid, name);
try {
response.sendRedirect("/folder?infolder=inbox");
}
catch(IOException e){
e.printStackTrace();
}
}
}
|
package com.jk.jkproject.ui.widget.danmaku;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.blankj.utilcode.util.LogUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jk.jkproject.R;
import com.jk.jkproject.ui.entity.LiveFireworksInfo;
import com.jk.jkproject.ui.widget.room.LiveLevelView;
import com.jk.jkproject.utils.EmojiParseUtil;
import com.jk.jkproject.utils.EmoticonUtils;
import com.jk.jkproject.utils.LiveRoleUtils;
import com.jk.jkproject.utils.ScreenUtils;
public class DanmakuChannel extends RelativeLayout {
public boolean isRunning = false;
private DanmakuClickListener listener;
public DanmakuEntity mEntity;
public DanmakuChannel(Context paramContext) {
super(paramContext);
init();
}
public DanmakuChannel(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
init();
}
public DanmakuChannel(Context paramContext, AttributeSet paramAttributeSet, int paramInt) {
super(paramContext, paramAttributeSet, paramInt);
init();
}
@TargetApi(21)
public DanmakuChannel(Context paramContext, AttributeSet paramAttributeSet, int paramInt1, int paramInt2) {
super(paramContext, paramAttributeSet, paramInt1, paramInt2);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.danmaku_channel_layout, (ViewGroup) this, true);
if (Build.VERSION.SDK_INT >= 21)
setClipToOutline(false);
}
public void setDanmakuClickListener(DanmakuClickListener paramDanmakuClickListener) {
this.listener = paramDanmakuClickListener;
}
public void setDanmakuEntity(DanmakuEntity paramDanmakuEntity) {
this.mEntity = paramDanmakuEntity;
}
public void startAnimation(final DanmakuEntity entity, final DanmakuEndListener danmakuEndListener) {
this.isRunning = true;
setDanmakuEntity(entity);
if (mEntity != null) {
final View view = View.inflate(getContext(), R.layout.danmu_userchat_item, null);
SimpleDraweeView simpleDraweeView = (SimpleDraweeView) view.findViewById(R.id.danmu_user_avatar);
LiveLevelView levelView = (LiveLevelView) view.findViewById(R.id.danmu_user_level);
TextView contentView = (TextView) view.findViewById(R.id.danmu_user_des);
if (entity.getType() == DanmakuEntity.DANMAKU_TYPE_USERCHAT) {
levelView.setLevel(entity.getLevel());
String name = entity.getName() + ":";
String content = entity.getText();
String avatarImageUrl = entity.getAvatar();
//匿名
if (LiveRoleUtils.isAnonymousRole(entity.getRole())) {
name = "匿名" + ":";
avatarImageUrl = "res:///" + R.mipmap.profile_secret_user;
}
simpleDraweeView.setImageURI(avatarImageUrl);
SpannableString spannableString = EmojiParseUtil.getInstace().getExpressionString(getContext(),
EmoticonUtils.get().getDefaultEmojiIds(),
name + content, 16);
spannableString.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.white)), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
contentView.setText(spannableString);
view.setTag(R.id.tag_uid, entity.getUserId());
view.setTag(R.id.tag_icon, entity.getAvatar());
view.setTag(R.id.tag_role, entity.getRole());
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String oid = (String) v.getTag(R.id.tag_uid);
String icon = (String) v.getTag(R.id.tag_icon);
int role = (int) v.getTag(R.id.tag_role);
// 不等于系统账号
if (!TextUtils.isEmpty(oid) && !TextUtils.isEmpty(icon) && !oid.equals("1000") && listener != null) {
listener.onDanmuIconClick(oid, icon, role);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
} else if (entity.getType() == DanmakuEntity.DANMAKU_TYPE_FIREWORKS) {
simpleDraweeView.setImageURI(Uri.parse("res:///" + R.mipmap.live_fireworks));
levelView.setLevel(entity.getLevel());
final LiveFireworksInfo info = entity.getLiveFireworksInfo();
if (info.getRich_text() != null) {
RichTextParse.parse(contentView, info.getRich_text(), false);
} else {
String desStr = getContext().getString(R.string.live_gift_fireworks);
String nameFrom = info.getFr_name();
String nameTo = info.getTo_name();
String format = String.format(desStr, nameFrom, nameTo);
// SpannableString spannableString = new SpannableString(format);
SpannableString spannableString = EmojiParseUtil.getInstace().getExpressionString(getContext(),
EmoticonUtils.get().getDefaultEmojiIds(),
format, 16);
spannableString.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.white)), 0, nameFrom.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.white)), nameFrom.length() + 2, nameFrom.length() + 2 + nameTo.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
contentView.setText(spannableString);
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onDanmakuClick(getContext(), entity);
}
}
});
} else {
simpleDraweeView.setVisibility(View.GONE);
levelView.setVisibility(View.GONE);
contentView.setTextColor(ContextCompat.getColor(getContext(), R.color.live_yellow));
if (entity.getRichText() != null) {
RichTextParse.parse(contentView, entity.getRichText(), false);
} else {
SpannableString spannableString = EmojiParseUtil.getInstace().getExpressionString(getContext(),
EmoticonUtils.get().getDefaultEmojiIds(),
entity.getText(), 16);
contentView.setText(spannableString);
}
}
view.measure(-1, -1);
int measuredWidth = view.getMeasuredWidth();
//int measuredHeight = view.getMeasuredHeight();
int screenW = ScreenUtils.getScreenW(getContext());
int width = measuredWidth > screenW ? measuredWidth : screenW;
DanmakuChannel.this.getLayoutParams().width = width;
// Animation anim = AnimationHelper.createTranslateAnim(getContext(), screenW, -measuredWidth);
ObjectAnimator animator = AnimationHelper.createObjectAnim(getContext(), view, screenW, -measuredWidth);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
new Handler().post(new Runnable() {
public void run() {
view.clearAnimation();
DanmakuChannel.this.removeView(view);
if (danmakuEndListener != null) {
danmakuEndListener.endDanmu();
}
}
});
isRunning = false;
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
addView(view);
LogUtils.i("将弹幕对象添加到指定的弹道上");
animator.start();
LogUtils.i("在指定的弹道上,开始执行水平移动动画");
}
}
}
|
package iks.pttrns.patternmethod;
public class Coffee extends Beverage {
/* public void prepare() {
boilWater();
brewCoffeeGrinds();
pourInCup();
addSugarAndMilk();
}
private void addSugarAndMilk() {
}
private void pourInCup() {
}
private void brewCoffeeGrinds() {
}
private void boilWater() {
}*/
@Override
void addCondiments() {
System.out.println("Adding sugar and milk");
}
@Override
void brew() {
System.out.println("Brew coffe grinds");
}
}
|
package com.tencent.mm.r;
import com.tencent.mm.protocal.c.by;
import java.util.Map;
public interface f {
void a(int i, Map<String, by> map, boolean z);
}
|
package pl.finapi.paypal.output.pdf;
import java.io.OutputStream;
import java.util.List;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.finapi.paypal.model.Currency;
import pl.finapi.paypal.model.output.DocumentModels;
import pl.finapi.paypal.model.output.ExchangeRateDifferenceReportModels;
import pl.finapi.paypal.output.pdf.element.DowodWewnetrznyPdfWriter;
import pl.finapi.paypal.output.pdf.element.EwidencjaProwizjiPdfWriter;
import pl.finapi.paypal.output.pdf.element.EwidencjaRoznicPdfWriter;
import pl.finapi.paypal.output.pdf.element.PaypalFeeInvoicePdfWriter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
@Component
public class PaypalFeeReportAndInvoiceAndEwidencjaAndDowodPdfWriter {
private final EwidencjaProwizjiPdfWriter reportPdfWriter;
private final EwidencjaRoznicPdfWriter ewidencjaRoznicPdfWriter;
private final PaypalFeeInvoicePdfWriter invoicePdfWriter;
private final DowodWewnetrznyPdfWriter dowodWewnetrznyPdfWriter;
@Autowired
public PaypalFeeReportAndInvoiceAndEwidencjaAndDowodPdfWriter(EwidencjaProwizjiPdfWriter reportPdfWriter,
EwidencjaRoznicPdfWriter ewidencjaRoznicPdfWriter, PaypalFeeInvoicePdfWriter invoicePdfWriter, DowodWewnetrznyPdfWriter dowodWewnetrznyPdfWriter) {
this.reportPdfWriter = reportPdfWriter;
this.ewidencjaRoznicPdfWriter = ewidencjaRoznicPdfWriter;
this.invoicePdfWriter = invoicePdfWriter;
this.dowodWewnetrznyPdfWriter = dowodWewnetrznyPdfWriter;
}
public void writePaypalFeeReportAndInvoiceAndDokumentWewnetrzny(OutputStream outputStream, DocumentModels documentModels, Document document)
throws DocumentException {
// 1 paypal fees - faktura wewnetrzna
document.newPage();
invoicePdfWriter.addContent(document, documentModels.getPaypalFeeInvoiceModel());
// 2 paypal fees table
document.newPage();
reportPdfWriter.addContent(document, documentModels.getPaypalFeeReportModel());
for (Entry<Currency, ExchangeRateDifferenceReportModels> entry : documentModels.getExchangeRateDifferenceReportModel().entrySet()) {
// 3 roznice kursowe - dowod wewnetrzny x 2
if (!entry.getValue().getExchangeRateDifferenceReportModel().getSumOfNegatives().isZero()) {
document.newPage();
dowodWewnetrznyPdfWriter.addContent(entry.getValue().getDowodWewnetrznyModelForNegative(), document);
}
if (!entry.getValue().getExchangeRateDifferenceReportModel().getSumOfPositives().isZero()) {
document.newPage();
dowodWewnetrznyPdfWriter.addContent(entry.getValue().getDowodWewnetrznyModelForPositive(), document);
}
// 4 roznice kursowe table
document.newPage();
ewidencjaRoznicPdfWriter.addContent(entry.getValue().getExchangeRateDifferenceReportModel(), document);
}
}
public void writePaypalFeeReportAndInvoiceAndDokumentWewnetrzny(OutputStream outputStream, List<DocumentModels> documentModelsList) {
try {
Document document = new Document(PageSize.A4);
com.itextpdf.text.pdf.PdfWriter.getInstance(document, outputStream);
document.setMargins(30, 30, 30, 30);
document.open();
for (DocumentModels documentModels : documentModelsList) {
writePaypalFeeReportAndInvoiceAndDokumentWewnetrzny(outputStream, documentModels, document);
}
document.close();
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
}
|
package com.hb.rssai.util;
import android.text.Editable;
import android.text.Html;
import android.text.Layout;
import android.text.Spannable;
import android.text.style.AlignmentSpan;
import android.text.style.BulletSpan;
import android.text.style.LeadingMarginSpan;
import android.text.style.TypefaceSpan;
import org.xml.sax.XMLReader;
import java.util.Vector;
public class HtmlTagHandler implements Html.TagHandler {
private int mListItemCount = 0;
private final Vector<String> mListParents = new Vector<String>();
private static class Code {
}
private static class Center {
}
@Override
public void handleTag(final boolean opening, final String tag, Editable output,
final XMLReader xmlReader) {
if (opening) {
if (tag.equalsIgnoreCase("ul") || tag.equalsIgnoreCase("ol")
|| tag.equalsIgnoreCase("dd")) {
mListParents.add(tag);
mListItemCount = 0;
} else if (tag.equalsIgnoreCase("code")) {
start(output, new Code());
} else if (tag.equalsIgnoreCase("center")) {
start(output, new Center());
}
} else {
if (tag.equalsIgnoreCase("ul") || tag.equalsIgnoreCase("ol")
|| tag.equalsIgnoreCase("dd")) {
mListParents.remove(tag);
mListItemCount = 0;
} else if (tag.equalsIgnoreCase("li")) {
handleListTag(output);
} else if (tag.equalsIgnoreCase("code")) {
end(output, Code.class, new TypefaceSpan("monospace"), false);
} else if (tag.equalsIgnoreCase("center")) {
end(output, Center.class,
new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), true);
}
}
}
private void start(Editable output, Object mark) {
int len = output.length();
output.setSpan(mark, len, len, Spannable.SPAN_MARK_MARK);
}
private void end(Editable output, Class kind, Object repl, boolean paragraphStyle) {
Object obj = getLast(output, kind);
int where = output.getSpanStart(obj);
int len = output.length();
output.removeSpan(obj);
if (where != len) {
if (paragraphStyle) {
output.append("\n");
len++;
}
output.setSpan(repl, where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
private Object getLast(Editable text, Class kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
for (int i = objs.length; i > 0; i--) {
if (text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) {
return objs[i - 1];
}
}
return null;
}
}
private void handleListTag(Editable output) {
if (mListParents.lastElement().equals("ul")) {
output.append("\n");
String[] split = output.toString().split("\n");
int lastIndex = split.length - 1;
int start = output.length() - split[lastIndex].length() - 1;
output.setSpan(new BulletSpan(15 * mListParents.size()), start, output.length(), 0);
} else if (mListParents.lastElement().equals("ol")) {
mListItemCount++;
output.append("\n");
String[] split = output.toString().split("\n");
int lastIndex = split.length - 1;
int start = output.length() - split[lastIndex].length() - 1;
output.insert(start, mListItemCount + ". ");
output.setSpan(new LeadingMarginSpan.Standard(15 * mListParents.size()), start,
output.length(), 0);
}
}
}
|
package org.alienideology.jcord.handle.permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.alienideology.jcord.handle.permission.Permission.PermissionLevel.*;
/**
* Permission - A way to limit and grant certain abilities to members.
* @author AlienIdeology
*/
public enum Permission {
/* Guild Permissions */
CREATE_INSTANT_INVITE (0x00000001, "Allows creation of instant invites", ALL),
KICK_MEMBERS (0x00000002, "Allows kicking members", GUILD_ONLY),
BAN_MEMBERS (0x00000004, "Allows banning members", GUILD_ONLY),
ADMINISTRATOR (0x00000008, "Allows all permissions and bypasses channel permission overwrites", GUILD_ONLY),
MANAGE_CHANNELS (0x00000010, "Allows management and editing of channels", ALL),
MANAGE_SERVER (0x00000020, "Allows management and editing of the guild", GUILD_ONLY),
ADD_REACTIONS (0x00000040, "Allows for the addition of reactions to messages", ALL),
VIEW_AUDIT_LOGS (0x00000080, "Allows for viewing the audit logs of the guild", GUILD_ONLY),
/* TextChannel Permissions */
READ_MESSAGES (0x00000400, "Allows reading messages in a channel. The channel will not appear for users without this permission", ALL),
SEND_MESSAGES (0x00000800, "Allows for sending messages in a channel", ALL),
SEND_TTS_MESSAGES (0x00001000, "Allows for sending of /tts messages", ALL),
MANAGE_MESSAGES (0x00002000, "Allows for deletion of other users messages", ALL),
EMBED_LINKS (0x00004000, "Links sent by this user will be auto-embedded", ALL),
ATTACH_FILES (0x00008000, "Allows for uploading images and files", ALL),
READ_MESSAGE_HISTORY (0x00010000, "Allows for reading of message history", ALL),
MENTION_EVERYONE (0x00020000, "Allows for using the @everyone tag to notify all users in a channel, and the @here tag to notify all online users in a channel", ALL),
USE_EXTERNAL_EMOJIS (0x00040000, "Allows the usage of custom emojis from other servers", ALL),
/* VoiceChannel Permissions */
CONNECT (0x00100000, "Allows for joining of a voice channel", ALL),
SPEAK (0x00200000, "Allows for speaking in a voice channel", ALL),
MUTE_MEMBERS (0x00400000, "Allows for muting members in a voice channel", ALL),
DEAFEN_MEMBERS (0x00800000, "Allows for deafening of members in a voice channel", ALL),
MOVE_MEMBERS (0x01000000, "Allows for moving of members between voice channels", ALL),
USE_VOICE_ACTIVITY (0x02000000, "Allows for using voice-activity-detection in a voice channel", ALL),
// These counts as Guild Permissions
CHANGE_NICKNAME (0x04000000, "Allows for modification of own nickname", GUILD_ONLY),
MANAGE_NICKNAMES (0x08000000, "Allows for modification of other users nicknames", GUILD_ONLY),
MANAGE_ROLES (0x10000000, "Allows management and editing of roles", GUILD_ONLY),
MANAGE_WEBHOOKS (0x20000000, "Allows management and editing of webhooks", ALL),
MANAGE_EMOJIS (0x40000000, "Allows management and editing of emojis", GUILD_ONLY),
MANAGE_PERMISSIONS (0x80000000, "Allows management and editing permissions of a role in a specific channel", CHANNEL_ONLY),
UNKNOWN (-1, "Unknown permission", UNKNOWN_LEVEL);
/**
* All permissions assignable.
*/
public static Collection<Permission> ALL_PERMS = getPermissionsByLong(2146958591);
/**
* No permissions.
*/
public static Collection<Permission> NO_PERMS = getPermissionsByLong(0);
/**
* All Guild related permissions.
*/
public static Collection<Permission> ALL_GUILD_PERMS = getPermissionsByLong(2080374975);
/**
* All TextChannel permissions.
*/
public static Collection<Permission> ALL_TEXT_PERMS = getPermissionsByLong(523328);
/**
* All VoiceChannel permissions.
*/
public static Collection<Permission> ALL_VOICE_PERMS = getPermissionsByLong(66060288);
/**
* A Pre-set permissions for small guilds.
* This granted {@code Mention Everyone} permission.
*
* See this <a href = "https://discordapi.com/permissions.html#70765633">Permission Calculator</a>
* for permissions included in this constant.
*/
public static Collection<Permission> PRE_SET_PERM_SMALL = getPermissionsByLong(70765633);
/**
* A Pre-set permissions for large guilds.
* This denied {@code Mention Everyone}, but granted {@code View Audit Logs} permission.
*
* See this <a href = "https://discordapi.com/permissions.html#70634689">Permission Calculator</a>
* for permissions included in this constant.
*/
public static Collection<Permission> PRE_SET_PERM_LARGE = getPermissionsByLong(70634689);
public long value;
public String description;
public PermissionLevel level;
Permission (long value, String description, PermissionLevel level) {
this.value = value;
this.description = description;
this.level = level;
}
public static boolean hasPermission(long permissions, Permission permission) {
return (permissions & permission.value) != 0;
}
public static List<Permission> getPermissionsByLong(long permissionsLong) {
List<Permission> permissions = new ArrayList<>();
for (Permission perm : Permission.values()) {
if (hasPermission(permissionsLong, perm) && perm != UNKNOWN) {
permissions.add(perm);
}
}
return permissions;
}
public static long getLongByPermissions(Permission... permissions) {
long permLong = 0;
for (Permission perm : permissions) {
permLong |= perm.value;
}
return permLong;
}
public static long getLongByPermissions(Collection<Permission> permissions) {
return getLongByPermissions(permissions.toArray(new Permission[permissions.size()]));
}
public boolean isAllLevel() {
return this.level == ALL;
}
public boolean isGuildLevel() {
return this.level == ALL || this.level == GUILD_ONLY;
}
public boolean isChannelLevel() {
return this.level == ALL || this.level == CHANNEL_ONLY;
}
@Override
public String toString() {
return name().substring(0,1)+name().substring(1).toLowerCase().replaceAll("_", " ");
}
enum PermissionLevel {
ALL,
GUILD_ONLY,
CHANNEL_ONLY,
UNKNOWN_LEVEL
}
}
|
package com.nikvay.saipooja_patient.view.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CalendarView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.gson.Gson;
import com.nikvay.saipooja_patient.R;
import com.nikvay.saipooja_patient.apiCallCommen.ApiClient;
import com.nikvay.saipooja_patient.apiCallCommen.ApiInterface;
import com.nikvay.saipooja_patient.model.DoctorModel;
import com.nikvay.saipooja_patient.model.SelectDateTimeModel;
import com.nikvay.saipooja_patient.model.ServiceModel;
import com.nikvay.saipooja_patient.model.SuccessModel;
import com.nikvay.saipooja_patient.utils.ErrorMessageDialog;
import com.nikvay.saipooja_patient.utils.NetworkUtils;
import com.nikvay.saipooja_patient.utils.StaticContent;
import com.nikvay.saipooja_patient.view.adapter.SelectDateTimeAdapter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DateTimeSelectActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private RecyclerView recyclerViewTime;
private SelectDateTimeAdapter selectDateTimeAdapter;
private ArrayList<SelectDateTimeModel> selectDateTimeModelArrayList=new ArrayList<>();
private ImageView iv_close,img_empty;
private CalendarView calendarView;
private String date,selectedDate;
private ApiInterface apiInterface;
private ErrorMessageDialog errorMessageDialog;
private ServiceModel serviceModel;
private DoctorModel doctorModel;
private TextView tv_notdound;
String dayArray[]={"Morning","Evening","Day"};
private Spinner dayStatusSpinner;
private ArrayAdapter arrayAdapter;
private String dayStatusCode="1", dayStatus;
private String mTitle="Service Details",service_id ,patient_id,user_id,doctor_id, TAG = getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_time_select);
find_All_Ids();
events();
}
private void events() {
iv_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
CharSequence strDate = null;
Time chosenDate = new Time();
chosenDate.set(dayOfMonth, month, year);
long dateAppointment = chosenDate.toMillis(true);
strDate = DateFormat.format("yyyy-MM-dd", dateAppointment);
date= (String) strDate;
if (NetworkUtils.isNetworkAvailable(DateTimeSelectActivity.this))
callTimeSlot();
else
NetworkUtils.isNetworkNotAvailable(DateTimeSelectActivity.this);
// Toast.makeText(DateTimeSelectActivity.this, date, Toast.LENGTH_SHORT).show();
}
});
}
private void find_All_Ids() {
tv_notdound=findViewById(R.id.textSlotNotFound);
dayStatusSpinner=findViewById(R.id.spinnerDaystatus);
arrayAdapter=new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,dayArray);
dayStatusSpinner.setAdapter(arrayAdapter);
dayStatusSpinner.setOnItemSelectedListener(this);
recyclerViewTime=findViewById(R.id.recyclerViewTime);
iv_close=findViewById(R.id.iv_close);
calendarView=findViewById(R.id.calendarView);
GridLayoutManager gridLayoutManager = new GridLayoutManager(DateTimeSelectActivity.this,3);
recyclerViewTime.setLayoutManager(gridLayoutManager);
recyclerViewTime.hasFixedSize();
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
doctorModel= (DoctorModel) bundle.getSerializable(StaticContent.IntentKey.APPOINTMENT);
serviceModel= (ServiceModel) bundle.getSerializable(StaticContent.IntentKey.SERVICE_DETAIL);
service_id=serviceModel.getService_id();
doctor_id=doctorModel.getDoctor_id();
user_id = doctorModel.getUser_id();
mTitle = bundle.getString(StaticContent.IntentKey.ACTIVITY_TYPE);
}
apiInterface = ApiClient.getClient().create(ApiInterface.class);
date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
calendarView.setMinDate(System.currentTimeMillis() - 1000);
errorMessageDialog= new ErrorMessageDialog(DateTimeSelectActivity.this);
if (NetworkUtils.isNetworkAvailable(DateTimeSelectActivity.this))
callTimeSlot();
else
NetworkUtils.isNetworkNotAvailable(DateTimeSelectActivity.this);
}
private void callTimeSlot()
{
Call<SuccessModel> call = apiInterface.appointmentTimeSlot(dayStatusCode,doctor_id,date,user_id);
call.enqueue(new Callback<SuccessModel>() {
@Override
public void onResponse(Call<SuccessModel> call, Response<SuccessModel> response) {
String str_response = new Gson().toJson(response.body());
Log.e("" + TAG, "Response >>>>" + str_response);
try {
if (response.isSuccessful()) {
SuccessModel successModel = response.body();
selectDateTimeModelArrayList.clear();
String message = null, code = null;
if (successModel != null) {
message = successModel.getMsg();
code = successModel.getError_code();
if (code.equalsIgnoreCase("1"))
{
selectDateTimeModelArrayList.clear();
selectDateTimeModelArrayList=successModel.getSelectDateTimeModelArrayList();
if(selectDateTimeModelArrayList.size()!=0)
{
selectDateTimeAdapter = new SelectDateTimeAdapter(DateTimeSelectActivity.this, selectDateTimeModelArrayList, serviceModel,doctorModel, date);
recyclerViewTime.setVisibility(View.VISIBLE);
recyclerViewTime.setAdapter(selectDateTimeAdapter);
selectDateTimeAdapter.notifyDataSetChanged();
tv_notdound.setVisibility(View.GONE);
}
else
{
errorMessageDialog.showDialog("Doctor is no Available");
}
} else {
recyclerViewTime.setVisibility(View.GONE);
tv_notdound.setVisibility(View.VISIBLE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<SuccessModel> call, Throwable t) {
errorMessageDialog.showDialog(t.getMessage());
}
});
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
dayStatus=dayArray[position];
if (dayStatus.equalsIgnoreCase("Morning"))
{
dayStatusCode="1";
callTimeSlot();
}
if (dayStatus.equalsIgnoreCase("Evening"))
{
dayStatusCode="2";
callTimeSlot();
}
if (dayStatus.equalsIgnoreCase("Day"))
{
dayStatusCode="3";
callTimeSlot();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
package quiz21;
import java.util.ArrayList;
import java.util.List;
public class ArrayListQuiz02 {
/*
* 1. User클래스는 은닉된 변수로 name, age를 선언하고 생성
* 2. User클래스를 저장할 수 있는 List생성 선언
* 3. User객체 2개를 생성해서 리스트에 추가
* 4. list에 저장된 모든 name, age를 반복문으로 출력
* 5. list에 홍길자가 있다면 홍길자의 이름, 나이만 출력
* 6. list에 홍길동이 있다면 홍길동User객체 삭제
*/
public static void main(String[] args) {
List<User> list = new ArrayList<>();
User u = new User("홍길동", 22);
User u1 = new User("홍길자", 32);
list.add(u);
list.add(u1);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName()+list.get(i).getAge()+" ");
}System.out.println();
for(User user : list) {
if(user.getName().equals("홍길자"))
System.out.println("이름 : "+user.getName() + ", 나이 : " +user.getAge());
}
for (int i = 0; i < list.size(); i++) {
if(list.get(i).getName().equals("홍길동"))
list.remove(i);
}
System.out.println(list.toString());
}
}
|
package net.xndk.proxygen.handlers;
import java.lang.annotation.Annotation;
import javax.ws.rs.Produces;
import net.xndk.proxygen.MethodProperties;
public class ProducesHandler implements AnnotationHandler {
public Class<? extends Annotation> getTarget() {
return Produces.class;
}
public void handleAnnotation(Annotation annotation, MethodProperties properties) {
String[] values = ((Produces) annotation).value();
if (values.length == 1) {
properties.setResponseContentType(values[0]);
}
else {
// TODO: Log wrong number of arguments. What should we do when we get more than one?
}
}
}
|
package com.test.ketang;
public class test {
public static void main(String args){
sort(1,2,3,4,5);
}
public static void sort(Object...nums){
for(Object i:nums){
System.out.println(i);
}
}
}
|
//package com.example.test;
import com.example.expr.Addition;
import com.example.expr.Constant;
import com.example.expr.Expression;
public class H30Spring_11 {
public static void main(String[] args){
Expression two = new Constant(2);
Expression five = new Constant(5);
Expression add = new Addition(two, five);
//System.out.println(add + " = " + add.evaluate());
System.out.println(new Subtraction(add, new Subtraction(two, five)));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.component;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.BeanAttributes;
import jakarta.enterprise.inject.spi.InterceptionType;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import org.apache.webbeans.config.WebBeansContext;
/**
* <p>{@link jakarta.enterprise.inject.spi.Interceptor}
* Bean implementation for CDI-style Beans.
* This is Interceptors which got defined using
* @{@link jakarta.interceptor.InterceptorBinding}.</p>
*/
public class CdiInterceptorBean<T> extends InterceptorBean<T>
{
private Set<Annotation> interceptorBindings;
public CdiInterceptorBean(WebBeansContext webBeansContext,
AnnotatedType<T> annotatedType,
BeanAttributes<T> beanAttributes,
Class<T> beanClass,
Set<Annotation> interceptorBindings,
boolean enabled,
Map<InterceptionType, Method[]> interceptionMethods)
{
super(webBeansContext, annotatedType, beanAttributes, beanClass, interceptionMethods);
this.interceptorBindings = interceptorBindings;
this.setEnabled(enabled);
}
@Override
public Set<Annotation> getInterceptorBindings()
{
return interceptorBindings;
}
}
|
package ru.moneydeal.app.network;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class AuthorizationTokenInterceptor implements Interceptor {
public interface ITokenRepo {
@Nullable
String getToken();
}
private final ITokenRepo mTokenRepo;
AuthorizationTokenInterceptor(ITokenRepo tokenRepo) {
mTokenRepo = tokenRepo;
}
@Override
public Response intercept(Chain chain) throws IOException {
String token = mTokenRepo.getToken();
Request request = chain.request();
if (token != null) {
request = newRequestWithAccessToken(request, token);
}
return chain.proceed(request);
}
@NonNull
private Request newRequestWithAccessToken(@NonNull Request request, @NonNull String accessToken) {
return request.newBuilder()
.header("Authorization", "Bearer " + accessToken)
.build();
}
}
|
import Lab3Help.BLineStop;
import Lab3Help.BLineTable;
import Lab3Help.BStop;
import Lab3Help.Path;
import java.util.Iterator;
import java.util.List;
public class DijkstraStringPath implements Path<String> {
private final DijkstraPath<String> d;
/**
* DijkstraStringPath creates a DijkstraPath with Strings
*
* @param stops a list of the stops from the text-file
* @param lines a list of the lines from the text-file
*/
public DijkstraStringPath(List<BStop> stops, List<BLineTable> lines) {
Graph<String> g = new Graph<>();
for (BStop s : stops) {
g.addVertex(s.getName());
}
for (BLineTable bLT : lines) {
BLineStop[] stopArray = bLT.getStops();
for (int i = 1; i < stopArray.length; i++) {
g.addEdge(stopArray[i - 1].getName(), stopArray[i].getName(), stopArray[i].getTime());
}
}
d = new DijkstraPath<>(g);
}
/**
* Computes the path from <code>from</code> to <code>to</code> (if any). Path
* information can be retrieved by subsequent calls to
* <code>getPath()</code> and <code>getPathLength()</code>. It must be
* possible to call this method any number of times.
* <p>
* Precondition: The underlying graph must not contain any negative
* edge weights.
*
* @param from the vertex of which to start from
* @param to the goal
*/
@Override
public void computePath(String from, String to) {
d.computePath(from, to);
}
/**
* Returns an iterator over the nodes in the path.
* <p>
* If a path has been found the first node in the iterator is the
* argument <code>from</code> passed to <code>computePath</code> and
* the last node is <code>to</code>.
* <p>
* If no path was found or if no call to computePath has been made the
* iterator is empty.
*
* @return An iterator over the computed path.
*/
@Override
public Iterator<String> getPath() {
return d.getPath();
}
/**
* Returns the length of the computed path, that is, the sum of the
* weights of each arc on the path.
* <p>
* If no path was found the return value is an arbitrary integer. It
* is appropriate but not required to return a special value such as
* -1 in this case.
*
* @return The length of the computed path.
*/
@Override
public int getPathLength() {
return d.getPathLength();
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
public class CreateDatabase {
public static void main(String[] args){
try
{
Connection con=null;
Class.forName("org.sqlite.JDBC");
Scanner sc=new Scanner(System.in);
String s=sc.next();
String url = "jdbc:sqlite:"+s+".db";
con=DriverManager.getConnection(url);
if(con!=null)
{
System.out.println("Connected to SQLite3");
}
else
{
System.out.println("Connection to SQLite has been failed");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
//
package view;
import Bancodedados.ConexaoBD;
import ClassesBD.BD;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Caio
*/
public class TelaPrincipalMDI extends javax.swing.JFrame {
private ListadePessoas list;
private ListadeP list_produto;
private Listadepedido pedido;
private BD banco;
/**
* Creates new form TelaPrincipalMDI
*/
public TelaPrincipalMDI() {
this.list = new ListadePessoas();
this.pedido = new Listadepedido();
this.list_produto = new ListadeP();
BD banco = new BD();
for(Cliente c2 : banco.listarCliente()){
this.list.setClientes(c2);
}
for(Funcionarios c2 : banco.listarFuncionario()){
this.list.setFuncionarios(c2);
}
for(Produto c2 : banco.listarProduto()){
this.list_produto.adicionarP(c2);
}
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jDesktopPane1 = new javax.swing.JDesktopPane();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
Menu = new javax.swing.JMenuBar();
Arquivo = new javax.swing.JMenu();
Sair = new javax.swing.JMenuItem();
Clientes = new javax.swing.JMenu();
Cadastrar = new javax.swing.JMenuItem();
MostrarClientes = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
Produtos = new javax.swing.JMenu();
CadastrarProdutos = new javax.swing.JMenuItem();
MostrarTodos = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
Pedidos = new javax.swing.JMenu();
CadastrarPedidos = new javax.swing.JMenuItem();
ListarPedidos = new javax.swing.JMenuItem();
Excluir = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MENU");
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icone.jpg"))); // NOI18N
jLabel2.setFont(new java.awt.Font("Prestige Elite Std", 0, 36)); // NOI18N
jLabel2.setForeground(new java.awt.Color(204, 204, 255));
jLabel2.setText("Restaurante Mizuno");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setText("\tEste software possibilita um controle de pedido ao proprietário de um restaurante.\n\n\tAs imagens são de minha autoria.\n\n\tO software marca qual o funcionário estava atendendo à aquele pedido e o Cliente\n\tque fez o pedido referente ao produto/prato cadastrado no cardápio.\n\n\tIsso garante uma maior segurança ao restaurante a erros e falhas ao anotar um pedido,\n\tpermanecendo assim, registrados na máquina. ");
jScrollPane1.setViewportView(jTextArea1);
jDesktopPane1.setLayer(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);
jDesktopPane1.setLayer(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);
jDesktopPane1.setLayer(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPane1Layout.createSequentialGroup()
.addContainerGap(557, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel1)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPane1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 792, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDesktopPane1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 433, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
);
Arquivo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icone.jpg"))); // NOI18N
Arquivo.setText("Arquivo");
Sair.setText("Sair");
Sair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SairActionPerformed(evt);
}
});
Arquivo.add(Sair);
Menu.add(Arquivo);
Clientes.setText("Clientes");
Clientes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClientesActionPerformed(evt);
}
});
Cadastrar.setText("Cadastrar");
Cadastrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CadastrarActionPerformed(evt);
}
});
Clientes.add(Cadastrar);
MostrarClientes.setText("Mostrar Todos");
MostrarClientes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MostrarClientesActionPerformed(evt);
}
});
Clientes.add(MostrarClientes);
jMenuItem4.setText("Excluir");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
Clientes.add(jMenuItem4);
Menu.add(Clientes);
jMenu1.setText("Funcionário");
jMenuItem1.setText("Cadastrar");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Mostrar");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setText("Excluir");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
Menu.add(jMenu1);
Produtos.setText("Cardápio");
CadastrarProdutos.setText("Cadastrar Pratos");
CadastrarProdutos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CadastrarProdutosActionPerformed(evt);
}
});
Produtos.add(CadastrarProdutos);
MostrarTodos.setText("Mostrar todos Pratos");
MostrarTodos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MostrarTodosActionPerformed(evt);
}
});
Produtos.add(MostrarTodos);
jMenuItem5.setText("Excluir Prato");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
Produtos.add(jMenuItem5);
Menu.add(Produtos);
Pedidos.setText("Pedidos");
CadastrarPedidos.setText("Cadastrar");
CadastrarPedidos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CadastrarPedidosActionPerformed(evt);
}
});
Pedidos.add(CadastrarPedidos);
ListarPedidos.setText("Listar Pedidos");
ListarPedidos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ListarPedidosActionPerformed(evt);
}
});
Pedidos.add(ListarPedidos);
Excluir.setText("Excluir");
Excluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExcluirActionPerformed(evt);
}
});
Pedidos.add(Excluir);
Menu.add(Pedidos);
setJMenuBar(Menu);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDesktopPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDesktopPane1)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void ClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClientesActionPerformed
}//GEN-LAST:event_ClientesActionPerformed
//CADASTRAR UM CLIENTE
private void CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadastrarActionPerformed
TelaCadastroCliente telaCadClien = new TelaCadastroCliente();
jDesktopPane1.add(telaCadClien);
telaCadClien.setVisible(true);
Cliente cl = new Cliente();
cl = telaCadClien.retornarCliente();
this.list.setClientes(cl);
}//GEN-LAST:event_CadastrarActionPerformed
//CADASTRAR PRODUTO
private void CadastrarProdutosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadastrarProdutosActionPerformed
TelaCadastroProdutos telaP = new TelaCadastroProdutos(list_produto);
jDesktopPane1.add(telaP);
telaP.setVisible(true);
Produto t = new Produto();
ArrayList<Produto> c = new ArrayList<>();
c = telaP.retornarP();
list_produto.setP(c);
}//GEN-LAST:event_CadastrarProdutosActionPerformed
//CADASTRAR PEDIDO
private void CadastrarPedidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadastrarPedidosActionPerformed
TelaCadastrarPedidos telaCadPedido = new TelaCadastrarPedidos(list_produto,list);
jDesktopPane1.add(telaCadPedido);
telaCadPedido.setVisible(true);
Pedido c = new Pedido();
c = telaCadPedido.retornaPedido();
this.pedido.adicionarPedido(c);
}//GEN-LAST:event_CadastrarPedidosActionPerformed
//MOSTRAR LISTA DE CLIENTES
private void MostrarClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MostrarClientesActionPerformed
TelaListaCliente telaClien = new TelaListaCliente(this.list);
jDesktopPane1.add(telaClien);
telaClien.setVisible(true);
}//GEN-LAST:event_MostrarClientesActionPerformed
//MOSTRAR LISTA DE PRODUTOS
private void MostrarTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MostrarTodosActionPerformed
TelaListaProduto telaClien = new TelaListaProduto(list_produto);
jDesktopPane1.add(telaClien);
telaClien.setVisible(true);
}//GEN-LAST:event_MostrarTodosActionPerformed
//MOSTRAR LISTA DE PEDIDOS
private void ListarPedidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ListarPedidosActionPerformed
TelaListaPedido telaClien = new TelaListaPedido(pedido);
jDesktopPane1.add(telaClien);
telaClien.setVisible(true);
for(Pedido pe : this.pedido.getPedido()){
telaClien.preencher(pe);
}
}//GEN-LAST:event_ListarPedidosActionPerformed
//EXCLUIR UM PEDIDO
private void ExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExcluirActionPerformed
if(this.pedido.getPedido().isEmpty()){
JOptionPane.showMessageDialog(null,"não há clientes cadastrados!");
}
else{
TelaExcluirPedido telaPedido = new TelaExcluirPedido(pedido);
jDesktopPane1.add(telaPedido);
telaPedido.setVisible(true);
ArrayList<Pedido> w = new ArrayList<>();
w = telaPedido.retornaPedido();
this.pedido.setPedido(w);
}
}//GEN-LAST:event_ExcluirActionPerformed
//FECHAR O PROGRAMA
private void SairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SairActionPerformed
this.dispose();
}//GEN-LAST:event_SairActionPerformed
//EXCLUIR UM CLIENTE
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
if(this.list.getClientes().isEmpty()){
JOptionPane.showMessageDialog(null,"não há clientes cadastrados!");
}
else{
TelaExcluirCliente telaCliente = new TelaExcluirCliente(list);
jDesktopPane1.add(telaCliente);
telaCliente.setVisible(true);
ArrayList<Cliente> cl = new ArrayList<>();
cl = telaCliente.retornarCliente();
this.list.mudarClientes(cl);
}
}//GEN-LAST:event_jMenuItem4ActionPerformed
//CADASTRAR UM FUNCIONARIO
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
TelaCadastroFun telaCadFun = new TelaCadastroFun();
jDesktopPane1.add(telaCadFun);
Funcionarios f = new Funcionarios("","");
f = telaCadFun.retornarFuncionario();
this.list.setFuncionarios(f);
telaCadFun.setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
//EXCLUIR FUNCIONARIO
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
if(this.list.getFuncionarios().isEmpty()){
JOptionPane.showMessageDialog(null,"não há Funcionarios cadastrados!");
}
else{
TelaExcluirFuncionario telaF = new TelaExcluirFuncionario(list);
jDesktopPane1.add(telaF);
telaF.setVisible(true);
ArrayList<Funcionarios> cl = new ArrayList<>();
cl = telaF.retornarF();
this.list.mudarFuncionarios(cl);
}
}//GEN-LAST:event_jMenuItem3ActionPerformed
//MOSTRAR LISTA DE FUNCIONÁRIOS
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
TelaListaFun telaFun = new TelaListaFun();
for(Funcionarios c : this.list.getFuncionarios()){
telaFun.preencher(c);
}
jDesktopPane1.add(telaFun);
telaFun.setVisible(true);
}//GEN-LAST:event_jMenuItem2ActionPerformed
//Excluir UM PRODUTO
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
if(this.list_produto.getP().isEmpty()){
JOptionPane.showMessageDialog(null,"Não há pratos cadastrados!");
}
else{
TelaExcluirProduto telaP = new TelaExcluirProduto(list_produto);
jDesktopPane1.add(telaP);
telaP.setVisible(true);
ArrayList<Produto> aux = new ArrayList<>();
aux = telaP.retornarProduto();
this.list_produto.setP(aux);
}
}//GEN-LAST:event_jMenuItem5ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaPrincipalMDI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaPrincipalMDI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaPrincipalMDI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaPrincipalMDI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaPrincipalMDI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu Arquivo;
private javax.swing.JMenuItem Cadastrar;
private javax.swing.JMenuItem CadastrarPedidos;
private javax.swing.JMenuItem CadastrarProdutos;
private javax.swing.JMenu Clientes;
private javax.swing.JMenuItem Excluir;
private javax.swing.JMenuItem ListarPedidos;
private javax.swing.JMenuBar Menu;
private javax.swing.JMenuItem MostrarClientes;
private javax.swing.JMenuItem MostrarTodos;
private javax.swing.JMenu Pedidos;
private javax.swing.JMenu Produtos;
private javax.swing.JMenuItem Sair;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration//GEN-END:variables
}
|
package com.cmp404.pharmacymanagement.repository;
import com.cmp404.pharmacymanagement.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ItemRepository extends JpaRepository<Item, Long> {
//List<Item> findByPharmacy(Pharmacy pharmacy, Sort sort);
List<Item> findItemsByPharmacyId(Long pharmacyId);
}
|
package equivalencyandcloning;
import java.util.Arrays;
public class ArrayEquivalencyTest {
public static void main(String[] args) {
//using == operator
System.out.println("Using == operator");
int[] arr1 = new int[5]; // each element is initialized to 0
int[] arr2 = new int[5]; // each element is initialized to 0
System.out.println(arr1 == arr2); // returns false
//using equals method of Object class
System.out.println("Using equals method of Object class");
int[] array1 = new int[5]; // each element is initialized to 0
int[] array2 = new int[5]; // each element is initialized to 0
System.out.println(array1.equals(array2)); // returns false
//using equals method of Arrays class
System.out.println("Using equals method of Arrays class");
int[] array3 = new int[5]; // each element is initialized to 0
int[] array4 = new int[5]; // each element is initialized to 0
System.out.println(Arrays.equals(array3, array4)); // returns true
//testing two dimensional arrays
int[][] a = { {1,5}, {2,6} };
int[][] b = { {1,5}, {2,6} };
//shallow comparison with two dim arrays
System.out.println("Shallow comparison with two dim arrays");
if (Arrays.equals(a, b) || a == b)
System.out.println("Arrays are equal");
else
System.out.println("Arrays ore not equal.");
//deep comparison with two dim arrays
System.out.println("Deep comparison with two dim arrays");
if (Arrays.deepEquals(a, b) )
System.out.println("Arrays are equal");
else
System.out.println("Arrays ore not equal.");
}
}
|
package pl.finsys.setterExample.impl;
import pl.finsys.setterExample.IOutputGenerator;
public class CsvOutputGenerator implements IOutputGenerator {
public void generateOutput() {
System.out.println("This is Csv Output Generator");
}
}
|
package LeetCode;
import NiuKe.patrent;
public class son extends patrent {
public static void main(String[] args) {
son son1 =new son();
System.out.println(son1);
}
}
|
package utility.model.SchemaParser.utility;
import static utility.model.SchemaParser.constants.Constants.NOT_NULL_STRING;
import static utility.model.SchemaParser.constants.Constants.NUMBER;
import static utility.model.SchemaParser.constants.Constants.N_VARCHAR;
import java.util.List;
import java.util.Objects;
import utility.model.SchemaParser.exception.FileValidatorException;
import utility.model.SchemaParser.model.Row;
import utility.model.SchemaParser.model.entity.Table;
import utility.model.SchemaParser.enums.RestrictionEnum;
public class SchemaValidator {
public static void validateSchemaTypeValue(Table objectFromSchemaFile, List<Row> rows) {
for (int i = 0; i < rows.size(); i++) {
for (int j = 0, k = 0; j < rows.get(i).columns.size() && k < objectFromSchemaFile.columns.size(); j++, k++) {
if ((objectFromSchemaFile.columns.get(k).name).equalsIgnoreCase(rows.get(0).columns.get(j).name.trim())) {
String type = objectFromSchemaFile.columns.get(k).type.name();
List<RestrictionEnum> rectrictions = objectFromSchemaFile.columns.get(k).rectrictions;
for (RestrictionEnum s : rectrictions) {
String name1 = s.name();
if (name1.equalsIgnoreCase(NOT_NULL_STRING)) {
String value = rows.get(i).columns.get(j).value;
if (Objects.nonNull(value)) {
continue;
} else {
throw new NullPointerException("null");
}
}
}
String value = rows.get(i).columns.get(j).value;
Integer rowType = null;
try {
if (type.equalsIgnoreCase(NUMBER)) {
int i1 = Integer.parseInt(value);
continue;
} else if (type.equalsIgnoreCase(N_VARCHAR)) {
if ("String".equalsIgnoreCase(value.getClass().getSimpleName())) {
continue;
}
}
} catch (Exception e) {
System.out.println("Record has error at line " + (i + 1));
throw new FileValidatorException(e.getMessage());
}
}
}
}
}
}
|
package Dao;
import java.sql.SQLException;
import model.Catalogo;
public interface IDao extends ICrud {
public boolean crear(Catalogo catalogo) throws SQLException;
boolean actualizar(Catalogo catalogo);
}
|
package br.com.home.listeners;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
@WebListener
public class MeuSessionActivationListener implements HttpSessionActivationListener {
@Override
public void sessionWillPassivate(HttpSessionEvent httpSessionEvent) {
}
@Override
public void sessionDidActivate(HttpSessionEvent httpSessionEvent) {
}
}
|
package sample;
import ch.heigvd.iict.ser.imdb.models.DataForMedia;
import com.google.gson.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.text.Text;
import java.rmi.RemoteException;
public class Controller {
/**
* Membres privés
*/
ControlleurConnexion connexionToAdmin = null;
private boolean isStillconnected = false;
// Objets pour l'interface
public Label connexionStatus;
public Label jsonDiplay;
public Button verifConnexion;
public Button mediaRecup;
public TreeView treeView;
public ScrollPane scrollPane;
/**
* initialisation de la connexionToAdmin apres création de la fenêtre
*/
@FXML
public void initialize(){
init();
mediaRecup.setStyle("-fx-background-color: red"); // Le rouge indique que la connexion n'est pas encore active
}
/**
* Récupération des données depuis Plex Admin via l'objet "connexionToAdmin" auquel on envoie le message
* getProjections()
* @param actionEvent
* @throws RemoteException
*/
public void getProjectionsFromPlexAdmin(ActionEvent actionEvent) throws RemoteException {
DataForMedia d = connexionToAdmin.getProjections();
String jsonData = d.getJsonData();
JsonObject obj = new JsonParser().parse(jsonData).getAsJsonObject();
String str = "Récupération des données:\n";
// Affichage des données dans au format Json
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
str+= json;
// Utilisation d'une vue en arbre via TreeView
Text text = new Text(str);
scrollPane.setContent(text);
createTreeView(obj);
}
/**
* Regroupe les éléments à la racine "PlexMedia" de l'arbre
* @param obj
*/
public void createTreeView(JsonObject obj){
TreeItem<String> root = new TreeItem<>("PlexMedia");
treeView.setRoot(root);
makeBranch("formatDate: " + obj.get("formatDate").toString(), root);
makeBranch("formatHeure: " + obj.get("formatHeure").toString(), root);
projectionBranches(obj.get("projections").getAsJsonArray(), root);
}
/**
* Ajoute les projections à l'arbre TreeView
* @param projections
* @param parent
* @return
*/
private TreeItem<String> projectionBranches(JsonArray projections, TreeItem<String> parent) {
TreeItem<String> proj = new TreeItem<>("projections");
TreeItem<String> film = null;
for (int i = 0; i < projections.size(); i++){
film = new TreeItem<>("projection N°: " + i);
makeBranch("Salle: " + projections.get(i).getAsJsonObject().get("salle").toString(), film);
makeBranch("Date: " + projections.get(i).getAsJsonObject().get("date").toString(), film);
makeBranch("Heure: " + projections.get(i).getAsJsonObject().get("heure").toString(), film);
makeFilm(projections.get(i).getAsJsonObject().get("film").getAsJsonObject(), film);
proj.getChildren().addAll(film);
}
parent.getChildren().add(proj);
return proj;
}
/**
* Ajoute le film lié à la projection, puis ajoute le tout à l'arbre
* @param obj
* @param parent
* @return
*/
public TreeItem<String> makeFilm(JsonObject obj, TreeItem<String> parent){
TreeItem<String> item = new TreeItem<>("Film: " + obj.getAsJsonObject().get("titre").toString());
item.setExpanded(false);
makeBranch("Duree: " + obj.get("duree").toString(),item);
makeActeurs(obj.get("acteurs").getAsJsonArray(), item);
parent.getChildren().add(item);
return item;
}
/**
* Ajoute les acteurs au film concerné, puis ajoute le tout à l'arbre
* @param array
* @param parent
* @return
*/
public TreeItem<String> makeActeurs(JsonArray array, TreeItem<String> parent){
TreeItem<String> item = new TreeItem<>("Liste des acteurs:");
item.setExpanded(false);
TreeItem<String> acteurs = null;
for (int i = 0; i < array.size(); i++){
acteurs = new TreeItem<>("Acteur n° " + i);
makeBranch("nom: " + array.get(i).getAsJsonObject().get("nom").toString(), acteurs);
makeBranch("naissance: " + array.get(i).getAsJsonObject().get("dateNaissance").toString(), acteurs);
makeBranch("role: " + array.get(i).getAsJsonObject().get("role").getAsJsonObject().get("personnage").toString(), acteurs);
item.getChildren().add(acteurs);
}
parent.getChildren().add(item);
return item;
}
/**
* Génère une branche pour l'arbre TreeView
* @param title
* @param parent
* @return
*/
public TreeItem<String> makeBranch(String title, TreeItem<String> parent){
TreeItem<String> item = new TreeItem<>(title);
item.setExpanded(false);
parent.getChildren().add(item);
return item;
}
/**
* Contrôle la connexion au serveur PlexAdmin
* @param actionEvent
*/
public void checkConnexionToPlexAdmin(ActionEvent actionEvent) {
if(isStillconnected){
connexionStatus.setText("Connexion à Plex Admin établie");
}else{
connexionStatus.setText("Connexion interompue vers Plex Admin");
// TODO ajouter un bouton pour relancer la connexionToAdmin
}
}
/**
* Appel le contrôleur de connexion
*/
public void init(){
try {
connexionToAdmin = new ControlleurConnexion(mediaRecup);
}catch (RemoteException e){
connexionStatus.setText("Erreur lors de la connexionToAdmin au serveur Plex Admin");
}
if (connexionToAdmin.getIsStillconnected()){
isStillconnected = true;
connexionStatus.setText("Connecté avec succès au serveur Plex Admin");
}
}
}
|
public class Special {
public int getFee(int feeType) {
switch (feeType) {
//River 200
//Electricity 150
//Water 150
//Hotel 150
//Conservation fee 200
case 1: return 200;
case 2: return 150;
case 3: return 150;
case 4: return 200;
case 5: return 200;
default: return 0;
}
}
//Use the method below as execute(player, getFee(3))
public void execute(Player player, int amount) {
player.deductMaterials(amount);
}
}
|
package com.smalaca.bank.infrastructure.events.eventsregistry;
import com.smalaca.bank.domain.account.MoneyTransferred;
import com.smalaca.bank.domain.eventsregistry.EventsRegistry;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component
public class SpringEventsRegistry implements EventsRegistry {
private final ApplicationEventPublisher applicationEventPublisher;
public SpringEventsRegistry(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@Override
public void publish(MoneyTransferred moneyTransferred) {
applicationEventPublisher.publishEvent(moneyTransferred);
}
}
|
/**
* class for the testing
*/
package fl.sabal.source.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import fl.sabal.source.interfacePC.Codes.DataBases.MySQL;
/**
* @author FL-AndruAnnohomy
*
*/
public class testingCode {
/**
*
*/
public testingCode() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MySQL mysql = new MySQL("localhost", "3306", "SOFTWARE_LABORATORY_MANAGER_JOURNALS", "root", "201220155");
try {
mysql.openConnection();
System.out.println("Conexion exitosa");
// ResultSet res = mysql.querySQL("CALL
// insertstudent('DANlL','DASN','DAN','DASN','Drrr','DlD','D');");
ResultSet res = mysql.callSQL("CALL selectcourse('MIERCOLES', 8);");
res.next();
System.out.println(res.getString(1) + "#" + res.getInt(2) + "#" + res.getInt(3) + "#" + res.getString(4)
+ "#" + res.getString(5) + "#" + res.getString(6));
int x = mysql.dmlSQL("CALL selectaccessadmin('ADMIN', '25091992');");
System.out.println(x);
x = mysql.dmlSQL("UPDATE tblcareer SET Name = 'cambio' WHERE idCareer = 1;");
System.out.println(x);
x = mysql.dmlSQL("DELETE FROM tblcareer WHERE idCareer > 5;");
System.out.println(x);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Sin conexion");
}
}
}
|
package com.vilio.ppms.dao.common;
import com.vilio.ppms.pojo.common.RouteTotalLog;
public interface RouteTotalLogMapper {
int deleteByPrimaryKey(Long id);
int insert(RouteTotalLog record);
int insertSelective(RouteTotalLog record);
RouteTotalLog selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(RouteTotalLog record);
int updateByPrimaryKey(RouteTotalLog record);
}
|
package project.dbms.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import project.dbms.entity.ArrayProbe;
import project.dbms.entity.Chromosome;
import project.dbms.entity.ClinicalSample;
import project.dbms.entity.Experiment;
import project.dbms.entity.GeneSequence;
import project.dbms.entity.MRNAExpression;
import project.dbms.entity.MeasurementUnit;
import project.dbms.entity.Organism;
import project.dbms.repository.ArrayProbeRepository;
import project.dbms.repository.ChromosomeRepository;
import project.dbms.repository.ClinicalSampleRepository;
import project.dbms.repository.ExperimentRepository;
import project.dbms.repository.GeneSequenceRepository;
import project.dbms.repository.MRNAExpressionRepository;
import project.dbms.repository.MeasurementUnitRepository;
import project.dbms.repository.OrganismRepository;
import project.dbms.service.ProjectService;
import project.dbms.vo.ArrayProbeVO;
import project.dbms.vo.ChromosomeVO;
import project.dbms.vo.ClinicalSampleVO;
import project.dbms.vo.ExperimentVO;
import project.dbms.vo.GeneSequenceVO;
import project.dbms.vo.MRNAExpressionVO;
import project.dbms.vo.MeasurementUnitVO;
import project.dbms.vo.OrganismVO;
@Service("projectService")
public class ProjectServiceImpl implements ProjectService {
private static Logger log = Logger.getLogger(ProjectServiceImpl.class);
@Autowired
private OrganismRepository organismRepo;
@Autowired
private ExperimentRepository experimentRepo;
@Autowired
private ClinicalSampleRepository clinicalSampleRepo;
@Autowired
private MeasurementUnitRepository measurementUnitRepo;
@Autowired
private ChromosomeRepository chromosomeRepository;
@Autowired
private GeneSequenceRepository geneSequenceRepository;
@Autowired
private ArrayProbeRepository arrayProbeRepository;
@Autowired
private MRNAExpressionRepository mrnaExpressionRepository;
@Override
public void createOrganism(OrganismVO organismVO) {
Organism organism = new Organism();
organism.setSpecies(organismVO.getSpecies());
organism.setScientificName(organismVO.getScientificName());
organism.setGenus(organismVO.getGenus());
organism.setCellType(organismVO.getCellType());
organism.setRegisteredDate(formatDate(new Date()));
organismRepo.save(organism);
}
public static String formatDate(Date date) {
String pattern = "dd-MMM-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.format(date);
}
@Override
public void createChromosme(ChromosomeVO vo) {
Chromosome chromosome = new Chromosome();
chromosome.setChromosomeNumber(vo.getChromosomeNumber());
chromosome.setTotalPairs(vo.getTotalPairs());
chromosome.setNoOfGenes(vo.getNoOfGenes());
Organism organism = organismRepo.findOne(vo.getOrganismId());
chromosome.setOrganism(organism);
chromosomeRepository.save(chromosome);
}
@Override
public void createGene(GeneSequenceVO vo) {
GeneSequence entity = new GeneSequence();
entity.setSequence(vo.getSequence());
Chromosome chromosome = chromosomeRepository.findOne(vo.getChromosomeId());
entity.setChromosome(chromosome);
geneSequenceRepository.save(entity);
}
@Override
public void createArrayProbe(ArrayProbeVO vo) {
ArrayProbe entity = new ArrayProbe();
entity.setArrayProbe(vo.getArrayProbe());
GeneSequence gene = geneSequenceRepository.findOne(vo.getGeneSequenceId());
entity.setGeneSequence(gene);
arrayProbeRepository.save(entity);
}
@Override
public void createMRNA(MRNAExpressionVO vo) {
MRNAExpression entity = new MRNAExpression();
entity.setExpression(vo.getExpression());
ArrayProbe array = arrayProbeRepository.findOne(vo.getArrayProbeId());
entity.setArrayProbe(array);
Experiment experiment = experimentRepo.findOne(vo.getExperimentId());
entity.setExperiment(experiment);
ClinicalSample sample = clinicalSampleRepo.findOne(vo.getClinicalSampleId());
entity.setClinicalSample(sample);
MeasurementUnit unit = measurementUnitRepo.findOne(vo.getMeasurementUnitId());
entity.setMeasurementUnit(unit);
mrnaExpressionRepository.save(entity);
}
@Override
public OrganismVO getOrganism(int organismId) {
Organism organism = organismRepo.findOne(organismId);
OrganismVO organismVO = new OrganismVO();
organismVO.setSpecies(organism.getSpecies());
organismVO.setScientificName(organism.getScientificName());
organismVO.setGenus(organism.getGenus());
organismVO.setCellType(organism.getCellType());
organismVO.setId(organism.getId());
int chromosomeCounter = 0;
for (Chromosome chromosome : organism.getChromosomes()) {
ChromosomeVO chromosomeVO = new ChromosomeVO();
chromosomeVO.setChromosomeNumber(chromosome.getChromosomeNumber());
chromosomeVO.setTotalPairs(chromosome.getTotalPairs());
chromosomeVO.setNoOfGenes(chromosome.getNoOfGenes());
chromosomeVO.setId(chromosome.getId());
chromosomeCounter = chromosomeCounter + 1;
System.out.println(chromosomeCounter);
chromosomeVO.setCounter(chromosomeCounter);
organismVO.getChromosomes().add(chromosomeVO);
int geneCounter = 0;
for (GeneSequence geneSequence : chromosome.getGeneSequences()) {
GeneSequenceVO geneSequenceVO = new GeneSequenceVO();
geneSequenceVO.setSequence(geneSequence.getSequence());
geneSequenceVO.setId(geneSequence.getId());
geneCounter = geneCounter + 1;
geneSequenceVO.setCounter(geneCounter);
chromosomeVO.getGeneSequences().add(geneSequenceVO);
int arrayCounter = 0;
for (ArrayProbe arrayProbe : geneSequence.getArrayProbes()) {
ArrayProbeVO arrayProbeVO = new ArrayProbeVO();
arrayProbeVO.setArrayProbe(arrayProbe.getArrayProbe());
arrayProbeVO.setId(arrayProbe.getId());
arrayCounter = arrayCounter + 1;
arrayProbeVO.setCounter(arrayCounter);
geneSequenceVO.getArrayProbes().add(arrayProbeVO);
int mrnaCounter = 0;
for (MRNAExpression mRNAExpression : arrayProbe.getmRNAExpression()) {
MRNAExpressionVO mRNAExpressionVO = new MRNAExpressionVO();
mRNAExpressionVO.setExpression(mRNAExpression.getExpression());
mrnaCounter = mrnaCounter + 1;
mRNAExpressionVO.setCounter(mrnaCounter);
mRNAExpressionVO.setId(mRNAExpression.getId());
if (mRNAExpression.getExperiment() != null) {
mRNAExpressionVO.setExperimentVO(new ExperimentVO(mRNAExpression.getExperiment().getId(),
mRNAExpression.getExperiment().getName()));
}
if (mRNAExpression.getClinicalSample() != null) {
mRNAExpressionVO.setClinicalSampleVO(
new ClinicalSampleVO(mRNAExpression.getClinicalSample().getId(),
mRNAExpression.getClinicalSample().getSampleName()));
}
if (mRNAExpression.getMeasurementUnit() != null) {
mRNAExpressionVO.setMeasurementUnitVO(
new MeasurementUnitVO(mRNAExpression.getMeasurementUnit().getId(),
mRNAExpression.getMeasurementUnit().getName()));
}
arrayProbeVO.getmRNAExpression().add(mRNAExpressionVO);
Collections.sort(arrayProbeVO.getmRNAExpression());
}
Collections.sort(geneSequenceVO.getArrayProbes());
}
Collections.sort(chromosomeVO.getGeneSequences());
}
}
Collections.sort(organismVO.getChromosomes());
return organismVO;
}
@Override
public List<OrganismVO> getOrganisms() {
List<OrganismVO> organismVOList = new ArrayList<OrganismVO>();
List<Organism> organisms = (List<Organism>) organismRepo.findAll();
for (Organism organism : organisms) {
OrganismVO organismVO = new OrganismVO();
organismVOList.add(organismVO);
organismVO.setSpecies(organism.getSpecies());
organismVO.setScientificName(organism.getScientificName());
organismVO.setGenus(organism.getGenus());
organismVO.setCellType(organism.getCellType());
organismVO.setId(organism.getId());
for (Chromosome chromosome : organism.getChromosomes()) {
ChromosomeVO chromosomeVO = new ChromosomeVO();
chromosomeVO.setChromosomeNumber(chromosome.getChromosomeNumber());
chromosomeVO.setTotalPairs(chromosome.getTotalPairs());
chromosomeVO.setNoOfGenes(chromosome.getNoOfGenes());
chromosomeVO.setId(chromosome.getId());
organismVO.getChromosomes().add(chromosomeVO);
for (GeneSequence geneSequence : chromosome.getGeneSequences()) {
GeneSequenceVO geneSequenceVO = new GeneSequenceVO();
geneSequenceVO.setSequence(geneSequence.getSequence());
geneSequenceVO.setId(geneSequence.getId());
chromosomeVO.getGeneSequences().add(geneSequenceVO);
for (ArrayProbe arrayProbe : geneSequence.getArrayProbes()) {
ArrayProbeVO arrayProbeVO = new ArrayProbeVO();
arrayProbeVO.setArrayProbe(arrayProbe.getArrayProbe());
arrayProbeVO.setId(arrayProbe.getId());
geneSequenceVO.getArrayProbes().add(arrayProbeVO);
for (MRNAExpression mRNAExpression : arrayProbe.getmRNAExpression()) {
MRNAExpressionVO mRNAExpressionVO = new MRNAExpressionVO();
mRNAExpressionVO.setExpression(mRNAExpression.getExpression());
mRNAExpressionVO.setId(mRNAExpression.getId());
if (mRNAExpression.getExperiment() != null) {
mRNAExpressionVO
.setExperimentVO(new ExperimentVO(mRNAExpression.getExperiment().getId(),
mRNAExpression.getExperiment().getName()));
}
if (mRNAExpression.getClinicalSample() != null) {
mRNAExpressionVO.setClinicalSampleVO(
new ClinicalSampleVO(mRNAExpression.getClinicalSample().getId(),
mRNAExpression.getClinicalSample().getSampleName()));
}
if (mRNAExpression.getMeasurementUnit() != null) {
mRNAExpressionVO.setMeasurementUnitVO(
new MeasurementUnitVO(mRNAExpression.getMeasurementUnit().getId(),
mRNAExpression.getMeasurementUnit().getName()));
}
arrayProbeVO.getmRNAExpression().add(mRNAExpressionVO);
}
}
}
}
}
return organismVOList;
}
@Override
public void createExperiment(ExperimentVO experimentVO) {
Experiment experiment = experimentRepo.findOne(experimentVO.getId());
if (experiment == null) {
experiment = new Experiment();
}
experiment.setName(experimentVO.getName());
experimentRepo.save(experiment);
}
@Override
public List<ExperimentVO> getExperiment() {
List<ExperimentVO> list = new ArrayList<ExperimentVO>();
List<Experiment> expList = (List<Experiment>) experimentRepo.findAll();
for (Experiment experiment : expList) {
ExperimentVO vo = new ExperimentVO(experiment.getId(), experiment.getName());
list.add(vo);
}
return list;
}
@Override
public void createClinicalSample(ClinicalSampleVO clinicalSampleVO) {
ClinicalSample sample = clinicalSampleRepo.findOne(clinicalSampleVO.getId());
if (sample == null) {
sample = new ClinicalSample();
}
sample.setSampleName(clinicalSampleVO.getSampleName());
clinicalSampleRepo.save(sample);
}
@Override
public List<ClinicalSampleVO> getClinicalSample() {
List<ClinicalSampleVO> list = new ArrayList<ClinicalSampleVO>();
List<ClinicalSample> sampleList = (List<ClinicalSample>) clinicalSampleRepo.findAll();
for (ClinicalSample sample : sampleList) {
ClinicalSampleVO vo = new ClinicalSampleVO(sample.getId(), sample.getSampleName());
list.add(vo);
}
return list;
}
@Override
public void createMeasurementUnit(MeasurementUnitVO measurementUnitVO) {
MeasurementUnit unit = measurementUnitRepo.findOne(measurementUnitVO.getId());
if (unit == null) {
unit = new MeasurementUnit();
}
unit.setName(measurementUnitVO.getName());
measurementUnitRepo.save(unit);
}
@Override
public List<MeasurementUnitVO> getMeasurementUnit() {
List<MeasurementUnitVO> list = new ArrayList<MeasurementUnitVO>();
List<MeasurementUnit> unitList = (List<MeasurementUnit>) measurementUnitRepo.findAll();
for (MeasurementUnit unit : unitList) {
MeasurementUnitVO vo = new MeasurementUnitVO(unit.getId(), unit.getName());
list.add(vo);
}
return list;
}
@Override
public int getExperimentCount() {
List<Experiment> list = (List<Experiment>) experimentRepo.findAll();
return list.size();
}
@Override
public int getSampleCount() {
List<ClinicalSample> list = (List<ClinicalSample>) clinicalSampleRepo.findAll();
return list.size();
}
@Override
public int getOrganismCount() {
List<Organism> list = (List<Organism>) organismRepo.findAll();
return list.size();
}
@Override
public String getLatestOrganismRegisteredName() {
if (organismRepo.findLastestOrganism().isEmpty()) {
return "NA";
} else {
return organismRepo.findLastestOrganism().get(0).getScientificName();
}
}
@Override
public void delete() {
mrnaExpressionRepository.deleteAll();
arrayProbeRepository.deleteAll();
geneSequenceRepository.deleteAll();
chromosomeRepository.deleteAll();
organismRepo.deleteAll();
}
@Override
public void deleteMeasurementUnit(int id) {
measurementUnitRepo.delete(id);
}
@Override
public void deleteExperiment(int id) {
experimentRepo.delete(id);
}
@Override
public void deleteClinicalSample(int id) {
clinicalSampleRepo.delete(id);
}
@Override
public void deleteOrganism(int id) {
Organism organism = organismRepo.findOne(id);
Set<Chromosome> chromosomes = organism.getChromosomes();
List<GeneSequence> geneSequences = new ArrayList<GeneSequence>();
for (Chromosome chromosome : chromosomes) {
geneSequences.addAll(chromosome.getGeneSequences());
}
List<ArrayProbe> arrayProbes = new ArrayList<ArrayProbe>();
for (GeneSequence geneSequence : geneSequences) {
arrayProbes.addAll(geneSequence.getArrayProbes());
}
List<MRNAExpression> mRNAExpressions = new ArrayList<MRNAExpression>();
for (ArrayProbe arrayProbe : arrayProbes) {
mRNAExpressions.addAll(arrayProbe.getmRNAExpression());
}
organismRepo.delete(organism);
chromosomeRepository.delete(chromosomes);
geneSequenceRepository.delete(geneSequences);
arrayProbeRepository.delete(arrayProbes);
mrnaExpressionRepository.delete(mRNAExpressions);
}
@Override
public ExperimentVO getExperiment(int id) {
Experiment exp = experimentRepo.findOne(id);
ExperimentVO expVO = new ExperimentVO(exp.getId(), exp.getName());
return expVO;
}
@Override
public MeasurementUnitVO getMeasurementUnit(int id) {
MeasurementUnit unit = measurementUnitRepo.findOne(id);
MeasurementUnitVO vo = new MeasurementUnitVO(unit.getId(), unit.getName());
return vo;
}
@Override
public ClinicalSampleVO getClinicalSample(int id) {
ClinicalSample sample = clinicalSampleRepo.findOne(id);
ClinicalSampleVO vo = new ClinicalSampleVO(sample.getId(), sample.getSampleName());
return vo;
}
@Override
public List<ChromosomeVO> getChromosomeList() {
List<ChromosomeVO> list = new ArrayList<ChromosomeVO>();
List<Chromosome> dbList = (List<Chromosome>) chromosomeRepository.findAll();
for (Chromosome entity : dbList) {
ChromosomeVO vo = new ChromosomeVO();
vo.setChromosomeNumber(entity.getChromosomeNumber());
vo.setId(entity.getId());
list.add(vo);
}
return list;
}
@Override
public List<GeneSequenceVO> getGeneList() {
List<GeneSequenceVO> list = new ArrayList<GeneSequenceVO>();
List<GeneSequence> dbList = (List<GeneSequence>) geneSequenceRepository.findAll();
for (GeneSequence entity : dbList) {
GeneSequenceVO vo = new GeneSequenceVO();
vo.setSequence(entity.getSequence());
vo.setId(entity.getId());
list.add(vo);
}
return list;
}
@Override
public List<ArrayProbeVO> getArrayList() {
List<ArrayProbeVO> list = new ArrayList<ArrayProbeVO>();
List<ArrayProbe> dbList = (List<ArrayProbe>) arrayProbeRepository.findAll();
for (ArrayProbe entity : dbList) {
ArrayProbeVO vo = new ArrayProbeVO();
vo.setArrayProbe(entity.getArrayProbe());
vo.setId(entity.getId());
list.add(vo);
}
return list;
}
@Override
public List<List<Map<Object, Object>>> getCanvasjsChartData() {
Map<Object, Object> map = null;
List<List<Map<Object, Object>>> list = new ArrayList<List<Map<Object, Object>>>();
List<Map<Object, Object>> dataPoints1 = new ArrayList<Map<Object, Object>>();
List<String> species = organismRepo.findAllOrganismSpecies();
for (String string : species) {
map = new HashMap<Object, Object>();
map.put("name", string);
map.put("y", 100 * organismRepo.countOrganismOfSpecificSpecies(string) / organismRepo.countAllOrganism());
dataPoints1.add(map);
}
return list;
}
@Override
public List<List<Map<Object, Object>>> getCanvasjsBarChartData() {
Map<Object, Object> map = null;
List<List<Map<Object, Object>>> list = new ArrayList<List<Map<Object, Object>>>();
List<Map<Object, Object>> dataPoints1 = new ArrayList<Map<Object, Object>>();
List<Organism> allOrganism = (List<Organism>) organismRepo.findAll();
Map<String, Integer> dateWiseCountMap = new HashMap<String, Integer>();
for (Organism organism : allOrganism) {
if (!dateWiseCountMap.containsKey(organism.getRegisteredDate())) {
dateWiseCountMap.put(organism.getRegisteredDate(), 0);
}
dateWiseCountMap.put(organism.getRegisteredDate(), dateWiseCountMap.get(organism.getRegisteredDate()) + 1);
}
for (Map.Entry<String, Integer> entry : dateWiseCountMap.entrySet()) {
map = new HashMap<Object, Object>();
map.put("x", parseDate(entry.getKey()).getTime());
map.put("y", entry.getValue());
dataPoints1.add(map);
}
list.add(dataPoints1);
return list;
}
private Date parseDate(String registeredDate) {
Date date = null;
try {
date = new SimpleDateFormat("dd-MMM-yyyy").parse(registeredDate);
} catch (ParseException e) {
log.error("Error while parsing date.");
}
return date;
}
@Override
public Map<String, Integer> getBarChartData() {
List<Organism> allOrganism = (List<Organism>) organismRepo.findAll();
Map<String, Integer> dateWiseCountMap = new HashMap<String, Integer>();
for (Organism organism : allOrganism) {
if (!dateWiseCountMap.containsKey(organism.getRegisteredDate())) {
dateWiseCountMap.put(organism.getRegisteredDate(), 0);
}
dateWiseCountMap.put(organism.getRegisteredDate(), dateWiseCountMap.get(organism.getRegisteredDate()) + 1);
}
return dateWiseCountMap;
}
@Override
public Map<String, Integer> getPieChartData() {
List<String> species = organismRepo.findAllOrganismSpecies();
Map<String, Integer> pieChartMap = new HashMap<String, Integer>();
for (String string : species) {
if (!pieChartMap.containsKey(string)) {
pieChartMap.put(string, organismRepo.countOrganismOfSpecificSpecies(string));
}
}
return pieChartMap;
}
}
|
package graft;
public class TestGraft {
}
|
import java.util.Scanner;
public class exer7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Digite o primeiro número inteiro:");
int pri = input.nextInt();
System.out.println("Digite o segundo número inteiro:");
int seg = input.nextInt();
pri++;
for(int i = pri; i < seg; i++) {
System.out.println(i + " ");
}
input.close();
}
}
|
package com.verbovskiy.finalproject.controller.command.impl;
import com.verbovskiy.finalproject.controller.command.ActionCommand;
import com.verbovskiy.finalproject.controller.command.PageType;
import com.verbovskiy.finalproject.controller.command.RequestParameter;
import com.verbovskiy.finalproject.exception.ServiceException;
import com.verbovskiy.finalproject.model.service.OrderService;
import com.verbovskiy.finalproject.model.service.impl.OrderServiceImpl;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
/**
* The type buy car command.
*
* @author Verbovskiy Sergei
* @version 1.0
*/
public class BuyCarCommand implements ActionCommand {
private final Logger logger = LogManager.getLogger(BuyCarCommand.class);
@Override
public String execute(HttpServletRequest request) {
HttpSession session = request.getSession();
long carId = Long.parseLong(request.getParameter(RequestParameter.CAR_ID));
String userEmail = (String) session.getAttribute(RequestParameter.EMAIL);
LocalDate date = LocalDate.now();
boolean inProcessing = true;
String page = PageType.ERROR.getPath();
try {
OrderService orderService = new OrderServiceImpl();
orderService.add(userEmail, carId, date, inProcessing);
request.setAttribute(RequestParameter.IS_BOUGHT, true);
page = PageType.BUY_CAR.getPath();
} catch (ServiceException e) {
logger.log(Level.ERROR, e);
}
return page;
}
}
|
package com.InstanTecnic.demo.Mensajeria.Repositorio;
import java.io.Serializable;
import java.util.List;
import com.InstanTecnic.demo.Mensajeria.Modelos.Consulta;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ConsultaRepo extends JpaRepository<Consulta, Serializable>{
public abstract List<Consulta> findByTecnicoOrCliente(long tecnico, long cliente);
public abstract List<Consulta> findByAceptada(String aceptada);
}
|
package com.zzlz13.zmusic.utils;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.zzlz13.zlibrary.utils.LUtil;
import com.zzlz13.zmusic.Constants;
import com.zzlz13.zmusic.bean.Song;
import com.zzlz13.zmusic.greendao.DaoMaster;
import com.zzlz13.zmusic.greendao.DaoSession;
import com.zzlz13.zmusic.greendao.PlaySong;
import com.zzlz13.zmusic.greendao.PlaySongDao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import de.greenrobot.dao.query.QueryBuilder;
/**
* Created by hjr on 2016/5/18.
*/
public class PlayListHelper {
private static List<PlaySong> list;
public static void clearPlayList(Context context){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
playSongDao.deleteAll();
}
public static boolean equalPlayList(Context context,int t, String albumName){
int type = SpUtils.getInt(context, Constants.PLAY_LIST_TYPE, 0);
String subName = SpUtils.getString(context, Constants.PLAYLIST_SUB_NAME, "");
switch (type){
case Constants.PLAYLIST_SONGS:
if (type == t){
return true;
}else{
SpUtils.putInt(context,Constants.PLAY_LIST_TYPE,t);
SpUtils.putString(context,Constants.PLAYLIST_SUB_NAME,"");
return false;
}
case Constants.PLAYLIST_ARTIST:
if (type == t && subName.equals(albumName)){
return true;
}else{
SpUtils.putInt(context,Constants.PLAY_LIST_TYPE,t);
SpUtils.putString(context,Constants.PLAYLIST_SUB_NAME,"");
return false;
}
case Constants.PLAYLIST_LOVE:
if (type == t){
return true;
}else{
SpUtils.putInt(context, Constants.PLAY_LIST_TYPE, t);
SpUtils.putString(context,Constants.PLAYLIST_SUB_NAME,"");
return false;
}
case Constants.PLAYLIST_ALBUM:
if (type == t && subName.equals(albumName)){
return true;
}else{
SpUtils.putInt(context,Constants.PLAY_LIST_TYPE,t);
SpUtils.putString(context,Constants.PLAYLIST_SUB_NAME,albumName);
return false;
}
case Constants.PLAYLIST_RECORD:
break;
case Constants.PLAYLIST_NONE:
SpUtils.putInt(context,Constants.PLAY_LIST_TYPE,t);
SpUtils.putString(context,Constants.PLAYLIST_SUB_NAME,albumName);
return false;
}
SpUtils.putInt(context,Constants.PLAY_LIST_TYPE,t);
SpUtils.putString(context, Constants.PLAYLIST_SUB_NAME, albumName);
return false;
}
public static void savePlayListIfNull(Context context,ArrayList<Song> songs){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
List<PlaySong> list = qb.list();
if (list == null || list.size() == 0){
for (Song song : songs) {
PlaySong entity = new PlaySong();
entity.setSongId(song._id);
entity.setTitle(song.title);
entity.setAlbum(song.album);
entity.setArtist(song.artist);
entity.setCoverPath(song.coverPath);
entity.setMusicPath(song.musicPath);
entity.setDuration(song.duration);
playSongDao.insertOrReplace(entity);
}
}
}
public static void savePlayList(Context context,ArrayList<Song> songs){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
for (Song song : songs) {
PlaySong entity = new PlaySong();
entity.setSongId(song._id);
entity.setTitle(song.title);
entity.setAlbum(song.album);
entity.setArtist(song.artist);
entity.setCoverPath(song.coverPath);
entity.setMusicPath(song.musicPath);
entity.setDuration(song.duration);
playSongDao.insertOrReplace(entity);
}
}
public static void savePlayListBeforeEqual(Context context,ArrayList<Song> songs,int type, String albumName){
if (equalPlayList(context, type, albumName)){
//相同 不处理
return;
}
clearPlayList(context);
LUtil.e("播放列表不一致,更新db");
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
for (Song song : songs) {
PlaySong entity = new PlaySong();
entity.setSongId(song._id);
entity.setTitle(song.title);
entity.setAlbum(song.album);
entity.setArtist(song.artist);
entity.setCoverPath(song.coverPath);
entity.setMusicPath(song.musicPath);
entity.setDuration(song.duration);
playSongDao.insertOrReplace(entity);
}
}
public static PlaySong removeSongById(Context context,String songId){
if (TextUtils.isEmpty(songId)) return null;
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
for (PlaySong playSong : qb.list()) {
if (songId.equals(playSong.getSongId())){
playSongDao.delete(playSong);
return playSong;
}
}
return null;
}
public static PlaySong querySongByMusicPath(Context context, String musicPath){
if (TextUtils.isEmpty(musicPath)) return null;
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
for (PlaySong playSong : qb.list()) {
if (musicPath.equals(playSong.getMusicPath())){
return playSong;
}
}
return null;
}
public static PlaySong queryCurrentByMusicPath(Context context, String musicPath){
if (TextUtils.isEmpty(musicPath)) return null;
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
List<PlaySong> list = qb.list();
for (int i=0; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
return playSong;
}
}
return null;
}
public static PlaySong queryShuffleNextByMusicPath(Context context, String musicPath){
if (TextUtils.isEmpty(musicPath)) return null;
int nextPosition = -1;
if (list == null){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
List<PlaySong> list = qb.list();
Collections.shuffle(list);
for (int i=0; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
if (i+1 < list.size()){
nextPosition = i+1;
}
break;
}
}
return nextPosition == -1 ? null : list.get(nextPosition);
}else{
for (int i=0; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
if (i+1 < list.size()){
nextPosition = i+1;
}
break;
}
}
return nextPosition == -1 ? list.get(list.size()) : list.get(nextPosition);
}
}
public static PlaySong queryNextByMusicPath(Context context, String musicPath){
if (TextUtils.isEmpty(musicPath)) return null;
int nextPosition = -1;
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
List<PlaySong> list = qb.list();
for (int i=0; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
if (i+1 < list.size()){
nextPosition = i+1;
}
break;
}
}
return nextPosition == -1 ? null : list.get(nextPosition);
}
public static PlaySong queryPreviousByMusicPath(Context context, String musicPath){
if (TextUtils.isEmpty(musicPath)) return null;
int nextPosition = -1;
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
List<PlaySong> list = qb.list();
for (int i=1; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
nextPosition = i-1;
break;
}
}
return nextPosition == -1 ? null : list.get(nextPosition);
}
public static PlaySong queryShufflePreviousByMusicPath(Context context, String musicPath){
if (TextUtils.isEmpty(musicPath)) return null;
int nextPosition = -1;
if (list == null){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
list = qb.list();
Collections.shuffle(list);
for (int i=1; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
nextPosition = i-1;
break;
}
}
return nextPosition == -1 ? null : list.get(nextPosition);
}else{
for (int i=1; i< list.size(); i++){
PlaySong playSong = list.get(i);
if (musicPath.equals(playSong.getMusicPath())){
nextPosition = i-1;
break;
}
}
return nextPosition == -1 ? list.get(0) : list.get(nextPosition);
}
}
/**
* id is null,return playlist position first item
* @param context
* @param id
* @return
*/
public static PlaySong querySongById(Context context, String id){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
if (qb == null || qb.list() == null || qb.list().size() == 0) return null;
if (TextUtils.isEmpty(id)){
return qb.list().get(0);
}
for (PlaySong playSong : qb.list()) {
if (id.equals(playSong.getSongId())){
return playSong;
}
}
return null;
}
public static List<PlaySong> queryAllSong(Context context){
SQLiteDatabase db = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null).getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
PlaySongDao playSongDao = daoSession.getPlaySongDao();
QueryBuilder<PlaySong> qb = playSongDao.queryBuilder();
return qb.list();
}
}
|
package com.bookingsample.inventory.web;
import com.bookingsample.inventory.data.Room;
import com.bookingsample.inventory.data.RoomCategory;
import com.bookingsample.inventory.data.RoomDTO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Created by davut on 26.03.2017.
*/
@RunWith(MockitoJUnitRunner.class)
public class RoomResourceTest {
@Mock
InventoryService service;
private RoomResource roomResource;
@Before
public void initTest()
{
this.roomResource = new RoomResource(service);
}
@Test
public void shouldUpdateRoom()
{
Room room = new Room(1, new RoomCategory() , "test" , "test");
when(service.getRoom(anyLong())).thenReturn(room);
RoomDTO rdto = new RoomDTO();
roomResource.updateRoom(1 ,rdto );
verify(service).updateRoom(1 , rdto);
}
@Test public void shouldReturnExceptionIfMethodFails()
{
when(service.updateRoom(anyLong() , any())).thenThrow(new RestException(99 , "test"));
ApiResponse resp = roomResource.updateRoom(1, new RoomDTO());
assertThat(resp.getError().errorCode , is(99));
}
@Test public void shouldReturnUndefinedErrorOnRuntimeExceptions()
{
when(service.updateRoom(anyLong() , any())).thenThrow(new RuntimeException());
ApiResponse resp = roomResource.updateRoom(1, new RoomDTO());
assertThat(resp.getError().errorCode , is(RestException.UNEXPECTED_ERROR));
}
@Test public void shouldDeleteGivenRoom()
{
long id = 1;
roomResource.deleteRoom(id);
verify(service).deleteRoom(id);
}
}
|
package com.codecool.car_race;
import java.util.Random;
public class Truck extends Vehicle {
private static int normalSpeed = 100;
private static Random rand = new Random();
public Truck() {
super(normalSpeed);
}
@Override
protected String generateName() {
return Integer.toString(rand.nextInt(1000));
}
@Override
public void prepareForLap(Race race) {
if (race.isThereABrokenTruck()) actualSpeed -= 33;
else actualSpeed = normalSpeed;
}
}
|
package com.accrete.ai.products.api;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.SparkSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
/**
* Created by.
*/
@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
@Autowired
public Environment env;
@Value("${app.name:DD}")
public String appName;
@Value("${spark.home}")
public String sparkHome;
@Value("${master.uri:local}")
public String masterUri;
@Bean
public SparkConf sparkConf() {
SparkConf sparkConf = new SparkConf()
.setAppName(appName)
.setSparkHome(sparkHome)
.setMaster(masterUri)
.set("spark.executor.host", "169.60.169.254") //Public Server IP
.set("spark.executor.cores","2")
.set("spark.executor.instances","3")
.set("spark.executor.memory","2g");
return sparkConf;
}
@Bean
public JavaSparkContext javaSparkContext() {
return new JavaSparkContext(sparkConf());
}
@Bean
public SparkSession sparkSession() {
return SparkSession
.builder()
.sparkContext(javaSparkContext().sc())
.appName(appName)
.getOrCreate();
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
|
// Sun Certified Java Programmer
// Chapter 2, P115
// Object Orientation
public class Tester115 {
public static void main(String[] args) {
}
}
|
package com.ss.android.ugc.aweme.miniapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.f.a;
import android.text.TextUtils;
import com.ss.android.ugc.aweme.miniapp.utils.c;
import com.ss.android.ugc.aweme.miniapp.views.MainProcessProxyActivity;
import com.tt.miniapphost.process.HostProcessBridge;
import com.tt.miniapphost.process.callback.IpcCallback;
import com.tt.miniapphost.process.data.CrossProcessDataEntity;
import com.tt.miniapphost.util.ProcessUtil;
import com.tt.option.w.g;
import java.io.IOException;
import java.util.UUID;
import org.json.JSONObject;
public final class h {
public static void a(Activity paramActivity, com.tt.option.w.h paramh, g paramg) {
if (TextUtils.equals("video", paramh.channel)) {
Intent intent = new Intent((Context)paramActivity, MainProcessProxyActivity.class);
a<String, String> a = new a();
a.put("schema", paramh.schema);
a.put("appId", paramh.appInfo.appId);
a.put("appTitle", paramh.title);
a.put("appUrl", paramh.queryString);
a.put("cardImage", paramh.imageUrl);
intent.putExtra("micro_app_class", paramActivity.getClass());
a(paramh, intent, a, 2);
intent.putExtra("micro_app_info", c.a(a));
intent.putExtra("translation_type", 3);
String str = UUID.randomUUID().toString();
intent.putExtra("creation_id", str);
intent.putExtra("shoot_way", "mp_record");
a(paramg, intent);
intent.putExtra("proxy_type", 1);
paramActivity.startActivity(intent);
HostProcessBridge.logEvent("shoot", new JSONObject((f.a().a("shoot_way", "mp_record").a("creation_id", str)).a));
}
}
static void a(g paramg, Intent paramIntent) {
ProcessUtil.fillCrossProcessCallbackIntent(paramIntent, new IpcCallback(paramg) {
public final void onIpcCallback(CrossProcessDataEntity param1CrossProcessDataEntity) {
g g1 = this.a;
if (g1 != null) {
if (param1CrossProcessDataEntity == null) {
g1.onFail(null);
return;
}
if (param1CrossProcessDataEntity.getBoolean("proxy_result")) {
this.a.onSuccess(null);
return;
}
this.a.onCancel(null);
}
}
public final void onIpcConnectError() {
this.a.onFail("ipc fail");
}
});
}
static void a(com.tt.option.w.h paramh, Intent paramIntent, a<String, String> parama, int paramInt) {
// Byte code:
// 0: aload_0
// 1: ifnonnull -> 15
// 4: new org/json/JSONObject
// 7: dup
// 8: invokespecial <init> : ()V
// 11: astore_0
// 12: goto -> 48
// 15: aload_0
// 16: getfield extra : Ljava/lang/String;
// 19: invokestatic isEmpty : (Ljava/lang/CharSequence;)Z
// 22: ifeq -> 36
// 25: new org/json/JSONObject
// 28: dup
// 29: invokespecial <init> : ()V
// 32: astore_0
// 33: goto -> 48
// 36: new org/json/JSONObject
// 39: dup
// 40: aload_0
// 41: getfield extra : Ljava/lang/String;
// 44: invokespecial <init> : (Ljava/lang/String;)V
// 47: astore_0
// 48: aload_0
// 49: ldc 'sticker_id'
// 51: invokevirtual optString : (Ljava/lang/String;)Ljava/lang/String;
// 54: astore #4
// 56: aload #4
// 58: invokestatic isEmpty : (Ljava/lang/CharSequence;)Z
// 61: ifne -> 73
// 64: aload_1
// 65: ldc 'sticker_id'
// 67: aload #4
// 69: invokevirtual putExtra : (Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;
// 72: pop
// 73: aload_0
// 74: ldc 'timor_video_source'
// 76: iload_3
// 77: invokevirtual put : (Ljava/lang/String;I)Lorg/json/JSONObject;
// 80: pop
// 81: aload_2
// 82: ldc 'extra'
// 84: aload_0
// 85: invokevirtual toString : ()Ljava/lang/String;
// 88: invokevirtual put : (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
// 91: pop
// 92: return
// 93: astore_0
// 94: return
// Exception table:
// from to target type
// 4 12 93 org/json/JSONException
// 15 33 93 org/json/JSONException
// 36 48 93 org/json/JSONException
// 48 73 93 org/json/JSONException
// 73 92 93 org/json/JSONException
}
static boolean a(Activity paramActivity, String paramString) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(paramString);
mediaPlayer.prepare();
if (mediaPlayer.getDuration() < 3000L) {
MiniAppService.inst().getPopToastDepend().a(paramActivity, paramActivity.getString(2097742069));
return true;
}
} catch (IOException iOException) {}
return false;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\h.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package app.integro.sjbhs.models;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class AnnouncementList {
private String message;
@SerializedName("sjbhs_announcement")
private ArrayList<Announcement> announcementArrayList;
public ArrayList<Announcement> getAnnouncementArrayList() {
return announcementArrayList;
}
public void setAnnouncementArrayList(ArrayList<Announcement> announcementArrayList) {
this.announcementArrayList = announcementArrayList;
}
private String success;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
|
package com.ybg.weixin.domain;
import com.ybg.base.util.SpringContextUtils;
import com.ybg.base.util.SystemConstant;
import com.ybg.weixin.service.WeixinSettingService;
/** 切勿随便更改 此类 */
public class WeixinAppInfo {
public static String getDomain() {
return SystemConstant.getSystemdomain();
}
public static String getMch_id() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getMch_id();
}
public static String getNotify_url() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getNotify_url();
}
public static String getPartnerkey() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getPartnerkey();
}
public static String getSecret() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getSecret();
}
public static String getState() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getState();
}
public static String getScope() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getScope();
}
public static String getAppid() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getAppid();
}
public static String getRedirect_uri() {
WeixinSettingService service = (WeixinSettingService) SpringContextUtils.getBean(WeixinSettingService.class);
return service.getIsUse().getRedirect_uri();
}
}
|
package com.sixmac.service;
import com.sixmac.entity.HostJoin;
import com.sixmac.service.common.ICommonService;
import java.util.List;
/**
* Created by Administrator on 2016/5/25 0025 上午 11:15.
*/
public interface HostJoinService extends ICommonService<HostJoin> {
public List<HostJoin> findByHostRaceId(Long raceId);
}
|
/*
* Copyright (C) 2010-2012, Wan Lee, wan5332@gmail.com
* Source can be obtained from git://github.com/wanclee/datashaper.git
* BSD-style license. Please read license.txt that comes with source files
*/
/**
* Utility for supporting batch operations
*/
package com.psrtoolkit.datashaper.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import com.psrtoolkit.datashaper.exception.DataShaperException;
/**
* Utility for supporting batch operations
*
* @author Wan
*
*/
public class OperationUtil {
private OperationUtil() {
}
public static boolean areBatchUpdatesSupported(Connection conn) {
try {
DatabaseMetaData dbMData = conn.getMetaData();
return dbMData.supportsBatchUpdates();
} catch (SQLException e) {
throw new DataShaperException("Error: failed in calling areBatchUpdatesSupported");
}
}
public static void commit(Connection conn) {
try {
conn.commit();
} catch (Exception ex) {
//ex.printStackTrace();
throw new DataShaperException("Error: failed to commit transaction", ex);
}
}
}
|
package com.tencent.mm.plugin.exdevice.i;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.exdevice.b.c;
import com.tencent.mm.plugin.exdevice.service.m;
import com.tencent.mm.plugin.exdevice.service.p;
import com.tencent.mm.plugin.exdevice.service.u;
import com.tencent.mm.sdk.platformtools.x;
import junit.framework.Assert;
public class a implements c {
private long iyn = -1;
protected c izu = null;
protected d izv = null;
private m izw = null;
public a(c cVar, d dVar) {
this.izu = cVar;
this.izv = dVar;
}
public final void a(d dVar) {
this.izv = dVar;
}
public final boolean b(m mVar) {
if (mVar == null) {
x.e("MicroMsg.exdevice.ExDeviceTask", "dispatcher is null");
return false;
} else if (this.izw != null) {
x.e("MicroMsg.exdevice.ExDeviceTask", "Prev task is still working!!!");
return false;
} else {
x.i("MicroMsg.exdevice.ExDeviceTask", "------startTask begin------cmdReqId = %d, cmdRespId = %d, deviceId = %d", new Object[]{Short.valueOf(this.izu.aGA()), Short.valueOf(this.izu.isC), Long.valueOf(this.izu.hjj)});
m mVar2 = new m(this.izu, this);
long a = mVar.a(mVar2);
if (-1 == a) {
x.e("MicroMsg.exdevice.ExDeviceTask", "dispatcher.startTask Failed!!!");
return false;
}
this.izw = mVar2;
this.iyn = a;
mVar2 = this.izw;
Assert.assertNotNull(mVar2.izR);
l lVar = mVar2.izR;
lVar.izK = false;
lVar.izL = false;
au.Em().cil().postDelayed(lVar.izM, 15000);
return true;
}
}
public final void a(long j, int i, int i2, String str, p pVar) {
int i3 = 1;
x.i("MicroMsg.exdevice.ExDeviceTask", "------onTaskEnd------ taskId = %d, errType = %d, errCode = %d, errMsg = %s, deviceId = %d, reqCmdId = %d, respCmdId = %d", new Object[]{Long.valueOf(j), Integer.valueOf(i), Integer.valueOf(i2), str, Long.valueOf(this.izu.hjj), Short.valueOf(this.izu.aGA()), Short.valueOf(this.izu.isC)});
com.tencent.mm.plugin.exdevice.g.a.l(this.izu.hjj, i == 0 ? 1 : 0);
if (pVar == null || pVar == this.izw) {
if (-1 == i && -2 == i2) {
x.e("MicroMsg.exdevice.ExDeviceTask", "Time Out in local!!!");
}
int i4 = this.izu.isD != null ? this.izu.isD.iwS : 0;
if (-5 == i4 || -3 == i4 || -4 == i4) {
x.w("MicroMsg.exdevice.ExDeviceTask", "ErrorCode = %d, destroy channel(deviceId = %d)", new Object[]{Integer.valueOf(this.izu.isD.iwS), Long.valueOf(this.izu.hjj)});
if (u.aHG().isY == null || !u.aHG().isY.cT(this.izu.hjj)) {
i3 = 0;
}
if (i3 == 0) {
x.e("MicroMsg.exdevice.ExDeviceTask", "stopChannel Failed!!!");
}
}
if (this.izv != null) {
this.izv.a(j, i, i2, str);
}
this.izw = null;
return;
}
x.e("MicroMsg.exdevice.ExDeviceTask", "netCmd != mRemoteTask");
}
}
|
package com.gyb.eduservice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gyb.eduservice.entity.EduChapter;
import com.gyb.eduservice.entity.vo.ChapterVo;
import java.util.List;
public interface EduChapterService extends IService<EduChapter> {
List<ChapterVo> getChapterVideoByCourseId(String courseId);
boolean deleteChapter(String chapterId);
}
|
package com.bw.movie.IView;
import com.bw.movie.mvp.model.bean.RegBean;
/**
* 作者:轻 on 2018/11/14 11:20
* <p>
* 邮箱:379996854@qq.com
*/
public interface IRegView extends IBaseView {
void success(RegBean regBean);
void Error(String msg);
}
|
package com.sudipatcp.hashing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TwoSum {
public ArrayList<Integer> twoSum(final List<Integer> A, int B) {
int finalIndex1 = Integer.MAX_VALUE, finalIndex2 = Integer.MAX_VALUE;
//HashMap<Integer, Integer> map = new HashMap<>();
boolean flag = false;
for(int i = 0; i < A.size(); i++){
if(A.subList(i+1, A.size()).contains(B-A.get(i))){
int index1 = i;
int index2 = A.subList(i+1, A.size()).indexOf(B-A.get(i)) + index1 + 1;
if(index1 < index2){
if(index2 < finalIndex2){
flag = true;
finalIndex2 = index2;
finalIndex1 = index1;
}
}
}
}
if(flag){
ArrayList<Integer> ans = new ArrayList<>();
ans.add(finalIndex1+1);
ans.add(finalIndex2+1);
return ans;
}
return new ArrayList<>();
}
public ArrayList<Integer> twoSum2(final List<Integer> A, int B) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < A.size(); i++)
{
if(!map.containsKey(A.get(i)))
map.put(A.get(i),i);
int b = B - A.get(i);
if(map.containsKey(b) && map.get(b) != i){
ArrayList<Integer> list = new ArrayList<>();
list.add(map.get(b) + 1);
list.add(i + 1);
return list;
}
}
return new ArrayList<>();
}
public static void main(String[] args) {
int arr [] = {1, 1, 1};
int num = 2;
ArrayList<Integer> list = new ArrayList<>();
for(int a : arr){
list.add(a);
}
TwoSum ts = new TwoSum();
System.out.println(ts.twoSum2(list, 2));
}
}
|
package JavaSessions;
public class DataTypes {
public static void main(String[] args) {
//syso+cntrl+space
// comments entered by Manish
/*
* Multiline comments
* Sep 22, 2020
* Data Types
*
*/
//Data types
//Integer family - byte, short, int, long
//Floating family - float, double
//Character - char
//boolean - true, false
//String
//1. byte
//range: -128 to 127
//size: 1 byte = 8 bits
byte b=100;
System.out.println(b);
byte b1=20;
byte b2=0;
byte b3=-90;
byte b4=20;
System.out.println(b1);
System.out.println(b3+b4);
System.out.println(b1+b2);
//2. short
//range: -32768 to 32767
//size: 2 bytes= 16 bits
short s1=10;
short s2=-1000;
short s3=100;
System.out.println(s1);
System.out.println(s2-s3);
//3. int
//range:-2147483648 to 2147483647
//size: 4 bytes = 32 bits
int i=10;
int total=20000;
System.out.println(i);
System.out.println(total);
//4. long
//range:
//size: 8 bytes = 64 bits
long l=803808343;
System.out.println(l);
//5. float
//range:7 digits after decimal place
//size:4 bytes = 32 bits
float f=12.33f;
System.out.println(f);
float f1=(float)23.44;
System.out.println(f1);
System.out.println(f+f1);
float f2=100;//100.0
System.out.println(f2);
//6. double
//range: 15 digits after decimal
//size:8 bytes=64 bits
double d=23.33;
double d1=34.79734;
System.out.println(d);
System.out.println(d1);
//7. char
//range:2 bytes = 16 bits
//size:character have single digit value
char ch='a';
char ch1='b';
char ch2='3';
char ch3='$';
System.out.println(ch);
System.out.println(ch1);
System.out.println(ch2);
System.out.println(ch3);
System.out.println(ch+ch1);
//ascii values
//a-z:97-122
//A-Z:65-90
//0-9:48-57
//8. boolean
//size=1 bit
//true/false
boolean flag=true;
boolean test=false;
System.out.println(flag);
System.out.println(test);
//9. String
// String -> a dobule quoted value in java
// String is not a data type in java. It is a Class
// all the classes in java starts with upper case
String str="Hello World";
System.out.println(str);
String str1="100";// here 100 is a string not an integer
System.out.println(str+str1);
// multiple properties of print statement
System.out.println(1000);
System.out.println(str);
System.out.println("Hello World");
System.out.println(10+20);
System.out.println("testing" +100);
System.out.println("Hello" + "World");
System.out.println("Hello " + "World");
System.out.println("Hello" + " World");
System.out.println("Hello" + " " + "World");
System.out.print(80);// print and stay in the same line
System.out.println(60);// prints and generates a new line
System.out.println(70);
System.err.println("print something in red");// print something
// in red like in exception handling.
System.out.println(4/2);
System.out.println(5%2);//modulus operator -> divides and gives the remainder
}
}
|
package Forms;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ExecutionException;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingWorker;
import Actions.ActionComboBoxList;
import InterfacesGUI.ClientGUI;
import Modeles.MComboBox;
import Objets.Course;
import Objets.Department;
public class CoursesForm extends JDialog
{
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JTextField nomField;
private ButtonGroup compulsoryRadio = new ButtonGroup();
private JRadioButton compulsoryRadioOui = new JRadioButton("Oui");
private JRadioButton compulsoryRadioNon = new JRadioButton("Non");
private JButton okButton = null;
private JButton cancelButton = new JButton("Annuler");
private ClientGUI fenetre = null;
private Course courseSelected = null;
private MComboBox<Department> comboBoxDepartmentModele = new MComboBox<Department>();
private JComboBox<Department> comboBoxDepartment = null;
private JComboBox<String> comboBoxYear = null;
/**
* Create the dialog.
*/
public CoursesForm(ClientGUI fenetre, Course courseSelected)
{
this.fenetre = fenetre;
this.courseSelected = courseSelected;
if(courseSelected == null)
{
setIconImage(Toolkit.getDefaultToolkit().getImage(CoursesForm.class.getResource("/Images/coursesAdd.png")));
setTitle("Ajouter un cours");
okButton = new JButton("Ajouter");
okButton.setIcon(new ImageIcon(CoursesForm.class.getResource("/Images/coursesAdd.png")));
}
else
{
setIconImage(Toolkit.getDefaultToolkit().getImage(CoursesForm.class.getResource("/Images/coursesUpdate.png")));
setTitle("Modifier un cours");
okButton = new JButton("Modifier");
okButton.setIcon(new ImageIcon(CoursesForm.class.getResource("/Images/coursesUpdate.png")));
}
cancelButton.setIcon(new ImageIcon(CoursesForm.class.getResource("/Images/coursesDel.png")));
setResizable(false);
setModal(true);
setBounds(100, 100, 450, 228);
setLocationRelativeTo(null);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(contentPanel, BorderLayout.CENTER);
comboBoxDepartment = new JComboBox<Department>(comboBoxDepartmentModele);
comboBoxYear = new JComboBox<String>(new DefaultComboBoxModel<String>(new String[] {"Tous niveaux", "L1", "L2", "L3", "M1", "M2"}));
ActionComboBoxList<Department> actionGetDepartments = new ActionComboBoxList<Department>(fenetre, comboBoxDepartmentModele, comboBoxDepartment, (courseSelected != null) ? courseSelected.getDepartement() : null, "departmentsList");
actionGetDepartments.execute();
initGUI();
createEvent();
}
public void initGUI()
{
JLabel lblNom = new JLabel("Nom :");
nomField = new JTextField();
nomField.setColumns(10);
JLabel lblDepartment = new JLabel("Département :");
JLabel lblCompulsory = new JLabel("Cours obligatoire :");
compulsoryRadio.add(compulsoryRadioOui);
compulsoryRadio.add(compulsoryRadioNon);
compulsoryRadioOui.setSelected(true);
JLabel lblYear = new JLabel("Niveau :");
GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
gl_contentPanel.setHorizontalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPanel.createParallelGroup(Alignment.TRAILING)
.addComponent(lblYear)
.addComponent(lblCompulsory)
.addComponent(lblDepartment)
.addComponent(lblNom))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING, false)
.addComponent(comboBoxDepartment, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(nomField, GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE))
.addGroup(gl_contentPanel.createSequentialGroup()
.addComponent(compulsoryRadioOui)
.addGap(18)
.addComponent(compulsoryRadioNon))
.addComponent(comboBoxYear, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE))
.addContainerGap(13, Short.MAX_VALUE))
);
gl_contentPanel.setVerticalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addGap(23)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDepartment)
.addComponent(comboBoxDepartment, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNom)
.addComponent(nomField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblCompulsory)
.addComponent(compulsoryRadioOui)
.addComponent(compulsoryRadioNon))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblYear)
.addComponent(comboBoxYear, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(47, Short.MAX_VALUE))
);
contentPanel.setLayout(gl_contentPanel);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
if(courseSelected != null)
{
nomField.setText(courseSelected.getName());
comboBoxYear.setSelectedIndex(courseSelected.getYear());
if(courseSelected.isCompulsory())
compulsoryRadioOui.setSelected(true);
else
compulsoryRadioNon.setSelected(true);
}
}
public void createEvent()
{
okButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(nomField.getText().isEmpty() || comboBoxDepartment.getSelectedItem() == null)
{
JOptionPane.showMessageDialog(null, "Vous devez remplir tous les champs.", "Champs requis", JOptionPane.ERROR_MESSAGE);
}
else if(compulsoryRadioOui.isSelected() && comboBoxYear.getSelectedItem() == null)
{
JOptionPane.showMessageDialog(null, "Vous devez choisir un niveau.", "Champs requis", JOptionPane.ERROR_MESSAGE);
}
else
{
ActionSave actionSave = new ActionSave();
actionSave.execute();
}
}
});
cancelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
dispose();
}
});
}
private class ActionSave extends SwingWorker<Object, Object>
{
@Override
protected Object doInBackground() throws Exception
{
try
{
if(fenetre.getOut() == null)
fenetre.setOut(new ObjectOutputStream(new BufferedOutputStream(fenetre.getServer().getOutputStream())));
String actionCommande = "Add";
int id = 0;
if(courseSelected != null)
{
actionCommande = "Update";
id = courseSelected.getCID();
}
Course course = new Course();
course.setCID(id);
course.setName(nomField.getText());
course.setDepartement((Department) comboBoxDepartment.getSelectedItem());
course.setYear(comboBoxYear.getSelectedIndex());
course.setCompulsory(compulsoryRadioOui.isSelected());
// Envoie commande
fenetre.getOut().writeObject("course" + actionCommande);
fenetre.getOut().flush();
// Envoie objet
fenetre.getOut().writeObject(course);
fenetre.getOut().flush();
if(fenetre.getIn() == null)
fenetre.setIn(new ObjectInputStream(new BufferedInputStream(fenetre.getServer().getInputStream())));
boolean result = (boolean) fenetre.getIn().readObject();
if(result) return course;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void done()
{
try
{
Course course = (Course) get();
if(course == null)
{
if(courseSelected == null)
JOptionPane.showMessageDialog(null, "Une erreur est survenue lors de l'ajout.\nVérifiez que le cours n'est pas déjà présent dans la base de données.", "Erreur d'ajout", JOptionPane.ERROR_MESSAGE);
else
JOptionPane.showMessageDialog(null, "Une erreur est survenue lors de la modification.\nVérifiez que le cours n'est pas déjà présent dans la base de données.", "Erreur de modification", JOptionPane.ERROR_MESSAGE);
}
else
{
if(courseSelected == null)
{
fenetre.getCoursesListGUI().getModele().add(course);
JOptionPane.showMessageDialog(null, "Cours ajouté avec succès.", "Ajout OK", JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Cours modifié avec succès.", "Modification OK", JOptionPane.INFORMATION_MESSAGE);
dispose();
}
}
catch (InterruptedException | ExecutionException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.