text stringlengths 10 2.72M |
|---|
package com.ff.push;
import android.app.Activity;
import android.view.SurfaceHolder;
import com.ff.push.meida.AudioChannel;
import com.ff.push.meida.VideoChannel;
public class LivePusher {
static {
System.loadLibrary("native-lib");
}
private AudioChannel audioChannel;
private VideoChannel videoChannel;
/**
* 构造方法
*
* @param activity
* @param width 视频采集宽度
* @param height 视频采集高度
* @param bitrate 视频码率
* @param fps 视频帧率
* @param cameraId 视频摄像头
* @param samplesInHZ 音频采样率
* @param channels 音频声道
* @param audioFormat 音频采样精度
* @param audioSource 音频麦克风
*/
public LivePusher(Activity activity, int width, int height, int bitrate, int fps, int cameraId,
int samplesInHZ, int channels, int audioFormat, int audioSource) {
native_init();
videoChannel = new VideoChannel(this, activity, width, height, bitrate, fps, cameraId);
audioChannel = new AudioChannel(this, samplesInHZ, channels, audioFormat, audioSource);
}
/**
* 设置摄像头预览的界面
*
* @param surfaceHolder {@link android.view.SurfaceHolder}
*/
public void setPreviewDisplay(SurfaceHolder surfaceHolder) {
videoChannel.setPreviewDisplay(surfaceHolder);
}
/**
* 切换前后摄像头
*/
public void switchCamera() {
videoChannel.switchCamera();
}
/**
* 重新开启摄像头
*/
public void restartPreview() {
videoChannel.restartPreview();
}
/**
* 开启推流
*
* @param path 推流地址
*/
public void startLive(String path) {
native_start(path);
videoChannel.startLive();
audioChannel.startLive();
}
public void release() {
videoChannel.release();
audioChannel.release();
native_release();
}
private native void native_init();
// 设置推流地址,并开始推流
private native void native_start(String path);
// 设置视频采集信息
public native void native_setVideoInfo(int width, int height, int fps, int bitrate);
// 推视频流
public native void native_pushVideo(byte[] data);
// 设置音频采集信息
public native void native_setAudioInfo(int samplesInHZ, int channels);
// 推音频流
public native void native_pushAudio(byte[] data);
// 获取faac编码器返回的缓冲区大小
public native int getInputSamples();
// 释放资源
public native void native_release();
}
|
/*******************************************************************************
* Copyright 2013 SecureKey Technologies 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.openmidaas.library.persistence.core;
import org.openmidaas.library.model.core.AbstractAttribute;
/**
* Interface to persist attributes.
* Implement this interface to persist attribute using your own
* storage engine.
*/
public interface AttributePersistenceDelegate extends PersistenceDelegate<AbstractAttribute<?>>{
/**
* Returns all email attributes in a list via the callback
* @param callback - callback to get a list of emails
*/
public void getEmails(EmailDataCallback callback);
/**
* Returns all phone attributes in a list via the callback
* @param callback - callback to get a list of phone numbers
*/
public void getPhoneNumbers(PhoneNumberDataCallback callback);
/**
* Returns generic attribute with the specified name in a list via the callback
* @param attributeName - the attribute name to get
* @param callback - callback to get list of generic attributes with the specified name
*/
public void getGenerics(String attributeName, GenericDataCallback callback);
/**
* Returns the subject token via a callback
* @param callback - the subject token callback
*/
public void getSubjectToken(SubjectTokenCallback callback);
/**
* Returns all addresses
* @param callback - callback for a list of addresses
*/
public void getAddresses(AddressDataCallback callback);
/**
* Returns all credit cards
* @param callback - callback for a list of credit cards
*/
public void getCreditCards(CreditCardDataCallback callback);
/**
* Returns all attributes in a list via the callback.
* @param callback - callback for a list of all attributes.
*/
public void getAllAttributes(AttributeDataCallback callback);
}
|
package com.company.bookmark.partner;
public interface Shareable {
public String getItemData();
}
|
package org.stoevesand.brain.rest;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlRootElement;
import org.stoevesand.brain.model.AbstractContent;
import org.stoevesand.brain.model.Answer;
import org.stoevesand.brain.model.CombinedUserLesson;
import org.stoevesand.brain.model.Item;
import org.stoevesand.brain.model.SingleUserLesson;
import org.stoevesand.brain.model.UserItem;
import org.stoevesand.brain.model.UserLesson;
import org.stoevesand.brain.model.UserLessonList;
@XmlRootElement(name = "message")
public class Message {
static final int ERROR_OK = 0;
static final int ERROR_UNKNOWN = 100;
static final int ERROR_ITEM_UNKNOWN = 100;
@XmlElement
Header header;
@XmlElementRefs(value = {
@XmlElementRef(name = "useritem", type = UserItem.class),
@XmlElementRef(name = "item", type = Item.class),
@XmlElementRef(name = "answer", type = Answer.class),
@XmlElementRef(name = "userlessons", type = UserLessonList.class),
@XmlElementRef(name = "userlessons", type = CombinedUserLesson.class),
@XmlElementRef(name = "userlesson", type = UserLesson.class),
@XmlElementRef(name = "userlesson", type = SingleUserLesson.class)
})
AbstractContent content;
public Message() {
}
public Message(Header header) {
this.header = header;
}
public void addContent(AbstractContent content) {
this.content = content;
}
}
|
package com.atguigu.java;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import org.junit.Test;
/**
*
* 了解
*
*/
public class DateTimeFormatterTest {
@Test
public void test2(){
Date date = new Date();
System.out.println(date);
}
@Test
public void test(){
// 预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//format()将时间转成字符串
System.out.println(dtf.format(LocalDateTime.now()));
// 本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
DateTimeFormatter dtf2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
System.out.println(dtf2.format(LocalDateTime.now()));
// 自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
System.out.println(dtf3.format(LocalDateTime.now()));
//将字符串解析成时间
TemporalAccessor parse = dtf.parse("2019-08-17T09:41:44.872");
System.out.println(parse);
}
}
|
package it.raffo.codewars;
public class Test
{
public static void main(String[] args)
{
System.out.println(Sum.GetSum(1, 1));
}
}
|
package scut218.pisces.dao;
import java.util.List;
import scut218.pisces.beans.User;
/**
* Created by Lenovo on 2018/3/14.
*/
public interface UserDAO {
void insert(User user);
void delete(String id);
void update(User user);
User queryById(String id);
List<User> queryAll();
}
|
/**
* Copyright 2015 EIS Co., Ltd. All rights reserved.
*/
package Java001;
/**
* @author 笹田 裕介 <br />
* eclipse上でコンパイル <br />
* コンパイルが正常終了することを確認 <br />
* 更新履歴 2015/12/06(更新者):笹田 裕介:新規作成 <br />
*/
public class Test02 {
/**
* メインメソッド <br />
* 改行して出力 <br />
*
* @param args 実行時引数
*/
public static void main( String[] args ) {
System.out.println( "ようこそJava勉強会へ。\n"
+ "これは2つ目のJavaプログラムです。" );
}
}
|
package org.valar.project.contactsApplication.service;
import java.util.List;
import org.valar.project.contactsApplication.model.Contact;
public interface ContactService {
public Integer save(Contact contact);
public Integer update(Contact c);
public Integer delete(Contact c);
public Integer delete(Integer[] contactId);
/**
* Return all the contacts associated with the logged in user
* @userId Logged in user's id
*/
public List<Contact> findUserContact(Integer userId);
/**
* Getting contacts associated with user
* @param userId
* @param txt by given free text
* @return
*/
public List<Contact> findUserContact(Integer userId, String txt);
}
|
package com.neo.runner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ConcreateApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("The ApplicationRunner run with args = {}", args);
}
}
|
package org.hpin.webservice.bean;
import java.util.Date;
public class CustomerRelationShipPro {
private String id; //主键ID
private String customerRelationShipId; //支公司ID
private String projectCode; //项目编码
private String projectName; //项目名称
private String projectOwner; //项目负责人
private String projectType; //项目类型(癌筛/基因)
private String linkName; //远盟链接人
private String linkTel; //远盟链接人电话
private String remark; //记录
private String mailAddress; //邮件地址
private String reception; //收件人
private String receptionTel; //收件人电话
private Date createTime; //创建日期;
private String createUserId; //创建人id
private String isDeleted; //是否删除;(0未删除,1删除)
private Date deleteTime; //删除时间
private String deleteUserId; //删除人ID
private Date updateTime; //修改时间;
private String updateUserId; //修改人;
// add by YoumingDeng 2016-12-06 start
public static final String F_ID = "id";
public static final String F_CUSTOMERRELATIONSHIPID = "customerRelationShipId";
public static final String F_PROJECTCODE = "projectCode";
public static final String F_PROJECTNAME = "projectName";
public static final String F_PROJECTOWNER = "projectOwner";
public static final String F_PROJECTTYPE = "projectType";
public static final String F_LINKNAME = "linkName";
public static final String F_LINKTEL = "linkTel";
public static final String F_REMARK = "remark";
public static final String F_MAILADDRESS = "mailAddress";
public static final String F_RECEPTION = "reception";
public static final String F_RECEPTIONTEL = "receptionTel";
public static final String F_CREATETIME = "createTime";
public static final String F_CREATEUSERID = "createUserId";
public static final String F_ISDELETED = "isDeleted";
public static final String F_DELETETIME = "deleteTime";
public static final String F_DELETEUSERID = "deleteUserId";
public static final String F_UPDATETIME = "updateTime";
public static final String F_UPDATEUSERID = "updateUserId";
public CustomerRelationShipPro() {
}
// add by YoumingDeng 2016-12-06 end
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCustomerRelationShipId() {
return customerRelationShipId;
}
public void setCustomerRelationShipId(String customerRelationShipId) {
this.customerRelationShipId = customerRelationShipId;
}
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectOwner() {
return projectOwner;
}
public void setProjectOwner(String projectOwner) {
this.projectOwner = projectOwner;
}
public String getProjectType() {
return projectType;
}
public void setProjectType(String projectType) {
this.projectType = projectType;
}
public String getLinkName() {
return linkName;
}
public void setLinkName(String linkName) {
this.linkName = linkName;
}
public String getLinkTel() {
return linkTel;
}
public void setLinkTel(String linkTel) {
this.linkTel = linkTel;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getMailAddress() {
return mailAddress;
}
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
public String getReception() {
return reception;
}
public void setReception(String reception) {
this.reception = reception;
}
public String getReceptionTel() {
return receptionTel;
}
public void setReceptionTel(String receptionTel) {
this.receptionTel = receptionTel;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public Date getDeleteTime() {
return deleteTime;
}
public void setDeleteTime(Date deleteTime) {
this.deleteTime = deleteTime;
}
public String getDeleteUserId() {
return deleteUserId;
}
public void setDeleteUserId(String deleteUserId) {
this.deleteUserId = deleteUserId;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
}
|
package polling;
import java.rmi.RemoteException;
public interface PollFactory extends java.rmi.Remote {
public void build(String model) throws RemoteException;
public boolean doneYet() throws RemoteException;
public IVehicle getVehicle() throws RemoteException;
}
|
package com.github.charlieboggus.sgl.input;
import static org.lwjgl.glfw.GLFW.*;
public enum Buttons
{
Left(GLFW_MOUSE_BUTTON_LEFT, "Left Mouse"),
Right(GLFW_MOUSE_BUTTON_RIGHT, "Right Mouse"),
Middle(GLFW_MOUSE_BUTTON_MIDDLE, "Middle Mouse"),
Button4(GLFW_MOUSE_BUTTON_4, "Mouse 4"),
Button5(GLFW_MOUSE_BUTTON_5, "Mouse 5"),
Button6(GLFW_MOUSE_BUTTON_6, "Mouse 6"),
Button7(GLFW_MOUSE_BUTTON_7, "Mouse 7"),
Button8(GLFW_MOUSE_BUTTON_8, "Mouse 8");
private final int code;
private final String name;
Buttons(int code, String name)
{
this.code = code;
this.name = name;
}
int getCode()
{
return this.code;
}
public String getName()
{
return this.name;
}
}
|
package com.tscloud.common.framework.domain.entity.manager;
import com.tscloud.common.framework.domain.ParentGroup;
import java.io.Serializable;
/**
* create by shm 2015-5-21
* 配置信息实体类
*/
public class Config extends ParentGroup implements Serializable {
private static final long serialVersionUID = -8271641164615707123L;
private String key;
private String value;
private String title;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
package com.adaming.services.impl;
import com.adaming.entities.Role;
import com.adaming.services.interfaces.IRoleService;
public class RoleService extends ServiceGenericImpl<Role> implements IRoleService{
}
|
package com.itcia.itgoo.dao;
import org.apache.ibatis.annotations.Insert;
import com.itcia.itgoo.dto.Communityfile;
public interface ICommunityDao {
@Insert("INSERT INTO COMMUNITYFILE VALUES(#{communityfile},#{communitynum})")
public void insertCommunityfile(String picPath, String communityfile);
}
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final String LINE_SPR = System.getProperty("line.separator");
final int BIG_MOD = 1000000007;
void run() throws Exception {
String line, a, b;
String[] ws;
while((line = br.readLine()) != null) {
ws = line.split(" ");
System.out.println(Puzzle(ws[0], ws[1]));
}
}
public static String Puzzle(String x, String y) {
return solve(x, y, 0, 0, "");
}
public static String solve(String x, String y, int i, int j, String res) {
if(i >= x.length() || j >= y.length())
return res;
char a = x.charAt(i);
char b = y.charAt(j);
String res1, res2;
if(a == b) {
return solve(x, y, i+1, j+1, res + String.valueOf(a));
} else {
res1 = solve(x, y, i+1, j, res);
res2 = solve(x, y, i, j+1, res);
if(res1.length() > res2.length())
return res1;
else
return res2;
}
}
/*
* Templates
*/
void dumpObjArr(Object[] arr, int n) {
for(int i = 0; i < n; i++) {
System.out.print(arr[i]);
if(i < n - 1)
System.out.print(" ");
}
System.out.println("");
}
void dumpObjArr2(Object[][] arr, int m, int n) {
for(int j = 0; j < m; j++)
dumpObjArr(arr[j], n);
}
int ni() throws Exception {
return Integer.parseInt(br.readLine().trim());
}
long nl() throws Exception {
return Long.parseLong(br.readLine().trim());
}
String ns() throws Exception {
return br.readLine();
}
boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
int getPrime(int n) {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
int count = 1;
int x = 1;
while(primes.size() < n) {
x+=2;
int m = (int)Math.sqrt(x);
for(int p : primes) {
if(p > m) {
primes.add(x);
break;
}
if(x % p == 0)
break;
}
}
return primes.get(primes.size() - 1);
}
public static void main(String[] args) throws Exception {
new Main().run();
}
}
|
package org.wicketstuff.gae;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import org.apache.wicket.DefaultPageManagerProvider;
import org.apache.wicket.page.IPageManager;
import org.apache.wicket.page.IPageManagerContext;
import org.apache.wicket.page.PersistentPageManager;
import org.apache.wicket.pageStore.DefaultPageStore;
import org.apache.wicket.pageStore.IDataStore;
import org.apache.wicket.pageStore.IPageStore;
import org.apache.wicket.pageStore.memory.HttpSessionDataStore;
import org.apache.wicket.pageStore.memory.PageNumberEvictionStrategy;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.io.IObjectStreamFactory;
import org.apache.wicket.util.lang.WicketObjects;
/**
* Application object for your web application. If you want to run this application without deploying, run the Start class.
*
* @see com.mycompany.Start#main(String[])
*/
public class GaeWicketApplication extends WebApplication
{
/**
* Constructor
*/
public GaeWicketApplication()
{
}
/**
* @see org.apache.wicket.Application#getHomePage()
*/
public Class<HomePage> getHomePage()
{
return HomePage.class;
}
@Override
protected void init() {
super.init();
getResourceSettings().setResourcePollFrequency(null);
WicketObjects.setObjectStreamFactory(new IObjectStreamFactory() {
@Override
public ObjectInputStream newObjectInputStream(InputStream in)
throws IOException {
return new ObjectInputStream(in);
}
@Override
public ObjectOutputStream newObjectOutputStream(OutputStream out)
throws IOException {
return new ObjectOutputStream(out);
}
});
setPageManagerProvider(new DefaultPageManagerProvider(this) {
public IPageManager get(IPageManagerContext pageManagerContext)
{
IDataStore dataStore = new HttpSessionDataStore(pageManagerContext, new PageNumberEvictionStrategy(10));
IPageStore pageStore = new DefaultPageStore(getName(), dataStore,
getCacheSize());
return new PersistentPageManager(getName(), pageStore, pageManagerContext);
}
});
}
}
|
package io.dcbn.backend.graph;
import javax.persistence.AttributeConverter;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* This converter is used to convert a {@link String} into a 2 dimensional double array.
*/
public class ProbabilityConverter implements AttributeConverter<double[][], String> {
/**
* Converter from double[][] to string
*
* @param attribute the array to convert into a {@link String}
* @return the {@link String} generated by the converter
*/
@Override
public String convertToDatabaseColumn(double[][] attribute) {
return Arrays.stream(attribute)
.map(array -> Arrays.stream(array)
.mapToObj(Double::toString)
.collect(Collectors.joining(";")))
.collect(Collectors.joining("#"));
}
/**
* Converter from {@link String} to double[][]
*
* @param dbData the {@link String} to convert into a double[][]
* @return the double[][] generated by the converter
*/
@Override
public double[][] convertToEntityAttribute(String dbData) {
return Arrays.stream(dbData.split("#"))
.map(array -> Arrays.stream(array.split(";"))
.mapToDouble(Double::parseDouble)
.toArray())
.toArray(double[][]::new);
}
}
|
package org.giddap.dreamfactory.fundamentals.datastructure;
/**
* http://www.museful.net/2012/software-development/circulararraylist-for-java
* http://bradforj287.blogspot.com/2010/11/efficient-circular-buffer-in-java.html
*/
public class CircularBuffer {
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.cache;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ActiveProfilesResolver;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextTestUtils;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.context.cache.ContextCacheTestUtils.assertContextCacheStatistics;
/**
* Integration tests for verifying proper behavior of the {@link ContextCache} in
* conjunction with cache keys used in {@link TestContext}.
*
* @author Sam Brannen
* @author Michail Nikolaev
* @since 3.1
* @see LruContextCacheTests
* @see SpringExtensionContextCacheTests
*/
class ContextCacheTests {
private final ContextCache contextCache = new DefaultContextCache();
@BeforeEach
void initialCacheState() {
assertContextCacheStatistics(contextCache, "initial state", 0, 0, 0);
assertParentContextCount(0);
}
private void assertParentContextCount(int expected) {
assertThat(contextCache.getParentContextCount()).as("parent context count").isEqualTo(expected);
}
private MergedContextConfiguration getMergedContextConfiguration(TestContext testContext) {
return (MergedContextConfiguration) ReflectionTestUtils.getField(testContext, "mergedConfig");
}
private ApplicationContext loadContext(Class<?> testClass) {
TestContext testContext = TestContextTestUtils.buildTestContext(testClass, contextCache);
return testContext.getApplicationContext();
}
private void loadCtxAndAssertStats(Class<?> testClass, int expectedSize, int expectedHitCount, int expectedMissCount) {
assertThat(loadContext(testClass)).isNotNull();
assertContextCacheStatistics(contextCache, testClass.getName(), expectedSize, expectedHitCount,
expectedMissCount);
}
@Test
void verifyCacheKeyIsBasedOnContextLoader() {
loadCtxAndAssertStats(AnnotationConfigContextLoaderTestCase.class, 1, 0, 1);
loadCtxAndAssertStats(AnnotationConfigContextLoaderTestCase.class, 1, 1, 1);
loadCtxAndAssertStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 1, 2);
loadCtxAndAssertStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 2, 2);
loadCtxAndAssertStats(AnnotationConfigContextLoaderTestCase.class, 2, 3, 2);
loadCtxAndAssertStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 4, 2);
}
@Test
void verifyCacheKeyIsBasedOnActiveProfiles() {
int size = 0, hit = 0, miss = 0;
loadCtxAndAssertStats(FooBarProfilesTestCase.class, ++size, hit, ++miss);
loadCtxAndAssertStats(FooBarProfilesTestCase.class, size, ++hit, miss);
// Profiles {foo, bar} should not hash to the same as {bar,foo}
loadCtxAndAssertStats(BarFooProfilesTestCase.class, ++size, hit, ++miss);
loadCtxAndAssertStats(FooBarProfilesTestCase.class, size, ++hit, miss);
loadCtxAndAssertStats(FooBarProfilesTestCase.class, size, ++hit, miss);
loadCtxAndAssertStats(BarFooProfilesTestCase.class, size, ++hit, miss);
loadCtxAndAssertStats(FooBarActiveProfilesResolverTestCase.class, size, ++hit, miss);
}
@Test
void verifyCacheBehaviorForContextHierarchies() {
int size = 0;
int hits = 0;
int misses = 0;
// Level 1
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel1TestCase.class, ++size, hits, ++misses);
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel1TestCase.class, size, ++hits, misses);
// Level 2
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel2TestCase.class, ++size /* L2 */, ++hits /* L1 */,
++misses /* L2 */);
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel2TestCase.class, size, ++hits /* L2 */, misses);
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel2TestCase.class, size, ++hits /* L2 */, misses);
// Level 3-A
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3aTestCase.class, ++size /* L3A */, ++hits /* L2 */,
++misses /* L3A */);
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3aTestCase.class, size, ++hits /* L3A */, misses);
// Level 3-B
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3bTestCase.class, ++size /* L3B */, ++hits /* L2 */,
++misses /* L3B */);
loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3bTestCase.class, size, ++hits /* L3B */, misses);
}
@Test
void removeContextHierarchyCacheLevel1() {
// Load Level 3-A
TestContext testContext3a = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
testContext3a.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
assertParentContextCount(2);
// Load Level 3-B
TestContext testContext3b = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
testContext3b.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
assertParentContextCount(2);
// Remove Level 1
// Should also remove Levels 2, 3-A, and 3-B, leaving nothing.
contextCache.remove(getMergedContextConfiguration(testContext3a).getParent().getParent(),
HierarchyMode.CURRENT_LEVEL);
assertContextCacheStatistics(contextCache, "removed level 1", 0, 1, 4);
assertParentContextCount(0);
}
@Test
void removeContextHierarchyCacheLevel1WithExhaustiveMode() {
// Load Level 3-A
TestContext testContext3a = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
testContext3a.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
assertParentContextCount(2);
// Load Level 3-B
TestContext testContext3b = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
testContext3b.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
assertParentContextCount(2);
// Remove Level 1
// Should also remove Levels 2, 3-A, and 3-B, leaving nothing.
contextCache.remove(getMergedContextConfiguration(testContext3a).getParent().getParent(),
HierarchyMode.EXHAUSTIVE);
assertContextCacheStatistics(contextCache, "removed level 1", 0, 1, 4);
assertParentContextCount(0);
}
@Test
void removeContextHierarchyCacheLevel2() {
// Load Level 3-A
TestContext testContext3a = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
testContext3a.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
assertParentContextCount(2);
// Load Level 3-B
TestContext testContext3b = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
testContext3b.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
assertParentContextCount(2);
// Remove Level 2
// Should also remove Levels 3-A and 3-B, leaving only Level 1 as a context in the
// cache but also removing the Level 1 hierarchy since all children have been
// removed.
contextCache.remove(getMergedContextConfiguration(testContext3a).getParent(), HierarchyMode.CURRENT_LEVEL);
assertContextCacheStatistics(contextCache, "removed level 2", 1, 1, 4);
assertParentContextCount(0);
}
@Test
void removeContextHierarchyCacheLevel2WithExhaustiveMode() {
// Load Level 3-A
TestContext testContext3a = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
testContext3a.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
assertParentContextCount(2);
// Load Level 3-B
TestContext testContext3b = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
testContext3b.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
assertParentContextCount(2);
// Remove Level 2
// Should wipe the cache
contextCache.remove(getMergedContextConfiguration(testContext3a).getParent(), HierarchyMode.EXHAUSTIVE);
assertContextCacheStatistics(contextCache, "removed level 2", 0, 1, 4);
assertParentContextCount(0);
}
@Test
void removeContextHierarchyCacheLevel3Then2() {
// Load Level 3-A
TestContext testContext3a = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
testContext3a.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
assertParentContextCount(2);
// Load Level 3-B
TestContext testContext3b = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
testContext3b.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
assertParentContextCount(2);
// Remove Level 3-A
contextCache.remove(getMergedContextConfiguration(testContext3a), HierarchyMode.CURRENT_LEVEL);
assertContextCacheStatistics(contextCache, "removed level 3-A", 3, 1, 4);
assertParentContextCount(2);
// Remove Level 2
// Should also remove Level 3-B, leaving only Level 1.
contextCache.remove(getMergedContextConfiguration(testContext3b).getParent(), HierarchyMode.CURRENT_LEVEL);
assertContextCacheStatistics(contextCache, "removed level 2", 1, 1, 4);
assertParentContextCount(0);
}
@Test
void removeContextHierarchyCacheLevel3Then2WithExhaustiveMode() {
// Load Level 3-A
TestContext testContext3a = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache);
testContext3a.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3);
assertParentContextCount(2);
// Load Level 3-B
TestContext testContext3b = TestContextTestUtils.buildTestContext(
ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache);
testContext3b.getApplicationContext();
assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4);
assertParentContextCount(2);
// Remove Level 3-A
// Should wipe the cache.
contextCache.remove(getMergedContextConfiguration(testContext3a), HierarchyMode.EXHAUSTIVE);
assertContextCacheStatistics(contextCache, "removed level 3-A", 0, 1, 4);
assertParentContextCount(0);
// Remove Level 2
// Should not actually do anything since the cache was cleared in the
// previous step. So the stats should remain the same.
contextCache.remove(getMergedContextConfiguration(testContext3b).getParent(), HierarchyMode.EXHAUSTIVE);
assertContextCacheStatistics(contextCache, "removed level 2", 0, 1, 4);
assertParentContextCount(0);
}
@Configuration
static class Config {
}
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class AnnotationConfigContextLoaderTestCase {
}
@ContextConfiguration(classes = Config.class, loader = CustomAnnotationConfigContextLoader.class)
private static class CustomAnnotationConfigContextLoaderTestCase {
}
private static class CustomAnnotationConfigContextLoader extends AnnotationConfigContextLoader {
}
@ActiveProfiles({ "foo", "bar" })
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class FooBarProfilesTestCase {
}
@ActiveProfiles({ "bar", "foo" })
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class BarFooProfilesTestCase {
}
private static class FooBarActiveProfilesResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> testClass) {
return new String[] { "foo", "bar" };
}
}
@ActiveProfiles(resolver = FooBarActiveProfilesResolver.class)
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class FooBarActiveProfilesResolverTestCase {
}
@ContextHierarchy({ @ContextConfiguration })
private static class ClassHierarchyContextHierarchyLevel1TestCase {
@Configuration
static class Level1Config {
}
}
@ContextHierarchy({ @ContextConfiguration })
private static class ClassHierarchyContextHierarchyLevel2TestCase extends
ClassHierarchyContextHierarchyLevel1TestCase {
@Configuration
static class Level2Config {
}
}
@ContextHierarchy({ @ContextConfiguration })
private static class ClassHierarchyContextHierarchyLevel3aTestCase extends
ClassHierarchyContextHierarchyLevel2TestCase {
@Configuration
static class Level3aConfig {
}
}
@ContextHierarchy({ @ContextConfiguration })
private static class ClassHierarchyContextHierarchyLevel3bTestCase extends
ClassHierarchyContextHierarchyLevel2TestCase {
@Configuration
static class Level3bConfig {
}
}
}
|
package domain;
import santaTecla.utils.IO;
import santaTecla.utils.WithConsoleModel;
import views.console.Messages;
public class Result extends WithConsoleModel{
private int blacks = 0;
private int whites = 0;
public Result(int blacks, int whites) {
assert blacks >= 0;
assert whites >= 0;
this.blacks = blacks;
this.whites = whites;
}
public boolean isWinner() {
return this.blacks == Combination.getWidth();
}
public Result calculateResult(ProposedCombination proposed, SecretCombination secret) {
int blacks = 0;
for (int i=0; i<secret.colors.size(); i++) {
if (proposed.contains(secret.colors.get(i), i)) {
blacks++;
}
}
int whites = 0;
for (Color color : secret.colors) {
if (proposed.contains(color)) {
whites++;
}
}
return new Result(blacks, whites - blacks);
}
public void writeResult() {
IO.write(String.valueOf(this.blacks));
IO.write(Messages.BLACKS);
IO.write(Messages.AND);
IO.write(String.valueOf(this.whites));
IO.write(Messages.WHITES);
IO.writeln();
}
}
|
package cn.itcast.controller;
import cn.itcast.config.LogConfig;
import cn.itcast.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "user-server", fallback = UserFeignClientImpl.class,configuration = LogConfig.class)
public interface UserFeignClient {
@GetMapping("/user/{id}")
User queryUserById(@PathVariable("id") Long id);
}
|
package com.b.test.security;
import com.b.test.entry.UserDetail;
import com.b.test.entry.UserLogin;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author hjl
* @date 2018/6/8/008 11:21
**/
public class UserLoginUtil {
public static UserLogin getUserLogin() {
Object o = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (o instanceof UserDetail) {
return ((UserDetail) o).getUserLogin();
}
return null;
}
}
|
package com.nsbhasin.nowyouseeme.data;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import java.util.Date;
@Entity
@TypeConverters(DateConverter.class)
public class Location {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private long id;
@ColumnInfo(name = "time_stamp")
public Date timeStamp;
public double latitude;
public double longitude;
public Location(Date timeStamp, double latitude, double longitude) {
this.timeStamp = timeStamp;
this.latitude = latitude;
this.longitude = longitude;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
@Override
public String toString() {
return "[" + String.valueOf(id) + " " + String.valueOf(timeStamp) + " " + String.valueOf(latitude) + " " + String.valueOf(longitude) + "]";
}
}
|
package DecorativePattern;
public class HousBlend extends Beverage {
public HousBlend(float cost,String description) {
super(description,cost);
}
}
|
package com.sapl.retailerorderingmsdpharma.MyDatabase;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import com.sapl.retailerorderingmsdpharma.activities.MyApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Mrunal on 02/02/2018.
*/
public class TABLE_PRICELIST_DETAILS {
public static String NAME = "PriceListDetails";
private static final String LOG_TAG = "TABLE_PriceList_Details";
public static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "
+ NAME + "(Id INTEGER, PriceListID SMALLINT, ItemID INTEGER, DiscoutType TEXT, DiscountRate INTEGER, " +
"SalesRate INTEGER, FromDate DATETIME, ToDate DATETIME, Remarks TEXT, CreatedDate DATETIME, CreatedBy DATETIME, UpdatedDate DATETIME, UpdatedBy DATETIME)";
public static void insert_bulk_PriceListDetails(JSONArray jsonArray) {
try {
MyApplication.logi(LOG_TAG, "in insert_bulk_PriceListDetails->");
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
db.beginTransaction();
String insert_sql = "insert into " + NAME + " (" + "ID,PriceListID,ItemID,DiscoutType,DiscountRate,SalesRate,FromDate,ToDate,Remarks,CreatedDate,CreatedBy,UpdatedDate,UpdatedBy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
MyApplication.logi(LOG_TAG, "insert_sql" + insert_sql);
SQLiteStatement statement = db.compileStatement(insert_sql);
JSONObject jsonObject = null;
int count_array = jsonArray.length();
MyApplication.logi(LOG_TAG, "COUNT ISS->" + count_array);
for (int i = 0; i < count_array; i++) {
jsonObject = jsonArray.getJSONObject(i);
statement.clearBindings();
statement.bindString(1, jsonObject.getString("ID"));
statement.bindString(2, jsonObject.getString("DistributorId"));
statement.bindString(3, jsonObject.getString("ItemID"));
statement.bindString(4, jsonObject.getString("DiscoutType"));
statement.bindString(5, jsonObject.getString("DiscountRate"));
MyApplication.logi(LOG_TAG, "Rajani2" + jsonObject.getString("DiscountRate"));
statement.bindString(6, jsonObject.getString("SalesRate"));
statement.bindString(7, jsonObject.getString("FromDate"));
statement.bindString(8, jsonObject.getString("ToDate"));
statement.bindString(9, jsonObject.getString("Remarks"));
statement.bindString(10, jsonObject.getString("CreatedDate"));
statement.bindString(11, jsonObject.getString("CreatedBy"));
statement.bindString(12, jsonObject.getString("UpdatedDate"));
statement.bindString(13, jsonObject.getString("UpdatedBy"));
statement.execute();
}
MyApplication.logi(LOG_TAG, "EndTime->");
MyApplication.logi(LOG_TAG, "Rajani3" + jsonObject.getString("DiscountRate"));
db.setTransactionSuccessful();
db.endTransaction();
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void deleteTableData() {
MyApplication.logi(LOG_TAG, "in delete price list DETAILS");
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
db.delete(NAME, null, null);
}
public static String getPriceListIDOfDistributor(String dist_id) {
MyApplication.logi(LOG_TAG, "in getPriceListOfDistributor");
int count;
String resp = "";
MyApplication.logi(LOG_TAG, "in getPriceListOfDistributor()" + dist_id);
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
//String query = "SELECT * from "+NAME+" where "+"PriceListID" +" =" + dist_id+"";
String query = "SELECT * from PriceListDetails where PriceListID =" + dist_id;
MyApplication.logi("mrunal", "In getPriceListOfDistributor query :" + query);
Cursor c = db.rawQuery(query, null);
count = c.getCount();
MyApplication.logi(LOG_TAG, "COUNT OF getPriceListOfDistributor IS-->" + count);
if (count > 0) {
c.moveToFirst();
do {
resp = c.getString(c.getColumnIndexOrThrow("PriceListID"));
MyApplication.logi(LOG_TAG, "RESPPPPP-->" + resp);
} while (c.moveToNext());
}
return resp;
}
public static int getSalesRate(String item_id,String dist_id) {
MyApplication.logi(LOG_TAG, "in getSalesRate");
int count;
int resp = 0;
MyApplication.logi(LOG_TAG, "in getSalesRate()" + item_id);
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
//String query = "SELECT * from "+NAME+" where "+"PriceListID" +" =" + dist_id+"";
// String query = "SELECT DISTINCT SalesRate from PriceListDetails where ItemID =" + item_id;
// String query = "select SalesRate from PriceListDetails where ItemID=item_id and PriceListID=dist_id";
String query = "SELECT DISTINCT SalesRate from PriceListDetails where ItemID ='" + item_id + "' AND PriceListID ='" + dist_id + "'";
MyApplication.logi("", "In getSalesRate query :" + query);
Cursor c = db.rawQuery(query, null);
count = c.getCount();
MyApplication.logi(LOG_TAG, "COUNT OF getSalesRate IS-->" + count);
if (count > 0) {
c.moveToFirst();
do {
try {
resp = Integer.parseInt(c.getString(c.getColumnIndexOrThrow("SalesRate")));
} catch (NumberFormatException e) {
e.printStackTrace();
}
MyApplication.logi(LOG_TAG, "RESPPPPP-->" + resp);
} while (c.moveToNext());
}
return resp;
}
public static String getDiscount_type(String item_id,String dist_id) {
MyApplication.logi(LOG_TAG, "in getDiscount_type");
int count;
String resp = "";
MyApplication.logi(LOG_TAG, "in getDiscount_type()" + item_id);
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
//String query = "SELECT * from "+NAME+" where "+"PriceListID" +" =" + dist_id+"";
// String query = "SELECT DISTINCT SalesRate from PriceListDetails where ItemID =" + item_id;
// String query = "select SalesRate from PriceListDetails where ItemID=item_id and PriceListID=dist_id";
String query = "SELECT DiscoutType from PriceListDetails where ItemID ='" + item_id + "' AND PriceListID ='" + dist_id + "'";
MyApplication.logi("", "In getDiscount_type query :" + query);
Cursor c = db.rawQuery(query, null);
count = c.getCount();
MyApplication.logi(LOG_TAG, "COUNT OF getDiscount_type IS-->" + count);
if (count > 0) {
c.moveToFirst();
do {
try {
resp = c.getString(c.getColumnIndexOrThrow("DiscoutType"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
MyApplication.logi(LOG_TAG, "getDiscount_typeRESPPPPP-->" + resp);
} while (c.moveToNext());
}
return resp;
}
public static int getDiscount_rate(String item_id,String dist_id) {
MyApplication.logi(LOG_TAG, "in DiscountRate");
int count;
int resp = 0;
MyApplication.logi(LOG_TAG, "in DiscountRate()" + item_id);
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
//String query = "SELECT * from "+NAME+" where "+"PriceListID" +" =" + dist_id+"";
// String query = "SELECT DISTINCT SalesRate from PriceListDetails where ItemID =" + item_id;
// String query = "select SalesRate from PriceListDetails where ItemID=item_id and PriceListID=dist_id";
String query = "SELECT DISTINCT DiscountRate from PriceListDetails where ItemID ='" + item_id + "' AND PriceListID ='" + dist_id + "'";
MyApplication.logi("", "In DiscountRate query :" + query);
Cursor c = db.rawQuery(query, null);
count = c.getCount();
MyApplication.logi(LOG_TAG, "COUNT OF DiscountRate IS-->" + count);
if (count > 0) {
c.moveToFirst();
do {
try {
resp = Integer.parseInt(c.getString(c.getColumnIndexOrThrow("DiscountRate")));
} catch (NumberFormatException e) {
e.printStackTrace();
}
MyApplication.logi(LOG_TAG, "getDiscount_rateRESPPPPP-->" + resp);
} while (c.moveToNext());
}
return resp;
}
public static void delete_table() {
SQLiteDatabase db = MyApplication.db.getWritableDatabase();
String str1 = "select * from " + NAME;
Cursor c = db.rawQuery(str1, null);
int count= c.getCount();
MyApplication.logi(LOG_TAG, "Count"+count);
int numRows = db.delete(NAME, null, null);
MyApplication.logi(LOG_TAG, "In delete_tbl_timetable_sync");
MyApplication.logi(LOG_TAG, "DeletedRows:->" + numRows);
}
}
|
/* Eoin McDonough 18241646
* Jakub Pažej 18260179
* Aleksander Jakusev 18257038
*/
public class excel_exe{
private String[] sheetNameList; //I would like an Array
private int numberOfPages = 0; //How many Pages
private int nextPosition = 0; //Position in array
private int n = 0; //Names the sheets
public excel_exe(){
sheetNameList = new String[256]; //Length of array starts at 0 so thats why 255
while (numberOfPages < 3){
numberOfPages++;
n++;
sheetNameList[nextPosition] = "Sheet" + n; //creates Sheet1, 2, 3
nextPosition++;
}
}
public excel_exe(int howManyPagesUWant){
sheetNameList = new String[256]; //Length of array starts at 0 so thats why 255
numberOfPages = 1;
nextPosition = 1;
n = 1;
sheetNameList[0] = "Sheet" + numberOfPages;
while (numberOfPages != howManyPagesUWant){
if (numberOfPages < howManyPagesUWant){
numberOfPages++;
n++;
sheetNameList[nextPosition] = "Sheet" + n;
nextPosition++;
}else if (numberOfPages > howManyPagesUWant){
System.out.println("There always must be at least one sheet.");
}
}
}
public boolean add(){
if (nextPosition == 256){
return false;
} else {
numberOfPages++;
n++;
sheetNameList[nextPosition] = "Sheet" + n;
nextPosition++;
return true;
}
}
public boolean add(String Name){
int p;
for(p = 0; p < nextPosition; p++) {
if(sheetNameList[p].compareToIgnoreCase(Name) == 0){
return false;
}
}
if(nextPosition == 256){
return false;
} else {
numberOfPages++;
n++;
sheetNameList[nextPosition] = Name;
nextPosition++;
return true;
}
}
public int remove(String sheetName){
int i ;
for(i = 0; i < nextPosition - 1; i++) {
if(sheetNameList[i].compareToIgnoreCase(sheetName) == 0){
sheetNameList[i] = "";
int j = i;
if ( i < numberOfPages ){
while ( i < numberOfPages ){
sheetNameList[i] = sheetNameList[i+1];
i++;
}
numberOfPages--;
nextPosition--;
return j;
}
}
}
return -1;
}
public String remove(int index){
if(numberOfPages != 1) {
if(index <= numberOfPages){
String gibmarksboss = sheetNameList[index];
sheetNameList[index] = "";
while ( index < numberOfPages ){
sheetNameList[index] = sheetNameList[index+1];
index++;
}
numberOfPages--;
nextPosition--;
return gibmarksboss;
}else if (index > numberOfPages){
return null;
}
}
return null;
}
public int move(String from, String to, boolean before){
String storage = "";
int j, k, sInt1,sInt2;
sInt1 =0;
sInt2 =0;
for(j = 0; j < nextPosition; j++) {
if(sheetNameList[j].compareToIgnoreCase(from) == 0) {
storage = sheetNameList[j];
sheetNameList[j] = "";
sInt1 = j;
}
}
for(k = 0; k < nextPosition; k++) {
if(sheetNameList[k].compareToIgnoreCase(to) == 0) {
sInt2=k;
}
}
if(sInt1 == 0 || sInt2 == 0) {
return -1;
}
if(before == false) {
if( sInt1 - sInt2 > 0) { //right plus on numbers between
while ( sInt1 != sInt2 ){
sheetNameList[sInt1] = sheetNameList[sInt1-1];
sInt1--;
}
sheetNameList[sInt2 + 1] = storage;
return sInt2 + 1;
}else if ( sInt1 - sInt2 < 0){ //left minus on numbers betwe3n
while (sInt1 != sInt2 ){
sheetNameList[sInt1] = sheetNameList[sInt1+1];
sInt1++;
}
sheetNameList[sInt2] = storage;
return sInt2;
}
}else if(before == true) {
if( sInt1 - sInt2 > 0) { //right plus on numbers between
while ( sInt1 !=sInt2 ){
sheetNameList[sInt1] = sheetNameList[sInt1-1];
sInt1--;
}
sheetNameList[sInt2] = storage;
return sInt2;
}else if ( sInt1 - sInt2 < 0){ //left minus on numbers betwe3n
while ( sInt1 != sInt2 ){
sheetNameList[sInt1] = sheetNameList[sInt1+1];
sInt1++;
}
sheetNameList[sInt2-1] = storage;
return sInt2;
}
}
return -1;
}
public String move(int from, int to, boolean before){
String storage =sheetNameList[from];
if(from == 0 || to == 0) {
return null;
}
if(before == false) {
if( from - to > 0) { //right plus on numbers between
while ( from != to ){
sheetNameList[from] = sheetNameList[from-1];
from--;
}
sheetNameList[to + 1] = storage;
return storage;
}else if ( from - to < 0){ //left minus on numbers betwe3n
while (from != to ){
sheetNameList[from] = sheetNameList[from+1];
from++;
}
sheetNameList[to] = storage;
return storage;
}
}else if(before == true) {
if( from - to > 0) { //right plus on numbers between
while ( from !=to ){
sheetNameList[from] = sheetNameList[from-1];
from--;
}
sheetNameList[to] = storage;
return storage;
}else if ( from - to < 0){ //left minus on numbers betwe3n
while ( from != to ){
sheetNameList[from] = sheetNameList[from+1];
from++;
}
sheetNameList[to-1] = storage;
return storage;
}
}
return null;
}
public String moveToEnd(int from){
String sleepTightAniki = sheetNameList[from];
while (from != numberOfPages ){
sheetNameList[from] = sheetNameList[from+1];
from++;
}
sheetNameList[numberOfPages -1] = sleepTightAniki;
return sheetNameList[numberOfPages];
}
public int moveToEnd(String from){
int i;
for(i = 0; i < nextPosition; i++) {
if ( sheetNameList[i].compareToIgnoreCase(from) == 0){
int j=i;
while (j != numberOfPages ){
sheetNameList[j] = sheetNameList[j+1];
j++;
}
sheetNameList[nextPosition -1] = from;
sheetNameList[numberOfPages] = from;
return i;
}
}
return -1;
}
public int rename(String currentName, String newName){
int i ;
for(i = 0; i < nextPosition; i++) {
if(sheetNameList[i].compareToIgnoreCase(currentName) != 0){
}else if(sheetNameList[i].compareToIgnoreCase(newName) == 0){
}else{
sheetNameList[i] = newName;
return i;
}
}
return -1;
}
public int index(String sheetName){
int i ;
for(i = 0; i < nextPosition - 1; i++) {
if(sheetNameList[i].compareToIgnoreCase(sheetName) == 0){
return i;
}
}
return -1;
}
public String sheetName(int index){
int i ;
for(i = 0; i < nextPosition - 1; i++) {
return sheetNameList[index];
}
return null;
}
public void display() {
int a =0;
while(a < numberOfPages) {
System.out.println(sheetNameList[a]);
a++;
}
}
public int length(){
return numberOfPages;
}
}
|
package com.esrinea.dotGeo.tracking.model.component.device.dao;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import org.apache.log4j.Logger;
import com.esrinea.dotGeo.tracking.model.common.dao.AbstractDAO;
import com.esrinea.dotGeo.tracking.model.component.device.entity.Device;
public class DeviceDAOImpl extends AbstractDAO<Device> implements DeviceDAO {
private static Logger LOG = Logger.getLogger(DeviceDAOImpl.class);
public DeviceDAOImpl() {
super(Device.class);
}
@Override
public List<Device> findByIdNativeQuery(int id) {
return entityManager.createNamedQuery("Device.findById", Device.class).setParameter(1, id).getResultList();
}
@Override
public Device find(int id, boolean retired) {
LOG.debug(String.format("Device.findByIdRetired, parameters: %s, %s", id, retired));
Device device = null;
try {
device = entityManager.createNamedQuery("Device.findByIdRetired", Device.class).setParameter("id", id).setParameter("retired", retired).getSingleResult();
} catch (NoResultException ex) {
throw new NoResultException(String.format("%s with ID %s does not exist in database or is %s.", "Device", id, retired ? "not retired" : "retired"));
}
return device;
}
@Override
public Device find(String serial, boolean retired) {
LOG.debug(String.format("Device.findBySerialRetired, parameters: %s, %s", serial, retired));
Device device = null;
try {
device = entityManager.createNamedQuery("Device.findBySerialRetired", Device.class).setParameter("serial", serial.trim()).setParameter("retired", retired).getSingleResult();
} catch (NoResultException ex) {
throw new NoResultException(String.format("%s with Serial %s does not exist in database or is %s.", "Device", serial, retired ? "not retired" : "retired"));
} catch (NonUniqueResultException ex) {
throw new NonUniqueResultException(String.format("Device with Serial %s is duplicated or the one to one realtion it is joining with is refering it, more than once by mistake.", serial));
}
return device;
}
@Override
public List<Device> find(boolean retired) {
LOG.debug(String.format("Device.findByRetired, parameters: %s", retired));
List<Device> devices = entityManager.createNamedQuery("Device.findByRetired", Device.class).setParameter("retired", retired).getResultList();
if (devices == null || devices.isEmpty()) {
LOG.info(String.format("No Records were found in Tracking_Resources table, with criteria of RETIRED is %s.", retired));
}
return devices;
}
@Override
public List<Device> findAndFetchDeviceType(boolean retired) {
LOG.debug(String.format("Device.findByRetiredFetchDeviceType, parameters: %s", retired));
List<Device> devices = entityManager.createNamedQuery("Device.findByRetiredFetchDeviceType", Device.class).setParameter("retired", retired).getResultList();
if (devices == null || devices.isEmpty()) {
LOG.info(String.format("No Records were found in Tracking_Resources table, with criteria of RETIRED is %s.", retired));
}
return devices;
}
}
|
package listener;
import util.Enums.CalibrationType;
import calibration.Calibration;
public interface CalibrationListener
{
public void calibrationEvent(Calibration obj, CalibrationType type, String path, boolean defaultCalibration);
}
|
package com.t2c.Concessionaire.exceptions;
public class NotSupportedDataException extends RuntimeException {
public NotSupportedDataException(String message) {
super(message);
}
}
|
package hu.lamsoft.hms.nutritionist.service.nutritionist.impl;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import hu.lamsoft.hms.common.persistence.customer.dao.CustomerDao;
import hu.lamsoft.hms.common.persistence.nutritionist.dao.NutritionistDao;
import hu.lamsoft.hms.common.persistence.nutritionist.entity.Nutritionist;
import hu.lamsoft.hms.common.service.mapper.ModelMapper;
import hu.lamsoft.hms.common.service.nutritionist.dto.NutritionistDTO;
import hu.lamsoft.hms.common.service.search.impl.SearchPredicateBuilderContext;
import hu.lamsoft.hms.nutritionist.service.nutritionist.NutritionistService;
import hu.lamsoft.hms.nutritionist.service.nutritionist.vo.NutritionistSearchVO;
@Service
@Transactional
public class NutritionistServiceImpl implements NutritionistService {
@Autowired
private NutritionistDao nutritionistDao;
@Autowired
private CustomerDao customerDao;
@Autowired
private ModelMapper modelMapper;
@Autowired
private SearchPredicateBuilderContext searchPredicateBuilderComponent;
@Override
public NutritionistDTO registrate(NutritionistDTO nutritionist) {
Assert.notNull(nutritionist);
Assert.notNull(nutritionist.getCustomer());
Assert.notNull(nutritionist.getCustomer().getId());
Nutritionist entity = new Nutritionist();
entity.setIntroduction(nutritionist.getIntroduction());
entity.setCustomer(customerDao.findOne(nutritionist.getCustomer().getId()));
return modelMapper.convertToDTO(nutritionistDao.save(entity), NutritionistDTO.class);
}
@Override
public Page<NutritionistDTO> searchNutritionist(NutritionistSearchVO nutritionistSearchVO) {
return modelMapper.convertToDTO(nutritionistDao.findAll(searchPredicateBuilderComponent.build(nutritionistSearchVO, NutritionistSearchVO.class), nutritionistSearchVO), NutritionistDTO.class);
}
}
|
package com.myxh.developernews.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import com.myxh.developernews.R;
import com.myxh.developernews.common.AppManager;
/**
* Created by asus on 2016/8/6.
*/
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 添加Activity到堆栈
AppManager.getInstance().addActivity(this);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 结束Activity&从堆栈中移除
AppManager.getInstance().finishActivity(this);
}
protected void openActivity(Class<?> pClass) {
openActivity(pClass, null);
}
protected void openActivity(Class<?> pClass, Bundle pBundle) {
Intent intent = new Intent(this, pClass);
if (pBundle != null) {
intent.putExtras(pBundle);
}
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
protected void openActivityWithOutAnim(Class<?> pClass) {
openActivityWithOutAnim(pClass, null);
}
protected void openActivityWithOutAnim(Class<?> pClass, Bundle pBundle) {
Intent intent = new Intent(this, pClass);
if (pBundle != null) {
intent.putExtras(pBundle);
}
startActivity(intent);
}
protected void openActivity(String pAction) {
openActivity(pAction, null);
}
protected void openActivity(String pAction, Bundle pBundle) {
Intent intent = new Intent(pAction);
if (pBundle != null) {
intent.putExtras(pBundle);
}
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
}
|
/*
* Copyright 2016 TeddySoft Technology. All rights reserved.
*
*/
package tw.teddysoft.gof.Command;
public interface Command {
public Result execute();
}
|
package com.hit.dao;
public class SqlConnector {
protected static String getSqlConnectorUrl() {
return "jdbc:mysql://localhost:3306/skymoodz";
}
protected static String getSqlConnectorUsername()
{
return "root";
}
protected static String getSqlConnectorPassword()
{
return "Tom2580Tom";
}
}
|
/* XZHL0810_MsgDialog.java V01L01 Copyright@QINGDAO FUBO SYSTEM ENGINEERING CO.,LTD 2012 */
/*--------------------------------------------------------------------------------------------------------------------*/
/* */
/* 项目名称 :信智互联 */
/* 画面ID :XZHL0810 */
/* 画面名 :商品信息查询 */
/* 实现功能 :商品列表对话框类 */
/* */
/* 变更历史 */
/* NO 日付 Ver 更新者 内容 */
/* 1 2014/05/22 V01L01 FBSE)高振川 新規作成 */
/* */
package com.fbse.recommentmobilesystem.XZHL0810;
import java.util.Properties;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.fbse.recommentmobilesystem.R;
import com.fbse.recommentmobilesystem.XZHL0840.XZHL0840_ShopModifyActivity;
import com.fbse.recommentmobilesystem.common.CommonConst;
import com.fbse.recommentmobilesystem.common.Commonutil;
import com.fbse.recommentmobilesystem.common.JsonUtil;
import com.fbse.recommentmobilesystem.common.LogUtil;
import com.fbse.recommentmobilesystem.common.MessageUtil;
import com.fbse.recommentmobilesystem.common.Msg;
import com.fbse.recommentmobilesystem.common.WebServiceOfHttps;
/**
* 对话框显示类
*
* 完成商品一览对话框
*/
@SuppressLint("HandlerLeak")
public class XZHL0810_MsgDialog extends Dialog{
// 文本框: 姓名
private TextView tvName;
// 文本框: 修改操作
private TextView tvXiugai;
// 文本框: 删除操作
private TextView tvShanchu;
// 传递给下一个activity的数据
private String[] content;
// Activity上下文
private Context context;
// 初始化配置文件
private Properties properties;
// 单一商品信息
private XZHL0810_GoodsItemBean bean;
private XZHL0810_RefreshInterface refresh;
private String msg;
/**
* 自定义构造器初始化参数
* @param context Activity的上下文
* @param theme 自定义dialog的样式
* @param position 删除标志位
* @param content 传递给下一个activity的数据
* @return XZHL0810_MsgDialog 返回dialog
*/
public XZHL0810_MsgDialog(Context context, int theme, int position, String[] content,
XZHL0810_GoodsItemBean bean, XZHL0810_RefreshInterface refresh) {
super(context, theme);
this.content=content;
this.context = context;
this.bean = bean;
this.refresh = refresh;
}
/**
* 重写的加载自定义dialog视图的方法
* @param savedInstanceState 界面参数
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtil.logStart();
this.setContentView(R.layout.xzhl0810_dialogview);
// 初始化控件
setupDialogView();
// 给dialog里的控件加监听器
addDialogListener();
// 初始化页面文件
initData();
LogUtil.logEnd();
}
/**
* 初始化配置文件
*/
private void initData(){
LogUtil.logStart();
properties = Commonutil.loadProperties(context);
LogUtil.logEnd();
}
/**
* 给dialog里的控件加监听器
*/
private void addDialogListener() {
LogUtil.logStart();
tvXiugai.setOnClickListener(new View.OnClickListener(){
// 修改文本框被点击时出发的事件
@Override
public void onClick(View v) {
LogUtil.logStart();
Intent intent = new Intent(context, XZHL0840_ShopModifyActivity.class);
intent.putExtra("goodsinfo", bean);
XZHL0810_MsgDialog.this.dismiss();
context.startActivity(intent);
LogUtil.logEnd();
}
});
tvShanchu.setOnClickListener(new View.OnClickListener(){
// 删除文本框被点击时触发的事件
@Override
public void onClick(View v) {
LogUtil.logStart();
// 构建是否确定删除商品的对话框
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(
MessageUtil.getMessage(context, Msg.Q015, new String[]{CommonConst.GOODS})).setCancelable(
true).setPositiveButton(properties.getProperty(Msg.I012,
CommonConst.SPACE), new DialogInterface.OnClickListener() {
// 点击确认按钮触发的事件
public void onClick(DialogInterface dialog, int id) {
LogUtil.logStart();
// 删除数据
new PostGoodsInfo().start();
refresh.refresh();
LogUtil.logEnd();
}
}).setNegativeButton(properties.getProperty(Msg.I005, CommonConst.SPACE),
new DialogInterface.OnClickListener() {
// 点击取消按钮触发的事件
public void onClick(DialogInterface dialog, int id) {
}
});
XZHL0810_MsgDialog.this.dismiss();
builder.create().show();
LogUtil.logEnd();
}
});
}
/**
* 初始化对话框样式
*/
private void setupDialogView() {
LogUtil.logStart();
tvName=(TextView) findViewById(R.id.tv_name_0810);
tvName.setText(content[1]);
tvXiugai=(TextView) findViewById(R.id.tv_caozuoxiugai_0810);
tvShanchu=(TextView) findViewById(R.id.tv_caozuoshanchu_0810);
LogUtil.logEnd();
}
/**
* 提交新增店员请求
* @param null
* @return String result 返回服务器返回的JSON
*/
private String postGoodsDelete(){
LogUtil.logStart();
//http://192.168.1.230:8081/FBSEMobileSystemS1/goods/list?wsdl
String result = null;
WebServiceOfHttps woh = new WebServiceOfHttps();
String[] key = {"id"};
String[] value = {content[0]};
String json = woh.WSservers(context, "goods/delete",
JsonUtil.DataToJson("a001", JsonUtil.DataToJson(key, value),
"a0065207-fefe-4166-ac00-a6a09ce5e2a1", JsonUtil.getSign("a001",
JsonUtil.DataToJson(key, value), "a0065207-fefe-4166-ac00-a6a09ce5e2a1")));
// 本地服务器异常
if("{\"states\":\"99\"}".equals(json)){
result = properties.getProperty(Msg.E0027, CommonConst.SPACE);
}else{
// 请求成功
if(JsonUtil.errorJson(json)==null){
result = MessageUtil.getMessage(context, Msg.I021, new String[]{content[1]});
// 远程服务器异常
}else if(CommonConst.TALENTERRORSTATES.equals(JsonUtil.errorJson(json).getSuccess())){
result = properties.getProperty(Msg.E0028, CommonConst.SPACE);
}else{
result = JsonUtil.errorJson(json).getErr_msg();
}
}
LogUtil.logEnd();
return result;
}
/**
* 请求删除结果处理
*/
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
LogUtil.logStart();
super.handleMessage(msg);
MessageUtil.commonToast(context, msg.obj.toString(), Toast.LENGTH_SHORT);
LogUtil.logEnd();
}
};
/**
* 删除商品后台类
*
* 异步提交删除商品请求
*/
class PostGoodsInfo extends Thread{
@Override
public void run() {
LogUtil.logStart();
super.run();
msg = postGoodsDelete();
Message message = new Message();
message.obj = msg;
handler.sendMessage(message);
LogUtil.logEnd();
}
}
}
|
package com.karachevtsev.matrixeditor;
/**
* Created by karachevtsev on 11.03.2016.
*/
public class PropertyValue {
public String value;
public String mark;
public PropertyValue(String value, String mark) {
this.value = value;
this.mark = mark;
}
}
|
package com.ocraftyone.MoreEverything.proxy;
import com.ocraftyone.MoreEverything.Reference;
import com.ocraftyone.MoreEverything.init.ModBlocks;
import com.ocraftyone.MoreEverything.init.ModItems;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.util.ResourceLocation;
public class ClientProxy extends CommonProxy {
@Override
public void registerRenders() {
ModItems.registerRenders();
ModBlocks.registerRenders();
}
public void registerModelBakeryVariants() {
ModelBakery.registerItemVariants(ModItems.itemCupcakePan, new ResourceLocation(Reference.modid, "cupcake_pan_empty"),new ResourceLocation(Reference.modid, "cupcake_pan_one_cupcake"), new ResourceLocation(Reference.modid, "cupcake_pan_two_cupcakes"), new ResourceLocation(Reference.modid, "cupcake_pan_three_cupcakes"), new ResourceLocation(Reference.modid, "cupcake_pan_four_cupcakes"), new ResourceLocation(Reference.modid, "cupcake_pan_five_cupcakes"), new ResourceLocation(Reference.modid, "cupcake_pan_six_cupcakes"), new ResourceLocation(Reference.modid, "cupcake_pan_one_dough"), new ResourceLocation(Reference.modid, "cupcake_pan_two_dough"), new ResourceLocation(Reference.modid, "cupcake_pan_three_dough"), new ResourceLocation(Reference.modid, "cupcake_pan_four_dough"), new ResourceLocation(Reference.modid, "cupcake_pan_five_dough"), new ResourceLocation(Reference.modid, "cupcake_pan_six_dough"));
}
}
|
package comp303.fivehundred.ai.basic;
import comp303.fivehundred.ai.IPlayingStrategy;
import comp303.fivehundred.model.Hand;
import comp303.fivehundred.model.Trick;
import comp303.fivehundred.util.Card;
import comp303.fivehundred.util.Card.Suit;
import comp303.fivehundred.util.CardList;
/**
* @author Ioannis Fytilis 260482744
* If leading, picks a card at random except jokers if playing in no trump.
* If following, choose the lowest card that can follow suit and win.
* If no card can follow suit and win, picks the lowest card that can follow suit.
* If no card can follow suit, picks the lowest trump card that can win.
* If there are no trump card or the trump cards can't win
* (because the trick was already trumped), then picks the lowest card.
* If a joker was led, dump the lowest card unless it can be beaten with
* the high joker according to the rules of the game.
*/
public class BasicPlayingStrategy implements IPlayingStrategy
{
@Override
public Card play(Trick pTrick, Hand pHand)
{
assert pTrick != null && pHand != null;
assert pTrick.size() >= 0 && pHand.size() > 0;
Suit pSuitLed = pTrick.getSuitLed();
Suit pTrump = pTrick.getTrumpSuit();
if (pTrick.size() == 0)
{
return pHand.canLead(pTrick.getTrumpSuit()==null).random();
}
else
{
Hand pFollowable = toHand(pHand.playableCards(pSuitLed, pTrump));
Hand winningCards = couldWin(pTrick, pFollowable);
if (winningCards.size() != 0)
{
return winningCards.selectLowest(pTrump);
}
else
{
return pFollowable.selectLowest(pTrump);
}
}
}
private Hand couldWin(Trick pTrick, Hand pHand)
{
Trick cloned = pTrick.clone();
Hand winningCards = new Hand();
for (Card card : pHand)
{
cloned.add(card);
if (cloned.highest().equals(card))
{
winningCards.add(card);
}
cloned.remove(card);
}
return winningCards;
}
private Hand toHand(CardList pList)
{
Hand pHand = new Hand();
for (Card card : pList)
{
pHand.add(card);
}
return pHand;
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.app.ui;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.GXT;
import com.sencha.gxt.core.client.dom.XDOM;
import com.sencha.gxt.core.client.dom.XElement;
import com.sencha.gxt.core.client.gestures.ScrollGestureRecognizer;
import com.sencha.gxt.core.client.gestures.ScrollGestureRecognizer.ScrollDirection;
import com.sencha.gxt.core.client.util.Rectangle;
import com.sencha.gxt.explorer.client.model.Example;
import com.sencha.gxt.widget.core.client.container.SimpleContainer;
import com.sencha.gxt.widget.core.client.container.Viewport;
public class ExampleContainer extends SimpleContainer {
public static final double DEFAULT_MAX_HEIGHT = -1;
public static final double DEFAULT_MAX_WIDTH = -1;
public static final double DEFAULT_MIN_HEIGHT = -1;
public static final double DEFAULT_MIN_WIDTH = -1;
public static final Overflow DEFAULT_OVERFLOW_X = Overflow.AUTO;
public static final Overflow DEFAULT_OVERFLOW_Y = Overflow.AUTO;
public static final double DEFAULT_PREFERRED_HEIGHT = 0.5;
public static final double DEFAULT_PREFERRED_MARGIN = 20;
public static final double DEFAULT_PREFERRED_WIDTH = 0.5;
private double maxHeight = DEFAULT_MAX_HEIGHT;
private double maxWidth = DEFAULT_MAX_WIDTH;
private double minHeight = DEFAULT_MIN_HEIGHT;
private double minWidth = DEFAULT_MIN_WIDTH;
private Overflow overflowX = DEFAULT_OVERFLOW_X;
private Overflow overflowY = DEFAULT_OVERFLOW_Y;
private double preferredHeight = DEFAULT_PREFERRED_HEIGHT;
private double preferredMargin = DEFAULT_PREFERRED_MARGIN;
private double preferredWidth = DEFAULT_PREFERRED_WIDTH;
private Rectangle cleanBounds;
public ExampleContainer(Example example) {
this(example != null ? example.getExample() : null);
if (example != null) {
maxHeight = example.getMaxHeight();
maxWidth = example.getMaxWidth();
minHeight = example.getMinHeight();
minWidth = example.getMinWidth();
overflowX = example.getOverflowX();
overflowY = example.getOverflowY();
preferredMargin = example.getPreferredMargin();
preferredHeight = example.getPreferredHeight();
preferredWidth = example.getPreferredWidth();
}
if (GXT.isTouch() && GXT.isSafari()) {
addGestureRecognizer(new ScrollGestureRecognizer(getContainerTarget(), ScrollDirection.BOTH));
}
}
public ExampleContainer(IsWidget widget) {
super();
addStyleName("explorer-example-body");
widget.asWidget().addStyleName("explorer-example-demo");
setWidget(widget);
}
public void doStandalone() {
Viewport vp = new Viewport();
vp.setTouchKeyboardAdjustPan(true);
vp.add(this);
RootPanel.get().add(vp);
}
public ExampleContainer setMaxHeight(double maxHeight) {
this.maxHeight = maxHeight;
return this;
}
public ExampleContainer setMaxWidth(double maxWidth) {
this.maxWidth = maxWidth;
return this;
}
public ExampleContainer setMinHeight(double minHeight) {
this.minHeight = minHeight;
return this;
}
public ExampleContainer setMinWidth(double minWidth) {
this.minWidth = minWidth;
return this;
}
public ExampleContainer setOverflowX(Overflow overflowX) {
this.overflowX = overflowX;
return this;
}
public ExampleContainer setOverflowY(Overflow overflowY) {
this.overflowY = overflowY;
return this;
}
public ExampleContainer setPreferredHeight(double preferredHeight) {
this.preferredHeight = preferredHeight;
return this;
}
public ExampleContainer setPreferredMargin(double preferredMargin) {
this.preferredMargin = preferredMargin;
return this;
}
public ExampleContainer setPreferredWidth(double preferredWidth) {
this.preferredWidth = preferredWidth;
return this;
}
@Override
protected void onAfterFirstAttach() {
super.onAfterFirstAttach();
// turn off the loading panel if there was one
XElement loadingPanel = (XElement) DOM.getElementById("explorer-loading-panel");
if (loadingPanel != null) {
loadingPanel.removeFromParent();
}
}
@Override
protected void doLayout() {
if (widget != null && resize) {
final XElement container = getContainerTarget();
final XElement element = widget.getElement().cast();
// determine if the widget is clean by checking if current bounds are clean
final Rectangle currentBounds = element.getBounds(true);
final boolean cleanWidget = cleanBounds == null || (
currentBounds.getX() == cleanBounds.getX()
&& currentBounds.getY() == cleanBounds.getY()
&& currentBounds.getWidth() == cleanBounds.getWidth()
&& currentBounds.getHeight() == cleanBounds.getHeight()
);
// only reposition and resize when the widget is clean
if (cleanWidget) {
// flags for testing if we prefer 100% width or height
final boolean fullWidth = preferredWidth == 1;
final boolean fullHeight = preferredHeight == 1;
// the widget needs to use relative positioning for container scrolling to work
element.makePositionable(false);
// enable container scrolling appropriate depending on type of device
if (GXT.isTouch()) {
container.getStyle().setOverflow(Overflow.SCROLL);
} else {
// widgets wanting 100% must handle scrolling themselves to avoid extraneous scroll bars
if (overflowX != Overflow.AUTO) {
container.getStyle().setOverflowX(overflowX);
} else if (fullWidth) {
container.getStyle().setOverflowX(Overflow.HIDDEN);
} else {
container.getStyle().setOverflowX(DEFAULT_OVERFLOW_X);
}
if (overflowY != Overflow.AUTO) {
container.getStyle().setOverflowY(overflowY);
} else if (fullHeight){
container.getStyle().setOverflowY(Overflow.HIDDEN);
} else {
container.getStyle().setOverflowY(DEFAULT_OVERFLOW_Y);
}
}
// fetch available container size
final int containerWidthPx = container.getComputedWidth();
final int containerHeightPx = container.getComputedHeight();
// calculate preferred margin as pixels
final int preferredMarginPx;
if (preferredMargin < -1) {
preferredMarginPx = -1;
} else if (preferredMargin >= 0 && preferredMargin <= 1) {
preferredMarginPx = (int) (containerWidthPx * preferredMargin);
} else {
preferredMarginPx = (int) preferredMargin;
}
// constrain widget margin
final int singleMargin;
if (preferredMarginPx < 0) {
singleMargin = 0;
} else {
singleMargin = preferredMarginPx;
}
final int bothMargins = singleMargin * 2;
// calculate minimum size as pixels
final int minWidthPx;
if (minWidth < -1) {
minWidthPx = -1;
} else if (minWidth >= 0 && minWidth <= 1) {
minWidthPx = (int) ((containerWidthPx - bothMargins) * minWidth);
} else {
minWidthPx = (int) minWidth;
}
final int minHeightPx;
if (minHeight < -1) {
minHeightPx = -1;
} else if (minHeight >= 0 && minHeight <= 1) {
minHeightPx = (int) ((containerHeightPx - bothMargins) * minHeight);
} else {
minHeightPx = (int) minHeight;
}
// calculate maximum size as pixels
final int maxWidthPx;
if (maxWidth < -1) {
maxWidthPx = -1;
} else if (maxWidth >= 0 && maxWidth <= 1) {
maxWidthPx = (int) ((containerWidthPx - bothMargins) * maxWidth);
} else {
maxWidthPx = (int) maxWidth;
}
final int maxHeightPx;
if (maxHeight < -1) {
maxHeightPx = -1;
} else if (maxHeight >= 0 && maxHeight <= 1) {
maxHeightPx = (int) ((containerHeightPx - bothMargins) * maxHeight);
} else {
maxHeightPx = (int) maxHeight;
}
// calculate preferred size as pixels
final int preferredWidthPx;
if (preferredWidth < -1) {
preferredWidthPx = -1;
} else if (preferredWidth >= 0 && preferredWidth <= 1) {
preferredWidthPx = (int) ((containerWidthPx - bothMargins) * preferredWidth);
} else {
preferredWidthPx = (int) preferredWidth;
}
final int preferredHeightPx;
if (preferredHeight < -1) {
preferredHeightPx = -1;
} else if (preferredHeight >= 0 && preferredHeight <= 1) {
preferredHeightPx = (int) ((containerHeightPx - bothMargins) * preferredHeight);
} else {
preferredHeightPx = (int) preferredHeight;
}
// constrain widget size
final int widgetWidthPx;
if (preferredWidthPx < minWidthPx && minWidthPx > -1) {
widgetWidthPx = minWidthPx;
} else if (preferredWidthPx > maxWidthPx && maxWidthPx > -1) {
widgetWidthPx = maxWidthPx;
} else {
widgetWidthPx = preferredWidthPx;
}
final int widgetHeightPx;
if (preferredHeightPx < minHeightPx && minHeightPx > -1) {
widgetHeightPx = minHeightPx;
} else if (preferredHeightPx > maxHeightPx && maxHeightPx > -1) {
widgetHeightPx = maxHeightPx;
} else {
widgetHeightPx = preferredHeightPx;
}
// calculate widget position for centering
final int left = (containerWidthPx - bothMargins - widgetWidthPx) / 2;
final int top = (containerHeightPx - bothMargins - widgetHeightPx) / 2;
// constrain widget to top-left
final int widgetLeftPx;
if (left < 0) {
widgetLeftPx = 0;
} else {
widgetLeftPx = left;
}
final int widgetTopPx;
if (top < 0) {
widgetTopPx = 0;
} else {
widgetTopPx = top;
}
// set the widget margin
element.setMargins(singleMargin);
// layout the widget at its calculated position & size
applyLayout(widget, new Rectangle(widgetLeftPx, widgetTopPx, widgetWidthPx, widgetHeightPx));
ScheduledCommand adjustLayout = new ScheduledCommand() {
@Override
public void execute() {
// after the layout has finished, fetch the adjusted widget size (including any possible overflow & scrollbars)
final int adjustedWidthPx;
if (fullWidth) {
adjustedWidthPx = widgetWidthPx;
} else if (element.isScrollableX()) {
adjustedWidthPx = element.getScrollWidth() + XDOM.getScrollBarWidth();
} else {
adjustedWidthPx = element.getComputedWidth();
}
final int adjustedHeightPx;
if (fullHeight) {
adjustedHeightPx = widgetHeightPx;
} else if (element.isScrollableY()) {
adjustedHeightPx = element.getScrollHeight() + XDOM.getScrollBarWidth();
} else {
adjustedHeightPx = element.getComputedHeight();
}
// if the actual size differs from the calculated size, position the widget again because it's not right
if (adjustedWidthPx != widgetWidthPx || adjustedHeightPx != widgetHeightPx) {
// recalculate widget position for centering
final int adjustedLeft = (containerWidthPx - bothMargins - adjustedWidthPx) / 2;
final int adjustedTop = (containerHeightPx - bothMargins - adjustedHeightPx) / 2;
// constrain widget to top-left
final int adjustedLeftPx;
if (adjustedLeft < 0) {
adjustedLeftPx = 0;
} else {
adjustedLeftPx = adjustedLeft;
}
final int adjustedTopPx;
if (adjustedTop < 0) {
adjustedTopPx = 0;
} else {
adjustedTopPx = adjustedTop;
}
// layout the widget at its recalculated position & size
applyLayout(widget, new Rectangle(adjustedLeftPx, adjustedTopPx, adjustedWidthPx, adjustedHeightPx));
}
ScheduledCommand adjustCleanBounds = new ScheduledCommand() {
@Override
public void execute() {
// after the layout has finished, preserve the clean bounds for next time
cleanBounds = element.getBounds(true);
}
};
if (GXT.isIE8()) {
Scheduler.get().scheduleDeferred(adjustCleanBounds);
} else {
Scheduler.get().scheduleFinally(adjustCleanBounds);
}
}
};
if (GXT.isIE8()) {
Scheduler.get().scheduleDeferred(adjustLayout);
} else {
Scheduler.get().scheduleFinally(adjustLayout);
}
} else {
// once the widget is dirty, ensure it can't ever be clean again even if the user restores original bounds
cleanBounds = new Rectangle(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE);
}
}
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
Widget child = getWidget();
if (child != null) {
child.setVisible(visible);
}
}
}
|
package com.ass.controller;
import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.ass.service.MailerService;
@Controller
public class TestController {
@Autowired
MailerService mailService;
@GetMapping("mail")
public String mail() throws MessagingException {
mailService.push("viethungthomany@gmail.com","Subject 1","body 1");
return "";
}
}
|
package com.epam.university.spring.service;
import com.epam.university.spring.domain.Auditorium;
import java.util.List;
public interface AuditoriumService {
List<Auditorium> getAuditoriums();
Auditorium getAuditoriumByName(String name);
}
|
package com.example.angela.avocadowe;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import java.util.ArrayList;
/**
* Created by Angela on 10/20/17.
*/
public class Person implements Parcelable, Comparable<Person> {
//instance variables
private String name;
private ArrayList<Owe> oweList;
private int amount = 0;
//constructors
public Person(String name, String description, String date, int amount) {
this.name = name;
oweList = new ArrayList<>();
this.amount = amount;
addOwe(date, description, this.amount);
}
public Person(String name, String date, int amount) {
this.name = name;
oweList = new ArrayList<>();
this.amount = amount;
addOwe(date, this.amount);
}
public Person(String name) {
this.name = name;
oweList = new ArrayList<>();
}
public Person(String name, ArrayList<Owe> oweList) {
this.oweList = oweList;
this.name = name;
}
//methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Owe> getOweList() {
return oweList;
}
public void setOweList(ArrayList<Owe> oweList) {
this.oweList = oweList;
}
public void addOwe(String date, String description, int amount) {
Owe initial = new Owe(amount, date, description);
oweList.add(initial);
}
public void addOwe(String date, int amount) {
Owe initial = new Owe( amount, date);
oweList.add(initial);
}
@Override
public String toString() {
return " " + name;
}
protected Person(Parcel in) {
name = in.readString();
if (in.readByte() == 0x01) {
oweList = new ArrayList<Owe>();
in.readList(oweList, Owe.class.getClassLoader());
} else {
oweList = null;
}
amount = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
if (oweList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(oweList);
}
dest.writeInt(amount);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int compareTo(@NonNull Person person) {
return name.compareTo(person.name);
}
} |
package com.ufpr.tads.dac.exceptions;
public class FuncionarioException extends Exception{
public FuncionarioException() {
}
public FuncionarioException(String msg) {
super(msg);
}
}
|
package com.lesports.albatross.adapter.community;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.lesports.albatross.activity.PhotoActivity;
import com.lesports.albatross.custom.FrescoPhotoView;
import java.util.ArrayList;
import java.util.List;
import uk.co.senab.photoview.PhotoViewAttacher;
/**
* 图片全屏浏览adapter
* Created by jiangjianxiong on 16/6/12.
*/
public class PhotoPagerAdapter extends PagerAdapter {
private Context mContext;
private List<String> mList;
private boolean isLocal = Boolean.FALSE;//是否本地图片
public PhotoPagerAdapter(Context context, boolean isLocal) {
this.mContext = context;
this.mList = new ArrayList<>();
this.isLocal = isLocal;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public View instantiateItem(ViewGroup container, int position) {
FrescoPhotoView photoView = new FrescoPhotoView(container.getContext());
if (!isLocal) {
photoView.setImageUri(mList.get(position), null);
} else {
photoView.setImageUri("file://" + mList.get(position), null);
}
container.addView(photoView);
photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
@Override
public void onPhotoTap(View view, float v, float v1) {
((PhotoActivity) mContext).exit();
}
@Override
public void onOutsidePhotoTap() {
((PhotoActivity) mContext).finish();
}
});
return photoView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public void updateDatas(List<String> list) {
mList.clear();
if (null != list) {
mList.addAll(list);
}
notifyDataSetChanged();
}
} |
package uk.co.ksl.oms.service.domain;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static uk.co.ksl.oms.service.domain.BuyOrSell.BUY;
public class LiveQuote {
private final Product product;
private final double buyPrice;
private final double sellPrice;
private final LocalDateTime timeOfQuote;
private final ZoneId timeZoneOfQuote;
public LiveQuote(Product product, double buyPrice, double sellPrice, LocalDateTime timeOfQuote, ZoneId timeZoneOfQuote) {
this.product = product;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
this.timeOfQuote = timeOfQuote;
this.timeZoneOfQuote = timeZoneOfQuote;
}
public boolean makeOffer(BuyOrSell buyOrSell, double offer) {
if (buyOrSell == BUY) {
return makeOfferForBuy(offer);
}
else {
return makeOfferForSell(offer);
}
}
public Product getProduct() {
return product;
}
public double getPrice(BuyOrSell buyOrSell) {
if (buyOrSell == BUY) {
return buyPrice;
}
else {
return sellPrice;
}
}
public double getBuyPrice() {
return buyPrice;
}
public double getSellPrice() {
return sellPrice;
}
public LocalDateTime getTimeOfQuote() {
return timeOfQuote;
}
public ZoneId getTimeZoneOfQuote() {
return timeZoneOfQuote;
}
private boolean makeOfferForBuy(double offer) {
return (offer >= buyPrice);
}
private boolean makeOfferForSell(double offer) {
return (offer <= sellPrice);
}
}
|
/**
* Componente Curricular: Módulo Integrador de Concorrência e Conectividade
* Autor: Allen Hichard Marques dos Santos e Caique dos Santos Trindade
* Data: 15/05/2016
*
* Declaramos que este código foi elaborado por nós em dupla e
* não contém nenhum trecho de código de outro colega ou de outro autor,
* tais como provindos de livros e apostilas, e páginas ou documentos
* eletrônicos da Internet. Qualquer trecho de código de outra autoria que
* uma citação para o não a nossa está destacado com autor e a fonte do
* código, e estamos cientes que estes trechos não serão considerados para fins
* de avaliação. Alguns trechos do código podem coincidir com de outros
* colegas pois estes foram discutidos em sessões tutorias.
*/
package EstacaoDeTrens;
/**
* A classe Trem representa um trem da sistema de compartilhamento de trilhos.
* É responsável por gerenciar parâmetros como localização, velocidade, deslocamento
* e de alterar os estados do sistema.
*
* @author Allen Hichard e Caique Trindade
*/
public class Trem {
private int x, y, contador, velocidade, velocidadeMPS, velocidadeLimite, perimetro, areaCompartilhada;
private boolean parado, controle = true;
private Trilho trilho;
public static final int SEGUNDO = 1000, VELOCIDADE_PADRAO = 100, VELOCIDADE_MAXIMA = 200;
/**
* O construtor da classe Trem inicializa suas variáveis com caracteristicas
* comportamentais dentro do sistema, como por exemplo: posição x e y,
* contador (que representa a distância até o ponto inicial da área
* compartilhada), tamanho da área compartilhada, o perímetro do seu percurso
* e referencia o trilho que o mesmo pertence.
*
* @param x
* @param y
* @param contadorInicial
* @param areaCompartilhada
* @param perimetroTotal
* @param trilho
*/
public Trem(int x, int y, int contadorInicial, int areaCompartilhada, int perimetroTotal, Trilho trilho) {
this.x = x;
this.y = y;
this.velocidadeMPS = VELOCIDADE_PADRAO;
this.velocidade = SEGUNDO/velocidadeMPS;
this.velocidadeLimite = VELOCIDADE_MAXIMA;
this.contador = contadorInicial;
this.areaCompartilhada = areaCompartilhada;
this.perimetro = perimetroTotal;
this.trilho = trilho;
this.parado = true;
}
/**
* Retorna a posição x do trem.
*
* @return Int com a coordenada X.
*/
public int getX() {
return x;
}
/**
* Retorna a posição y do trem.
*
* @return Int com a coordenada Y.
*/
public int getY() {
return y;
}
/**
* Retorna a distancia até a entrada na zona compartilhada.
*
* @return Int com o contador.
*/
public int getDistanciaPontoCompartilhado() {
return contador;
}
/**
* Retorna o estado do trem.
*
* @return True, se parado. False, caso contrário.
*/
public boolean isParado() {
return parado;
}
/**
* Método responsável por iniciar o funcionamento do trem. Desse modo,
* cria a Thread responsável por fazer o andar do trem.
*/
public void start() {
parado = false;
new Thread(new MotorTrem()).start();
}
/**
* Retorna a velocidade do trem.
*
* @return Int com a velocidade atual do trem.
*/
public int getVelocidade() {
return velocidadeMPS;
}
/**
* Retorna a velocidade limite do trem.
*
* @return Int com a velocidade limite atual do trem.
*/
public int getVelocidadeLimite() {
return velocidadeLimite;
}
/**
* Altera a velocidade limite do trem, caso a alteração seja necessária e válida.
* Exemplo: se um trem está a 100 e altera a velocidade limite para 110, não
* é preciso alterar a velocidade atual, já que a mesma está abaixo. Caso a
* velocidade limite seja alterada para um valor menor, tipo 90, a velocidade
* é mudada para 90, nesse caso.
*
* @param velocidadeLimite Int com a velocidade limite.
*/
public void setVelocidadeLimite(int velocidadeLimite) {
if (velocidadeLimite <= VELOCIDADE_MAXIMA)
this.velocidadeLimite = velocidadeLimite;
else
this.velocidadeLimite = VELOCIDADE_MAXIMA;
if (velocidadeLimite < velocidadeMPS)
this.setVelocidade(velocidadeLimite);
trilho.attVelocidade(velocidadeMPS, this.velocidadeLimite);
}
/**
* Altera a velocidade de um trem, verificando se a velocidade que será
* setada é menor ou igual a velocidade limite, caso for maior não é possível
* fazer a alteração por segurança do sistema. Só poderá ser alterado a
* velocidade se for menor ou igual que a velocidade limite. A velocidade
* minima de um trem é 10.
*
* @param velocidade Int com a velocidade.
*
* @return True, caso efetuada com sucesso. False, caso contrário.
*/
public boolean setVelocidade(int velocidade) {
if (velocidade > velocidadeLimite)
return false;
if (velocidade != velocidadeMPS) {
if (velocidade < 10)
this.velocidadeMPS = 10;
else
this.velocidadeMPS = velocidade;
this.velocidade = SEGUNDO/this.velocidadeMPS;
}
trilho.attVelocidade(velocidadeMPS, this.velocidadeLimite);
return true;
}
/**
* Classe MotorTrem é rodada por uma thread que é executada enquanto o trem
* estiver circulando em seu trilho, sempre verificando se o trem está
* entrando ou saindo da zona compartilhada e tomando as medidas necessárias
* para cada uma das situações.
*/
private class MotorTrem implements Runnable {
@Override
public void run() {
while(true) {
if (contador == 1) {
contador = perimetro;
trilho.solicitarPermissao();
while(!trilho.getPermissao()) {
try {
Thread.sleep((long)velocidade);
} catch (InterruptedException ex) {}
}
trilho.gerenciarVelocidade();
setVelocidadeLimite(VELOCIDADE_MAXIMA);
setVelocidade(VELOCIDADE_MAXIMA);
}
else if (contador == areaCompartilhada) {
setVelocidadeLimite(VELOCIDADE_MAXIMA);
setVelocidade(VELOCIDADE_PADRAO);
trilho.sairAreaCompartilhada();
}
if (x < trilho.getLargura() && y == 0)
x+=1;
else if (x == trilho.getLargura() && y < trilho.getAltura())
y+=1;
else if (y == trilho.getAltura() && x > 0)
x-=1;
else if (x == 0 && y > 0)
y-=1;
contador--;
if (contador % 2 == 0)
trilho.atualizarCoordenada(x, y);
try {
Thread.sleep((long)velocidade);
} catch (InterruptedException ex) {};
}
}
}
}
|
import java.util.ArrayList;
public class VoteProcessor {
public String calculateElectionWinner(ArrayList<String> votes) {
String Winner = "";
int votesFrancis = 0;
int votesSnowden = 0;
for (int i = 0; i < votes.size(); i++) {
if (votes.get(i).equalsIgnoreCase("pope francis")) {
votesFrancis++;
} else {
votesSnowden++;
}
}
if(votesFrancis > votesSnowden) {
Winner = "pope francis";
}
else if(votesFrancis < votesSnowden) {
Winner = "edward snowden";
}
else {
Winner = "TIE";
}
return Winner;
}
}
|
package interfejsi1;
public class Tacka implements IMoveable{
public double x,y;
@Override
public void printLocation() {
System.out.println(this.toString());
}
@Override
public String toString() {
return "Tacka [x=" + x + ", y=" + y + "]";
}
@Override
public void moveUp(double value) {
// TODO Auto-generated method stub
}
@Override
public void moveDown(double value) {
// TODO Auto-generated method stub
}
@Override
public void moveLeft(double value) {
x-=value;
}
@Override
public void moveRight(double value) {
x+=value;
}
}
|
import java.io.Reader;
import java.util.Scanner;
public class Calculator {
//
// public void takeInput(String input) throws IncorrectInputException {
//
// }
/**
* Makes a basic calculation using two numbers and an operator.
* @param num1 a float, the first number in the operation.
* @param num2 a float, the second number in the operation.
* @param operator a String representing one of +, -, *, /
* @return the result of the calculation.
*/
public static int basicCalculate(int num1, int num2, String operator) {
switch (operator) {
case "+": return num1 + num2;
case "-": return num1 - num2;
case "*": return num1 * num2;
case "/": return num1/num2;
default: return 0; // need to fix this
}
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in).useDelimiter("\\s");
try {
int num1 = Integer.parseInt(userInput.next());
String operator = userInput.next();
int num2 = Integer.parseInt(userInput.next());
System.out.println(basicCalculate(num1, num2, operator));
} catch (NumberFormatException e) {
System.out.println("Must provide numbers.");
}
}
}
|
package com.cs.player;
/**
* @author Hadi Movaghar
*/
public class PlayerLimitationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PlayerLimitationException(final String message) {
super(message);
}
}
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package simulator.srl;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Response</b></em>'.
* <!-- end-user-doc -->
*
*
* @see simulator.srl.ResultsPackage#getResponse()
* @model
* @generated
*/
public interface Response extends SimulationElement {
} // Response
|
package defence;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import javax.swing.*;
import defence.ReadMap;
public class Main {
public static void makeWindow(String title, BufferedImage[] play_map){
// Set up the frame
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(10, 10));
frame.setResizable(false);
frame.setVisible(true);
for (int i = 0; i < 100; i++){
// frame.add(new JLabel("This is a label"));
frame.add(new JLabel(new ImageIcon(play_map[i])));
}
// Pack all of our lovely items into the frame
frame.pack();
}
public static void main(String args[]){
BufferedImage[] play_map = ReadMap.Read_Map("/Users/jack.sarick/Code/Java Game/defence/src/defence/map_1.map", 100);
makeWindow("Defence", play_map);
}
}
|
package edu.almightyconverter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_layout_container);
final String[] inputArray = new String[]{"Base-N Conversion",
"Distance",
"Temperature",
"Volume",
"Pressure",
"Area",
"Take Notes"};
ActivityMainListAdapter adapter = new ActivityMainListAdapter(this, inputArray);
listView.setAdapter(adapter);
//Intent intentMain = new Intent(this,BaseNActivity.class);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(MainActivity.this,Integer.toString(position),Toast.LENGTH_SHORT).show();
switch (position) {
case 0: {
Intent intentMain = new Intent(MainActivity.this,BaseNActivity.class);
startActivity(intentMain);
}
case 6: {
Intent intentMain = new Intent(MainActivity.this,TakeNotesActivity.class);
startActivity(intentMain);
}
}
}
});
}
}
|
package edu.cs.ubbcluj;
/**
* Created by Zete-Írs on 2016.04.08..
*/
public class TestableLogAnalyzer extends LogAnalyzer{
private FakeFileExtMgr fakeFileExtMgr;
public TestableLogAnalyzer(FakeFileExtMgr fakeFileExtMgr){
this.fakeFileExtMgr = fakeFileExtMgr;
}
@Override
public FileExtMgr getFileExtMgr(){
return fakeFileExtMgr;
}
}
|
package StepDefinations;
import io.cucumber.java.Before;
public class Hooks {
StepDefination m=new StepDefination();
@Before("@DeletePlace")
public void beforeScenario() throws Exception
{
if(m.placeid==null)
{
m.add_place_payload_with("sai", "Telugu", "warangal");
m.user_call_with_http_request("AddPlaceAPI", "POST");
m.verify_placed_id_created_maps_to_using("sai", "getPlaceApI");
}
}
}
|
package info.gridworld.grid;
/**
* A <code>SparseGridNodeList</code> is a linked list which used in a sparse array.
* @author Eduardo
*/
public class SparseGridNodeList
{
private SparseGridNode first;
//private int size;
public SparseGridNodeList()
{
first = null;
//size = 0;
}
/**
* insert element at the first
*/
public void insertFirst(SparseGridNode inNode)
{
SparseGridNode link = new SparseGridNode();
link = inNode;
link.setNext(first);
first = link;
//size++;
}
/**
* delete a node in the list according to the given colNum
* @param col
* @return the removed node
*/
public SparseGridNode delNode(int col)
{
if(first == null || first.getColNum() == col)
{
SparseGridNode oldNode = first;
first = first.getNext();
return oldNode;
}
else
{
SparseGridNode curNode = first.getNext();
SparseGridNode prevNode = getFirst();
while(curNode != null)
{
if(curNode.getColNum() == col)
{
prevNode.setNext(curNode.getNext());
return curNode;
}
else
{
prevNode = curNode;
curNode = curNode.getNext();
}
}
return null;
}
}
/**
* get the first node of the list
* @return the first node or null if list is empty
*/
public SparseGridNode getFirst()
{
return first;
}
} |
package com.zhongyp.advanced.pattern.strategy;
/**
* project: demo
* author: zhongyp
* date: 2018/1/24
* mail: zhongyp001@163.com
*/
public class FlyNoWay implements FlyBehavior {
@Override
public void fly() {
System.out.println("I can not fly");
}
}
|
package com.example.okta_cust_sign_in.interfaces;
public interface AppLoadingView {
void show();
void show(String message);
void hide();
}
|
package com.staniul.teamspeak.commands.validators;
import com.staniul.util.validation.Validator;
public class IntegerParamsValidator implements Validator<String> {
@Override
public boolean validate(String element) {
return element.matches("^-?[1-9]\\d*$");
}
}
|
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class MyHelloWorld {
public static void main(String args[])
{
SpringApplication.run(MyHelloWorld.class, args);
}
@RequestMapping("/")
public String displayResult()
{
return("Hello Manish, It is spring boot docker again");
}
}
|
package com.micHon.adapter;
public class EuroSocket {
public void plugIn(EuroDevice device){
device.on();
}
}
|
package com.wrathOfLoD.Models.Ability.Abilities;
import com.wrathOfLoD.Models.Entity.Character.Character;
import com.wrathOfLoD.Models.Map.Map;
import com.wrathOfLoD.Models.Skill.SneakSkillManager;
import com.wrathOfLoD.Utility.Position;
/**
* Created by matthewdiaz on 4/17/16.
*/
public class RemoveTrapAbility extends Ability {
private SneakSkillManager ssm;
public RemoveTrapAbility(Character character, int manaCost) {
super(character, manaCost);
ssm = (SneakSkillManager) character.getSkillManager();
setName("Remove trap");
}
public boolean shouldDoAbility(){
return checkCanCastAbility(ssm.getRemoveTrapLevel());
}
public void doAbilityHook(){
Character character = getCharacter();
Position position = character.getPosition().getPosInDir(character.getDirection());
Map.getInstance().removeTrap(position);
}
}
|
package com.example.prog3.alkasaffollowup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import com.example.prog3.alkasaffollowup.Model.MailingOut;
import java.util.StringTokenizer;
public class DisplayMailOut extends AppCompatActivity {
private TextView subject, purpose, projectName , emailTo, dateTime;
private MailingOut recieve;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_mail_out);
subject=(TextView)findViewById(R.id.singlemailsubject);
purpose=(TextView)findViewById(R.id.singlemailPurpose);
projectName=(TextView)findViewById(R.id.singlemailProjectName);
emailTo=(TextView)findViewById(R.id.singlemailTo);
dateTime=(TextView)findViewById(R.id.singlemailDateTime);
recieve = getIntent().getParcelableExtra("singleMail");
subject.setText(recieve.getSubject());
purpose.setText(Html.fromHtml(recieve.getPurpose().toString()));
emailTo.setText(recieve.getToEmployee() + " - " + recieve.getToBranch());
if (recieve.getProjectName() == null){
projectName.setText("General");
}
else
projectName.setText(recieve.getProjectName());
try {
String s = recieve.getSentDate();
StringTokenizer tokenizer = new StringTokenizer(s, "T");
String date = tokenizer.nextToken();
String time = tokenizer.nextToken();
StringTokenizer timeTok = new StringTokenizer(time, ":");
String hours = timeTok.nextToken();
String minutes = timeTok.nextToken();
dateTime.setText(date + " " + hours+":"+minutes);
}
catch (Exception e){
}
}
}
|
package com.jh.share.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Service;
import com.jh.share.model.FileBucket;
import com.jh.share.repository.FileBucketRepository;
@Service
public class FileServiceImpl implements FileService{
@Autowired
private FileBucketRepository fileBucketRepository;
@Override
public String findFileBucketPathById(int id) {
String filePath = fileBucketRepository.findOne((long) id).getFilePath();
return filePath;
}
@Override
public FileBucket create(FileBucket fileBucket) {
FileBucket file = fileBucketRepository.saveAndFlush(fileBucket);
return file;
}
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Paul Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.kemitix.dependency.digraph.maven.plugin;
import lombok.val;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
/**
* Default implementation of the Digraph Service.
*
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@Immutable
class DefaultDigraphService implements DigraphService {
private static final String REPORT_FILE = "digraph.dot";
private final SourceDirectoryProvider directoryProvider;
private final SourceFileProvider fileProvider;
private final FileLoader fileLoader;
private final SourceFileAnalyser fileAnalyser;
private final ReportGenerator reportGenerator;
private final ReportWriter reportWriter;
private final DotFileFormatFactory dotFileFormatFactory;
/**
* Constructor.
*
* @param directoryProvider The Directory Provider
* @param fileProvider The File Provider
* @param fileLoader The File Loader
* @param fileAnalyser The File Analyser
* @param reportGenerator The Report Generator
* @param reportWriter The Report Writer
* @param dotFileFormatFactory The Dot File Format Factory
*/
@Inject
DefaultDigraphService(
final SourceDirectoryProvider directoryProvider, final SourceFileProvider fileProvider,
final FileLoader fileLoader, final SourceFileAnalyser fileAnalyser, final ReportGenerator reportGenerator,
final ReportWriter reportWriter, final DotFileFormatFactory dotFileFormatFactory
) {
this.directoryProvider = directoryProvider;
this.fileProvider = fileProvider;
this.fileLoader = fileLoader;
this.fileAnalyser = fileAnalyser;
this.reportGenerator = reportGenerator;
this.reportWriter = reportWriter;
this.dotFileFormatFactory = dotFileFormatFactory;
}
@Override
@SuppressWarnings("npathcomplexity")
public void execute(final DigraphMojo mojo) {
val dependencyData = DigraphFactory.newDependencyData(mojo.getBasePackage());
fileProvider.process(directoryProvider.getDirectories(mojo.getProjects(), mojo.isIncludeTests()))
.stream()
.map(fileLoader::asInputStream)
.forEach(in -> fileAnalyser.analyse(dependencyData, in));
dependencyData.updateNames();
if (mojo.isDebug()) {
dependencyData.debugLog(mojo.getLog());
}
try {
val outputDirectory = new File(mojo.getProject()
.getBuild()
.getDirectory());
outputDirectory.mkdirs();
reportWriter.write(
reportGenerator.generate(
dotFileFormatFactory.create(mojo.getFormat(), dependencyData.getBaseNode())),
new File(outputDirectory, REPORT_FILE).getAbsolutePath()
);
} catch (IOException ex) {
mojo.getLog()
.error(ex.getMessage());
}
}
}
|
package Team.junit;
import Team.domain.Employee;
import Team.service.NameListService;
import org.junit.Test;
public class NameListServiceTest {
@Test
public void testGetAllEmployees(){
NameListService service=new NameListService();
Employee[] allEmployees = service.getAllEmployees();
for(Employee e:allEmployees){
System.out.println(e);
}
}
}
|
package com.boku.auth.http.server.servletfilter;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.boku.auth.http.AuthorizationHeader;
import com.boku.auth.http.httpmessage.CanonicalHttpHeader;
import com.boku.auth.http.httpmessage.CanonicalHttpResponse;
import com.boku.auth.http.httpsigner.HttpMessageSigner;
import com.boku.util.DigestFactory;
import com.boku.util.HexCodec;
/**
* Does the work of signing {@link HttpServletResponse}s from {@link BokuHttpAuthFilter}
*/
class BokuHttpAuthFilterResponseSigner {
private final HttpMessageSigner httpMessageSigner;
BokuHttpAuthFilterResponseSigner(HttpMessageSigner httpMessageSigner) {
this.httpMessageSigner = httpMessageSigner;
}
AuthorizationHeader signResponse(AuthorizationHeader requestAuthHeader, List<String> headersToSign, HttpServletResponse httpResponse, byte[] respData) {
// This is the header we're going to output.
// We take partner ID and key ID from the request header, i.e. this is symmetric. In future we may want to
// allow the key provider to pick the key for signing messages to allow for asymmetric signatures.
AuthorizationHeader respAuthHeader = new AuthorizationHeader();
respAuthHeader.setPartnerId(requestAuthHeader.getPartnerId());
respAuthHeader.setKeyId(requestAuthHeader.getKeyId());
// Create canonical response object, while setting the correct list of signed-headers
CanonicalHttpResponse canonicalResponse = new CanonicalHttpResponse();
for (String hdr : headersToSign) {
Collection<String> values = httpResponse.getHeaders(hdr);
if (values == null || values.isEmpty()) {
continue;
}
respAuthHeader.getSignedHeaders().add(hdr);
for (String value : values) {
canonicalResponse.getHeaders().add(new CanonicalHttpHeader(hdr, value.trim()));
}
}
if (respData.length > 0) {
byte[] digest = DigestFactory.getSHA256().digest(respData);
canonicalResponse.setEntityDigest(HexCodec.encodeString(digest));
}
// Fill in missing values and sign
this.httpMessageSigner.sign(respAuthHeader, canonicalResponse);
return respAuthHeader;
}
}
|
package thesis;
import io.vertx.core.AbstractVerticle;
import thesis.verticles.App;
import thesis.verticles.MongoFooServiceVerticle;
public class MainDeployer extends AbstractVerticle{
@Override
public void start() throws Exception {
super.start();
vertx.deployVerticle(new MongoFooServiceVerticle(), r -> {
if(r.succeeded())
System.out.println("Deployed MongoFoo Verticle");
else
System.err.println(r.cause());
});
vertx.deployVerticle(new App(), r -> {
if(r.succeeded())
System.out.println("Deployed App Verticle");
else
System.err.println(r.cause());
});
}
}
|
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddPromotionMerchantCouponListGetResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.Map;
import java.util.TreeMap;
public class PddPromotionMerchantCouponListGetRequest extends PopBaseHttpRequest<PddPromotionMerchantCouponListGetResponse>{
/**
* 页码,默认1
*/
@JsonProperty("page")
private Integer page;
/**
* 每页数量,默认100
*/
@JsonProperty("page_size")
private Integer pageSize;
/**
* 批次开始时间(范围开始)
*/
@JsonProperty("batch_start_time_from")
private Long batchStartTimeFrom;
/**
* 批次开始时间(范围结束)
*/
@JsonProperty("batch_start_time_to")
private Long batchStartTimeTo;
/**
* 批次状态 1 领取中,2 已领完,3 已结束
*/
@JsonProperty("batch_status")
private Integer batchStatus;
/**
* 排序 1 创建时间正序,2 创建时间倒序,3 开始时间正序,4 开始时间倒序,5 初始数量正序, 6 初始数量倒序,7 领取数量正序,8 领取数量倒序;默认2
*/
@JsonProperty("sort_by")
private Integer sortBy;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.promotion.merchant.coupon.list.get";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddPromotionMerchantCouponListGetResponse> getResponseClass() {
return PddPromotionMerchantCouponListGetResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(page != null) {
paramsMap.put("page", page.toString());
}
if(pageSize != null) {
paramsMap.put("page_size", pageSize.toString());
}
if(batchStartTimeFrom != null) {
paramsMap.put("batch_start_time_from", batchStartTimeFrom.toString());
}
if(batchStartTimeTo != null) {
paramsMap.put("batch_start_time_to", batchStartTimeTo.toString());
}
if(batchStatus != null) {
paramsMap.put("batch_status", batchStatus.toString());
}
if(sortBy != null) {
paramsMap.put("sort_by", sortBy.toString());
}
return paramsMap;
}
public void setPage(Integer page) {
this.page = page;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setBatchStartTimeFrom(Long batchStartTimeFrom) {
this.batchStartTimeFrom = batchStartTimeFrom;
}
public void setBatchStartTimeTo(Long batchStartTimeTo) {
this.batchStartTimeTo = batchStartTimeTo;
}
public void setBatchStatus(Integer batchStatus) {
this.batchStatus = batchStatus;
}
public void setSortBy(Integer sortBy) {
this.sortBy = sortBy;
}
} |
package connectors.mongodb;
import chat.errors.CoreException;
import chat.logs.LoggerEx;
import chat.utils.ConcurrentHashSet;
import com.mongodb.ClientSessionOptions;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
public class MongoClientHelper {
private static final String TAG = MongoClientHelper.class.getSimpleName();
private String hosts;//"mongodb://localhost:27017,localhost:27018,localhost:27019"
// private static MongoClientHelper instance;
private static int[] lock = new int[0];
// private MongoClient mongoClient;
private Integer connectionsPerHost;
private Integer threadsAllowedToBlockForConnectionMultiplier;
private Integer maxWaitTime;
private Integer connectTimeout;
private Integer socketTimeout;
private Boolean socketKeepAlive;
private ConcurrentHashMap<String, MongoClient> clientMap = new ConcurrentHashMap<>();
public MongoClientHelper() {
// instance = this;
}
// public static MongoClientHelper getInstance() {
// return instance;
// }
// public void connect() throws CoreException {
// connect(null);
// }
private MongoClient connect(String dbName) throws CoreException {
// if(toHosts == null)
// toHosts = hosts;
MongoClient mongoClient = clientMap.get(dbName);
if(mongoClient == null) {
synchronized (clientMap) {
mongoClient = clientMap.get(dbName);
if(mongoClient == null) {
LoggerEx.info(TAG, "Connecting hosts " + hosts);
try {
MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder();
if(connectionsPerHost != null)
optionsBuilder.connectionsPerHost(connectionsPerHost);
if(threadsAllowedToBlockForConnectionMultiplier != null)
optionsBuilder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
if(maxWaitTime != null)
optionsBuilder.maxWaitTime(maxWaitTime);
if(connectTimeout != null)
optionsBuilder.connectTimeout(connectTimeout);
if(socketTimeout != null)
optionsBuilder.socketTimeout(socketTimeout);
if(socketKeepAlive != null)
optionsBuilder.socketKeepAlive(socketKeepAlive);
// CodecRegistry registry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromCodecs(new CleanDocumentCodec()));
// optionsBuilder.codecRegistry(registry);
// if(mongoClient != null) {
// mongoClient.close();
// LoggerEx.info(TAG, "Connected hosts " + hosts + " closing old hosts client " + hosts + " now.");
// }
MongoClientURI connectionString = new MongoClientURI(hosts + "/" + dbName, optionsBuilder);
mongoClient = new MongoClient(connectionString);
clientMap.put(dbName, mongoClient);
LoggerEx.info(TAG, "Connected hosts " + hosts + " db " + dbName);
} catch (Throwable t) {
t.printStackTrace();
LoggerEx.fatal(TAG, "Build mongo uri for hosts " + hosts + " failed, " + t.getMessage());
}
}
}
}
return mongoClient;
}
public void disconnect() {
synchronized (lock) {
if(hosts != null) {
Collection<MongoClient> clients = clientMap.values();
for(MongoClient mongoClient : clients) {
if(mongoClient != null) {
mongoClient.close();
}
}
hosts = null;
}
}
}
public MongoDatabase getMongoDatabase(String databaseName) {
MongoClient client = clientMap.get(databaseName);
if(client == null) {
try {
connect(databaseName);
} catch (CoreException e) {
e.printStackTrace();
LoggerEx.error(TAG, "connect database " + databaseName + " failed, " + e.getMessage());
}
}
client = clientMap.get(databaseName);
if(client != null) {
return client.getDatabase(databaseName);
}
return null;
}
public ClientSession startSession(String databaseName) {
MongoClient client = clientMap.get(databaseName);
if(client != null) {
return client.startSession();
}
return null;
}
public ClientSession startSession(String databaseName, ClientSessionOptions options) {
MongoClient client = clientMap.get(databaseName);
if(client != null) {
return client.startSession(options);
}
return null;
}
public String getHosts() {
return hosts;
}
public Integer getConnectionsPerHost() {
return connectionsPerHost;
}
public void setConnectionsPerHost(Integer connectionsPerHost) {
this.connectionsPerHost = connectionsPerHost;
}
public Integer getThreadsAllowedToBlockForConnectionMultiplier() {
return threadsAllowedToBlockForConnectionMultiplier;
}
public void setThreadsAllowedToBlockForConnectionMultiplier(
Integer threadsAllowedToBlockForConnectionMultiplier) {
this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
}
public Integer getMaxWaitTime() {
return maxWaitTime;
}
public void setMaxWaitTime(Integer maxWaitTime) {
this.maxWaitTime = maxWaitTime;
}
public Integer getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Integer getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
}
public Boolean getSocketKeepAlive() {
return socketKeepAlive;
}
public void setSocketKeepAlive(Boolean socketKeepAlive) {
this.socketKeepAlive = socketKeepAlive;
}
public void setHosts(String hosts) {
this.hosts = hosts;
}
}
|
package com.tqb.utils;
import java.util.List;
public class PageBean<E> {
private int currentPage; // 当前页
private int pageSize; // 每页显示多少条记录
// 查询数据库
private List<E> recordList; // 本页的数据列表
private int recordCount; // 总记录数
// 计算
private int pageCount; // 总页数
private int beginPageIndex; // 页码列表的开始索引(包含)
private int endPageIndex; // 页码列表的结束索引(包含)
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<E> getRecordList() {
return recordList;
}
public void setRecordList(List<E> recordList) {
this.recordList = recordList;
}
public int getRecordCount() {
return recordCount;
}
public void setRecordCount(int recordCount) {
this.recordCount = recordCount;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getBeginPageIndex() {
return beginPageIndex;
}
public void setBeginPageIndex(int beginPageIndex) {
this.beginPageIndex = beginPageIndex;
}
public int getEndPageIndex() {
return endPageIndex;
}
public void setEndPageIndex(int endPageIndex) {
this.endPageIndex = endPageIndex;
}
}
|
package com.lagardien.ocpviolation;
/**
* Ijaaz Lagardien
* 214167542
* Group 3A
* Dr B. Kabaso
* Date: 13 March 2016
*/
public class Rectangle extends Shape
{
Rectangle()
{
super.type = 1;
}
}
|
package uow.finalproject.webapp.entityType;
public enum Suburb {
NSW("NSW"), //New South Wales
QLD("QLD"), //Queensland
SA("SA"), //South Australia
TAS("TAS"), //Tasmania
VIC("VIC"), //Victoria
WA("WA"); //Western Australia
private String name;
Suburb(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
|
package com.adv.mapper;
import com.adv.pojo.BuyTables;
import com.adv.pojo.BuyTablesExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface BuyTablesMapper {
int countByExample(BuyTablesExample example);
int deleteByExample(BuyTablesExample example);
int deleteByPrimaryKey(Integer id);
int insert(BuyTables record);
int insertSelective(BuyTables record);
List<BuyTables> selectByExample(BuyTablesExample example);
BuyTables selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") BuyTables record, @Param("example") BuyTablesExample example);
int updateByExample(@Param("record") BuyTables record, @Param("example") BuyTablesExample example);
int updateByPrimaryKeySelective(BuyTables record);
int updateByPrimaryKey(BuyTables record);
} |
package com.company.resume.Repositories;
import com.company.resume.Models.Skill;
import org.springframework.data.repository.CrudRepository;
public interface SkillsRepository extends CrudRepository<Skill, Long> {
Iterable <Skill> findAllSkillByNameContainingIgnoreCase(String query);
}
|
package update;
import dbConnector.MsSqlHandler;
import java.awt.Toolkit;
import java.sql.*;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import login.LoginDataBase;
/**
*
* @author Barış Dalyan Emre
*/
public class UpdateCustomer extends javax.swing.JFrame {
private MsSqlHandler handler = null;
private String connectionString = LoginDataBase.getDbConnectiString(); // Your DB link.
private String user = LoginDataBase.getUserName();
private String password = LoginDataBase.getPassword();
private JTable tblCustomers = null;
private DefaultTableModel tblModel = null;
public UpdateCustomer() {
initComponents();
}
/**
* Paste initComponents() with Annotation: @SuppressWarnings("unchecked") here.
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code.
*
*/
private void btnUpdateCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateCustomerActionPerformed
int id, choice;
String customerName, address, phoneNum;
String queryUpdate = "UPDATE tbl_Customer SET Customer_Name = ?, Address = ?, "
+ "Phone = ? WHERE Customer_Id = ?";
try {
choice = tblCustomers.getSelectedRow();
PreparedStatement preparedStatement = handler.executeUpdateQuerys(queryUpdate);
id = Integer.parseInt(tblModel.getValueAt(choice, 3).toString().trim());
customerName = tfCustomerName.getText();
phoneNum = tfPhone.getText();
address = tfAddress.getText();
if (!customerName.equals("") && !phoneNum.equals("") && !address.equals("")) { // Check, did user fill all fields.
preparedStatement.setString(1, tfCustomerName.getText());
preparedStatement.setString(2, tfAddress.getText());
preparedStatement.setString(3, tfPhone.getText());
preparedStatement.setInt(4, id);
tblModel.setValueAt(customerName, choice, 0);
tblModel.setValueAt(phoneNum, choice, 1);
tblModel.setValueAt(address, choice, 2);
preparedStatement.executeUpdate(); // queryUpdate is processed and datas are updated.
lblInfo.setText("*Update successful !");
handler.closeConnection(); // Cuts connection.
} else {
lblInfo.setText("*Please fill necessary fields!");
}
} catch (SQLException exception) {
System.out.println("Error Code: " + exception.getErrorCode());
System.out.println("Error: ");
exception.printStackTrace();
}
}//GEN-LAST:event_btnUpdateCustomerActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
try {
handler = new MsSqlHandler(user, password, connectionString);
System.out.println("Connected..."); // You can delete this code.
int choice = tblCustomers.getSelectedRow();
// Selected row datas are auto-inserted to text fields.
tfCustomerName.setText(tblModel.getValueAt(choice, 0).toString().trim());
tfPhone.setText(tblModel.getValueAt(choice, 1).toString().trim());
tfAddress.setText(tblModel.getValueAt(choice, 2).toString().trim());
} catch (SQLException exception) {
System.out.println("Error Code: " + exception.getErrorCode());
System.out.println("Error: ");
exception.printStackTrace();
}
}//GEN-LAST:event_formWindowOpened
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
handler.closeConnection();
System.gc(); // JVM returns unused objects in order to recycle to RAM.
}//GEN-LAST:event_formWindowClosing
// Access is opened from tblCustomers for tblModel and tblCustomers.
public void setTblCustomers(JTable tblCustomers) {
this.tblCustomers = tblCustomers;
}
public void setTblModel(DefaultTableModel tblModel) {
this.tblModel = tblModel;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnUpdateCustomer;
private javax.swing.JPanel jPanel;
private javax.swing.JLabel lblAddress;
private javax.swing.JLabel lblInfo;
private javax.swing.JLabel lblName;
private javax.swing.JLabel lblNumberWarning;
private javax.swing.JLabel lblPhone;
private javax.swing.JTextField tfAddress;
private javax.swing.JTextField tfCustomerName;
private javax.swing.JTextField tfPhone;
// End of variables declaration//GEN-END:variables
}
|
package com.codetop._1;
import org.junit.Test;
public class Merge {
/**
* 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
* 输出:[1,2,2,3,5,6]
* 示例 2:
*
* 输入:nums1 = [1], m = 1, nums2 = [], n = 0
* 输出:[1]
* 思路:
* 将nums2先加入到nums1中
* i指向nums1的起点
* j指向nums2的起点
* 如果nums1[i] > nums[j] 就swap,该思路最终没有通过
*
* 思路2:
* 先不对nums1进行填充
* 使用i、j分别作为nums1和nums2的起始位置
* if(nums1[i] > nums2[j]){
* //插入元素nums2[j]
* //nums1[i]以及i以后的所有元素往后移动
* j++
* }
*
* 思路3:
* 对nums1进行填充,填充的数字为有效元素的最后一位
*
* 思路4:
* 双指针同时从最后开始遍历
*
* @param nums1
* @param m
* @param nums2
* @param n
*/
public void merge4(int[] nums1, int m, int[] nums2, int n){
int i = m - 1; //从末尾开始
int j = n - 1; //从末尾开始
int k = m + n - 1; //从末尾开始
while (j >= 0) {
if (i < 0) {
while (j >= 0) {
nums1[k--] = nums2[j--];
}
return;
}
//哪个数大就对应的添加哪个数。
if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}
}
public void merge3(int[] nums1, int m, int[] nums2, int n){
if(n == 0){
return;
}
//fill nums1
if(m-1<0){
for (int i = 0; i < nums1.length; i++) {
nums1[i] = nums2[i];
}
return;
}
int nums1Max = nums1[m-1];
int nums2Min = nums2[0];
for (int i = m; i < nums1.length; i++) {
nums1[i] = nums1Max;
}
int i = nums1.length - 1;
int j = nums2.length - 1;
while(i>=0){
//nums1中后面的元素
if(i >= m ){
if(nums2[j] > nums1[i]){
nums1[i] = nums2[j];
}
i--;
j--;
continue;
}
if(nums1[i] > nums2Min){
nums1[i] = nums2Min;
}
i--;
continue;
}
}
public void merge2(int[] nums1, int m, int[] nums2, int n) {
if(nums2.length == 0){
return;
}
if(m == 0){
for (int i = 0; i < nums1.length; i++) {
nums1[i] = nums2[i];
}
return;
}
int i = 0;
int j = 0;
while(j<n){
if(nums1[i] > nums2[j]){
//先将元素nums1[i]及其以后的元素往后挪一位,挪动的数量为m-i个位置
moveArrayOneStep(nums1,i);
//插入元素nums2[j]到nums1[i]
nums1[i] = nums2[j];
j++;
}
if(i == m-1+j){//代表遍历到了原有nums1的末尾
if(j<n){
//将nums2[j]以后的元素拼在nums1[i+1]及其以后
for (int k = i+1; k < nums1.length; k++) {
nums1[k] = nums2[j];
j++;
}
}
}
i++;
}
}
private void moveArrayOneStep(int[] nums1, int i) {
for (int j = nums1.length-1; j >i ; j--) {
nums1[j] = nums1[j-1];
}
}
@Test
public void test2(){
int[] arr = new int[]{1,2,3,4,0,0,0};
moveArrayOneStep(arr,2);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public void merge(int[] nums1, int m, int[] nums2, int n) {
if(nums2.length == 0){
return;
}
//add nums2 to nums1
for (int i = m,j=0; i < nums1.length; i++) {
nums1[i] = nums2[j];
j++;
}
for (int i = 0; i < nums1.length-1; i++) {
if(nums1[i] > nums1[i+1]){
swap(nums1,i,i+1);
}
}
}
private void swap(int[] nums,int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
/**
*
* [1,2,3,0,0,0]
* 3
* [2,5,6]
* 3
*
* [2,0]
* 1
* [1]
* 1
*
* [2,0]
* 1
* [1]
* 1
*
* [4,0,0,0,0,0]
* 1
* [1,2,3,5,6]
* 5
*
* [1,2,3,0,0,0]
* 3
* [2,5,6]
* 3
*
* [1,2,4,5,6,0]
* 5
* [3]
* 1
*
* [1,2,3,0,0,0]
* 3
* [2,5,6]
* 3
*
* [4,5,6,0,0,0]
* 3
* [1,2,3]
* 3
*
* [1,2,3,0,0,0]
* 3
* [2,5,6]
* 3
*
* [0]
* 0
* [1]
* 1
*
* 最后执行的输入:
* [2,0]
* 1
* [1]
* 1
*
* [2,0]
* 1
* [1]
* 1
*
*/
@Test
public void test(){
int[] nums1 = new int[]{2,0};
int m = 1;
int[] nums2 = new int[]{1};
int n = 1;
merge4(nums1,m,nums2,n);
for (int i = 0; i < nums1.length; i++) {
System.out.println(nums1[i]);
}
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.procesos.cuadrecifras.filtro.totalesestacion.estructura;
public enum TotalesEstacionEstructuraRegistro
{
ESTACION("Estacion", 0, 0, 6, false),
TOTAL("Codigo_Total", 1, 7, 6, true),
CANAL("Canal", 2, 17, 1, true),
CANTIDAD_EVENTOS("Cantidad_Eventos", 3, 18, 6, false),
VALOR_EVENTOS("Valor_Eventos", 4, 24, 16, false);
public String nombre;
public int orden;
public int posIni;
public int longitud;
public boolean esFiltro;
private TotalesEstacionEstructuraRegistro(final String nombre, final int orden, final int posIni, final int longitud, final boolean esFiltro) {
this.nombre = nombre;
this.orden = orden;
this.posIni = posIni;
this.longitud = longitud;
this.esFiltro = esFiltro;
}
}
|
package edu.betygreg.domain;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by Jaeger on 2016-05-31.
*/
public class AssignmentList {
private HashMap<String, Assignment> assignmentHList = new HashMap<>();
private String name;//TODO tänk här
private String id;
public AssignmentList() {
addTempAssignmentHash();
}
public HashMap<String, Assignment> getAssignmentHList() {
return assignmentHList;
}
/*
public String getAssignmentGrade(String key) {
return assignmentHList.get(key).getGrade();
}
public Grade getAssignmentGradeObject(String key) {
return assignmentHList.get(key).getGradeObject();
}
*/
public Grade setAssignmentGrade(String key, String grade) {
return assignmentHList.get(key).setGrade(grade);
}
public void renameAssignment(String key, String name) {
assignmentHList.get(key).setName(name);
}
public String getAssignmentName(String key) {
return assignmentHList.get(key).getName();
}
public String getAssignments(String key) {
String assignments = "";
Iterator it = assignmentHList.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
//System.out.println(pair.getKey() + " = " + pair.getValue());
assignments = assignments + pair.getKey() + ", ";
//it.remove(); // avoids a ConcurrentModificationException
}
return assignments;
}
private void addTempAssignmentHash() {
Assignment assignment0 = new Assignment("0", "Task0");
Assignment assignment1 = new Assignment("1", "Task1");
Assignment assignment2 = new Assignment("2", "Task2");
assignmentHList.put(assignment0.getId(), assignment0);
assignmentHList.put(assignment1.getId(), assignment1);
assignmentHList.put(assignment2.getId(), assignment2);
}
} |
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.codec;
import org.springframework.core.NestedRuntimeException;
import org.springframework.lang.Nullable;
/**
* General error that indicates a problem while encoding and decoding to and
* from an Object stream.
*
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
* @since 5.0
*/
@SuppressWarnings("serial")
public class CodecException extends NestedRuntimeException {
/**
* Create a new CodecException.
* @param msg the detail message
*/
public CodecException(String msg) {
super(msg);
}
/**
* Create a new CodecException.
* @param msg the detail message
* @param cause root cause for the exception, if any
*/
public CodecException(String msg, @Nullable Throwable cause) {
super(msg, cause);
}
}
|
package it.sevenbits.codecorrector.formatter.javaformatter;
import it.sevenbits.codecorrector.formatter.IProperties;
import org.junit.Test;
import static junit.framework.Assert.fail;
import static junitx.framework.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Created by remmele on 06.07.16.
*/
public class JavaConverterConfigTest {
@Test
public void testSetSpaceState() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.setState(State.Space);
assertEquals("wrong result.", State.Space, config.getState());
}
@Test
public void testSetEndLineState() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.setState(State.EndLine);
assertEquals("wrong result.", State.EndLine, config.getState());
}
@Test
public void testStringAppendInBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer("Hello World!");
assertEquals("wrong result.", "Hello World!", config.getContentOfBuffer());
}
@Test
public void testFiveStringAppendInBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer("ABC");
config.appendInBuffer("123");
config.appendInBuffer("EFG");
config.appendInBuffer("456");
config.appendInBuffer("!!!");
assertEquals("wrong result.", "ABC123EFG456!!!", config.getContentOfBuffer());
}
@Test
public void testIntegerAppendInBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer(100500);
assertEquals("wrong result.", "100500", config.getContentOfBuffer());
}
@Test
public void testFiveIntegerAppendInBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer(1);
config.appendInBuffer(2);
config.appendInBuffer(3);
config.appendInBuffer(4);
config.appendInBuffer(5);
assertEquals("wrong result.", "12345", config.getContentOfBuffer());
}
@Test
public void testCharacterAppendInBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer('A');
assertEquals("wrong result.", "A", config.getContentOfBuffer());
}
@Test
public void testFiveCharacterAppendInBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer('A');
config.appendInBuffer('B');
config.appendInBuffer('C');
config.appendInBuffer('D');
config.appendInBuffer('E');
assertEquals("wrong result.", "ABCDE", config.getContentOfBuffer());
}
@Test
public void testClearBuffer() {
IProperties mockProperties = mock(IProperties.class);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.appendInBuffer(123);
config.appendInBuffer("ABCDEFG");
config.clearBuffer();
assertEquals("wrong result.", "", config.getContentOfBuffer());
}
@Test
public void testGetIndent() {
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndent()).thenReturn(" ");
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
assertEquals("wrong result.", " ", config.getIndent());
}
@Test
public void testGetEndLine() {
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getEndLine()).thenReturn("\n");
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
assertEquals("wrong result.", "\n", config.getEndLine());
}
@Test
public void testIncreaseLevel() {
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndentStartLevel()).thenReturn(0);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.increaseIndentLevel();
config.increaseIndentLevel();
config.increaseIndentLevel();
assertEquals("wrong result.", new Integer(3), config.getIndentLevel());
}
@Test
public void testDecreaseLevel() throws JavaConverterException {
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndentStartLevel()).thenReturn(5);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.decreaseIndentLevel();
config.decreaseIndentLevel();
assertEquals("wrong result.", new Integer(3), config.getIndentLevel());
}
@Test(expected = JavaConverterException.class)
public void testDecreaseLevelException() throws JavaConverterException {
IProperties mockProperties = mock(IProperties.class);
when(mockProperties.getIndentStartLevel()).thenReturn(0);
JavaConverterConfig config = new JavaConverterConfig(mockProperties);
config.decreaseIndentLevel();
fail();
}
}
|
/***********************************************************
* @Description : 日志接口
* @author : 梁山广(Liang Shan Guang)
* @date : 2020/5/17 14:40
* @email : liangshanguang2@gmail.com
***********************************************************/
package 第04章_工厂方法模式.第3节_应用举例;
public interface Logger {
public void writeLog();
}
|
/*
* 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 Controlador;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author agonzalez
*/
public class Modificar extends Conexion{
public boolean formulario_atendido(int cod_coordinacion){
PreparedStatement pst = null;
try{
String modificar2 = "UPDATE solicitud_vehiculo SET FINALIZADO = \"si\" WHERE COD_SOLICITUD_VEHICULO =?";
pst = getConexion().prepareStatement(modificar2);
pst.setInt(1, cod_coordinacion);
if(pst.executeUpdate() == 1){
return true;
}
} catch(Exception ex){
System.err.println("Error" + ex);
}finally{
try{
if(getConexion() != null) getConexion().close();
if(pst != null) pst.close();
}catch(Exception e){
System.err.println("Error"+ e);
}
}
return false;
}
public static void main(String[] args){
Modificar co = new Modificar();
System.out.println(co.formulario_atendido(1));
}
}
|
/*
* Created on Mar 2, 2007
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.modules.client.classcmplc.form;
/**
* @author bruno.zanetti
*
*
* Window - Preferences - Java - Code Style - Code Templates
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public interface ClassCmplcDetailable {
/**
*
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public String getSelectedClassCmplcCode();
/**
*
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public void setSelectedClassCmplcCode(String selectedClassCmplc_);
} |
package com.oldlie.common.utils.accountcreator;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author OLDLIE
* @date 2020/10/16
*/
public class NameListener extends AnalysisEventListener<Name> {
private Name name;
private List<String> nameList;
public List<String> getNameList () {
return this.nameList;
}
public NameListener() {
this.name = new Name();
this.nameList = new ArrayList<>();
}
@Override
public void invoke(Name name, AnalysisContext analysisContext) {
this.nameList.add(name.getName());
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
|
//Figure 2-34
import Semaphore;
public class ReaderWriter extends Thread {
// Shared objects
// controls access to rc
public static Semaphore mutex = new Semaphore(1);
// controls access to the database
public static Semaphore db = new Semaphore(1);
// # of processes reading
public static int rc = 0;
class DBReader extends Thread {
private int myNumber; // Id for the Reader
public DBReader(int i) { // Constructor for the Reader
myNumber = i;
}
public void run(){ // What a reader does
while(true) {
mutex.down(); // Get exclusive access to rc
rc = rc + 1; // One reader more now
if (rc == 1) // If this is the first reader
db.down(); // Get access to database
mutex.up(); // Release access to rc
read_data_base(); // Access the data
mutex.down(); // Get exclusive access to rc
rc = rc - 1; // One reader fewer now
if (rc == 0)
ReaderWriter.db.up(); // If this is the last reader
ReaderWriter.mutex.up(); // Release access to rc
use_data_read(); // Noncritical region
}
}
public void read_data_base(){
System.out.println("Reader " + myNumber + " is reading data base");
try {
sleep(1000);
} catch (InterruptedException ex){ }
}
public void use_data_read(){
System.out.println("Reader " + myNumber + " is using the data ");
try {
sleep(5000);
} catch (InterruptedException ex){ }
}
} //end of Reader Class
private class DBWriter extends Thread {
private int myNumber; // Id for the Reader
public DBWriter(int i) { // Constructor for the Reader
myNumber = i;
}
public void run(){ // What a writer does
while(true) {
think_up_data(); // Noncritical region
db.down(); // Get exclusive access to database
write_data_base(); // Update the data
db.up(); // Release access to the database
}
}
public void think_up_data(){
System.out.println("Writer " + myNumber + " is thinking up data ");
try {
sleep(10000);
} catch (InterruptedException ex){ }
}
public void write_data_base(){
System.out.println("Writer " + myNumber + " is writing data ");
try {
sleep(1000);
} catch (InterruptedException ex){ }
}
} //end of Writer Class
// How to start things up
public void run(){
final int READERS = 3;
final int WRITERS = 4;
DBReader r;
DBWriter w;
for(int i=0; i<READERS; i++) {
// Create and start each reader
r = new DBReader(i);
r.start();
}
for(int i=0; i<WRITERS; i++) {
// Create and start each writer
w = new DBWriter(i);
w.start();
}
}
// Start the program
public static void main(String args[]) {
ReaderWriter rw = new ReaderWriter();
rw.start();
}
}
|
package com.example.fileupload.QuestionDTO;
import org.springframework.data.annotation.Id;
import java.util.List;
public class QuestionDTO {
private int quesId;
private String question;
private String answerType;
private String quesType;
private List<String> options;
private String category;
private String binaryFilePath;
private boolean screenedFlag;
private String correctAns;
private String difficultyLevel;
public QuestionDTO() {
}
public String getDifficultyLevel() {
return difficultyLevel;
}
public void setDifficultyLevel(String difficultyLevel) {
this.difficultyLevel = difficultyLevel;
}
public String getAnswerType() {
return answerType;
}
public void setAnswerType(String answerType) {
this.answerType = answerType;
}
public String getQuesType() {
return quesType;
}
public void setQuesType(String quesType) {
this.quesType = quesType;
}
public int getQuesId() {
return quesId;
}
public void setQuesId(int quesId) {
this.quesId = quesId;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBinaryFilePath() {
return binaryFilePath;
}
public void setBinaryFilePath(String binaryFilePath) {
this.binaryFilePath = binaryFilePath;
}
public boolean getScreenedFlag() {
return screenedFlag;
}
public void setScreenedFlag(boolean screenedFlag) {
this.screenedFlag = screenedFlag;
}
public String getCorrectAns() {
return correctAns;
}
public void setCorrectAns(String correctAns) {
this.correctAns = correctAns;
}
@Override
public String toString() {
return "QuestionDTO{" +
"quesId=" + quesId +
", question='" + question + '\'' +
", answerType='" + answerType + '\'' +
", quesType='" + quesType + '\'' +
", options=" + options +
", category='" + category + '\'' +
", binaryFilePath='" + binaryFilePath + '\'' +
", screenedFlag=" + screenedFlag +
", correctAns='" + correctAns + '\'' +
", difficultyLevel='" + difficultyLevel + '\'' +
'}';
}
}
|
package com.appspot.smartshop.adapter;
import java.util.List;
import com.appspot.smartshop.R;
import com.appspot.smartshop.dom.UserInfo;
import com.appspot.smartshop.ui.user.AddFriendActivity;
import com.appspot.smartshop.utils.DataLoader;
import com.appspot.smartshop.utils.SimpleAsyncTask;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class AddFriendAdapter extends ArrayAdapter<UserInfo>{
public static final String TAG = "[AddFriendAdapter]";
private Context context;
private LayoutInflater inflater;
private SimpleAsyncTask task;
public AddFriendAdapter(Context context, int textViewResourceId,
List<UserInfo> objects) {
super(context, textViewResourceId, objects);
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.add_friend_item, null);
holder.friendAvatar = (ImageView) convertView.findViewById(R.id.friend_avatar);
holder.friendAddress = (TextView) convertView.findViewById(R.id.txtFriendAddress);
holder.friendEmail = (TextView) convertView.findViewById(R.id.txtFriendEmail);
holder.friendName = (TextView) convertView.findViewById(R.id.txtFriendName);
holder.chBxSelectFriend = (CheckBox) convertView.findViewById(R.id.chBxSelectFriendToAdd);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
final UserInfo friendInfo = getItem(position);
//TODO: VANLOI999 remember set up avatar for friend
holder.friendAddress.setText(friendInfo.address);
holder.friendName.setText(friendInfo.first_name + friendInfo.last_name);
holder.friendEmail.setText(friendInfo.email);
holder.chBxSelectFriend.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Log.d(TAG, AddFriendActivity.friendsToAdd);
if(AddFriendActivity.friendsToAdd.length()==0){
AddFriendActivity.friendsToAdd += friendInfo.username;
}else if(!AddFriendActivity.friendsToAdd.contains(friendInfo.username)){
AddFriendActivity.friendsToAdd += ","+ friendInfo.username;
}
}
}
});
return convertView;
}
static class ViewHolder{
ImageView friendAvatar;
TextView friendName;
TextView friendEmail;
TextView friendAddress;
CheckBox chBxSelectFriend;
}
}
|
package com.zhangdxchn.lib.weixin.bean.menu;
public class MeidaButton extends Button {
private String media_id;
public String getMedia_id() {
return media_id;
}
public void setMedia_id(String media_id) {
this.media_id = media_id;
}
} |
package com.yg.constant;
public class WebConstant {
//HttpSession里面代表经理的level值
public static final String MGR_LEVEL = "mgr";
//HttpSession里面代表员工的level值
public static final String EMP_LEVEL = "emp";
//HttpSession里面代表用户级别的属性名
public static final String LEVEL = "level";
//HttpSession里面代表用户名的属性名
public static final String USER = "user";
}
|
package com.assignment.project_one.project_one;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
public class BookController {
@Value("${server.port}")
int port;
@Autowired
BookRepository bookRepository;
@RequestMapping(value = "/port")
public String getPort() {
return "Port used is " + port;
}
@GetMapping("/books")
public List<Book> getAllbook() {
return bookRepository.findAll();
}
@RequestMapping(value = "/insertBook", method = RequestMethod.POST)
public void insertBook(@RequestBody Book book) {
bookRepository.save(book);
}
@RequestMapping(value = "getBookById", method = RequestMethod.POST)
public Book getBookById(@RequestParam(value = "id") int id) {
Optional<Book> result = bookRepository.findById(Long.valueOf(id));
return result.get();
}
@GetMapping("/getBookById/{id}")
public Book getBookByPathId(@PathVariable int id) {
Optional<Book> result = bookRepository.findById(Long.valueOf(id));
return result.get();
}
// @PutMapping(value = "updateAuthor")
// public void updateAuthor(@RequestBody ReplaceName replaceName) {
// try {
// bookRepository.updateAuthor(replaceName.getName(), replaceName.getReplaceWith());
// }catch (Exception e){
// System.out.println(e.getMessage());
// }
// }
@PutMapping(value = "updateAuthor/{name}/{replace}")
public void updateAuthor(@PathVariable String name, @PathVariable String replace) {
try {
bookRepository.updateAuthor(name, replace);
}catch (Exception e){
System.out.println(e.getMessage());
}
}
@DeleteMapping(value = "deleteByCost/{cost}")
public void deleteByCost(@PathVariable int cost){
bookRepository.deleteByCost(cost);
}
}
|
package com.legaoyi.protocol.messagebody.encoder;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.legaoyi.protocol.down.messagebody.JTT808_8401_MessageBody;
import com.legaoyi.protocol.exception.IllegalMessageException;
import com.legaoyi.protocol.message.MessageBody;
import com.legaoyi.protocol.message.encoder.MessageBodyEncoder;
import com.legaoyi.protocol.util.ByteUtils;
import com.legaoyi.protocol.util.MessageBuilder;
/**
*
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2015-01-30
*/
@Component(MessageBodyEncoder.MESSAGE_BODY_ENCODER_BEAN_PREFIX + "8401_2011" + MessageBodyEncoder.MESSAGE_BODY_ENCODER_BEAN_SUFFIX)
public class JTT808_8401_MessageBodyEncoder implements MessageBodyEncoder {
@Override
public byte[] encode(MessageBody message) throws IllegalMessageException {
try {
JTT808_8401_MessageBody messageBody = (JTT808_8401_MessageBody) message;
MessageBuilder mb = new MessageBuilder();
mb.addByte(messageBody.getType());
if (messageBody.getType() != 0) {
List<Map<String, Object>> itemList = messageBody.getItemList();
int size = itemList.size();
if (size > 0) {
mb.addByte(size);
for (Map<String, Object> map : itemList) {
int type = (Integer) map.get("type");
String name = (String) map.get("name");
String tel = (String) map.get("tel");
mb.addByte(type);
byte[] bytes = ByteUtils.gbk2bytes(tel);
mb.addByte(bytes.length);
mb.append(bytes);
bytes = ByteUtils.gbk2bytes(name);
mb.addByte(bytes.length);
mb.append(bytes);
}
} else {
mb.addByte(0);
}
}
return mb.getBytes();
} catch (Exception e) {
throw new IllegalMessageException(e);
}
}
}
|
package tailminuseff.config;
import eventutil.EventListenerList;
import java.beans.*;
import java.util.concurrent.*;
import javax.inject.Inject;
public class PropertyChangeEventDebouncer {
private final long maximumEventFrequencyMs = 500;
private final Object lock = new Object();
private final EventListenerList<PropertyChangeListener> outputEventListeners = new EventListenerList<PropertyChangeListener>(lock);
private final ScheduledExecutorService scheduledExecutorService;
@Inject
public PropertyChangeEventDebouncer(ScheduledExecutorService scheduledExecutorService) {
this.inputListener = evt -> {
if (future != null) {
future.cancel(false);
}
future = scheduledExecutorService.schedule(() -> {
synchronized (lock) {
final PropertyChangeEvent newEvt = new PropertyChangeEvent(PropertyChangeEventDebouncer.this, null, null, null);
outputEventListeners.forEachLisener(listener -> listener.propertyChange(newEvt));
return null;
}
}, maximumEventFrequencyMs, TimeUnit.MILLISECONDS);
};
this.scheduledExecutorService = scheduledExecutorService;
}
public PropertyChangeListener getInputListener() {
return inputListener;
}
private ScheduledFuture<Void> future;
private final PropertyChangeListener inputListener;
public void addPropertyChangeListener(PropertyChangeListener listener) {
outputEventListeners.addListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
outputEventListeners.removeListener(listener);
}
}
|
package it.ialweb.poi;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class NewPostDialog extends DialogFragment {
public static final String POSTTEXT = "POSTTEXT";
private EditText postText;
private Callback callback;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Callback)
callback = (Callback) activity;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View vView = inflater.inflate(R.layout.fragment_new_post_dialog, null);
postText = (EditText) vView.findViewById(R.id.editText_post);
if (savedInstanceState != null)
postText.setText(savedInstanceState.getString(POSTTEXT));
builder.setView(vView)
// Add action buttons
.setPositiveButton(R.string.post, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onPost(postText.getText().toString());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NewPostDialog.this.getDialog().cancel();
}
});
return builder.create();
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(POSTTEXT, postText.getText().toString());
super.onSaveInstanceState(outState);
}
public interface Callback {
void onPost(String txt);
}
}
|
/*
* 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 Servlets;
import HibFiles.Notification;
import HibFiles.PoolManager;
import HibFiles.Rating;
import HibFiles.Recipe;
import HibFiles.UserLogin;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
/**
*
* @author User
*/
public class PostRating extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String msg = "";
try {
//Get attributes from http request
String rid = request.getParameter("rid");
String rating = request.getParameter("rating");
System.out.println("Rating for recipe rid = " + rid + " is " + rating);
//Create hibernate session
Session s = PoolManager.getSessionFactory().openSession();
//Initiate transaction
Transaction t = s.beginTransaction();
//Load recipe with given rid
Recipe r = (Recipe) s.load(Recipe.class, Integer.parseInt(rid));
Double d = Double.parseDouble(rating);
//Get currently logged in user
UserLogin ul = (UserLogin) request.getSession().getAttribute("user");
Criteria c1 = s.createCriteria(Rating.class);
c1.add(Restrictions.eq("recipe", r));
c1.add(Restrictions.eq("user", ul.getUser()));
Rating rt = (Rating) c1.uniqueResult();
if (rt == null) {
//Create rating object
Rating rat = new Rating();
rat.setRecipe(r);
rat.setStars(d);
rat.setUser(ul.getUser());
//Save rating object
s.save(rat);
Criteria c2 = s.createCriteria(Rating.class);
c2.add(Restrictions.eq("recipe", r));
List<Rating> rl = c2.list();
double tot_rating = 0;
for (Rating ra : rl) {
tot_rating = tot_rating + ra.getStars();
}
double overall_rating = tot_rating / rl.size();
r.setOverallRating(overall_rating);
r.setRatedCount(rl.size());
s.update(r);
String logged_in = ul.getUser().getIduser() + "";
String us = r.getUser().getIduser() + "";
if (!logged_in.equals(us)) {
Notification n = new Notification();
n.setCategory("Rate on Recipe");
n.setDate(new Date());
n.setUser(r.getUser());
n.setStatus("Unread");
n.setNotification(ul.getUser().getFname() + " rated your recipe " + r.getName() + ".");
s.save(n);
}
t.commit();
msg = "success";
} else {
msg = "Error";
}
out.write(msg);
} catch (Exception e) {
throw new ServletException();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* A factory delegate for resolving {@link MediaType} objects
* from {@link Resource} handles or filenames.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
* @since 5.0
*/
public final class MediaTypeFactory {
private static final String MIME_TYPES_FILE_NAME = "/org/springframework/http/mime.types";
private static final MultiValueMap<String, MediaType> fileExtensionToMediaTypes = parseMimeTypes();
private MediaTypeFactory() {
}
/**
* Parse the {@code mime.types} file found in the resources. Format is:
* <code>
* # comments begin with a '#'<br>
* # the format is <mime type> <space separated file extensions><br>
* # for example:<br>
* text/plain txt text<br>
* # this would map file.txt and file.text to<br>
* # the mime type "text/plain"<br>
* </code>
* @return a multi-value map, mapping media types to file extensions.
*/
private static MultiValueMap<String, MediaType> parseMimeTypes() {
InputStream is = MediaTypeFactory.class.getResourceAsStream(MIME_TYPES_FILE_NAME);
Assert.state(is != null, MIME_TYPES_FILE_NAME + " not found in classpath");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.US_ASCII))) {
MultiValueMap<String, MediaType> result = new LinkedMultiValueMap<>();
String line;
while ((line = reader.readLine()) != null) {
if (line.isEmpty() || line.charAt(0) == '#') {
continue;
}
String[] tokens = StringUtils.tokenizeToStringArray(line, " \t\n\r\f");
MediaType mediaType = MediaType.parseMediaType(tokens[0]);
for (int i = 1; i < tokens.length; i++) {
String fileExtension = tokens[i].toLowerCase(Locale.ENGLISH);
result.add(fileExtension, mediaType);
}
}
return result;
}
catch (IOException ex) {
throw new IllegalStateException("Could not read " + MIME_TYPES_FILE_NAME, ex);
}
}
/**
* Determine a media type for the given resource, if possible.
* @param resource the resource to introspect
* @return the corresponding media type, or {@code null} if none found
*/
public static Optional<MediaType> getMediaType(@Nullable Resource resource) {
return Optional.ofNullable(resource)
.map(Resource::getFilename)
.flatMap(MediaTypeFactory::getMediaType);
}
/**
* Determine a media type for the given file name, if possible.
* @param filename the file name plus extension
* @return the corresponding media type, or {@code null} if none found
*/
public static Optional<MediaType> getMediaType(@Nullable String filename) {
return getMediaTypes(filename).stream().findFirst();
}
/**
* Determine the media types for the given file name, if possible.
* @param filename the file name plus extension
* @return the corresponding media types, or an empty list if none found
*/
public static List<MediaType> getMediaTypes(@Nullable String filename) {
List<MediaType> mediaTypes = null;
String ext = StringUtils.getFilenameExtension(filename);
if (ext != null) {
mediaTypes = fileExtensionToMediaTypes.get(ext.toLowerCase(Locale.ENGLISH));
}
return (mediaTypes != null ? mediaTypes : Collections.emptyList());
}
}
|
package com.beike.service.mobile.impl;
import com.beike.service.mobile.LuceneMobileAssistService;
public class LuceneMobileAssitServiceImpl implements LuceneMobileAssistService {
@Override
public String getCityEnNameByAreaID(long area_id) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.example.loadinganimationexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.ybq.android.spinkit.style.DoubleBounce;
// #21 (로딩화면 만들기 feat. github)
// https://github.com/ybq/Android-SpinKit
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
package Model;
import View.ViewObserver;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
public class VehicleList {
private final int delay = 50;
Timer timer = new Timer(delay, new TimerListener());
public ArrayList<IVehicle> cars = new ArrayList<>();
public ArrayList<ViewObserver> observers= new ArrayList<>();
public VehicleFactory factory = new VehicleFactory();
Random rand = new Random();
public int getNumberOfVehicles(){
return cars.size();
}
public ArrayList<IVehicle> getCars() {
return cars;
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (cars.size()==0){
update();
}
for (IVehicle car : cars) {
car.move();
if (!isItInsideFrame(car.getX(), car.getY())) {
car.stopEngine();
car.turnLeft();
car.turnLeft();
car.startEngine();
}
// repaint() calls the paintComponent method of the panel
update(); }
}
}
public void startTimer(){
timer.start();
}
boolean isItInsideFrame(int x, int y) {
if (x < 0 || x > 690 || y < 0 || y > 500) {
return false;
} else return true;
}
public void update(){
for (ViewObserver o:observers) {
o.update();
}
}
public void addCar(){
if (cars.size()<=10){
int r = rand.nextInt(3);
if (r==0) {
cars.add(factory.createMotorvehicle("volvo240",cars.size()));
}
else if (r==1){
cars.add(factory.createMotorvehicle("saab95",cars.size()));
}
else cars.add(factory.createMotorvehicle("scania",cars.size()));
}
else throw new IllegalArgumentException("Reached maximum amount of cars");
}
public void removeCar(){
cars.remove((cars.size()-1));
}} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.