text
stringlengths 10
2.72M
|
|---|
/**
* A box
*/
public class Box implements Comparable{
private int height;
private int longSide;
private int shortSide;
/*
* Makes a box, will make the long side the long side on it's own.
* It doesn't trust you anyway.
*/
public Box(int height, int side1, int side2){
this.height = height;
this.longSide = side1 > side2 ? side1 : side2;
this.shortSide = side2 > side1 ? side1 : side2;
}
/*
* Returns the height of the box
*/
public int getHeight(){
return this.height;
}
/*
* Returns the long side
*/
public int getLongSide(){
return this.longSide;
}
/*
* Returns the short side
*/
public int getShortSide(){
return this.shortSide;
}
/**
* Rotate the box by swapping the short side and the height
*/
public void swapShort() {
int tmp = this.shortSide;
this.shortSide = this.height;
this.height = tmp;
fixBase();
}
/**
* Rotate the box by swapping the long side and the height
*/
public void swapLong() {
int tmp = this.longSide;
this.longSide = this.height;
this.height = tmp;
fixBase();
}
/**
* Ensure the longSide is the long side, and shortSide is the
* short side of the base.
* This is useful after swapping one for the height to ensure
* the values are still correct.
*/
private void fixBase() {
int tmp;
if (this.shortSide > this.longSide) {
tmp = this.longSide;
this.longSide = this.shortSide;
this.shortSide = tmp;
}
}
/*
* Compares the shortSide, longSide and height of the box
*/
@Override
public int compareTo(Object o){
Box b = (Box)o;
int value = Integer.compare(this.shortSide, b.getShortSide());
if (value != 0){
return value;
} else {
value = Integer.compare(this.longSide, b.getLongSide());
if (value != 0){
return value;
} else {
return Integer.compare(this.height, b.getHeight());
}
}
}
/**
* Returns a string representation of the box
*/
@Override
public String toString() {
return String.format("Box <%d,%d,%d>",
this.height,
this.longSide,
this.shortSide);
}
}
|
package client;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseListenerList implements MouseListener {
private JList list;
private Control control;
public MouseListenerList(JList list, Control control) {
this.list = list;
this.control = control;
list.addMouseListener(this);
}
@Override
public void mouseClicked(MouseEvent e) {
list = (JList) e.getSource();
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
if (index >= 0) {
Object o = list.getModel().getElementAt(index);
control.move(o.toString());
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
|
package parking_plaza;
public class Bus extends Vehicle {
double coefficient = 2.5;
}
|
package com.blog.service.impl;
import java.util.List;
import com.blog.Idao.IAdminuserDao;
import com.blog.Iservice.IAdminuserService;
import com.blog.bean.Adminuser;
import com.blog.bean.DongTai;
import com.blog.dao.impl.AdminuserDao;
public class AdminuserService implements IAdminuserService {
IAdminuserDao admin= new AdminuserDao();
public boolean Change_a_pass(Adminuser adminuser,int a_id){
return admin.Change_a_pass(adminuser, a_id);
}
public boolean isLogin(String a_name){
return admin.Login(a_name);
}
public Adminuser isAdminUserByname(String a_name){
return admin.adminUserByname(a_name);
}
public boolean isRegAdminUser(Adminuser adminuser){
boolean falg = admin.isAdminuserByname(adminuser);
if(!falg){
admin.RegAdminUser(adminuser);
return true;
}else{
return false;
}
}
public List<Adminuser> adminuserlist() {
// TODO Auto-generated method stub
return admin.adminuserlist();
}
public int getTotalCountadminuser() {
// TODO Auto-generated method stub
return admin.getTotalCountadminuser();
}
public List<Adminuser> adminuserlistBypage(int currentPage, int pageSize) {
// TODO Auto-generated method stub
return admin.adminuserlistBypage(currentPage, pageSize);
}
}
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(SiteWarn)预警类型
//generate by redcloud,2020-07-24 19:59:20
public class SiteWarn implements Serializable {
private static final long serialVersionUID = 65L;
// 主键id
private Long id ;
// 名称
private String title ;
// 描述
private String border ;
// 预警等级
private String grade ;
// 创建时间
private Long created ;
// 修改时间
private Long updated ;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this.title = title;
}
public String getBorder() {
return border ;
}
public void setBorder(String border) {
this.border = border;
}
public String getGrade() {
return grade ;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Long getCreated() {
return created ;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getUpdated() {
return updated ;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
}
|
package com.company;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
ArrayOperations op = new ArrayOperations();
int[] myIntegers = op.getIntegers(scanner,5);
int[] sorted = op.sortIntegers(myIntegers);
op.printArray(sorted);
}
}
|
package com.koma.wanandroid.api;
import com.koma.component_base.base.BaseResponse;
import com.koma.component_base.bean.w.BannerData;
import com.koma.wanandroid.bean.ArticleBean;
import com.koma.wanandroid.bean.KnowledgeBean;
import io.reactivex.Observable;
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Path;
/**
* @author Koma
* @date 2018/7/31 下午 05:01
* @des
*/
public interface ApiService {
/**
* 首页广告栏
*
* @return
*/
@GET("banner/json")
Observable<BaseResponse<List<BannerData>>> getBannerData();
//页码,拼接在连接中,从0开始。
@GET("article/list/{page}/json")
Observable<BaseResponse<ArticleBean.DataBean>> getArticleData(@Path("page") int page);
@GET("tree/json")
Observable<BaseResponse<List<KnowledgeBean>>>getKnowledgeData();
}
|
/**
* Copyright (C) Alibaba Cloud Computing, 2012
* All rights reserved.
*
* 版权所有 (C)阿里巴巴云计算,2012
*/
package com.aliyun.oss.internal;
import static com.aliyun.oss.common.utils.CodingUtils.assertParameterNotNull;
import static com.aliyun.oss.internal.OSSUtils.OSS_RESOURCE_MANAGER;
import static com.aliyun.oss.internal.OSSUtils.ensureBucketNameValid;
import static com.aliyun.oss.internal.OSSUtils.safeCloseResponse;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.ServiceCredentials;
import com.aliyun.oss.common.comm.ExecutionContext;
import com.aliyun.oss.common.comm.RequestMessage;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.common.comm.ServiceClient;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.AccessControlList;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.BucketList;
import com.aliyun.oss.model.BucketLoggingResult;
import com.aliyun.oss.model.BucketReferer;
import com.aliyun.oss.model.BucketWebsiteResult;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.LifecycleRule;
import com.aliyun.oss.model.LifecycleRule.RuleStatus;
import com.aliyun.oss.model.ListBucketsRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.SetBucketLifecycleRequest;
import com.aliyun.oss.model.SetBucketLoggingRequest;
import com.aliyun.oss.model.SetBucketWebsiteRequest;
/**
* bucket operation
* */
public class OSSBucketOperation extends OSSOperation {
private static final String SUBRESOURCE_ACL = "acl";
private static final String SUBRESOURCE_REFERER = "referer";
private static final String SUBRESOURCE_LOCATION = "location";
private static final String SUBRESOURCE_LOGGING = "logging";
private static final String SUBRESOURCE_WEBSITE = "website";
private static final String SUBRESOURCE_LIFECYCLE = "lifecycle";
public OSSBucketOperation(URI endpoint, ServiceClient client, ServiceCredentials cred) {
super(endpoint, client, cred);
}
/**
* Creates a bucket.
* */
public Bucket createBucket(CreateBucketRequest createBucketRequest)
throws OSSException, ClientException{
String bucketName = createBucketRequest.getBucketName();
String locationConstraint = createBucketRequest.getLocationConstraint();
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
String xmlBody = "";
if (locationConstraint != null) {
xmlBody = buildCreateBucketXml(locationConstraint);
}
byte[] inputBytes = xmlBody.getBytes();
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.PUT)
.setBucket(bucketName)
.setInputStream(new ByteArrayInputStream(inputBytes))
.setInputSize(inputBytes.length)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
return new Bucket(bucketName);
}
/**
* Delete the bucket.
* */
public void deleteBucket(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.DELETE)
.setBucket(bucketName)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* Lists all my buckets.
* */
public BucketList listBuckets(ListBucketsRequest listBucketRequest) throws OSSException, ClientException{
// check parameter
assertParameterNotNull(listBucketRequest, "request");
// 使用LinkedHashMap以保证参数有序可测试
Map<String, String> params = new LinkedHashMap<String, String>();
if (listBucketRequest.getPrefix() != null){
params.put("prefix", listBucketRequest.getPrefix());
}
if (listBucketRequest.getMarker() != null){
params.put("marker", listBucketRequest.getMarker());
}
if (listBucketRequest.getMaxKeys() != null){
params.put("max-keys", Integer.toString(listBucketRequest.getMaxKeys()));
}
ResponseMessage response = null;
try {
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod());
response = send(request, context, true);
// TODO: refactor ResponseParser
return ResponseParser.parseListBucket(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* Sets ACL for the bucket.
*/
public void setBucketAcl(String bucketName, CannedAccessControlList acl)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
if (acl == null) {
acl = CannedAccessControlList.Private;
}
Map<String, String> headers = new HashMap<String, String>();
headers.put(OSSHeaders.OSS_CANNED_ACL, acl.toString());
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_ACL, null);
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.PUT)
.setBucket(bucketName)
.setHeaders(headers)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* Gets ACL of the bucket.
* */
public AccessControlList getBucketAcl(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_ACL, null);
ResponseMessage response = null;
try{
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
response = send(request, context, true);
return ResponseParser.parseGetBucketAcl(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* Sets http referer for the bucket.
*/
public void setBucketReferer(String bucketName, BucketReferer referer)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
if (referer == null) {
referer = new BucketReferer();
}
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_REFERER, null);
byte[] inputBytes = referer.toXmlString().getBytes();;
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.PUT)
.setBucket(bucketName)
.setParameters(params)
.setInputStream(new ByteArrayInputStream(inputBytes))
.setInputSize(inputBytes.length)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* Gets http referer of the bucket.
* */
public BucketReferer getBucketReferer(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_REFERER, null);
ResponseMessage response = null;
try {
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
response = send(request, context, true);
return ResponseParser.parseGetBucketReferer(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* Get bucket location
*/
public String getBucketLocation(String bucketName) {
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LOCATION, null);
ResponseMessage response = null;
try{
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
response = send(request, context, true);
return ResponseParser.parseGetBucketLocation(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* is bucket exist
* */
public boolean bucketExists(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
try {
getBucketAcl(bucketName);
} catch (OSSException e) {
if(e.getErrorCode().equals(OSSErrorCode.NO_SUCH_BUCKET)) {
return false;
}
}
return true;
}
/**
* list objects in the bucket.
* */
public ObjectListing listObjects(ListObjectsRequest listObjectRequest)
throws OSSException, ClientException{
assertParameterNotNull(listObjectRequest, "request");
if (listObjectRequest.getBucketName() == null)
throw new IllegalArgumentException(OSS_RESOURCE_MANAGER.getString("MustSetBucketName"));
ensureBucketNameValid(listObjectRequest.getBucketName());
// 使用LinkedHashMap以保证参数有序可测试
Map<String, String> params = new LinkedHashMap<String, String>();
if (listObjectRequest.getPrefix() != null){
params.put("prefix", listObjectRequest.getPrefix());
}
if (listObjectRequest.getMarker() != null){
params.put("marker", listObjectRequest.getMarker());
}
if (listObjectRequest.getDelimiter() != null){
params.put("delimiter", listObjectRequest.getDelimiter());
}
if (listObjectRequest.getMaxKeys() != null){
params.put("max-keys", Integer.toString(listObjectRequest.getMaxKeys()));
}
ResponseMessage response = null;
try{
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(listObjectRequest.getBucketName())
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), listObjectRequest.getBucketName());
response = send(request, context, true);
return ResponseParser.parseListObjects(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* set bucket logging.
* */
public void setBucketLogging(SetBucketLoggingRequest setBucketLoggingRequest)
throws OSSException, ClientException{
String bucketName = setBucketLoggingRequest.getBucketName();
String targetBucket = setBucketLoggingRequest.getTargetBucket();
String targetPrefix = setBucketLoggingRequest.getTargetPrefix();
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
assertParameterNotNull(targetBucket, "targetBucket");
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LOGGING, null);
String xmlBody = "";
xmlBody = buildPutBucketLoggingXml(targetBucket,targetPrefix);
byte[] inputBytes = xmlBody.getBytes();
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.PUT)
.setBucket(bucketName)
.setParameters(params)
.setInputStream(new ByteArrayInputStream(inputBytes))
.setInputSize(inputBytes.length)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* get bucket logging.
* */
public BucketLoggingResult getBucketLogging(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LOGGING, null);
ResponseMessage response = null;
try{
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
response = send(request, context, true);
return ResponseParser.parseBucketLogging(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* delete bucket logging.
* */
public void deleteBucketLogging(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LOGGING, null);
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.DELETE)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* set bucket website.
* */
public void setBucketWebsite(SetBucketWebsiteRequest setBucketWebSiteRequest)
throws OSSException, ClientException{
String bucketName = setBucketWebSiteRequest.getBucketName();
String indexDocument = setBucketWebSiteRequest.getIndexDocument();
String errorDocument = setBucketWebSiteRequest.getErrorDocument();
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
assertParameterNotNull(indexDocument, "indexDocument");
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_WEBSITE, null);
String xmlBody = "";
xmlBody = buildPutBucketWebSiteXml(indexDocument,errorDocument);
byte[] inputBytes = xmlBody.getBytes();
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.PUT)
.setBucket(bucketName)
.setParameters(params)
.setInputStream(new ByteArrayInputStream(inputBytes))
.setInputSize(inputBytes.length)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* get bucket website.
* */
public BucketWebsiteResult getBucketWebsite(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_WEBSITE, null);
ResponseMessage response = null;
try{
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
response = send(request, context, true);
return ResponseParser.parseBucketWebsite(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* delete bucket website.
* */
public void deleteBucketWebsite(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_WEBSITE, null);
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.DELETE)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* set bucket lifecycle.
* */
public void setBucketLifecycle(SetBucketLifecycleRequest setBucketLifecycleRequest)
throws OSSException, ClientException{
String bucketName = setBucketLifecycleRequest.getBucketName();
List<LifecycleRule> lifecycleRules = setBucketLifecycleRequest.getLifecycleRules();
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
assertParameterNotNull(lifecycleRules, "lifecycleRules");
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LIFECYCLE, null);
String xmlBody = "";
xmlBody = buildSetBucketLifecycleXml(lifecycleRules);
byte[] inputBytes = xmlBody.getBytes();
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.PUT)
.setBucket(bucketName)
.setParameters(params)
.setInputStream(new ByteArrayInputStream(inputBytes))
.setInputSize(inputBytes.length)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
/**
* get bucket lifecycle.
* */
public List<LifecycleRule> getBucketLifecycle(String bucketName)
throws OSSException, ClientException{
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LIFECYCLE, null);
ResponseMessage response = null;
try{
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.GET)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
response = send(request, context, true);
return ResponseParser.parseGetBucketLifecycle(response.getRequestId(), response.getContent());
} finally {
if (response != null){
safeCloseResponse(response);
}
}
}
/**
* delete bucket lifecycle.
*/
public void deleteBucketLifecycle(String bucketName)
throws OSSException, ClientException {
assertParameterNotNull(bucketName, "bucketName");
ensureBucketNameValid(bucketName);
Map<String, String> params = new HashMap<String, String>();
params.put(SUBRESOURCE_LIFECYCLE, null);
RequestMessage request = new OSSRequestMessageBuilder(getInnerClient())
.setEndpoint(getEndpoint())
.setMethod(HttpMethod.DELETE)
.setBucket(bucketName)
.setParameters(params)
.build();
ExecutionContext context = createDefaultContext(request.getMethod(), bucketName);
send(request, context);
}
private static String buildPutBucketWebSiteXml(String indexDocument,String errorDocument) {
StringBuffer xml = new StringBuffer();
xml.append("<WebsiteConfiguration>");
xml.append("<IndexDocument>");
xml.append("<Suffix>" + indexDocument + "</Suffix>");
xml.append("</IndexDocument>");
if(errorDocument != null){
xml.append("<ErrorDocument>");
xml.append("<Key>" + errorDocument + "</Key>");
xml.append("</ErrorDocument>");
}
xml.append("</WebsiteConfiguration>");
return xml.toString();
}
private static String buildPutBucketLoggingXml(String targetBucket,String targetPrefix) {
StringBuffer xml = new StringBuffer();
xml.append("<BucketLoggingStatus>");
xml.append("<LoggingEnabled>");
xml.append("<TargetBucket>" + targetBucket + "</TargetBucket>");
if(targetPrefix != null){
xml.append("<TargetPrefix>" + targetPrefix + "</TargetPrefix>");
}
xml.append("</LoggingEnabled>");
xml.append("</BucketLoggingStatus>");
return xml.toString();
}
private static String buildCreateBucketXml(String locationConstraint) {
StringBuffer xml = new StringBuffer();
xml.append("<CreateBucketConfiguration>");
xml.append("<LocationConstraint>" + locationConstraint + "</LocationConstraint>");
xml.append("</CreateBucketConfiguration>");
return xml.toString();
}
private static String buildSetBucketLifecycleXml(List<LifecycleRule> lifecycleRules) {
StringBuffer xml = new StringBuffer();
xml.append("<LifecycleConfiguration>");
for (LifecycleRule rule : lifecycleRules) {
xml.append("<Rule>");
xml.append("<ID>" + rule.getId() + "</ID>");
xml.append("<Prefix>" + rule.getPrefix() + "</Prefix>");
if (rule.getStatus() == RuleStatus.Enabled) {
xml.append("<Status>Enabled</Status>");
} else {
xml.append("<Status>Disabled</Status>");
}
if (rule.getExpirationTime() != null) {
String formatDate = DateUtil.formatIso8601Date(rule.getExpirationTime());
xml.append("<Expiration><Date>" + formatDate + "</Date></Expiration>");
} else {
xml.append("<Expiration><Days>" + rule.getExpriationDays() + "</Days></Expiration>");
}
xml.append("</Rule>");
}
xml.append("</LifecycleConfiguration>");
return xml.toString();
}
}
|
package de.drkhannover.tests.api.auth;
import static de.drkhannover.tests.api.util.NullHelpers.notNull;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.drkhannover.tests.api.conf.ConfigurationValues;
import de.drkhannover.tests.api.user.dto.TokenDto;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
public class JwtAuth {
static class Credentials {
public String password;
public String username;
}
private JwtAuth() {}
public static UsernamePasswordAuthenticationToken extractCredentialsFromHttpRequest(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null && password == null) {
try {
Credentials cred = new ObjectMapper().readValue(request.getInputStream(), Credentials.class);
username = cred.username;
password = cred.password;
} catch (java.io.IOException e) {
throw new RuntimeException(e);
}
}
return new UsernamePasswordAuthenticationToken(username, password);
}
public static @Nullable String createJwtFromAuthentication(Authentication authentication, ConfigurationValues jwtConf) {
if (authentication.getPrincipal() instanceof UserDetails) {
return createJwtToken((UserDetails) authentication, jwtConf);
} else {
return null;
}
}
public static @Nonnull String createJwtToken(UserDetails user, ConfigurationValues jwtConf) {
var roles = user.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
var signingKey = jwtConf.getJwtSecret().getBytes();
var token = Jwts.builder()
.signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
.setHeaderParam("typ", jwtConf.getJwtTokenType())
.setIssuer(jwtConf.getJwtTokenIssuer())
.setAudience(jwtConf.getJwtTokenAudience())
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 86400000))
.claim("rol", roles)
.compact();
return notNull(token);
}
public static @Nullable UsernamePasswordAuthenticationToken readJwtToken(String token, String jwtSecret) {
var signingKey = jwtSecret.getBytes();
var parsedToken = Jwts.parser()
.setSigningKey(signingKey)
.parseClaimsJws(token.replace("Bearer ", ""));
var username = parsedToken
.getBody()
.getSubject();
var expiration = parsedToken.getBody().getExpiration();
var authorities = ((List<?>) parsedToken.getBody()
.get("rol")).stream()
.map(authority -> new SimpleGrantedAuthority((String) authority))
.collect(Collectors.toList());
if (!StringUtils.isEmpty(username)) {
return new UsernamePasswordAuthenticationToken(username, new TokenDto(token, expiration), authorities);
} else {
return null;
}
}
}
|
package org.formation.graphql;
import lombok.Data;
@Data
public class MemberInput {
private String nom,prenom,email,password;
private int age;
}
|
public class QuesoBlanco extends IngredienteDecorator{
public QuesoBlanco(Sandwich s){
super(s);
}
public double getPrecio(){
return sandwich.getPrecio() + 2;
}
public String getDescripcion(){
return sandwich.getDescripcion() + ", Queso blanco";
}
}
|
package be.openclinic.reporting;
import javax.xml.ws.Service;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import net.admin.AdminPerson;
import pe.gob.sis.ResultQueryAsegurado;
import pe.gob.sis.Service1;
import pe.gob.sis.Service1Soap;
import pe.gob.sis.ServiceProduction;
public class SIS {
public static ResultQueryAsegurado getAffiliationInformation(int personid){
AdminPerson person = AdminPerson.getAdminPerson(personid+"");
Service service = null;
Service1Soap soap = null;
if(MedwanQuery.getInstance().getConfigInt("enableSISProduction",0)==1) {
Debug.println("Using SIS production environment");
service = new ServiceProduction();
soap=((ServiceProduction)service).getService1Soap();
} else {
Debug.println("Using SIS test environment");
service = new Service1();
soap=((Service1)service).getService1Soap();
}
String autorization = soap.getSession(MedwanQuery.getInstance().getConfigString("sis.username","OPENCLINIC"), MedwanQuery.getInstance().getConfigString("sis.password","123456"));
Debug.println("SIS communication session authorization key = "+autorization);
try{
autorization = Long.parseLong(autorization)+"";
}
catch(Exception e){
autorization="0";
}
ResultQueryAsegurado r = soap.consultarAfiliadoFuaE(1, autorization, MedwanQuery.getInstance().getConfigString("sis.senderdni","02424160"), "1", ScreenHelper.checkString(person.getID("natreg")), "", "", "", "");
if(r.getIdError().equalsIgnoreCase("0") && !autorization.equalsIgnoreCase("0")){
r.setResultado(autorization);
}
Debug.println("SIS query error = "+r.getIdError());
Debug.println("SIS query patient insurance status = "+r.getEstado());
return r;
}
public static ResultQueryAsegurado getAffiliationInformationFromDNI(String dni){
Service1 service = new Service1();
Service1Soap soap = service.getService1Soap();
String autorization = soap.getSession(MedwanQuery.getInstance().getConfigString("sis.username","OPENCLINIC"), MedwanQuery.getInstance().getConfigString("sis.password","123456"));
try{
autorization = Long.parseLong(autorization)+"";
}
catch(Exception e){
autorization="0";
}
ResultQueryAsegurado r = soap.consultarAfiliadoFuaE(1, autorization, MedwanQuery.getInstance().getConfigString("sis.senderdni","02424160"), "1", dni, "", "", "", "");
if(!autorization.equalsIgnoreCase("0")){
r.setResultado(autorization);
}
return r;
}
}
|
package org.aravind.oss.kafka.connect.lib;
/**
* @author Aravind R Yarram
* @since 0.5.0
*/
public interface TaskConfigExtractor<T> {
public String extract(T input);
}
|
/*
* 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 ingsw;
import javax.swing.JOptionPane;
import java.sql.*;
/**
*
* @author Dario
*/
public class MenuController {
private String username = "";
private String password = "";
private static Database db = new Database();
private static Connection cn;
private LoginForm login=new LoginForm(this);
private boolean connect;
public void startLogin() {
login.setVisible(true);
}
public void setUsername(String user) {
this.username=user;
}
public void setPassword(String pass) {
this.password=pass;
}
public void doLogin() {
try {
connect = db.createConnection(username,password);
} catch(Exception e) {
JOptionPane.showMessageDialog(login, e.getMessage(),"Errore", JOptionPane.ERROR_MESSAGE);
}
cn = db.getConnection();
if(connect){
MenuForm menuForm = new MenuForm();
login.setVisible(false);
menuForm.setVisible(true);
}
}
}
|
import java.util.*;
/**
* _39_CombinationSum
*/
public class _39_CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
_combinationSum(target, new ArrayList<>(), 0, candidates, res);
return res;
}
public void _combinationSum(int restValue, List<Integer> list, int index, int[] candidate, List<List<Integer>> res) {
if (restValue < 0)
return;
if (restValue == 0) {
List<Integer> singleList = new ArrayList<>(list);
res.add(singleList);
return;
}
for (int i = index; i < candidate.length; ++i) {
list.add(candidate[i]);
_combinationSum(restValue - candidate[i], list, i, candidate, res);
list.remove(list.size() - 1);
}
}
}
|
package com.springD.framework.utils;
import com.springD.framework.common.Constants;
import com.springD.framework.shiro.ShiroUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import javax.servlet.http.HttpSession;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 用户util
* @author Chenz
*
*/
public class UserUtils {
public static final String CACHE_USER = "userCache";
/**
* 获取当前登录用户
* @return
*/
public static ShiroUser getShiroUser(){
Subject subject = SecurityUtils.getSubject();
ShiroUser user = (ShiroUser) subject.getPrincipal();
return user;
}
/**
* 判断是否需要验证码
* @param username
* @return
*/
public static boolean isCaptchaRequired(HttpSession session){
String sessionId = session.getId();
AtomicInteger retryCount = (AtomicInteger) CacheUtils.get("passwordRetryCache", sessionId);
if(retryCount != null && retryCount.get() > Constants.LOGIN_TRY_TIME){
return true;
}else{
return false;
}
}
}
|
package chunk;
public class Chunk {
public static int MAX_SIZE = 64000;
ChunkInfo chunkInfo;
int replicationDegree;
byte[] data;
public Chunk(ChunkInfo chunkInfo, int replicationDegree, byte[] data) {
this.chunkInfo = chunkInfo;
this.replicationDegree = replicationDegree;
this.data = data;
}
public Chunk(String fileID, int chunkNumber, int replicationDegree, byte[] data) {
this.chunkInfo = new ChunkInfo(fileID, chunkNumber);
this.replicationDegree = replicationDegree;
this.data = data;
}
public Chunk(String fileID) {
this.chunkInfo = new ChunkInfo(fileID);
}
public Chunk(String fileID,int chunkNumber){
this.chunkInfo = new ChunkInfo(fileID,chunkNumber);
}
public ChunkInfo getChunkInfo() {
return chunkInfo;
}
public void setChunkInfo(ChunkInfo chunkInfo) {
this.chunkInfo = chunkInfo;
}
public int getReplicationDegree() {
return replicationDegree;
}
public void setReplicationDegree(int replicationDegree) {
this.replicationDegree = replicationDegree;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
|
package datacompression.hufmann;
public class HuffmanNode extends HuffmanTree {
private HuffmanTree left;
private HuffmanTree right;
public HuffmanNode(HuffmanTree right, HuffmanTree left) {
super(right.getFrequency() + left.getFrequency());
this.right = right;
this.left = left;
}
public HuffmanTree getRight() {
return right;
}
public void setRight(HuffmanTree right) {
this.right = right;
}
public HuffmanTree getLeft() {
return left;
}
public void setLeft(HuffmanTree left) {
this.left = left;
}
}
|
package recursion_baekjoon;
import java.util.Scanner;
public class TreeRound_Test {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int number = scn.nextInt();
TreeRound [] arr = new TreeRound[number];
}
}
|
package pooPractica.Personas;
import Main.FichaReparacion;
import pooPractica.Vehiculos.Vehiculo;
/**
*
* @author RadW
*/
public class Cliente extends Persona{
private String email;
private Vehiculo[] vehiculos; //array con los vehiculos que posee el cliente
private FichaReparacion fichaActual; // ficha de reparación actual en proceso
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package com.navarromugas.models;
import java.awt.Graphics;
public interface Simulable {
public void dibujar(Graphics g);
public void calcularEstadoSiguiente();
}
|
package com.citibank.ods.modules.client.customerprvt.functionality.valueobject;
import com.citibank.ods.entity.pl.TplCustomerPrvtEntity;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
*@see package com.citibank.ods.modules.client.customerPrvt.functionality.valueObject;
*@version 1.0
*@author l.braga,14/03/2007
*
*<PRE>
*<U>Updated by:</U>
*<U>Description:</U>
*</PRE>
*/
public class CustomerPrvtDetailFncVO extends BaseCustomerPrvtDetailFncVO
{
public CustomerPrvtDetailFncVO()
{
m_tplCustomerPrvtEntity = new TplCustomerPrvtEntity();
}
}
|
package com.bitlab.message.data;
import com.bitlab.constant.Constants;
import com.bitlab.constant.InvType;
import com.bitlab.util.ByteParser;
import com.bitlab.util.ByteUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Inventory {
private InvType type;
private String hash;
public Inventory(byte[] bytes) {
ByteParser parser = new ByteParser(bytes);
int type = parser.parseInt(true);
if(type <= InvType.MSG_CMPCT_BLOCK.value) {
this.type = Constants.INV_TYPES[type];
} else {
if(type == InvType.MSG_WITNESS_BLOCK.value)
this.type = InvType.MSG_WITNESS_BLOCK;
else if(type == InvType.MSG_WITNESS_TX.value)
this.type = InvType.MSG_WITNESS_TX;
else if(type == InvType.MSG_FILTERED_WITNESS_BLOCK.value)
this.type = InvType.MSG_FILTERED_WITNESS_BLOCK;
}
hash = ByteUtils.bytesToHexString(ByteUtils.reverseBytes(parser.parseByte(32)));
}
public byte[] serialize() {
ByteBuffer buffer = ByteBuffer.allocate(36);
buffer.order(ByteOrder.LITTLE_ENDIAN).putInt(type.value).order(ByteOrder.BIG_ENDIAN).put(ByteUtils.hexStringToBytes(hash));
return buffer.array();
}
public InvType getType () {
return type;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Inventory{");
sb.append("data=").append(type);
sb.append(", hash='").append(hash).append('\'');
sb.append('}');
return sb.toString();
}
}
|
package com.example.demo.hello;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RouteConsumer {
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(value = "direct",type = "direct"),
key = {"info","error","warning"}
)
})
public void reactReceive1(String s){
System.out.println("receive 1 接收的消息:"+s);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(value = "direct",type = "direct"),
key = {"error"}
)
})
public void reactReceive2(String s){
System.out.println("receive 2 接收的消息:"+s);
}
}
|
package com.git.cloud.resmgt.compute.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.git.cloud.appmgt.dao.IDeployunitDao;
import com.git.cloud.appmgt.model.po.DeployUnitPo;
import com.git.cloud.appmgt.model.vo.AppStatVo;
import com.git.cloud.appmgt.model.vo.DeployUnitVo;
import com.git.cloud.appmgt.service.IAppMagService;
import com.git.cloud.appmgt.service.IDeployunitService;
import com.git.cloud.common.enums.OperationType;
import com.git.cloud.common.enums.ResourceType;
import com.git.cloud.common.enums.Source;
import com.git.cloud.common.enums.Type;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.foundation.util.UUIDGenerator;
import com.git.cloud.log.model.po.NotificationPo;
import com.git.cloud.log.service.INotificationService;
import com.git.cloud.policy.model.vo.AllocIpParamVo;
import com.git.cloud.policy.service.IIpAllocToDeviceNewService;
import com.git.cloud.resmgt.common.dao.ICmHostDAO;
import com.git.cloud.resmgt.common.model.bo.CmDeviceHostShowBo;
import com.git.cloud.resmgt.common.model.po.CmHostPo;
import com.git.cloud.resmgt.common.model.vo.IpRuleInfoVo;
import com.git.cloud.resmgt.common.service.ICmDeviceService;
import com.git.cloud.resmgt.compute.dao.IRmHostDao;
import com.git.cloud.resmgt.compute.handler.HostControllerServiceImpl;
import com.git.cloud.resmgt.compute.model.comparator.ScanVmResultVoComparator;
import com.git.cloud.resmgt.compute.model.po.DuPoByRmHost;
import com.git.cloud.resmgt.compute.model.vo.CloudServiceVoByRmHost;
import com.git.cloud.resmgt.compute.model.vo.IpObj;
import com.git.cloud.resmgt.compute.model.vo.IpRules;
import com.git.cloud.resmgt.compute.model.vo.ScanVmResultVo;
import com.git.cloud.resmgt.compute.model.vo.VmVo;
import com.git.cloud.resmgt.compute.service.IRmHostService;
import com.git.cloud.resource.model.po.VmInfoPo;
import com.git.cloud.taglib.util.Internation;
//@Service("rmHostService")
public class RmHostServiceImpl implements IRmHostService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private ICmDeviceService iCmDeviceService;
private IRmHostDao rmHostDao;
private IIpAllocToDeviceNewService ipAllocService;
private HostControllerServiceImpl hostControllerServiceImpl;
private INotificationService notiServiceImpl;
private IDeployunitService deployunitServiceImpl;
private IDeployunitDao deployunitDaoImpl;
private ICmHostDAO cmHostDao;
private IAppMagService appMagServiceImpl;
public IDeployunitDao getDeployunitDaoImpl() {
return deployunitDaoImpl;
}
public void setDeployunitDaoImpl(IDeployunitDao deployunitDaoImpl) {
this.deployunitDaoImpl = deployunitDaoImpl;
}
public ICmHostDAO getCmHostDao() {
return cmHostDao;
}
public void setCmHostDao(ICmHostDAO cmHostDao) {
this.cmHostDao = cmHostDao;
}
public IDeployunitService getDeployunitServiceImpl() {
return deployunitServiceImpl;
}
public void setDeployunitServiceImpl(IDeployunitService deployunitServiceImpl) {
this.deployunitServiceImpl = deployunitServiceImpl;
}
public IAppMagService getAppMagServiceImpl() {
return appMagServiceImpl;
}
public void setAppMagServiceImpl(IAppMagService appMagServiceImpl) {
this.appMagServiceImpl = appMagServiceImpl;
}
public INotificationService getNotiServiceImpl() {
return notiServiceImpl;
}
public void setNotiServiceImpl(INotificationService notiServiceImpl) {
this.notiServiceImpl = notiServiceImpl;
}
public HostControllerServiceImpl getHostControllerServiceImpl() {
return hostControllerServiceImpl;
}
public void setHostControllerServiceImpl(
HostControllerServiceImpl hostControllerServiceImpl) {
this.hostControllerServiceImpl = hostControllerServiceImpl;
}
@Override
public List<ScanVmResultVo> scanVmList(VmVo vm) throws Exception {
List<ScanVmResultVo> resultList = hostControllerServiceImpl.scanVmFromHost(vm);
//获取IP规则
List<IpRules> rules = this.getIpRules(vm);
//获取云服务列表
List<CloudServiceVoByRmHost> clouds = this.vmCloudServiceList(vm);
for(ScanVmResultVo soj :resultList){
if (this.checkVmIsExsit(soj.getVmName()))
soj.setIsExist(1);
else {
soj.setIsExist(0);
soj.setCloudServiceList(clouds);
soj.setRules(rules);
soj.setVmId(UUIDGenerator.getUUID());
}
String ips[] = soj.getIp().split(",");
List<IpObj> ipList = new ArrayList<IpObj>();
for (int i = 0; i < ips.length; i++) {
IpObj ip = new IpObj();
ip.setIp(ips[i]);
ipList.add(ip);
}
soj.setIpList(ipList);
}
/* 对扫描结果进行排序 */
ScanVmResultVoComparator comparator = new ScanVmResultVoComparator();
Collections.sort(resultList, comparator);
return resultList;
}
@Override
public List<CloudServiceVoByRmHost> vmCloudServiceList(VmVo vm) {
return rmHostDao.getCloudServices(vm);
}
@Override
public List<IpRules> getIpRules(VmVo vm) {
if ("0".equals(vm.getCloudService()) || vm.getCloudService() == null || "1".equals(vm.getCloudService())) {
vm.setCloudService("");
}
List<IpRules> list = rmHostDao.getIpRules(vm);
return list;
}
/**
* 检查虚拟机是否存在
*/
@Override
public boolean checkVmIsExsit(String vmName) {
return rmHostDao.checkVmIsExist(vmName);
}
/**
* 获取服务器角色列表
*/
@Override
public List<DuPoByRmHost> getDuList(VmVo vm) {
List<DuPoByRmHost> duList = rmHostDao.getDuList(vm);
List<DuPoByRmHost> duListNoSrvId = rmHostDao.getDuListNoServiceId();
duList.addAll(duListNoSrvId);
return duList;
}
/**
* 检查datastore是否存在
*/
@Override
public boolean checkDataStore(String dataStoreName, String hostId) {
return rmHostDao.checkDataStore(dataStoreName, hostId);
}
public ICmDeviceService getiCmDeviceService() {
return iCmDeviceService;
}
@Autowired
public void setiCmDeviceService(ICmDeviceService iCmDeviceService) {
this.iCmDeviceService = iCmDeviceService;
}
public IRmHostDao getRmHostDao() {
return rmHostDao;
}
@Autowired
public void setRmHostDao(IRmHostDao rmHostDao) {
this.rmHostDao = rmHostDao;
}
public IIpAllocToDeviceNewService getIpAllocService() {
return ipAllocService;
}
@Autowired
public void setIpAllocService(IIpAllocToDeviceNewService ipAllocService) {
this.ipAllocService = ipAllocService;
}
}
|
package cz.dix.alg.genetics.strategy;
import cz.dix.alg.genetics.Population;
/**
* Selection strategy represents a way how should be performed selection over whole population in a alg algorithm.
*
* @author Zdenek Obst, zdenek.obst-at-gmail.com
*/
public interface SelectionStrategy {
/**
* Makes a selection over the population.
*
* @param population population to be processed
* @return population after the selection
*/
Population makeSelection(Population population);
}
|
package com.udacity.gradle.builditbigger;
import android.support.test.rule.ActivityTestRule;
import org.junit.Rule;
import org.junit.Test;
import static junit.framework.Assert.assertTrue;
/**
* Created by Vlad
*/
public class JokeTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void jokeTest() throws Exception {
MainActivity activity = mActivityRule.getActivity();
activity.setJokeResponse(new MainActivity.onJokeRetrieved() {
@Override
public void jokeRetrieved(String response) {
assertTrue(!response.isEmpty());
}
});
}
}
|
package com.aelitis.azureus.ui.swt.views;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import org.gudy.azureus2.core3.config.COConfigurationManager;
import org.gudy.azureus2.core3.util.*;
import org.gudy.azureus2.plugins.PluginInterface;
import org.gudy.azureus2.plugins.utils.resourcedownloader.ResourceDownloader;
import org.gudy.azureus2.pluginsimpl.local.PluginInitializer;
import com.aelitis.azureus.ui.common.viewtitleinfo.ViewTitleInfo;
import com.aelitis.azureus.ui.common.viewtitleinfo.ViewTitleInfoManager;
import com.aelitis.azureus.util.JSONUtils;
import com.aelitis.azureus.util.MapUtils;
public class ViewTitleInfoBetaP
implements ViewTitleInfo
{
private static final String PARAM_LASTPOSTCOUNT = "betablog.numPosts";
long numNew = 0;
private long postCount = 0;
@SuppressWarnings("rawtypes")
public ViewTitleInfoBetaP() {
SimpleTimer.addEvent("devblog", SystemTime.getCurrentTime(),
new TimerEventPerformer() {
public void perform(TimerEvent event) {
long lastPostCount = COConfigurationManager.getLongParameter(
PARAM_LASTPOSTCOUNT, 0);
PluginInterface pi = PluginInitializer.getDefaultInterface();
try {
ResourceDownloader rd = pi.getUtilities().getResourceDownloaderFactory().create(
new URL(
"http://api.tumblr.com/v2/blog/devblog.vuze.com/info?api_key=C5a8UGiSwPflOrVecjcvwGiOWVsLFF22pC9SgUIKSuQfjAvDAY"));
InputStream download = rd.download();
Map json = JSONUtils.decodeJSON(FileUtil.readInputStreamAsString(
download, 65535));
Map mapResponse = MapUtils.getMapMap(json, "response", null);
if (mapResponse != null) {
Map mapBlog = MapUtils.getMapMap(mapResponse, "blog", null);
if (mapBlog != null) {
postCount = MapUtils.getMapLong(mapBlog, "posts", 0);
numNew = postCount - lastPostCount;
ViewTitleInfoManager.refreshTitleInfo(ViewTitleInfoBetaP.this);
}
}
} catch (Exception e) {
}
}
});
}
public Object getTitleInfoProperty(int propertyID) {
if (propertyID == TITLE_INDICATOR_TEXT && numNew > 0) {
return "" + numNew;
}
return null;
}
public void clearIndicator() {
COConfigurationManager.setParameter(PARAM_LASTPOSTCOUNT, postCount);
numNew = 0;
}
}
|
package com.encdata.corn.niblet.dto.keycloak;
/**
* Copyright (c) 2015-2017 Enc Group
*
* @Description 部门列表接口返回list中单个元素对象
* @Author Siwei Jin
* @Date 2018/10/25 9:13
*/
public class GroupElementDto {
//机构id
private String id;
//机构名称
private String name;
//父机构id
private String pId;
//父机构名称
private String pName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
|
import java.io.PrintStream;
import java.util.*;
public class SortedLinkedListMultiset<T> extends Multiset<T>
{
protected LinkedListNode headNode;
public SortedLinkedListMultiset() {
// Implement me
headNode = null;
} // end of SortedLinkedListMultiset()
private LinkedListNode getLastNode() {
if (headNode == null) {
return null;
}
else {
LinkedListNode lastNode = headNode;
while (lastNode.getNextNode() != null) {
if (lastNode.getNextNode() == null) {
return lastNode;
}
}
}
return null;
}
private LinkedListNode nodeToInsert(String insertValue, LinkedListNode node) {
if (insertValue.compareTo(node.getValue()) > 0) {
if (node.getNextNode() != null) {
LinkedListNode insertNode = nodeToInsert(insertValue, node.getNextNode());
return insertNode;
}
else {
return node;
}
}
else {
return node;
}
}
private boolean insertAtNode(String insertValue, LinkedListNode insertNode) {
if (insertValue.compareTo(insertNode.getValue()) < 0) {
if (insertNode.getPrevNode() == null) {
insertNode.setPrevNode(new LinkedListNode(insertValue));
insertNode.getPrevNode().setNextNode(insertNode);
if (insertNode.getValue().equals(headNode.getValue())) {
headNode = insertNode.getPrevNode();
}
return true;
}
else {
LinkedListNode newNode = new LinkedListNode(insertValue, insertNode.getPrevNode());
newNode.setNextNode(insertNode);
insertNode.setPrevNode(newNode);
newNode.getPrevNode().setNextNode(newNode);
return true;
}
}
else {
if (insertValue.equals(insertNode.getValue())) {
insertNode.addListAppearance();
return true;
}
if (insertNode.getNextNode() == null) {
insertNode.setNextNode(new LinkedListNode(insertValue, insertNode));
insertNode.getNextNode().setPrevNode(insertNode);
return true;
}
else {
LinkedListNode newNode = new LinkedListNode(insertValue, insertNode);
newNode.setNextNode(insertNode.getNextNode());
insertNode.setNextNode(newNode);
newNode.getNextNode().setPrevNode(newNode);
return true;
}
}
}
public void add(T item) {
// Implement me!
String itemString = (String)item;
LinkedListNode insertNode;
if (headNode == null) {
headNode = new LinkedListNode(itemString);
}
else {
insertNode = nodeToInsert(itemString, headNode);
if (insertNode != null) {
insertAtNode(itemString, insertNode);
}
else {
}
}
} // end of add()
public int search(T item) {
// Implement me!
LinkedListNode comparisonNode;
String itemString = (String)item;
if (headNode == null) {
return 0;
}
else {
comparisonNode = headNode;
if (comparisonNode.getValue().equals(itemString)) {
return comparisonNode.getAppearancesInList();
}
while (comparisonNode.getNextNode() != null) {
comparisonNode = comparisonNode.getNextNode();
if (comparisonNode.getValue().equals(itemString)) {
return comparisonNode.getAppearancesInList();
}
}
}
// default return, please override when you implement this method
return 0;
} // end of add()
public void removeOne(T item) {
// Implement me!
LinkedListNode comparisonNode;
String itemString = (String)item;
if (headNode == null) {
return;
}
else {
comparisonNode = headNode;
while (comparisonNode.getNextNode() != null) {
if (comparisonNode.getValue().equals(itemString)) {
if (comparisonNode.getAppearancesInList() <= 1) {
if (comparisonNode.getPrevNode() != null) {
comparisonNode.getPrevNode().setNextNode(comparisonNode.getNextNode());
}
else {
headNode = comparisonNode.getNextNode();
}
if (comparisonNode.getNextNode() != null) {
comparisonNode.getNextNode().setPrevNode(comparisonNode.getPrevNode());
}
}
else {
comparisonNode.removeListAppearance();
}
}
comparisonNode = comparisonNode.getNextNode();
}
}
} // end of removeOne()
public void removeAll(T item) {
// Implement me!
LinkedListNode comparisonNode;
String itemString = (String)item;
if (headNode == null) {
return;
}
else {
comparisonNode = headNode;
do {
if (comparisonNode.getValue().equals(itemString)) {
if (comparisonNode.getNextNode() != null) {
comparisonNode.getNextNode().setPrevNode(comparisonNode.getPrevNode());
}
else {
}
if (comparisonNode.getPrevNode() != null) {
comparisonNode.getPrevNode().setNextNode(comparisonNode.getNextNode());
}
else {
headNode = comparisonNode.getNextNode();
}
break;
}
if (comparisonNode.getNextNode() != null) {
comparisonNode = comparisonNode.getNextNode();
}
else {
return;
}
} while (comparisonNode != null);
}
} // end of removeAll()
public void print(PrintStream out) {
// Implement me!
printAllNodesFrom(headNode, out);
} // end of print()
public void printAllNodesFrom(LinkedListNode headNode, PrintStream out) {
if (headNode == null) {
return;
}
System.out.println(headNode.getValue() + printDelim + headNode.getAppearancesInList());
//out.println(headNode.getValue() + printDelim + headNode.getAppearancesInList());
printAllNodesFrom(headNode.getNextNode(), out);
}
// public void printAllNodesFrom(LinkedListNode headNode) {
// if (headNode == null) {
// return;
// }
//// System.out.println(headNode.getValue() + printDelim + headNode.getAppearancesInList());
//// System.out.println(headNode.getValue() + printDelim + this.search((T)headNode.getValue()));
//
// printAllNodesFrom(headNode.getNextNode());
//
// }
} // end of class SortedLinkedListMultiset
|
package com.demo.student;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.demo.CustomObjectMapper;
import com.demo.ResponseWrapper;
import com.demo.ResponseWrapperList;
import com.demo.kafka.KafkaConfiguration;
import com.fasterxml.jackson.core.JsonProcessingException;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/students")
public class StudentRestController {
private final static String SUBMIT_ACTION = "submit";
private final static String EDIT_ACTION = "edit";
private final static String UNDO_DELETE_ACTION = "undo";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private StudentRepository studentRepository;
@Autowired
private StudentRedisService studentRedisService;
@GetMapping("/redis")
public Mono<ResponseEntity<ResponseWrapperList>> getAllFromRedis() {
Mono<List<Student>> result = studentRedisService.findAll().collectList();
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapperList(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseWrapperList(HttpStatus.NO_CONTENT.getReasonPhrase(),HttpStatus.NO_CONTENT.value())));
}
@GetMapping("/redis/{id}")
public Mono<ResponseEntity<ResponseWrapper>> getByIdFromRedis(
@PathVariable String id) {
Mono<Student> result = studentRedisService.findById(id);
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapper(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseWrapper(HttpStatus.NOT_FOUND.getReasonPhrase(),HttpStatus.NOT_FOUND.value())));
}
@GetMapping("/{id}")
public Mono<ResponseEntity<ResponseWrapper>> getById(
@PathVariable String id) {
Mono<Student> result = studentRedisService.findById(id) // 1. find in redis, if not found then
.switchIfEmpty(studentRepository.findById(id).flatMap(it -> { // 2. find in database, then
return studentRedisService.save(it); // 3. put to redis
}));
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapper(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseWrapper(HttpStatus.NOT_FOUND.getReasonPhrase(),HttpStatus.NOT_FOUND.value())));
}
@GetMapping
public Mono<ResponseEntity<ResponseWrapperList>> getListByParam(
@RequestParam(name = "name", required = false) String name) {
Mono<List<Student>> result = studentRepository.findByName("%"+name+"%").collectList();
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapperList(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseWrapperList(HttpStatus.NO_CONTENT.getReasonPhrase(),HttpStatus.NO_CONTENT.value())));
}
@PostMapping
public Mono<ResponseEntity<ResponseWrapper>> create(
@RequestParam(name = "action", required = false) String action, // available action: SUBMIT
@RequestBody Student student) {
student = validate(student, new Student(UUID.randomUUID().toString()), action);
Mono<Student> result = studentRedisService.save(student).flatMap(v -> (
v.getStatus().equals(
StudentRedisService.SUBMITTED_STATUS)? // insert into database when status = submitted
studentRepository.save(v):Mono.just(v)
))
.doOnSuccess(v -> {
try {
this.kafkaTemplate.send(KafkaConfiguration.TOPIC, new CustomObjectMapper().writeValueAsString(v));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}); // -> Kafka
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapper(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseWrapper(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),HttpStatus.INTERNAL_SERVER_ERROR.value())));
}
@PutMapping("/{id}")
public Mono<ResponseEntity<ResponseWrapper>> update(
@PathVariable String id,
@RequestParam(name = "action", required = false) String action, // available action: SUBMIT | EDIT
@RequestBody(required = false) Student student) {
Mono<Student> result = studentRedisService.findById(id).switchIfEmpty(studentRepository.findById(id)).map(v -> (validate(student, v, action))).flatMap(v -> (studentRedisService.update(id, v).flatMap(x -> (
v.getStatus().equals(
StudentRedisService.SUBMITTED_STATUS)? // insert into database when status = submitted
studentRepository.save(v):Mono.just(x)
))));
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapper(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseWrapper(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),HttpStatus.INTERNAL_SERVER_ERROR.value())));
}
@DeleteMapping("/{id}")
public Mono<ResponseEntity<ResponseWrapper>> delete(
@PathVariable String id,
@RequestParam(name = "action", required = false) String action // available action: UNDO_DELETE
) {
if(action != null && action.equals(UNDO_DELETE_ACTION)) {
Mono<Student> result = studentRedisService.findById(id).flatMap(v -> (studentRepository.save(v)));
return result
.map(s -> ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapper(s)))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseWrapper(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),HttpStatus.INTERNAL_SERVER_ERROR.value())));
}
Mono<Void> result = studentRepository.findById(id).flatMap(v -> {
v.setDeletedDate(LocalDateTime.now());
return studentRedisService.save(v);
}).then(studentRepository.deleteById(id));
return result.then(Mono.just(ResponseEntity.status(HttpStatus.OK).body(new ResponseWrapper())));
}
private Student validate(Student _student, Student data, String action) {
Student student = data;
if(_student != null) {
student.setName(_student.getName());
student.setMale(_student.getMale());
student.setGrade(_student.getGrade()); // check if user granted to change this value
if(data.getCreatedDate() != null) {
student.setLastModifiedDate(LocalDateTime.now());
}
}
if(action == null) {
if(student.getStatus() == null) student.setStatus(StudentRedisService.DRAFTED_STATUS);
}else {
if(action.equals(SUBMIT_ACTION)) { // make sure user login is authorized for this action
student.setStatus(StudentRedisService.SUBMITTED_STATUS);
}
if(action.equals(EDIT_ACTION)) { // make sure user login is authorized for this action
student.setStatus(StudentRedisService.DRAFTED_STATUS);
}
}
return student;
}
}
|
package com.rev.dao.spring;
import com.rev.dao.AbsenceRepository;
import com.rev.model.Absence;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class AbsenceSpringRepository extends SpringRepository<Absence> implements AbsenceRepository {
@Autowired
public AbsenceSpringRepository(SessionFactory sf){
super(sf);
}
}
|
package com.hamatus.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.envers.Audited;
import org.hibernate.envers.RelationTargetAuditMode;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A SectorTranslation.
*/
@Entity
@Table(name = "sector_translation")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "sectortranslation")
@Audited
public class SectorTranslation extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(min = 3, max = 2048)
@Column(name = "description", length = 2048, nullable = false)
private String description;
@NotNull
@Size(min = 2, max = 5)
@Column(name = "lang_key", length = 5, nullable = false)
private String langKey;
@ManyToOne
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
private Sector sector;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Sector getSector() {
return sector;
}
public void setSector(Sector sector) {
this.sector = sector;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SectorTranslation sectorTranslation = (SectorTranslation) o;
if(sectorTranslation.id == null || id == null) {
return false;
}
return Objects.equals(id, sectorTranslation.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "SectorTranslation{" +
"id=" + id +
", description='" + description + "'" +
", langKey='" + langKey + "'" +
'}';
}
}
|
package com.inform.model;
import java.io.Serializable;
import java.time.LocalDateTime;
public class InformVO implements Serializable, Comparable<InformVO>{
private String mem_no;
private String notice_content;
private LocalDateTime notice_time;
private String notice_title;
public InformVO() {
super();
}
public InformVO(String mem_no, String notice_content, LocalDateTime notice_time, String notice_title) {
super();
this.mem_no = mem_no;
this.notice_content = notice_content;
this.notice_time = notice_time;
this.notice_title = notice_title;
}
public String getMem_no() {
return mem_no;
}
public void setMem_no(String mem_no) {
this.mem_no = mem_no;
}
public String getNotice_content() {
return notice_content;
}
public void setNotice_content(String notice_content) {
this.notice_content = notice_content;
}
public LocalDateTime getNotice_time() {
return notice_time;
}
public void setNotice_time(LocalDateTime notice_time) {
this.notice_time = notice_time;
}
public String getNotice_title() {
return notice_title;
}
public void setNotice_title(String notice_titl) {
this.notice_title = notice_titl;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((notice_time == null) ? 0 : notice_time.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InformVO other = (InformVO) obj;
if (notice_time == null) {
if (other.notice_time != null)
return false;
} else if (!notice_time.equals(other.notice_time))
return false;
return true;
}
@Override
public int compareTo(InformVO o) {
if(this.notice_time.isAfter(o.notice_time)) {
return -1;
}else if(this.notice_time.isBefore(o.getNotice_time())) {
return 1;
}else
return 0;
}
@Override
public String toString() {
return "InformVO [mem_no=" + mem_no + ", notice_content=" + notice_content + ", notice_time=" + notice_time
+ ", notice_titl=" + notice_title + "]";
}
}
|
/*
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.cloud.cloudant.v1.model;
import java.util.List;
import java.util.Map;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* The putCloudantSecurityConfiguration options.
*/
public class PutCloudantSecurityConfigurationOptions extends GenericModel {
protected String db;
protected Map<String, List<String>> cloudant;
protected SecurityObject admins;
protected SecurityObject members;
protected Boolean couchdbAuthOnly;
/**
* Builder.
*/
public static class Builder {
private String db;
private Map<String, List<String>> cloudant;
private SecurityObject admins;
private SecurityObject members;
private Boolean couchdbAuthOnly;
private Builder(PutCloudantSecurityConfigurationOptions putCloudantSecurityConfigurationOptions) {
this.db = putCloudantSecurityConfigurationOptions.db;
this.cloudant = putCloudantSecurityConfigurationOptions.cloudant;
this.admins = putCloudantSecurityConfigurationOptions.admins;
this.members = putCloudantSecurityConfigurationOptions.members;
this.couchdbAuthOnly = putCloudantSecurityConfigurationOptions.couchdbAuthOnly;
}
/**
* Instantiates a new builder.
*/
public Builder() {
}
/**
* Instantiates a new builder with required properties.
*
* @param db the db
* @param cloudant the cloudant
*/
public Builder(String db, Map<String, List<String>> cloudant) {
this.db = db;
this.cloudant = cloudant;
}
/**
* Builds a PutCloudantSecurityConfigurationOptions.
*
* @return the new PutCloudantSecurityConfigurationOptions instance
*/
public PutCloudantSecurityConfigurationOptions build() {
return new PutCloudantSecurityConfigurationOptions(this);
}
/**
* Set the db.
*
* @param db the db
* @return the PutCloudantSecurityConfigurationOptions builder
*/
public Builder db(String db) {
this.db = db;
return this;
}
/**
* Set the cloudant.
*
* @param cloudant the cloudant
* @return the PutCloudantSecurityConfigurationOptions builder
*/
public Builder cloudant(Map<String, List<String>> cloudant) {
this.cloudant = cloudant;
return this;
}
/**
* Set the admins.
*
* @param admins the admins
* @return the PutCloudantSecurityConfigurationOptions builder
*/
public Builder admins(SecurityObject admins) {
this.admins = admins;
return this;
}
/**
* Set the members.
*
* @param members the members
* @return the PutCloudantSecurityConfigurationOptions builder
*/
public Builder members(SecurityObject members) {
this.members = members;
return this;
}
/**
* Set the couchdbAuthOnly.
*
* @param couchdbAuthOnly the couchdbAuthOnly
* @return the PutCloudantSecurityConfigurationOptions builder
*/
public Builder couchdbAuthOnly(Boolean couchdbAuthOnly) {
this.couchdbAuthOnly = couchdbAuthOnly;
return this;
}
}
protected PutCloudantSecurityConfigurationOptions(Builder builder) {
com.ibm.cloud.sdk.core.util.Validator.notEmpty(builder.db,
"db cannot be empty");
com.ibm.cloud.sdk.core.util.Validator.notNull(builder.cloudant,
"cloudant cannot be null");
db = builder.db;
cloudant = builder.cloudant;
admins = builder.admins;
members = builder.members;
couchdbAuthOnly = builder.couchdbAuthOnly;
}
/**
* New builder.
*
* @return a PutCloudantSecurityConfigurationOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the db.
*
* Path parameter to specify the database name.
*
* @return the db
*/
public String db() {
return db;
}
/**
* Gets the cloudant.
*
* Database permissions for Cloudant users and/or API keys.
*
* @return the cloudant
*/
public Map<String, List<String>> cloudant() {
return cloudant;
}
/**
* Gets the admins.
*
* Schema for names and roles to map to a database permission.
*
* @return the admins
*/
public SecurityObject admins() {
return admins;
}
/**
* Gets the members.
*
* Schema for names and roles to map to a database permission.
*
* @return the members
*/
public SecurityObject members() {
return members;
}
/**
* Gets the couchdbAuthOnly.
*
* Manage permissions using the `_users` database only.
*
* @return the couchdbAuthOnly
*/
public Boolean couchdbAuthOnly() {
return couchdbAuthOnly;
}
}
|
package gov.nih.mipav.model.provenance;
import javax.swing.event.ChangeEvent;
/**
*
* Provenance Change event for listeners to update (jtable provenance viewing)
*
*/
public class ProvenanceChangeEvent extends ChangeEvent{
private ProvenanceEntry entry;
/**
* default constructor
* @param source the source of the event
* @param entry the provenance entry
*/
public ProvenanceChangeEvent(Object source, ProvenanceEntry entry){
super(source);
this.entry = entry;
}
/**
* Retrieves the provenance entry
* @return the entry
*/
public ProvenanceEntry getEntry(){
return entry;
}
}
|
/*
* 1) abstract class don't need implement abstract method
* 2) 'abstract'(modifier) method can only declared in abstract class.
*
*/
package Inheritance;
/**
*
* @author YNZ
*/
interface A{
void doSomething();
void getInfor();
}
abstract class B implements A{
//abstract class don't need implement abstracted method.
}
class C extends B{
@Override
public void doSomething() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
//abstract void getinfor();
@Override
public void getInfor() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
public class NotImpAbstract {
}
|
/*
* 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 app.action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.ResultPath;
/**
*
* @author bruceoutdoors
*/
@ResultPath("/WEB-INF/content/error")
public class ErrorAction extends ActionSupport {
public String id;
public String index() {
return "404";
}
public String show() {
return id;
}
}
|
package pl.rafalmag.xmasgiftsdrawer;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
public class MainApplication extends Application {
private MainApplicationComponent component;
@Override
public void onCreate() {
super.onCreate();
// component = DaggerMainApplicationComponent.builder()
// .xmasGiftsDrawerModule(new XmasGiftsDrawerModule())
// .build();
component = DaggerMainApplicationComponent.create();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
public static MainApplicationComponent getComponent(Context context) {
return ((MainApplication) context.getApplicationContext()).component;
}
}
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.GoodsSpecification;
@Repository("goodsSpecificationDAO")
public class GoodsSpecificationDAO extends GenericDAO<GoodsSpecification> {
}
|
package com.infoworks.lab.util.services.impl;
import com.infoworks.lab.rest.models.Message;
import com.infoworks.lab.util.services.iProperties;
import com.it.soul.lab.sql.entity.EntityInterface;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Consumer;
public class ApplicationProperties implements iProperties {
private boolean createIfNotExist() throws RuntimeException{
if (path == null) return false;
if (!Files.exists(path)){
File props = path.toFile();
try {
return props.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
return false;
}
private Path path;
private final Properties configProp = new Properties();
public ApplicationProperties(String name) throws RuntimeException {
this(name, new HashMap<>());
}
public ApplicationProperties(String name, Map<String, String> defaultConfig) throws RuntimeException {
if (!name.endsWith(".properties")){
throw new RuntimeException("Doesn't have file extension as properties");
}
this.path = Paths.get(name);
if(createIfNotExist()) System.out.println("File Created!");
load(defaultConfig);
}
private void load(Map<String, String> defaultConfig) throws RuntimeException {
if (path == null) return;
//Private constructor to restrict new instances
System.out.println("Reading all properties from the file: " + path.toAbsolutePath().toString());
try(InputStream in = new FileInputStream(path.toFile())) {
configProp.load(in);
if (configProp.isEmpty()
&& (defaultConfig != null && !defaultConfig.isEmpty())){
configProp.putAll(defaultConfig);
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
public void flush() {
if (path == null) return;
try(OutputStream stream = new FileOutputStream(path.toFile())) {
configProp.store(stream,"Properties file updated: " + path.toAbsolutePath().toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void save(boolean async) {
flush();
}
public String read(String key) {
return configProp.getProperty(key, "");
}
@Override
public void put(String key, String value) {
configProp.setProperty(key, value);
}
@Override
public String replace(String key, String value) {
return (String) configProp.replace(key, value);
}
@Override
public String remove(String key) {
return (String) configProp.remove(key);
}
public String fileName() {
if (path == null) return "";
return path.getFileName().toString();
}
@Override
public int size() {
return configProp.size();
}
@Override
public boolean contains(String value) {
return configProp.contains(value);
}
@Override
public boolean containsKey(String key) {
return configProp.containsKey(key);
}
@Override
public void clear() {
configProp.clear();
}
@Override
public <E extends EntityInterface> void putObject(String key, E value) throws IOException{
String json = Message.marshal(value);
String base64 = Base64.getEncoder().encodeToString(json.getBytes());
put(key, base64);
}
@Override
public <E extends EntityInterface> E getObject(String key, Class<E> type) throws IOException{
String base64 = read(key);
String json = new String(Base64.getDecoder().decode(base64));
if (!Message.isValidJson(json)) throw new IOException("Invalid Json Format!");
return Message.unmarshal(type, json);
}
@Override
public String[] readSync(int offset, int pageSize) {
int size = this.size();
int maxItemCount = Math.abs(offset) + Math.abs(pageSize);
if (maxItemCount <= size) {
String[] values = configProp.values().toArray(new String[0]);
List<String> res = Arrays.asList(values).subList(Math.abs(offset), maxItemCount);
return res.toArray(new String[0]);
}
return new String[0];
}
@Override
public void readAsync(int offset, int pageSize, Consumer<String[]> consumer) {
if(consumer != null) {
consumer.accept(readSync(offset, pageSize));
}
}
}
|
package Root;
import java.util.*;
/**
*@Author: Sofia
*@Email: feng-sofia@foxmail.com
*@Date: 2019/5/31 13:58
*@Description: 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
*
* 例如:
* 给定二叉树: [3,9,20,null,null,15,7],
* 引用队列,将每层的root放进,值存进list中,将包含每层的值的list放进最终的返回队列中
*/
public class LevelOrder {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> que = new LinkedList<>();
que.add(root);
while (!que.isEmpty()) {
int count = que.size();
List<Integer> list = new ArrayList<>();
while (count > 0) {
TreeNode node = que.poll();
list.add(node.val);
if (node.right != null) {
que.add(node.right);
}
if (node.left != null) {
que.add(node.left);
}
count--;
}
res.add(list);
}
return res;
}
//先序深度优先算法,
public void DFSlervelOrderHelper(TreeNode root,int depth,List<List<Integer>> ans){
if (root == null){
return;
}
//如果采用中序/后序遍历,需要将if改成while
if (depth >= ans.size()){
ans.add(new ArrayList<>());
}
ans.get(depth).add(root.val);
DFSlervelOrderHelper(root.left,depth + 1,ans);
DFSlervelOrderHelper(root.right, depth+1, ans);
}
}
|
package com.atguigu.java3;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import org.junit.Test;
/**
转换流:
作用 : 1.读取文件时可以将字节流转成字符流 ,写出内容时可以将字符流转成字节流
2.可以将读取内容的编码集(utf-8)在写入另一个文件时变成另一种编码集(gbk)
*/
public class IOStreamTest {
/*
* 编码集的转换
*
* 注意 : InputStreamReader中设置的编码集必须和读取文件内容的编码集一致
*/
@Test
public void test2() throws Exception{
FileInputStream fis = new FileInputStream("char8.txt");
InputStreamReader isr = new InputStreamReader(fis,"gbk");
FileOutputStream fos = new FileOutputStream("999.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
//一边读一边写
char[] c = new char[1024];
int len = 0;
while((len = isr.read(c)) != -1){
//写内容
osw.write(c, 0, len);
}
//关流
isr.close();
osw.close();
fos.close();
fis.close();
}
/*
* 字节流和字符流的转换
*/
@Test
public void test() throws Exception{
FileInputStream fis = new FileInputStream("333.txt");
InputStreamReader isr = new InputStreamReader(fis);
FileOutputStream fos = new FileOutputStream("999.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
//一边读一边写
char[] c = new char[1024];
int len = 0;
while((len = isr.read(c)) != -1){
//写内容
osw.write(c, 0, len);
}
//关流
isr.close();
osw.close();
fos.close();
fis.close();
}
}
interface MyInterface{
void show(InputStream is);
}
|
package com.example2.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.example2.models.User;
public class CSVAccessor implements Accessor {
private static BufferedReader in = null;
private static BufferedWriter out = null;
public static final String CSV_FILE = "/Applications/eclipse/workspace/ExampleProject2/csv.csv";
// public static void main(String... args) throws IOException {
// List<User> users = getAllUsers();
// for (User user : users) {
// System.out.println(user.getName());
// }
// System.out.println("****");
// User currentUser = getUser("mary");
// System.out.println(currentUser.getName());
// System.out.println("****");
// User newUser = new User("anoop", "anoop", 27);
// saveUser(newUser);
// }
@Override
public List<User> getAllUsers() {
List<User> userList = null;
try {
in = new BufferedReader(new FileReader(CSV_FILE));
String userRecord = "";
int count = 0;
String username = "";
String password = "";
int age = 0;
User currentUser = null;
userRecord = in.readLine();
if (userRecord != null) {
userList = new ArrayList<User>();
}
while (userRecord != null) {
if (!userRecord.equals("")) {
String[] explode = userRecord.split(",");
count = explode.length;
if (count == 3) {
username = explode[0];
password = explode[1];
age = Integer.parseInt(explode[2]);
currentUser = new User(username, password, age);
userList.add(currentUser);
}
}
userRecord = in.readLine();
}
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e1) {
System.out.println("Error reading CSV file");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("error closing file");
}
}
}
return userList;
}
@Override
public User getUser(String userName) {
User currentUser = null;
List<User> userList = null;
userList = getAllUsers();
if (userList != null) {
for (User user : userList) {
if (user.getName().equals(userName)) {
currentUser = user;
}
}
}
return currentUser;
}
@Override
public boolean saveUser(User user) {
boolean returnValue = false;
StringBuffer sb = new StringBuffer();
sb.append(user.getName());
sb.append(",");
sb.append(user.getPassword());
sb.append(",");
sb.append(user.getAge() + "\n");
try {
out = new BufferedWriter(new FileWriter(CSV_FILE, true));
out.append(sb);
returnValue = true;
} catch (IOException e) {
System.out.println("Error writing to output file");
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
System.out.println("Error in closing the output file");
}
}
}
return returnValue;
}
}
|
package Excepciones;
public class SocioException extends Exception {
private static final long serialVersionUID = 6812041000672289692L;
public SocioException() {
super("NO HAY SOCIOS");
}
}
|
package org.dbdoclet.tidbit.perspective.panel.docbook;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import org.dbdoclet.jive.widget.GridPanel;
import org.dbdoclet.service.ResourceServices;
import org.dbdoclet.tidbit.common.Context;
public class TitleProperties extends GridPanel {
private static final long serialVersionUID = 1L;
private ResourceBundle res;
public TitleProperties(Context context) {
res = context.getResourceBundle();
createGui();
}
private void createGui() {
setBorder(BorderFactory.createTitledBorder(ResourceServices.getString(res,"C_TITLE")));
}
}
|
package enfieldacademy.spotifystreamer.fragments;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import enfieldacademy.spotifystreamer.R;
import enfieldacademy.spotifystreamer.SpotifyListHelper;
import enfieldacademy.spotifystreamer.adapters.ArtistsSearchResultAdapter;
import kaaes.spotify.webapi.android.SpotifyApi;
import kaaes.spotify.webapi.android.SpotifyService;
import kaaes.spotify.webapi.android.models.Artist;
import kaaes.spotify.webapi.android.models.ArtistsPager;
import kaaes.spotify.webapi.android.models.Pager;
public class BandSearchFragment extends Fragment {
// to satisfy looking for bands with very short names like U2, but also trying to respect API limits
private final int NUM_OF_CHARS_BEFORE_SEARCH = 1;
private ArtistsSearchResultAdapter mArtistsSearchResultAdapter;
private SpotifyService mSpotify;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SpotifyApi api = new SpotifyApi();
mSpotify = api.getService();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_band_search, container, false);
EditText musicSearchBox = (EditText) rootView.findViewById(R.id.music_search_box);
musicSearchBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(s.length() > NUM_OF_CHARS_BEFORE_SEARCH) {
SearchArtistsTask search = new SearchArtistsTask(s.toString());
search.execute();
}
}
});
ListView lv = (ListView) rootView.findViewById(R.id.searchListView);
mArtistsSearchResultAdapter = new ArtistsSearchResultAdapter(getActivity());
lv.setAdapter(mArtistsSearchResultAdapter);
lv.setOnItemClickListener(mArtistsSearchResultAdapter);
return rootView;
}
public class SearchArtistsTask extends AsyncTask<Void, Void, List<Artist>> {
private String mSearchStr;
private Toast mToast;
public SearchArtistsTask(String searchStr){
this.mSearchStr = searchStr;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected List<Artist> doInBackground(Void... params) {
// added the asterisk so that partial names still find bands/singers
// for ex: 'Subli' will find Sublime whereas without an asterisk it would not
try {
ArtistsPager artistsPager = mSpotify.searchArtists(mSearchStr + "*");
Pager<Artist> pagerOfArtists = artistsPager.artists;
return pagerOfArtists.items;
} catch (Exception e){
return null;
}
}
@Override
protected void onPostExecute(List<Artist> artists) {
super.onPostExecute(artists);
// cancel current toast because a new action is being determined
// it could succeed or it could fail
if(mToast != null) mToast.cancel();
if(artists == null) {
mToast = Toast.makeText(getActivity(), "An unexpected error occurred! :(", Toast.LENGTH_SHORT);
mToast.show();
} else if(artists.isEmpty()){
mToast = Toast.makeText(getActivity(), "No artists found! Please try again.", Toast.LENGTH_SHORT);
mToast.show();
}
SpotifyListHelper.setArtistList(artists);
mArtistsSearchResultAdapter.notifyDataSetChanged();
}
}
}
|
package fr.esilv.s8.tdfinal;
/**
* Created by Pierre-Marie on 17/03/2017.
*/
public class Constants {
public static final String API_KEY = "AIzaSyBXJ8UmdjW_0OpKxOjVM3qSO-r4vydcOkI";
}
|
package com.san.braceletXUser;
import com.san.bracelet.Bracelet;
import com.san.user.User;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@Table(name = "bracelet_x_user")
@IdClass(BraceletXUserPK.class)
public class BraceletXUser {
@Id
@ManyToOne
private User user;
@Id
@ManyToOne
private Bracelet bracelet;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp bracelet_x_user_created_at;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Timestamp bracelet_x_user_cupdated_at;
public BraceletXUser() {
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Bracelet getBracelet() {
return bracelet;
}
public void setBracelet(Bracelet bracelet) {
this.bracelet = bracelet;
}
public Timestamp getBracelet_x_user_created_at() {
return bracelet_x_user_created_at;
}
public void setBracelet_x_user_created_at(Timestamp bracelet_x_user_created_at) {
this.bracelet_x_user_created_at = bracelet_x_user_created_at;
}
public Timestamp getBracelet_x_user_cupdated_at() {
return bracelet_x_user_cupdated_at;
}
public void setBracelet_x_user_cupdated_at(Timestamp bracelet_x_user_cupdated_at) {
this.bracelet_x_user_cupdated_at = bracelet_x_user_cupdated_at;
}
}
|
import java.util.Scanner;
public class Username {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the name:");
String myString = input.nextLine();
System.out.println("Welcome "+myString);
}
}
|
package com.gaoshin.appbooster.service;
import com.gaoshin.appbooster.entity.User;
public interface UserService {
User register(User user);
User login(User user);
User getUserById(String userId);
void sendMobileVerifyCode(String userId, String phone) throws Exception;
void verify(String userId, String code);
}
|
package strings_stringbuffer;
import java.util.Scanner;
public class Program8 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
while(str.contains("*")){
int index=str.indexOf("*");
String s=str.substring(index-1,index+2);
str=str.replace(s,"");
}
System.out.println(str);
}
}
|
package primosparalelos;
import java.util.ArrayList;
import java.util.Scanner;
import com.opencsv.CSVWriter;
import java.awt.Desktop;
import java.io.File;
import java.io.FileWriter;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
/**
*
* @author Ignacio Rivera F
*/
public class PrimosParalelos {
/**
* @param args the command line arguments
* @throws java.lang.InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// variable usadas para calcular el tiempo de ejecucion
long tInicio = 0;
long tFin = 0;
// almacena el tiempo de ejecucion de cada muestra
List<String[]> listaTiemos = new ArrayList<String[]>();
// encabezado
listaTiemos.add("n hilos;milisegundos;speed Up;cantidad de numeros primos".split(";"));
System.out.println("Ingrese el numero maximo de hilos");
Scanner sc = new Scanner(System.in);
int cantHilosMax = sc.nextInt();
if (cantHilosMax < 1 || cantHilosMax > 2000000) {
System.err.println("la cantidad de hilos solicitada es invaida");
System.exit(0);
}
long timeOne = 0;
// muestreo para 1 ha n hilos
for (int j = 1; j <= cantHilosMax; j++) {
// clase paralelizable
Primo[] vectorPrimos = new Primo[j];
Thread[] vecThread = new Thread[j];
// se definen las particiones del problema segun la cantidad de hilos de la muestra
for (int i = 0; i < vectorPrimos.length; i++) {
vectorPrimos[i] = new Primo((int)((i * (100000.0 / j))+1.0), (int)((i + 1.0) * (100000.0 / j)));
vecThread[i] = new Thread(vectorPrimos[i]);
}
//inicio de la ejecucion en paralelo
tInicio = System.currentTimeMillis();
for (int i = 0; i < vecThread.length; i++) {
vecThread[i].start();
}
for (int i = 0; i < vecThread.length; i++) {
vecThread[i].join();
}
// fin de la ejecucion en paralelo
tFin = System.currentTimeMillis();
long sumaCantPrimos = 0;
for (int i = 0; i < vectorPrimos.length; i++) {
sumaCantPrimos += vectorPrimos[i].cantPirmos;
}
if(j == 1){
timeOne = (tFin - tInicio);
}
double speedUP =(((double)timeOne)/(tFin - tInicio));
DecimalFormat BE_DF = (DecimalFormat)DecimalFormat.getNumberInstance(Locale.GERMAN);
String muestra = j + ";" + (tFin - tInicio)+";"+BE_DF.format(speedUP)+";"+sumaCantPrimos;
listaTiemos.add(muestra.split(";"));
}
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter("muestras.csv"), ';');
// se exportan los datos en un archivo .csv
writer.writeAll(listaTiemos);
writer.close();
} catch (Exception e) {
System.err.println("fallo la escritura del archivo muestras.csv");
return;
}
try {
File archivo = new File("muestras.csv");
Desktop.getDesktop().open(archivo);
File grafico = new File("Grafico.xlsx");
//se abre un archivo excel conectado al archivo .csv
Desktop.getDesktop().open(grafico);
} catch (Exception e) {
}
}
}
class Primo implements Runnable {
private int starN;
private int terminoN;
public long cantPirmos;
public Primo(int s, int t) {
this.starN = s; //inicio de la particion del problema
this.terminoN = t; // fin de la particion del problema
this.cantPirmos = 0;
}
@Override
public void run() {
for (int i = this.starN; i <= this.terminoN; i++) {
if(esPrimo(i)){
this.cantPirmos++;
}
}
}
/**
* evalua si un numero entero recibido por parametro es primo
*
* @param n
* @return
*/
private boolean esPrimo(int n) {
if (n < 2) {
return false;
}
for (int i = n - 1; i > 1; i--) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
|
package com.sneha.spring16.planetary;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
public class PdfParse {
public static void main(final String[] args) throws IOException, TikaException {
File folder = new File("/Users/SnehaS/Extra/");
convertPdfToText(folder);
}
public static void convertPdfToText(File folderName) {
try {
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
File[] listOfFiles = folderName.listFiles();
for (int i = 1; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
FileInputStream inputstream = new FileInputStream(listOfFiles[i]);
ParseContext pcontext = new ParseContext();
// parsing the document using PDF parser
PDFParser pdfparser = new PDFParser();
pdfparser.parse(inputstream, handler, metadata, pcontext);
String fileNameWithExtension = listOfFiles[i].getName();
int indexOfDot = fileNameWithExtension.indexOf(".");
String fileNameWithoutExtension = fileNameWithExtension.substring(0,indexOfDot);
File file = new File(
"/Users/SnehaS/Desktop/DR/planetaryIR-Repo/Sample-Data/" + fileNameWithoutExtension + ".txt");
// if file doesn't exist, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(handler.toString());
bw.close();
}
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/**
*
*/
package com.fidel.dummybank.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.fidel.dummybank.common.AccountCategory;
/**
* @author Swapnil
*
*/
@Entity
@Table(name = "account_info")
public class AccountInfo {
@Id
@GenericGenerator(name = "acc_no_seq", strategy = "com.fidel.dummybank.sequence.AccountNoSequenceGenerator")
@GeneratedValue(generator = "acc_no_seq")
@Column(name = "account_no")
private String accountNo;
private String category = AccountCategory.SAVING.toString();
private Integer accountBalance = 0;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "cust_id")
private CustomerInfo customerInfo;
/**
* @return the accountNo
*/
public String getAccountNo() {
return accountNo;
}
/**
* @param accountNo the accountNo to set
*/
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
/**
* @return the category
*/
public String getCategory() {
return category;
}
/**
* @param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* @return the accountBalance
*/
public Integer getAccountBalance() {
return accountBalance;
}
/**
* @param accountBalance the accountBalance to set
*/
public void setAccountBalance(Integer accountBalance) {
this.accountBalance = accountBalance;
}
/**
* @return the customerInfo
*/
public CustomerInfo getCustomerInfo() {
return customerInfo;
}
/**
* @param customerInfo the customerInfo to set
*/
public void setCustomerInfo(CustomerInfo customerInfo) {
this.customerInfo = customerInfo;
}
}
|
package com.appsala.app.services;
import java.util.List;
import java.util.Optional;
import com.appsala.app.entities.Bloco;
import org.springframework.stereotype.Service;
import com.appsala.app.repository.BlocoRepository;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class BlocoService {
@Autowired
private BlocoRepository blocoRepository;
public BlocoService() { }
public <S extends Bloco> S create(S entity) {
return blocoRepository.save(entity);
}
public <S extends Bloco> S update(S entity) {
return blocoRepository.save(entity);
}
public void deleteById(Integer id) {
blocoRepository.deleteById(id);
}
public Bloco findById(Integer id) {
Optional<Bloco> blocoOpt = blocoRepository.findById(id);
return blocoOpt.orElse(null);
}
public List<Bloco> findAll() {
return blocoRepository.findAll();
}
}
|
package com.zd.christopher.dao;
import com.zd.christopher.bean.Administrator;
public interface IAdministratorDAO extends IEntityDAO<Administrator>
{
public boolean updateCourse(Administrator administrator);
}
|
/* $Id$ */
package djudge.judge;
import djudge.dservice.DServiceTask;
public class JudgeTaskDescription
{
public String tproblem;
public String tcontest;
public int tid;
public int fTrial;
public String tlanguage;
public String tsourcecode;
public JudgeTaskDescription()
{
}
public JudgeTaskDescription(DServiceTask task)
{
tproblem = task.getProblem();
tcontest = task.getContest();
fTrial = 0;
tlanguage = task.getLanguage();
tsourcecode = task.getSource();
tid = task.getID();
}
}
|
package com.bistel.tracereport.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
/**
*
* The Utility class to provide helper methods for Message/Trace report generation
*
*/
public class MessageGenUtil {
private static final DateFormat lotIdDf= new SimpleDateFormat("yyyyMMdd");
/**
*
* @param tid - numeric id of tool
* @return - Tool Id
*/
public static String getToolId(String tid){
String toolId= "T"+appendZeros(tid, 4);
return toolId;
}
/**
*
* @param stepId - numeric id of step
* @return STEP ID
*/
public static String getStepId(String stepId){
String stepIdStr="S"+appendZeros(String.valueOf(stepId), 4);
return stepIdStr;
}
/**
*
* @param toolId - TOOL ID
* @param modNum - numeric module number
* @return - MODULE ID
*/
public static String getModuleId(String toolId, int modNum){
String moduleId=toolId+"_M"+appendZeros(String.valueOf(modNum), 2);
return moduleId;
}
/**
*
* @param numParam - parameter number
* @return ParamName String
*/
public static String getParamName(int numParam){
String param= "P"+appendZeros(String.valueOf(numParam), 4);
return param;
}
/**
*
* @param cal- Calendar Instance
* @return - LOT ID
*/
public static String getLotId(Calendar cal){
String lotId = null;
Random rand= new Random();
int randVal= rand.nextInt(4);
//if(randVal>0){
int minutes= (cal.get(Calendar.HOUR_OF_DAY)*60+(cal.get(Calendar.MINUTE)/3)*3)%1440;
lotId= "L"+lotIdDf.format(cal.getTime())+"_"+appendZeros(String.valueOf(minutes), 4);
//}
//else {
//System.out.println("Returning lotid "+lotId);
//}
return lotId;
}
/**
*
* @param lotId - LOT ID
* @param cal - Calendar Instance
* @param modNum - module number
* @return
*/
public static String getSubstrateId(String lotId, Calendar cal,int modNum ){
String subsId = null;
if(null!= lotId){
subsId= lotId+cal.get(Calendar.MINUTE)+"."+appendZeros(String.valueOf(modNum), 2);
}
return subsId;
}
/**
* This method appends zeros as prefix to ensure totalLength
* @param val
* @param totalLength
* @return
*/
private static String appendZeros(String val, int totalLength){
StringBuilder sb = new StringBuilder(4);
if(null!= val ){
int len= totalLength-val.length();
for(int i=0;i<len;i++){
sb.append("0");
}
}
sb.append(val);
return sb.toString();
}
}
|
package be.dpms.medwan.webapp.wo.occupationalmedicine;
import be.dpms.medwan.common.model.vo.occupationalmedicine.RiskProfileRiskCodeVO;
import be.dpms.medwan.common.model.vo.occupationalmedicine.RiskCodeVO;
import be.mxs.common.model.vo.IIdentifiable;
import be.mxs.common.util.db.MedwanQuery;
import java.io.Serializable;
public class RiskProfileRiskCodeWO implements Serializable, IIdentifiable, Comparable {
public RiskProfileRiskCodeVO riskProfileRiskCodeVO;
public RiskCodeVO riskCodeVO;
public int compareTo(Object o){
int comp;
if (o.getClass().isInstance(this)){
comp = this.getRiskCodeVO().getLabel().compareTo(((RiskProfileRiskCodeWO)o).getRiskCodeVO().getLabel());
}
else {
throw new ClassCastException();
}
return comp;
}
public RiskProfileRiskCodeWO(RiskProfileRiskCodeVO riskProfileRiskCodeVO,String language) {
this.riskProfileRiskCodeVO = riskProfileRiskCodeVO;
this.riskCodeVO = MedwanQuery.getInstance().findRiskCode(riskProfileRiskCodeVO.riskCodeId.toString(),language);
}
public RiskProfileRiskCodeVO getRiskProfileRiskCodeVO(){
return riskProfileRiskCodeVO;
}
public RiskCodeVO getRiskCodeVO(){
return riskCodeVO;
}
}
|
package com.eigenmusik.api.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
/**
* Configure the API for OAuth.
*/
@Configuration
public class OAuthConfiguration {
@Configuration
@EnableAuthorizationServer
public static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("myAuthenticationManager")
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
return new JwtAccessTokenConverter();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("web")
.authorities("ROLE_USER", "ROLE_CLIENT")
.authorizedGrantTypes("password")
.resourceIds(EigenMusikConfiguration.RESOURCE_ID)
.secret("secret")
.scopes("read", "write");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.checkTokenAccess("permitAll()");
}
}
@Configuration
@EnableResourceServer
public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
return new JwtAccessTokenConverter();
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setTokenEnhancer(accessTokenConverter());
defaultTokenServices.setClientDetailsService(clientDetailsService);
resources.resourceId(EigenMusikConfiguration.RESOURCE_ID).tokenServices(defaultTokenServices);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/tracks/**", "/source/**").permitAll()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
}
|
/*
* 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.dao.annotation;
import jakarta.persistence.PersistenceException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.junit.jupiter.api.Test;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.RepositoryInterface;
import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.RepositoryInterfaceImpl;
import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.StereotypedRepositoryInterfaceImpl;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.stereotype.Repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class PersistenceExceptionTranslationPostProcessorTests {
@Test
@SuppressWarnings("resource")
public void proxiesCorrectly() {
GenericApplicationContext gac = new GenericApplicationContext();
gac.registerBeanDefinition("translator",
new RootBeanDefinition(PersistenceExceptionTranslationPostProcessor.class));
gac.registerBeanDefinition("notProxied", new RootBeanDefinition(RepositoryInterfaceImpl.class));
gac.registerBeanDefinition("proxied", new RootBeanDefinition(StereotypedRepositoryInterfaceImpl.class));
gac.registerBeanDefinition("classProxied", new RootBeanDefinition(RepositoryWithoutInterface.class));
gac.registerBeanDefinition("classProxiedAndAdvised",
new RootBeanDefinition(RepositoryWithoutInterfaceAndOtherwiseAdvised.class));
gac.registerBeanDefinition("myTranslator",
new RootBeanDefinition(MyPersistenceExceptionTranslator.class));
gac.registerBeanDefinition("proxyCreator",
BeanDefinitionBuilder.rootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class).
addPropertyValue("order", 50).getBeanDefinition());
gac.registerBeanDefinition("logger", new RootBeanDefinition(LogAllAspect.class));
gac.refresh();
RepositoryInterface shouldNotBeProxied = (RepositoryInterface) gac.getBean("notProxied");
assertThat(AopUtils.isAopProxy(shouldNotBeProxied)).isFalse();
RepositoryInterface shouldBeProxied = (RepositoryInterface) gac.getBean("proxied");
assertThat(AopUtils.isAopProxy(shouldBeProxied)).isTrue();
RepositoryWithoutInterface rwi = (RepositoryWithoutInterface) gac.getBean("classProxied");
assertThat(AopUtils.isAopProxy(rwi)).isTrue();
checkWillTranslateExceptions(rwi);
Additional rwi2 = (Additional) gac.getBean("classProxiedAndAdvised");
assertThat(AopUtils.isAopProxy(rwi2)).isTrue();
rwi2.additionalMethod(false);
checkWillTranslateExceptions(rwi2);
assertThatExceptionOfType(DataAccessResourceFailureException.class).isThrownBy(() ->
rwi2.additionalMethod(true))
.withMessage("my failure");
}
protected void checkWillTranslateExceptions(Object o) {
assertThat(o).isInstanceOf(Advised.class);
assertThat(((Advised) o).getAdvisors()).anyMatch(
PersistenceExceptionTranslationAdvisor.class::isInstance);
}
@Repository
public static class RepositoryWithoutInterface {
public void nameDoesntMatter() {
}
}
public interface Additional {
void additionalMethod(boolean fail);
}
public static class RepositoryWithoutInterfaceAndOtherwiseAdvised extends StereotypedRepositoryInterfaceImpl
implements Additional {
@Override
public void additionalMethod(boolean fail) {
if (fail) {
throw new PersistenceException("my failure");
}
}
}
public static class MyPersistenceExceptionTranslator implements PersistenceExceptionTranslator {
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
if (ex instanceof PersistenceException) {
return new DataAccessResourceFailureException(ex.getMessage());
}
return null;
}
}
@Aspect
public static class LogAllAspect {
@Before("execution(void *.additionalMethod(*))")
public void log(JoinPoint jp) {
// System.out.println("Before " + jp.getSignature().getName());
}
}
}
|
/**
* <copyright>
* </copyright>
*
*
*/
package ssl.resource.ssl.grammar;
public class SslWhiteSpace extends ssl.resource.ssl.grammar.SslFormattingElement {
private final int amount;
public SslWhiteSpace(int amount, ssl.resource.ssl.grammar.SslCardinality cardinality) {
super(cardinality);
this.amount = amount;
}
public int getAmount() {
return amount;
}
public String toString() {
return "#" + getAmount();
}
}
|
package com.ut.database.dao;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import com.ut.database.entity.UUID;
/**
* author : chenjiajun
* time : 2018/12/14
* desc :
*/
@Dao
public interface UUIDDao {
@Query("SELECT * FROM uuid ORDER BY id desc LIMIT 1")
UUID findUUID();
@Insert
void insertUUID(UUID uuid);
@Query("DELETE FROM uuid")
void deleteUUID();
}
|
package fr.skytasul.quests.stages;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PlayerDeathEvent;
import fr.skytasul.quests.api.stages.AbstractStage;
import fr.skytasul.quests.api.stages.StageCreation;
import fr.skytasul.quests.gui.ItemUtils;
import fr.skytasul.quests.gui.creation.stages.Line;
import fr.skytasul.quests.gui.misc.DamageCausesGUI;
import fr.skytasul.quests.players.PlayerAccount;
import fr.skytasul.quests.structure.QuestBranch;
import fr.skytasul.quests.structure.QuestBranch.Source;
import fr.skytasul.quests.utils.Lang;
import fr.skytasul.quests.utils.XMaterial;
public class StageDeath extends AbstractStage {
private List<DamageCause> causes;
public StageDeath(QuestBranch branch, List<DamageCause> causes) {
super(branch);
this.causes = causes;
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Player p = event.getEntity();
if (!hasStarted(p)) return;
if (!causes.isEmpty()) {
EntityDamageEvent lastDamage = p.getLastDamageCause();
if (lastDamage == null) return;
if (!causes.contains(lastDamage.getCause())) return;
}
if (canUpdate(p, true)) finishStage(p);
}
@Override
protected String descriptionLine(PlayerAccount acc, Source source) {
return Lang.SCOREBOARD_DIE.toString();
}
@Override
protected void serialize(ConfigurationSection section) {
if (!causes.isEmpty()) section.set("causes", causes.stream().map(DamageCause::name).collect(Collectors.toList()));
}
public static StageDeath deserialize(ConfigurationSection section, QuestBranch branch) {
List<DamageCause> causes;
if (section.contains("causes")) {
causes = section.getStringList("causes").stream().map(DamageCause::valueOf).collect(Collectors.toList());
}else {
causes = Collections.emptyList();
}
return new StageDeath(branch, causes);
}
public static class Creator extends StageCreation<StageDeath> {
private static final int CAUSES_SLOT = 7;
private List<DamageCause> causes;
public Creator(Line line, boolean ending) {
super(line, ending);
line.setItem(CAUSES_SLOT, ItemUtils.item(XMaterial.SKELETON_SKULL, Lang.stageDeathCauses.toString()), (p, item) -> {
new DamageCausesGUI(causes, newCauses -> {
setCauses(newCauses);
reopenGUI(p, true);
}).create(p);
});
}
public void setCauses(List<DamageCause> causes) {
this.causes = causes;
line.editItem(CAUSES_SLOT, ItemUtils.lore(line.getItem(CAUSES_SLOT), Lang.optionValue.format(causes.isEmpty() ? Lang.stageDeathCauseAny : Lang.stageDeathCausesSet.format(causes.size()))));
}
@Override
public void start(Player p) {
super.start(p);
setCauses(Collections.emptyList());
}
@Override
public void edit(StageDeath stage) {
super.edit(stage);
setCauses(stage.causes);
}
@Override
protected StageDeath finishStage(QuestBranch branch) {
return new StageDeath(branch, causes);
}
}
}
|
package mantra;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.tool.Grammar;
import java.io.IOException;
public class Parse {
public static final String MantraGrammar =
"/Users/parrt/mantra/code/grammar/src/grammar/mantra/Mantra.g4";
public static void main(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
String fileName = args[i];
ParseTree t = parse(fileName, MantraGrammar, "compilationUnit");
}
}
public static ParseTree parse(String fileName,
String combinedGrammarFileName,
String startRule)
throws IOException
{
final Grammar g = Grammar.load(combinedGrammarFileName);
LexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRFileStream(fileName));
CommonTokenStream tokens = new CommonTokenStream(lexEngine);
ParserInterpreter parser = g.createParserInterpreter(tokens);
try {
ParseTree t = parser.parse(g.getRule(startRule).index);
System.out.println("parse tree: " + t.toStringTree(parser));
((ParserRuleContext)t).inspect(parser);
return t;
}
catch (RecognitionException re) {
DefaultErrorStrategy strat = new DefaultErrorStrategy();
strat.reportError(parser, re);
}
return null;
}
/*
public static ParseTree parse(String fileNameToParse,
String lexerGrammarFileName,
String parserGrammarFileName,
String startRule)
throws IOException
{
Tool antlr = new Tool();
final LexerGrammar lg = (LexerGrammar)antlr.loadGrammar(lexerGrammarFileName);
final Grammar pg = loadGrammar(antlr, parserGrammarFileName, lg);
ANTLRFileStream input = new ANTLRFileStream(fileNameToParse);
LexerInterpreter lexEngine = lg.createLexerInterpreter(input);
CommonTokenStream tokens = new CommonTokenStream(lexEngine);
ParserInterpreter parser = pg.createParserInterpreter(tokens);
try {
ParseTree t = parser.parse(pg.getRule(startRule).index);
System.out.println("parse tree: "+t.toStringTree(parser));
return t;
}
catch (RecognitionException re) {
DefaultErrorStrategy strat = new DefaultErrorStrategy();
strat.reportError(parser, re);
}
return null;
}
// Same as loadGrammar(fileName) except import vocab from existing lexer
public static Grammar loadGrammar(Tool tool, String fileName, LexerGrammar lexerGrammar) {
GrammarRootAST grammarRootAST = tool.parseGrammar(fileName);
final Grammar g = tool.createGrammar(grammarRootAST);
g.fileName = fileName;
g.importVocab(lexerGrammar);
tool.process(g, false);
return g;
}
*/
}
|
package kz.greetgo.file_storage.impl;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.result.DeleteResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import kz.greetgo.file_storage.FileDataReader;
import kz.greetgo.file_storage.FileStorage;
import kz.greetgo.file_storage.FileStoringOperation;
import kz.greetgo.file_storage.FileUpdatingOperation;
import kz.greetgo.file_storage.errors.NoFileName;
import kz.greetgo.file_storage.errors.NoFileWithId;
import kz.greetgo.file_storage.errors.NoParam;
import org.bson.BsonObjectId;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.types.ObjectId;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.include;
import static com.mongodb.client.model.Updates.set;
import static kz.greetgo.file_storage.impl.MongoUtil.toByteArray;
import static kz.greetgo.file_storage.impl.MongoUtil.toDate;
import static kz.greetgo.file_storage.impl.MongoUtil.toMap;
import static kz.greetgo.file_storage.impl.MongoUtil.toStr;
class FileStorageMongodb implements FileStorage {
private final FileStorageBuilderInMongodbImpl builder;
FileStorageMongodb(FileStorageBuilderInMongodbImpl builder) {this.builder = builder;}
@Override
public FileDataReader read(String fileId) throws NoFileWithId {
FileDataReader reader = readOrNull(fileId);
if (reader == null) {
throw new NoFileWithId(fileId);
}
return reader;
}
@Override
public FileDataReader readOrNull(String fileId) {
final Document record = builder.collection
.find(eq(builder.names.id, fileId))
.projection(include(
builder.names.name,
builder.names.mimeType,
builder.names.createdAt,
builder.names.fileParam
))
.first();
if (record == null) {
return null;
}
return new FileDataReader() {
@Override
public String name() {
return toStr(record.get(builder.names.name));
}
byte[] data = null;
final Object sync = new Object();
@Override
public byte[] dataAsArray() {
{
byte[] data = this.data;
if (data != null) {
return data;
}
}
synchronized (sync) {
{
byte[] data = this.data;
if (data != null) {
return data;
}
}
return data = loadData();
}
}
private byte[] loadData() {
final Document record = builder.collection
.find(eq(builder.names.id, fileId))
.projection(include(builder.names.content))
.first();
if (record == null) {
throw new NullPointerException("record == null for fileId = " + fileId);
}
return toByteArray(record.get(builder.names.content));
}
@Override
public Date createdAt() {
return toDate(record.get(builder.names.createdAt));
}
@Override
public String mimeType() {
return toStr(record.get(builder.names.mimeType));
}
@Override
public String paramValue(String paramName) {
Map<String, String> map = toMap(record.get(builder.names.fileParam));
for (Map.Entry<String, String> entry : map.entrySet()) {
if (Objects.equals(paramName, entry.getKey())) {
return entry.getValue();
}
}
return null;
}
@Override
public Map<String, String> allParams() {
return toMap(record.get(builder.names.fileParam));
}
@Override
public String id() {
return fileId;
}
@Override
public void writeTo(OutputStream out) {
try {
out.write(dataAsArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
}
@Override
public void delete(String fileId) throws NoFileWithId {
DeleteResult deleteResult = builder.collection.deleteOne(eq(builder.names.id, fileId));
if (deleteResult.getDeletedCount() < 1) {
throw new NoFileWithId(fileId);
}
}
@Override
public FileStoringOperation storing() {
return new FileStoringOperation() {
String name = null;
@Override
public FileStoringOperation name(String name) {
this.name = name;
Function<String, String> mimeTypeExtractor = builder.parent.mimeTypeExtractor;
if (mimeTypeExtractor != null) {
mimeType = mimeTypeExtractor.apply(name);
}
return this;
}
String name() {
if (builder.parent.mandatoryName && name == null) {
throw new NoFileName();
}
return name;
}
Date createdAt = null;
@Override
public FileStoringOperation createdAt(Date createdAt) {
this.createdAt = createdAt;
return this;
}
String mimeType = null;
@Override
public FileStoringOperation mimeType(String mimeType) {
this.mimeType = mimeType;
return this;
}
String mimeType() {
return builder.parent.validateMimeType(mimeType);
}
byte[] data = null;
@Override
public FileStoringOperation data(byte[] data) {
Objects.requireNonNull(data);
this.data = data;
inputStream = null;
return this;
}
InputStream inputStream = null;
@Override
public FileStoringOperation data(InputStream inputStream) {
Objects.requireNonNull(inputStream);
data = null;
this.inputStream = inputStream;
return this;
}
byte[] data() {
if (inputStream != null) {
return LocalUtil.readAll(inputStream);
}
if (data != null) {
return data;
}
throw new RuntimeException("No data to insert");
}
private String presetFileId = null;
@Override
public FileStoringOperation presetId(String presetFileId) {
this.presetFileId = presetFileId;
return this;
}
private Map<String, String> param = new HashMap<>();
@Override
public FileStoringOperation param(String paramName, String paramValue) {
if (paramName == null || paramValue == null) {
throw new NoParam();
}
param.put(paramName, paramValue);
return this;
}
@Override
public String store() {
ensureIndex();
String id = presetFileId;
if (id == null) {
id = builder.parent.idGenerator(IdGeneratorType.HEX12).get();
}
Date createdAt = this.createdAt;
if (createdAt == null) {
createdAt = new Date();
}
Document insert = new Document();
insert.append(builder.names.id, id);
insert.append(builder.names.name, name());
insert.append(builder.names.mimeType, mimeType());
insert.append(builder.names.content, data());
insert.append(builder.names.createdAt, createdAt);
if (param != null) {
insert.append(builder.names.fileParam, param);
}
builder.collection.insertOne(insert);
return id;
}
};
}
@Override
public FileUpdatingOperation updating() {
return new FileUpdatingOperation() {
boolean isNameSet = false;
String newName = null;
@Override
public FileUpdatingOperation name(String name) {
isNameSet = true;
newName = name;
return this;
}
Map<String, String> param = new HashMap<>();
@Override
public FileUpdatingOperation param(String name, String newValue) {
if (name == null) {
throw new NoParam();
}
param.put(name, newValue);
return this;
}
@Override
public void store(String fileId) {
if (isNameSet) {
Objects.requireNonNull(fileId, "File ID is expected to be not null");
builder.parent.checkName(newName);
BsonValue bsonId = convertToBsonId(fileId);
builder.collection.updateOne(eq("id", fileId), set(builder.names.name, newName));
}
if(!param.isEmpty()) {
param.forEach( (key, value) -> builder.collection.updateOne(eq("id", fileId), set(builder.names.fileParam + "." + key, value)));
}
}
};
}
private BsonObjectId convertToBsonId(String id) {
byte[] idBytes;
try {
idBytes = HexUtil.hexToBytes(id);
} catch (HexUtil.HexConvertException e) {
throw new IllegalId("V1qliS7dFl :: id must be hex string" + " for 12 bytes: " + e.getMessage(), e);
}
if (idBytes.length != 12) {
throw new IllegalId("id must be hex string for 12 bytes," + " but now length = " + idBytes.length + " : id = `" + id + "`");
}
ObjectId objectId = new ObjectId(idBytes);
return new BsonObjectId(objectId);
}
private final AtomicBoolean ensureIndexWasCalled = new AtomicBoolean(false);
private void ensureIndex() {
if (ensureIndexWasCalled.get()) {
return;
}
ensureIndexWasCalled.set(true);
IndexOptions options = new IndexOptions();
options.unique(true);
Document index = new Document();
index.append(builder.names.id, 1);
builder.collection.createIndex(index, options);
}
}
|
package com.hengda.dongying.ui;
import com.hengda.dongying.R;
import org.kymjs.kjframe.KJActivity;
public class MainActivity extends KJActivity {
@Override
public void setRootView() {
setContentView(R.layout.activity_main);
}
}
|
/*
* 文件名:EnrolService.java 版权:Copyright by www.chinauip.com 描述: 修改人:Administrator 修改时间:2017年2月23日
* 跟踪单号: 修改单号: 修改内容:
*/
package com.jyzx.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jyzx.common.CommonService;
import com.jyzx.otherDBSource.JinXinDbService;
import com.jyzx.po.HttpResult;
import com.jyzx.util.CommonUtil;
import com.jyzx.util.FilterParam;
/**
* 检查是否被列入企业经营异常名录或严重违法失信企业名单的;不能做简易注销
* @author suwy
* @version 2017年2月23日
* @see EnrolService
* @since
*/
@Service("enrolService")
public class EnrolService extends CommonService
{
@Autowired
private JinXinDbService jinXinDbService;
/**
*
*/
public EnrolService()
{}
/*
* 描述: 被列入企业经营异常名录或严重违法失信企业名单的;不能做简易注销<br>
* @param regno 注册号
* @param uniscid 统一社会代码
* @return 结果
* @see
*/
public HttpResult checkIsEnrol(String regno, String uniscid)
{
HttpResult result = new HttpResult();
boolean isExist = false;
if (regno.equals("") && uniscid.equals(""))
{
result.setResult("fail");
result.setMessage("注册号,统一社会信用代码不能同时为空");
return result;
}
List<Map<String, String>> res = null;
List<FilterParam> params = new ArrayList<FilterParam>();
StringBuffer sbf = new StringBuffer(); // 检查内资信息表,查找企业的信息
sbf.append("select regno from TB_ZC_NZ_BASEINFO where ENTSTATE LIKE '003%'");
sbf.append(CommonUtil.handlerCondition(regno, uniscid, params));
sbf.append(" union all ");
sbf.append("select regno from TB_ZC_WZ_BASEINFO where ENTSTATE LIKE '003%'");// 再查外资表
sbf.append(CommonUtil.handlerCondition(regno, uniscid, params));
sbf.append(" FETCH FIRST 1 ROWS ONLY");
res = (List<Map<String, String>>)commonDao.listAll(sbf.toString(),
params.toArray(new FilterParam[params.size()]));
switch (res.size())
{
case 0:
result.setResult("fail");
result.setMessage("查找不到该企业的相关信息");
break;
case 1:
isExist = true;
break;
default:
result.setResult("fail");
result.setMessage("查询异常");
}
if (isExist)
{
String nregno = res.get(0).get("regno");
// 经营异常名录
String sql = "select count(*) from TB_SHS_ENTITY where sregno=? and sremovetype is null";
Object[] param = {nregno};
int num = jinXinDbService.getCount(sql, param);
if (num > 0)
{
result.setResult("yes");
result.setMessage("该企业在经营异常名录中有记录");
return result;
}
// 严重违法:
sql = "select count(*) from TB_YZWF_APPROVE where sregno=? and ssptype='001' and isdelete='0'";
num = jinXinDbService.getCount(sql, param);
if (num > 0)
{
result.setResult("yes");
result.setMessage("该企业在严重违法中有记录");
return result;
}
result.setResult("no");
result.setMessage("没有被列入");
return result;
}
return result;
}
}
|
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.commons.lang.StringUtils.trim;
public class Main {
public static void main(String[] args) {
/*String account = DES_Base64_encode("N520520".getBytes(),"1234567890".getBytes()).toString();
String ac_password = DES_Base64_encode("N521521521".getBytes(),"1234567890".getBytes()).toString();
System.out.println(account+" : "+ac_password);*/
//String ac_password = DES_Base64_encode("a.123456".getBytes(),"1234567890".getBytes()).toString();
//System.out.println(" : "+ac_password);
//Test_StringBuffer();
//Test_Pattern();
/*Float num1;
String qq = "19.987";
num1 = Float.valueOf(qq.toString());
System.out.println(num1);*/
//System.out.println(MD5("admin"+"ClAdmin168^&*"+"20180123161600"));
// C:\Users\XS-021\Downloads\tunnelSignature.xls
// 读取文件
//Test_file_reader();
// 汉字校验
//Test_chinese_verify();
}
private static void Test_chinese_verify(){
String str = "qwertyuiop123;是";
System.out.println(str.getBytes().length);
System.out.println(str.length());
if(str.getBytes().length==str.length()){
System.out.println("没有汉字");
}else{
System.out.println("有汉字");
}
}
private static void Test_file_reader(){
String pathString = "c:"+File.separator+"Users"+File.separator+"XS-021"+
File.separator+"Downloads"+File.separator+"tunnelSignature.txt";
File file = new File(pathString);
BufferedReader reder = null;
try{
reder = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String string = null;
while ((string = reder.readLine()) != null) {
System.out.println(string);
}
}catch(Exception e){
}
}
private static void Test_file(){
String pathString = "c:"+File.separator+"Users"+File.separator+"XS-021"+
File.separator+"Downloads"+File.separator+"tunnelSignatures.txt";
File file = new File(pathString);
try {
FileInputStream fi = new FileInputStream(file);
HSSFWorkbook book = new HSSFWorkbook(fi);
//HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(new File("C:/Users/XS-021/Downloads/tunnelSignature.xls")));
System.out.println(book);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void Test_gateway(){
String spCode = "gateway:1-spcode:0401,gateway:2-spcode:12512141311," +
"gateway:2-spcode:123123123,gateway:1-spcode:12512141311,gateway:1-spcode:1111";
String[] s;
StringBuilder sbyd = new StringBuilder();
StringBuilder sblt = new StringBuilder();
StringBuilder sbdx = new StringBuilder();
s=spCode.split(",");
String yd="";
String lt="";
String dx="";
for (int i = 0; i < s.length; i++) {
//s[i]=s[i].replaceAll("gateway:,", "");
s[i]=s[i].replaceAll("spcode:", ",");
s[i]=s[i].replaceAll("gateway:1-", "Y");
s[i]=s[i].replaceAll("gateway:2-", "L");
s[i]=s[i].replaceAll("gateway:3-", "D");
if(s[i].startsWith("Y")){
sbyd.append(s[i].substring(2, s[i].length()) +",");
}
yd=sbyd+"";
//System.out.println(sbyd+"");
//System.out.println("sss "+new StringBuilder(yd).append(sbyd).toString());
if(s[i].startsWith("L")){
sblt.append(s[i].substring(2, s[i].length()) +",");
}
lt=sblt+"";
if(s[i].startsWith("D")){
sbdx.append(s[i].substring(2, s[i].length()) +",");
}
dx=sbdx+"";
}
String gateway_spcode="";
if(yd != "" && yd.length()>0){
gateway_spcode=gateway_spcode+"Y:"+yd;
}if(lt != "" && lt.length()>0){
gateway_spcode=gateway_spcode+"L:"+lt;
}if(dx != "" && dx.length()>0){
gateway_spcode=gateway_spcode+"D:"+dx;
}if(gateway_spcode.length()>0){
gateway_spcode=gateway_spcode.substring(0, gateway_spcode.length()-1);
}
System.out.println(gateway_spcode);
}
private static void Test_Pattern(){
String str = "16670306453";
// 正则表达式规则
String regEx = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
String regEx2 = "^\\d+$";
String regEx3 = "^0(.[0-9]+)?$";
String regEx4 = "^1[3456789]\\d{9}$";
String regEx5 = "((13)|(15)|(16)|(19)|(18)|(14)|(17))\\d{9}";
String regEx6 = "1\\d{2,10}";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx4);
Matcher matcher = pattern.matcher(str);
boolean rs = matcher.matches();
System.out.println(rs);
//Pattern.compile(regEx).matcher(str);
}
private static void Test_StringBuffer(){
String name = "gateway:1-name:李芳180通道产品,gateway:1-name:新产品-行业泰逗," +
"gateway:3-name:李芳180通道产品,gateway:2-name:李芳180通道产品";
StringBuilder sbyd=new StringBuilder();
StringBuilder sblt=new StringBuilder();
StringBuilder sbdx=new StringBuilder();
String[] stringArray;
stringArray = name.split(",");
String YD_product = "";
String LT_product = "";
String DX_product = "";
for(int i = 0; i < stringArray.length; i++){
stringArray[i] = stringArray[i].replaceAll("gateway:1-name","Y");
stringArray[i] = stringArray[i].replaceAll("gateway:2-name","L");
stringArray[i] = stringArray[i].replaceAll("gateway:3-name","D");
if(stringArray[i].startsWith("Y")){
sbyd.append(stringArray[i].substring(2,stringArray[i].length())+",");
}
YD_product = new StringBuilder(YD_product).append(sbyd).toString();
if(stringArray[i].startsWith("L")){
sblt.append(stringArray[i].substring(2,stringArray[i].length())+",");
}
LT_product = new StringBuilder(LT_product).append(sblt).toString();
if(stringArray[i].startsWith("D")){
sbdx.append(stringArray[i].substring(2,stringArray[i].length())+",");
}
DX_product = new StringBuilder(DX_product).append(sbdx).toString();
}
String name2 = "";
if(StringUtils.isNotBlank(YD_product)){
name2 = new StringBuilder(name2).append(new StringBuilder("移动通道产品:")).append(sbyd).toString();
}
if(StringUtils.isNotBlank(LT_product)){
name2 = new StringBuilder(name2).append(new StringBuilder("联通通道产品:")).append(sblt).toString();
}
if(StringUtils.isNotBlank(YD_product)){
name2 = new StringBuilder(name2).append(new StringBuilder("电信通道产品:")).append(sbdx).toString();
}
if(StringUtils.isNotBlank(name2)){
name2 = name2.substring(0,name2.length() - 1);
}
sbyd.delete(0, sbyd.length());
sblt.delete(0, sblt.length());
sbdx.delete(0, sbdx.length());
System.out.println(name2);
name2 = name2.replace(",联通",";联通");
name2 = name2.replace(",电信",";电信");
System.out.println("-------------------------");
System.out.println(name2);
}
/**
* DES加密 后 BASE64编码 DES:密钥12345678
* @param content
* @param keyBytes
* @return
*/
public static String DES_Base64_encode(byte[] content, byte[] keyBytes) {
try {
DESKeySpec keySpec = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(keySpec.getKey()));
byte[] result = cipher.doFinal(content);
return new String(Base64.encodeBase64(result));
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
/**
* MD5加密
* @param decript
* @return
*/
public static String MD5(String decript) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
return "";
}
}
}
class test {
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
|
package com.github.louism33.axolotl.moveordering;
import com.github.louism33.axolotl.search.EngineSpecifications;
import com.github.louism33.chesscore.Chessboard;
import com.github.louism33.chesscore.IllegalUnmakeException;
import org.junit.Assert;
import static com.github.louism33.axolotl.moveordering.MoveOrderingConstants.*;
import static com.github.louism33.axolotl.search.EngineSpecifications.*;
import static com.github.louism33.chesscore.MoveParser.*;
public class MoveOrderer {
private static boolean ready = false;
private static int[][] mateKillers;
private static int[][][] killerMoves;
private static int[][][] historyMoves;
public static final int MOVE_MASK = ~MOVE_SCORE_MASK;
public static void initMoveOrderer(){
mateKillers = new int[THREAD_NUMBER][128];
killerMoves = new int[THREAD_NUMBER][128][2];
historyMoves = new int[THREAD_NUMBER][64][64];
ready = true;
}
public static int getMoveScore (int moveScore){
Assert.assertTrue(moveScore > 0);
int i = (moveScore & MOVE_SCORE_MASK) >>> moveScoreOffset;
Assert.assertTrue(i > 0);
return i;
}
static int buildMoveScore(int move, int score){
Assert.assertTrue(move > 0);
Assert.assertTrue(score > 0);
int i1 = score << moveScoreOffset;
Assert.assertTrue(i1 > 0);
int i = move | i1;
Assert.assertTrue(i > 0);
return i;
}
public static void scoreMoves(int whichThread, int[] moves, Chessboard board, int ply,
int hashMove){
if (!ready) {
initMoveOrderer();
}
try {
scoreMovesHelper(whichThread, moves, board, ply, hashMove);
} catch (IllegalUnmakeException e) {
e.printStackTrace();
}
}
private static void scoreMovesHelper(int whichThread, int[] moves, Chessboard board, int ply,
int hashMove) throws IllegalUnmakeException {
for (int i = 0; i < moves.length; i++) {
if (moves[i] == 0){
break;
}
int move = moves[i];
Assert.assertTrue(move < MOVE_SIZE_LIMIT);
if (move == hashMove) {
moves[i] = buildMoveScore(moves[i], hashScore);
}
else if (mateKillers[whichThread][ply] != 0 && moves[i] == mateKillers[whichThread][ply]) {
Assert.assertTrue(mateKillers[whichThread][ply] < MOVE_SIZE_LIMIT);
moves[i] = buildMoveScore(moves[i], mateKillerScore);
}
else if (board.moveIsCaptureOfLastMovePiece(moves[i])) {
moves[i] = buildMoveScore(moves[i], CAPTURE_BIAS_LAST_MOVED_PIECE + mvvLVA(moves[i]));
}
else if (isPromotionToQueen(moves[i])) {
if (isCaptureMove(moves[i])) {
moves[i] = buildMoveScore(moves[i], queenCapturePromotionScore);
}
else {
moves[i] = buildMoveScore(moves[i], queenQuietPromotionScore);
}
}
else if (isPromotionToKnight(moves[i])) {
moves[i] = buildMoveScore(moves[i], knightPromotionScore);
}
else if (isPromotionToBishop(moves[i]) || isPromotionToRook(moves[i])) {
moves[i] = buildMoveScore(moves[i], uninterestingPromotion);
}
else if (isCaptureMove(moves[i])) {
moves[i] = buildMoveScore(moves[i], mvvLVA(moves[i]));
}
else if (killerMoves[whichThread][ply][0] != 0 && killerMoves[whichThread][ply][0] == moves[i]) {
Assert.assertTrue(killerMoves[whichThread][ply][0] < MOVE_SIZE_LIMIT);
moves[i] = buildMoveScore(moves[i], killerOneScore);
}
else if (killerMoves[whichThread][ply][1] != 0 && killerMoves[whichThread][ply][1] == moves[i]) {
Assert.assertTrue(killerMoves[whichThread][ply][1] < MOVE_SIZE_LIMIT);
moves[i] = buildMoveScore(moves[i], killerTwoScore);
}
else if (ply >= 2 && killerMoves[whichThread][ply - 2][0] != 0
&& killerMoves[whichThread][ply - 2][0] == moves[i]) {
Assert.assertTrue(killerMoves[whichThread][ply - 2][0] < MOVE_SIZE_LIMIT);
moves[i] = buildMoveScore(moves[i], oldKillerScoreOne);
}
else if (ply >= 2 && killerMoves[whichThread][ply - 2][1] != 0
&& killerMoves[whichThread][ply - 2][1] == (moves[i])) {
Assert.assertTrue(killerMoves[whichThread][ply - 2][1] < MOVE_SIZE_LIMIT);
moves[i] = buildMoveScore(moves[i], oldKillerScoreTwo);
}
else if (checkingMove(board, moves[i])) {
moves[i] = buildMoveScore(moves[i], giveCheckMove);
}
else if (isCastlingMove(moves[i])) {
moves[i] = buildMoveScore(moves[i], castlingMove);
}
else {
moves[i] = buildMoveScore(moves[i],
Math.max(historyMoveScore(whichThread, moves[i]), uninterestingMove));
}
}
}
private static int mvvLVA(int move){
int sourceScore = scoreByPiece(move, getMovingPieceInt(move));
int destinationScore = scoreByPiece(move, getVictimPieceInt(move));
return CAPTURE_BIAS + destinationScore - sourceScore;
}
private static int scoreByPiece(int move, int piece){
switch (piece){
case NO_PIECE:
return 0;
case WHITE_PAWN:
case BLACK_PAWN:
return 1;
case WHITE_KNIGHT:
case BLACK_KNIGHT:
return 3;
case WHITE_BISHOP:
case BLACK_BISHOP:
return 3;
case WHITE_ROOK:
case BLACK_ROOK:
return 5;
case WHITE_QUEEN:
case BLACK_QUEEN:
return 9;
case WHITE_KING:
case BLACK_KING:
return 10;
default:
throw new RuntimeException("score by piece problem "+ move);
}
}
/*
Quiescence Search ordering:
order moves by most valuable victim and least valuable aggressor
*/
public static void scoreMovesQuiescence(int[] moves, Chessboard board){
scoreMovesQuiescenceHelper(moves, board);
}
private static void scoreMovesQuiescenceHelper(int[] moves, Chessboard board){
for (int i = 0; i < moves.length; i++) {
if (moves[i] == 0){
break;
}
int move = moves[i];
if (isCaptureMove(move)) {
if (isPromotionMove(move) && isPromotionToQueen(move)) {
moves[i] = buildMoveScore(move, queenCapturePromotionScore);
} else if (board.moveIsCaptureOfLastMovePiece(moves[i])) {
moves[i] = buildMoveScore(move, CAPTURE_BIAS_LAST_MOVED_PIECE + mvvLVA(moves[i]));
} else {
moves[i] = buildMoveScore(move, mvvLVA(moves[i]));
}
} else if (isPromotionMove(move) && (isPromotionToQueen(moves[i]))) {
moves[i] = buildMoveScore(moves[i], queenQuietPromotionScore);
}
else {
moves[i] = 0;
}
}
}
public static boolean checkingMove(Chessboard board, int move) throws IllegalUnmakeException {
board.makeMoveAndFlipTurn(move);
boolean checkingMove = board.inCheck(board.isWhiteTurn());
board.unMakeMoveAndFlipTurn();
return checkingMove;
}
public static void updateHistoryMoves(int whichThread, int move, int ply){
historyMoves[whichThread][getSourceIndex(move)][getDestinationIndex(move)] += (2 * ply);
}
private static int historyMoveScore(int whichThread, int move){
int maxMoveScoreOfHistory = MAX_HISTORY_MOVE_SCORE;
int historyScore = historyMoves[whichThread][getSourceIndex(move)][getDestinationIndex(move)];
return historyScore > maxMoveScoreOfHistory ? maxMoveScoreOfHistory : historyScore;
}
public static void updateKillerMoves(int whichThread, int move, int ply){
Assert.assertTrue(move < MOVE_SIZE_LIMIT);
if (move != killerMoves[whichThread][ply][0]){
if (killerMoves[whichThread][ply][0] != 0) {
killerMoves[whichThread][ply][1] = killerMoves[whichThread][ply][0];
}
killerMoves[whichThread][ply][0] = move;
}
}
public static void updateMateKillerMoves(int whichThread, int move, int ply){
mateKillers[whichThread][ply] = move;
}
}
|
package io.github.cottonmc.libcd.mixin;
import io.github.cottonmc.libcd.impl.ResourceSearcher;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.List;
import net.minecraft.class_2960;
import net.minecraft.class_3262;
import net.minecraft.class_3264;
import net.minecraft.class_3294;
import net.minecraft.class_3300;
@Mixin(class_3294.class)
public abstract class MixinNamespaceResourceManager implements class_3300, ResourceSearcher {
@Shadow @Final protected List<class_3262> packList;
@Shadow @Final private class_3264 type;
@Shadow protected abstract boolean isPathAbsolute(class_2960 id);
public boolean libcd$contains(class_2960 id) {
if (!this.isPathAbsolute(id)) {
return false;
} else {
for(int i = this.packList.size() - 1; i >= 0; --i) {
class_3262 pack = this.packList.get(i);
if (pack.method_14411(this.type, id)) {
return true;
}
}
return false;
}
}
// @Inject(method = "findResources", at = @At("RETURN"), locals = LocalCapture.CAPTURE_FAILEXCEPTION)
// private void checkConditioalRecipes(String parent, Predicate<String> loadFilter, CallbackInfoReturnable<Collection<Identifier>> cir,
// List<Identifier> sortedResources) {
// List<Identifier> sortedCopy = new ArrayList<>(sortedResources);
// for (Identifier id : sortedCopy) {
// //don't try to load for things that use mcmetas already!
// if (id.getPath().contains(".mcmeta") || id.getPath().contains(".png")) continue;
// Identifier metaId = new Identifier(id.getNamespace(), id.getPath() + ".mcmeta");
// if (libcd$contains(metaId)) {
// try {
// Resource meta = getResource(metaId);
// String metaText = IOUtils.toString(meta.getInputStream(), Charsets.UTF_8);
// if (!ConditionalData.shouldLoad(id, metaText)) {
// sortedResources.remove(id);
// }
// } catch (IOException e) {
// CDCommons.logger.error("Error when accessing resource metadata for %s: %s", id.toString(), e.getMessage());
// }
// }
// }
// }
}
|
package multipleregression;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import utils.io.Read;
/**
*
* @author Luis
*/
public class Main {
public static void main(String[] args) {
System.out.println("Multiple Linear Regression Pre-Processing w/ Backward Elimination"
+ System.lineSeparator()
+ "Researchers: Anton Kovalyov, Luis Garay"
+ System.lineSeparator()
+ "Supervisor: Dr. Hansheng Lei"
+ System.lineSeparator());
Scanner input = new Scanner(System.in);
boolean choice = true;
while (choice) {
System.out.println("Run Multiple Regression w/ GUI - 1"
+ System.lineSeparator()
+ "Run Multiple Regression w/o GUI - 2"
+ System.lineSeparator()
+ "Stop Program - 5");
switch (input.next().charAt(0)) {
case '1':
System.out.println("Loading GUI...");
GUI.main(args);
break;
case '2':
System.out.println("Input dataset location: ");
String datasetLocation = input.next();
if (Read.isPathValid(datasetLocation)) {
MLR.run(datasetLocation);
} else {
System.out.println("Path is incorrect. Try again!");
}
break;
case '5':
choice = false;
break;
default:
System.out.println("Bad Input! Please try again!");
break;
}
}
}
private static int determineAttributeLength(String columnHeader) {
return StringUtils.split(columnHeader, ",").length;
}
}
|
package com.pwq.DesignPatterns.SimpleFactory.Mediator;
import java.util.ArrayList;
/**
* @Author:WenqiangPu
* @Description
* @Date:Created in 19:05 2017/11/2
* @Modified By:
*/
public abstract class Mediator {
protected ArrayList<Colleague> colleagues;
public void register(Colleague colleague){
colleagues.add(colleague);
}
public abstract void operation();
}
|
package com.pdd.pop.sdk.common.exception;
public class JsonParseException extends RuntimeException{
public JsonParseException() {
super("Json parse error");
}
}
|
package com.mercadolibre.android.ui;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
/**
* RelativeLayout with rounded corners.
*
* @since 19/04/2016
*/
public class RoundedRelativeLayout extends RelativeLayout {
private int radius;
/**
* Default constructor to use by code
*
* @param context the android context
*/
public RoundedRelativeLayout(final Context context) {
this(context, null);
}
/**
* Default constructor to use by XML
*
* @param context the android context
* @param attrs an attribute set
*/
public RoundedRelativeLayout(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Default constructor to use by XML
*
* @param context the android context
* @param attrs an attribute set
* @param defStyleAttr the default style attributes
*/
public RoundedRelativeLayout(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
final TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RoundedRelativeLayout, defStyleAttr, 0);
radius = a.getDimensionPixelSize(R.styleable.RoundedRelativeLayout_ui_cornerRadius, 0);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
// Turn off hardware acceleration for this view, because clipping is not supported.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
@Override
protected void dispatchDraw(final Canvas canvas) {
final Path path = new Path();
path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), radius, radius, Path.Direction.CW);
canvas.clipPath(path);
super.dispatchDraw(canvas);
}
@Override
public String toString() {
return "RoundedRelativeLayout{"
+ "radius=" + radius
+ '}';
}
}
|
package com.example.demo.exceptions;
import lombok.Builder;
import lombok.Getter;
/**
* Error Response definition to send to the requestor if there an error during processing of a request.
* This is used by ExceptionHandler {@link com.example.demo.QuestionsExceptionHandler.exceptions.QuestionsApiExceptionHandler}.
*
* @author Narasimha Reddy Guthireddy
*/
@Builder
@Getter
public class QuestionsErrorResponse {
private String errorCode;
private String message;
private String description;
}
|
package oj;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
public class JavaChecking {
private String fnamecompile;
private String fnamerun;
private String problemid;
private String problemidin;
private String problemiduserout;
private String problemidout;
private String p;
public JavaChecking(String fnamecompile,String problemid) {
//super();
this.fnamecompile = fnamecompile;
this.fnamerun= fnamecompile.substring(0, fnamecompile.length()-5);
//this.fnamerun="codef";
this.problemid = problemid;
this.problemidout = problemid+"_out.txt";
this.problemidin = problemid+"_in.txt";
this.problemiduserout = problemid+".txt";
//this.p=p;
System.out.println(fnamerun);
}
public String compilejava() {
int er=0;
//String compileString = "javac "+"Show1.java";
String compileString = "javac "+fnamecompile;
try {
Process process = Runtime.getRuntime().exec(compileString);
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
BufferedReader bre = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line ;
while((line=bre.readLine())!=null) {
System.out.println("error msg");
System.out.println(line);
er++;
}
bre.close();
while((line=br.readLine())!=null) {
//System.out.println("pp1");
System.out.println(line);
}
br.close();
//
//
process.destroy();
int k =process.exitValue();
System.out.println(k);
// //process.
is.close();
if(er!=0) {
return "Compilation Error";
}
else {
return runjava();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String runjava() {
int er=0;
long start,end;
try {
String []str = {"cmd"};
String []str1 = {"cmd","javac Show.java",fnamerun};
//Process process = Runtime.getRuntime().exec("java "+"Show1");
start = System.currentTimeMillis();
Process process = Runtime.getRuntime().exec("java "+fnamerun);
//Process process = new ProcessBuilder("cmd").start();
FileReader fr = new FileReader(problemidin);
BufferedReader brin = new BufferedReader(fr);
String lineString;
OutputStream os = process.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
while ((lineString = brin.readLine())!=null) {
//System.out.println(password);
bw.write(lineString+"\n");
System.out.println(lineString);
bw.flush();
}
// bw.write("kk\n");
System.out.println("kk");
int i=0;
boolean deadYet = false;
do {
Thread.sleep(1000);
try {
process.exitValue();
deadYet = true;
} catch (IllegalThreadStateException e) {
System.out.println("Not done yet...");
if (++i >= 5) {
process.destroyForcibly();
return "Time Limit Execeeded";
}
}
} while (!deadYet);
// bw.flush();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
BufferedReader bre = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line ;
// os.close();
// is.close();
//process.destroy();
while((line=bre.readLine())!=null) {
System.out.println("error msg");
System.out.println(line);
er++;
}
bre.close();
FileWriter fw1 = new FileWriter(problemiduserout);
FileWriter fw = new FileWriter(problemiduserout,true);
//fW.write("file writing\nnew");
PrintWriter pw = new PrintWriter(fw);
while((line=br.readLine())!=null) {
//System.out.println("pp");
System.out.println(line);
pw.println(line);
if (line.equals("")) {
System.out.println("equl");
}
}
pw.close();
//
//
//int k =process.waitFor(arg0, arg1)();
//System.out.println(k);
// //process.
os.close();
is.close();
//Thread.sleep(2000);
try {
process.exitValue();
//process.
//deadYet = true;
} catch (IllegalThreadStateException e) {
System.out.println("Not done yet2...");
process.destroy();
// if (++i >= 5) throw new RuntimeException("timeout");
}
//Thread.sleep(1100);
// if(!process.waitFor(114, TimeUnit.MILLISECONDS)) {
// System.out.println("pp");
// process.destroy();
// //return "Time Limit Execeeded";
// }
// System.out.println(start-(System.currentTimeMillis()));
System.out.println(process.isAlive());
if(process.isAlive()) {
System.out.println("pp");
process.destroy();
//return "Time Limit Execeeded";
}
process.destroy();
end = System.currentTimeMillis();
System.out.println("time"+(end-start));
// Scanner scanner = new Scanner(System.in);
// String readString = scanner.nextLine();
// System.out.println(readString);
if(er!=0) {
return "Runtime error";
}
else if ((end-start)>5000) {
System.out.println("time"+(end-start));
return "Time Limit Execeeded";
}
else {
return outputcheck();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String outputcheck() throws IOException, InterruptedException {
// String[] cmd1 = {"/bin/sh", "-c", "diff op.txt a.txt"};
// Process proc = Runtime.getRuntime().exec(cmd1);
// proc.waitFor();
// int j = proc.exitValue();
// if(j==0)
// return "Accepted";
// else
// return "Wrong Answer";
boolean result= false;
FileReader fr = new FileReader(problemidout);
BufferedReader bro = new BufferedReader(fr);
String lineString;
FileReader fr1 = new FileReader(problemiduserout);
BufferedReader bro1 = new BufferedReader(fr1);
String lineString1;
while (true) {
lineString = bro.readLine();
lineString1= bro1.readLine();
if (lineString==null && lineString1!=null) {
result=false;
break;
}else if (lineString!=null && lineString1==null) {
result=false;
break;
}
else if (lineString==null && lineString1==null) {
break;
}
if(lineString.equals(lineString1)) {
System.out.println(lineString +" "+lineString1);
result = true;
//break;
}
else {
result = false;
System.out.println(result);
break;
}
}
bro.close();
bro1.close();
if (result) {
System.out.println("cld");
return "Accepted";
}
else {
System.out.println("wa cld");
return "Wrong Answer";
}
//return null;
}
}
|
package com.finahub.coding.server.airtable;
import java.util.HashMap;
import java.util.Map;
import com.finahub.coding.server.vo.BankInfo;
public class AirtableBase {
@SuppressWarnings("rawtypes")
private final Map<String, Table> tableMap = new HashMap<>();
private final String baseName;
private final Airtable parent;
public AirtableBase(String val, Airtable airtable) {
baseName=val;
parent=airtable;
}
public Airtable airtable() {
return parent;
}
@SuppressWarnings("rawtypes")
public Table table(String name) {
return table(name, BankInfo.class);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Table table(String name, Class clazz) {
if(!tableMap.containsKey(name)) {
Table t = new Table(name, clazz);
t.setParent(this);
tableMap.put(name, t);
}
return tableMap.get(name);
}
public String name() {
return baseName;
}
}
|
package f.star.iota.milk.config;
import android.content.Context;
import android.content.SharedPreferences;
import f.star.iota.milk.SourceType;
public class SplashConfig {
public static int getSplashSource(Context context) {
SharedPreferences sp = context.getSharedPreferences("splash_config", Context.MODE_PRIVATE);
return sp.getInt("splash_background_source", SourceType.APIC);
}
public static void saveSplashSource(Context context, int type) {
SharedPreferences sp = context.getSharedPreferences("splash_config", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putInt("splash_background_source", type);
edit.apply();
}
}
|
package com.artogrid.bundle.sync.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class SyncBondOfferGroupDTO implements java.io.Serializable{
private long version;
private long lastVersion;
private String companyId;
private SyncBondOfferMethodDTO methodAdd;
private SyncBondOfferMethodDTO methodUpdate;
private SyncBondOfferMethodDTO methodDelete;
private SyncBondOfferMethodDTO methodRefer;
private SyncBondOfferMethodDTO methodDeal;
private SyncBondOfferMethodDTO methodUnRefer;
private SyncBondOfferMethodDTO methodAudit;
/**
* @return the methodAdd
*/
public SyncBondOfferMethodDTO getMethodAdd() {
return methodAdd;
}
/**
* @param methodAdd the methodAdd to set
*/
public void setMethodAdd(SyncBondOfferMethodDTO methodAdd) {
this.methodAdd = methodAdd;
}
/**
* @return the methodUpdate
*/
public SyncBondOfferMethodDTO getMethodUpdate() {
return methodUpdate;
}
/**
* @param methodUpdate the methodUpdate to set
*/
public void setMethodUpdate(SyncBondOfferMethodDTO methodUpdate) {
this.methodUpdate = methodUpdate;
}
/**
* @return the methodDelete
*/
public SyncBondOfferMethodDTO getMethodDelete() {
return methodDelete;
}
/**
* @param methodDelete the methodDelete to set
*/
public void setMethodDelete(SyncBondOfferMethodDTO methodDelete) {
this.methodDelete = methodDelete;
}
/**
* @return the methodRefer
*/
public SyncBondOfferMethodDTO getMethodRefer() {
return methodRefer;
}
/**
* @param methodRefer the methodRefer to set
*/
public void setMethodRefer(SyncBondOfferMethodDTO methodRefer) {
this.methodRefer = methodRefer;
}
/**
* @return the methodDeal
*/
public SyncBondOfferMethodDTO getMethodDeal() {
return methodDeal;
}
/**
* @param methodDeal the methodDeal to set
*/
public void setMethodDeal(SyncBondOfferMethodDTO methodDeal) {
this.methodDeal = methodDeal;
}
/**
* @return the methodUnRefer
*/
public SyncBondOfferMethodDTO getMethodUnRefer() {
return methodUnRefer;
}
/**
* @param methodUnRefer the methodUnRefer to set
*/
public void setMethodUnRefer(SyncBondOfferMethodDTO methodUnRefer) {
this.methodUnRefer = methodUnRefer;
}
/**
* @return the methodAudit
*/
public SyncBondOfferMethodDTO getMethodAudit() {
return methodAudit;
}
/**
* @param methodAudit the methodAudit to set
*/
public void setMethodAudit(SyncBondOfferMethodDTO methodAudit) {
this.methodAudit = methodAudit;
}
/**
* @return the companyId
*/
public String getCompanyId() {
return companyId;
}
/**
* @param companyId the companyId to set
*/
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
/**
* @return the version
*/
public long getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(long version) {
this.version = version;
}
/**
* @return the lastVersion
*/
public long getLastVersion() {
return lastVersion;
}
/**
* @param lastVersion the lastVersion to set
*/
public void setLastVersion(long lastVersion) {
this.lastVersion = lastVersion;
}
}
|
package com.bits.farheen.dhun.events;
import com.bits.farheen.dhun.models.SongsModel;
import java.util.ArrayList;
/**
* Created by farheen on 11/29/16
*/
public class QueueChange {
private int positionToPlay;
private ArrayList<SongsModel> queue;
public QueueChange(int positionToPlay, ArrayList<SongsModel> queue) {
this.queue = queue;
this.positionToPlay = positionToPlay;
}
public int getPositionToPlay() {
return positionToPlay;
}
public ArrayList<SongsModel> getQueue() {
return queue;
}
}
|
package my.myapps.service.transactional;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import my.myapps.model.dao.BranchDao;
import my.myapps.model.entity.Branch;
import my.myapps.model.entity.Topic;
import my.myapps.service.BranchService;
import my.myapps.service.transactional.TransactionalBranchService;
public class TransactionalBranchServiceTest
{
@Mock
private BranchDao branchDao;
private BranchService branchService;
@BeforeMethod
public void init() throws Exception {
initMocks(this);
branchService=new TransactionalBranchService(branchDao);
}
@Test
public void testGetBranches()
{
List<Branch> expectedBranches = new ArrayList<Branch>();
Mockito.when(branchDao.getTopLevelBranches()).thenReturn(expectedBranches);
List<Branch> actualBranches = branchService.getBranches();
assertEquals(actualBranches, expectedBranches, "Branch return list is different from expected");
Mockito.verify(branchDao).getTopLevelBranches();
}
@Test
public void testGetBranchTopics()
{
List<Topic> expectedTopics = new ArrayList<Topic>();
Mockito.when(branchDao.getBranchTopics(777L)).thenReturn(expectedTopics);
List<Topic> actualTopics = branchService.getBranchTopics(777L);
assertEquals(expectedTopics, actualTopics, "Topic return list is different from expected");
Mockito.verify(branchDao).getBranchTopics(777L);
}
}
|
package pattern.templateMethod;
public class TestaContas {
public static void main(String[] args) {
Conta cc = new ContaCorrente();
Conta cp = new ContaPoupanca();
cc.deposita(30.0);
cc.saca(10.0);
cp.deposita(30.0);
cp.deposita(10.0);
System.out.println("Saldo da conta corrente: "+cc.getSaldo());
System.out.println("Saldo da conta corrente: "+cp.getSaldo());
}
}
|
package haw.ci.lib.nodes;
import haw.ci.lib.SymbolTable;
import haw.ci.lib.descriptor.Descriptor;
public class ModuleNode extends AbstractNode {
private static final long serialVersionUID = 5975246380655596518L;
private IdentNode ident;
private DeclarationNode declaration;
private StatementSequenceNode statementSequence;
public ModuleNode(IdentNode ident, DeclarationNode declaration, StatementSequenceNode statementSequence) {
this.ident = ident;
this.declaration = declaration;
this.statementSequence = statementSequence;
}
public StatementSequenceNode getStatementSequence() {
return statementSequence;
}
public DeclarationNode getDeclaration() {
return declaration;
}
public IdentNode getIdent() {
return ident;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((declaration == null) ? 0 : declaration.hashCode());
result = prime * result + ((ident == null) ? 0 : ident.hashCode());
result = prime
* result
+ ((statementSequence == null) ? 0 : statementSequence
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ModuleNode other = (ModuleNode) obj;
if (declaration == null) {
if (other.declaration != null)
return false;
} else if (!declaration.equals(other.declaration))
return false;
if (ident == null) {
if (other.ident != null)
return false;
} else if (!ident.equals(other.ident))
return false;
if (statementSequence == null) {
if (other.statementSequence != null)
return false;
} else if (!statementSequence.equals(other.statementSequence))
return false;
return true;
}
@Override
public String toString(int indentation) {
String result = toString(indentation, this.getClass().getName() + "\n");
if(ident != null) {
result += ident.toString(indentation+1);
}
if(declaration != null) {
result += declaration.toString(indentation+1);
}
if(statementSequence != null) {
result += statementSequence.toString(indentation+1);
}
return result;
}
@Override
public Descriptor compile(SymbolTable symbolTable) {
write("PUSHS, " + ident.getValue());
write("JMP, 0");
declaration.compile(symbolTable);
write("LABEL, 0");
write(String.format("PUSHI, %d",symbolTable.size()));
write("SETSP");
statementSequence.compile(symbolTable);
write("STOP");
return null;
}
}
|
package com.lwc.user.bo;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* 资源 BO实体
* </p>
*
* @author Li
* @since 2019-07-29
*/
@Data
@NoArgsConstructor
@ApiModel(value="ResourceBo", description="资源 BO实体")
public class ResourceBo implements Serializable{
private static final long serialVersionUID = -1L;
@ApiModelProperty(value = "分布式主键")
private Long id;
@ApiModelProperty(value = "资源名称")
private String resourceName;
@ApiModelProperty(value = "资源类型 0-目录 1-菜单 2-按钮 3-接口")
private Integer resourceType;
@ApiModelProperty(value = "接口/连接地址")
private String url;
@ApiModelProperty(value = "接口方法")
private String method;
@ApiModelProperty(value = "是否忽略权限校验 0-否 1-是")
private Boolean ignoreFlag;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createAt;
@ApiModelProperty(value = "创建人")
private Long createBy;
@ApiModelProperty(value = "修改时间")
private LocalDateTime updateAt;
@ApiModelProperty(value = "修改人")
private Long updateBy;
@ApiModelProperty(value = "是否逻辑删除")
private Boolean deleteFlag;
@ApiModelProperty(value = "乐观锁字段")
private Integer version;
}
|
package cn.itcast.bookstore.order.dao;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import cn.itcast.bookstore.book.domain.Book;
import cn.itcast.bookstore.order.domain.Order;
import cn.itcast.bookstore.order.domain.OrderItem;
import cn.itcast.bookstore.order.domain.Report;
import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
public class OrderDao {
private QueryRunner qr = new TxQueryRunner();
/**
* 添加订单到数据库
*
* @param order
*/
public void addOrder(Order order) {
try {
String sql = "insert into orders values(?,?,?,?,?,?)";
Timestamp timestamp = new Timestamp(order.getOrdertime().getTime());
Object[] params = { order.getOid(), timestamp, order.getTotal(), order.getState(),
order.getOwner().getUid(), order.getAddress() };
qr.update(sql, params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 添加订单条目到订单
*
* @param orderItemList
*/
public void addOrderItemList(List<OrderItem> orderItemList) {
try {
String sql = "insert into orderitem values(?,?,?,?,?)";
Object[][] params = new Object[orderItemList.size()][];
for (int i = 0; i < orderItemList.size(); i++) {
OrderItem item = orderItemList.get(i);
params[i] = new Object[] { item.getIid(), item.getCount(), item.getSubtotal(), item.getOrder().getOid(),
item.getBook().getBid() };
}
qr.batch(sql, params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 我的订单
*
* @param uid
* @return
*/
public List<Order> findByUid(String uid) {
try {
/*
* 1.得到当前用户的所有订单
*/
String sql = "select * from orders where uid =?";
List<Order> orderList = qr.query(sql, new BeanListHandler<Order>(Order.class), uid);
/*
* 2.循环遍历每个Order,为其加载他自己所有的订单条目
*/
for (Order order : orderList) {
loadOrderItems(order);// 为order对象添加它的所有订单条目
}
return orderList;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 加载指定的订单的所有的订单条目
*
* @param order
* @throws SQLException
*/
private void loadOrderItems(Order order) throws SQLException {
// TODO Auto-generated method stub
/*
* 查询两张表:orderitem,book
*/
String sql = "select * from orderitem i , book b where i.bid = b.bid and oid =?";
List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), order.getOid());
List<OrderItem> orderItemList = toOrderItemList(mapList);
order.setOrderItemList(orderItemList);
}
/**
* 把每个mapList中的每个Map装换成两个对象,并建立关系(把一堆map转换成一堆orderItem)
*
* @param mapList
* @return
*/
private List<OrderItem> toOrderItemList(List<Map<String, Object>> mapList) {
List<OrderItem> orderItemList = new ArrayList<OrderItem>();
for (Map<String, Object> map : mapList) {
OrderItem item = toOrderItem(map);
orderItemList.add(item);
}
return orderItemList;
}
/**
* 把一个Map转换成一个OrderItem对象
*
* @param map
* @return
*/
private OrderItem toOrderItem(Map<String, Object> map) {
// TODO Auto-generated method stub
OrderItem orderItem = CommonUtils.toBean(map, OrderItem.class);
Book book = CommonUtils.toBean(map, Book.class);
orderItem.setBook(book);
return orderItem;
}
public Order load(String oid) {
try {
/*
* 1.得到当前用户的所有订单
*/
String sql = "select * from orders where oid =?";
Order order = qr.query(sql, new BeanHandler<Order>(Order.class), oid);
/*
* 2.为order加载他的所有条目
*/
loadOrderItems(order);// 为order对象添加它的所有订单条目
return order;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int getStateByOid(String oid) {
try {
String sql = "select state from orders where oid =?";
return (Integer) qr.query(sql, new ScalarHandler(), oid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateState(String oid, int state) {
try {
String sql = "update orders set state=? where oid=?";
qr.update(sql, state, oid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 找到所有的订单
public List<Order> findAllOrders() {
// TODO Auto-generated method stub
try {
String sql = "select * from orders ";
List<Order> orderList = qr.query(sql, new BeanListHandler<Order>(Order.class));
/*
* 2.循环遍历每个Order,为其加载他自己所有的订单条目
*/
for (Order order : orderList) {
loadOrderItems(order);// 为order对象添加它的所有订单条目
}
return orderList;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 后台找到各种状态的订单
*
* @param state
* @return
*/
public List<Order> findByState(String state) {
try {
String sql = "select * from orders where state = ?";
List<Order> orderList = qr.query(sql, new BeanListHandler<Order>(Order.class), state);
/*
* 2.循环遍历每个Order,为其加载他自己所有的订单条目
*/
for (Order order : orderList) {
loadOrderItems(order);// 为order对象添加它的所有订单条目
}
return orderList;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Order findById(String oid) {
// TODO Auto-generated method stub
try {
String sql = "select * from orders where oid = ? ";
return qr.query(sql, new BeanHandler<Order>(Order.class), oid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteOrders(String oid) {
try {
String sql1 = "delete from orderitem where oid = ?";
String sql = "delete from orders where oid = ?";
qr.update(sql1, oid);
qr.update(sql, oid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Report> report(){
try {
String sql = "select * from book left join (SELECT SUM(COUNT) AS totalCount, bid bidd FROM orderitem WHERE oid IN\r\n" +
"( SELECT DISTINCT oid FROM orders WHERE state = 4 OR state = 2 or state =3)GROUP BY bidd) t1 on book.bid= t1.bidd order by t1.totalCount desc LIMIT 0,5";
return qr.query(sql, new BeanListHandler<Report>(Report.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
|
package PageUI;
public class WithdrawalPageObject {
}
|
package com.grocery.codenicely.vegworld_new.about_us.view;
import com.grocery.codenicely.vegworld_new.about_us.model.data.AboutUsData;
/**
* Created by meghal on 13/10/16.
*/
public interface AboutUsView {
void showMessage(String message);
void showLoader(boolean show);
void setData(AboutUsData aboutUsData);
}
|
package com.daviga404.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.libs.com.google.gson.Gson;
import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder;
import com.daviga404.Plotty;
import com.daviga404.plots.Plot;
public class DataManager {
public File file;
public Gson gson;
public Plotty plugin;
public PlottyConfig config,defaultConfig;
public DataManager(Plotty plugin){
defaultConfig = new PlottyConfig();
defaultConfig.baseBlock = 1;
defaultConfig.centertp = true;
defaultConfig.clearEnabled = false;
defaultConfig.clearOnDelete = true;
defaultConfig.delCooldown = 30;
defaultConfig.enableEco = false;
defaultConfig.enableTnt = false;
defaultConfig.maxPlots = 5;
defaultConfig.playerGrantNotify = new String[]{};
defaultConfig.players = new PlottyPlayer[]{};
defaultConfig.plotCost = 0.0;
defaultConfig.plotHeight = 20;
defaultConfig.plotSize = 64;
defaultConfig.publicByDefault = true;
defaultConfig.surfaceBlock = 2;
defaultConfig.voteDelay = 12.0;
defaultConfig.worlds = new String[]{};
defaultConfig.flags = new HashMap<String,String>();
this.plugin = plugin;
try {
checkForFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public void checkDefaults(){
config.flags = config.flags == null ? defaultConfig.flags : config.flags;
config.playerGrantNotify = config.playerGrantNotify == null ? defaultConfig.playerGrantNotify : config.playerGrantNotify;
config.players = config.players == null ? defaultConfig.players : config.players;
config.worlds = config.worlds == null ? defaultConfig.worlds : config.worlds;
save();
}
/**
* Checks if the plots file exists and loads data into class.
* @throws IOException
*/
public void checkForFile() throws IOException{
if(!plugin.getDataFolder().exists()){
plugin.getDataFolder().mkdir();
}
file = new File(plugin.getDataFolder()+File.separator+"plots.json");
gson = new GsonBuilder().setPrettyPrinting().create();
if(!file.exists()){
file.createNewFile();
Bukkit.getLogger().info("Creating default plots file...");
FileWriter out = new FileWriter(file);
out.write(gson.toJson(defaultConfig));
out.flush();
config = defaultConfig;
Bukkit.getLogger().info("Created default plots file (plugins/Plotty/plots.json)");
}else{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String ln,buff="";
while((ln = br.readLine()) != null){
buff += ln;
}
config = gson.fromJson(buff, PlottyConfig.class);
Bukkit.getLogger().info("Plotty data loaded.");
}
checkDefaults();
}
/**
* Adds a plot to the config file and saves.
* @param p The plot to add
* @param owner The name of the owner of the plot
* @param id The ID of the plot
* @see getLatestId();
*/
public void addPlot(Plot p, String owner, int id){
PlottyPlayer player = getPlayer(owner);///////////////
PlottyPlot plot = new PlottyPlot();
plot.friends = new String[]{};
plot.id = id;
plot.world = p.getWorld().getName();
plot.x = p.getX();
plot.z = p.getZ();
plot.visible = config.publicByDefault;
player.plots = pushPlottyPlot(player.plots, plot);
config.players[pIndex(owner)] = player;
save();
}
/**
* Removes a plot from the config file and saves.
* @param id The ID of the plot
* @param owner The name of the owner
* @return Whether the task succeeded.
*/
public boolean removePlot(int id, String owner){
PlottyPlayer p = getPlayer(owner);
if(p == null) return false;
PlottyPlot[] newArray = new PlottyPlot[p.plots.length-1];
int i=0;
for(PlottyPlot plot : p.plots){
if(plot.id != id){
newArray[i] = plot;
i++;
}
}
p.plots = newArray;
if(pIndex(p.name) == -1) return false;
config.players[pIndex(p.name)] = p;
save();
return true;
}
/**
* Adds a friend to a plot in the config and saves.
* @param p The plot to add a friend to
* @param owner The name of the owner of the plot
* @param friend The friend to add
*/
public void addFriend(PlottyPlot p, String owner, String friend){
p.friends = pushString(p.friends, friend);
PlottyPlayer player = getPlayer(owner);
player.plots[plotIndex(p.id, player)] = p;
config.players[pIndex(owner)] = player;
save();
}
/**
* Removes a friend from a plot in the config and saves.
* @param p The plot to remove a friend from
* @param owner The name of the plot owner
* @param friend The name of the friend to remove.
*/
public void removeFriend(PlottyPlot p, String owner, String friend){
boolean exists=false;
for(String cf : p.friends){
if(friend.equalsIgnoreCase(cf)){
exists = true;
}
}
if(!exists){return;}
String[] newFriends = new String[p.friends.length-1];
int added=0;
for(String cfriend : p.friends){
if(!friend.equalsIgnoreCase(cfriend)){
newFriends[added] = cfriend;
added++;
}
}
p.friends = newFriends;
PlottyPlayer player = getPlayer(owner);
player.plots[plotIndex(p.id, player)] = p;
config.players[pIndex(owner)] = player; //Don't you just love fixed size arrays... T_T
save();
}
/**
* Gets a plot object from coordinates of corner.
* @param x The X location of the plot corner.
* @param z The Z location of the plot corner.
* @return A plot object (null if not found)
*/
public PlottyPlot getPlotFromCoords(int x,int z){
for(PlottyPlayer p : config.players){
for(PlottyPlot pl : p.plots){
if(pl.x == x && pl.z == z){
return pl;
}
}
}
return null;
}
/**
* Gets a plot object from an ID.
* @param id The ID of the plot.
* @return
*/
public PlottyPlot getPlotFromId(int id){
for(PlottyPlayer p : config.players){
for(PlottyPlot pl : p.plots){
if(pl.id == id){
return pl;
}
}
}
return null;
}
/**
* Gets the owner of a plot from the plot object.
* @param pl The plot to find the owner of.
* @return The name of the plot owner (null if not found)
*/
public String getPlotOwner(PlottyPlot pl){
for(PlottyPlayer p : config.players){
for(PlottyPlot pp : p.plots){
if(pp.id == pl.id){
return p.name;
}
}
}
return null;
}
/**
* Gets the index of a plot in a player's config file (used to replace plots with new info)
* @param id The ID of the plot.
* @param p The player file of the owner of the plot.
* @return The index of the plot in a player's file. Returns -1 if not found.
*/
public int plotIndex(int id, PlottyPlayer p){
int i=0;
for(PlottyPlot pl : p.plots){
if(pl.id == id){
return i;
}
i++;
}
return -1;
}
/**
* Gets the index of a player in the config file (used to replace player files with new info)
* @param p The name of the player (case insensitive)
* @return The index of a player in the config file. Returns -1 if not found.
*/
public int pIndex(String p){
int i=0;
for(PlottyPlayer pl : config.players){
if(pl.name.equalsIgnoreCase(p)){
return i;
}
i++;
}
return -1;
}
/**
* Gets if the player has reached their maximum number of plots.
* @param name The name of the player.
* @return A boolean that is true if the player has reached their maximum number of plots.
*/
public boolean pExceededMaxPlots(String name){
int count = getPlayer(name).plots.length;
int max = getPlayer(name).maxPlots == -1 ? config.maxPlots : getPlayer(name).maxPlots;
return count >= max;
}
//Utils
public PlottyPlot[] pushPlottyPlot(PlottyPlot[] array, PlottyPlot object){
PlottyPlot[] newArray = new PlottyPlot[array.length+1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[newArray.length-1] = object;
return newArray;
}
public PlottyPlayer[] pushPlottyPlayer(PlottyPlayer[] array, PlottyPlayer object){
PlottyPlayer[] newArray = new PlottyPlayer[array.length+1];
System.arraycopy(array,0,newArray,0,array.length);
newArray[newArray.length-1] = object;
return newArray;
}
public String[] pushString(String[] array, String object){
String[] newArray = new String[array.length+1];
System.arraycopy(array,0,newArray,0,array.length);
newArray[newArray.length-1] = object;
return newArray;
}
public PlottyPlayer getPlayer(String name){
for(PlottyPlayer p : config.players){
if(p.name.equalsIgnoreCase(name)){
return p;
}
}
PlottyPlayer p = new PlottyPlayer();
p.maxPlots = -1;
p.name = name;
p.plots = new PlottyPlot[]{};
config.players = pushPlottyPlayer(config.players,p);
save();
return p;
}
public void save(){
try {
FileWriter out = new FileWriter(file);
out.write(gson.toJson(config));
out.flush();
}catch(Exception e){
Bukkit.getLogger().severe("IOException: "+e.getMessage()+" ("+e.toString()+")");
}
}
public int getLatestId(){
int greatest=-1;
for(PlottyPlayer p : config.players){
for(PlottyPlot pl : p.plots){
if(pl.id > greatest){
greatest = pl.id;
}
}
}
greatest++;
return greatest;
}
}
|
import java.util.List;
import java.util.ArrayList;
public class Carrinho {
private List<Vendavel> cart;
public Carrinho(){
cart = new ArrayList();
}
public void adicionaVendavel(Vendavel t){
cart.add(t);
}
public Double calculaTotalVenda() {
Double total = 0.0;
for(Vendavel v : cart) {
total += v.getValorVenda();
}
return total;
}
public void exibeItensCarrinho() {
for(Vendavel v : cart) {
System.out.println(v);
}
}
}
|
package com.letscrawl.test;
import java.io.UnsupportedEncodingException;
import java.util.List;
import com.letscrawl.base.bean.DocumentFile;
import com.letscrawl.base.bean.ParseResult;
import com.letscrawl.base.bean.Url;
import com.letscrawl.processor.download.downloader.impl.CommonDownloader;
import com.letscrawl.processor.parse.parser.impl.JsoupParser;
public class JsoupParserTest {
public static void main(String[] args) {
try {
CommonDownloader commonDownloader = CommonDownloader.getInstance();
DocumentFile documentFile = commonDownloader.download(new Url(
"http://os.51cto.com/art/201509/490791.htm"));
JsoupParser jsoupParser = JsoupParser.getInstance();
ParseResult parseResult = jsoupParser.parse(
new String(documentFile.getContent(),
DocumentFile.DEFAULT_CHARSET), TestData.parseRule);
List<List<ParseResult>> subParseResultListList = parseResult
.getSubParseResultListList();
for (List<ParseResult> subParseResultList : subParseResultListList) {
System.out.println("==================");
for (ParseResult subParseResult : subParseResultList) {
List<String> subContentList = subParseResult
.getContentList();
System.out.println(subParseResult.getName());
for (String subContent : subContentList) {
System.out.println(subContent);
}
}
System.out.println("==================");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
|
package EXAMS.E03.bakery.repositories.interfaces;
import EXAMS.E03.bakery.entities.bakedFoods.interfaces.BakedFood;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class FoodRepositoryImpl implements FoodRepository<BakedFood> {
private Collection<BakedFood> models;
public FoodRepositoryImpl() {
this.models = new ArrayList<>();
}
@Override
public BakedFood getByName(String name) {
return this.models.stream()
.filter(f -> f.getName().equals(name))
.findFirst()
.orElse(null);
}
@Override
public Collection<BakedFood> getAll() {
return Collections.unmodifiableCollection(this.models);
}
@Override
public void add(BakedFood bakedFood) {
this.models.add(bakedFood);
}
}
|
package com.example.mschyb.clockingapp;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ScheduleDateActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_date);
if(Config.getUserId() == 0)
{
startActivity(new Intent(getApplicationContext(), LoginScreenActivity.class));
}
else
{}
TextView dateText = (TextView) findViewById(R.id.dateText);
TextView startTimeText = (TextView) findViewById(R.id.startTimeText);
TextView endTimeText = (TextView) findViewById(R.id.endTimeText);
Button backButton = (Button) findViewById(R.id.btnScDate);
//set the onClick listener for the button
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), ViewScheduleActivity.class));
}
}
);//end backButton.setOnClickListener
Bundle extras = getIntent().getExtras();
dateText.setText(getMonthForInt(extras.getInt("scheduledMonth")-1) + " " + extras.getInt("scheduledDay") + ", " + extras.getInt("scheduledYear"));
dateText.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
if(extras!=null && extras.containsKey("startTime"))
{
String month="";
String sDate="", eDate="";
String[] times= new String[2];
Date startDateTime=new Date();
Date endDateTime=new Date();
times[0] = sDate=extras.getString("startTime");
times[1] = eDate=extras.getString("endTime");
//hard coding id until login set id is finished
// Config.setUserId(2);
// times = new Utilities().getSchedule(Config.getUserId(),sDate,eDate);//SaveSharedPreference.getUserID(getApplicationContext()), sDate,eDate);
if(times!=null) {
try {
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
SimpleDateFormat printFormat = new SimpleDateFormat("h:mm a");
// new SimpleDateFormat("hh:mm a").format(new Date("1/12/2011 16:00:00"))
startTimeText.setText("Shift Start Time: " + parseFormat.format(new Date("1/12/2011 " + times[0])));
endTimeText.setText("Shift End Time: " + parseFormat.format(new Date("1/12/2011 " + times[1])));
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
startTimeText.setText("Not Scheduled Today");
endTimeText.setText("");
}
}
else
{
startTimeText.setText("Not Scheduled Today");
// dateText.setText("No date chosen, please go back and choose date");
// startTimeText.setText("");
endTimeText.setText("");
}
}
public String getMonthForInt(int num) {
String month = "";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11 ) {
month = months[num];
}
return month;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_schedule_date, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package org.my1matrix.my1testapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.layout_main);
}
@Override
public void onStart() {
super.onStart();
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(R.string.say_hello);
}
}
|
package symapQuery;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
public class CollapsiblePanel extends JPanel {
private static final long serialVersionUID = 7114124162647988756L;
public CollapsiblePanel(String title, String description) {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBackground(Color.WHITE);
showIcon = createImageIcon("/images/plus.gif");
hideIcon = createImageIcon("/images/minus.gif");
showHideButton = new JButton(title);
showHideButton.setBorderPainted(false);
showHideButton.setFocusPainted(false);
showHideButton.setContentAreaFilled(false);
showHideButton.setMargin(new Insets(5, 0, 5, 0));
showHideButton.setAlignmentX(LEFT_ALIGNMENT);
showHideButton.addActionListener(
new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
if (!visible) expand();
else collapse();
}});
if (!description.equals("")) {
labelDescription = new JLabel(" " + description);
labelDescription.setFont(new Font(labelDescription.getFont().getName(), Font.PLAIN, labelDescription.getFont().getSize()));
labelDescription.setAlignmentX(LEFT_ALIGNMENT);
labelDescription.setBackground(Color.WHITE);
}
thePanel = new JPanel();
thePanel.setLayout(new BoxLayout(thePanel, BoxLayout.Y_AXIS));
thePanel.setBorder ( BorderFactory.createEmptyBorder(5, 20, 10, 20) );
thePanel.setAlignmentX(LEFT_ALIGNMENT);
thePanel.setBackground(Color.WHITE);
thePanel.add(new JSeparator());
super.add( showHideButton );
if (labelDescription != null) super.add( labelDescription );
super.add( thePanel );
theSizeExpanded = getPreferredSize();
collapse();
theSizeCollapsed = getPreferredSize();
setAlignmentX(LEFT_ALIGNMENT);
}
public void collapse() {
visible = false;
showHideButton.setIcon(showIcon);
showHideButton.setToolTipText("Expand");
setMaximumSize(theSizeCollapsed);
thePanel.setVisible(false);
}
public void expand() {
visible = true;
showHideButton.setIcon(hideIcon);
showHideButton.setToolTipText("Collapse");
setMaximumSize(theSizeExpanded);
thePanel.setVisible(true);
}
public Component add(Component comp) {
thePanel.add(comp);
if(!visible) {
expand();
theSizeExpanded = getPreferredSize();
collapse();
}
else {
theSizeExpanded = getPreferredSize();
expand();
}
return comp;
}
private static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = CollapsiblePanel.class.getResource(path);
if (imgURL != null)
return new ImageIcon(imgURL);
else
return null;
}
private boolean visible = false;
private ImageIcon showIcon = null, hideIcon = null;
private JButton showHideButton = null;
private JLabel labelDescription = null;
private JPanel thePanel = null;
private Dimension theSizeExpanded = null, theSizeCollapsed = null;
}
|
package com.autentia.poc.jacoco.model;
import static org.junit.Assert.*;
import org.junit.Test;
public class UserTest {
long ID = 1l;
String NAME = "TEST_NAME";
String EMAIL = "EMAIL_TEST";
@Test
public void testUser() {
User userSUT = new User(ID,NAME,EMAIL);
assertEquals(userSUT.toString(), "ID: "+this.ID+" - Username: "+this.NAME+" - Email: "+ this.EMAIL);
}
}
|
package com.sxb.controller.php;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.reflect.TypeToken;
import com.sxb.model.RespsonData;
import com.sxb.model.RespsonPHP;
import com.sxb.model.Suser;
import com.sxb.service.SuserService;
import com.sxb.util.HtmTools;
import com.sxb.util.JsonUtils;
import com.sxb.util.RegexUtil;
/**
* @description PHP1.7版本接口----用户信息服务RestController
* @author <a href="mailto:ou8zz@sina.com">OLE</a>
* @date 2016/06/14
* @version 1.0
*/
@RestController
@Scope(value="request")
public class SuserCore {
private Log log = LogFactory.getLog(SuserCore.class);
@Resource(name="suserService")
private SuserService suserService;
/**
* 注册新增用户信息 http://localhost/register.php
* @param Suser json 对象
* 请求示例:data={"userphone":"1589336622", "username":"user_001", "password":"pwe"}
* @return RespsonData 成功失败
*/
@RequestMapping(method=RequestMethod.POST, value="/register.php")
public Object register(@RequestBody(required=false) String data) {
RespsonPHP rd = new RespsonPHP();
try {
// 处理PHP格式数据,苦逼
if(RegexUtil.isEmpty(data)) {
rd.setCode(561);
rd.setData("data is null");
return rd;
}
data = HtmTools.decode(data);
data = data.split("=")[1];
Map<String, String> m = JsonUtils.fromJson(data, new TypeToken<Map<String, String>>() {}.getType());
Suser u = new Suser();
u.setUsername(m.get("username"));
u.setUserphone(m.get("userphone"));
u.setPassword(m.get("password"));
suserService.addSuser(u);
} catch (Exception e) {
rd.setCode(560);
rd.setData(e.getMessage());
log.error("add user error", e);
}
return rd;
}
/**
* 编辑用户信息 http://localhost/user_modifyfields.php
* @param Suser json 对象
* 请求示例:data={"userphone":"1589336622", "username":"user_001", "address":"address", "constell":"constell", "signature":"signature"}
* @return RespsonData 用户信息
*/
@RequestMapping(method=RequestMethod.POST, value="/user_modifyfields.php")
public Object editUser(@RequestBody(required=false) String data) {
RespsonPHP rd = new RespsonPHP();
try {
// 处理PHP格式数据,苦逼
if(RegexUtil.isEmpty(data)) {
rd.setCode(561);
rd.setData("data is null");
return rd;
}
data = HtmTools.decode(data);
data = data.split("=")[1];
Map<String, String> m = JsonUtils.fromJson(data, new TypeToken<Map<String, String>>() {}.getType());
Suser u = new Suser();
u.setUsername(m.get("username"));
u.setUserphone(m.get("userphone"));
u.setAddress(m.get("address"));
u.setConstellation(m.get("constell"));
u.setPersonal_signature(m.get("signature"));
suserService.editSuser(u);
} catch (Exception e) {
rd.setCode(560);
rd.setData(e.getMessage());
log.error("editUser error", e);
}
return rd;
}
/**
* 获取用户信息 http://localhost/user_getinfo.php
* @param Suser json 对象
* 请求示例:data={"userphone":"1589336622"}
* @return RespsonData 用户信息
*/
@RequestMapping(method=RequestMethod.POST, value="/user_getinfo.php")
public Object getUserInfo(@RequestBody(required=false) String data) {
RespsonPHP rd = new RespsonPHP();
try {
// 处理PHP格式数据,苦逼
if(RegexUtil.isEmpty(data)) {
rd.setCode(561);
rd.setData("data is null");
return rd;
}
data = HtmTools.decode(data);
data = data.split("=")[1];
Map<String, String> m = JsonUtils.fromJson(data, new TypeToken<Map<String, String>>() {}.getType());
Suser u = new Suser(m.get("userphone"));
Suser suser = suserService.getSuser(u);
if(RegexUtil.isEmpty(suser)) {
rd.setCode(561);
rd.setData("user is not existed");
return rd;
}
rd.setData(suser);
} catch (Exception e) {
rd.setCode(560);
rd.setData(e.getMessage());
log.error("getUserInfo error", e);
}
return rd;
}
/**
* 上传用户头像 http://lsxb/user/image_post.php
* @param Suser json 对象
* 请求示例:
* impage=file
* imagepostdata={"file":"文件格式内容","imagetype":1,"userphone":"13588885555"}
* 文件类型分为分别为:head_image:用户头像,cover_image:封面
* @return RespsonData data=1表示成功0失败
*/
@RequestMapping(method=RequestMethod.POST, value="/image_post.php")
public Object imagePost(@RequestParam(required=false) MultipartFile image,
@RequestParam(required=false) String imagepostdata,
HttpServletRequest request) {
RespsonPHP rd = new RespsonPHP();
try {
if(RegexUtil.isEmpty(image)) {
rd.setCode(561);
rd.setData("file is null");
return rd;
}
// 处理PHP格式数据,苦逼
if(RegexUtil.isEmpty(imagepostdata)) {
rd.setCode(561);
rd.setData("data is null");
return rd;
}
imagepostdata = HtmTools.decode(imagepostdata);
Map<String, String> m = JsonUtils.fromJson(imagepostdata, new TypeToken<Map<String, String>>() {}.getType());
String imagetype = m.get("imagetype");
String userphone = m.get("userphone");
if(RegexUtil.isEmpty(imagetype)) {
rd.setCode(561);
rd.setData("imagetype is null");
return rd;
} else if(imagetype.equals("1")) {
imagetype = "head_image";
} else if(imagetype.equals("2")) {
imagetype = "cover_image";
}
if(RegexUtil.isEmpty(userphone)) {
rd.setCode(561);
rd.setData("userphone is null");
return rd;
}
String path = request.getSession().getServletContext().getRealPath("/") + "/upload/";
String images = suserService.imagePost(image, imagetype, userphone, path);
rd.setData(images);
} catch (Exception e) {
rd.setCode(560);
rd.setData(e.getMessage());
log.error("imagePost error", e);
}
return rd;
}
/**
* 获取指定图片 http://localhost/image_get.php
* 所有本地资源文件都已经转移到七牛云平台,所有后台所有数据都从七牛云取得
* @param Suser json 对象
* 请求示例:{"imagepath":"/upload/img.jpg", "width":"300", "height":"300"}
* @return RespsonData 返回图片资源
*/
@RequestMapping(method=RequestMethod.GET, value="/image_get.php")
public Object getImage(@RequestParam(value="imagepath", required=false) String imagepath,
@RequestParam(value="width", required=false) Integer width,
@RequestParam(value="height", required=false) Integer height,
HttpServletRequest request,
HttpServletResponse response) {
ServletOutputStream out = null;
RespsonData rd = new RespsonData("");
try {
response.setContentType("image/gif");
out = response.getOutputStream();
String ac = imagepath;
if(RegexUtil.notEmpty(width) && RegexUtil.notEmpty(height)) {
ac = imagepath + "?imageView2/2/w/"+width+"/h/"+height+"/interlace/0/q/100";
}
URL url = new URL(ac);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
out.write(btImg);
out.flush();
out.close();
} catch (Exception e) {
rd.setErrorCode(560);
rd.setErrorInfo(e.getMessage());
log.error("getImage error", e);
}
if (out != null) {
try {out.close();} catch (IOException e) {}
}
return rd;
}
/**
* 从输入流中获取数据
* @param inStream 输入流
* @return
* @throws Exception
*/
private byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
|
package com.pruebatecnicaomar.PruebaTecnicaOmar.model;
import java.util.Date;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "historialLRC")
public class LRCHistorialEntity extends CoinHistorialEntity{
public LRCHistorialEntity() {
super();
};
public LRCHistorialEntity(Long id, Date fecha, CriptomonedaEntity moneda) {
super(id, fecha, moneda);
};
}
|
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.Destroyable;
import java.util.*;
/**
* 使用PULL解析器解释Project.xml
*/
public class ProjectReader implements Destroyable {
private boolean isAvaliable;
private XmlPullParserFactory xmlFactory;
private File m_file;
private FileInputStream m_stream;
private GameInfo gameInfo;
public ProjectReader(File file) {
isAvaliable = true;
m_file = file;
}
public boolean load(World.Option opt) {
try {
m_stream = new FileInputStream(m_file);
xmlFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = xmlFactory.newPullParser();
parser.setInput(m_stream, "UTF-8");
int event = parser.getEventType();
Stack<String> fatherNodes = new Stack<>();
gameInfo = new GameInfo();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
if (parser.getName().equals("Values")) {
fatherNodes.push(parser.getAttributeValue(0));
}
if(fatherNodes.isEmpty()) {
break;
}
if ("GameInfo".equals(fatherNodes.peek())) {
gameInfo.setValue(parser);
}else if ("Player".equals(fatherNodes.peek()) && "SpawnPosition".equals(parser.getAttributeValue(0))) {
String[] str = parser.getAttributeValue(2).split(",");
if (!opt.isInited) {
opt.origin = new Point(((int) Float.parseFloat(str[0])) / 16, ((int) Float.parseFloat(str[2])) / 16);
opt.origin.offset(opt.chunkCount / 2, opt.chunkCount / 2);
}
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("Values")) {
fatherNodes.pop();
}
break;
}
event = parser.next();
}
} catch (Exception e) {
isAvaliable = false;
e.printStackTrace();
}
return isAvaliable;
}
public File save() {
return m_file;
}
@Override
public void destroy() throws DestroyFailedException {
try {
m_stream.close();
isAvaliable = false;
} catch (IOException e) {
throw new DestroyFailedException(e.getMessage());
}
}
@Override
public boolean isDestroyed() {
return isAvaliable;
}
public GameInfo GameInfo() {
return gameInfo;
}
public class GameInfo {
public int WorldSeed;
public String WorldName;
public String TerrainGenerationMode;
public int TerrainLevel;
public int TerrainBlockIndex;
public int TerrainOceanBlockIndex;
public int TemperatureOffset;
public int HumidityOffset;
public int SeaLevelOffset;
public void setValue(XmlPullParser parser) {
if ("WorldSeed".equals(parser.getAttributeValue(0))) {
WorldSeed = Integer.parseInt(parser.getAttributeValue(2));
}else if ("WorldName".equals(parser.getAttributeValue(0))) {
WorldName = parser.getAttributeValue(2);
}else if ("TerrainGenerationMode".equals(parser.getAttributeValue(0))) {
TerrainGenerationMode = parser.getAttributeValue(2);
}else if ("TerrainLevel".equals(parser.getAttributeValue(0))) {
TerrainLevel = Integer.parseInt(parser.getAttributeValue(2));
}else if ("TerrainBlockIndex".equals(parser.getAttributeValue(0))) {
TerrainBlockIndex = Integer.parseInt(parser.getAttributeValue(2));
}else if ("TerrainOceanBlockIndex".equals(parser.getAttributeValue(0))) {
TerrainOceanBlockIndex = Integer.parseInt(parser.getAttributeValue(2));
}else if ("TemperatureOffset".equals(parser.getAttributeValue(0))) {
TemperatureOffset = Integer.parseInt(parser.getAttributeValue(2));
}else if ("HumidityOffset".equals(parser.getAttributeValue(0))) {
HumidityOffset = Integer.parseInt(parser.getAttributeValue(2));
}else if ("SeaLevelOffset".equals(parser.getAttributeValue(0))) {
SeaLevelOffset = Integer.parseInt(parser.getAttributeValue(2));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.