hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
8ba2565aa7090e144e246728a172ad7d1270bf14 | 2,248 | package hr.fer.zemris.java.tecaj.hw5;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
public class hexdumpShellComm implements ShellCommand {
/**
* Prints the hexadecimal output of the bytes in the file. It also
* attempts to interpret the bytes as characters and prints them to
* the right of the hex output. Bytes which cannot be converted to
* chars are printed as '.'.
*/
@Override
public ShellStatus executeCommand(BufferedReader in, BufferedWriter out,
String[] arguments) {
PrintWriter shellOutput = new PrintWriter(out);
if(arguments.length < 1) {
shellOutput.println("Usage: hexdump FILENAME");
return ShellStatus.CONTINUE;
}
Path filePath = Paths.get(arguments[0]);
try(BufferedInputStream fin = new BufferedInputStream(
new FileInputStream(filePath.toFile()))) {
byte[] bytes = new byte[16]; // there are 16 bytes displayed per output line
int lineNum = 0;
int bytesRead;
while((bytesRead = fin.read(bytes)) != -1) {
StringBuilder lineOut = new StringBuilder();
lineOut.append(String.format("%010X: ", lineNum * 16));
for(int i = 0; i < bytes.length; i++) {
if(i == 8) {
// separate after 8 bytes
lineOut.deleteCharAt(lineOut.length() - 1);
lineOut.append("|");
}
if(i > bytesRead - 1) {
// reached the end of file
bytes[i] = (byte) ' '; // for later use
lineOut.append(" ");
}
else {
lineOut.append(String.format("%02X ", bytes[i]));
}
}
lineOut.append("| ");
for(int i = 0; i < bytes.length; i++) {
int byteVal = (Byte.valueOf(bytes[i])).intValue();
if(byteVal < 32 || byteVal > 172) {
lineOut.append(".");
} else {
lineOut.append(String.format("%c", bytes[i]));
}
}
shellOutput.println(lineOut.toString());
lineNum++;
}
} catch (FileNotFoundException e) {
shellOutput.println("File not found");
} catch (IOException e) {
shellOutput.println("I/O error");
}
return ShellStatus.CONTINUE;
}
}
| 30.378378 | 79 | 0.656584 |
8cba2cc7eb9dbe28cb1614c6a5489b792ae9d1ba | 14,269 | package com.yxlg.manage.member.service.impl;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import com.yxlg.base.constant.Constants;
import com.yxlg.base.constant.Constants.DateFormatConstant;
import com.yxlg.base.dao.IBaseDAO;
import com.yxlg.base.member.entity.Member;
import com.yxlg.base.member.entity.MemberAddressInfo;
import com.yxlg.base.member.entity.MemberBankCard;
import com.yxlg.base.member.entity.MemberGrade;
import com.yxlg.base.member.entity.MemberLevelDiscountNo;
import com.yxlg.base.member.entity.MemberType;
import com.yxlg.base.memberRecommend.entity.MemberRecommend;
import com.yxlg.base.upload.util.UploadByUrl;
import com.yxlg.base.util.BusinessException;
import com.yxlg.base.util.ObtainCurrentUser;
import com.yxlg.base.util.PageBean;
import com.yxlg.base.util.Pagination;
import com.yxlg.base.util.QRCodeUtil;
import com.yxlg.manage.member.service.IManagerMemberService;
/**
*
* @author jerry.qin
* @version <br>
* <p>
* 会员查询接口的实现类
* </p>
*/
@Service
public class ManagerMemberServiceImpl implements IManagerMemberService {
private static final Logger log = LoggerFactory.getLogger(ManagerMemberServiceImpl.class);
@Override
public Pagination findMemberWithPageCriteria(PageBean pageBean,
String memberId, String memberName, String gender, String phoneNo,
String email, String registerTimeFrom, String registerTimeTo, String memberType, String birthday, String searchDesignerId,
String platform, String deviceType, String city) {
DetachedCriteria detachedCriteria = DetachedCriteria
.forClass(Member.class);
if (!StringUtils.isEmpty(memberId)) {
detachedCriteria.add(Restrictions.like("memberId", memberId,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(memberName)) {
detachedCriteria.add(Restrictions.like("memberName", memberName,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(gender)) {
detachedCriteria.add(Restrictions.eq("gender", gender));
}
if (!StringUtils.isEmpty(phoneNo)) {
detachedCriteria.add(Restrictions.like("phoneNo", phoneNo,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(email)) {
detachedCriteria.add(Restrictions.like("email", email,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(birthday)) {
detachedCriteria.add(Restrictions.like("birthday", birthday,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(platform)) {
detachedCriteria.add(Restrictions.like("platform", platform,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(deviceType)) {
detachedCriteria.add(Restrictions.like("deviceType", deviceType,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(city)) {
detachedCriteria.add(Restrictions.like("city", city,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(registerTimeFrom)) {
Date dateFrom = null;
try {
dateFrom = DateUtils.parseDate(registerTimeFrom, Constants.DateFormatConstant.DATE_FORMAT);
detachedCriteria.add(Restrictions.ge("registTime", dateFrom));
} catch (ParseException e) {
throw new BusinessException("", e);
}
}
if (!StringUtils.isEmpty(registerTimeTo)) {
Date dateTo = null;
registerTimeTo += " 23:59:59";
try {
dateTo = DateUtils.parseDate(registerTimeTo, Constants.DateFormatConstant.TIME_FORMAT);
detachedCriteria.add(Restrictions.le("registTime", dateTo));
} catch (ParseException e) {
throw new BusinessException("", e);
}
}
if (!StringUtils.isEmpty(memberType)) {
detachedCriteria.createCriteria("memberType").add(Restrictions.like("memberType", memberType,
MatchMode.ANYWHERE));
}
if (!StringUtils.isEmpty(searchDesignerId)) {
detachedCriteria.add(Restrictions.eq("memberLevelDiscountNoId", searchDesignerId));
}
detachedCriteria.addOrder(Order.desc("registTime"));
Pagination pagination = new Pagination();
Long count = baseDao.findAllCountCriteria(detachedCriteria);
List<Object> rows = baseDao.findAllWithPageCriteria(pageBean,
detachedCriteria);
pagination.setRows(rows);
pagination.setTotal(count);
return pagination;
}
@Override
public Pagination findPromoteMember(PageBean pageBean) {
// 查询出所有会员类型
DetachedCriteria detachedCriteria = DetachedCriteria
.forClass(MemberType.class);
Pagination pagination = new Pagination();
Long count = baseDao.findAllCountCriteria(detachedCriteria);
List<Object> rows = baseDao.findAllWithPageCriteria(pageBean,
detachedCriteria);
pagination.setRows(rows);
pagination.setTotal(count);
return pagination;
}
@Override
public List<MemberRecommend> findPhoneNo(String memberId) {
DetachedCriteria detachedCriteria = DetachedCriteria
.forClass(MemberRecommend.class);
DetachedCriteria memberCriteria = detachedCriteria
.createCriteria("member");
memberCriteria.add(Restrictions.eq("memberId", memberId));
List<MemberRecommend> list = baseDao
.findByDetachedCriteria(memberCriteria);
return list;
}
@Override
public List<Member> findPhoneNoAndName(String memberId) {
DetachedCriteria detachedCriteria = DetachedCriteria
.forClass(MemberRecommend.class);
DetachedCriteria memberCriteria = detachedCriteria
.createCriteria("member");
memberCriteria.add(Restrictions.eq("memberId", memberId));
List<MemberRecommend> list = baseDao
.findByDetachedCriteria(memberCriteria);
List<Member> list2 = new ArrayList<Member>();
for (int i = 0; i < list.size(); i++) {
String phoneNo = list.get(i).getPhoneNo();
list2.add(baseDao.findUniqueByProperty(Member.class, "phoneNo",
phoneNo));
}
return list2;
}
@Override
public List<MemberAddressInfo> findAddress(String memberId) {
DetachedCriteria detachedCriteria = DetachedCriteria
.forClass(MemberAddressInfo.class);
DetachedCriteria memberCriteria = detachedCriteria
.createCriteria("member");
memberCriteria.add(Restrictions.eq("memberId", memberId));
List<MemberAddressInfo> list = baseDao
.findByDetachedCriteria(memberCriteria);
return list;
}
@Override
public Pagination findMemberGrade(PageBean pageBean, String memberTypeId) {
/*
String flag = C2MConstants.MemberType.COMMON_MEMBER_NO;
if(C2MConstants.MemberType.MARKETING_MEMBER.equals(memberType)) {
flag = C2MConstants.MemberType.MARKETING_MEMBER_NO;
} else if(C2MConstants.MemberType.INSIDE_MEMBER.equals(memberType)) {
flag = C2MConstants.MemberType.INSIDE_MEMBER_NO;
}else if(C2MConstants.MemberType.INSIDE_MARKETING_MEMBER.equals(memberType)) {
flag = C2MConstants.MemberType.INSIDE_MARKETING_MEMBER_NO;
}
*/
if(StringUtils.isNotBlank(memberTypeId)){
//2017-1-11 alisa.yang 由于增加会员类型名称与级别都要修改此处!!!太麻烦!!!直接用id查询才合适
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(MemberGrade.class);
detachedCriteria.add(Restrictions.eq("memberType", memberTypeId));
Pagination pagination = new Pagination();
Long count = baseDao.findAllCountCriteria(detachedCriteria);
List<Object> rows = baseDao.findAllWithPageCriteria(pageBean,
detachedCriteria);
pagination.setRows(rows);
pagination.setTotal(count);
return pagination;
}
return null;
}
@Override
public String promoteMemberGrade(String memberId, String memberGradeId, HttpSession session) {
Serializable[] ids = memberId.split(",");
List<Serializable> list = Arrays.asList(ids);
//获取之前的会员类型
String memberGradePre = baseDao.findById(Member.class, list.get(0)).getMemberGrade().getMemberGradeName();
//获取当前登录人
ObtainCurrentUser obtainCurrentUser = new ObtainCurrentUser();
String userName = obtainCurrentUser.getOperator(session);
Map<String, Object> map = new HashMap<String, Object>();
MemberGrade memberGrade = baseDao.findById(MemberGrade.class, memberGradeId);
map.put("memberGrade", memberGrade.getMemberGradeId());
baseDao.updateBatchByPropertyName(Member.class, map, "memberId", list);
String dateString = DateFormatUtils.format(new Date(), DateFormatConstant.TIME_FORMAT);
log.info("会员【" + memberId + "】的会员级别于" + dateString + "由" + memberGradePre + "修改为" + memberGrade.getMemberGradeName() + ",修改人" + userName);
return Constants.ReturnMsg.SC_SUCCESS;
}
@Override
public int editAddedName(String memberId, String addedName){
try {
Member member = baseDao.findById(Member.class, memberId);
member.setAddedName(addedName);
baseDao.update(member);
} catch (Exception e) {
log.error("客服人员编辑用户姓名出错" + e.getMessage());
throw new BusinessException("客服人员编辑用户姓名出错,memberId:" + memberId + ",addedName:" + addedName, e);
}
return HttpStatus.OK.value();
}
@Override
public String getVouchersQrcode(String memberIds) {
memberIds = memberIds.substring(0, memberIds.length() - 1);
String[] memIds = memberIds.split(",");
DetachedCriteria criteria = DetachedCriteria.forClass(Member.class);
criteria.add(Restrictions.in("memberId", memIds));
List<Member> memList = baseDao.findByDetachedCriteria(criteria);
if (memList.size() == 0) {
return "会员数据不是最新的,请刷新重试";
}
// 生成包含用户 MemberID信息的二维码图片,上传七牛服务器,并把将返回地址保存到数据库中
String qrCodePath = "images/member/qrcode/vouchers/";
SimpleDateFormat format = new SimpleDateFormat(Constants.DateFormatConstant.TIME_FORMAT_FOR_NAME);
int random = (int) (Math.random() * 1000000);
qrCodePath = qrCodePath + format.format(new Date()) + String.valueOf(random) + ".jpg";
for (Member member : memList) {
String qrcodeSavePath = QRCodeUtil.generateQrCode(member.getMemberId(), qrCodePath);
member.setVouchersQrcode(UploadByUrl.decodeQinuPath(qrcodeSavePath));
}
baseDao.updateBatch(memList);
return "选择会员的代金券发放二维码已生成";
}
@Override
public String setMemberRebate(String memberIds, String rebate) {
Serializable[] ids = memberIds.split(",");
List<Serializable> list = Arrays.asList(ids);
Map<String, Object> map = new HashMap<String, Object>();
if(StringUtils.equals("1", rebate)){
map.put("rebate", 1);
}else{
map.put("rebate", 0);
}
baseDao.updateBatchByPropertyName(Member.class, map, "memberId", list);
return Constants.ReturnMsg.SC_SUCCESS;
}
@Override
public Pagination findLevelDiscountNo(PageBean pageBean) {
DetachedCriteria criteria = DetachedCriteria.forClass(MemberLevelDiscountNo.class);
Pagination pagination = new Pagination();
Long count = baseDao.findAllCountCriteria(criteria);
List<Object> rows = baseDao.findAllWithPageCriteria(pageBean,
criteria);
pagination.setRows(rows);
pagination.setTotal(count);
return pagination;
}
@Override
public String setLevelDiscountNo(String memberId,
String MemberLevelDiscountNoId) {
Member member = baseDao.findById(Member.class, memberId);
member.setMemberLevelDiscountNoId(MemberLevelDiscountNoId);
baseDao.update(member);
return Constants.ReturnMsg.SC_SUCCESS;
}
@Override
public Map<String, String> findLevelDiscountNo2() {
List<MemberLevelDiscountNo> memberLevelDiscountNos = baseDao.findAll(MemberLevelDiscountNo.class);
Map<String, String> map = new HashMap<String, String>();
for (MemberLevelDiscountNo discountNo : memberLevelDiscountNos) {
map.put(discountNo.getMemberLevelDiscountNoId(), discountNo.getLevelName());
}
return map;
}
@Override
public String discountNo() {
StringBuffer json = new StringBuffer("");
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(MemberLevelDiscountNo.class);
List<MemberLevelDiscountNo> discountNoList = baseDao.findByDetachedCriteria(detachedCriteria);
int totalSize = discountNoList.size();
int curentSize = 1;
json.append("[");
// 拼接json字符串
for (MemberLevelDiscountNo memberLevelDiscountNo : discountNoList) {
json.append("{\"id\":").append("\"").append(memberLevelDiscountNo.getMemberLevelDiscountNoId())
.append("\",\"text\":\"").append(memberLevelDiscountNo.getLevelName()).append("\"");
json.append("}");
if (totalSize != curentSize++) {
json.append(",");
}
}
json.append("]");
return json.toString();
}
@Override
public List<MemberBankCard> findBankCard(String memberId) {
List<MemberBankCard> list = baseDao.findListByProperty(MemberBankCard.class, "member.memberId", memberId);
return list;
}
/* (non-Javadoc)
* @see com.yxlg.manage.member.service.IManagerMemberService#sendMsg(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public String sendMsg(String memberType, String phoneNos, String projectCode, String var1, String var2, String var3, String var4) throws Exception {
if(StringUtils.isNotBlank(memberType)){
if(!"-2".equals(memberType)){
DetachedCriteria criteria = DetachedCriteria.forClass(Member.class);
if(!"-1".equals(memberType)){
criteria.createAlias("memberGrade", "mGrade").add(Restrictions.eq("mGrade.memberType", memberType));
}
criteria.setProjection(Projections.property("phoneNo"));
List<String> phoneNoList = baseDao.findByDetachedCriteria(criteria);
if(phoneNoList != null && !phoneNoList.isEmpty()){
phoneNos = StringUtils.join(phoneNoList, ",");
}else{
return "未找到发送的手机号";
}
}else if(StringUtils.isBlank(phoneNos)){
return "所选手机号不可空";
}
return null;
}
return "未选接收会员类型";
}
@Resource
private IBaseDAO baseDao;
}
| 34.973039 | 195 | 0.741047 |
f007ca461fa4c60a5fba67d1f9b7aee8bdf4aa24 | 211 | package com.nuggetsworld.novel.module.reader.entity;
public class BookMark {
public int chapter;
public String title;
public int startPos;
public int endPos;
public String desc = "";
}
| 14.066667 | 52 | 0.687204 |
86cdaec2f7828cef5f56c548ba360a4f8cc93967 | 2,628 | package com.yanp.way;
import java.util.Locale;
import android.graphics.Color;
import android.os.Environment;
/**
* @class Constantes
*
* All the constants used by the app are here.
*
* @author YPierru
*
*/
public final class Constants {
/**
* <b>{@value}</b><br />
* If true, the position is calculate with cellular data.
* If false, the app will use the phone's intern GPS.
*/
public static final boolean NETWORK_GPS=true;
/**
* <b>{@value}</b><br />
* Level of zoom when the user creates a new route.
*/
public static final int ZOOM_NEW_ROUTE=16;
/**
* <b>{@value}</b><br />
* Default level of zoom.
*/
public static final int ZOOM_GENERAL=15;
/**
* <b>{@value}</b><br />
* Level of zoom during GPS navigation
*/
public static final int ZOOM_GPS=18;
/**
* <b>{@value}</b> ms<br />
* Speed of the camera animation
*/
public static final int ZOOM_SPEED_MS=600;
/**
* <b>{@value}</b><br />
* Tilt of the camera view during GPS navigation
*/
public static final int USER_GPS_TILT=90;
/**
* <b>{@value}</b> meters<br />
* Radius of detection of user's position on a point.
* If the user is closer than this value, consider that he is on the point.
*/
public static final int RADIUS_DETECTION=18;
/**
* <b>{@value}</b> ms<br />
* Minimum time beetween 2 GPS requests.
*/
public static final int MIN_TIME_GPS_REQUEST_MS=5;
/**
* <b>{@value}</b> ms<br />
* Minimum distance beetween 2 GPS requests.
*/
public static final int MIN_DIST_GPS_REQUEST_M=0;
/**
* Path of the root of the external storage directory.
*/
public static final String PATH_FILE_ROUTES=Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
/**
* <b>{@value}</b><br />
* Size of the text in the wheel.
*/
public static final int TEXT_SIZE_WHEEL=13;
/**
* <b>{@value}</b><br />
* Width of the line draws between 2 points.
*/
public static final int WIDTH_POLYLINE=10;
/**
* Color of the line draws between 2 points.
*/
public static final int COLOR_POLYLINE=Color.argb(120, 0, 180, 0);
/**
* <b>{@value}</b><br />
* Width of the line draws during GPS navigation.
*/
public static final int WIDTH_POLYLINE_GPS=12;
/**
* Color of the line draws during GPS navigation.
*/
public static final int COLOR_POLYLINE_GPS=Color.argb(200, 0, 120, 0);
/**
* <b>{@value}</b><br />
* Earth radius.
*/
public static final double EARTH_RADIUS=3958.75;
/**
* <b>{@value}</b><br />
* The current language of the device
*/
public static final Locale CURRENT_LANGUAGE=Locale.getDefault();
}
| 21.719008 | 111 | 0.645358 |
fa3a5916bd2164e008a58aa2a1a480b7fb1b6f0a | 473 | package ai.elimu.dao;
import java.util.List;
import ai.elimu.model.admin.Application;
import ai.elimu.model.admin.ApplicationVersion;
import org.springframework.dao.DataAccessException;
public interface ApplicationVersionDao extends GenericDao<ApplicationVersion> {
ApplicationVersion read(Application application, Integer versionCode) throws DataAccessException;
List<ApplicationVersion> readAll(Application application) throws DataAccessException;
}
| 31.533333 | 101 | 0.824524 |
3d22c4a23509d0526281c584ccc7449026f98ab8 | 7,409 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.solace.samples.jcsmp;
import com.solacesystems.jcsmp.BytesXMLMessage;
import com.solacesystems.jcsmp.JCSMPException;
import com.solacesystems.jcsmp.JCSMPFactory;
import com.solacesystems.jcsmp.JCSMPProperties;
import com.solacesystems.jcsmp.JCSMPSession;
import com.solacesystems.jcsmp.JCSMPStreamingPublishCorrelatingEventHandler;
import com.solacesystems.jcsmp.JCSMPTransportException;
import com.solacesystems.jcsmp.TextMessage;
import com.solacesystems.jcsmp.XMLMessageConsumer;
import com.solacesystems.jcsmp.XMLMessageListener;
import com.solacesystems.jcsmp.XMLMessageProducer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This simple introductory sample shows an application that both publishes and subscribes.
*/
public class HelloWorld {
private static final String SAMPLE_NAME = HelloWorld.class.getSimpleName();
private static final String TOPIC_PREFIX = "solace/samples/"; // used as the topic "root"
private static final String API = "JCSMP";
private static volatile boolean isShutdown = false; // are we done yet?
/** Simple application for doing pub/sub publish-subscribe */
public static void main(String... args) throws JCSMPException, IOException {
if (args.length < 3) { // Check command line arguments
System.out.printf("Usage: %s <host:port> <message-vpn> <client-username> [password]%n", SAMPLE_NAME);
System.out.printf(" e.g. %s localhost default default%n%n", SAMPLE_NAME);
System.exit(-1);
}
// User prompt, what is your name??, to use in the topic
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String uniqueName = "";
while (uniqueName.isEmpty()) {
System.out.printf("Hello! Enter your name, or a unique word: ");
uniqueName = reader.readLine().trim().replaceAll("\\s+", "_"); // clean up whitespace
}
System.out.println(API + " " + SAMPLE_NAME + " initializing...");
// Build the properties object for initializing the JCSMP Session
final JCSMPProperties properties = new JCSMPProperties();
properties.setProperty(JCSMPProperties.HOST, args[0]); // host:port
properties.setProperty(JCSMPProperties.VPN_NAME, args[1]); // message-vpn
properties.setProperty(JCSMPProperties.USERNAME, args[2]); // client-username
if (args.length > 3) {
properties.setProperty(JCSMPProperties.PASSWORD, args[3]); // client-password
}
properties.setProperty(JCSMPProperties.REAPPLY_SUBSCRIPTIONS, true); // subscribe Direct subs after reconnect
final JCSMPSession session = JCSMPFactory.onlyInstance().createSession(properties);
session.connect(); // connect to the broker
// setup Producer callbacks config: simple anonymous inner-class for handling publishing events
final XMLMessageProducer producer;
producer = session.getMessageProducer(new JCSMPStreamingPublishCorrelatingEventHandler() {
// unused in Direct Messaging application, only for Guaranteed/Persistent publishing application
@Override public void responseReceivedEx(Object key) {
}
// can be called for ACL violations, connection loss, and Persistent NACKs
@Override
public void handleErrorEx(Object key, JCSMPException cause, long timestamp) {
System.out.printf("### Producer handleErrorEx() callback: %s%n", cause);
if (cause instanceof JCSMPTransportException) { // unrecoverable, all reconnect attempts failed
isShutdown = true;
}
}
});
// setup Consumer callbacks next: anonymous inner-class for Listener async threaded callbacks
final XMLMessageConsumer consumer = session.getMessageConsumer(new XMLMessageListener() {
@Override
public void onReceive(BytesXMLMessage message) {
// could be 4 different message types: 3 SMF ones (Text, Map, Stream) and just plain binary
System.out.printf("vvv RECEIVED A MESSAGE vvv%n%s===%n",message.dump()); // just print
}
@Override
public void onException(JCSMPException e) { // uh oh!
System.out.printf("### MessageListener's onException(): %s%n",e);
if (e instanceof JCSMPTransportException) { // unrecoverable, all reconnect attempts failed
isShutdown = true; // let's quit
}
}
});
// Ready to start the application, just add one subscription
session.addSubscription(JCSMPFactory.onlyInstance().createTopic(TOPIC_PREFIX + "*/hello/>")); // use wildcards
consumer.start(); // turn on the subs, and start receiving data
System.out.printf("%nConnected and subscribed. Ready to publish. Press [ENTER] to quit.%n");
System.out.printf(" ~ Run this sample twice splitscreen to see true publish-subscribe. ~%n%n");
TextMessage message = JCSMPFactory.onlyInstance().createMessage(TextMessage.class);
while (System.in.available() == 0 && !isShutdown) { // loop now, just use main thread
try {
Thread.sleep(5000); // take a pause
// specify a text payload
message.setText(String.format("Hello World from %s!",uniqueName));
// make a dynamic topic: solace/samples/jcsmp/hello/[uniqueName]
String topicString = TOPIC_PREFIX + API.toLowerCase() + "/hello/" + uniqueName.toLowerCase();
System.out.printf(">> Calling send() on %s%n",topicString);
producer.send(message, JCSMPFactory.onlyInstance().createTopic(topicString));
message.reset(); // reuse this message on the next loop, to avoid having to recreate it
} catch (JCSMPException e) {
System.out.printf("### Exception caught during producer.send(): %s%n",e);
if (e instanceof JCSMPTransportException) { // unrecoverable
isShutdown = true;
}
} catch (InterruptedException e) {
// Thread.sleep() interrupted... probably getting shut down
}
}
isShutdown = true;
session.closeSession(); // will also close producer and consumer objects
System.out.println("Main thread quitting.");
}
}
| 52.546099 | 121 | 0.662573 |
246fef92e3ef07f716e5e1bccfaf004da9cfb40e | 1,302 | package de.garbereder;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class TestAutomationTestGetterAndSetter extends TestCase {
@Rule
public ExpectedException thrown = ExpectedException.none();
protected TestAutomation testAutomation = new TestAutomation();
private class DummyClass {
protected int myInt;
public int getMyInt() {
return myInt;
}
public void setMyInt(int myInt) {
this.myInt = myInt;
}
}
private class WrongGetter extends DummyClass {
@Override
public int getMyInt() {
return 0;
}
}
@Test
public void testTestHashCodeAutomated() throws Exception {
DummyClass o = new DummyClass();
testAutomation.testGetterAndSetterAutomated(o);
}
@Test
public void testTestHashCodeAutomatedFails() throws Exception {
WrongGetter o = new WrongGetter();
try {
testAutomation.testGetterAndSetterAutomated(o);
} catch (Error e) {
return;
}
fail("testGetterAndSetterAutomated should have thrown an error");
}
} | 23.672727 | 73 | 0.652074 |
f1addf90b51854d5b492ecb3813392ed7530975e | 704 | package com.common.api.vo;
import java.io.Serializable;
public class CacheData implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4167770912646605408L;
private String key;
private String value;
private String md5;
private String time;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
| 13.283019 | 68 | 0.678977 |
dff60b8a8210a3d9c12b5c823564054da90fd445 | 155 | package se.lnu.siq.s4rdm3x.dmodel.classes.CPPCompatibility.simple;
public class Fuu {
public int getMagicNumber() {
return 17;
}
}
| 19.375 | 67 | 0.658065 |
bcd2dc4bc51522c03558b2af0af4a1c89248dbfa | 3,020 | /*
MIT License
Copyright (c) 2019 Emmanouil Sarris
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Binary to String: Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print
* the binary representation. If the number cannot be represented accurately in binary with at most 32
* characters, print "ERROR:'
* Hints: #143, #167, #173, #269, #297
* - To wrap your head around the problem, try thinking about how you'd do it for integers
* - In a number like. 893 (in base 10), what does each digit signify? What then does each
* digit in .10010 signify in base 2?
* - A number such as .893 (in base 10) indicates 8 * 10-1 + 9 * 10-2 + 3 * 10-3•
* Translate this system into base 2.
* - How would you get the first digit in . 893? If you multiplied by 10, you'd shift the values
* over to get 8.93.What happens if you multiply by 2?
* - Think about what happens for values that can't be represented accurately in binary
*/
package chapter._05five;
public class IntQuest2 {
/**
* This method transforms the given number (<1) into a binary floating point.
* @param number = the number to be converted
* @return
*/
public static String realToString(double number) {
StringBuilder myStr = new StringBuilder();
for (int i = 0; i < 32; i++) {
number *= 2;
if (number >= 1) {
myStr.append(1);
number -= 1;
} else {
myStr.append(0);
}
if (number == 0.0) {
return "0." + myStr.toString();
}
}
return "ERROR";
}
public static void main(String[] args) {
System.out.println(realToString(0.5));
System.out.println(realToString(0.125));
System.out.println(realToString(0.525));
System.out.println(realToString(0.987));
System.out.println(realToString(0.333));
System.out.println(realToString(0.25));
System.out.println(realToString(0.1));
}
}
| 40.266667 | 106 | 0.675166 |
6c82cf7711e2051bde32ff6e873c190e3df1a46a | 510 | package com.example.dahai.photopicklib.photoview;
/**
* Interface definition for a callback to be invoked when the photo is experiencing a drag event
*/
public interface OnViewDragListener {
/**
* Callback for when the photo is experiencing a drag event. This cannot be invoked when the
* user is scaling.
*
* @param dx The change of the coordinates in the x-direction
* @param dy The change of the coordinates in the y-direction
*/
void onDrag(float dx, float dy);
}
| 30 | 96 | 0.701961 |
27276217f4f5c8d83f88c204c627c9ecc3ac786c | 3,469 | /*
Copyright (C) 2009 Ueli Hofstetter
This source code is release under the BSD License.
This file is part of JQuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://jquantlib.org/
JQuantLib is free software: you can redistribute it and/or modify it
under the terms of the JQuantLib license. You should have received a
copy of the license along with this program; if not, please email
<[email protected]>. The license is also available online at
<http://www.jquantlib.org/index.php/LICENSE.TXT>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
JQuantLib is based on QuantLib. http://quantlib.org/
When applicable, the original copyright notice follows this notice.
*/
package org.jquantlib.math.optimization;
import org.jquantlib.math.matrixutilities.Array;
public class LineSearch {
private final static String CANNOT_UPDATE_LINESEARCH = "cannot update linesearch";
// current values of the search direction
protected Array searchDirection_;
// new x and its gradient
protected Array xtd_, gradient_;
// cost function value and gradient norm corresponding to xtd_
protected double qt_, qpt_;
// flag to know if linesearch succed
protected boolean succeed_;
// Default constructor - there are no default param values in java :-(
public LineSearch(){
this(0.0);
}
// Default constructor
public LineSearch(final double init){
qt_ = init;
qpt_= init;
succeed_ = true;
if (System.getProperty("EXPERIMENTAL") == null)
throw new UnsupportedOperationException("Work in progress");
}
// return last x value
public Array lastX(){
return xtd_;
}
// return last cost function value
public double lastFunctionValue(){
return qt_;
}
// return last gradient
public Array lastGradient(){
return gradient_;
}
// return square norm of last gradient
public double lastGradientNormNorm2(){
return qpt_;
}
// current value of the search direction
public Array searchDirection(){
return searchDirection_;
}
//FIXME: to be reviewed.
// Perform line search
public double evaluate(final Problem P, final EndCriteria.Type ecType, final EndCriteria endCriteria, final double t_ini){
throw new UnsupportedOperationException("Work in progress");
}
public double update(final Array params, final Array direction, final double beta, final Constraint constraint){
double diff = beta;
//TODO: check whether we implemented overloaded c++ operators correctly
Array newParams = params.add(direction.mul(diff));
boolean valid = constraint.test(newParams);
int icount = 0;
while(!valid){
if(icount > 200)
throw new ArithmeticException("can't update lineSearch");
diff *= 0.5;
icount++;
newParams = params.add(direction.mul(diff));
valid = constraint.test(newParams);
}
params.add(direction.mul(diff));
return diff;
}
public void setSearchDirection(final Array searchDirection){
this.searchDirection_ = searchDirection;
}
}
| 31.252252 | 126 | 0.684924 |
8d509593274e0737d1be7da0eb20eada8447005f | 538 | package aquality.appium.mobile.elements;
import aquality.appium.mobile.elements.interfaces.ILabel;
import aquality.selenium.core.elements.ElementState;
import org.openqa.selenium.By;
/**
* The class that describes the label
*/
public class Label extends Element implements ILabel {
protected Label(final By locator, final String name, final ElementState state) {
super(locator, name, state);
}
protected String getElementType() {
return getLocalizationManager().getLocalizedMessage("loc.label");
}
}
| 26.9 | 84 | 0.745353 |
1e38273c173a3a51d6fc14403763bc24ccb38f70 | 66,749 | /**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.client.gadget.renderer;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.AUTHOR_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.ID_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.IFRAME_URL_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.LAST_KNOWN_HEIGHT_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.LAST_KNOWN_WIDTH_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.PREFS_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.SNIPPET_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.STATE_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.TITLE_ATTRIBUTE;
import static org.waveprotocol.wave.model.gadget.GadgetConstants.URL_ATTRIBUTE;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.ScriptElement;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Window.Location;
import org.waveprotocol.wave.client.account.ProfileManager;
import org.waveprotocol.wave.client.common.util.UserAgent;
import org.waveprotocol.wave.client.editor.content.AnnotationPainter;
import org.waveprotocol.wave.client.editor.content.CMutableDocument;
import org.waveprotocol.wave.client.editor.content.ContentElement;
import org.waveprotocol.wave.client.editor.content.ContentNode;
import org.waveprotocol.wave.client.gadget.GadgetLog;
import org.waveprotocol.wave.client.gadget.StateMap;
import org.waveprotocol.wave.client.gadget.StateMap.Each;
import org.waveprotocol.wave.client.scheduler.ScheduleCommand;
import org.waveprotocol.wave.client.scheduler.ScheduleTimer;
import org.waveprotocol.wave.client.scheduler.Scheduler;
import org.waveprotocol.wave.client.scheduler.Scheduler.Task;
import org.waveprotocol.wave.model.conversation.ConversationBlip;
import org.waveprotocol.wave.model.conversation.ObservableConversation;
import org.waveprotocol.wave.model.document.util.Point;
import org.waveprotocol.wave.model.document.util.XmlStringBuilder;
import org.waveprotocol.wave.model.gadget.GadgetXmlUtil;
import org.waveprotocol.wave.model.id.ModernIdSerialiser;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.supplement.ObservableSupplementedWave;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV;
import org.waveprotocol.wave.model.util.ReadableStringSet;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* Class to implement gadget widgets rendered in the client.
*
*
* TODO(user): Modularize the gadget APIs (base, Podium, Wave, etc).
*
* TODO(user): Refactor the common RPC call code.
*/
public class GadgetWidget extends ObservableSupplementedWave.ListenerImpl
implements GadgetRpcListener, GadgetWaveletListener, GadgetUiListener {
private static final String GADGET_RELAY_PATH = "gadgets/files/container/rpc_relay.html";
private static final int DEFAULT_HEIGHT_PX = 100;
private static final int DEFAULT_WIDTH_PX = 600;
/**
* Helper class to analyze element changes in the gadget state and prefs.
*/
private abstract class ElementChangeTask {
/**
* Runs processChange() wrapped in code that detects and submits changes in
* the gadget state and prefs.
*
* @param node The node being processed or null if not defined.
*/
void run(ContentNode node) {
if (!isActive()) {
log("Element change event in removed node: ignoring.");
return;
}
StateMap oldState = StateMap.create();
oldState.copyFrom(state);
final StateMap oldPrefs = StateMap.create();
oldPrefs.copyFrom(userPrefs);
processChange(node);
if (!state.compare(oldState)) {
gadgetStateSubmitter.submit();
}
// TODO(user): Optimize prefs updates.
if (!userPrefs.compare(oldPrefs)) {
userPrefs.each(new StateMap.Each() {
@Override
public void apply(String key, String value) {
if (!oldPrefs.has(key) || !value.equals(oldPrefs.get(key))) {
setGadgetPref(key, value);
}
}
});
}
}
/**
* Processes the changes in the elements.
*
* @param node The node being processed or null if not defined.
*/
abstract void processChange(ContentNode node);
}
/**
* Podium state is stored as a part of the wave gadget state and can be
* visible to the Gadget via both Wave and Podium RPC interfaces.
*/
private static final String PODIUM_STATE_NAME = "podiumState";
/**
* Gadget RPC path: location of the RPC JavaScript code to be loaded into the
* client code. This is the standard Gadget library to support RPCs.
*/
static final String GADGET_RPC_PATH = "/gadgets/js/core:rpc.js";
/**
* Gadget name prefix: the common part of the gadget IFrame ID and name. The
* numeric gadget ID is appended to this prefix.
*/
static final String GADGET_NAME_PREFIX = "wgadget_iframe_";
/** Primary view for gadgets. */
static final String GADGET_PRIMARY_VIEW = "canvas";
/** Default view for gadgets. */
static final String GADGET_DEFAULT_VIEW = "default";
/**
* Time in milliseconds to wait for the RPC script to load before logging a
* warning.
*/
private static final int GADGET_RPC_LOAD_WARNING_TIMEOUT_MS = 30000;
/** Time granularity to check for the Gadget RPC library load state. */
private static final int GADGET_RPC_LOAD_TIMER_MS = 250;
/** Editing mode polling timer. */
private static final int EDITING_POLLING_TIMER_MS = 200;
/** Blip submit delay in milliseconds. */
private static final int BLIP_SUBMIT_TIMEOUT_MS = 30;
/** Gadget state send delay in milliseconds. */
private static final int STATE_SEND_TIMEOUT_MS = 30;
/** The Wave API version supported by the gadget container. */
private static final String WAVE_API_VERSION = "1";
/** The key for the playback state in the wave gadget state map. */
private static final String PLAYBACK_MODE_KEY = "${playback}";
/** The key for the edit state in the wave gadget state map. */
private static final String EDIT_MODE_KEY = "${edit}";
/** Gadget-loading frame border removal delay in ms. */
private static final int FRAME_BORDER_REMOVE_DELAY_MS = 3000;
/** Delay before sending one more participant information update in ms. */
private static final int REPEAT_PARTICIPANT_INFORMATION_SEND_DELAY_MS = 5000;
/** Object that manages Gadget UI HTML elements. */
private GadgetWidgetUi ui;
/** Gadget title element. */
private GadgetElementChild titleElement;
/** The gadget spec URL. */
private String source;
/** Gadget instance ID counter (local for each client). */
private static int nextClientInstanceId = 0;
/** Gadget instance ID. Non-final for testing. */
private int clientInstanceId;
/** Gadget iframe URL. */
private String iframeUrl;
/** Gadget RPC token.*/
private final String rpcToken;
/** Gadget security token. */
private String securityToken;
/** Gadget user preferences. */
private GadgetUserPrefs userPrefs;
/**
* Gadget state element map. Maps state keys to the corresponding elements.
*/
private final StringMap<GadgetElementChild> prefElements;
/**
* Widget active flag: true after the widget is created, false after it is
* destroyed.
*/
private boolean active = false;
/** ID of the gadget's wave/let. */
private WaveletName waveletName;
/** Host blip of this gadget. */
private ConversationBlip blip;
/** Blip submitter. */
private Submitter blipSubmitter;
/** Gadget state submitter. */
private Submitter gadgetStateSubmitter;
/** Private gadget state submitter. */
private Submitter privateGadgetStateSubmitter;
/** ContentElement in the wave that corresponds to this gadget. */
private ContentElement element;
/** Indicator for gadget's blip editing state. */
private EditingIndicator editingIndicator;
/** Participant information. */
private ParticipantInformation participants;
/** Gadget state. */
private StateMap state;
/** User id of the current logged in user. */
private String loginName;
/**
* Gadget state element map. Maps state keys to the corresponding elements.
*/
private final StringMap<GadgetElementChild> stateElements;
/** Indicates whether the gadget is known to support the Wave API. */
private boolean waveEnabled = false;
/** Version of Wave API that is used by the gadget-side code. */
private String waveApiVersion = "";
/** Per-user wavelet to store private gadget data. */
private ObservableSupplementedWave supplement;
/** Provides profile information. */
private ProfileManager profileManager;
/** Wave client locale. */
private Locale locale;
/** Gadget library initialization flag. */
private static boolean initialized = false;
/**
* Gadget element child that defines what nodes to check for redundancy in the
* removeRedundantNodeTask. Only a single task can be scheduled at a time.
*/
private GadgetElementChild redundantNodeCheckChild = null;
/**
* Indicates whether the gadget has performed a document mutation on behalf of
* the user. This flag is checked when the gadget tries to perform
* non-essential modifications of the document such as duplicate node cleanup
* or height attribute update. Performing such operations may generate
* unnecessary playback frames and attribute modifications to a user who did
* not use the gadget. The flag is set when the gadget modifies state, prefs,
* title, or any other elements that normally are linked to user actions in
* the gadget.
*/
private boolean documentModified = false;
/**
* Indicates that the iframe URL attribute should be updated when the gadget
* modifies the document in response to a user action.
*/
private boolean toUpdateIframeUrl = false;
private final String clientInstanceLogLabel;
// Note that the following regex expressions are strings rather than compiled patterns because GWT
// does not (yet) support those. Consider using the new GWT RegExp class in the future.
/**
* Pattern to match rpc token, security token, and user preference parameters
* in a URL fragment. Used to remove all these parameters.
*/
private final static String FRAGMENT_CLEANING_PATTERN = "(^|&)(rpctoken=|st=|up_)[^&]*";
/**
* Pattern to match module ID and security token parameters a URL. Used to
* remove all these parameters.
*/
private final static String URL_CLEANING_PATTERN = "&(mid=|st=|lang=|country=|debug=)[^&]*";
/**
* Pattern to match and remove URL fragment including the #.
*/
private final static String FRAGMENT_PATTERN = "#.*";
/**
* Pattern to match and remove URL part before fragment including the #.
*/
private final static String BEFORE_FRAGMENT_PATTERN = "[^#]*#";
/**
* Pattern to validate URL fragment.
*/
private final static String FRAGMENT_VALIDATION_PATTERN =
"([\\w~!&@\\$\\-\\.\\'\\(\\)\\*\\+\\,\\;\\=\\?\\:]|%[0-9a-fA-F]{2})+";
/**
* Pattern to match iframe host in the beginning of a URL. This is not a
* validation check. The user can choose their own host. This simply serves
* to extract the iframe segment of the URL
*/
private final static String IFRAME_HOST_PATTERN =
"^\\/\\/(https?:\\/\\/)?[^\\/]+\\/";
/**
* Pattern to remove XML-unsafe characters. Snippeting fails on some of those
* symbol combinations due to a potential bug in XML attribute processing.
* Theoretically all those symbols should be tolerated and displayed in
* snippets without any special processing in this class.
*
* TODO(user): Investigate/test this later to remove sanitization.
*/
private final static String SNIPPET_SANITIZER_PATTERN = "[<>\\\"\\'\\&]";
/**
* Constructs GadgetWidget for testing.
*/
private GadgetWidget() {
clientInstanceId = nextClientInstanceId++;
clientInstanceLogLabel = "[" + clientInstanceId + "]";
prefElements = CollectionUtils.createStringMap();
stateElements = CollectionUtils.createStringMap();
rpcToken = "" +
((Long.valueOf(Random.nextInt()) << 32) | (Long.valueOf(Random.nextInt()) & 0xFFFFFFFFL));
}
private static native boolean gadgetLibraryLoaded() /*-{
return ($wnd.gadgets && $wnd.gadgets.rpc) ? true : false;
}-*/;
/**
* Preloads the libraries and initializes them on the first use.
*/
private static void initializeGadgets() {
if (!initialized && !gadgetLibraryLoaded()) {
GadgetLog.log("Initializing Gadget RPC script tag.");
loadGadgetRpcScript();
initialized = true;
GadgetLog.log("Gadgets RPC script tag initialized.");
}
// TODO(user): Remove the css hacks once CAJA is fixed.
if (!initialized && !gadgetLibraryLoaded()) {
// HACK(user): NOT reachable, but GWT thinks it is.
excludeCssName();
}
}
/**
* Utility function to convert a Gadget StateMap to a string to be stored as
* an attribute value.
*
* @param state JSON object to be converted to string.
* @return string to be saved as an attribute value.
*/
private static String stateToAttribute(StateMap state) {
if (state == null) {
return URL.encodeComponent("{}");
}
return URL.encodeComponent(state.toJson());
}
/**
* Utility function to convert an attribute string to a Gadget StateMap.
*
* @param attribute attribute value string.
* @return StateMap constructed from the attribute value.
*/
private StateMap attributeToState(String attribute) {
StateMap result = StateMap.create();
if ((attribute != null) && !attribute.equals("")) {
log("Unescaped attribute: ", URL.decodeComponent(attribute));
result.fromJson(URL.decodeComponent(attribute));
log("State map: ", result.toJson());
}
return result;
}
/**
* Returns the gadget name that identifies the gadget and its frame.
*
* @return gadget name.
*/
private String getGadgetName() {
return GADGET_NAME_PREFIX + clientInstanceId;
}
private void updatePrefsFromAttribute(String prefAttribute) {
if (!stateToAttribute(userPrefs).equals(prefAttribute)) {
StateMap prefState = attributeToState(prefAttribute);
userPrefs.parse(prefState, true);
log("Updating user prefs: ", userPrefs.toJson());
prefState.each(new StateMap.Each() {
@Override
public void apply(String key, String value) {
setGadgetPref(key, value);
}
});
}
}
/**
* Processes changes in the gadget element attributes.
* TODO(user): move some of this code to the handler.
*
* @param name attribute name.
* @param value new attribute value.
*/
public void onAttributeModified(String name, String value) {
log("Attribute '", name, "' changed to '", value, "'");
if (userPrefs == null) {
log("Attribute changed before the gadget is initialized.");
return;
}
if (name.equals(URL_ATTRIBUTE)) {
source = (value == null) ? "" : value;
} else if (name.equals(TITLE_ATTRIBUTE)) {
String title = (value == null) ? "" : URL.decodeComponent(value);
if (!title.equals(ui.getTitleLabelText())) {
log("Updating title: ", title);
ui.setTitleLabelText(title);
}
} else if (name.equals(PREFS_ATTRIBUTE)) {
updatePrefsFromAttribute(value);
} else if (name.equals(STATE_ATTRIBUTE)) {
StateMap newState = attributeToState(value);
if (!state.compare(newState)) {
String podiumState = newState.get(PODIUM_STATE_NAME);
if ((podiumState != null) && (!podiumState.equals(state.get(PODIUM_STATE_NAME)))) {
sendPodiumOnStateChangedRpc(getGadgetName(), podiumState);
}
state.clear();
state.copyFrom(newState);
log("Updating gadget state: ", state.toJson());
gadgetStateSubmitter.submit();
}
}
}
/**
* Loads Gadget RPC library script.
*/
private static void loadGadgetRpcScript() {
ScriptElement script = Document.get().createScriptElement();
script.setType("text/javascript");
script.setSrc(GADGET_RPC_PATH);
Document.get().getBody().appendChild(script);
}
/**
* Appends tokens to the iframe URI fragment.
*
* @param fragment Original parameter fragment of the gadget URI.
* @return Updated parameter fragment with new RPC and security tokens.
*/
private String updateGadgetUriFragment(String fragment) {
fragment = "rpctoken=" + rpcToken +
(fragment.isEmpty() || (fragment.charAt(0) == '&') ? "" : "&") + fragment;
if ((securityToken != null) && !securityToken.isEmpty()) {
fragment += "&st=" + URL.encodeComponent(securityToken);
}
return fragment;
}
@VisibleForTesting
static String cleanUrl(String url) {
String baseUrl = url;
String fragment = "";
int fragmentIndex = url.indexOf("#");
if (fragmentIndex >= 0) {
fragment = (url.substring(fragmentIndex + 1)).replaceAll(FRAGMENT_CLEANING_PATTERN, "");
if (fragment.startsWith("&")) {
fragment = fragment.substring(1);
}
baseUrl = url.substring(0, fragmentIndex);
}
baseUrl = baseUrl.replaceAll(URL_CLEANING_PATTERN, "");
return baseUrl + (fragment.isEmpty() ? "" : "#" + fragment);
}
/**
* Constructs IFrame URI of this gadget.
*
* @param instanceId instance to encode in the URI.
* @param url URL template.
* @return IFrame URI of this gadget.
*/
String buildIframeUrl(int instanceId, String url) {
final StringBuilder builder = new StringBuilder();
String fragment = "";
int fragmentIndex = url.indexOf("#");
if (fragmentIndex >= 0) {
fragment = url.substring(fragmentIndex + 1);
url = url.substring(0, fragmentIndex);
}
builder.append(url);
boolean enableGadgetCache = false;
builder.append("&nocache=" + (enableGadgetCache ? "0" : "1"));
builder.append("&mid=" + instanceId);
builder.append("&lang=" + locale.getLanguage());
builder.append("&country=" + locale.getCountry());
String href = getUrlPrefix();
// TODO(user): Parent is normally the last non-hash parameter. It is moved
// as a temp fix for kitchensinky. Move it back when the kitchensinky is
// working wihout this workaround.
builder.append("&parent=" + URL.encode(href));
builder.append("&wave=" + WAVE_API_VERSION);
builder.append("&waveId=" + URL.encodeQueryString(
ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletName.waveId)));
fragment = updateGadgetUriFragment(fragment);
if (!fragment.isEmpty()) {
builder.append("#" + fragment);
log("Appended fragment: ", fragment);
}
if (userPrefs != null) {
userPrefs.each(new StateMap.Each() {
@Override
public void apply(String key, String value) {
if (value != null) {
builder.append("&up_");
builder.append(URL.encodeQueryString(key));
builder.append('=');
builder.append(URL.encodeQueryString(value));
}
}
});
}
return builder.toString();
}
/**
* Verifies that the gadget has non-empty attribute.
*
* @param name attribute name.
* @return true if non-empty height attribute exists, flase otherwise.
*/
private boolean hasAttribute(String name) {
if (element.hasAttribute(name)) {
String value = element.getAttribute(name);
if (!"".equals(value)) {
return true;
}
}
return false;
}
/**
* Updates the gadget attribute in a deferred command if the panel is
* editable.
*
* @param attributeName attribute name.
* @param value new attribute value.
*/
private void scheduleGadgetAttributeUpdate(final String attributeName, final String value) {
ScheduleCommand.addCommand(new Scheduler.Task() {
@Override
public void execute() {
if (canModifyDocument() && documentModified) {
String oldValue = element.getAttribute(attributeName);
if (!value.equals(oldValue)) {
element.getMutableDoc().setElementAttribute(element, attributeName, value);
}
}
}
});
}
/**
* Updates gadget IFrame attributes.
*
* @param url URL template for the iframe.
* @param width preferred width of the iframe.
* @param height preferred height of the iframe.
*/
private void updateGadgetIframe(String url, long width, long height) {
if (!isActive()) {
return;
}
iframeUrl = url;
if (hasAttribute(LAST_KNOWN_WIDTH_ATTRIBUTE)) {
setSavedIframeWidth();
} else if (width != 0) {
ui.setIframeWidth(width + "px");
ui.makeInline();
scheduleGadgetAttributeUpdate(LAST_KNOWN_WIDTH_ATTRIBUTE, Long.toString(width));
}
if (!hasAttribute(LAST_KNOWN_HEIGHT_ATTRIBUTE) && (height != 0)) {
ui.setIframeHeight(height);
scheduleGadgetAttributeUpdate(LAST_KNOWN_HEIGHT_ATTRIBUTE, Long.toString(height));
}
String ifr = buildIframeUrl(getInstanceId(), url);
log("ifr: ", ifr);
ui.setIframeSource(ifr);
}
private int parseSizeString(String heightString) throws NumberFormatException {
if (heightString.endsWith("px")) {
return Integer.parseInt(heightString.substring(0, heightString.length() - 2));
} else {
return Integer.parseInt(heightString);
}
}
/**
* Updates gadget iframe height if the gadget has the height attribute.
*/
private void setSavedIframeHeight() {
if (hasAttribute(LAST_KNOWN_HEIGHT_ATTRIBUTE)) {
String savedHeight = element.getAttribute(LAST_KNOWN_HEIGHT_ATTRIBUTE);
try {
int height = parseSizeString(savedHeight);
ui.setIframeHeight(height);
} catch (NumberFormatException e) {
log("Invalid saved height attribute (ignored): ", savedHeight);
}
}
}
/**
* Updates gadget iframe height if the gadget has the height attribute.
*/
private void setSavedIframeWidth() {
if (hasAttribute(LAST_KNOWN_WIDTH_ATTRIBUTE)) {
String savedWidth = element.getAttribute(LAST_KNOWN_WIDTH_ATTRIBUTE);
try {
int width = parseSizeString(savedWidth);
ui.setIframeWidth(width + "px");
ui.makeInline();
} catch (NumberFormatException e) {
log("Invalid saved width attribute (ignored): ", savedWidth);
}
}
}
/**
* Creates a display widget for the gadget.
*
* @param element ContentElement from the wave.
* @param blip gadget blip.
* @return display widget for the gadget.
*/
public static GadgetWidget createGadgetWidget(ContentElement element, WaveletName waveletName,
ConversationBlip blip, ObservableSupplementedWave supplement,
ProfileManager profileManager, Locale locale, String loginName) {
final GadgetWidget widget = GWT.create(GadgetWidget.class);
widget.element = element;
widget.editingIndicator =
new BlipEditingIndicator(element.getRenderedContentView().getDocumentElement());
widget.ui = new GadgetWidgetUi(widget.getGadgetName(), widget.editingIndicator);
widget.state = StateMap.create();
initializeGadgets();
widget.blip = blip;
widget.initializeGadgetContainer();
widget.ui.setGadgetUiListener(widget);
widget.waveletName = waveletName;
widget.supplement = supplement;
widget.profileManager = profileManager;
widget.locale = locale;
widget.loginName = loginName;
supplement.addListener(widget);
return widget;
}
/**
* @return the actual GWT widget
*/
public GadgetWidgetUi getWidget() {
return ui;
}
@Override
public void setTitle(String title) {
if (!isActive()) {
return;
}
final String newTitle = (title == null) ? "" : title;
log("Set title '", XmlStringBuilder.createText(newTitle), "'");
if (titleElement == null) {
onModifyingDocument();
GadgetElementChild.create(element.getMutableDoc().insertXml(
Point.end((ContentNode) element), GadgetXmlUtil.constructTitleXml(newTitle)));
blipSubmitter.submit();
} else {
if (!title.equals(titleElement.getValue())) {
onModifyingDocument();
titleElement.setValue(newTitle);
blipSubmitter.submit();
}
}
}
@Override
public void logMessage(String message) {
GadgetLog.developerLog(message);
}
private String sanitizeSnippet(String snippet) {
return snippet.replaceAll(SNIPPET_SANITIZER_PATTERN, " ");
}
@Override
public void setSnippet(String snippet) {
if (!canModifyDocument()) {
return;
}
String safeSnippet = sanitizeSnippet(snippet);
log("Snippet changed: " + safeSnippet);
scheduleGadgetAttributeUpdate(SNIPPET_ATTRIBUTE, safeSnippet);
}
/**
* Gets the attribute value from the mutable document associated with the
* gadget.
*
* @param attributeName name of the attribute
* @return attribute value or empty string if attribute is missing
*/
private String getAttribute(String attributeName) {
return element.hasAttribute(attributeName) ? element.getAttribute(attributeName) : "";
}
@VisibleForTesting
static String getIframeHost(String url) {
// Ideally this should be done with regex matcher which is not supported in GWT.
String iframeHostMatcher = url.replaceFirst(IFRAME_HOST_PATTERN, "");
if (iframeHostMatcher.length() != url.length()) {
return url.substring(0, url.length() - iframeHostMatcher.length());
} else {
return "";
}
}
/**
* Controller registration task.
*
* @param url URL template of the gadget iframe.
* @param width preferred iframe width.
* @param height preferred iframe height.
*/
private void controllerRegistration(String url, long width, long height) {
Controller controller = Controller.getInstance();
String iframeHost = getIframeHost(url);
String relayUrl = iframeHost + GADGET_RELAY_PATH;
controller.setRelayUrl(getGadgetName(), relayUrl);
controller.registerGadgetListener(getGadgetName(), GadgetWidget.this);
controller.setRpcToken(getGadgetName(), rpcToken);
updateGadgetIframe(url, width, height);
removeFrameBorder();
delayedPodiumInitialization();
log("Gadget ", getGadgetName(), " is registered, relayUrl=", relayUrl,
", RPC token=", rpcToken);
}
private void registerWithController(String url, long width, long height) {
if (gadgetLibraryLoaded()) {
controllerRegistration(url, width, height);
} else {
scheduleControllerRegistration(url, width, height);
}
}
/**
* Registers the Gadget object as RPC event listener with the Gadget RPC
* Controller after waiting for the Gadget RPC library to load.
*/
private void scheduleControllerRegistration(
final String url, final long width, final long height) {
new ScheduleTimer() {
private double loadWarningTime =
Duration.currentTimeMillis() + GADGET_RPC_LOAD_WARNING_TIMEOUT_MS;
@Override
public void run() {
if (!isActive()) {
cancel();
log("Not active.");
return;
} else if (gadgetLibraryLoaded()) {
cancel();
controllerRegistration(url, width, height);
} else {
if (Duration.currentTimeMillis() > loadWarningTime) {
log("Gadget RPC script failed to load on time.");
loadWarningTime += GADGET_RPC_LOAD_WARNING_TIMEOUT_MS;
}
}
}
}.scheduleRepeating(GADGET_RPC_LOAD_TIMER_MS);
}
private void initializeGadgetContainer() {
userPrefs = GadgetUserPrefs.create();
blipSubmitter = new Submitter(BLIP_SUBMIT_TIMEOUT_MS, new Submitter.SubmitTask() {
@Override public void doSubmit() {
// TODO: send a playback frame signal.
log("Blip submitted.");
}
});
gadgetStateSubmitter = new Submitter(STATE_SEND_TIMEOUT_MS, new Submitter.SubmitTask() {
@Override public void doSubmit() {
sendGadgetState();
log("Gadget state sent.");
}
});
privateGadgetStateSubmitter = new Submitter(STATE_SEND_TIMEOUT_MS, new Submitter.SubmitTask() {
@Override public void doSubmit() {
sendPrivateGadgetState();
log("Private gadget state sent.");
}
});
}
private void initializePodium() {
if (!isActive()) {
// If the widget does not exist, exit.
return;
}
for (ParticipantId participant : blip.getConversation().getParticipantIds()) {
String myId = participants.getMyId();
if ((myId != null) && !participant.getAddress().equals(myId)) {
String opponentId = participant.getAddress();
try {
sendPodiumOnInitializedRpc(getGadgetName(), myId, opponentId);
log("Sent Podium initialization: " + myId + " " + opponentId);
String podiumState = state.get(PODIUM_STATE_NAME);
if (podiumState != null) {
sendPodiumOnStateChangedRpc(getGadgetName(), podiumState);
log("Sent Podium state update.");
}
} catch (Exception e) {
// This is a catch to avoid sending RPCs to deleted gadgets.
log("Podium initialization failure");
}
return;
}
}
log("Podium is not initialized: less than two participants.");
}
private void delayedPodiumInitialization() {
// TODO(user): This is a hack to delay Podium initialization.
// Define an initialization protocol for Podium to avoid this.
new ScheduleTimer() {
@Override
public void run() {
initializePodium();
}
}.schedule(3000);
}
private void removeFrameBorder() {
new ScheduleTimer() {
@Override
public void run() {
ui.removeThrobber();
}
}.schedule(FRAME_BORDER_REMOVE_DELAY_MS);
}
private void constructGadgetFromMetadata(GadgetMetadata metadata, String view, String token) {
log("Received metadata: ", metadata.getIframeUrl(view));
String url = cleanUrl(metadata.getIframeUrl(view));
if (url.equals(iframeUrl) && ((token == null) || token.isEmpty())) {
log("Received metadata matches the cached information.");
constructGadgetSizeFromMetadata(metadata, view, url);
return;
}
// NOTE(user): Technically we should not save iframe URLs for gadgets with security tokens,
// but some gadgets, such as YNM, that depend on opensocial libraries get security tokens they
// never use. Also to enable gadgets in Ripple and other light Wave clients it's desirable to
// to always have the iframe URL at least for rudimentary rendering.
if (canModifyDocument() && documentModified) {
scheduleGadgetAttributeUpdate(IFRAME_URL_ATTRIBUTE, url);
} else {
toUpdateIframeUrl = true;
}
securityToken = token;
if ("".equals(ui.getTitleLabelText()) && metadata.hasTitle()) {
ui.setTitleLabelText(metadata.getTitle());
}
constructGadgetSizeFromMetadata(metadata, view, url);
}
private void constructGadgetSizeFromMetadata(GadgetMetadata metadata, String view, String url) {
int height =
(int) (metadata.hasHeight() ? metadata.getHeight() : metadata.getPreferredHeight(view));
int width =
(int) (metadata.hasWidth() ? metadata.getWidth() : metadata.getPreferredWidth(view));
registerWithController(url, width, height);
if (height > 0) {
setIframeHeight(String.valueOf(height));
} else {
setIframeHeight(String.valueOf(DEFAULT_HEIGHT_PX));
}
if (width > 0){
setIframeWidth(String.valueOf(width));
} else {
setIframeWidth(String.valueOf(DEFAULT_WIDTH_PX));
}
}
/**
* This function generates a gadget instance ID for generating gadget metadata
* and security tokens. The ID should be 1. hard to guess; 2. same for the
* same gadget element for the same participant in the same wave every time
* the wave is rendered in the same client; 3. preferably, but not necessarily
* different for different gadget elements and different participants.
*
* Condition 2 is needed to achieve consistent behavior in gadgets that, for
* example, request special permissions using OAuth/OpenSocial.
*
* This function satisfies those conditions, except the ID is going to be
* always the same for the same type of the gadget in the same wavelet for the
* same participant. This poses minimal risk (in terms of matching domains and
* security tokens) because the gadgets with matching IDs would be rendered
* for the same person in the same wave.
*
* NOTE(user): Instance ID should be non-negative number to work around a
* bug in GGS and/or Linux libraries that produces non-renderable iframe URLs
* for negative instance IDs. The domain name starts with dash "-". Browsers
* in Windows and Mac OS tolerate this, but browsers in Linux fail to render
* such URLs.
*
* @return instance ID for the gadget.
*/
private int getInstanceId() {
String name = ModernIdSerialiser.INSTANCE.serialiseWaveletName(waveletName);
String instanceDescriptor = name + loginName + source;
int hash = instanceDescriptor.hashCode();
return (hash < 0) ? ~hash : hash;
}
private void showBrokenGadget(String message) {
ui.showBrokenGadget(message);
log("Broken gadget: ", message);
}
private boolean validIframeUrl(String url) {
return (url != null) && !url.isEmpty() && !getIframeHost(url).isEmpty();
}
private void scheduleGadgetIdUpdate() {
ScheduleCommand.addCommand(new Scheduler.Task() {
@Override
public void execute() {
generateAndSetGadgetId();
}
});
}
private void allowModificationOfNewlyCreatedGadget() {
// Missing height attribute indicates freshly added gadget. Assume that the
// document is modified for the purpose of updating attributes.
if (!hasAttribute(LAST_KNOWN_HEIGHT_ATTRIBUTE) && editingIndicator.isEditing()) {
scheduleGadgetIdUpdate();
onModifyingDocument();
}
}
/**
* Creates a widget to render the gadget.
*/
public void createWidget() {
if (isActive()) {
log("Repeated attempt to create gadget widget.");
return;
}
active = true;
log("Creating Gadget Widget ", getGadgetName());
ui.enableMenu();
allowModificationOfNewlyCreatedGadget();
setSavedIframeHeight();
setSavedIframeWidth();
source = getAttribute(URL_ATTRIBUTE);
String title = getAttribute(TITLE_ATTRIBUTE);
ui.setTitleLabelText((title == null) ? "" : URL.decodeComponent(title));
updatePrefsFromAttribute(getAttribute(PREFS_ATTRIBUTE));
refreshParticipantInformation();
// HACK(anorth): This event routing should happen outside the widget.
ObservableConversation conv = (ObservableConversation) blip.getConversation();
conv.addListener(new WaveletListenerAdapter(blip, this));
log("Requesting Gadget metadata: ", source);
String cachedIframeUrl = getAttribute(IFRAME_URL_ATTRIBUTE);
if (validIframeUrl(cachedIframeUrl)) {
registerWithController(cleanUrl(cachedIframeUrl), 0, 0);
}
GadgetDataStoreImpl.getInstance().getGadgetData(source, waveletName, getInstanceId(),
new GadgetDataStore.DataCallback() {
@Override
public void onError(String message, Throwable t) {
if ((t != null) && (t.getMessage() != null)) {
message += " " + t.getMessage();
}
showBrokenGadget(message);
}
@Override
public void onDataReady(GadgetMetadata metadata, String securityToken) {
if (isActive()) {
ReadableStringSet views = metadata.getViewSet();
String view = null;
if (views.contains(GADGET_PRIMARY_VIEW)) {
view = GADGET_PRIMARY_VIEW;
} else if (views.contains(GADGET_DEFAULT_VIEW)) {
view = GADGET_DEFAULT_VIEW;
} else if (!views.isEmpty()) {
view = views.someElement();
} else {
showBrokenGadget("Gadget has no view to render.");
return;
}
String url = metadata.getIframeUrl(view);
if (validIframeUrl(url)) {
constructGadgetFromMetadata(metadata, view, securityToken);
} else {
showBrokenGadget("Invalid IFrame URL " + url);
}
}
}
});
}
/**
* Utility function to send setPref RPC to the gadget.
*
* @param target the gadget frame ID.
* @param name name of the preference to set.
* @param value value of the preference.
*/
public native void sendGadgetPrefRpc(String target, String name, String value) /*-{
try {
$wnd.gadgets.rpc.call(target, 'set_pref', null, 0, name, value);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('set_pref RPC failed');
}
}-*/;
/**
* Utility function to send initialization RPC to Podium gadget.
*
* @param target the gadget frame ID.
* @param id Podium ID of this client.
* @param otherId Podium ID of the opponent client.
*/
public native void sendPodiumOnInitializedRpc(String target, String id, String otherId) /*-{
try {
$wnd.gadgets.rpc.call(target, 'onInitialized', null, id, otherId);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('onInitialized RPC failed');
}
}-*/;
/**
* Utility function to send state change RPC to Podium gadget.
*
* @param target the gadget frame ID.
* @param state Podium gadget state.
*/
public native void sendPodiumOnStateChangedRpc(String target, String state) /*-{
try {
$wnd.gadgets.rpc.call(target, 'onStateChanged', null, state);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('onStateChanged RPC failed');
}
}-*/;
/**
* Utility function to send title to the embedding container.
*
* @param title the title value for the container.
*/
public native void sendEmbeddedRpc(String title) /*-{
try {
$wnd.gadgets.rpc.call(null, 'set_title', null, title);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('set_title RPC failed');
}
}-*/;
/**
* Utility function to send participant information to Wave gadget.
*
* @param target the gadget frame ID.
* @param participants JSON string of Wavelet participants.
*/
public native void sendParticipantsRpc(String target, JavaScriptObject participants) /*-{
try {
$wnd.gadgets.rpc.call(target, 'wave_participants', null, participants);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('wave_participants RPC failed');
}
}-*/;
/**
* Utility function to send Gadget state to Wave gadget.
*
* @param target the gadget frame ID.
* @param state JSON string of Gadget state.
*/
public native void sendGadgetStateRpc(String target, JavaScriptObject state) /*-{
try {
$wnd.gadgets.rpc.call(target, 'wave_gadget_state', null, state);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('wave_gadget_state RPC failed');
}
}-*/;
/**
* Utility function to send private Gadget state to Wave gadget.
*
* @param target the gadget frame ID.
* @param state JSON string of Gadget state.
*/
public native void sendPrivateGadgetStateRpc(String target, JavaScriptObject state) /*-{
try {
$wnd.gadgets.rpc.call(target, 'wave_private_gadget_state', null, state);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('wave_private_gadget_state RPC failed');
}
}-*/;
/**
* Utility function to send Gadget mode to Wave gadget.
*
* @param target the gadget frame ID.
* @param mode JSON string of Gadget state.
*/
public native void sendModeRpc(String target, JavaScriptObject mode) /*-{
try {
$wnd.gadgets.rpc.call(target, 'wave_gadget_mode', null, mode);
} catch (e) {
// HACK(user): Ignoring any failure for now.
@org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
('wave_gadget_mode RPC failed');
}
}-*/;
/**
* Sends the gadget state to the wave gadget. Injects the playback state value
* into the state.
*/
public void sendGadgetState() {
if (waveEnabled) {
log("Sending gadget state: ", state.toJson());
sendGadgetStateRpc(getGadgetName(), state.asJavaScriptObject());
}
}
/**
* Sends the private gadget state to the wave gadget.
*/
public void sendPrivateGadgetState() {
if (waveEnabled) {
String gadgetId = getGadgetId();
StateMap privateState = StateMap.createFromStringMap(gadgetId != null ?
supplement.getGadgetState(gadgetId) : CollectionUtils.<String> emptyMap());
log("Sending private gadget state: ", privateState.toJson());
sendPrivateGadgetStateRpc(getGadgetName(), privateState.asJavaScriptObject());
}
}
/**
* Sends the gadget mode to the wave gadget.
*/
public void sendMode() {
if (waveEnabled) {
StateMap mode = StateMap.create();
mode.put(PLAYBACK_MODE_KEY, "0");
mode.put(EDIT_MODE_KEY, editingIndicator.isEditing() ? "1" : "0");
log("Sending gadget mode: ", mode.toJson());
sendModeRpc(getGadgetName(), mode.asJavaScriptObject());
}
}
/**
* Returns the ID of the user who added the gadget as defined in the author
* attribute. If the attribute is not defined returns the blip author instead
* (as the best guess for the author for backward compatibility).
*
* @return author ID of the user who added the gadget to the wave
*/
private String getAuthor() {
String author = element.getAttribute(AUTHOR_ATTRIBUTE);
return (author != null) ? author : blip.getAuthorId().getAddress();
}
/**
* Builds a map of participants from two lists of participant ids.
*/
private StringMap<ParticipantId> getParticipantsForIds(
Collection<ParticipantId> list1, Collection<ParticipantId> list2) {
StringMap<ParticipantId> mergedMap = CollectionUtils.createStringMap();
for (ParticipantId p : list1) {
mergedMap.put(p.getAddress(), p);
}
for (ParticipantId p : list2) {
mergedMap.put(p.getAddress(), p);
}
return mergedMap;
}
/**
* Refreshes the participant information.
*/
private void refreshParticipantInformation() {
StringMap<ParticipantId> waveletParticipants = getParticipantsForIds(
blip.getConversation().getParticipantIds(), blip.getContributorIds());
ParticipantId viewerId = new ParticipantId(loginName);
waveletParticipants.put(viewerId.getAddress(), viewerId);
List<ParticipantId> participantList = CollectionUtils.newJavaList(waveletParticipants);
participants = ParticipantInformation.create(
viewerId.getAddress(), getAuthor(), participantList, getUrlPrefix(), profileManager);
final StringBuilder builder = new StringBuilder();
builder.append("Participants: ");
builder.append("I am " + participants.getMyId());
for (ParticipantId participant : participantList) {
builder.append("; " + participant);
}
log(builder.toString());
}
/**
* Refreshes and sends participant information to wave-enabled gadget.
*/
private void sendCurrentParticipantInformation() {
if (waveEnabled) {
refreshParticipantInformation();
sendParticipantsRpc(getGadgetName(), participants);
log("Sent participants: ", participants);
}
}
/**
* Utility function to perform setPref RPC to the gadget.
*
* @param name name of the preference to set.
* @param value value of the preference.
*/
public void setGadgetPref(final String name, final String value) {
ScheduleCommand.addCommand(new Task() {
@Override
public void execute() {
if (isActive()) {
sendGadgetPrefRpc(getGadgetName(), name, value);
}
}
});
}
/**
* Marks the Widget as inactive after the gadget node is removed from the
* parent.
*/
public void setInactive() {
log("Gadget node removed.");
supplement.removeListener(this);
active = false;
}
@Override
public void setIframeHeight(String height) {
if (!isActive()) {
return;
}
log("Set IFrame height ", height);
try {
int heightValue = parseSizeString(height);
ui.setIframeHeight(heightValue);
scheduleGadgetAttributeUpdate(LAST_KNOWN_HEIGHT_ATTRIBUTE, Long.toString(heightValue));
} catch (NumberFormatException e) {
log("Invalid height (ignored): ", height);
}
}
public void setIframeWidth(String width) {
if (!isActive()) {
return;
}
log("Set IFrame width ", width);
try {
int widthValue = parseSizeString(width);
ui.setIframeWidth(widthValue + "px");
ui.makeInline();
scheduleGadgetAttributeUpdate(LAST_KNOWN_WIDTH_ATTRIBUTE, Long.toString(widthValue));
} catch (NumberFormatException e) {
log("Invalid width (ignored): ", width);
}
}
@Override
public void requestNavigateTo(String url) {
log("Requested navigate to: ", url);
// NOTE(user): Currently only allow the gadgets to change the fragment part of the URL.
String newFragment = url.replaceFirst(BEFORE_FRAGMENT_PATTERN, "");
if (newFragment.matches(FRAGMENT_VALIDATION_PATTERN)) {
Location.replace(Location.getHref().replaceFirst(FRAGMENT_PATTERN, "") + "#" + newFragment);
} else {
log("Navigate request denied.");
}
}
@Override
public void updatePodiumState(String podiumState) {
if (isActive()) {
modifyState(PODIUM_STATE_NAME, podiumState);
blipSubmitter.submit();
}
}
private void setPref(String key, String value) {
if (!canModifyDocument() || (key == null) || (value == null)) {
return;
}
userPrefs.put(key, value);
if (prefElements.containsKey(key)) {
if (!prefElements.get(key).getValue().equals(value)) {
log("Updating preference '", key, "'='", value, "'");
onModifyingDocument();
prefElements.get(key).setValue(value);
blipSubmitter.submit();
}
} else {
log("New preference '", key, "'='", value, "'");
onModifyingDocument();
element.getMutableDoc().insertXml(
Point.end((ContentNode)element), GadgetXmlUtil.constructPrefXml(key, value));
blipSubmitter.submit();
}
}
@Override
public void setPrefs(String ... keyValue) {
// Ignore callbacks from the gadget in playback mode.
if (!canModifyDocument()) {
return;
}
// Ignore the last key if its value is missing.
for (int i = 0; i < keyValue.length - 1; i+=2) {
setPref(keyValue[i], keyValue[i + 1]);
}
}
/**
* Sets up a polling loop to check the edit mode state and send it to the
* gadget.
*
* TODO(user): Add edit mode change events to the client and find a way to
* relay them to the gadget containers.
*/
private void setupModePolling() {
new ScheduleTimer() {
private boolean wasEditing = editingIndicator.isEditing();
@Override
public void run() {
if (!isActive()) {
cancel();
return;
} else {
boolean newEditing = editingIndicator.isEditing();
if (wasEditing != newEditing) {
sendMode();
wasEditing = newEditing;
}
}
}
}.scheduleRepeating(EDITING_POLLING_TIMER_MS);
}
/**
* HACK: This is a workaround for Firefox bug
* https://bugzilla.mozilla.org/show_bug.cgi?id=498904 Due to this bug the
* gadget RPCs may be sent to a dead iframe. Changing the iframe ID fixes
* container-to-gadget communication. Non-wave gadgets may have other issues
* associated with this bug. But most wave-enabled gadgets should work when
* the iframe ID is updated in the waveEnable call.
*/
private void substituteIframeId() {
clientInstanceId = nextClientInstanceId++;
ui.setIframeId(getGadgetName());
controllerRegistration(iframeUrl, 0, 0);
}
@Override
public void waveEnable(String waveApiVersion) {
if (!isActive()) {
return;
}
// HACK: See substituteIframeId() description.
// TODO(user): Remove when the Firefox bug is fixed.
if (UserAgent.isFirefox()) {
substituteIframeId();
}
waveEnabled = true;
this.waveApiVersion = waveApiVersion;
log("Wave-enabled gadget registered with API version ", waveApiVersion);
sendWaveGadgetInitialization();
setupModePolling();
}
@Override
public void waveGadgetStateUpdate(final JavaScriptObject delta) {
// Return if in playback mode. isEditable indicates playback.
if (!canModifyDocument()) {
return;
}
final StateMap deltaState = StateMap.create();
deltaState.fromJsonObject(delta);
// Defer state modifications to avoid RPC failure in Safari 3. The
// intermittent failure is caused by RPC called from received RPC
// callback.
// TODO(user): Remove this workaround once this is fixed in GGS.
ScheduleCommand.addCommand(new Task() {
@Override
public void execute() {
deltaState.each(new Each() {
@Override
public void apply(final String key, final String value) {
if (value != null) {
modifyState(key, value);
} else {
deleteState(key);
}
}
});
log("Applied delta ", delta.toString(), " new state ", state.toJson());
gadgetStateSubmitter.triggerScheduledSubmit();
blipSubmitter.submitImmediately();
}
});
}
/**
* Generates a unique gadget ID.
* TODO(user): Replace with proper MD5-based UUID.
*
* @return a unique gadget ID.
*/
private String generateGadgetId() {
String name = ModernIdSerialiser.INSTANCE.serialiseWaveletName(waveletName);
String instanceDescriptor = name + getAuthor() + source;
String prefix = Integer.toHexString(instanceDescriptor.hashCode());
String time = Integer.toHexString(new Date().hashCode());
String version = Long.toHexString(blip.getLastModifiedVersion());
return prefix + time + version;
}
private String generateAndSetGadgetId() {
if (!canModifyDocument()) {
return null;
}
String id = generateGadgetId();
element.getMutableDoc().setElementAttribute(element, ID_ATTRIBUTE, id);
return id;
}
private String getGadgetId() {
return element.getAttribute(ID_ATTRIBUTE);
}
private String getOrGenerateGadgetId() {
String id = getGadgetId();
if ((id == null) || id.isEmpty()) {
id = generateAndSetGadgetId();
}
return id;
}
@Override
public void wavePrivateGadgetStateUpdate(JavaScriptObject delta) {
// Return if in playback mode. isEditable indicates playback.
if (!canModifyDocument()) {
return;
}
StateMap deltaState = StateMap.create();
deltaState.fromJsonObject(delta);
final String gadgetId = getOrGenerateGadgetId();
if (gadgetId != null) {
deltaState.each(new Each() {
@Override
public void apply(final String key, final String value) {
supplement.setGadgetState(gadgetId, key, value);
}
});
log("Applied private delta ", deltaState.toJson());
privateGadgetStateSubmitter.triggerScheduledSubmit();
} else {
log("Unable to get gadget ID to update private state. Delta ", deltaState.toJson());
}
}
private void modifyState(String key, String value) {
if (!canModifyDocument()) {
log("Unable to modify state ", key, " ", value);
} else {
log("Modifying state ", key, " ", value);
if (stateElements.containsKey(key)) {
if (!stateElements.get(key).getValue().equals(value)) {
onModifyingDocument();
stateElements.get(key).setValue(value);
}
} else {
onModifyingDocument();
element.getMutableDoc().insertXml(
Point.end((ContentNode)element), GadgetXmlUtil.constructStateXml(key, value));
}
}
}
private void deleteState(String key) {
if (!canModifyDocument()) {
log("Unable to remove state ", key);
} else {
log("Removing state ", key);
if (stateElements.containsKey(key)) {
onModifyingDocument();
element.getMutableDoc().deleteNode(stateElements.get(key).getElement());
}
}
}
private void sendWaveGadgetInitialization() {
sendMode();
sendCurrentParticipantInformation();
gadgetStateSubmitter.submitImmediately();
privateGadgetStateSubmitter.submitImmediately();
// Send participant information one more time as participant pictures may be
// loaded with a delay. There is no callback to get the picture update
// event.
new ScheduleTimer() {
@Override
public void run() {
if (isActive()) {
sendCurrentParticipantInformation();
}
}
}.schedule(REPEAT_PARTICIPANT_INFORMATION_SEND_DELAY_MS);
}
private void updateElementMaps(
GadgetElementChild child, StringMap<GadgetElementChild> childMap, StateMap stateMap) {
if (child.getKey() == null) {
log("Missing key attribute: element ignored.");
return;
}
if (childMap.containsKey(child.getKey())) {
logFine("Old value: ", childMap.get(child.getKey()));
}
childMap.put(child.getKey(), child);
stateMap.put(child.getKey(), child.getValue());
logFine("Updated element ", child.getKey(), " : ", child.getValue());
}
private void processTitleChild(GadgetElementChild child) {
titleElement = child;
String newTitleValue = child.getValue();
if (newTitleValue == null) {
newTitleValue = "";
}
if (!newTitleValue.equals(ui.getTitleLabelText())) {
ui.setTitleLabelText(newTitleValue);
}
}
private void removeChildFromMaps(
GadgetElementChild child, StringMap<GadgetElementChild> childMap, StateMap stateMap) {
String key = child.getKey();
if (childMap.containsKey(key)) {
stateMap.remove(key);
childMap.remove(key);
logFine("Removed element ", key);
}
}
private void processChild(GadgetElementChild child) {
if (child == null) {
return;
}
logFine("Processing: ", child);
switch (child.getType()) {
case STATE:
updateElementMaps(child, stateElements, state);
break;
case PREF:
updateElementMaps(child, prefElements, userPrefs);
break;
case TITLE:
processTitleChild(child);
break;
case CATEGORIES:
logFine("Categories element ignored.");
break;
default:
// Note(user): editor may add/remove selection and cursor nodes.
logFine("Unexpected gadget node ", child.getTag());
}
}
/**
* Finds the first copy of the given child in the sibling sequence starting at
* the given node.
*
* @param child Child to find next copy of.
* @param node Node to scan from.
* @return Next copy of the child or null if not found.
*/
private static GadgetElementChild findNextChildCopy(GadgetElementChild child, ContentNode node) {
if (child == null) {
return null;
}
while (node != null) {
GadgetElementChild gadgetChild = GadgetElementChild.create(node);
if (child.isDuplicate(gadgetChild)) {
return gadgetChild;
}
node = node.getNextSibling();
}
return null;
}
/**
* Task removes redundant nodes that match redundantNodeCheckChild.
*/
private final Scheduler.Task removeRedundantNodesTask = new Scheduler.Task() {
@Override
public void execute() {
if (!canModifyDocument()) {
return;
}
if (redundantNodeCheckChild != null) {
GadgetElementChild firstMatchingNode = findNextChildCopy(
redundantNodeCheckChild, element.getFirstChild());
GadgetElementChild lastSeenNode = firstMatchingNode;
while (lastSeenNode != null) {
lastSeenNode = findNextChildCopy(
redundantNodeCheckChild, firstMatchingNode.getElement().getNextSibling());
if (lastSeenNode != null) {
log("Removing: ", lastSeenNode);
element.getMutableDoc().deleteNode(lastSeenNode.getElement());
}
}
} else {
log("Undefined redundant node check child.");
}
redundantNodeCheckChild = null;
}
};
/**
* Scans nodes and removes duplicate copies of the given child leaving only
* the first copy.
* TODO(user): Unit test for node manipulations.
*
* @param child Child to delete the duplicates of.
*/
private void removeRedundantNodes(final GadgetElementChild child) {
if (!documentModified || (child == null)) {
return;
}
if (redundantNodeCheckChild == null) {
redundantNodeCheckChild = child;
ScheduleCommand.addCommand(removeRedundantNodesTask);
} else {
log("Overlapping redundant node check requests.");
}
}
private final ElementChangeTask childAddedTask = new ElementChangeTask() {
@Override
void processChange(ContentNode node) {
GadgetElementChild child = GadgetElementChild.create(node);
log("Added: ", child);
if (child != null) {
removeRedundantNodes(child);
processChild(child);
}
}
};
/**
* Processes an add child event.
*
* @param node the child added to the gadget node.
*/
public void onChildAdded(ContentNode node) {
childAddedTask.run(node);
}
private final ElementChangeTask childRemovedTask = new ElementChangeTask() {
@Override
void processChange(ContentNode node) {
GadgetElementChild child = GadgetElementChild.create(node);
log("Removed: ", child);
switch (child.getType()) {
case STATE:
removeChildFromMaps(child, stateElements, state);
break;
case PREF:
removeChildFromMaps(child, prefElements, userPrefs);
break;
case TITLE:
log("Removing title is not supported");
break;
case CATEGORIES:
log("Removing categories is not supported");
break;
default:
// Note(user): editor may add/remove selection and cursor nodes.
log("Unexpected gadget node removed ", child.getTag());
}
}
};
/**
* Processes a remove child event.
*
* @param node
*/
public void onRemovingChild(ContentNode node) {
childRemovedTask.run(node);
}
/**
* Rescans all gadget children to update the values stored in the gadget
* object.
*/
private void rescanGadgetXmlElements() {
log("Rescanning elements");
ContentNode childNode = element.getFirstChild();
while (childNode != null) {
processChild(GadgetElementChild.create(childNode));
childNode = childNode.getNextSibling();
}
}
private final ElementChangeTask descendantsMutatedTask = new ElementChangeTask() {
@Override
void processChange(ContentNode node) {
rescanGadgetXmlElements();
}
};
private final Scheduler.Task schedulableMutationTask = new Scheduler.Task() {
@Override
public void execute() {
descendantsMutatedTask.run(null);
}
};
/**
* Processes a mutation event.
*/
public void onDescendantsMutated() {
log("Descendants mutated.");
ScheduleCommand.addCommand(schedulableMutationTask);
}
@Override
public void onBlipContributorAdded(ParticipantId contributor) {
if (isActive()) {
log("Contributor added ", contributor);
sendCurrentParticipantInformation();
} else {
log("Contributor added event in deleted node.");
}
}
@Override
public void onBlipContributorRemoved(ParticipantId contributor) {
if (isActive()) {
log("Contributor removed ", contributor);
sendCurrentParticipantInformation();
} else {
log("Contributor removed event in deleted node.");
}
}
@Override
public void onParticipantAdded(ParticipantId participant) {
if (isActive()) {
log("Participant added ", participant);
sendCurrentParticipantInformation();
} else {
log("Participant added event in deleted node.");
}
}
@Override
public void onParticipantRemoved(ParticipantId participant) {
if (isActive()) {
log("Participant removed ", participant);
sendCurrentParticipantInformation();
} else {
log("Participant removed event in deleted node.");
}
}
private Object[] expandArgs(Object object, Object ... objects) {
Object[] args = new Object[objects.length + 1];
args[0] = object;
System.arraycopy(objects, 0, args, 1, objects.length);
return args;
}
private void log(Object ... objects) {
if (GadgetLog.shouldLog()) {
GadgetLog.logLazy(expandArgs(clientInstanceLogLabel, objects));
}
}
private void logFine(Object ... objects) {
if (GadgetLog.shouldLogFine()) {
GadgetLog.logFineLazy(expandArgs(clientInstanceLogLabel, objects));
}
}
/**
* Returns the URL of the client including protocol and host.
*
* @return URL of the client.
*/
private String getUrlPrefix() {
return Location.getProtocol() + "//" + Location.getHost();
}
/**
* Returns the UI element.
*
* @return UI element.
*/
Element getElement() {
return ui.getElement();
}
private boolean isActive() {
return active;
}
private boolean canModifyDocument() {
return isActive();
}
@Override
public void deleteGadget() {
if (canModifyDocument()) {
element.getMutableDoc().deleteNode(element);
}
}
@Override
public void selectGadget() {
if (isActive()) {
CMutableDocument doc = element.getMutableDoc();
element.getSelectionHelper().setSelectionPoints(
Point.before(doc, element), Point.after(doc, element));
}
}
@Override
public void resetGadget() {
if (canModifyDocument()) {
state.each(new Each() {
@Override
public void apply(String key, String value) {
deleteState(key);
}
});
gadgetStateSubmitter.submit();
final String gadgetId = getGadgetId();
if (gadgetId != null) {
supplement.getGadgetState(gadgetId).each(new ProcV<String>() {
@Override
public void apply(String key, String value) {
supplement.setGadgetState(gadgetId, key, null);
}
});
privateGadgetStateSubmitter.submit();
}
}
}
private static native void excludeCssName() /*-{
css();
}-*/;
private static class BlipEditingIndicator implements EditingIndicator {
private final ContentElement element;
/**
* Constructs editing indicator for the gadget's blip.
*/
BlipEditingIndicator(ContentElement element) {
this.element = element;
}
/**
* Returns the current edit state of the blip.
* TODO(user): add event-driven update of the edit state.
*
* @return whether the blip is in edit state.
*/
@Override
public boolean isEditing() {
return (element != null)
? AnnotationPainter.isInEditingDocument(ContentElement.ELEMENT_MANAGER, element) : false;
}
}
@Override
public void onMaybeGadgetStateChanged(String gadgetId) {
if (gadgetId != null) {
String myId = getGadgetId();
if (gadgetId.equals(myId)) {
privateGadgetStateSubmitter.submitImmediately();
}
}
}
/**
* Executes when the document is being modified in response to a user action.
*/
private void onModifyingDocument() {
documentModified = true;
if (toUpdateIframeUrl) {
scheduleGadgetAttributeUpdate(IFRAME_URL_ATTRIBUTE, iframeUrl);
toUpdateIframeUrl = false;
}
}
/**
* Creates GadgetWidget instance with preset fields for testing.
*
* TODO(user): Refactor to remove test code.
*
* @param id client instance ID
* @param userPrefs user prederences
* @param waveletName wavelet name
* @param securityToken security token
* @param locale locale
* @return test instance of the widget
*/
@VisibleForTesting
static GadgetWidget createForTesting(int id, GadgetUserPrefs userPrefs, WaveletName waveletName,
String securityToken, Locale locale) {
GadgetWidget widget = new GadgetWidget();
widget.clientInstanceId = id;
widget.userPrefs = userPrefs;
widget.waveletName = waveletName;
widget.securityToken = securityToken;
widget.locale = locale;
return widget;
}
/**
* @return RPC token for testing
*/
@VisibleForTesting
String getRpcToken() {
return rpcToken;
}
}
| 32.881281 | 100 | 0.668235 |
1392cefd512078055424277425de354dd0b5af55 | 596 | package statements.functions.meta.functionarity;
import interpreter.LimitedRemoveStack;
import interpreter.NoBracesStack;
import statements.EvaluationException;
import statements.functions.UnaryFunction;
import statements.literals.ListStatement;
public abstract class AryFunction extends UnaryFunction<ListStatement> {
protected abstract int getArity();
@Override
protected void eval(NoBracesStack stackState, ListStatement a) throws EvaluationException {
LimitedRemoveStack stackWrap = new LimitedRemoveStack(stackState, getArity());
a.dequote(stackWrap);
stackWrap.close();
}
}
| 28.380952 | 92 | 0.827181 |
3b8be8ea4ffcb67ea87e230c5c883846910cb033 | 1,009 | package com.noobanidus.hungering.compat.baubles;
import baubles.api.cap.BaublesCapabilities;
import com.noobanidus.hungering.item.ItemTorc;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class CapabilityHandler implements ICapabilityProvider {
public static final CapabilityHandler INSTANCE = new CapabilityHandler();
@Override
public boolean hasCapability(@Nonnull net.minecraftforge.common.capabilities.Capability<?> capability, @Nullable EnumFacing facing) {
return capability == BaublesCapabilities.CAPABILITY_ITEM_BAUBLE;
}
@Nullable
@Override
public <T> T getCapability(@Nonnull net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable EnumFacing facing) {
return capability == BaublesCapabilities.CAPABILITY_ITEM_BAUBLE ? BaublesCapabilities.CAPABILITY_ITEM_BAUBLE.cast(ItemTorc.bauble) : null;
}
}
| 40.36 | 146 | 0.801784 |
0b58acc046054cee9e8dd6c466a5c3d14ba82ac9 | 2,278 | package com.fasterxml.clustermate.service.cleanup;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
import com.fasterxml.clustermate.service.SharedServiceStuff;
import com.fasterxml.clustermate.service.Stores;
import com.fasterxml.clustermate.service.cluster.ClusterViewByServer;
/**
* Bogus "cleaner" task that will calculate disk space usage for backend data store.
*/
public class DiskUsageTracker extends CleanupTask<DiskUsageStats>
{
/* Let's cap max files and dirs traversed, to limit amount of time we
* spend on collecting stats in case we get misconfigured.
*/
protected final static int MAX_DIRS = 4000;
protected final static int MAX_FILES = 25000;
/**
* We will also calculate disk usage of metadata database, if available.
*/
protected File _dbRoot;
public DiskUsageTracker() { }
@Override
protected void init(SharedServiceStuff stuff, Stores<?,?> stores,
ClusterViewByServer cluster, AtomicBoolean shutdown)
{
super.init(stuff, stores, cluster, shutdown);
_dbRoot = stores.getEntryStore().getBackend().getStorageDirectory();
}
@Override
public DiskUsageStats _cleanUp()
{
DiskUsageStats stats = new DiskUsageStats(MAX_DIRS, MAX_FILES);
_reportStart();
if (_dbRoot != null) {
_add(stats, _dbRoot);
}
try {
return stats;
} finally {
_reportEnd(stats);
}
}
private boolean _add(DiskUsageStats stats, File curr)
{
if (curr.isDirectory()) {
if (!stats.addDir()) {
return false;
}
for (File f : curr.listFiles()) {
if (!_add(stats, f)) {
return false;
}
}
} else {
if (!stats.addFile(curr)) {
return false;
}
}
return true;
}
/*
/**********************************************************************
/* Overridable reporting methods
/**********************************************************************
*/
protected void _reportStart() { }
protected void _reportEnd(DiskUsageStats stats) { }
}
| 28.123457 | 84 | 0.564091 |
704fff99b9f2c15b5d594510d2d8fe5b9122717d | 8,333 | class AEjSQ {
public static void lcSMFe (String[] MvH2f) throws EfE {
int Dlpp;
return;
void v_se84Q9dInC;
while ( zWQHWSpA8vH.QxhoBOtx5p9l3()) return;
}
public boolean[] EvzRi6jLLG () {
;
int[] goTnp = null[ this.V6bPRPFaiAbcG()] = !qy3GQ()[ -true.k1cLA6n4PTfw6()];
;
int dVT_BY0HfB = false._tirhe() = new h75().o();
{
void vKwAX0;
;
pyEabiJmWoFsSw[][] HL;
return;
-!new boolean[ -!kNg9FinF().iERrqJNnEM][ --null[ pw.s2uvaE3j9b_q]];
void[] E_1p_Hlpvmsl;
int C5evt;
null.o;
}
boolean ABf0WGSulpM5 = tvePzhG3D()[ new void[ null.Gg4YDDX8iwfF7()].w()];
boolean[][] Ju0lV;
void OZ1Z1An7eU;
return -!true.QGmSoZnuWAPLCS();
{
;
}
{
while ( new ACNx26ZNAn[ !-!-new q()[ ( zhc_Y55S4mNvD.AlgOE())[ this.X]]].sBeWk67pTv) ;
FB M1ij1fSyrPGnUw;
while ( -!npLHiGJ.tKCHmmOF()) new V6ww[ new B98().omY8mLRH0()].WkKyXp();
while ( -!-new krU[ ( new LQVyW2cK().T8Z)[ null.sK()]].xQR4E()) while ( !new ZvtQXtiihv()[ new H().bD7BS4y()]) ;
}
true.fWls;
{
void[][] tTonC;
void[] FSsxSPpYsGti4;
this.avFJlqtsK28wT();
return;
{
{
int VSHobKuNs6Ox;
}
}
void[] iCjvpjBQkzQuZd;
return;
;
{
int AAzgQDBi3Tz7;
}
while ( --null.DEsrPj8C) {
C6MbMK5oQcKw[] Qip7lf;
}
bh[] Pka5QL9X9jCr_;
int pdy;
QRbnga tZgGWi;
int xVYa9FaOCFYaGY;
}
while ( ---WaTE().COTOP) return;
boolean YgpRf7lgkAzuLO = -( this.pg8fmQJs)[ !-V_().ceziLa] = -LAv[ !new cuxJ()._K9ktJ6pror1y];
}
public void[][][][][][] rJX4QK2OeZyy () throws e {
void EPWxAWx0i = -!!-new ACDuFSCIKE().H0hSJh74WB;
boolean TSy2Y = --!new boolean[ -true.PO6PT3K()].QIWHtvebH;
return this.TI();
int[] ZvCHVi;
void[][] pA0OXpQZCw6;
}
public boolean ab4YJluN4GnAW;
public int cqgvjwLaLS4 () throws EMYb2J8nHCjRd {
while ( new slsC6()[ -null[ false.EeH8tW]]) ;
if ( !new void[ SX().NdS_93o_QRIc()].Ajso4()) if ( new Zi8rPxHXLbnF().lRVoIEX8C) while ( xuV9A36l5SZ0aF().A()) -null.Sb();
void[][] Kj = false.wFFwQmlH8A62Z;
boolean[][][] dIK = new PE[ null.fGIkDKi2WBxP()].CDJeCGACbjRdn() = -this[ ---null.QxgCpoh9bGAAz()];
return;
kE0BSHht[] Cl6U4Cq24 = this.sh3Cw9KuURNRat();
boolean LFh7xFq;
nobneXJuzj G4P0bahLJDh;
int M;
while ( sJLnzyJDUDRJU()[ 7[ ( !-new Sf56()[ new BeqZGgevNUa5()[ new void[ this[ hj8()[ !--!!new vwX().h8ff]]].laqP]]).v0snuJCJ1]]) if ( -YZUo28().VG_VkO1gc) return;
cM8_kmuL _etIdAO3;
9639[ qnd6GxVeiPe.RVUj];
while ( --_NyC.mTEkNdZaC()) if ( 363912443.LFqCM()) return;
;
}
public static void wvpyc (String[] A) throws K1 {
;
}
public boolean[][][][] bbVCgUSYOJXyk6;
public static void JS1rDX3np1xj (String[] Rf0tLmutw) {
boolean w1zMGg7XG1p_sM = this.d0ZTD06c() = new fB()[ new void[ !new void[ -new int[ !!!!-!this.a].LtEFbUSAnu()][ null[ false.OWZNpbf8k]]].u()];
if ( !h6sFsI2mWKg().Ya5S1l8L6t_o()) {
;
}else while ( null[ --true.Fft35Rcc6()]) {
return;
}
int[] pvPgQXc0ZWx4tC = --!-N()[ false.siGqvoxRMMwZ];
{
int[][][][] S;
;
}
if ( SXH2[ -----!true[ !-uS_m54n8z_Fmr.ivpl4l]]) ( -this[ 89554173.oBlAQqydnB()])[ -!qtE0EHoI.I0()];else return;
{
;
boolean Ep;
;
-new T[ ( -( uQjZfX1x_WvD.TyFWRVM)[ !new c()[ new LcVixSNLYX[ -d.Dx2i79R6p7zt()].YmCr()]]).WZlJhgeXPATd2u].BP;
boolean qNXXkR3Tf;
void[][][] QHPkuqpJCqr;
return;
if ( this.Okg4BwAl0hiSN()) !Rq6OMotPwrVgB()[ ( true.YDgdg()).PTf4pgnUB6()];
while ( P4i()[ --false.gseMuXDfdF3()]) return;
}
void[][] _dCa;
{
return;
boolean pZoN;
return;
true.E2jI00j32m_();
}
boolean C2nUOfethunLS = !-!dUM9XUkJS.oBLHelIkscj();
int[] ZiX93yZdqM3SS6;
return;
{
if ( !ErgE()[ !true[ this[ --!-!true.aCO0qOZSpUIkvg()]]]) null[ true.KOYblcJaUtYWY];
{
--null[ !!!--!null[ !!this.pPLL()]];
}
;
if ( !new O93().QzejZ) !new void[ !this.cm9RnJr()][ !null.OgCof2n3R()];
}
return;
boolean[] cJ2biQRPG8CE;
;
void PVTQx1_BwpBC;
return !!new qqVE().F46ctZ3JUoux();
}
public static void BdNivI6PBVf (String[] Iaen3MXfG5B8bv) throws gi8LYCi2EH {
boolean A;
void[] ELFZ9MKE;
while ( !new boolean[ new Z2tcwrA().S8QBNL8()].S5vP4) return;
}
public boolean T_ZeUauLC6Q4G;
public int[][][] yEVqhg_;
public int[][][] QI7LfTbI0sm5PZ () {
{
!50101327.PSIk();
wpp1ziwfVxQcm1[][][] qs95HS;
int[][][] mRRn;
return;
while ( null[ !s7xEL3pOfRN.Bhs0]) while ( true[ ( null.kl3WWAldcTY7rM).Z07gUmR]) ;
null[ !!--false.H3ExQfVyYW];
while ( ( -new zxEqLHU9vQnix3().XI()).mcM74ichgn) {
S BPZ6DT9a9hI;
}
return;
return;
if ( null[ -WU().PzAlrXjDV()]) ;
WQw y;
int[][][] ngjsCI;
if ( new w9v1z[ !ghEOMurGhmcD().itk].Oi2m9l) while ( !n[ true[ -!new D5Ti71q().V2Bz9paHC]]) if ( !false.qaEIUsZCK()) ;
{
return;
}
void tfLg58RjHosM;
Lkeq3GRCJtiEDC[][] c9pAHlma76yHj;
int[] l43H2;
n4zE9wQRzXaAi Z2rG;
boolean FiGxO_;
}
!-this[ false.m7Vsk0sxyDDPMf()];
--false.Mo8rScnFM;
while ( !Z6dO().yHAvok97ZR()) if ( !--!!this.EuVy) return;
boolean sZf;
int[] ekuv95i;
if ( false.iXzQH4o()) return;
}
public int Lwi;
}
class KYP726e {
}
class zbMHebXaPAwg_ {
}
class xex {
public boolean F;
public boolean LasFuzhW8DRxd;
}
class kak0oh {
public boolean[] PVPh;
public boolean[] y01L;
public void[][] Jbq (hQfPCQbai[][][][][][] qj, void[][][] jOReHb, void[][] ZgZQUjbfAvij, Dd2p5ZHoSVgd[][][] AHmnJhC6fiE1PV) throws z {
boolean RnNtVB1pbwq = new int[ this.d0uh_6JvK_kk()][ -new _Nv0ytDj4F5q7().zlwvLm()] = -40631729.FDrCjb();
boolean KK = -( null.ZR())[ new TszjynsI7XL[ ( !!xgmZv().OS9()).InQ484].gKbIQQh2pP()] = !!-new int[ false.p8e()][ !-!!!-!---!!new void[ -new boolean[ ( -j()[ ( -NcW1Ea38Vl4mC().VN8bCBFGnA)[ !!46[ Fa8yt.sDbz5ujbOb9oq6()]]]).hHaMu34vgpQgbV][ -!true.rmp6iW()]].I4dI];
wv6ORx CJ4eBUDd5JDH;
if ( -!null.f4uPrKfOSg()) if ( new int[ this[ x().NJvyt()]][ new void[ D1kTBO()[ ( -true.DWWjvF)[ ----this.TU]]].lRKiP0WWn]) while ( this.Nv_oo3oz4he) -new mWUNNDvW().VmYrY9P();
void UGH6L;
while ( YwrU9VBKX0E().O75YQ7) ;
void QnL2PS8Zp7j_m8 = -( ( !false.WnCfFXN)[ !new void[ -true[ !!( true.QPSpNltjX).ELSRaGiwEl()]].WcXMh4]).BIEX9rR6dRDaY = 8.ybue1;
}
public static void zeiw48aucJlg (String[] Ke) throws NchGfNKA5OJ5PM {
boolean xht;
if ( ---!!!-( --true.pe8oiyDRBcu5IT()).u0Uwl85s) return;else ;
{
int _btNKcnG;
true.rqeV;
null[ -null.JAWAsrf];
while ( -( true.lvZIVnJ())[ 94705554[ ( new boolean[ -!true.G3wozen_49MJVO()].RiqL_UHRkO2()).MjpHwC6Qv]]) {
ocEepu7g[] uaLs88MGq;
}
return;
void UC;
boolean Izl0c9zQmyJFt;
int[] sCBcV;
int Jpkc2nw1BN;
}
boolean lqSXT;
;
boolean[] FxnFb64GhMHAEk = --!--!!-!true.roRs() = new boolean[ -gAtRGsjxmy7Di[ -true.rjg6nja]].YBEnWGD;
while ( new jw1nyMMm48G()[ false.y5An36X]) ;
boolean FdJVyWyyfD5E;
}
}
| 36.073593 | 274 | 0.50354 |
de7a2e7166a481add3c826356e63c299c9d82237 | 4,691 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.nx42.maps4cim.util.gis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.text.ParseException;
import org.junit.Test;
import de.nx42.maps4cim.util.gis.Area;
import de.nx42.maps4cim.util.gis.Coordinate;
import de.nx42.maps4cim.util.gis.UnitOfLength;
/**
*
* @author Sebastian Straub <[email protected]>
*/
public class AreaTest {
protected static final double north = 48.0;
protected static final double west = 10.0;
protected static final Coordinate nw = new Coordinate(north, west);
protected static final double south = 47.0;
protected static final double east = 11.0;
protected static final Coordinate se = new Coordinate(south, east);
protected static final double precision = 0.0000001;
@Test
public void testConstructor1() {
Area instance = new Area(south, west, north, east);
testResult(instance);
}
@Test
public void testConstructor2() {
Area instance = new Area(nw, se);
testResult(instance);
}
@Test
public void testConstructorCenter1() {
Coordinate center = new Coordinate(48.0, 10.0);
Area result = new Area(center, 1.0);
Area expResult = new Area(47.5, 9.5, 48.5, 10.5);
assertEquals(expResult, result);
}
@Test
public void testConstructorCenter2() {
Coordinate center = new Coordinate(48.0, 10.0);
Area result = new Area(center, 2.0, 1.0);
Area expResult = new Area(47.0, 9.5, 49.0, 10.5);
assertEquals(expResult, result);
}
@Test
public void testConstructorCenter3() {
Coordinate center = new Coordinate(48.0, 10.0);
Area result = new Area(center, 100.0, UnitOfLength.KILOMETER);
Area expResult = new Area(47.5508423579, 9.32874443674, 48.4491576420, 10.67125556325);
assertEquals(expResult, result);
}
@Test
public void testConstructorCenter4() {
Coordinate center = new Coordinate(48.0, 10.0);
Area result = new Area(center, 100.0, 65.0, UnitOfLength.KILOMETER);
Area expResult = new Area(47.550842357935, 9.5636838838824, 48.449157642011, 10.4363161161166);
assertEquals(expResult, result);
}
@Test
public void testConstructorCenter5() {
Coordinate center = new Coordinate(48.0, 10.0);
Area result = new Area(center, 100000.0, UnitOfLength.METER);
Area expResult = new Area(47.5508423579, 9.32874443674, 48.4491576420, 10.67125556325);
assertEquals(expResult, result);
}
@Test
public void testConstructor5() {
Area instance = new Area(new double[]{south, west, north, east});
testResult(instance);
}
protected void testResult(Area instance) {
assertEquals(south, instance.getMinLat(), precision);
assertEquals(west, instance.getMinLon(), precision);
assertEquals(north, instance.getMaxLat(), precision);
assertEquals(east, instance.getMaxLon(), precision);
assertEquals(nw, instance.getBoundNW());
assertEquals(se, instance.getBoundSE());
}
@Test
public void testParseSimple() {
String s = "47.0,10.0,48.0,11.0";
compareParsed(s);
}
@Test
public void testParseSimpleEvil() {
String s = " N47.0° , E 10.0, n 48.0000°, 11";
compareParsed(s);
}
@Test
public void testParseOsm() {
String s = "minlon=10.0&minlat=47.0&maxlon=11.0&maxlat=48.0";
compareParsed(s);
}
@Test
public void testParseOsmEvil() {
String s = " minLon=10&minLat= 47.0 & MAXlon= 11.0 & maxLAT= 48.00000 ";
compareParsed(s);
}
@Test
public void testParseCenter() {
String s = "10.5,47.5,1.0";
compareParsedCenter(s, new Area(nw, se));
}
@Test
public void testParseCenter2() {
String s = "11.5,47.5,1.0,2.0";
compareParsedCenter(s, new Area(46.5, 11, 48.5, 12));
}
protected void compareParsed(String input) {
try {
Area expResult = new Area(nw, se);
Area result = Area.parse(input);
assertEquals(expResult, result);
} catch (ParseException ex) {
fail("Error while parsing: " + ex);
}
}
protected void compareParsedCenter(String input, Area expResult) {
try {
Area result = Area.parseCenter(input);
assertEquals(expResult, result);
} catch (ParseException ex) {
fail("Error while parsing: " + ex);
}
}
}
| 28.779141 | 103 | 0.625027 |
7010b03c1c21dc76f4c53a013c1ed58768c3f2e6 | 3,856 | /*
* Copyright 2003-2019 JetBrains s.r.o.
*
* 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 jetbrains.mps.core.aspects.constraints.rules.kinds;
import jetbrains.mps.core.context.Context;
import jetbrains.mps.core.context.ContextGenre;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.annotations.Immutable;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import org.jetbrains.mps.openapi.model.SNode;
@Immutable
public final class ContainmentContext implements Context {
@NotNull private final SAbstractConcept myChildConcept;
// might be root
@Nullable private final SNode myChildNode;
@Nullable private final SNode myParentNode;
@NotNull private final SAbstractConcept myParentConcept;
@Nullable/*TODO @NotNull*/ private final SContainmentLink myLink;
private ContainmentContext(@NotNull SNode childNode) {
myChildNode = childNode;
myParentNode = childNode.getParent();
myParentConcept = myParentNode.getConcept();
myChildConcept = childNode.getConcept();
myLink = childNode.getContainmentLink();
}
private ContainmentContext(@NotNull SAbstractConcept childConcept,
@Nullable SNode childNode,
@NotNull SAbstractConcept parentConcept,
@Nullable SNode parentNode,
@Nullable SContainmentLink link) {
myChildConcept = childConcept;
myChildNode = childNode;
myParentConcept = parentConcept;
myParentNode = parentNode;
myLink = link;
}
@Nullable
public SNode getChildNode() {
return myChildNode;
}
@NotNull
public SNode getParentNode() {
return myParentNode;
}
@Nullable
public SContainmentLink getLink() {
return myLink;
}
public SAbstractConcept getChildConcept() {
return myChildConcept;
}
@NotNull
@Override
public ContextGenre getCategory() {
throw new UnsupportedOperationException("");
}
@NotNull
public SAbstractConcept getParentConcept() {
return myParentConcept;
}
public static final class Builder {
private SNode childNode;
private SAbstractConcept childConcept;
private SContainmentLink link;
private SNode parentNode;
private SAbstractConcept parentConcept;
public Builder childNode(@Nullable SNode childNode) {
this.childNode = childNode;
if (childNode != null) {
childConcept = childNode.getConcept();
}
return this;
}
public Builder parentNode(@Nullable SNode parentNode) {
this.parentNode = parentNode;
if (parentNode != null) {
parentConcept = parentNode.getConcept();
}
return this;
}
public Builder childConcept(@NotNull SAbstractConcept childConcept) {
this.childConcept = childConcept;
return this;
}
public Builder link(/*@NotNull*/ SContainmentLink link) {
this.link = link;
return this;
}
@NotNull
public ContainmentContext buildFromChildNode(@NotNull SNode childNode) {
return new ContainmentContext(childNode);
}
@NotNull
public ContainmentContext build() {
return new ContainmentContext(childConcept, childNode, parentConcept, parentNode, link);
}
}
}
| 29.661538 | 94 | 0.713434 |
89f889525f616d2e2b15c6f40c22f9a7e7403f82 | 4,647 | package no.cantara.docsite.client;
import no.cantara.docsite.commands.BaseHystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import static no.cantara.docsite.util.CommonUtil.captureStackTrace;
public class HttpRequests {
private static final Logger LOG = LoggerFactory.getLogger(HttpRequests.class);
static final HttpClient HTTP_CLIENT;
static final HttpClient HTTP_CLIENT_SHIELDS;
static {
/*
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
*/
HTTP_CLIENT = HttpClient.newBuilder().build();
// ForceHostnameVerificationSSLContext ctx = new ForceHostnameVerificationSSLContext("sni89405.cloudflaressl.com", 443);
// HTTP_CLIENT_SHIELDS = HttpClient.newBuilder().sslContext(ctx).sslParameters(ctx.getParametersForSNI()).followRedirects(HttpClient.Redirect.ALWAYS).build();
HTTP_CLIENT_SHIELDS = HttpClient.newBuilder().build();
}
public static HttpResponse<String> get(String uri, String... headers) {
return get(uri, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8), headers);
}
public static <R> HttpResponse<R> get(String uri, HttpResponse.BodyHandler<R> bodyHandler, String... headers) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(uri));
if (headers != null && headers.length > 0) builder.headers(headers);
HttpRequest request = builder.GET().build();
return HTTP_CLIENT.send(request, bodyHandler);
} catch (Throwable e) {
if (e instanceof InterruptedException) {
return BaseHystrixCommand.getNullResponse(uri);
}
LOG.error("HttpRequest Error: {} => {}", uri, captureStackTrace(e));
throw new RuntimeException(e);
}
}
public static <R> HttpResponse<R> getShieldsIO(String uri, HttpResponse.BodyHandler<R> bodyHandler, String... headers) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(uri));
if (headers != null && headers.length > 0) builder.headers(headers);
HttpRequest request = builder.GET().build();
return HTTP_CLIENT_SHIELDS.send(request, bodyHandler);
} catch (Throwable e) {
if (e instanceof InterruptedException) {
return BaseHystrixCommand.getNullResponse(uri);
}
LOG.error("HttpRequest Error: {} => {}", uri, captureStackTrace(e));
throw new RuntimeException(e);
}
}
public static HttpResponse<String> post(String uri, HttpRequest.BodyPublisher bodyPublisher, String... headers) {
return post(uri, bodyPublisher, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8), headers);
}
public static <R> HttpResponse<R> post(String uri, HttpRequest.BodyPublisher bodyPublisher, HttpResponse.BodyHandler<R> bodyHandler, String... headers) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(uri));
if (headers != null && headers.length > 0) builder.headers(headers);
HttpRequest request = builder.POST(bodyPublisher).build();
return HTTP_CLIENT.send(request, bodyHandler);
} catch (Exception e) {
if (e instanceof InterruptedException) {
return BaseHystrixCommand.getNullResponse(uri);
}
LOG.error("HttpRequest Error: {} => {}", uri, captureStackTrace(e));
throw new RuntimeException(e);
}
}
}
| 42.633028 | 165 | 0.638261 |
47590fc5e2af58dded4646ae1a41fc0c162e247a | 879 | package com.xmomen.module.account.service;
import com.xmomen.module.user.entity.SysPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import com.xmomen.framework.mybatis.dao.MybatisDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>User: Zhang Kaitao
* <p>Date: 14-1-28
* <p>Version: 1.0
*/
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private MybatisDao mybatisDao;
@Override
@Transactional
public SysPermissions createPermission(SysPermissions permission) {
permission = mybatisDao.saveByModel(permission);
return permission;
}
@Override
@Transactional
public void deletePermission(Long permissionId) {
mybatisDao.deleteByPrimaryKey(SysPermissions.class, permissionId);
}
}
| 25.852941 | 71 | 0.770193 |
a0d5ec7b5ab6d584b4fe9be8c4c615980c8f5f6f | 812 | package daily;
/**
* @author ber
* @version 1.0
* @date 21/8/28 15:26
*/
public class T278 {
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1, right = n, mid;
while (left < right) {
// 防止计算时溢出
mid = left + (right - left) / 2;
if (!isBadVersion(mid)) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
// 题目要求
private class VersionControl {
boolean isBadVersion(int version) {
return false;
}
}
}
| 22.555556 | 74 | 0.472906 |
38d1c835a92574259df6b4e6d58196fd8e63d2c3 | 1,655 | /**
* Copyright (c) 2016, www.jd.com. All rights reserved.
*/
package freamwork.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static freamwork.simple.common.UniqNumUtil.getUniqNum;
/**
* <b>类描述</b>: <br>
* <b>创建人</b>: <a href="mailto:[email protected]">百墨</a> <br>
* <b>创建时间</b>: 2016/4/15 - 10:05 <br>
*
* @version 1.0.0 <br>
*/
public class EventPool {
private static List<Event> eventPool;
private static int size;
public static void init(int size) {
EventPool.size = size;
eventPool = new ArrayList<Event>(size);
for (int a = 0; a < size; a++) {
Event event = new Event();
event.setE1(getUniqNum(10));
event.setE2(getUniqNum(10));
event.setE3(getUniqNum(10));
event.setE4(getUniqNum(10));
event.setE5(getUniqNum(10));
event.setE6(getUniqNum(10));
event.setE7(getUniqNum(10));
event.setE8(getUniqNum(10));
SubEvent subEvent = new SubEvent();
subEvent.setF1(getUniqNum(11));
subEvent.setF2(getUniqNum(11));
subEvent.setF4(getUniqNum(11));
subEvent.setF3(getUniqNum(11));
subEvent.setF5(getUniqNum(11));
subEvent.setF6(getUniqNum(11));
subEvent.setF7(getUniqNum(11));
subEvent.setF8(getUniqNum(11));
subEvent.setF9(getUniqNum(11));
event.setSubEvent(subEvent);
eventPool.add(event);
}
}
public static Event get() {
return eventPool.get(new Random().nextInt(size));
}
}
| 28.050847 | 65 | 0.575831 |
6729f07a4432937fd269cf29406519d1baea7dec | 618 | package wasmruntime.Enums;
import java.util.HashMap;
import java.util.Map;
public enum WasmType {
I32(0),
I64(1),
F32(2),
F64(3),
V128(4),
Funcref(5),
Externref(6);
private final int type;
WasmType(int type) {
this.type = type;
}
public static Map<Byte, WasmType> idMap = new HashMap<Byte, WasmType>();
static {
idMap.put((byte) 0, I32);
idMap.put((byte) 1, I64);
idMap.put((byte) 2, F32);
idMap.put((byte) 3, F64);
idMap.put((byte) 4, V128);
idMap.put((byte) 5, Funcref);
idMap.put((byte) 6, Externref);
}
public int getNum() {
return type;
}
} | 17.166667 | 74 | 0.601942 |
e0f9d2cde0bc3c899e5462d612eae1e1eb7d53a6 | 527 | package webapp.demo1_handler;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
/**
* 简单的http处理
* */
@Mapping("/demo1/run0/")
@Controller
public class Run0Handler implements Handler {
@Override
public void handle(Context cxt) throws Exception {
if(cxt.param("str") == null) {
cxt.output("是null");
}else{
cxt.output("不是null(ok)");
}
}
}
| 22.913043 | 54 | 0.660342 |
f291fe8e7070f5c2d290505cf1286ea9f5fba49d | 4,590 | /*
* Copyright 2017 David Karnok
*
* 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 hu.akarnokd.asyncenum;
import org.junit.Test;
import java.io.IOException;
public class AsyncPublishTest {
@Test
public void passthrough() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(v -> v),
1, 2, 3, 4, 5
);
}
@Test
public void passthroughError() {
TestHelper.assertFailure(
AsyncEnumerable.error(new IOException())
.publish(v -> v),
IOException.class
);
}
@Test
public void doubleSum() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(v -> v.sumInt(u -> u).mergeWith(v.sumInt(u -> u))),
15, 15
);
}
@Test
public void simpleTransform() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(v -> v.map(u -> u * 2)),
2, 4, 6, 8, 10
);
}
@Test
public void simpleTransformTake() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(v -> v.map(u -> u * 2))
.take(3),
2, 4, 6
);
}
@Test
public void innerTake() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(an -> an.take(3)),
1, 2, 3
);
}
@Test
public void spiltCombine() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(an -> an.take(3).mergeWith(an.takeLast(2))),
1, 2, 3, 4, 5
);
}
@Test
public void spiltCombineEvenOdd() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(an -> an.filter(v -> v % 2 == 0).mergeWith(an.filter(v -> v % 2 != 0))),
1, 2, 3, 4, 5
);
}
@Test
public void spiltCombineConcat() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(an ->
an.take(3)
.concatWith(an.takeLast(2))),
1, 2, 3, 4, 5
);
}
@Test
public void lateInner() {
TestHelper.assertResult(
AsyncEnumerable.range(1, 5)
.publish(an -> an.concatWith(an))
, 1, 2, 3, 4, 5
);
}
@Test
public void cancelRace() {
TestHelper.cancelRace(an -> an.publish(f -> f));
}
@Test
public void cancelRace2() {
TestHelper.cancelRace(an -> an.publish(f -> f.map(v -> v)));
}
@Test
public void addRace() {
TestHelper.assertResult(
AsyncEnumerable.empty()
.publish(an -> {
Runnable r = an.enumerator()::cancel;
TestHelper.withExecutor(executor -> {
for (int i = 0; i < 10000; i++) {
TestHelper.race(r, r, executor);
}
});
return an;
})
);
}
@Test
public void addRace2() {
TestHelper.assertResult(
AsyncEnumerable.empty()
.publish(an -> {
Runnable r = () -> {
AsyncEnumerator<Object> en = an.enumerator();
en.cancel();
en.cancel();
};
TestHelper.withExecutor(executor -> {
for (int i = 0; i < 10000; i++) {
TestHelper.race(r, r, executor);
}
});
return an;
})
);
}
}
| 27.48503 | 105 | 0.450763 |
60d00872b39101750023ba216721b283fe1af97a | 11,172 | package upAnalysis.summary;
import java.util.HashMap;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.dom.ASTNode;
import upAnalysis.summary.ops.Predicate;
import upAnalysis.summary.ops.Source;
import upAnalysis.summary.ops.TypeConstraintPredicate;
import upAnalysis.summary.summaryBuilder.rs.ResolvedSource;
import upAnalysis.summary.summaryBuilder.rs.ValueRS;
import upAnalysis.summary.summaryBuilder.values.ExactlyType;
import upAnalysis.summary.summaryBuilder.values.Literal;
import upAnalysis.summary.summaryBuilder.values.Value;
import edu.cmu.cs.crystal.bridge.LatticeElement;
import edu.cmu.cs.crystal.tac.model.Variable;
/* UPLatticeElements are immutable
They also are kept around in summaries, so LE's CAN NOT refer to any AST or CFG information
as this would result in keeping ASTs in memory.
UPLatticeElements provide a crystal lattice element wrapper to our underlying representation of facts about
variables. UPLatticeElement may be either
TOP
BOTTOM
Source
Value
*/
public class UPLatticeElement implements LatticeElement<UPLatticeElement>
{
public LE_TYPE leType;
private Value value; // Depending on the type of the le, either
private Source source; // if variable comes interprocedurally, where it comes from
private static UPLatticeElement TOP = new UPLatticeElement(LE_TYPE.TOP);
private static UPLatticeElement BOTTOM = new UPLatticeElement(LE_TYPE.BOTTOM);
// unlike top and bottom, there may exist true and false literal LEs that are not these
// instances. So all comparisons should always check equality.
private static UPLatticeElement TRUE = UPLatticeElement.Literal(true);
private static UPLatticeElement FALSE = UPLatticeElement.Literal(false);
private static UPLatticeElement NULL = UPLatticeElement.Literal(null);
// CONSTRUCTORS
private UPLatticeElement(LE_TYPE type)
{
leType = type;
}
public static UPLatticeElement Top()
{
return TOP;
}
public static UPLatticeElement Bottom()
{
return BOTTOM;
}
public static UPLatticeElement Source(Source source)
{
UPLatticeElement le = new UPLatticeElement(LE_TYPE.SOURCE);
le.source = source;
return le;
}
public static UPLatticeElement Literal(Object literal)
{
UPLatticeElement le = new UPLatticeElement(LE_TYPE.VALUE);
le.value = new Literal(literal);
return le;
}
// Creates two new LEs that have the source op tested as true and tested as false.
// Params:
// op - the op being tested
// node - the ASTNode where the test occurs
public static void BooleanFork(Source op, Variable target, ASTNode node, Path path1, Path path2)
{
UPLatticeElement trueLE = new UPLatticeElement(LE_TYPE.SOURCE);
UPLatticeElement falseLE = new UPLatticeElement(LE_TYPE.SOURCE);
Predicate truePred = new Predicate(target, op, true);
Predicate falsePred = new Predicate(target, op, false);
truePred.setNegatedPredicate(falsePred);
falsePred.setNegatedPredicate(truePred);
trueLE.source = op.addConstraint(truePred);
falseLE.source = op.addConstraint(falsePred);
path1.put(target, trueLE);
path1.addConstraint(truePred);
path2.put(target, falseLE);
path2.addConstraint(falsePred);
}
public static void InstanceofFork(Source op, Variable target, Variable operand,
IType typeConstraint, ASTNode node, Path path1, Path path2)
{
UPLatticeElement trueLE = new UPLatticeElement(LE_TYPE.SOURCE);
UPLatticeElement falseLE = new UPLatticeElement(LE_TYPE.SOURCE);
TypeConstraintPredicate truePred = new TypeConstraintPredicate(operand, op, typeConstraint, true);
TypeConstraintPredicate falsePred = new TypeConstraintPredicate(operand, op, typeConstraint, false);
truePred.setNegatedPredicate(falsePred);
falsePred.setNegatedPredicate(truePred);
trueLE.source = op.addConstraint(truePred);
falseLE.source = op.addConstraint(falsePred);
path1.put(operand, trueLE);
path1.put(target, UPLatticeElement.TRUE);
path1.addConstraint(truePred);
path2.put(operand, falseLE);
path2.put(target, UPLatticeElement.FALSE);
path2.addConstraint(falsePred);
}
public static UPLatticeElement False()
{
return FALSE;
}
public static UPLatticeElement True()
{
return TRUE;
}
public static UPLatticeElement Null()
{
return NULL;
}
// oldLE must be a SOURCE or TYPE_CONSTRAINT
// TODO: what about an exactly type here?
public static UPLatticeElement AddTypeConstraint(UPLatticeElement oldLE, IType constraint)
{
// Adding a type constraint to a value does not reveal information - we already know the exact type
if (oldLE.leType == LE_TYPE.VALUE)
return oldLE;
assert constraint != null : "Can't have a null type constraint!";
assert oldLE.source != null : "Old le must have a source!";
if (oldLE.leType != LE_TYPE.SOURCE)
throw new IllegalArgumentException("Must pass a source or type constraint LE");
UPLatticeElement newElement = new UPLatticeElement(LE_TYPE.SOURCE);
newElement.source = oldLE.source.addConstraint(new TypeConstraintPredicate(oldLE.source.getVariable(),
oldLE.source, constraint, true));
return newElement;
}
public static UPLatticeElement ExactlyType(IType type)
{
UPLatticeElement newElement = new UPLatticeElement(LE_TYPE.VALUE);
newElement.value = new ExactlyType(type);
return newElement;
}
public Source getSource()
{
assert source != null : "Should only ask for source on source le!";
return source;
}
public Value getValue()
{
assert value != null : "Should only ask for value on value le!";
return value;
}
public IType getType()
{
if (leType != LE_TYPE.VALUE && value instanceof ExactlyType)
throw new RuntimeException("Illegal to ask for a type on a LE that is not an EXACTLY_TYPE");
return ((ExactlyType) value).getType();
}
// STATE TESTS
// True if this LE is a literal or could be a literal interprocedurally, which is
// true iff this is LE is a SOURCE or LITERAL
public boolean couldBeLiteral()
{
return leType == LE_TYPE.SOURCE || leType == LE_TYPE.VALUE;
}
// Only true if we know this is false. This happens either through being a literal or with a boolean constraint.
public boolean isTrueLiteral()
{
return (leType == LE_TYPE.VALUE && value instanceof Literal && ((Literal) value).isTrue()) ||
(leType == LE_TYPE.SOURCE && source.isTrue());
}
// Only true if this is a literal which is true. False does not mean this is a false literal
public boolean isFalseLiteral()
{
return leType == LE_TYPE.VALUE && value instanceof Literal && ((Literal) value).isFalse() ||
(leType == LE_TYPE.SOURCE && source.isFalse());
}
// True for sources, type constraints (which is a source with type constraints), and forked literals
public boolean isFromSource()
{
return leType == LE_TYPE.SOURCE;
}
public boolean isExactlyType()
{
return leType == LE_TYPE.VALUE && value instanceof ExactlyType;
}
public boolean equals(Object other)
{
if (!(other instanceof UPLatticeElement))
return false;
UPLatticeElement otherLE = (UPLatticeElement) other;
return this.leType.equals(otherLE.leType) &&
maybeNullEquals(this.value, otherLE.value) &&
maybeNullEquals(this.source, otherLE.source);
}
public int hashCode()
{
return leType.hashCode() +
(value == null ? 0 : value.hashCode()) +
(source == null ? 0 : source.hashCode());
}
private boolean maybeNullEquals(Object a, Object b)
{
return (a == null && b == null) || (a != null && a.equals(b));
}
public String toString()
{
String output;
if (leType == LE_TYPE.BOTTOM)
output = "<BOT>";
else if (leType == LE_TYPE.TOP)
output = "<TOP>";
else if (leType == LE_TYPE.VALUE)
output = "<" + value.toString() + ">";
else if (leType == LE_TYPE.SOURCE)
output = "<" + source.toString() + ">";
else
throw new UnsupportedOperationException();
return output;
}
// LATTICE OPERATIONS
// TODO: we could be much more aggressive in not throwing away information on joins
// where we still have some typing information in common. Just not clear this is worth implementing.
public UPLatticeElement join(UPLatticeElement other, ASTNode node)
{
if (this == BOTTOM)
{
return other;
}
else if (other == BOTTOM)
{
return this;
}
else if (this == TOP || other == TOP)
{
return TOP;
}
else if (this.leType == LE_TYPE.VALUE && other.leType == LE_TYPE.VALUE)
{
if (this.equals(other))
return this;
else // if (literal.getClass() == other.literal.getClass()) or anything else is true
// We should really return an EXACTLY_TYPE here, but I don't know how to get an IType from
// a getClass, we just return top. Doing this accurately would only help
// for object types that can be literals.
return TOP;
}
else if (this.leType == LE_TYPE.SOURCE && other.leType == LE_TYPE.SOURCE)
{
if (other.source.sourcesEqual(this.source))
return UPLatticeElement.Source(this.source.join(other.source));
else
return TOP;
}
else
{
return TOP;
}
}
// TODO: I'm not entirely sure this is correct. At the moment, we return false
// in situations in which the information in both is incompatible (e.g. we are two different literals)
// I think this is the correct behavior.
public boolean atLeastAsPrecise(UPLatticeElement oldResult, ASTNode node)
{
if (this == BOTTOM || oldResult == TOP)
return true;
// TODO: we need to get lattice ordering in here rather than just equality!
else if (this.leType == LE_TYPE.VALUE && oldResult.leType == LE_TYPE.VALUE)
return this.value.equals(oldResult.value);
else if (this.leType == LE_TYPE.SOURCE && oldResult.leType == LE_TYPE.SOURCE)
return this.source.equals(oldResult.source);
else
return false;
}
// Since we are immutable, no need to copy.
public UPLatticeElement copy()
{
return this;
}
// Resolve the lattice element to a value. This resolve is specifically called for sources nested in other sources
// (e.g., paramaters, field write operands). If the
public ResolvedSource resolve(Path path, HashMap<Source, ResolvedSource> varBindings)
{
if (this.leType == LE_TYPE.SOURCE)
{
// If it has constraints on it, use these constraints to resolve it to a ValueRS. We have more information
// about this source at this program point then when we original bound it by using these constraints.
ResolvedSource rs = source.resolveUsingConstraints();
if (rs != null)
return rs;
else
{
rs = source.resolveUsingBindings(varBindings);
if (rs == null)
throw new RuntimeException("Error - " + this.toString() + " has not been resolved yet.");
else
return rs;
}
}
else if (this.leType == LE_TYPE.VALUE)
return new ValueRS(value);
else
return ValueRS.TOP;
}
} | 31.82906 | 117 | 0.70068 |
64ab83ede0666d37df2f684c7574d43c651902dd | 270 | package blingclock.visualiser;
public interface TimeVisualiser {
public void setCountdownTimeRemaining(int days,long countDownTenths,long hundredths);
public void setTargetSeconds(long targetSeconds);
public void reset();
public void flash(boolean onOrOff);
}
| 22.5 | 88 | 0.807407 |
537571acd0827df0eaeb3f20e88abff81b53f059 | 770 | package com.bbn.serif.sentences;
import com.bbn.bue.common.Finishable;
import com.bbn.serif.sentences.constraints.SentenceSegmentationConstraint;
import com.bbn.serif.theories.DocTheory;
import com.google.common.annotations.Beta;
import java.util.Set;
/**
* Segments a document into sentences. Input documents should not already have sentences or
* an {@link IllegalArgumentException} should be thrown.
*
* The implementation is responsible for verifying that the constraints are obeyed and crashing or
* issuing a warning as appropriate.
*/
@Beta
public interface SentenceFinder extends Finishable {
DocTheory segmentSentences(DocTheory docTheory);
DocTheory segmentSentences(DocTheory docTheory, Set<SentenceSegmentationConstraint> constraints);
}
| 27.5 | 99 | 0.806494 |
1e603a0be2486d87b12ffe71277454bbcfc509b1 | 732 | package com.zjtx.ocmall.framework.database.dialect;
public class Mysql5Dialect extends Dialect {
protected static final String SQL_END_DELIMITER = ";";
public Mysql5Dialect() {
}
public String getLimitString(String sql, boolean hasOffset) {
return Mysql5PageHelper.getLimitString(sql, -1, -1);
}
public String getLimitString(String sql, int offset, int limit) {
return Mysql5PageHelper.getLimitString(sql, offset, limit);
}
@Override
public String getTotalCountString(String sql) {
return Mysql5PageHelper.getCountString(sql);
}
public boolean supportsLimit() {
return true;
}
public String addLog(String sql) {
return sql;
}
} | 23.612903 | 69 | 0.678962 |
ff00f0f93b3f313b82ece5896dd5466848b7f80e | 1,186 | package com.poliveira.apps.example;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import com.poliveira.apps.imagewindow.ImageWindow;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageWindow imageWindow = (ImageWindow) findViewById(R.id.view);
imageWindow.getImageView().setImageResource(R.drawable.a);
imageWindow.setOnCloseListener(new ImageWindow.OnCloseListener() {
@Override
public void onCloseClick(final View imageWindow) {
imageWindow.animate().scaleY(0).scaleX(0).setDuration(500).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
((ViewGroup) imageWindow.getParent()).removeView(imageWindow);
}
}).start();
}
});
}
}
| 34.882353 | 118 | 0.668634 |
168c8c89cc1384f7f63ee973743d624d2bac1479 | 2,066 | /**
* Copyright 2018 Taucoin Core Developers.
*
* 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 io.taucoin.torrent.publishing.core.utils;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import io.taucoin.torrent.publishing.MainApplication;
/**
* 复制剪切版管理
*/
public class CopyManager {
/**
* 复制文本到剪切版
*/
public static void copyText(CharSequence copyText) {
if(StringUtil.isEmpty(copyText)){
copyText = "";
}
Context context = MainApplication.getInstance();
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(null, copyText));
}
/**
* 获取剪切板上的内容
*/
public static String getClipboardContent(Context context) {
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (cm != null) {
ClipData data = cm.getPrimaryClip();
if (data != null && data.getItemCount() > 0) {
ClipData.Item item = data.getItemAt(0);
if (item != null) {
CharSequence sequence = item.coerceToText(context);
if (sequence != null) {
return sequence.toString();
}
}
}
}
return null;
}
/**
* 清除剪切板上的内容
*/
public static void clearClipboardContent() {
copyText( "");
}
}
| 30.382353 | 101 | 0.630203 |
94ab870feadf2e79c30d3d35b0a361ef147eb97f | 409 | package com.google.android.gms.auth;
import android.content.Intent;
public class GooglePlayServicesAvailabilityException extends UserRecoverableAuthException {
private final int zzdzl;
GooglePlayServicesAvailabilityException(int i, String str, Intent intent) {
super(str, intent);
this.zzdzl = i;
}
public int getConnectionStatusCode() {
return this.zzdzl;
}
}
| 24.058824 | 91 | 0.723716 |
6bc0563104a5290d5d76883343d9eae2d9fed22b | 1,272 | package com.github.appreciated.app.layout.component.menu.left.items;
import com.github.appreciated.app.layout.component.menu.RoundImage;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
/**
* A simple container component which may contain an image and two labels concerned component won't be added to its parent
*/
public class LeftHeaderItem extends Composite<VerticalLayout> {
public LeftHeaderItem(String title, String subtitle, String src) {
VerticalLayout content = getContent();
content.setPadding(false);
content.getStyle().set("padding","var(--app-layout-menu-header-padding)");
content.setMargin(false);
setId("menu-header-wrapper");
if (src != null) {
content.add(new RoundImage(src, "56px", "56px"));
}
if (title != null) {
Label titleLabel = new Label(title);
titleLabel.setId("menu-header-title");
content.add(titleLabel);
}
if (subtitle != null) {
Label subtitleLabel = new Label(subtitle);
subtitleLabel.setId("menu-header-subtitle");
content.add(subtitleLabel);
}
}
} | 37.411765 | 122 | 0.66195 |
8ca1c102bc9790d8563fa4c8697a60e449e632f5 | 570 |
package com.ronsoft.books.nio.buffers;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class Test
{
public static void main (String argv[])
{
ByteBuffer bb = ByteBuffer.allocate (100);
bb.mark();
bb.position(5);
bb.reset();
bb.mark().position(5).reset();
char [] myBuffer = new char [100];
CharBuffer cb = CharBuffer.wrap (myBuffer);
cb.position(12).limit(21);
CharBuffer sliced = cb.slice();
System.out.println ("Sliced: offset=" + sliced.arrayOffset()
+ ", capacity=" + sliced.capacity());
}
}
| 18.387097 | 62 | 0.673684 |
fc830a10aec93a9ddf776bc7bc9f4b3028ef75ab | 6,767 | /*
* Copyright 2014 - 2020 Blazebit.
*
* 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.blazebit.persistence.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is a specialized parser for the JSON structure that will be produced by the JSON functions in Blaze-Persistence.
* The parser can only parse valid JSON that conforms to that structure. Other JSON may run into problems.
*
* @author Christian Beikov
* @since 1.5.0
*/
public final class JsonParser {
private JsonParser() {
}
public static List<Object[]> parseStringOnly(CharSequence json, String... fields) {
List<Object[]> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
if (json != null && json.length() != 0) {
Map<String, Integer> fieldMap = new HashMap<>(fields.length);
for (int i = 0; i < fields.length; i++) {
fieldMap.put(fields[i], i);
}
int start = CharSequenceUtils.indexOf(json, '[') + 1;
int end = CharSequenceUtils.lastIndexOf(json, ']');
for (int i = start; i < end; i++) {
Object[] object = new Object[fields.length];
boolean quoteMode = false;
int fieldIndex = -1;
boolean escapes = false;
i = CharSequenceUtils.indexOf(json, '{', i) + 1;
for (; i < end; i++) {
char c = json.charAt(i);
if (!quoteMode) {
if (c == '"') {
quoteMode = true;
} else if (c == '}') {
break;
} else if (c != ':' && c != ',' && !Character.isWhitespace(c)) {
// non-string value
switch (c) {
case 'n':
object[fieldIndex] = null;
i += 3;
fieldIndex = -1;
escapes = false;
break;
case '[':
// Nested object handling
int nestedEnd = findEnd(json, i);
object[fieldIndex] = new SubSequence(json, i, nestedEnd);
fieldIndex = -1;
i = nestedEnd - 1;
break;
default:
throw new IllegalArgumentException("Non-String value unsupported! Found at: " + i);
}
}
} else {
if (c == '\\') {
escapes = true;
c = json.charAt(++i);
switch (c) {
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'r':
c = '\r';
break;
case 'n':
c = '\n';
break;
case 't':
c = '\t';
break;
case 'u':
c = (char) Integer.parseInt(json.subSequence(i + 1, i + 5).toString(), 16);
i += 4;
break;
case '"':
case '\\':
case '/':
break;
default:
throw new IllegalStateException("Unexpected escape sequence at position: " + i);
}
sb.append(c);
} else if (c == '"') {
if (fieldIndex == -1) {
fieldIndex = fieldMap.get(sb.toString());
} else {
if (escapes) {
object[fieldIndex] = sb.toString();
} else {
object[fieldIndex] = new SubSequence(json, i - sb.length(), i);
}
fieldIndex = -1;
escapes = false;
}
sb.setLength(0);
quoteMode = false;
} else {
sb.append(c);
}
}
}
list.add(object);
}
}
return list;
}
private static int findEnd(CharSequence json, int i) {
int arrayLevel = 1;
int end = json.length();
boolean quoteMode = false;
i++;
for (;i < end; i++) {
final char c = json.charAt(i);
if (!quoteMode) {
switch (c) {
case '"':
quoteMode = true;
break;
case '[':
arrayLevel++;
break;
case ']':
arrayLevel--;
if (arrayLevel == 0) {
return i + 1;
}
break;
default:
break;
}
} else if (c == '\\') {
i++;
} else if (c == '"') {
quoteMode = false;
}
}
return i;
}
}
| 39.573099 | 120 | 0.348308 |
f4c39c8be161ff019669519a759b47a2d3aa2be5 | 257 | package de.osthus.ambeth;
import de.osthus.ambeth.bundle.Core;
public class TexTodosMain
{
public static void main(String[] args)
{
Ambeth.createEmptyBundle(Core.class).withApplicationModules(TexTodosModule.class).withArgs(args).startAndClose();
}
}
| 21.416667 | 115 | 0.785992 |
b0134b625f5096c4d49229fd5a32e6b0b4361ae9 | 169 | package dev.demo.landmarks.web.dto;
import lombok.Data;
import java.util.UUID;
@Data
public class CountryResponse {
private UUID id;
private String name;
}
| 12.071429 | 35 | 0.727811 |
ba04a6a063a9a175b7097374088348f1ce828314 | 1,398 | package cn.gdeiassistant.Pojo.DelayTask;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class DelayTask implements Delayed {
//延时任务元素基类,其子类类型决定延时任务内容
private final DelayTaskElement delayTaskElement;
//单位为毫秒,过期时间为用户输入的延时时间加上现在时间
private final long expire;
public DelayTask(DelayTaskElement delayTaskElement, long expire, TimeUnit unit) {
super();
this.delayTaskElement = delayTaskElement;
this.expire = unit.toNanos(expire) + System.currentTimeMillis();
}
public DelayTaskElement getDelayTaskElement() {
return delayTaskElement;
}
public long getExpire() {
return expire;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(this.expire - System.currentTimeMillis(), unit);
}
@Override
public int compareTo(Delayed o) {
long delta = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
return (int) delta;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DelayTask delayTask = (DelayTask) o;
return delayTaskElement.getId().equals(delayTask.delayTaskElement.getId());
}
@Override
public int hashCode() {
return delayTaskElement.hashCode();
}
}
| 25.888889 | 87 | 0.670243 |
4d54cb6131c40a5af7a9be9d41a2fe5ad748ec7a | 1,093 | package cn.zhku.test.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* 数据库创建连接类
* 该工具类不需要被继承
*/
public class JdbcUtils {
private static String url = "jdbc:mysql://localhost:3306/user";
private static String username = "root";
private static String password ="123";
public JdbcUtils(){
try{
Class.forName("com.mysql.jdbc.Driver");
} catch(Exception e){
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,username,password);
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
| 20.240741 | 71 | 0.646844 |
94327ad4194207e8060971007befb5a60ae95b0c | 19,292 | /*
* 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 poe.level.data;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import org.json.JSONArray;
import org.json.JSONObject;
import poe.level.data.Gem.Info;
import poe.level.fx.POELevelFx;
/**
*
* @author Christos
*/
public class GemHolder {
public ArrayList<Gem> gems;
private ArrayList<Gem> witch;
private ArrayList<Gem> shadow;
private ArrayList<Gem> templar;
private ArrayList<Gem> ranger;
private ArrayList<Gem> duelist;
private ArrayList<Gem> marauder;
private ArrayList<Gem> scion;
private ArrayList<Gem> witchO;
private ArrayList<Gem> shadowO;
private ArrayList<Gem> templarO;
private ArrayList<Gem> rangerO;
private ArrayList<Gem> duelistO;
private ArrayList<Gem> marauderO;
private ArrayList<Gem> scionO;
private ArrayList<Gem> dropOnly;
private static GemHolder mInstance;
private Gem dummie;
public String className;
private HashMap<String,ArrayList<HashMap<Zone,ArrayList<Gem>>>> the_ultimate_map;
private ArrayList<HashMap<Zone,ArrayList<Gem>>> zone_gems;
private HashSet<Gem> gem_pool;
public static synchronized GemHolder getInstance() {
if (mInstance == null ) {
mInstance = new GemHolder();
}
return mInstance;
}
public GemHolder(){
gems = new ArrayList<>();
witch = new ArrayList<>();
shadow = new ArrayList<>();
templar = new ArrayList<>();
ranger = new ArrayList<>();
duelist = new ArrayList<>();
marauder = new ArrayList<>();
scion = new ArrayList<>();
witchO = new ArrayList<>();
shadowO = new ArrayList<>();
templarO = new ArrayList<>();
rangerO = new ArrayList<>();
duelistO = new ArrayList<>();
marauderO = new ArrayList<>();
scionO = new ArrayList<>();
dropOnly = new ArrayList<>();
dummie = new Gem("<empty group>");
the_ultimate_map = new HashMap<>();
the_ultimate_map.put("witch", null);
the_ultimate_map.put("shadow", null);
the_ultimate_map.put("templar", null);
the_ultimate_map.put("ranger", null);
the_ultimate_map.put("duelist", null);
the_ultimate_map.put("marauder", null);
the_ultimate_map.put("scion", null);
}
private void placeGemInClass(Gem a, String ch){
//ch = classname
//a = gem object
if(ch.equals("Witch")){
witch.add(a);
}else if(ch.equals("Shadow")){
shadow.add(a);
}else if(ch.equals("Templar")){
templar.add(a);
}else if(ch.equals("Ranger")){
ranger.add(a);
}else if(ch.equals("Duelist")){
duelist.add(a);
}else if(ch.equals("Marauder")){
marauder.add(a);
}else if(ch.equals("Scion")){
scion.add(a);
}
}
public void putGem(Gem a){
gems.add(a);
if(a.isRewarded){}//not configured this feature yet.
if(a.isBought()){
//class to quest name
HashMap<String,ArrayList<String>> mm = new HashMap<>();
for(Info inf : a.buy){
for(String class_ : inf.available_to){
if(mm.containsKey(class_)){
mm.get(class_).add(inf.quest_name);
}else{
ArrayList<String> q = new ArrayList<>();
q.add(inf.quest_name);
mm.put(class_, q);
}
}
}
boolean classCanGetIt;
for(String class_ : mm.keySet()){
classCanGetIt = false;
String[] questline = Zone.questline;
for(int i=0; i<questline.length; i++){
if(mm.get(class_).contains(questline[i])){
for(Info inf : a.buy){
if(questline[i].equals(inf.quest_name)){
Gem duped = a.dupeGem();
duped.act = inf.act;
duped.npc = inf.npc;
duped.town = inf.town;
duped.quest_name = inf.quest_name;
duped.available_to = inf.available_to;
placeGemInClass(duped,class_);
classCanGetIt = true;
break;
}
}
break;
}
}
if(!classCanGetIt){
//System.err.println("CLASS : "+class_+" GEM : "+a.getGemName());
}
}
}else{
//System.err.println(" GEM : "+a.getGemName() + " not asssigned to any class");
dropOnly.add(a);
}
}
public void pool(){
gem_pool = new HashSet<>();
for(Gem g: gems){
gem_pool.add(g);
}
}
public String linkNpcToTown(String npc){
switch (npc) {
case "Lilly Roth":
return "Lioneye's Watch";
case "Nessa":
return "Lioneye's Watch";
case "Yeena":
return "The Forest Encampment";
case "Clarissa":
return "The Sarn Encampment";
case "Petarus and Vanja":
return "Highgate";
case "Siosa":
return "The Library";
}
return "Unknown";
}
public void init_remaining_in_pool(){
/*
for(Gem g : gem_pool){
g.isRewarded = false;
g.reward = null;
g.buy = new ArrayList<>();
System.out.println(g.getGemName());
}*/
JSONArray gems = new JSONArray();
Collections.sort(this.gems, new Comparator<Gem>() {
@Override
public int compare(Gem s1, Gem s2) {
return s1.getGemName().compareToIgnoreCase(s2.getGemName());
}
});
int counter = 0;
for(Gem g : this.gems){
JSONObject bObj = new JSONObject();
bObj.put("id", counter);
bObj.put("name", g.getGemName());
bObj.putOpt("alt_name", g.alt_name);
bObj.put("required_lvl",g.required_lvl);
bObj.put("color", g.getGemColor());
bObj.put("iconPath", g.iconPath);
bObj.put("isReward", g.isRewarded);
bObj.put("isVaal",g.isVaal);
JSONObject rewardObj = new JSONObject();
if(g.isRewarded){
rewardObj.put("quest_name", g.reward.quest_name);
rewardObj.put("npc",g.reward.npc);
rewardObj.put("act",g.reward.act);
rewardObj.put("town",linkNpcToTown(g.reward.npc));
JSONArray av_array = new JSONArray();
for(String s : g.reward.available_to){
av_array.put(s);
}
rewardObj.put("available_to",av_array);
}
bObj.put("reward",rewardObj);
JSONArray buy_array = new JSONArray();
for(Info gInf : g.buy){
JSONObject bInfObj = new JSONObject();
bInfObj.put("quest_name", gInf.quest_name);
bInfObj.put("npc",gInf.npc);
bInfObj.put("act",gInf.act);
bInfObj.put("town",linkNpcToTown(gInf.npc));
JSONArray av_array = new JSONArray();
for(String s : gInf.available_to){
av_array.put(s);
}
bInfObj.put("available_to",av_array);
buy_array.put(bInfObj);
}
bObj.put("buy", buy_array);
bObj.put("isActive", g.isActive);
bObj.put("isSupport", g.isSupport);
JSONArray tags = new JSONArray();
for(String gInf : g.tags){
tags.put(gInf);
}
bObj.put("gemTags", tags);
gems.put(bObj);
counter++;
}
String gem_to_json = gems.toString();
//Gson gson = new Gson();
//String build_to_json = gson.toJson(linker.get(activeBuildID).build);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(POELevelFx.directory+"\\Path of Leveling\\gems_new.json");
bw = new BufferedWriter(fw);
bw.write(gem_to_json);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void updateGemInfo(ArrayList<String> gemlist){
String gemname = gemlist.get(0);
if(gemname.equals("Siphoning Trap")){
System.out.println();
}
if(gemname.endsWith("Support")){
int lastIndexOf = gemname.lastIndexOf("Support");
gemname = gemname.substring(0, lastIndexOf-1);
}
boolean found = false;
for(Gem g : gems){
//if(gemname.contains(g.getGemName()) || g.getGemName().contains(gemname)){
if(gemname.equals(g.getGemName())){
found = true;
if(gemlist.get(1).equals("N/A")){
g.isRewarded = false;
g.reward = null;
}else{
String rew_string = gemlist.get(1);
int rew_act = Integer.parseInt(rew_string.charAt(4)+"");
int indexOf = rew_string.indexOf("with");
String rew_act_str = rew_string.substring(12,indexOf).trim();
rew_string = rew_string.trim();
String classes_str = rew_string.substring(indexOf+5,rew_string.length()-1);
String[] split = classes_str.split(",");
ArrayList<String> av_list = new ArrayList<>();
for(int i = 0; i<split.length;i++){
av_list.add(split[i].trim());
}
g.reward = g.new Info();
g.reward.act = rew_act;
g.reward.npc = "Unknown";
g.reward.quest_name = rew_act_str;
g.reward.town = "Unknwon";
g.reward.available_to = new ArrayList<>(av_list);
}
g.buy = new ArrayList<>();
for(int k = 2; k< gemlist.size(); k++){
String rew_string = gemlist.get(k);
int rew_act = Integer.parseInt(rew_string.charAt(4)+"");
int indexOf = rew_string.indexOf("with");
int indexOf_from = rew_string.lastIndexOf("from");
String rew_act_str = rew_string.substring(12,indexOf_from).trim();
String npc_name = rew_string.substring(indexOf_from+5,indexOf-1).trim();
rew_string = rew_string.trim();
String classes_str = rew_string.substring(indexOf+5,rew_string.length()-1).trim();
String[] split;
if(classes_str.equals("any character")){
split = new String[]{"Marauder", "Witch", "Scion", "Ranger", "Duelist", "Shadow", "Templar"};
}else{
split = classes_str.split(",");
}
ArrayList<String> av_list = new ArrayList<>();
for(int i = 0; i<split.length;i++){
av_list.add(split[i].trim());
}
Info inf = g.new Info();
inf.act = rew_act;
inf.npc = npc_name;
inf.quest_name = rew_act_str;
inf.town = "Unknwon";
inf.available_to = new ArrayList<>(av_list);
g.buy.add(inf);
}
gem_pool.remove(g);
break;
}
}
if(!found){
System.out.println("gem : "+gemname+" not found.");
}
}
public ArrayList<Gem> getGems(){
return gems;
}
public ArrayList<Gem> getGemsClass(){
if(className.toUpperCase().equals("WITCH")){
return witch;
}else if(className.toUpperCase().equals("SHADOW")){
return shadow;
}else if(className.toUpperCase().equals("TEMPLAR")){
return templar;
}else if(className.toUpperCase().equals("RANGER")){
return ranger;
}else if(className.toUpperCase().equals("DUELIST")){
return duelist;
}else if(className.toUpperCase().equals("MARAUDER")){
return marauder;
}else if(className.toUpperCase().equals("SCION")){
return scion;
}
return null;
}
public ArrayList<Gem> getGemOther(){
/*
if(className.toUpperCase().equals("WITCH")){
if(witchO.isEmpty()){
for(Gem g : gems){
if(!witch.contains(g)){
witchO.add(g);
}
}
}
return witchO;
}else if(className.toUpperCase().equals("SHADOW")){
if(shadowO.isEmpty()){
for(Gem g : gems){
if(!shadow.contains(g)){
shadowO.add(g);
}
}
}
return shadowO;
}else if(className.toUpperCase().equals("TEMPLAR")){
if(templarO.isEmpty()){
for(Gem g : gems){
if(!templar.contains(g)){
templarO.add(g);
}
}
}
return templarO;
}else if(className.toUpperCase().equals("RANGER")){
if(witchO.isEmpty()){
for(Gem g : gems){
if(!ranger.contains(g)){
rangerO.add(g);
}
}
}
return rangerO;
}else if(className.toUpperCase().equals("DUELIST")){
if(duelistO.isEmpty()){
for(Gem g : gems){
if(!duelist.contains(g)){
duelistO.add(g);
}
}
}
return duelistO;
}else if(className.toUpperCase().equals("MARAUDER")){
if(marauderO.isEmpty()){
for(Gem g : gems){
if(!marauder.contains(g)){
marauderO.add(g);
}
}
}
return marauderO;
}else if(className.toUpperCase().equals("SCION")){
if(scionO.isEmpty()){
for(Gem g : gems){
if(!scion.contains(g)){
scionO.add(g);
}
}
}
return scionO;
}
return null;
*/
return dropOnly;
}
public ArrayList<HashMap<Zone,ArrayList<Gem>>> getAll(){
if(the_ultimate_map.get(className.toLowerCase()) == null){
the_ultimate_map.put(className.toLowerCase(),getGemClassAndQuest());
}
return the_ultimate_map.get(className.toLowerCase());
}
public ArrayList<HashMap<Zone,ArrayList<Gem>>> getGemClassAndQuest(){
HashSet<String> avoidDuplicate = new HashSet<>();
zone_gems = new ArrayList<>();
ArrayList<Gem> initial = GemHolder.getInstance().getGemsClass();
//ArrayList<Gem> newList = new ArrayList<>();
for(int i=0; i<6; i++){
if(i == 4) continue; //skip act 5
HashMap<Zone,ArrayList<Gem>> map = new HashMap<>();
for(Zone z : ActHandler.getInstance().getActs().get(i).zones){
if(z.questRewardsSkills && !avoidDuplicate.contains(z.quest)){
avoidDuplicate.add(z.quest);
ArrayList<Gem> zoneList = new ArrayList<>();
for(Gem g : initial){
if(g.quest_name == null){
System.out.println(g.getGemName());
}else{
if(g.quest_name.equals(z.quest)){
zoneList.add(g);
}
}
}
map.put(z, zoneList);
}
}
zone_gems.add(map);
}
return zone_gems;
}
public Gem tossDummie(){
return dummie;
}
public Gem createGemFromCache(String gemName, String className){
ArrayList<Gem> gems = null;
if(className.toUpperCase().equals("WITCH")){
gems = new ArrayList<>(witch);
}else if(className.toUpperCase().equals("SHADOW")){
gems = new ArrayList<>(shadow);
}else if(className.toUpperCase().equals("TEMPLAR")){
gems = new ArrayList<>(templar);
}else if(className.toUpperCase().equals("RANGER")){
gems = new ArrayList<>(ranger);
}else if(className.toUpperCase().equals("DUELIST")){
gems = new ArrayList<>(duelist);
}else if(className.toUpperCase().equals("MARAUDER")){
gems = new ArrayList<>(marauder);
}else if(className.toUpperCase().equals("SCION")){
gems = new ArrayList<>(scion);
}
if(gems!=null) {
for (Gem g : gems) {
if (g.isSameGemNameOrOlder(gemName)) {
return g.dupeGem();
}
}
}
//if we reach here no gem was found so it is placed on the drop-only
gems = new ArrayList<>(getGemOther());
for(Gem g : gems) {
if (g.isSameGemNameOrOlder(gemName)) {
return g.dupeGem();
}
}
System.out.println("Failed to createGemFromCache with gemName: " + gemName + " and className: " + className);
return null;
}
public ArrayList<Gem> custom(String query){
String query_lower = query.toLowerCase();
ArrayList<Gem> list = new ArrayList<>();
for(Gem g : getGemsClass()){
String gem_lower = g.getGemName().toLowerCase();
if(gem_lower.contains(query_lower)){
list.add(g);
}
}
return list;
}
}
| 34.26643 | 117 | 0.483361 |
8044d8df4f2f411980c48eefcba214fed3975413 | 2,284 | package org.vaadin.addon.audio.client.webaudio;
import java.util.logging.Logger;
import org.vaadin.addon.audio.shared.util.LogUtils;
import elemental.html.AudioContext;
public class GainNode extends AudioNode {
private static final native elemental.html.AudioNode
createGainNode(AudioContext ctx) /*-{
return ctx.createGain();
}-*/;
protected GainNode(AudioContext ctx) {
super(createGainNode(ctx));
}
public void setGain(double gain) {
setGain(getNativeNode(), gain);
}
private static final native void setGain(elemental.html.AudioNode node, double gain) /*-{
node.gain.value = gain;
}-*/;
public double getGain() {
return getGain(getNativeNode());
}
private static final native double getGain(elemental.html.AudioNode node) /*-{
return node.gain.value;
}-*/;
public void setValueAtTime(double value, double changeDuration) {
// the timeConstant is the amount of time it takes to get to 67% of the final value
double timeConstant = changeDuration * 0.67d;
setValueAtTime(getNativeNode(), value, Context.get().getCurrentTime(), timeConstant);
}
private static final native void setValueAtTime(elemental.html.AudioNode node, double value, double startTime, double timeConstant) /*-{
console.error(node.gain.setValueAtTime(value, startTime, timeConstant));
}-*/;
public void exponentialRampToValueAtTime(double value, double time) {
Logger.getLogger("GainNode").info(LogUtils.prefix("exponentialRampToValueAtTime(" + value + ", " + time + ") now=" + Context.get().getCurrentTime()));
exponentialRampToValueAtTime(getNativeNode(), value, time, Context.get().getCurrentTime());
}
private static final native void exponentialRampToValueAtTime(elemental.html.AudioNode node, double value, double time, double currentTime) /*-{
console.error(node);
console.error(currentTime + " -> " + time);
// according to web audio spec, 0 is an invalid value
if (value <= 0) {
value = 0.01;
}
// need to trigger start time by setting a value
node.gain.setValueAtTime(node.gain.value, currentTime);
// start exp curve
node.gain.exponentialRampToValueAtTime(value, time);
}-*/;
@Override
public String toString() {
String str = "";
str += "GainNode:\n\r";
str += " Gain: " + getGain();
return str;
}
}
| 31.722222 | 152 | 0.724606 |
b488ac500a5ef077fad5215c4a8542051bbd98ee | 1,281 | FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFF
FFFFF
FFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFF
FFFFF
F
| 31.243902 | 94 | 0.968774 |
70a70b39f9caa9f7ad48593baeab5b252fa67808 | 4,577 | /*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2020 the original authors 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
*
* 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 io.janusproject.services.spawn;
import java.util.List;
import java.util.UUID;
import io.janusproject.services.DependentService;
import io.sarl.lang.core.Agent;
import io.sarl.lang.core.AgentContext;
import io.sarl.lang.util.SynchronizedSet;
/**
* This service provides the tools to manage the life-cycle of the agents.
*
* @author $Author: srodriguez$
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public interface SpawnService extends DependentService {
/**
* Spawn agents of the given type, and pass the parameters to its initialization function.
*
* @param nbAgents the number of agents to spawn.
* @param spawningAgent the agent which is spawning.
* @param parent the parent entity that is creating the agents.
* @param agentClazz the type of the agents to spawn.
* @param agentId the identifier of the agent to spawn. If <code>null</code> the identifier is randomly selected.
* If {@code nbAgents} is greater than 1, the agent identifier must be {@code null}.
* @param params the list of the parameters to pass to the agent initialization function.
* @return the identifiers of the agents, never <code>null</code>.
*/
List<UUID> spawn(int nbAgents, UUID spawningAgent, AgentContext parent, UUID agentId, Class<? extends Agent> agentClazz, Object... params);
/**
* Kill the agent with the given identifier.
*
* @param agentID the identifier of the agent to kill.
* @return {@code true} if the agent was killed by this call; {@code false} if the agent
* is unknown or already killed.
*/
default boolean killAgent(UUID agentID) {
return killAgent(agentID, false);
}
/**
* Kill the agent with the given identifier.
*
* @param agentID the identifier of the agent to kill.
* @param forceKilling indicates if the kill of the agent must be forced when it is possible.
* @return {@code true} if the agent was killed by this call; {@code false} if the agent
* is unknown or already killed.
* @since 0.10
*/
boolean killAgent(UUID agentID, boolean forceKilling);
/**
* Add a listener on the changes in the current state of an agent.
*
* @param id identifier of the agent.
* @param agentLifecycleListener the listener on the any change in the life-cycle of the agent.
*/
void addSpawnServiceListener(UUID id, SpawnServiceListener agentLifecycleListener);
/**
* Add a listener on the changes in the current state of an agent.
*
* @param agentLifecycleListener the listener on the any change in the life-cycle of the agent.
*/
void addSpawnServiceListener(SpawnServiceListener agentLifecycleListener);
/**
* Remove a listener on the changes in the current state of an agent.
*
* @param id identifier of the agent.
* @param agentLifecycleListener the listener on the any change in the life-cycle of the agent.
*/
void removeSpawnServiceListener(UUID id, SpawnServiceListener agentLifecycleListener);
/**
* Remove a listener on the changes in the current state of an agent.
*
* @param agentLifecycleListener the listener on the any change in the life-cycle of the agent.
*/
void removeSpawnServiceListener(SpawnServiceListener agentLifecycleListener);
/**
* Add a listener on the changes related to the kernel agent.
*
* @param listener listener on the spawning events in the local kernel.
*/
void addKernelAgentSpawnListener(KernelAgentSpawnListener listener);
/**
* Remove a listener on the changes related to the kernel agent.
*
* @param listener listener on the spawning events in the local kernel.
*/
void removeKernelAgentSpawnListener(KernelAgentSpawnListener listener);
/**
* Replies the registered agents.
*
* @return the registered agents.
* @since 0.10
*/
SynchronizedSet<UUID> getAgents();
}
| 34.413534 | 140 | 0.734105 |
275342a645330b4bb49a94c771252d82253ab269 | 1,752 | package net.minecraft.server;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import java.util.List;
import java.util.function.Function;
public class CommandList {
public static void a(com.mojang.brigadier.CommandDispatcher<CommandListenerWrapper> com_mojang_brigadier_commanddispatcher) {
com_mojang_brigadier_commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) CommandDispatcher.a("list").executes((commandcontext) -> {
return a((CommandListenerWrapper) commandcontext.getSource());
})).then(CommandDispatcher.a("uuids").executes((commandcontext) -> {
return b((CommandListenerWrapper) commandcontext.getSource());
})));
}
private static int a(CommandListenerWrapper commandlistenerwrapper) {
return a(commandlistenerwrapper, EntityHuman::getScoreboardDisplayName);
}
private static int b(CommandListenerWrapper commandlistenerwrapper) {
return a(commandlistenerwrapper, (entityplayer) -> {
return new ChatMessage("commands.list.nameAndId", new Object[]{entityplayer.getDisplayName(), entityplayer.getProfile().getId()});
});
}
private static int a(CommandListenerWrapper commandlistenerwrapper, Function<EntityPlayer, IChatBaseComponent> function) {
PlayerList playerlist = commandlistenerwrapper.getServer().getPlayerList();
List<EntityPlayer> list = playerlist.getPlayers();
IChatMutableComponent ichatmutablecomponent = ChatComponentUtils.b(list, function);
commandlistenerwrapper.sendMessage(new ChatMessage("commands.list.players", new Object[]{list.size(), playerlist.getMaxPlayers(), ichatmutablecomponent}), false);
return list.size();
}
}
| 48.666667 | 170 | 0.746005 |
6de942d69102cdc30075a92fb451e1bf1536192c | 4,432 | package provider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import dbhelper.ContactOpenHelper;
import dbhelper.PacketOpenHelper;
public class PacketProvider extends ContentProvider {
//主机地址常量:当前类的完整路径
public static final String AUTHORITIES =PacketProvider.class.getCanonicalName();//获取类的完整路径
//地址匹配对象
public static UriMatcher mUriMatcher;
//对应packet表的URI常量
public static final Uri URI_PACKET=Uri.parse("content://"+AUTHORITIES+"/packet");
public static final int PACKET=1;
static {
mUriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
//匹配规则
mUriMatcher.addURI(AUTHORITIES,"/packet",PACKET);
//content://provider.PacketProvider/packet
}
private PacketOpenHelper mHelper;
public PacketProvider() {
}
@Override
public boolean onCreate() {
mHelper=new PacketOpenHelper(getContext());
return false;
}
@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* CRUD
* @param uri
* @param values
* @return
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
//数据是存到sqlite-->创建db文件,建表-->sqliteOpenHelper
switch (mUriMatcher.match(uri)){
case PACKET:
SQLiteDatabase db=mHelper.getWritableDatabase();
long _id=db.insert(PacketOpenHelper.TABLE_PACKET,"",values);
if (_id!=-1){
Log.i("PacketProvider", "插入成功");
//拼接最新的Uri
//content://provider.ContactsProvider/contact/_id
uri= ContentUris.withAppendedId(uri, _id);
//通知observer数据改变了
notifyObserver();
}
break;
default:
break;
}
return uri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int del_count=0;
switch (mUriMatcher.match(uri)){
case PACKET:
SQLiteDatabase db=mHelper.getWritableDatabase();
//返回影响的行数
del_count=db.delete(PacketOpenHelper.TABLE_PACKET, selection, selectionArgs);
if (del_count>0){
Log.i("PacketProvider","删除成功");
//通知observer数据改变了
notifyObserver();
}
break;
default:
break;
}
return del_count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int up_count=0;
switch (mUriMatcher.match(uri)){
case PACKET:
SQLiteDatabase db=mHelper.getWritableDatabase();
//返回更新的行数
up_count=db.update(PacketOpenHelper.TABLE_PACKET, values, selection, selectionArgs);
if (up_count>0){
Log.i("PacketProvider", "更改成功");
//通知observer数据改变了
notifyObserver();
}
break;
default:
break;
}
return up_count;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor cursor=null;
switch (mUriMatcher.match(uri)){
case PACKET:
SQLiteDatabase db=mHelper.getWritableDatabase();
//返回更新的行数
cursor=db.query(PacketOpenHelper.TABLE_PACKET, projection, selection, selectionArgs,null,null,sortOrder);
Log.i("PacketProvider","查询成功");
break;
default:
break;
}
return cursor;
}
public void notifyObserver(){
//通知observer数据改变了
Log.i("PacketProvider","notifyObserver");
getContext().getContentResolver().notifyChange(PacketProvider.URI_PACKET,null);
}
}
| 29.350993 | 121 | 0.574684 |
56703d3623b565595833ab82255e209127b0fea2 | 1,256 | class Solution {
public void solveSudoku(char[][] board) {
boolean[][] rows=new boolean[9][9];
boolean[][] cols=new boolean[9][9];
boolean[][] myblocks=new boolean[9][9];
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
char c = board[i][j];
if(c == '.') continue;
int v = c - '1'; //convert to index value;
rows[i][v] = cols[j][v] = myblocks[i - i%3 + j/3][v] = true;
}
}
solveRecur(board, 0, rows, cols, myblocks);
}
private boolean solveRecur(char[][] board, int index, boolean[][] rows, boolean[][] cols, boolean[][] myblocks) {
while(index<81 && board[index/9][index%9] != '.') index++;
if(index==81) return true;
int r=index/9, c=index%9;
for(int v=0;v<9;v++){
if(rows[r][v]||cols[c][v]||myblocks[r-r%3+c/3][v]) continue;
rows[r][v]=cols[c][v]=myblocks[r-r%3+c/3][v]=true;
board[r][c]=Integer.toString(v+1).charAt(0);
if(solveRecur(board,index+1,rows,cols,myblocks)) return true;
rows[r][v]=cols[c][v]=myblocks[r-r%3+c/3][v]=false;
board[r][c]='.';
}
return false;
}
} | 36.941176 | 117 | 0.479299 |
b1d609f9aba92970e8c761fea0656434b25b38e8 | 2,269 | package ru.apetrov.SearchFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Andrey on 17.07.2017.
*/
public class Searcher {
/**
* Список всех файлов в заданной директории.
*/
private static List<File> files = new ArrayList<File>();
/**
* входные параметры поиска (<директроия поиска> / <искомая строка>).
*/
private final String[] args;
/**
* директроия поиска.
*/
private final File dir;
/**
* искомая строка.
*/
private final String line;
/**
* Конструктор.
* @param args args.
*/
public Searcher(String[] args) {
this.args = args;
File file = new File(args[0]);
this.dir = file;
this.line = args[1];
files = Collections.synchronizedList(files);
}
/**
* Геттер.
* @return files.
*/
public static List<File> getFiles() {
return files;
}
/**
* Запуск.
*/
public void start() {
this.findOfFiles(this.dir);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.findOfLine();
}
/**
* В каждой вложенной директории создается поток,
* добавляющий файлы в список files.
* @param dir директроия поиска.
*/
private void findOfFiles(File dir) {
new Thread(new ThreadOfDirectory(dir)).start();
for (File currentDir : dir.listFiles()) {
if (currentDir.isDirectory()) {
this.findOfFiles(currentDir);
}
}
}
/**
* Для каждого файла из списка files, создается поток поиска заданной строки в файле.
*/
private void findOfLine() {
for (int i = 0; i < Searcher.files.size(); i++) {
try {
new Thread(new ThreadOfFile(Searcher.files.get(i), this.line)).start();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
/**
* Main.
* @param args args.
*/
public static void main(String[] args) {
new Searcher(args).start();
}
}
| 22.245098 | 89 | 0.543852 |
4cc65889e8958bc9f9a60364c3dac82df79d7fb1 | 981 | package com.mrbonono63.create.foundation.ponder.elements;
import java.util.function.Function;
import com.mrbonono63.create.foundation.ponder.PonderScene;
import com.mrbonono63.create.foundation.utility.outliner.Outline.OutlineParams;
import com.mrbonono63.create.foundation.utility.outliner.Outliner;
public class OutlinerElement extends AnimatedSceneElement {
private Function<Outliner, OutlineParams> outlinerCall;
private int overrideColor;
public OutlinerElement(Function<Outliner, OutlineParams> outlinerCall) {
this.outlinerCall = outlinerCall;
this.overrideColor = -1;
}
@Override
public void tick(PonderScene scene) {
super.tick(scene);
if (fade.getValue() < 1/16f)
return;
if (fade.getValue(0) > fade.getValue(1))
return;
OutlineParams params = outlinerCall.apply(scene.getOutliner());
if (overrideColor != -1)
params.colored(overrideColor);
}
public void setColor(int overrideColor) {
this.overrideColor = overrideColor;
}
}
| 27.25 | 79 | 0.77472 |
d707023aa95b176470f99282434ffe6c99638eb3 | 951 | package ru.job4j.chess.figures;
import ru.job4j.chess.*;
import ru.job4j.chess.exceptions.*;
/**
* Class Figure Каркас шахматной доски [#792]
* @author Aleksey Sidorenko (mailto:[email protected])
* @since 12.01.2018
*/
abstract public class Figure {
final Cell position;
/**
* Конструктор.
*/
public Figure(Cell position) {
this.position = position;
}
/**
* Метод вычисляет путь фигуры во время хода.
* @return Массив ячеек, которые проходит фигура.
* @param source текущая позиция фигуры
* @param dest позиция фигуры после перемещения
* @throws ImpossibleMoveException
*/
public abstract Cell[] way(Cell source, Cell dest) throws ImpossibleMoveException;
/**
* Метод Создает копию фигуры в ячейке.
* @return Копия фигуры.
* @param dest Ячейка, в которой будет находится копия фигуры.
*/
public abstract Figure copy(Cell dest);
}
| 25.026316 | 86 | 0.666667 |
5ecc8b19e7895c6fcd5c2360124afe0494103491 | 1,720 | package com.packt.webstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.function.Function;
public class Cart implements Serializable {
private static final long serialVersionUID = 6554623865768217431L;
private String id;
private List<CartItem> cartItems;
private BigDecimal grandTotal;
public Cart(String id) {
this.id = id;
}
public String getId() {
return id;
}
public BigDecimal getGrandTotal() {
updateGrandTotal();
return grandTotal;
}
public void setGrandTotal(BigDecimal grandTotal) {
this.grandTotal = grandTotal;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
public CartItem getItemByProductId(String productId) {
return cartItems.stream().filter(cartItem -> cartItem.getProduct().getProductId().equals(productId)).findAny()
.orElse(null);
}
public void updateGrandTotal() {
Function<CartItem, BigDecimal> totalMapper = cartItem -> cartItem.getTotalPrice();
BigDecimal grandTotal = cartItems.stream().map(totalMapper).reduce(BigDecimal.ZERO, BigDecimal::add);
this.setGrandTotal(grandTotal);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
Cart other = (Cart) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | 22.051282 | 112 | 0.707558 |
051a08e5ea13e13f091b1b42de77c8b9284edcb0 | 4,157 | /*
* Copyright by Zoltán Cseresnyés, Ruman Gerst
*
* Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge
* https://www.leibniz-hki.de/en/applied-systems-biology.html
* HKI-Center for Systems Biology of Infection
* Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Institute (HKI)
* Adolf-Reichwein-Straße 23, 07745 Jena, Germany
*
* The project code is licensed under BSD 2-Clause.
* See the LICENSE file provided with the code for the full license.
*/
package org.hkijena.jipipe.extensions.parameters.library.jipipe;
import org.hkijena.jipipe.api.JIPipeAuthorMetadata;
import org.hkijena.jipipe.api.parameters.JIPipeParameterAccess;
import org.hkijena.jipipe.ui.JIPipeWorkbench;
import org.hkijena.jipipe.ui.components.DocumentChangeListener;
import org.hkijena.jipipe.ui.components.markdown.MarkdownDocument;
import org.hkijena.jipipe.ui.parameters.JIPipeParameterEditorUI;
import org.hkijena.jipipe.ui.parameters.ParameterPanel;
import org.hkijena.jipipe.utils.UIUtils;
import org.jdesktop.swingx.JXTextField;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
public class JIPipeAuthorMetadataParameterEditorUI extends JIPipeParameterEditorUI {
private final JXTextField firstNameEditor = new JXTextField("First name");
private final JXTextField lastNameEditor = new JXTextField("Last name");
private boolean isReloading = false;
/**
* Creates new instance
*
* @param workbench the workbech
* @param parameterAccess Parameter
*/
public JIPipeAuthorMetadataParameterEditorUI(JIPipeWorkbench workbench, JIPipeParameterAccess parameterAccess) {
super(workbench, parameterAccess);
initialize();
reload();
}
private void initialize() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
firstNameEditor.getDocument().addDocumentListener(new DocumentChangeListener() {
@Override
public void changed(DocumentEvent documentEvent) {
if (!isReloading) {
JIPipeAuthorMetadata parameter = getParameter(JIPipeAuthorMetadata.class);
parameter.setFirstName(firstNameEditor.getText());
setParameter(parameter, false);
}
}
});
add(firstNameEditor);
add(Box.createHorizontalStrut(8));
lastNameEditor.getDocument().addDocumentListener(new DocumentChangeListener() {
@Override
public void changed(DocumentEvent documentEvent) {
if (!isReloading) {
JIPipeAuthorMetadata parameter = getParameter(JIPipeAuthorMetadata.class);
parameter.setLastName(lastNameEditor.getText());
setParameter(parameter, false);
}
}
});
add(lastNameEditor);
add(Box.createHorizontalStrut(8));
JButton editButton = new JButton("Edit", UIUtils.getIconFromResources("actions/stock_edit.png"));
UIUtils.makeFlat(editButton);
editButton.setToolTipText("Shows the full editor");
editButton.addActionListener(e -> {
JIPipeAuthorMetadata parameter = getParameter(JIPipeAuthorMetadata.class);
ParameterPanel.showDialog(getWorkbench(),
parameter,
new MarkdownDocument("# Edit author\n\nUse this editor to update additional author properties."),
"Edit author",
ParameterPanel.WITH_DOCUMENTATION | ParameterPanel.WITH_SEARCH_BAR | ParameterPanel.WITH_SCROLLING);
reload();
});
add(editButton);
}
@Override
public boolean isUILabelEnabled() {
return true;
}
@Override
public void reload() {
JIPipeAuthorMetadata parameter = getParameter(JIPipeAuthorMetadata.class);
try {
isReloading = true;
firstNameEditor.setText(parameter.getFirstName());
lastNameEditor.setText(parameter.getLastName());
} finally {
isReloading = false;
}
}
}
| 37.790909 | 120 | 0.673563 |
a7cde0e52e59dce8c750260486fa783ebcffcbdc | 7,084 | /*
* 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 org.keycloak.quickstart.springboot.config;
import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory;
import org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
import org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter;
import org.keycloak.quickstart.springboot.components.CustomKeycloakAuthenticationProcessingFilter;
import org.keycloak.quickstart.springboot.components.CustomKeycloakLogoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Application security configuration.
*
*/
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
grantedAuthorityMapper.setPrefix("ROLE_");
grantedAuthorityMapper.setConvertToUpperCase(true);
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Autowired
public KeycloakClientRequestFactory keycloakClientRequestFactory;
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public KeycloakRestTemplate keycloakRestTemplate() {
return new KeycloakRestTemplate(keycloakClientRequestFactory);
}
@Bean
public KeycloakConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.csrf()
.requireCsrfProtectionMatcher(this.keycloakCsrfRequestMatcher())
.and()
.sessionManagement()
.sessionAuthenticationStrategy(this.sessionAuthenticationStrategy())
.and()
.addFilterBefore(this.keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(this.keycloakAuthenticationProcessingFilter(), BasicAuthenticationFilter.class)
.addFilterAfter(this.keycloakSecurityContextRequestFilter(), SecurityContextHolderAwareRequestFilter.class)
.addFilterAfter(this.keycloakAuthenticatedActionsRequestFilter(), KeycloakSecurityContextRequestFilter.class)
.exceptionHandling().authenticationEntryPoint(this.authenticationEntryPoint())
.and()
.logout().addLogoutHandler(this.keycloakLogoutHandler())
.logoutUrl("/sso/logout").permitAll()
.logoutSuccessHandler(logoutSuccessHandler())
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/products*").hasRole("USER")
.anyRequest().permitAll();
}
@Bean
public LogoutSuccessHandler logoutSuccessHandler(){
return new LogoutSuccessHandler(){
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.print("{}");
out.flush();
}
};
// return (HttpServletRequest request, HttpServletResponse response, Authentication authentication) ->{
// response.setContentType("application/json");
// PrintWriter out = response.getWriter();
// out.print("{}");
// out.flush();
// };
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
//////////////
protected CustomKeycloakLogoutHandler keycloakLogoutHandler() throws Exception {
return new CustomKeycloakLogoutHandler(adapterDeploymentContext());
}
//@TODO Find out why AbstractAuthenticationProcessingFilter is being called twice.
// This most probably is happening due to its decleration as a Bean in superclass
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
CustomKeycloakAuthenticationProcessingFilter filter = new CustomKeycloakAuthenticationProcessingFilter(authenticationManagerBean());
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
return filter;
}
/////////////
}
| 47.543624 | 167 | 0.763834 |
26eabaa31d213c40ea9ede2556c566d3172fbc9d | 12,139 | package io.choerodon.devops.app.service.impl;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import io.choerodon.core.convertor.ConvertHelper;
import io.choerodon.core.exception.CommonException;
import io.choerodon.devops.api.dto.DevopsEnviromentDTO;
import io.choerodon.devops.api.dto.DevopsEnviromentRepDTO;
import io.choerodon.devops.api.dto.DevopsEnvironmentUpdateDTO;
import io.choerodon.devops.app.service.DevopsEnvironmentService;
import io.choerodon.devops.domain.application.entity.DevopsEnvironmentE;
import io.choerodon.devops.domain.application.factory.DevopsEnvironmentFactory;
import io.choerodon.devops.domain.application.repository.ApplicationInstanceRepository;
import io.choerodon.devops.domain.application.repository.DevopsEnvironmentRepository;
import io.choerodon.devops.domain.application.repository.DevopsServiceRepository;
import io.choerodon.devops.domain.application.repository.IamRepository;
import io.choerodon.devops.infra.common.util.FileUtil;
import io.choerodon.devops.infra.common.util.GenerateUUID;
import io.choerodon.websocket.helper.EnvListener;
import io.choerodon.websocket.helper.EnvSession;
/**
* Created by younger on 2018/4/9.
*/
@Service
public class DevopsEnvironmentServiceImpl implements DevopsEnvironmentService {
@Value("${agent.version}")
private String agentExpectVersion;
@Value("${agent.serviceUrl}")
private String agentServiceUrl;
@Value("${agent.repoUrl}")
private String agentRepoUrl;
;
private IamRepository iamRepository;
private DevopsEnvironmentRepository devopsEnviromentRepository;
private EnvListener envListener;
private DevopsServiceRepository devopsServiceRepository;
private ApplicationInstanceRepository applicationInstanceRepository;
public DevopsEnvironmentServiceImpl(IamRepository iamRepository,
DevopsEnvironmentRepository devopsEnviromentRepository,
EnvListener envListener,
DevopsServiceRepository devopsServiceRepository,
ApplicationInstanceRepository applicationInstanceRepository) {
this.iamRepository = iamRepository;
this.devopsEnviromentRepository = devopsEnviromentRepository;
this.envListener = envListener;
this.devopsServiceRepository = devopsServiceRepository;
this.applicationInstanceRepository = applicationInstanceRepository;
}
@Override
public String create(Long projectId, DevopsEnviromentDTO devopsEnviromentDTO) {
DevopsEnvironmentE devopsEnvironmentE = ConvertHelper.convert(devopsEnviromentDTO, DevopsEnvironmentE.class);
devopsEnvironmentE.initProjectE(projectId);
devopsEnviromentRepository.checkCode(devopsEnvironmentE);
devopsEnviromentRepository.checkName(devopsEnvironmentE);
devopsEnvironmentE.initActive(true);
devopsEnvironmentE.initConnect(false);
devopsEnvironmentE.initToken(GenerateUUID.generateUUID());
devopsEnvironmentE.initProjectE(projectId);
List<DevopsEnvironmentE> devopsEnvironmentES = devopsEnviromentRepository
.queryByprojectAndActive(projectId, true);
devopsEnvironmentE.initSequence(devopsEnvironmentES);
InputStream inputStream = this.getClass().getResourceAsStream("/shell/environment.sh");
Map<String, String> params = new HashMap<>();
params.put("{NAMESPACE}", devopsEnvironmentE.getCode());
params.put("{VERSION}", agentExpectVersion);
params.put("{SERVICEURL}", agentServiceUrl);
params.put("{TOKEN}", devopsEnvironmentE.getToken());
params.put("{REPOURL}", agentRepoUrl);
params.put("{ENVID}", devopsEnviromentRepository.create(devopsEnvironmentE)
.getId().toString());
return FileUtil.replaceReturnString(inputStream, params);
}
@Override
public List<DevopsEnviromentRepDTO> listByProjectIdAndActive(Long projectId, Boolean active) {
Map<String, EnvSession> envs = envListener.connectedEnv();
List<DevopsEnvironmentE> devopsEnvironmentES = devopsEnviromentRepository
.queryByprojectAndActive(projectId, active).parallelStream()
.sorted(Comparator.comparing(DevopsEnvironmentE::getSequence))
.collect(Collectors.toList());
for (DevopsEnvironmentE devopsEnvironmentE : devopsEnvironmentES) {
Integer flag = 0;
devopsEnvironmentE.setUpdate(false);
for (Map.Entry<String, EnvSession> entry : envs.entrySet()) {
EnvSession envSession = entry.getValue();
if (envSession.getEnvId().equals(devopsEnvironmentE.getId())) {
flag = agentExpectVersion.compareTo(envSession.getVersion());
devopsEnvironmentE.initConnect(true);
}
if (flag > 0) {
devopsEnvironmentE.setUpdate(true);
devopsEnvironmentE.initConnect(false);
devopsEnvironmentE.setUpdateMessage("Version is too low, please upgrade!");
}
}
}
return ConvertHelper.convertList(devopsEnvironmentES, DevopsEnviromentRepDTO.class);
}
@Override
public List<DevopsEnviromentRepDTO> listDeployed(Long projectId) {
List<Long> envList = devopsServiceRepository.selectDeployedEnv();
return listByProjectIdAndActive(projectId, true).stream().filter(t ->
envList.contains(t.getId())).collect(Collectors.toList());
}
@Override
public Boolean activeEnvironment(Long projectId, Long environmentId, Boolean active) {
if (!active && applicationInstanceRepository.selectByEnvId(environmentId) > 0) {
throw new CommonException("error.env.stop");
}
DevopsEnvironmentE devopsEnvironmentE = devopsEnviromentRepository.queryById(environmentId);
devopsEnvironmentE.setActive(active);
if (active) {
devopsEnvironmentE.initSequence(devopsEnviromentRepository
.queryByprojectAndActive(projectId, active));
} else {
List<DevopsEnvironmentE> devopsEnvironmentES = devopsEnviromentRepository
.queryByprojectAndActive(projectId, true).parallelStream()
.sorted(Comparator.comparing(DevopsEnvironmentE::getSequence))
.collect(Collectors.toList());
List<Long> environmentIds = devopsEnvironmentES
.stream()
.map(devopsEnvironmentE1
-> devopsEnvironmentE1.getId().longValue())
.collect(Collectors.toList());
environmentIds.remove(environmentId);
Long[] ids = new Long[environmentIds.size()];
sort(environmentIds.toArray(ids));
}
devopsEnviromentRepository.update(devopsEnvironmentE);
return true;
}
@Override
public DevopsEnvironmentUpdateDTO query(Long environmentId) {
return ConvertHelper.convert(devopsEnviromentRepository
.queryById(environmentId), DevopsEnvironmentUpdateDTO.class);
}
@Override
public DevopsEnvironmentUpdateDTO update(DevopsEnvironmentUpdateDTO devopsEnvironmentUpdateDTO, Long projectId) {
DevopsEnvironmentE devopsEnvironmentE = ConvertHelper.convert(
devopsEnvironmentUpdateDTO, DevopsEnvironmentE.class);
devopsEnvironmentE.initProjectE(projectId);
if (checkNameChange(devopsEnvironmentUpdateDTO)) {
devopsEnviromentRepository.checkName(devopsEnvironmentE);
}
return ConvertHelper.convert(devopsEnviromentRepository.update(
devopsEnvironmentE), DevopsEnvironmentUpdateDTO.class);
}
@Override
public List<DevopsEnviromentRepDTO> sort(Long[] environmentIds) {
List<Long> ids = new ArrayList<>();
Collections.addAll(ids, environmentIds);
List<DevopsEnvironmentE> devopsEnvironmentES = ids.stream()
.map(id -> devopsEnviromentRepository.queryById(id))
.collect(Collectors.toList());
Long sequence = 1L;
for (DevopsEnvironmentE devopsEnvironmentE : devopsEnvironmentES) {
devopsEnvironmentE.setSequence(sequence);
devopsEnviromentRepository.update(devopsEnvironmentE);
sequence = sequence + 1;
}
Map<String, EnvSession> envs = envListener.connectedEnv();
for (DevopsEnvironmentE devopsEnvironmentE : devopsEnvironmentES) {
Integer flag = 0;
devopsEnvironmentE.setUpdate(false);
for (Map.Entry<String, EnvSession> entry : envs.entrySet()) {
EnvSession envSession = entry.getValue();
if (envSession.getEnvId().equals(devopsEnvironmentE.getId())) {
flag = agentExpectVersion.compareTo(envSession.getVersion());
devopsEnvironmentE.initConnect(true);
}
if (flag > 0) {
devopsEnvironmentE.setUpdate(true);
devopsEnvironmentE.initConnect(false);
devopsEnvironmentE.setUpdateMessage("Version is too low, please upgrade!");
}
}
}
return ConvertHelper.convertList(devopsEnvironmentES, DevopsEnviromentRepDTO.class);
}
@Override
public String queryShell(Long environmentId, Boolean update) {
if (update == null) {
update = false;
}
DevopsEnvironmentE devopsEnvironmentE = devopsEnviromentRepository.queryById(environmentId);
InputStream inputStream = null;
Map<String, String> params = new HashMap<>();
if (update) {
inputStream = this.getClass().getResourceAsStream("/shell/environment-upgrade.sh");
} else {
inputStream = this.getClass().getResourceAsStream("/shell/environment.sh");
}
params.put("{NAMESPACE}", devopsEnvironmentE.getCode());
params.put("{VERSION}", agentExpectVersion);
params.put("{SERVICEURL}", agentServiceUrl);
params.put("{TOKEN}", devopsEnvironmentE.getToken());
params.put("{REPOURL}", agentRepoUrl);
params.put("{ENVID}", devopsEnvironmentE.getId().toString());
return FileUtil.replaceReturnString(inputStream, params);
}
@Override
public void checkName(Long projectId, String name) {
DevopsEnvironmentE devopsEnvironmentE = DevopsEnvironmentFactory.createDevopsEnvironmentE();
devopsEnvironmentE.initProjectE(projectId);
devopsEnvironmentE.setName(name);
devopsEnviromentRepository.checkName(devopsEnvironmentE);
}
@Override
public void checkCode(Long projectId, String code) {
DevopsEnvironmentE devopsEnvironmentE = DevopsEnvironmentFactory.createDevopsEnvironmentE();
devopsEnvironmentE.initProjectE(projectId);
devopsEnvironmentE.setCode(code);
devopsEnviromentRepository.checkCode(devopsEnvironmentE);
}
/**
* 校验name是否改变
*
* @param devopsEnvironmentUpdateDTO 环境参数
* @return boolean
*/
public Boolean checkNameChange(DevopsEnvironmentUpdateDTO devopsEnvironmentUpdateDTO) {
DevopsEnvironmentE devopsEnvironmentE = devopsEnviromentRepository
.queryById(devopsEnvironmentUpdateDTO.getId());
return devopsEnvironmentE.getName().equals(devopsEnvironmentUpdateDTO.getName()) ? false : true;
}
@Override
public List<DevopsEnviromentRepDTO> listByProjectId(Long projectId) {
List<DevopsEnviromentRepDTO> devopsEnviromentRepDTOList = listByProjectIdAndActive(projectId, true);
return devopsEnviromentRepDTOList.stream().filter(t ->
applicationInstanceRepository.selectByEnvId(t.getId()) > 0)
.collect(Collectors.toList());
}
}
| 46.868726 | 117 | 0.69009 |
90c052a430b878a6bdf8b8656966ca656c582e5f | 1,356 | /*
* Copyright 2019-2021 Daniel Siviter
*
* 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 uk.dansiviter.gcp.microprofile.metrics;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import uk.dansiviter.gcp.Util;
/**
* Override with the {@link javax.enterprise.inject.Specializes} mechanism if you need to override.
*/
public class SchedulerProducer {
@Produces
@ApplicationScoped
public ScheduledExecutorService scheduler() {
return Executors.newSingleThreadScheduledExecutor();
}
public void shutdown(@Disposes ScheduledExecutorService scheduler) {
Util.shutdown(scheduler, 60, SECONDS);
}
}
| 31.534884 | 99 | 0.781711 |
763409eb9945bfa4b13a3a64b0ad4dadca5b50f5 | 2,409 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.codeStyle;
import com.intellij.formatting.fileSet.FileSetDescriptor;
import com.intellij.formatting.fileSet.FileSetDescriptorFactory;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.annotations.OptionTag;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
public class ExcludedFiles {
private final List<FileSetDescriptor> myDescriptors = ContainerUtil.newArrayList();
private final State myState = new State();
public void serializeInto(@NotNull Element element) {
if (myDescriptors.size() > 0) {
XmlSerializer.serializeInto(myState, element);
}
}
public void deserializeFrom(@NotNull Element element) {
XmlSerializer.deserializeInto(myState, element);
}
public void addDescriptor(@NotNull FileSetDescriptor descriptor) {
myDescriptors.add(descriptor);
}
public List<FileSetDescriptor> getDescriptors() {
return myDescriptors;
}
public void setDescriptors(@NotNull List<FileSetDescriptor> descriptors) {
myDescriptors.clear();
myDescriptors.addAll(descriptors);
}
public boolean contains(@NotNull PsiFile file) {
if (file.isPhysical()) {
for (FileSetDescriptor descriptor : myDescriptors) {
if (descriptor.matches(file)) return true;
}
}
return false;
}
public void clear() {
myDescriptors.clear();
}
public boolean equals(@NotNull Object o) {
return o instanceof ExcludedFiles && myDescriptors.equals(((ExcludedFiles)o).myDescriptors);
}
public class State {
@OptionTag("DO_NOT_FORMAT")
public List<FileSetDescriptor.State> getDescriptors() {
return myDescriptors.stream()
.map(descriptor -> descriptor.getState()).collect(Collectors.toList());
}
public void setDescriptors(@NotNull List<FileSetDescriptor.State> states) {
myDescriptors.clear();
for (FileSetDescriptor.State state : states) {
FileSetDescriptor descriptor = FileSetDescriptorFactory.createDescriptor(state);
if (descriptor != null) {
myDescriptors.add(descriptor);
}
}
}
}
}
| 30.493671 | 140 | 0.728933 |
94d5eae3b465f8873bd1b06af9dbf51dbaaae4e9 | 4,615 | package com.hedera.exchange;
/*-
*
* Hedera Exchange Rate Tool
*
* Copyright (C) 2019 - 2020 Hedera Hashgraph, LLC
*
* 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.
*
*
* Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ExchangeRateTestCases {
@Test
public void fromArrayJson() throws IOException {
final String json = "[{\"CurrentRate\":{\"hbarEquiv\":1000000,\"centEquiv\":71400," +
"\"expirationTime\":1567490400000},\"NextRate\":{\"hbarEquiv\":1000000,\"centEquiv\":67800," +
"\"expirationTime\":1567490403600}}]";
final ExchangeRate exchangeRate = ExchangeRate.fromJson(json);
assertEquals(1000000, exchangeRate.getCurrentRate().getHBarEquiv());
assertEquals(71400, exchangeRate.getCurrentRate().getCentEquiv());
assertEquals(1567490400000L, exchangeRate.getCurrentRate().getExpirationTimeInSeconds());
assertEquals(1000000, exchangeRate.getNextRate().getHBarEquiv());
assertEquals(67800, exchangeRate.getNextRate().getCentEquiv());
assertEquals(1567490403600L, exchangeRate.getNextRate().getExpirationTimeInSeconds());
}
@Test
public void fromJson() throws IOException {
final String json = "{\"CurrentRate\":{\"hbarEquiv\":1000000,\"centEquiv\":71400," +
"\"expirationTime\":1567490400000},\"NextRate\":{\"hbarEquiv\":1000000,\"centEquiv\":67800," +
"\"expirationTime\":1567490403600}}";
final ExchangeRate exchangeRate = ExchangeRate.fromJson(json);
assertEquals(1000000, exchangeRate.getCurrentRate().getHBarEquiv());
assertEquals(71400, exchangeRate.getCurrentRate().getCentEquiv());
assertEquals(1567490400000L, exchangeRate.getCurrentRate().getExpirationTimeInSeconds());
assertEquals(1000000, exchangeRate.getNextRate().getHBarEquiv());
assertEquals(67800, exchangeRate.getNextRate().getCentEquiv());
assertEquals(1567490403600L, exchangeRate.getNextRate().getExpirationTimeInSeconds());
}
@ParameterizedTest
@CsvSource({
"1581638400,true",
"1581639400,false",
"1581724800,true"
})
public void isMidnightRate(long expirationTime, boolean isMidnight) {
Rate currRate = new Rate(30000, 120000, expirationTime);
Rate nextRate = new Rate(30000, 120000, expirationTime+3600);
ExchangeRate exchangeRate = new ExchangeRate(currRate, nextRate);
assertEquals(isMidnight, exchangeRate.isMidnightTime());
}
}
| 40.840708 | 98 | 0.759047 |
7c8bbab5b9d93239a1241bd6db139d78d1ca1dda | 3,207 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
package org.apache.openoffice.ooxml.framework.part;
/** Operations around part names.
*/
public class PartName
implements Comparable<PartName>
{
public PartName (final String sPath)
{
if ( ! (sPath.isEmpty() || sPath.startsWith("/")))
{
assert(sPath.isEmpty() || sPath.startsWith("/"));
}
assert(sPath.indexOf('\\') == -1);
msPath = sPath;
}
public PartName (
final String sPath,
final PartName aParentName,
final String sMode)
{
switch(sMode)
{
case "External":
msPath = sPath;
break;
case "Internal":
msPath = Cleanup(aParentName.GetPathname() + "/" + sPath);
break;
default:
throw new RuntimeException();
}
}
public PartName getRelationshipsPartName ()
{
return new PartName(GetPathname() + "/_rels/" + GetBasename() + ".rels");
}
private String GetPathname ()
{
if (msPath.isEmpty())
return "";
else
{
final int nPathnameEnd = msPath.lastIndexOf('/');
assert(nPathnameEnd>=0);
return msPath.substring(0, nPathnameEnd);
}
}
public String GetBasename ()
{
if (msPath.isEmpty())
return "";
else
{
final int nBasenameStart = msPath.lastIndexOf('/');
assert(nBasenameStart>=0);
return msPath.substring(nBasenameStart+1);
}
}
public String GetExtension ()
{
final int nExtensionStart = msPath.lastIndexOf('.');
if (nExtensionStart < 0)
return null;
else
return msPath.substring(nExtensionStart+1);
}
public String GetFullname()
{
return msPath;
}
@Override
public int compareTo (final PartName aOther)
{
return msPath.compareTo(aOther.msPath);
}
private String Cleanup (final String sName)
{
return sName.replaceAll("/[^/]+/\\.\\./", "/");
}
@Override
public String toString ()
{
return msPath;
}
private final String msPath;
}
| 21.098684 | 81 | 0.554412 |
b4b226994973fcd46b211206dfe1761f5ad17db0 | 1,085 | /**
* Copyright 2020 Alibaba Group Holding Limited.
*
* 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.alibaba.maxgraph.compiler.tree;
public final class TreeConstants {
public static final int ID_INDEX = -1;
public static final int LABEL_INDEX = -2;
public static final int KEY_INDEX = -3;
public static final int VALUE_INDEX = -4;
public static final int USER_LABEL_START = -10;
public static final int SYS_LABEL_START = -1000;
public static final int MAGIC_LABEL_ID = -9999;
public static final int MAGIC_PROP_ID = 9999;
}
| 36.166667 | 75 | 0.733641 |
251a6a5c5ac6d0eda7feb71b1e0ef5d6d63fa724 | 4,332 | package com.vaadin.flow.component.charts.model;
/*-
* #%L
* Vaadin Charts for Flow
* %%
* Copyright (C) 2014 - 2019 Vaadin Ltd
* %%
* This program is available under Commercial Vaadin Add-On License 3.0
* (CVALv3).
*
* See the file licensing.txt distributed with this software for more
* information about licensing.
*
* You should have received a copy of the CVALv3 along with this program.
* If not, see <https://vaadin.com/license/cval-3>.
* #L%
*/
import javax.annotation.Generated;
import com.vaadin.flow.component.charts.model.style.Style;
/**
* The axis title, showing next to the axis line.
*/
@Generated(value = "This class is generated and shouldn't be modified", comments = "Incorrect and missing API should be reported to https://github.com/vaadin/vaadin-charts-flow/issues/new")
public class AxisTitle extends AbstractConfigurationObject {
private VerticalAlign align;
private Number margin;
private Number offset;
private Boolean reserveSpace;
private Number rotation;
private Style style;
private String text;
private Number x;
private Number y;
public AxisTitle() {
}
/**
* @see #setAlign(VerticalAlign)
*/
public VerticalAlign getAlign() {
return align;
}
/**
* Alignment of the title relative to the axis values. Possible values are
* "low", "middle" or "high".
* <p>
* Defaults to: middle
*/
public void setAlign(VerticalAlign align) {
this.align = align;
}
/**
* @see #setMargin(Number)
*/
public Number getMargin() {
return margin;
}
/**
* The pixel distance between the axis labels and the title. Positive values
* are outside the axis line, negative are inside.
* <p>
* Defaults to: 40
*/
public void setMargin(Number margin) {
this.margin = margin;
}
/**
* @see #setOffset(Number)
*/
public Number getOffset() {
return offset;
}
/**
* The distance of the axis title from the axis line. By default, this
* distance is computed from the offset width of the labels, the labels'
* distance from the axis and the title's margin. However when the offset
* option is set, it overrides all this.
*/
public void setOffset(Number offset) {
this.offset = offset;
}
/**
* @see #setReserveSpace(Boolean)
*/
public Boolean getReserveSpace() {
return reserveSpace;
}
/**
* Whether to reserve space for the title when laying out the axis.
* <p>
* Defaults to: true
*/
public void setReserveSpace(Boolean reserveSpace) {
this.reserveSpace = reserveSpace;
}
/**
* @see #setRotation(Number)
*/
public Number getRotation() {
return rotation;
}
/**
* The rotation of the text in degrees. 0 is horizontal, 270 is vertical
* reading from bottom to top.
* <p>
* Defaults to: 270
*/
public void setRotation(Number rotation) {
this.rotation = rotation;
}
/**
* @see #setStyle(Style)
*/
public Style getStyle() {
if (style == null) {
style = new Style();
}
return style;
}
/**
* <p>
* CSS styles for the title. When titles are rotated they are rendered using
* vector graphic techniques and not all styles are applicable.
* </p>
*
* <p>
* In <a href=
* "http://www.highcharts.com/docs/chart-design-and-style/style-by-css"
* >styled mode</a>, the stroke width is given in the
* <code>.highcharts-axis-title</code> class.
* </p>
* <p>
* Defaults to: { "color": "#666666" }
*/
public void setStyle(Style style) {
this.style = style;
}
public AxisTitle(String text) {
this.text = text;
}
/**
* @see #setText(String)
*/
public String getText() {
return text;
}
/**
* The actual text of the axis title. Horizontal texts can contain HTML, but
* rotated texts are painted using vector techniques and must be clean text.
* The Y axis title is disabled by setting the <code>text</code> option to
* <code>null</code>.
* <p>
* Defaults to: Values
*/
public void setText(String text) {
this.text = text;
}
/**
* @see #setX(Number)
*/
public Number getX() {
return x;
}
/**
* Horizontal pixel offset of the title position.
* <p>
* Defaults to: 0
*/
public void setX(Number x) {
this.x = x;
}
/**
* @see #setY(Number)
*/
public Number getY() {
return y;
}
/**
* Vertical pixel offset of the title position.
*/
public void setY(Number y) {
this.y = y;
}
}
| 20.727273 | 189 | 0.660896 |
05a82cad6da39cd4c61951747fbb2a77a494b474 | 2,355 | package com.lzt.operate.mybatis.base.service.impl;
import com.lzt.operate.mybatis.base.dao.BaseMapper;
import com.lzt.operate.mybatis.base.model.BaseExample;
import com.lzt.operate.mybatis.base.service.BaseService;
import com.lzt.operate.mybatis.common.PageInfo;
import java.util.List;
import java.util.Optional;
/**
* @author luzhitao
*/
public abstract class BaseServiceImpl<T, Example extends BaseExample, ID> implements BaseService<T, Example, ID> {
private BaseMapper<T, Example, ID> mapper;
public void setMapper(BaseMapper<T, Example, ID> mapper) {
this.mapper = mapper;
}
@Override
public long countByExample(Example example) {
return this.mapper.countByExample(example);
}
@Override
public int deleteByExample(Example example) {
return this.mapper.deleteByExample(example);
}
@Override
public int deleteByPrimaryKey(ID id) {
return this.mapper.deleteByPrimaryKey(id);
}
@Override
public int insert(T record) {
return this.mapper.insert(record);
}
@Override
public int insertSelective(T record) {
return this.mapper.insertSelective(record);
}
@Override
public List<T> selectByExample(Example example) {
return this.mapper.selectByExample(example);
}
@Override
public Optional<T> selectByCondition(Example example) {
List<T> list = this.selectByExample(example);
if (Optional.ofNullable(list).isPresent()) {
if (list.size() >= 1) {
return Optional.of(list.get(0));
}
}
return Optional.empty();
}
@Override
public List<T> selectByPageExample(Example example, PageInfo pageInfo) {
if (pageInfo != null) {
example.setPageInfo(pageInfo);
pageInfo.setPageParams(Long.valueOf(this.countByExample(example)).intValue());
}
return this.selectByExample(example);
}
@Override
public T selectByPrimaryKey(ID id) {
return this.mapper.selectByPrimaryKey(id);
}
@Override
public int updateByExampleSelective(T record, Example example) {
return this.mapper.updateByExampleSelective(record, example);
}
@Override
public int updateByExample(T record, Example example) {
return this.mapper.updateByExample(record, example);
}
@Override
public int updateByPrimaryKeySelective(T record) {
return this.mapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(T record) {
return this.mapper.updateByPrimaryKey(record);
}
} | 23.55 | 114 | 0.751592 |
26b65c839ff4aebaebc1c9b6188612492b93265c | 38,836 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
import com.handmark.pulltorefresh.library.internal.Utils;
// Referenced classes of package com.handmark.pulltorefresh.library:
// IPullToRefresh, e, h, f,
// LoadingLayoutProxy, OverscrollHelper, c, d,
// ILoadingLayout, g
public abstract class PullToRefreshBase extends LinearLayout
implements IPullToRefresh
{
public static final int SMOOTH_SCROLL_DURATION_MS = 200;
public static final int SMOOTH_SCROLL_LONG_DURATION_MS = 325;
static final boolean a = true;
static final boolean b = false;
static final String c = "PullToRefresh";
static final float d = 4.2F;
static final int e = 225;
static final String f = "ptr_state";
static final String g = "ptr_mode";
static final String h = "ptr_current_mode";
static final String i = "ptr_disable_scrolling";
static final String j = "ptr_show_refreshing_view";
static final String k = "ptr_super";
private boolean A;
private Interpolator B;
private AnimationStyle C;
private LoadingLayout D;
private LoadingLayout E;
private OnRefreshListener F;
private OnRefreshListener2 G;
private OnPullEventListener H;
private h I;
View l;
private int m;
private float n;
private float o;
private float p;
private float q;
private boolean r;
private State s;
private Mode t;
private Mode u;
private FrameLayout v;
private boolean w;
private boolean x;
private boolean y;
private boolean z;
public PullToRefreshBase(Context context)
{
super(context);
r = false;
s = State.RESET;
t = Mode.a();
w = true;
x = false;
y = true;
z = true;
A = true;
C = AnimationStyle.a();
a(context, ((AttributeSet) (null)));
}
public PullToRefreshBase(Context context, AttributeSet attributeset)
{
super(context, attributeset);
r = false;
s = State.RESET;
t = Mode.a();
w = true;
x = false;
y = true;
z = true;
A = true;
C = AnimationStyle.a();
a(context, attributeset);
}
public PullToRefreshBase(Context context, Mode mode)
{
super(context);
r = false;
s = State.RESET;
t = Mode.a();
w = true;
x = false;
y = true;
z = true;
A = true;
C = AnimationStyle.a();
t = mode;
a(context, ((AttributeSet) (null)));
}
public PullToRefreshBase(Context context, Mode mode, AnimationStyle animationstyle)
{
super(context);
r = false;
s = State.RESET;
t = Mode.a();
w = true;
x = false;
y = true;
z = true;
A = true;
C = AnimationStyle.a();
t = mode;
C = animationstyle;
a(context, ((AttributeSet) (null)));
}
private void a()
{
if (F != null)
{
F.onRefresh(this);
} else
if (G != null)
{
if (u == Mode.PULL_FROM_START)
{
G.onPullDownToRefresh(this);
return;
}
if (u == Mode.PULL_FROM_END)
{
G.onPullUpToRefresh(this);
return;
}
}
}
private final void a(int i1)
{
a(i1, 200L, 0L, ((g) (new e(this))));
}
private final void a(int i1, long l1)
{
a(i1, l1, 0L, null);
}
private final void a(int i1, long l1, long l2, g g1)
{
if (I != null)
{
I.a();
}
f.a[getPullToRefreshScrollDirection().ordinal()];
JVM INSTR tableswitch 1 1: default 44
// 1 111;
goto _L1 _L2
_L1:
int j1 = getScrollY();
_L4:
if (j1 != i1)
{
if (B == null)
{
B = new DecelerateInterpolator();
}
I = new h(this, j1, i1, l1, g1);
if (l2 <= 0L)
{
break; /* Loop/switch isn't completed */
}
postDelayed(I, l2);
}
return;
_L2:
j1 = getScrollX();
if (true) goto _L4; else goto _L3
_L3:
post(I);
return;
}
private void a(Context context, AttributeSet attributeset)
{
switch (f.a[getPullToRefreshScrollDirection().ordinal()])
{
default:
setOrientation(1);
break;
case 1: // '\001'
break MISSING_BLOCK_LABEL_231;
}
_L1:
setGravity(17);
m = ViewConfiguration.get(context).getScaledTouchSlop();
TypedArray typedarray = context.obtainStyledAttributes(attributeset, com.xiaomi.hm.health.R.styleable.PullToRefresh);
if (typedarray.hasValue(4))
{
t = Mode.a(typedarray.getInteger(4, 0));
}
if (typedarray.hasValue(12))
{
C = AnimationStyle.a(typedarray.getInteger(12, 0));
}
l = createRefreshableView(context, attributeset);
a(context, l);
D = createLoadingLayout(context, Mode.PULL_FROM_START, typedarray);
E = createLoadingLayout(context, Mode.PULL_FROM_END, typedarray);
if (typedarray.hasValue(0))
{
Drawable drawable1 = typedarray.getDrawable(0);
if (drawable1 != null)
{
l.setBackgroundDrawable(drawable1);
}
} else
if (typedarray.hasValue(16))
{
Utils.warnDeprecation("ptrAdapterViewBackground", "ptrRefreshableViewBackground");
Drawable drawable = typedarray.getDrawable(16);
if (drawable != null)
{
l.setBackgroundDrawable(drawable);
}
}
if (typedarray.hasValue(9))
{
z = typedarray.getBoolean(9, true);
}
if (typedarray.hasValue(13))
{
x = typedarray.getBoolean(13, false);
}
handleStyledAttributes(typedarray);
typedarray.recycle();
updateUIForMode();
return;
setOrientation(0);
goto _L1
}
private void a(Context context, View view)
{
v = new FrameLayout(context);
v.addView(view, -1, -1);
addViewInternal(v, new android.widget.LinearLayout.LayoutParams(-1, -1));
}
static void a(PullToRefreshBase pulltorefreshbase)
{
pulltorefreshbase.a();
}
static void a(PullToRefreshBase pulltorefreshbase, int i1, long l1, long l2, g g1)
{
pulltorefreshbase.a(i1, l1, l2, g1);
}
static Interpolator b(PullToRefreshBase pulltorefreshbase)
{
return pulltorefreshbase.B;
}
private boolean b()
{
f.c[t.ordinal()];
JVM INSTR tableswitch 1 4: default 40
// 1 47
// 2 42
// 3 40
// 4 52;
goto _L1 _L2 _L3 _L1 _L4
_L1:
return false;
_L3:
return isReadyForPullStart();
_L2:
return isReadyForPullEnd();
_L4:
if (isReadyForPullEnd() || isReadyForPullStart())
{
return true;
}
if (true) goto _L1; else goto _L5
_L5:
}
private void c()
{
f.a[getPullToRefreshScrollDirection().ordinal()];
JVM INSTR tableswitch 1 1: default 28
// 1 183;
goto _L1 _L2
_L1:
float f1;
float f2;
f1 = q;
f2 = o;
_L15:
f.c[u.ordinal()];
JVM INSTR tableswitch 1 1: default 68
// 1 196;
goto _L3 _L4
_L3:
int i1;
int j1;
i1 = Math.round(Math.min(f1 - f2, 0.0F) / 4.2F);
j1 = getHeaderSize();
_L11:
setHeaderScroll(i1);
if (i1 == 0 || isRefreshing()) goto _L6; else goto _L5
_L5:
float f3 = (float)Math.abs(i1) / (float)j1;
f.c[u.ordinal()];
JVM INSTR tableswitch 1 1: default 144
// 1 219;
goto _L7 _L8
_L7:
D.onPull(f3);
_L12:
if (s == State.PULL_TO_REFRESH || j1 < Math.abs(i1)) goto _L10; else goto _L9
_L9:
a(State.PULL_TO_REFRESH, new boolean[0]);
_L6:
return;
_L2:
f1 = p;
f2 = n;
continue; /* Loop/switch isn't completed */
_L4:
i1 = Math.round(Math.max(f1 - f2, 0.0F) / 4.2F);
j1 = getFooterSize();
goto _L11
_L8:
E.onPull(f3);
goto _L12
_L10:
if (s != State.PULL_TO_REFRESH || j1 >= Math.abs(i1)) goto _L6; else goto _L13
_L13:
a(State.RELEASE_TO_REFRESH, new boolean[0]);
return;
if (true) goto _L15; else goto _L14
_L14:
}
private android.widget.LinearLayout.LayoutParams d()
{
switch (f.a[getPullToRefreshScrollDirection().ordinal()])
{
default:
return new android.widget.LinearLayout.LayoutParams(-1, -2);
case 1: // '\001'
return new android.widget.LinearLayout.LayoutParams(-2, -1);
}
}
private int e()
{
switch (f.a[getPullToRefreshScrollDirection().ordinal()])
{
default:
return Math.round((float)getHeight() / 4.2F);
case 1: // '\001'
return Math.round((float)getWidth() / 4.2F);
}
}
final transient void a(State state, boolean aflag[])
{
s = state;
Log.d("PullToRefresh", (new StringBuilder()).append("State: ").append(s.name()).toString());
f.b[s.ordinal()];
JVM INSTR tableswitch 1 5: default 84
// 1 110
// 2 117
// 3 124
// 4 131
// 5 131;
goto _L1 _L2 _L3 _L4 _L5 _L5
_L1:
if (H != null)
{
H.onPullEvent(this, s, u);
}
return;
_L2:
onReset();
continue; /* Loop/switch isn't completed */
_L3:
onPullToRefresh();
continue; /* Loop/switch isn't completed */
_L4:
onReleaseToRefresh();
continue; /* Loop/switch isn't completed */
_L5:
onRefreshing(aflag[0]);
if (true) goto _L1; else goto _L6
_L6:
}
public void addView(View view, int i1, android.view.ViewGroup.LayoutParams layoutparams)
{
Log.d("PullToRefresh", (new StringBuilder()).append("addView: ").append(view.getClass().getSimpleName()).toString());
View view1 = getRefreshableView();
if (view1 instanceof ViewGroup)
{
((ViewGroup)view1).addView(view, i1, layoutparams);
return;
} else
{
throw new UnsupportedOperationException("Refreshable View is not a ViewGroup so can't addView");
}
}
protected final void addViewInternal(View view, int i1, android.view.ViewGroup.LayoutParams layoutparams)
{
super.addView(view, i1, layoutparams);
}
protected final void addViewInternal(View view, android.view.ViewGroup.LayoutParams layoutparams)
{
super.addView(view, -1, layoutparams);
}
protected LoadingLayout createLoadingLayout(Context context, Mode mode, TypedArray typedarray)
{
LoadingLayout loadinglayout = C.a(context, mode, getPullToRefreshScrollDirection(), typedarray);
loadinglayout.setVisibility(4);
return loadinglayout;
}
protected LoadingLayoutProxy createLoadingLayoutProxy(boolean flag, boolean flag1)
{
LoadingLayoutProxy loadinglayoutproxy = new LoadingLayoutProxy();
if (flag && t.showHeaderLoadingLayout())
{
loadinglayoutproxy.addLayout(D);
}
if (flag1 && t.showFooterLoadingLayout())
{
loadinglayoutproxy.addLayout(E);
}
return loadinglayoutproxy;
}
protected abstract View createRefreshableView(Context context, AttributeSet attributeset);
public final boolean demo()
{
if (t.showHeaderLoadingLayout() && isReadyForPullStart())
{
a(2 * -getHeaderSize());
return true;
}
if (t.showFooterLoadingLayout() && isReadyForPullEnd())
{
a(2 * getFooterSize());
return true;
} else
{
return false;
}
}
protected final void disableLoadingLayoutVisibilityChanges()
{
A = false;
}
public final Mode getCurrentMode()
{
return u;
}
public final boolean getFilterTouchEvents()
{
return y;
}
protected final LoadingLayout getFooterLayout()
{
return E;
}
protected final int getFooterSize()
{
return E.getContentSize();
}
protected final LoadingLayout getHeaderLayout()
{
return D;
}
protected final int getHeaderSize()
{
return D.getContentSize();
}
public final ILoadingLayout getLoadingLayoutProxy()
{
return getLoadingLayoutProxy(true, true);
}
public final ILoadingLayout getLoadingLayoutProxy(boolean flag, boolean flag1)
{
return createLoadingLayoutProxy(flag, flag1);
}
public final Mode getMode()
{
return t;
}
public abstract Orientation getPullToRefreshScrollDirection();
protected int getPullToRefreshScrollDuration()
{
return 200;
}
protected int getPullToRefreshScrollDurationLonger()
{
return 325;
}
public final View getRefreshableView()
{
return l;
}
protected FrameLayout getRefreshableViewWrapper()
{
return v;
}
public final boolean getShowViewWhileRefreshing()
{
return w;
}
public final State getState()
{
return s;
}
protected void handleStyledAttributes(TypedArray typedarray)
{
}
public final boolean isDisableScrollingWhileRefreshing()
{
return !isScrollingWhileRefreshingEnabled();
}
public final boolean isPullToRefreshEnabled()
{
return t.b();
}
public final boolean isPullToRefreshOverScrollEnabled()
{
return android.os.Build.VERSION.SDK_INT >= 9 && z && OverscrollHelper.a(l);
}
protected abstract boolean isReadyForPullEnd();
protected abstract boolean isReadyForPullStart();
public final boolean isRefreshing()
{
return s == State.REFRESHING || s == State.MANUAL_REFRESHING;
}
public final boolean isScrollingWhileRefreshingEnabled()
{
return x;
}
public final boolean onInterceptTouchEvent(MotionEvent motionevent)
{
int i1;
if (!isPullToRefreshEnabled())
{
return false;
}
i1 = motionevent.getAction();
if (i1 == 3 || i1 == 1)
{
r = false;
return false;
}
if (i1 != 0 && r)
{
return true;
}
i1;
JVM INSTR tableswitch 0 2: default 72
// 0 339
// 1 72
// 2 77;
goto _L1 _L2 _L1 _L3
_L1:
return r;
_L3:
float f3;
float f4;
if (!x && isRefreshing())
{
return true;
}
if (!b())
{
continue; /* Loop/switch isn't completed */
}
f3 = motionevent.getY();
f4 = motionevent.getX();
f.a[getPullToRefreshScrollDirection().ordinal()];
JVM INSTR tableswitch 1 1: default 140
// 1 255;
goto _L4 _L5
_L4:
float f5;
float f6;
f5 = f3 - o;
f6 = f4 - n;
_L6:
float f7 = Math.abs(f5);
if (f7 > (float)m && (!y || f7 > Math.abs(f6)))
{
if (t.showHeaderLoadingLayout() && f5 >= 1.0F && isReadyForPullStart())
{
o = f3;
n = f4;
r = true;
if (t == Mode.BOTH)
{
u = Mode.PULL_FROM_START;
}
} else
if (t.showFooterLoadingLayout() && f5 <= -1F && isReadyForPullEnd())
{
o = f3;
n = f4;
r = true;
if (t == Mode.BOTH)
{
u = Mode.PULL_FROM_END;
}
}
}
continue; /* Loop/switch isn't completed */
_L5:
f5 = f4 - n;
f6 = f3 - o;
goto _L6
_L2:
if (b())
{
float f1 = motionevent.getY();
q = f1;
o = f1;
float f2 = motionevent.getX();
p = f2;
n = f2;
r = false;
}
if (true) goto _L1; else goto _L7
_L7:
}
protected void onPtrRestoreInstanceState(Bundle bundle)
{
}
protected void onPtrSaveInstanceState(Bundle bundle)
{
}
protected void onPullToRefresh()
{
switch (f.c[u.ordinal()])
{
default:
return;
case 1: // '\001'
E.pullToRefresh();
return;
case 2: // '\002'
D.pullToRefresh();
break;
}
}
public final void onRefreshComplete()
{
if (isRefreshing())
{
a(State.RESET, new boolean[0]);
}
}
protected void onRefreshing(boolean flag)
{
if (t.showHeaderLoadingLayout())
{
D.refreshing();
}
if (t.showFooterLoadingLayout())
{
E.refreshing();
}
if (flag)
{
if (w)
{
c c1 = new c(this);
switch (f.c[u.ordinal()])
{
case 2: // '\002'
default:
smoothScrollTo(-getHeaderSize(), c1);
return;
case 1: // '\001'
case 3: // '\003'
smoothScrollTo(getFooterSize(), c1);
break;
}
return;
} else
{
smoothScrollTo(0);
return;
}
} else
{
a();
return;
}
}
protected void onReleaseToRefresh()
{
switch (f.c[u.ordinal()])
{
default:
return;
case 1: // '\001'
E.releaseToRefresh();
return;
case 2: // '\002'
D.releaseToRefresh();
break;
}
}
protected void onReset()
{
r = false;
A = true;
D.reset();
E.reset();
smoothScrollTo(0);
}
protected final void onRestoreInstanceState(Parcelable parcelable)
{
if (parcelable instanceof Bundle)
{
Bundle bundle = (Bundle)parcelable;
setMode(Mode.a(bundle.getInt("ptr_mode", 0)));
u = Mode.a(bundle.getInt("ptr_current_mode", 0));
x = bundle.getBoolean("ptr_disable_scrolling", false);
w = bundle.getBoolean("ptr_show_refreshing_view", true);
super.onRestoreInstanceState(bundle.getParcelable("ptr_super"));
State state = State.a(bundle.getInt("ptr_state", 0));
if (state == State.REFRESHING || state == State.MANUAL_REFRESHING)
{
a(state, new boolean[] {
true
});
}
onPtrRestoreInstanceState(bundle);
return;
} else
{
super.onRestoreInstanceState(parcelable);
return;
}
}
protected final Parcelable onSaveInstanceState()
{
Bundle bundle = new Bundle();
onPtrSaveInstanceState(bundle);
bundle.putInt("ptr_state", s.a());
bundle.putInt("ptr_mode", t.c());
bundle.putInt("ptr_current_mode", u.c());
bundle.putBoolean("ptr_disable_scrolling", x);
bundle.putBoolean("ptr_show_refreshing_view", w);
bundle.putParcelable("ptr_super", super.onSaveInstanceState());
return bundle;
}
protected final void onSizeChanged(int i1, int j1, int k1, int l1)
{
Object aobj[] = new Object[2];
aobj[0] = Integer.valueOf(i1);
aobj[1] = Integer.valueOf(j1);
Log.d("PullToRefresh", String.format("onSizeChanged. W: %d, H: %d", aobj));
super.onSizeChanged(i1, j1, k1, l1);
refreshLoadingViewsSize();
refreshRefreshableViewSize(i1, j1);
post(new d(this));
}
public final boolean onTouchEvent(MotionEvent motionevent)
{
if (isPullToRefreshEnabled()) goto _L2; else goto _L1
_L1:
return false;
_L2:
if (!x && isRefreshing())
{
return true;
}
if (motionevent.getAction() == 0 && motionevent.getEdgeFlags() != 0) goto _L1; else goto _L3
_L3:
motionevent.getAction();
JVM INSTR tableswitch 0 3: default 72
// 0 74
// 1 142
// 2 113
// 3 142;
goto _L4 _L5 _L6 _L7 _L6
_L6:
continue; /* Loop/switch isn't completed */
_L4:
return false;
_L5:
if (!b()) goto _L1; else goto _L8
_L8:
float f1 = motionevent.getY();
q = f1;
o = f1;
float f2 = motionevent.getX();
p = f2;
n = f2;
return true;
_L7:
if (!r) goto _L1; else goto _L9
_L9:
o = motionevent.getY();
n = motionevent.getX();
c();
return true;
if (!r) goto _L1; else goto _L10
_L10:
r = false;
if (s == State.RELEASE_TO_REFRESH && (F != null || G != null))
{
a(State.REFRESHING, new boolean[] {
true
});
return true;
}
if (isRefreshing())
{
smoothScrollTo(0);
return true;
} else
{
a(State.RESET, new boolean[0]);
return true;
}
}
protected final void refreshLoadingViewsSize()
{
int i1;
int j1;
int k1;
int l1;
int i2;
i1 = (int)(1.2F * (float)e());
j1 = getPaddingLeft();
k1 = getPaddingTop();
l1 = getPaddingRight();
i2 = getPaddingBottom();
f.a[getPullToRefreshScrollDirection().ordinal()];
JVM INSTR tableswitch 1 2: default 68
// 1 151
// 2 232;
goto _L1 _L2 _L3
_L1:
int k2;
int l2;
int i3;
int j3;
j3 = i2;
k2 = l1;
i3 = k1;
l2 = j1;
_L5:
Object aobj[] = new Object[4];
aobj[0] = Integer.valueOf(l2);
aobj[1] = Integer.valueOf(i3);
aobj[2] = Integer.valueOf(k2);
aobj[3] = Integer.valueOf(j3);
Log.d("PullToRefresh", String.format("Setting Padding. L: %d, T: %d, R: %d, B: %d", aobj));
setPadding(l2, i3, k2, j3);
return;
_L2:
int l3;
if (t.showHeaderLoadingLayout())
{
D.setWidth(i1);
l3 = -i1;
} else
{
l3 = 0;
}
if (t.showFooterLoadingLayout())
{
E.setWidth(i1);
k2 = -i1;
i3 = k1;
l2 = l3;
j3 = i2;
} else
{
i3 = k1;
l2 = l3;
j3 = i2;
k2 = 0;
}
continue; /* Loop/switch isn't completed */
_L3:
int j2;
if (t.showHeaderLoadingLayout())
{
D.setHeight(i1);
j2 = -i1;
} else
{
j2 = 0;
}
if (t.showFooterLoadingLayout())
{
E.setHeight(i1);
int k3 = -i1;
l2 = j1;
i3 = j2;
j3 = k3;
k2 = l1;
} else
{
k2 = l1;
l2 = j1;
i3 = j2;
j3 = 0;
}
if (true) goto _L5; else goto _L4
_L4:
}
protected final void refreshRefreshableViewSize(int i1, int j1)
{
android.widget.LinearLayout.LayoutParams layoutparams = (android.widget.LinearLayout.LayoutParams)v.getLayoutParams();
f.a[getPullToRefreshScrollDirection().ordinal()];
JVM INSTR tableswitch 1 2: default 44
// 1 45
// 2 66;
goto _L1 _L2 _L3
_L1:
return;
_L2:
if (layoutparams.width != i1)
{
layoutparams.width = i1;
v.requestLayout();
return;
}
continue; /* Loop/switch isn't completed */
_L3:
if (layoutparams.height != j1)
{
layoutparams.height = j1;
v.requestLayout();
return;
}
if (true) goto _L1; else goto _L4
_L4:
}
public void setDisableScrollingWhileRefreshing(boolean flag)
{
boolean flag1;
if (!flag)
{
flag1 = true;
} else
{
flag1 = false;
}
setScrollingWhileRefreshingEnabled(flag1);
}
public final void setFilterTouchEvents(boolean flag)
{
y = flag;
}
protected final void setHeaderScroll(int i1)
{
Log.d("PullToRefresh", (new StringBuilder()).append("setHeaderScroll: ").append(i1).toString());
int j1 = e();
int k1 = Math.min(j1, Math.max(-j1, i1));
if (A)
{
if (k1 < 0)
{
D.setVisibility(0);
} else
if (k1 > 0)
{
E.setVisibility(0);
} else
{
D.setVisibility(4);
E.setVisibility(4);
}
}
switch (f.a[getPullToRefreshScrollDirection().ordinal()])
{
default:
return;
case 2: // '\002'
scrollTo(0, k1);
return;
case 1: // '\001'
scrollTo(k1, 0);
return;
}
}
public void setLastUpdatedLabel(CharSequence charsequence)
{
getLoadingLayoutProxy().setLastUpdatedLabel(charsequence);
}
public void setLoadingDrawable(Drawable drawable)
{
getLoadingLayoutProxy().setLoadingDrawable(drawable);
}
public void setLoadingDrawable(Drawable drawable, Mode mode)
{
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setLoadingDrawable(drawable);
}
public void setLongClickable(boolean flag)
{
getRefreshableView().setLongClickable(flag);
}
public final void setMode(Mode mode)
{
if (mode != t)
{
Log.d("PullToRefresh", (new StringBuilder()).append("Setting mode to: ").append(mode).toString());
t = mode;
updateUIForMode();
}
}
public void setOnPullEventListener(OnPullEventListener onpulleventlistener)
{
H = onpulleventlistener;
}
public final void setOnRefreshListener(OnRefreshListener2 onrefreshlistener2)
{
G = onrefreshlistener2;
F = null;
}
public final void setOnRefreshListener(OnRefreshListener onrefreshlistener)
{
F = onrefreshlistener;
G = null;
}
public void setPullLabel(CharSequence charsequence)
{
getLoadingLayoutProxy().setPullLabel(charsequence);
}
public void setPullLabel(CharSequence charsequence, Mode mode)
{
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setPullLabel(charsequence);
}
public final void setPullToRefreshEnabled(boolean flag)
{
Mode mode;
if (flag)
{
mode = Mode.a();
} else
{
mode = Mode.DISABLED;
}
setMode(mode);
}
public final void setPullToRefreshOverScrollEnabled(boolean flag)
{
z = flag;
}
public final void setRefreshing()
{
setRefreshing(true);
}
public final void setRefreshing(boolean flag)
{
if (!isRefreshing())
{
a(State.MANUAL_REFRESHING, new boolean[] {
flag
});
}
}
public void setRefreshingLabel(CharSequence charsequence)
{
getLoadingLayoutProxy().setRefreshingLabel(charsequence);
}
public void setRefreshingLabel(CharSequence charsequence, Mode mode)
{
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setRefreshingLabel(charsequence);
}
public void setReleaseLabel(CharSequence charsequence)
{
setReleaseLabel(charsequence, Mode.BOTH);
}
public void setReleaseLabel(CharSequence charsequence, Mode mode)
{
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setReleaseLabel(charsequence);
}
public void setScrollAnimationInterpolator(Interpolator interpolator)
{
B = interpolator;
}
public final void setScrollingWhileRefreshingEnabled(boolean flag)
{
x = flag;
}
public final void setShowViewWhileRefreshing(boolean flag)
{
w = flag;
}
protected final void smoothScrollTo(int i1)
{
a(i1, getPullToRefreshScrollDuration());
}
protected final void smoothScrollTo(int i1, g g1)
{
a(i1, getPullToRefreshScrollDuration(), 0L, g1);
}
protected final void smoothScrollToLonger(int i1)
{
a(i1, getPullToRefreshScrollDurationLonger());
}
protected void updateUIForMode()
{
android.widget.LinearLayout.LayoutParams layoutparams = d();
if (this == D.getParent())
{
removeView(D);
}
if (t.showHeaderLoadingLayout())
{
addViewInternal(D, 0, layoutparams);
}
if (this == E.getParent())
{
removeView(E);
}
if (t.showFooterLoadingLayout())
{
addViewInternal(E, layoutparams);
}
refreshLoadingViewsSize();
Mode mode;
if (t != Mode.BOTH)
{
mode = t;
} else
{
mode = Mode.PULL_FROM_START;
}
u = mode;
}
private class State extends Enum
{
public static final State MANUAL_REFRESHING;
public static final State OVERSCROLLING;
public static final State PULL_TO_REFRESH;
public static final State REFRESHING;
public static final State RELEASE_TO_REFRESH;
public static final State RESET;
private static final State b[];
private int a;
static State a(int i1)
{
State astate[] = values();
int j1 = astate.length;
for (int k1 = 0; k1 < j1; k1++)
{
State state = astate[k1];
if (i1 == state.a())
{
return state;
}
}
return RESET;
}
public static State valueOf(String s1)
{
return (State)Enum.valueOf(com/handmark/pulltorefresh/library/PullToRefreshBase$State, s1);
}
public static State[] values()
{
return (State[])b.clone();
}
int a()
{
return a;
}
static
{
RESET = new State("RESET", 0, 0);
PULL_TO_REFRESH = new State("PULL_TO_REFRESH", 1, 1);
RELEASE_TO_REFRESH = new State("RELEASE_TO_REFRESH", 2, 2);
REFRESHING = new State("REFRESHING", 3, 8);
MANUAL_REFRESHING = new State("MANUAL_REFRESHING", 4, 9);
OVERSCROLLING = new State("OVERSCROLLING", 5, 16);
State astate[] = new State[6];
astate[0] = RESET;
astate[1] = PULL_TO_REFRESH;
astate[2] = RELEASE_TO_REFRESH;
astate[3] = REFRESHING;
astate[4] = MANUAL_REFRESHING;
astate[5] = OVERSCROLLING;
b = astate;
}
private State(String s1, int i1, int j1)
{
super(s1, i1);
a = j1;
}
}
private class Mode extends Enum
{
public static final Mode BOTH;
public static final Mode DISABLED;
public static final Mode MANUAL_REFRESH_ONLY;
public static Mode PULL_DOWN_TO_REFRESH;
public static final Mode PULL_FROM_END;
public static final Mode PULL_FROM_START;
public static Mode PULL_UP_TO_REFRESH;
private static final Mode b[];
private int a;
static Mode a()
{
return PULL_FROM_START;
}
static Mode a(int i1)
{
Mode amode[] = values();
int j1 = amode.length;
for (int k1 = 0; k1 < j1; k1++)
{
Mode mode = amode[k1];
if (i1 == mode.c())
{
return mode;
}
}
return a();
}
public static Mode valueOf(String s1)
{
return (Mode)Enum.valueOf(com/handmark/pulltorefresh/library/PullToRefreshBase$Mode, s1);
}
public static Mode[] values()
{
return (Mode[])b.clone();
}
boolean b()
{
return this != DISABLED && this != MANUAL_REFRESH_ONLY;
}
int c()
{
return a;
}
public boolean showFooterLoadingLayout()
{
return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
}
public boolean showHeaderLoadingLayout()
{
return this == PULL_FROM_START || this == BOTH;
}
static
{
DISABLED = new Mode("DISABLED", 0, 0);
PULL_FROM_START = new Mode("PULL_FROM_START", 1, 1);
PULL_FROM_END = new Mode("PULL_FROM_END", 2, 2);
BOTH = new Mode("BOTH", 3, 3);
MANUAL_REFRESH_ONLY = new Mode("MANUAL_REFRESH_ONLY", 4, 4);
Mode amode[] = new Mode[5];
amode[0] = DISABLED;
amode[1] = PULL_FROM_START;
amode[2] = PULL_FROM_END;
amode[3] = BOTH;
amode[4] = MANUAL_REFRESH_ONLY;
b = amode;
PULL_DOWN_TO_REFRESH = PULL_FROM_START;
PULL_UP_TO_REFRESH = PULL_FROM_END;
}
private Mode(String s1, int i1, int j1)
{
super(s1, i1);
a = j1;
}
}
private class AnimationStyle extends Enum
{
public static final AnimationStyle FLIP;
public static final AnimationStyle ROTATE;
private static final AnimationStyle a[];
static AnimationStyle a()
{
return ROTATE;
}
static AnimationStyle a(int i1)
{
switch (i1)
{
default:
return ROTATE;
case 1: // '\001'
return FLIP;
}
}
public static AnimationStyle valueOf(String s1)
{
return (AnimationStyle)Enum.valueOf(com/handmark/pulltorefresh/library/PullToRefreshBase$AnimationStyle, s1);
}
public static AnimationStyle[] values()
{
return (AnimationStyle[])a.clone();
}
LoadingLayout a(Context context, Mode mode, Orientation orientation, TypedArray typedarray)
{
switch (f.d[ordinal()])
{
default:
return new RotateLoadingLayout(context, mode, orientation, typedarray);
case 2: // '\002'
return new FlipLoadingLayout(context, mode, orientation, typedarray);
}
}
static
{
ROTATE = new AnimationStyle("ROTATE", 0);
FLIP = new AnimationStyle("FLIP", 1);
AnimationStyle aanimationstyle[] = new AnimationStyle[2];
aanimationstyle[0] = ROTATE;
aanimationstyle[1] = FLIP;
a = aanimationstyle;
}
private AnimationStyle(String s1, int i1)
{
super(s1, i1);
}
}
private class OnRefreshListener
{
public abstract void onRefresh(PullToRefreshBase pulltorefreshbase);
}
private class OnRefreshListener2
{
public abstract void onPullDownToRefresh(PullToRefreshBase pulltorefreshbase);
public abstract void onPullUpToRefresh(PullToRefreshBase pulltorefreshbase);
}
private class Orientation extends Enum
{
public static final Orientation HORIZONTAL;
public static final Orientation VERTICAL;
private static final Orientation a[];
public static Orientation valueOf(String s1)
{
return (Orientation)Enum.valueOf(com/handmark/pulltorefresh/library/PullToRefreshBase$Orientation, s1);
}
public static Orientation[] values()
{
return (Orientation[])a.clone();
}
static
{
VERTICAL = new Orientation("VERTICAL", 0);
HORIZONTAL = new Orientation("HORIZONTAL", 1);
Orientation aorientation[] = new Orientation[2];
aorientation[0] = VERTICAL;
aorientation[1] = HORIZONTAL;
a = aorientation;
}
private Orientation(String s1, int i1)
{
super(s1, i1);
}
}
private class OnPullEventListener
{
public abstract void onPullEvent(PullToRefreshBase pulltorefreshbase, State state, Mode mode);
}
}
| 25.46623 | 127 | 0.525389 |
cfdcaf22f3253e1ea3a04ddef9047685ddf6968d | 1,288 | package com.laputa.laputa_sns.configurer;
import com.laputa.laputa_sns.interceptor.ValidateInterceptor;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author JQH
* @since 下午 12:31 20/02/14
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
private final ValidateInterceptor validateInterceptor;
public WebConfigurer(ValidateInterceptor validateInterceptor) {
this.validateInterceptor = validateInterceptor;
}
@Override
public void addInterceptors(@NotNull InterceptorRegistry registry) {
registry.addInterceptor(validateInterceptor).addPathPatterns("/**")
.excludePathPatterns("/**/*.js", "/**/*.html", "/**/*.css", "/**/*.jpg", "/**/*.png");
}
// @Override
// public void addCorsMappings(@NotNull CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins("*")
// .allowCredentials(true)
// .exposedHeaders("X-LPT-USER-TOKEN")
// .allowedMethods("GET", "POST", "PATCH", "DELETE");
// }
}
| 32.2 | 102 | 0.684783 |
08ea8aaf99a0e07cd2362fba05191dbab0273d63 | 384 | package com.tiernebre.zone_blitz.user.exception;
import com.tiernebre.zone_blitz.exception.InvalidException;
import lombok.Getter;
import java.util.Set;
@Getter
public class InvalidUserException extends InvalidException {
public InvalidUserException(
Set<String> errors
) {
super("The request to create a user contained invalid data.", errors);
}
}
| 24 | 78 | 0.742188 |
e7b4e8c52785583478695ec40e66c64616901a2d | 1,872 | /**********************************************************************************
* $URL: $
* $Id: $
* **********************************************************************************
* <p>
* Author: David P. Bauer, [email protected]
* <p>
* Copyright (c) 2016 University of Dayton
* <p>
* Licensed under the Educational Community 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
* <p>
* http://www.opensource.org/licenses/ECL-2.0
* <p>
* 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.sakaiproject.lessonbuildertool;
public class SimpleChecklistItemImpl implements SimpleChecklistItem {
private long id; // Basic ID
private String name; // Name to be displayed
private long link; // ID of item if linked, -1 otherwise
public SimpleChecklistItemImpl() {
name = "";
}
public SimpleChecklistItemImpl(long id, String name, Long link) {
this.id = id;
this.name = name;
this.setLink(link);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getLink() {
return link;
}
public void setLink(Long link) {
if(link == null) {
link = -1L;
}
this.link = link;
}
} | 27.529412 | 85 | 0.547009 |
0d0c4fefdb6c525d52e65be7f430fe715a719eb2 | 1,146 | package com.galaxy.galaxyquests.quests.quests.external;
import com.electro2560.dev.cluescrolls.events.PlayerClueCompletedEvent;
import com.electro2560.dev.cluescrolls.events.PlayerScrollCompletedEvent;
import com.galaxy.galaxyquests.QuestsPlugin;
import com.galaxy.galaxyquests.quests.quests.external.executor.ExternalQuestExecutor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
public class ClueScrollsQuests extends ExternalQuestExecutor {
public ClueScrollsQuests(QuestsPlugin plugin) {
super(plugin, "cluescrolls");
}
@EventHandler(ignoreCancelled = true)
public void onClueCompleted(PlayerClueCompletedEvent event) {
Player player = event.getPlayer();
String clueType = event.getClueType();
this.execute("complete_clue", player, result -> result.root(clueType));
}
@EventHandler(ignoreCancelled = true)
public void onScrollCompleted(PlayerScrollCompletedEvent event) {
Player player = event.getPlayer();
String tierType = event.getTierType();
this.execute("complete_scroll", player, result -> result.root(tierType));
}
}
| 35.8125 | 85 | 0.756545 |
c9939ac03cb3b60cdedeb07903a1f9b509850850 | 4,384 | package promoter;
import java.util.Random;
import acculturative.PeriodWarden;
import manufacturingPieces.PannonianMatter;
import space.*;
import book.*;
public abstract class Manufacturers {
public int placeMilad = supplierSideboard++;
public space.Warehouse thirdShelving = null, successiveWarehouses = null;
public manufacturingPieces.PannonianMatter theVictim = null;
public double actuallyNeglectedHours = 0.0;
public double actualizedStymiedPeriod = 0.0;
public double preciseManufacturedAmount = 0.0;
public double fabricationGraze = 0.0;
public double cultivationHateful = 0.0;
public promoter.MakerLand nation = null;
public static int supplierSideboard = 0;
public static final java.util.Random haphazardlyFilmmaker = new java.util.Random();
public synchronized void differencing(
double stingy, double grasp, space.Warehouse later, space.Warehouse past) {
this.cultivationHateful = stingy;
this.fabricationGraze = grasp;
this.thirdShelving = later;
this.successiveWarehouses = past;
this.preciseManufacturedAmount = 0;
this.actuallyNeglectedHours = 0;
this.actualizedStymiedPeriod = 0;
}
public synchronized void systemAgainTotem() {
double postscript;
if (this.theVictim != null) {
try {
this.movementLiveArtefactCssStored();
} catch (space.ClosetImbuedDispensation cma) {
this.nation = MakerLand.interference;
this.actualizedStymiedPeriod -= acculturative.PeriodWarden.presentlyMinutes();
return;
}
}
try {
this.garnerForthcomingItems();
} catch (space.EntrepotHollowOutlier einsteinium) {
this.nation = MakerLand.famine;
this.actuallyNeglectedHours -= acculturative.PeriodWarden.presentlyMinutes();
return;
}
postscript = cultivationHateful + fabricationGraze * (haphazardlyFilmmaker.nextDouble() - 0.5);
this.preciseManufacturedAmount += postscript;
book.GatheringDipper.previousDipper()
.embedCarnival(
new book.FarmExposition(
acculturative.PeriodWarden.presentlyMinutes() + postscript,
FarmExposition.ExtendsCompletesDisagree,
this));
}
protected abstract void garnerForthcomingItems() throws EntrepotHollowOutlier;
protected abstract void movementLiveArtefactCssStored() throws ClosetImbuedDispensation;
public synchronized void unlocked() {
try {
this.movementLiveArtefactCssStored();
this.actualizedStymiedPeriod += acculturative.PeriodWarden.presentlyMinutes();
this.nation = MakerLand.preparing;
book.GatheringDipper.previousDipper()
.embedCarnival(
new book.FarmExposition(
acculturative.PeriodWarden.presentlyMinutes(),
FarmExposition.StoolCommencement,
this));
} catch (space.ClosetImbuedDispensation salaam) {
this.nation = MakerLand.interference;
return;
}
}
public synchronized void unstarve() {
this.nation = MakerLand.preparing;
this.actuallyNeglectedHours += acculturative.PeriodWarden.presentlyMinutes();
book.GatheringDipper.previousDipper()
.embedCarnival(
new book.FarmExposition(
acculturative.PeriodWarden.presentlyMinutes(),
FarmExposition.StoolCommencement,
this));
}
public synchronized promoter.MakerLand liveSay() {
return this.nation;
}
public synchronized String toString() {
return "Producer" + placeMilad;
}
public synchronized java.lang.String stats() {
if (nation == MakerLand.famine) {
this.actuallyNeglectedHours += acculturative.PeriodWarden.presentlyMinutes();
this.nation = MakerLand.slumber;
} else if (this.nation == MakerLand.interference) {
this.actualizedStymiedPeriod += acculturative.PeriodWarden.presentlyMinutes();
this.nation = MakerLand.slumber;
} else {
this.nation = MakerLand.slumber;
}
return java.lang.String.format(
"| %-14s | %-12.10s | %-8.8s | %-8.8s |",
this,
this.preciseManufacturedAmount / acculturative.PeriodWarden.presentlyMinutes() * 100.0,
this.actuallyNeglectedHours / acculturative.PeriodWarden.presentlyMinutes() * 100.0,
this.actualizedStymiedPeriod / acculturative.PeriodWarden.presentlyMinutes() * 100.0);
}
}
| 35.354839 | 99 | 0.703239 |
afdae7da0f0c818817476387d108d0f86ec284c2 | 2,625 | /*
* Copyright 2015 Lithium Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lithium.flow.util;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import javax.annotation.Nonnull;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
/**
* @author Matt Ayres
*/
public class Needle<T> implements AutoCloseable {
private final Threader threader;
private final Semaphore semaphore;
private final BlockingQueue<ListenableFuture<T>> queue = new LinkedBlockingQueue<>();
public Needle(@Nonnull Threader threader) {
this(threader, Integer.MAX_VALUE);
}
public Needle(@Nonnull Threader threader, int permits) {
this.threader = checkNotNull(threader);
semaphore = new Semaphore(permits);
}
@Nonnull
public ListenableFuture<T> execute(@Nonnull String name, @Nonnull Executable executable) {
return submit(name, () -> {
executable.call();
return null;
});
}
@Nonnull
public ListenableFuture<T> submit(@Nonnull String name, @Nonnull Callable<T> callable) {
checkNotNull(name);
checkNotNull(callable);
ListenableFuture<T> future = threader.submit(name, () -> {
semaphore.acquireUninterruptibly();
try {
return callable.call();
} finally {
semaphore.release();
}
});
queue.add(future);
return future;
}
@Override
public void close() {
toList();
}
/**
* @deprecated Use {@link #toList()} instead.
*/
@Deprecated
@Nonnull
public List<T> finish() {
return toList();
}
@Nonnull
public List<T> toList() {
List<T> values = new ArrayList<>();
while (!queue.isEmpty()) {
List<ListenableFuture<T>> futures = new ArrayList<>();
queue.drainTo(futures);
values.addAll(Unchecked.get(() -> Futures.successfulAsList(futures).get()));
}
return values;
}
public int size() {
return queue.size();
}
}
| 24.53271 | 91 | 0.720381 |
9101e0f029aa22793d176eaaa012143fc72c8f5f | 3,305 | /*
Copyright 2000-2005 University Duisburg-Essen, Working group "Information Systems"
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.
*/
// $Id: Arg2Expression.java,v 1.5 2005/02/21 17:29:18 huesselbeck Exp $
package de.unidu.is.expressions;
import java.util.Map;
/**
* An expression with an operator and two arguments, e.g. the sum of two
* expressions.
*
* @author Henrik Nottelmann
* @version $Revision: 1.5 $, $Date: 2005/02/21 17:29:18 $
* @since 2003-10-27
*/
public class Arg2Expression extends AbstractExpression {
/**
* Expression operator.
*/
protected final String op;
/**
* First argument of this expression.
*/
protected final Expression arg1;
/**
* Second argument of this expression.
*/
protected final Expression arg2;
/**
* Creates a new expression object.
*
* @param op expression operator
* @param arg1 first argument of this expression
* @param arg2 second argument of this expression
*/
public Arg2Expression(String op, Expression arg1, Expression arg2) {
this.op = op;
this.arg1 = arg1;
this.arg2 = arg2;
}
/**
* Performs an substitution for variables, e.g. for each key
* <code>variable</code> in the specified binding, all occurences of
* <code>${key}</code> are replaced by the corresponding value in the
* map.<p>
* <p>
* Only the arguments are substituted.
*
* @param binding variable binding
* @return expression after substitution
*/
public Expression substitute(Map binding) {
Expression newArg1 = arg1.substitute(binding);
Expression newArg2 = arg2.substitute(binding);
if (arg1 != newArg1 || arg2 != newArg2)
return new Arg2Expression(op, newArg1, newArg2);
return this;
}
/**
* Returns the expression in infix notation, embedded in round brackets.
*
* @return expression as a string
*/
public String toString() {
return "(" + arg1 + op + arg2 + ")";
}
/**
* Returns a string representation for this expression which can be
* used as a template in an SQL statement.
*
* @return template for SQL statements
*/
public String getSQLTemplate() {
return "(" + arg1.getSQLTemplate() + op + arg2.getSQLTemplate() + ")";
}
/**
* Returns the first argument.
*
* @return first argument
*/
public Expression getArg1() {
return arg1;
}
/**
* Returns the second argument.
*
* @return second argument
*/
public Expression getArg2() {
return arg2;
}
/**
* Returns the operator symbol.
*
* @return operator symbol
*/
public String getOp() {
return op;
}
}
| 26.023622 | 82 | 0.63298 |
e2cd648d8bbfd92162b16a6659897baf2b5519cc | 2,631 | package com.ruoyi.web.controller.system;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.SysEvapsn;
import com.ruoyi.system.service.ISysEvapsnService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.util.List;
/**
* 用户信息
*
* @author ruoyi
*/
@Controller
@RequestMapping("/system/evapsn")
public class SysEvapsnController extends BaseController
{
private String prefix = "system/evapsn";
@Autowired
private ISysEvapsnService evapsnService;
@RequiresPermissions("system:evapsn:view")
@GetMapping()
public String evapsn()
{
return prefix + "/evapsn";
}
@RequiresPermissions("system:evapsn:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(SysEvapsn evapsn){
startPage();
List<SysEvapsn> list = evapsnService.selectEvapsnList(evapsn);
return getDataTable(list);
}
@PostMapping("/createqcode")
@ResponseBody
public AjaxResult createQcode(Long evaId){
System.out.println(evaId);
String loginid = evapsnService.selectLoginIdByEvaId(evaId).getLoginId();
System.out.println(loginid);
String url ="http://api.k780.com:88/?app=qr.get&data="+loginid+"&level=L&size=6";
SysEvapsn evapsn = new SysEvapsn();
evapsn.setEvaId(evaId);
evapsn.setQcode(url);
int i = evapsnService.setQcodeIntoEvapsn(evapsn);
logger.info("插入二维码是否成功:"+i);
JSONObject jsonObject = new JSONObject();
jsonObject.put("url",url);
jsonObject.put("status",i);
AjaxResult ajaxResult = AjaxResult.success(jsonObject);
return ajaxResult;
}
@GetMapping("/add")
public String add(ModelMap map){
return prefix + "/add";
}
@RequiresPermissions("system:evapsn:add")
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(@Valid SysEvapsn evapsn){
return toAjax(evapsnService.insertEvapsn(evapsn));
}
} | 29.561798 | 89 | 0.717598 |
cbeddea03bb1e0a64026761f0b24cac3d81e588a | 4,526 | package com.walkertribe.ian.protocol.core.world;
import com.walkertribe.ian.enums.ObjectType;
import com.walkertribe.ian.enums.OrdnanceType;
import com.walkertribe.ian.enums.TubeState;
import com.walkertribe.ian.iface.PacketReader;
import com.walkertribe.ian.iface.PacketWriter;
import com.walkertribe.ian.world.Artemis;
import com.walkertribe.ian.world.ArtemisObject;
import com.walkertribe.ian.world.ArtemisPlayer;
/**
* ObjectParser implementation for weapons console updates
* @author rjwut
*/
public class WeapParser extends AbstractObjectParser {
private enum Bit {
TORP_HOMING,
TORP_NUKE,
TORP_MINE,
TORP_EMP,
TORP_PSHOCK,
TORP_BEACON,
TORP_PROBE,
TORP_TAG,
TUBE_TIME_1,
TUBE_TIME_2,
TUBE_TIME_3,
TUBE_TIME_4,
TUBE_TIME_5,
TUBE_TIME_6,
TUBE_STATE_1,
TUBE_STATE_2,
TUBE_STATE_3,
TUBE_STATE_4,
TUBE_STATE_5,
TUBE_STATE_6,
TUBE_CONTENT_1,
TUBE_CONTENT_2,
TUBE_CONTENT_3,
TUBE_CONTENT_4,
TUBE_CONTENT_5,
TUBE_CONTENT_6
}
private static final int BIT_COUNT = Bit.values().length;
private static final Bit[] TORPEDOS = {
Bit.TORP_HOMING, Bit.TORP_NUKE, Bit.TORP_MINE, Bit.TORP_EMP,
Bit.TORP_PSHOCK, Bit.TORP_BEACON, Bit.TORP_PROBE, Bit.TORP_TAG
};
private static final Bit[] TUBE_TIMES = {
Bit.TUBE_TIME_1, Bit.TUBE_TIME_2, Bit.TUBE_TIME_3,
Bit.TUBE_TIME_4, Bit.TUBE_TIME_5, Bit.TUBE_TIME_6
};
private static final Bit[] TUBE_STATES = {
Bit.TUBE_STATE_1, Bit.TUBE_STATE_2, Bit.TUBE_STATE_3,
Bit.TUBE_STATE_4, Bit.TUBE_STATE_5, Bit.TUBE_STATE_6
};
private static final Bit[] TUBE_CONTENTS = {
Bit.TUBE_CONTENT_1, Bit.TUBE_CONTENT_2, Bit.TUBE_CONTENT_3,
Bit.TUBE_CONTENT_4, Bit.TUBE_CONTENT_5, Bit.TUBE_CONTENT_6
};
protected WeapParser() {
super(ObjectType.WEAPONS_CONSOLE);
}
@Override
public int getBitCount() {
return BIT_COUNT;
}
@Override
protected ArtemisPlayer parseImpl(PacketReader reader) {
int[] torps = new int[TORPEDOS.length];
boolean[] hasTubeTime = new boolean[Artemis.MAX_TUBES];
float[] tubeTimes = new float[Artemis.MAX_TUBES];
TubeState[] tubeStates = new TubeState[Artemis.MAX_TUBES];
byte[] tubeContents = new byte[Artemis.MAX_TUBES];
for (int i = 0; i < torps.length; i++) {
torps[i] = (reader.readByte(TORPEDOS[i], (byte) -1));
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
Bit bit = TUBE_TIMES[i];
if (reader.has(bit)) {
tubeTimes[i] = reader.readFloat(TUBE_TIMES[i]);
hasTubeTime[i] = true;
}
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
byte state = reader.readByte(TUBE_STATES[i], (byte) -1);
if (state != -1) {
tubeStates[i] = TubeState.values()[state];
}
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
tubeContents[i] = reader.readByte(TUBE_CONTENTS[i], (byte) -1);
}
ArtemisPlayer player = new ArtemisPlayer(reader.getObjectId(), ObjectType.WEAPONS_CONSOLE);
for (int i = 0; i < TORPEDOS.length; i++) {
player.setTorpedoCount(OrdnanceType.values()[i], torps[i]);
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
if (hasTubeTime[i]) {
player.setTubeCountdown(i, tubeTimes[i]);
}
player.setTubeState(i, tubeStates[i]);
player.setTubeContentsValue(i, tubeContents[i]);
}
return player;
}
@Override
public void write(ArtemisObject obj, PacketWriter writer) {
ArtemisPlayer player = (ArtemisPlayer) obj;
OrdnanceType[] ordTypes = OrdnanceType.values();
for (int i = 0; i < TORPEDOS.length; i++) {
OrdnanceType type = ordTypes[i];
writer.writeByte(TORPEDOS[i], (byte) player.getTorpedoCount(type), (byte) -1);
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
if (player.isTubeHasCountdown(i)) {
writer.writeObjectFloat(TUBE_TIMES[i], player.getTubeCountdown(i));
}
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
TubeState state = player.getTubeState(i);
byte stateByte = (byte) (state != null ? state.ordinal() : -1);
writer.writeByte(TUBE_STATES[i], stateByte, (byte) -1);
}
for (int i = 0; i < Artemis.MAX_TUBES; i++) {
byte type = player.getTubeContentsValue(i);
writer.writeByte(TUBE_CONTENTS[i], type, (byte) -1);
}
}
}
| 28.465409 | 99 | 0.639638 |
1978e92ea5edd175f07c7a576f73b63a443c2850 | 597 | import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class E9_CopyAPicture01 {
public static void main(String[] args) throws IOException {
FileInputStream inputStream = new FileInputStream(new File("D:\\FilesStreams\\Exercise\\cosmo.jpg"));
FileOutputStream outputStream = new FileOutputStream(new File("D:\\local.jpg"));
byte[] buffer = new byte[1024];
int read = 0;
while((read = inputStream.read(buffer)) > 0){
outputStream.write(buffer,0,read);
}
}
}
| 27.136364 | 109 | 0.670017 |
46484ea1620a5985850ac040aa84c6d670f21682 | 3,206 | package seedu.address.testutil;
import java.util.HashSet;
import java.util.Set;
import seedu.address.model.position.Description;
import seedu.address.model.position.Position;
import seedu.address.model.position.PositionName;
import seedu.address.model.position.PositionOpenings;
import seedu.address.model.position.Requirement;
import seedu.address.model.util.SampleDataUtil;
/**
* A utility class to help with building Position objects.
*/
public class PositionBuilder {
public static final String DEFAULT_POSITION_NAME = "Senior Front-End Engineer";
public static final String DEFAULT_DESCRIPTION = "Job is remote with great medical benefits!";
public static final String DEFAULT_POSITION_OPENINGS = "3";
// Identity fields
private PositionName positionName;
private Description description;
// Data fields
private PositionOpenings positionOpenings;
private Set<Requirement> requirements;
/**
* Creates a {@code PositionBuilder} with the default details.
*/
public PositionBuilder() {
positionName = new PositionName(DEFAULT_POSITION_NAME);
description = new Description(DEFAULT_DESCRIPTION);
positionOpenings = new PositionOpenings(DEFAULT_POSITION_OPENINGS);
requirements = new HashSet<>();
}
/**
* Initializes the PositionBuilder with the data of {@code positionToCopy}.
*/
public PositionBuilder(Position positionToCopy) {
positionName = positionToCopy.getPositionName();
description = positionToCopy.getDescription();
positionOpenings = positionToCopy.getPositionOpenings();
requirements = new HashSet<>(positionToCopy.getRequirements());
}
/**
* Sets the {@code PositionName} of the {@code Position} that we are building.
*/
public PositionBuilder withPositionName(String positionName) {
this.positionName = new PositionName(positionName);
return this;
}
/**
* Parses the {@code requirements} into a {@code Set<Requirement>} and set it to the {@code Position}
* that we are building.
*/
public PositionBuilder withRequirements() {
this.requirements = new HashSet<>();
return this;
}
/**
* Parses the {@code requirements} into a {@code Set<Requirement>} and set it to the {@code Position}
* that we are building.
*/
public PositionBuilder withRequirements(String... requirements) {
this.requirements = SampleDataUtil.getRequirementSet(requirements);
return this;
}
/**
* Sets the {@code Description} of the {@code Position} that we are building.
*/
public PositionBuilder withDescription(String description) {
this.description = new Description(description);
return this;
}
/**
* Sets the {@code PositionOpenings} of the {@code Position} that we are building.
*/
public PositionBuilder withPositionOpenings(String positionOpenings) {
this.positionOpenings = new PositionOpenings(positionOpenings);
return this;
}
public Position build() {
return new Position(positionName, description, positionOpenings, requirements);
}
}
| 33.395833 | 105 | 0.699314 |
92e948bf8431043fd929c8e20b45bf979ce29e6b | 961 | package com.desertkun.brainout.events;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.desertkun.brainout.data.active.ActiveData;
public class PhysicsContactEvent extends Event
{
public Vector2 speed;
public ActiveData activeData;
public PhysicsContactEvent()
{
this.speed = new Vector2();
}
@Override
public ID getID()
{
return ID.physicsContact;
}
private Event init(Vector2 speed, ActiveData activeData)
{
this.speed.set(speed);
this.activeData = activeData;
return this;
}
public static Event obtain(Vector2 speed, ActiveData activeData)
{
PhysicsContactEvent e = obtain(PhysicsContactEvent.class);
if (e == null) return null;
return e.init(speed, activeData);
}
@Override
public void reset()
{
this.speed.set(0, 0);
this.activeData = null;
}
}
| 21.355556 | 68 | 0.649324 |
ab8e913ac98185847907048667d1f78fab2a7338 | 2,265 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.cellar.bundle;
import java.io.Serializable;
/**
* Serializable wrapper to store and transport bundle state.
*/
public class BundleState implements Serializable {
public static final int UPDATE = 555;
private static final long serialVersionUID = 5933673686648413918L;
private long id;
private String name;
private String symbolicName;
private String version;
private String location;
private Integer startLevel;
private int status;
private byte[] data;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSymbolicName() {
return symbolicName;
}
public void setSymbolicName(String symbolicName) {
this.symbolicName = symbolicName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Integer getStartLevel() {
return startLevel;
}
public void setStartLevel(Integer startLevel) {
this.startLevel = startLevel;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data.clone();
}
}
| 22.425743 | 76 | 0.647682 |
16d420619089ac6b2a0b45d535dca21f1994b12c | 4,048 | package seedu.address.testutil.expenses;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import seedu.address.model.expenses.Expenses;
import seedu.address.model.expenses.ExpensesList;
/**
* A utility class containing a list of {@code expenses} objects to be used in tests.
*/
public class TypicalExpenses {
public static final String VALID_EMPLOYEEID_ALICE = "000001";
public static final String VALID_EXPENSES_AMOUNT_ALICE = "369.00";
public static final String VALID_TRAVEL_EXPENSES_ALICE = "123.00";
public static final String VALID_MEDICAL_EXPENSES_ALICE = "123.00";
public static final String VALID_MISCELLANEOUS_EXPENSES_ALICE = "123.00";
public static final Expenses ALICE_CLAIM = new ExpensesBuilder().withEmployeeId("000001")
.withExpensesAmount("123.00", "123.00", "123.00")
.withTravelExpenses("123.00").withMedicalExpenses("123.00").withMiscellaneousExpenses("123.00").build();
public static final Expenses BENSON_CLAIM = new ExpensesBuilder().withEmployeeId("000002")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
public static final Expenses CARL_CLAIM = new ExpensesBuilder().withEmployeeId("000003")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
public static final Expenses DANIEL_CLAIM = new ExpensesBuilder().withEmployeeId("000004")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
public static final Expenses ELLE_CLAIM = new ExpensesBuilder().withEmployeeId("000005")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
public static final Expenses FIONA_CLAIM = new ExpensesBuilder().withEmployeeId("000006")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
public static final Expenses GEORGE_CLAIM = new ExpensesBuilder().withEmployeeId("000007")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
// Manually added - Expenses's details found in {@code CommandTestUtil}
public static final Expenses BENSON_CLAIM_COPY = new ExpensesBuilder().withEmployeeId("000002")
.withExpensesAmount("123", "123", "123")
.withTravelExpenses("123").withMedicalExpenses("123").withMiscellaneousExpenses("123").build();
public static final Expenses AMY_CLAIM = new ExpensesBuilder().withEmployeeId("000010")
.withExpensesAmount("234", "345", "456")
.withTravelExpenses("234").withMedicalExpenses("345").withMiscellaneousExpenses("456").build();
public static final Expenses BOB_CLAIM = new ExpensesBuilder().withEmployeeId("000011")
.withExpensesAmount("345", "456", "567")
.withTravelExpenses("345").withMedicalExpenses("456").withMiscellaneousExpenses("567").build();
public static final String KEYWORD_MATCHING_MEIER = "Meier"; // A keyword that matches MEIER
private TypicalExpenses() {} // prevents instantiation
/**
* Returns an {@code ExpensesList} with all the typical expenses.
*/
public static ExpensesList getTypicalExpensesList() {
ExpensesList el = new ExpensesList();
for (Expenses expenses : getTypicalExpenses()) {
el.addExpenses(expenses);
}
return el;
}
public static List<Expenses> getTypicalExpenses() {
return new ArrayList<>(Arrays.asList(ALICE_CLAIM, BENSON_CLAIM, CARL_CLAIM, DANIEL_CLAIM,
ELLE_CLAIM, FIONA_CLAIM, GEORGE_CLAIM));
}
}
| 54.702703 | 116 | 0.702816 |
14ee89d4d6840e8f941d13ff2fb4b55ffacff86e | 719 | package com.astudio.sportsclubdemo.service;
import com.astudio.sportsclubdemo.entity.Drink;
import com.astudio.sportsclubdemo.entity.DrinkSales;
import com.astudio.sportsclubdemo.repository.DrinkRepository;
import com.astudio.sportsclubdemo.repository.DrinkSalesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DrinkSalesServices {
@Autowired
private DrinkSalesRepository drinkRepository;
public DrinkSales addSales(DrinkSales drinkSales){
return drinkRepository.save(drinkSales);
}
public List<DrinkSales> getAll(){
return drinkRepository.findAll();
}
}
| 27.653846 | 66 | 0.798331 |
ac2cbe9649d884ed9746a462a23570527077efec | 679 | package tv.nexx.flutter.android.estd.functional;
class Right<T, R> implements Either<T, R> {
private final R value;
Right(R value) {
this.value = value;
}
@Override
public <U> Either<T, U> map(Function<R, U> function) {
return new Right<>(function.apply(value));
}
@Override
public <U> Either<T, U> flatMap(Function<R, Either<T, U>> function) {
return function.apply(value);
}
@Override
public <U> U fold(Function<T, U> left, Function<R, U> right) {
return right.apply(value);
}
@Override
public void consume(Consumer<T> left, Consumer<R> right) {
right.accept(value);
}
}
| 22.633333 | 73 | 0.599411 |
6a792d6a84c5fc08d30ebb2e1d066ef344e548d6 | 1,046 | package com.numerx.formboot.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.numerx.formboot.**.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//设置请求的页面大于最大页后操作,true调回到首页,false继续请求 默认false
//paginationInterceptor.setOverflow(false);
//设置最大单页限制数量,默认500条,-1不受限制
//paginationInterceptor.setLimit(500);
//开启count的join优化,只针对部分leftjoin
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
| 40.230769 | 94 | 0.826004 |
127cd3f79c488c0157adc60187f7b8668e108d78 | 4,562 | /*
* Copyright (c) 2009-@year@. The GUITAR group at the University of
* Maryland. Names of owners of this group may be obtained by sending
* an e-mail to [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package edu.umd.cs.guitar.replayer;
import java.util.List;
import java.io.IOException;
import edu.umd.cs.guitar.event.GEvent;
import edu.umd.cs.guitar.model.GApplication;
import edu.umd.cs.guitar.model.GObject;
import edu.umd.cs.guitar.model.GWindow;
import edu.umd.cs.guitar.model.data.ComponentType;
import edu.umd.cs.guitar.model.data.PropertyType;
/**
* Monitor the Replayer's behavior. This component handles platform-specific
* issues with the Replayer.
*
* @author <a href="mailto:[email protected]"> Bao Nguyen </a>
*
*/
public abstract class GReplayerMonitor
{
public GApplication application;
boolean isUseReg = false;
/**
* @return the isUseReg
*/
public boolean isUseReg() {
return isUseReg;
}
/**
* @param isUseReg the isUseReg to set
*/
public void setUseReg(boolean isUseReg) {
this.isUseReg = isUseReg;
}
/**
* Connect to application. This task includes start up the application if
* needed
*
*/
public abstract void connectToApplication();
/**
* Set up the replayer environment before the execution.
*/
public abstract void setUp();
/**
* Clean up the replayer environment after the execution.
*/
public abstract void cleanUp();
/**
*
* Find a window from its ID. This method should wait until a window is
* retrieved or time out (i.e. not found).
*
* <p>
*
* @param sWindowTitle
* @return Gwindow
*/
public abstract GWindow getWindow(String sWindowTitle);
/**
*
* Wait until a window with the given image appears.
*
* @param sWindowTitle String window title of window to look for
* @param sImageFilename String filename of image file
* @return Gwindow
*/
public abstract GWindow waitForWindow(String sWindowTitle,
String sImageFilename)
throws IOException;
/**
* Write a matched set of ripped and replayed components
* to log space
*/
public abstract void writeMatchedComponents(GObject replayComponent,
String sRipImageFilePath)
throws IOException;
/**
* Get an action from its name
*
* <p>
*
* @param sActionName
* @return GEvent
*/
public abstract GEvent getAction(String sActionName);
/**
* Get parameters from from action name
*
* <p>
*
* @param action
* @return java.lang.Object
*/
public abstract Object getArguments(String action);
/**
*
* Select a subset of properties for component GUI information to work as
* its identifier.
*
* <p>
*
* @param comp
*
* @return PropertyType
*/
public abstract List<PropertyType> selectIDProperties(ComponentType comp);
/**
* The abstract representing a subject under test (SUT) application in GUITAR.
* @return the application
*/
public GApplication getApplication() {
return application;
}
/**
* Delay for a <code> delay </code> milliseconds
*
* @param delay
*/
abstract public void delay(int delay);
} // End of class
| 27.98773 | 82 | 0.648838 |
6e20f1384fb6757bf92ff08a5730b75d1198c6da | 281 | package algorithms.trie;
public class TrieNode {
public boolean isWord;
public TrieNode[] children;
public TrieNode() {
children = new TrieNode[26];
for (int i=0; i < 26; i++){
children[i] = null;
}
isWord = false;
}
}
| 18.733333 | 36 | 0.540925 |
4687754044e818646a0a7c92b468e0588ec03829 | 4,937 | /*
* Copyright (C) 2021 Authlete, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.authlete.common.dto;
import java.io.Serializable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Grant.
*
* <p>
* This class holds the same information as the response from the Grant
* Management Endpoint on the grant management action 'query' does.
* </p>
*
* @see <a href="https://openid.net/specs/fapi-grant-management.html"
* >Grant Management for OAuth 2.0</a>
*
* @since 3.1
*/
public class Grant implements Serializable
{
private static final long serialVersionUID = 1L;
private GrantScope[] scopes;
private String[] claims;
private AuthzDetails authorizationDetails;
/**
* Get the grant scopes.
*
* @return
* The grant scopes.
*/
public GrantScope[] getScopes()
{
return scopes;
}
/**
* Set the grant scopes.
*
* @param scopes
* The grant scopes.
*
* @return
* {@code this} object.
*/
public Grant setScopes(GrantScope[] scopes)
{
this.scopes = scopes;
return this;
}
/**
* Get the claims.
*
* @return
* The claims
*/
public String[] getClaims()
{
return claims;
}
/**
* Set the claims
*
* @param claims
* The claims
*
* @return
* {@code this} object.
*/
public Grant setClaims(String[] claims)
{
this.claims = claims;
return this;
}
/**
* Get the authorization details.
*
* @return
* The authorization details.
*/
public AuthzDetails getAuthorizationDetails()
{
return authorizationDetails;
}
/**
* Set the authorization details.
*
* @param details
* The authorization details.
*
* @return
* {@code this} object.
*/
public Grant setAuthorizationDetails(AuthzDetails details)
{
this.authorizationDetails = details;
return this;
}
/**
* Convert this instance into a JSON string.
*
* <p>
* The returned string contains a JSON object which has {@code "scopes"},
* {@code "claims"} and {@code "authorization_details"} as top-level
* properties.
* </p>
*
* @return
* A JSON string.
*/
public String toJson()
{
return createSerializer().toJson(this);
}
/**
* Build a {@code Grant} instance from a JSON string.
*
* <p>
* The following is an example of input JSON.
* </p>
*
* <pre>
* {
* "scopes":[
* {
* "scope":"contacts read write",
* "resource":[
* "https://rs.example.com/api"
* ]
* },
* {
* "scope":"openid"
* }
* ],
* "claims":[
* "given_name",
* "nickname",
* "email",
* "email_verified"
* ],
* "authorization_details":[
* {
* "type":"account_information",
* "actions":[
* "list_accounts",
* "read_balances",
* "read_transactions"
* ],
* "locations":[
* "https://example.com/accounts"
* ]
* }
* ]
* }
* </pre>
*
* @param json
* A JSON string.
*
* @return
* A {@code Grant} instance built from the input JSON.
*/
public static Grant fromJson(String json)
{
if (json == null)
{
return null;
}
return createDeserializer().fromJson(json, Grant.class);
}
/**
* Create a serializer for {@link Grant}.
*/
private static Gson createSerializer()
{
return new GsonBuilder()
.registerTypeAdapter(
Grant.class, new GrantSerializer())
.create();
}
/**
* Create a deserializer for {@link Grant}.
*/
private static Gson createDeserializer()
{
return new GsonBuilder()
.registerTypeAdapter(
Grant.class, new GrantDeserializer())
.create();
}
}
| 21.098291 | 77 | 0.514888 |
8836a0e353ee5ff35481f2e9d700e7344b2ee893 | 5,142 | /*
* Copyright (c) 2022 nosqlbench
*
* 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 io.nosqlbench.engine.core.script;
import com.codahale.metrics.*;
import io.nosqlbench.engine.api.activityapi.core.Activity;
import io.nosqlbench.engine.api.activityapi.core.ActivityType;
import io.nosqlbench.engine.api.activityimpl.ActivityDef;
import io.nosqlbench.engine.api.metrics.ActivityMetrics;
import io.nosqlbench.engine.core.lifecycle.ActivityTypeLoader;
import io.nosqlbench.engine.core.metrics.PolyglotMetricRegistryBindings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Find the metrics associated with an activity type by instantiating the activity in idle mode.
*/
public class MetricsMapper {
private final static Logger logger = LogManager.getLogger(MetricsMapper.class);
private static final Set<Class<?>> metricsElements = new HashSet<>() {{
add(Meter.class);
add(Counter.class);
add(Timer.class);
add(Histogram.class);
add(Gauge.class);
add(Snapshot.class);
}};
private static final Predicate<Method> isSimpleGetter = method ->
method.getName().startsWith("get")
&& method.getParameterCount() == 0
&& !method.getName().equals("getClass");
private static final Function<Method, String> getPropertyName = method ->
{
String mName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
return mName;
};
public static String metricsDetail(String activitySpec) {
//StringBuilder metricsDetail = new StringBuilder();
List<String> metricsDetails = new ArrayList<>();
ActivityDef activityDef = ActivityDef.parseActivityDef(activitySpec);
logger.info("introspecting metric names for " + activitySpec);
Optional<ActivityType> activityType = new ActivityTypeLoader().load(activityDef);
if (!activityType.isPresent()) {
throw new RuntimeException("Activity type '" + activityDef.getActivityType() + "' does not exist in this runtime.");
}
Activity activity = activityType.get().getAssembledActivity(activityDef, new HashMap<>());
PolyglotMetricRegistryBindings nashornMetricRegistryBindings = new PolyglotMetricRegistryBindings(ActivityMetrics.getMetricRegistry());
activity.initActivity();
activity.getInputDispenserDelegate().getInput(0);
activity.getActionDispenserDelegate().getAction(0);
activity.getMotorDispenserDelegate().getMotor(activityDef, 0);
Map<String, Metric> metricMap = nashornMetricRegistryBindings.getMetrics();
// Map<String, Map<String,String>> details = new LinkedHashMap<>();
for (Map.Entry<String, Metric> metricEntry : metricMap.entrySet()) {
String metricName = metricEntry.getKey();
Metric metricValue = metricEntry.getValue();
Map<String, String> getterSummary = getGetterSummary(metricValue);
// details.put(metricName,getterSummary);
List<String> methodDetails = getterSummary.entrySet().stream().map(
es -> metricName + es.getKey() + " " + es.getValue()
).collect(Collectors.toList());
methodDetails.sort(String::compareTo);
String getterText = methodDetails.stream().collect(Collectors.joining("\n"));
metricsDetails.add(metricName + "\n" + getterText);
}
// return details;
return metricsDetails.stream().collect(Collectors.joining("\n"));
}
private static Map<String, String> getGetterSummary(Object o) {
return getGetterSummary(new HashMap<>(), "", o.getClass());
}
private static Map<String, String> getGetterSummary(Map<String, String> accumulator, String name, Class<?> objectType) {
Arrays.stream(objectType.getMethods())
.filter(isSimpleGetter)
.forEach(m -> {
if (m.getReturnType().isPrimitive()) {
accumulator.put(name + "." + getPropertyName.apply(m), m.getReturnType().getSimpleName());
} else {
String fullName = name + "." + getPropertyName.apply(m);
getGetterSummary(accumulator, fullName, m.getReturnType());
}
});
return accumulator;
}
}
| 42.495868 | 143 | 0.672112 |
08d6c8031e097f16f66aa57a01e814279909049b | 232 | package com.openthinks.demo.data.tree;
public interface TreeInterface<T> {
public T getRootData();
public int getHeight();
public int getNumberOfNodes();
public boolean isEmpty();
public void clear();
}
| 15.466667 | 39 | 0.676724 |
f38a25078ed335ab16efd5c4540f32ba62d37faa | 8,907 | /*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* NOTICE
*
* This software was produced for the U. S. Government
* under Basic Contract No. FA8702-17-C-0001, and is
* subject to the Rights in Noncommercial Computer Software
* and Noncommercial Computer Software Documentation
* Clause 252.227-7014 (MAY 2013)
*
* (c)2016-2017 The MITRE Corporation. All Rights Reserved.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
package org.mitre.tangerine.reasoner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class FLogicKB {
public int lastAssertionIdx; // index of last triple inserted or found
public Stack<Integer> freeKBIdx = new Stack<Integer>(); // list of free N_ary objects
public List<Integer> inferredIdx = new ArrayList<Integer>(); // list of assertions that were inferred
private StringIndex predIndex = new StringIndex();
private StringIndex[] argsIndex = new StringIndex[FLogicConstants.MAX_ARITY]; // indices into the assertions
public List<N_ary> kb = new ArrayList<N_ary>(); // collection of assertions
public List<N_ary> fts = new ArrayList<N_ary>(); // free text search assertions
public JSONParser jparser = new JSONParser();
static Logger logger = Logger.getLogger(FLogicKB.class);
public FLogicKB() {
for (int i = 0; i < FLogicConstants.MAX_ARITY; i++) {
argsIndex[i] = new StringIndex();
}
}
public void release() {
jparser=null;
clearKB();
freeKBIdx=null;
inferredIdx=null;
predIndex.release();
predIndex=null;
for(int i=0; i<FLogicConstants.MAX_ARITY; i++) {
argsIndex[i].release();
argsIndex[i]=null;
}
argsIndex=null;
kb=null;
}
public void clearKB() {
int i;
// clear fts
for(i=0; i<fts.size(); i++) {
N_ary na = kb.get(i);
na = null;
}
fts.clear();
// clear the kb
for(i=0; i<kb.size(); i++) {
N_ary na = kb.get(i);
na = null;
}
kb.clear();
// clear the indices
getPredIndex().clear();
for (i = 0; i < FLogicConstants.MAX_ARITY; i++) {
getArgsIndex()[i].clear();
}
freeKBIdx.clear();
inferredIdx.clear();
}
public void addAssertion(String pred, int arity, String args[], byte recordType) {
addAssertion(pred, arity, args, FLogicConstants.DEFAULT_GRAPH, "->", recordType);
}
public void addAssertion(String pred, int arity, String args[], String graph, byte recordType) {
addAssertion(pred, arity, args, graph, "->", recordType);
}
public void addAssertion(String pred, int arity, String args[], String graph, String inhSem, byte recordType) {
N_ary na;
int idx;
String attrs=null, prov=null;
// Free Text Search results
if(pred.equals("FreeTextSearch") || pred.equals("RegexTextSearch")) {
na = new N_ary();
na.setGraph(graph);
na.setPred(pred);
for (int i = 0; i < arity && i < FLogicConstants.MAX_ARITY; i++) na.getArgs()[i] = args[i];
na.setArity(arity);
na.setRecordType(recordType);
na.setInhSem(FLogicConstants.NOT_INHERITABLE);
fts.add(na);
return;
}
if(arity > 2) {
int origArity = arity;
for(int i=2; i<origArity; i++) {
if(args[i].startsWith("{\"T\":{")) {
attrs = args[i]; // attributes
arity--;
} else if(args[i].startsWith("{\"V\":{")) {
prov = args[i]; // provenance
arity--;
}
}
}
// avoid adding duplicates
if (attrs==null && assertionExists(pred, arity, args)) return;
if (freeKBIdx.size() == 0) {
na = new N_ary(); // create n-ary
idx = kb.size(); // save assertion
kb.add(na);
} else { // re-use existing n_ary that was previously freed
idx = freeKBIdx.pop();
na = kb.get(idx);
}
na.setGraph(graph);
na.setPred(pred);
for (int i = 0; i < arity && i < FLogicConstants.MAX_ARITY; i++) {
na.getArgs()[i] = args[i];
}
na.setArity(arity);
na.setRecordType(recordType);
if (inhSem.equals("->")) {
na.setInhSem(FLogicConstants.NOT_INHERITABLE);
} else if (inhSem.equals("*m->")) {
na.setInhSem(FLogicConstants.MONOTONIC);
} else {
na.setInhSem(FLogicConstants.NON_MONOTONIC);
}
na.clearAttributes();
if(attrs != null) { // parse attributes
try {
JSONObject Attrs = (JSONObject) jparser.parse(attrs);
JSONObject T = (JSONObject) Attrs.get("T");
if(T!=null)
for(Object key : T.keySet()) {
String attr_name = (String) key;
String attr_val = (String) T.get(key);
na.setAttribute(attr_name, attr_val);
}
} catch (java.lang.ClassCastException e) {
;
} catch (Exception e) {
e.printStackTrace();
}
}
lastAssertionIdx = idx;
// index assertion
getPredIndex().addToIndex(pred, idx);
for (int i = 0; i < arity && i < FLogicConstants.MAX_ARITY; i++) {
getArgsIndex()[i].addToIndex(args[i], idx);
}
if (recordType == FLogicConstants.INFERRED_ASSERTION
|| recordType == FLogicConstants.RULE_INFERENCE) {
inferredIdx.add(idx);
} else {
delInferred();
}
}
public N_ary getAssertion(int idx, String pred) {
N_ary na;
if(pred.equals("FreeTextSearch") || pred.equals("RegexTextSearch")) na = fts.get(idx);
else na = kb.get(idx);
return na;
}
public N_ary getAssertion(int idx) {
N_ary na;
na = kb.get(idx);
return na;
}
public void delAssertion(String pred, int arity, String args[]) {
// does this assertion exist
if (!assertionExists(pred, arity, args)) {
return;
}
// lastAssertionIdx contains the location of this assertion
delAssertion(lastAssertionIdx);
// some cached inferences are now no longer valid
// clear all inferred assertions since there is no way to determine
// which inferred assertions are affected by the deletion
delInferred();
}
public void delAssertion(int idx) {
boolean erase;
N_ary assrt;
assrt = kb.get(idx);
// save the position of the assertion
freeKBIdx.push(idx);
// remove from the predicate index
getPredIndex().deleteIndexValue(assrt.getPred(), idx);
for (int i = 0; i < FLogicConstants.MAX_ARITY; i++) {
getArgsIndex()[i].deleteIndexValue(assrt.getArgs()[i], idx);
}
}
public void delInferred() {
for (int idx : inferredIdx) {
delAssertion(idx);
}
inferredIdx.clear();
}
public boolean assertionExists(String pred, int arity, String args[]) {
N_ary na;
int idx, matchCnt;
// use the 'sub' index to search
HashSet<Integer> argList = getArgsIndex()[0].getIndexValues(args[0]);
if (argList != null) {
for (Iterator it = getArgsIndex()[0].getIndexValues(args[0]).iterator(); it.hasNext();) {
matchCnt = 1;
idx = (Integer) it.next();
na = kb.get(idx);
if (na.getArity() == arity && na.getPred().equals(pred)) {
for (int i = 1; i < arity; i++) {
if (na.getArgs()[i].equals(args[i])) {
matchCnt++;
}
}
if (matchCnt == arity) {
lastAssertionIdx = idx;
return true;
}
}
}
}
return false;
}
/**
* @return the predIndex
*/
public StringIndex getPredIndex() {
return predIndex;
}
/**
* @return the argsIndex
*/
public StringIndex[] getArgsIndex() {
return argsIndex;
}
}
| 31.810714 | 115 | 0.520939 |
23e676a8e253686984ceec034e5f4e692be4759a | 4,115 | /**
* Copyright [2020] JD.com, Inc. TIG. ChubaoStream team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joyqueue.nsr.composition.service;
import org.joyqueue.domain.DataCenter;
import org.joyqueue.nsr.composition.config.CompositionConfig;
import org.joyqueue.nsr.service.internal.DataCenterInternalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* CompositionDataCenterInternalService
* author: gaohaoxiang
* date: 2019/8/12
*/
public class CompositionDataCenterInternalService implements DataCenterInternalService {
protected final Logger logger = LoggerFactory.getLogger(CompositionDataCenterInternalService.class);
private CompositionConfig config;
private DataCenterInternalService igniteDataCenterService;
private DataCenterInternalService journalkeeperDataCenterService;
public CompositionDataCenterInternalService(CompositionConfig config, DataCenterInternalService igniteDataCenterService,
DataCenterInternalService journalkeeperDataCenterService) {
this.config = config;
this.igniteDataCenterService = igniteDataCenterService;
this.journalkeeperDataCenterService = journalkeeperDataCenterService;
}
@Override
public DataCenter getById(String id) {
if (config.isReadIgnite()) {
return igniteDataCenterService.getById(id);
} else {
try {
return journalkeeperDataCenterService.getById(id);
} catch (Exception e) {
logger.error("getById exception, id: {}", id, e);
return igniteDataCenterService.getById(id);
}
}
}
@Override
public DataCenter add(DataCenter dataCenter) {
DataCenter result = null;
if (config.isWriteIgnite()) {
result = igniteDataCenterService.add(dataCenter);
}
if (config.isWriteJournalkeeper()) {
try {
journalkeeperDataCenterService.add(dataCenter);
} catch (Exception e) {
logger.error("add journalkeeper exception, params: {}", dataCenter, e);
}
}
return result;
}
@Override
public DataCenter update(DataCenter dataCenter) {
DataCenter result = null;
if (config.isWriteIgnite()) {
result = igniteDataCenterService.update(dataCenter);
}
if (config.isWriteJournalkeeper()) {
try {
journalkeeperDataCenterService.update(dataCenter);
} catch (Exception e) {
logger.error("update journalkeeper exception, params: {}", dataCenter, e);
}
}
return result;
}
@Override
public void delete(String id) {
if (config.isWriteIgnite()) {
igniteDataCenterService.delete(id);
}
if (config.isWriteJournalkeeper()) {
try {
journalkeeperDataCenterService.delete(id);
} catch (Exception e) {
logger.error("delete journalkeeper exception, params: {}", id, e);
}
}
}
@Override
public List<DataCenter> getAll() {
if (config.isReadIgnite()) {
return igniteDataCenterService.getAll();
} else {
try {
return journalkeeperDataCenterService.getAll();
} catch (Exception e) {
logger.error("getAll exception", e);
return igniteDataCenterService.getAll();
}
}
}
}
| 34.291667 | 124 | 0.639611 |
a3db0f1fff520f1d163d6026850b9f3cec5e1553 | 567 | package com.insilicokdd.gui;
import java.awt.*;
public class LayoutPlot {
public void addobjects(Component componente, Container yourcontainer, GridBagLayout layout, GridBagConstraints gbc, int gridx, int gridy, double weightx, double weighty, int gridwidth, int gridheigth){
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheigth;
layout.setConstraints(componente, gbc);
yourcontainer.add(componente);
}
}
| 29.842105 | 205 | 0.686067 |
b4c9b1159d934aebd834c43d320566b45ca8e1b6 | 5,557 | /**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.demos;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.openimaj.feature.local.list.LocalFeatureList;
import org.openimaj.feature.local.list.MemoryLocalFeatureList;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.analysis.pyramid.SimplePyramid;
import org.openimaj.image.feature.dense.gradient.dsift.ApproximateDenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.ByteDSIFTKeypoint;
import org.openimaj.image.feature.dense.gradient.dsift.DenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.FloatDSIFTKeypoint;
import org.openimaj.io.IOUtils;
import org.openimaj.util.function.Operation;
import org.openimaj.util.parallel.Parallel;
public class FVFWDSift {
static interface DSFactory {
DenseSIFT create();
}
private static void extractPDSift(final File indir, final File outDir, final DSFactory factory) throws IOException
{
Parallel.forEach(Arrays.asList(indir.listFiles()), new Operation<File>() {
@Override
public void perform(File dir) {
try {
if (!dir.isDirectory())
return;
final DenseSIFT sift = factory.create();
for (final File imgfile : dir.listFiles()) {
if (!imgfile.getName().endsWith(".jpg"))
continue;
final File outfile = new File(outDir, imgfile.getAbsolutePath().replace(indir.getAbsolutePath(),
"").replace(".jpg", ".bin"));
outfile.getParentFile().mkdirs();
final FImage image = ImageUtilities.readF(imgfile);
final SimplePyramid<FImage> pyr = new SimplePyramid<FImage>((float) Math.sqrt(2), 5);
pyr.processImage(image);
final LocalFeatureList<FloatDSIFTKeypoint> allKeys = new MemoryLocalFeatureList<FloatDSIFTKeypoint>();
for (final FImage img : pyr) {
sift.analyseImage(img);
final double scale = 160.0 / img.height;
final LocalFeatureList<ByteDSIFTKeypoint> kps = sift.getByteKeypoints();
for (final ByteDSIFTKeypoint kp : kps) {
kp.x *= scale;
kp.y *= scale;
final float[] descriptor = new float[128];
float sumsq = 0;
// reorder to make comparision with matlab
// easier; add offset
for (int i = 0; i < 16; i++) {
descriptor[i * 8] = kp.descriptor[i * 8] + 128;
descriptor[i * 8 + 1] = kp.descriptor[i * 8 + 7] + 128;
descriptor[i * 8 + 2] = kp.descriptor[i * 8 + 6] + 128;
descriptor[i * 8 + 3] = kp.descriptor[i * 8 + 5] + 128;
descriptor[i * 8 + 4] = kp.descriptor[i * 8 + 4] + 128;
descriptor[i * 8 + 5] = kp.descriptor[i * 8 + 3] + 128;
descriptor[i * 8 + 6] = kp.descriptor[i * 8 + 2] + 128;
descriptor[i * 8 + 7] = kp.descriptor[i * 8 + 1] + 128;
}
// rootsift
for (int i = 0; i < 128; i++) {
descriptor[i] = (float) Math.sqrt(descriptor[i]);
sumsq += descriptor[i] * descriptor[i];
}
sumsq = (float) Math.sqrt(sumsq);
final float norm = 1f / Math.max(Float.MIN_NORMAL, sumsq);
for (int i = 0; i < 128; i++) {
descriptor[i] *= norm;
}
allKeys.add(new FloatDSIFTKeypoint(kp.x, kp.y, descriptor, kp.energy));
}
}
IOUtils.writeBinary(outfile, allKeys);
System.out.println(imgfile + " " + allKeys.size());
}
} catch (final Exception e) {
e.printStackTrace();
System.err.println(e);
}
}
});
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
final DSFactory factory = new DSFactory() {
@Override
public DenseSIFT create() {
return new ApproximateDenseSIFT(1, 6);
}
};
extractPDSift(
new File("/Volumes/Raid/face_databases/lfw-centre-affine-matlab/"),
new File("/Volumes/Raid/face_databases/lfw-centre-affine-pdsift/"),
factory);
}
}
| 37.046667 | 115 | 0.679863 |
0704d5a1bde09c294934dfb7f48fed66555fb785 | 9,227 | package gg.projecteden.nexus.features.store.perks;
import com.destroystokyo.paper.event.player.PlayerPickupExperienceEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerXpGainEvent;
import fr.minuskube.inv.ClickableItem;
import fr.minuskube.inv.SmartInventory;
import fr.minuskube.inv.content.InventoryContents;
import fr.minuskube.inv.content.InventoryProvider;
import gg.projecteden.nexus.features.menus.MenuUtils;
import gg.projecteden.nexus.framework.commands.models.CustomCommand;
import gg.projecteden.nexus.framework.commands.models.annotations.Aliases;
import gg.projecteden.nexus.framework.commands.models.annotations.Arg;
import gg.projecteden.nexus.framework.commands.models.annotations.Confirm;
import gg.projecteden.nexus.framework.commands.models.annotations.Path;
import gg.projecteden.nexus.framework.commands.models.annotations.Permission;
import gg.projecteden.nexus.framework.commands.models.annotations.Switch;
import gg.projecteden.nexus.framework.commands.models.events.CommandEvent;
import gg.projecteden.nexus.models.boost.BoostConfig;
import gg.projecteden.nexus.models.boost.BoostConfig.DiscordHandler;
import gg.projecteden.nexus.models.boost.BoostConfigService;
import gg.projecteden.nexus.models.boost.Boostable;
import gg.projecteden.nexus.models.boost.Booster;
import gg.projecteden.nexus.models.boost.Booster.Boost;
import gg.projecteden.nexus.models.boost.BoosterService;
import gg.projecteden.nexus.models.costume.Costume;
import gg.projecteden.nexus.utils.ItemBuilder;
import gg.projecteden.nexus.utils.JsonBuilder;
import gg.projecteden.nexus.utils.PlayerUtils;
import gg.projecteden.nexus.utils.PlayerUtils.Dev;
import gg.projecteden.nexus.utils.StringUtils;
import gg.projecteden.nexus.utils.Tasks;
import gg.projecteden.nexus.utils.Utils;
import gg.projecteden.utils.TimeUtils.TickTime;
import gg.projecteden.utils.TimeUtils.Timespan;
import gg.projecteden.utils.TimeUtils.Timespan.FormatType;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
@Aliases("boost")
@NoArgsConstructor
public class BoostsCommand extends CustomCommand implements Listener {
private final BoostConfigService configService = new BoostConfigService();
private final BoostConfig config = configService.get0();
private final BoosterService service = new BoosterService();
private Booster booster;
public BoostsCommand(@NonNull CommandEvent event) {
super(event);
if (isPlayerCommandEvent())
booster = service.get(player());
}
static {
Tasks.repeatAsync(0, 5, () -> {
BoostConfig config = BoostConfig.get();
for (Boostable boostable : config.getBoosts().keySet()) {
Boost boost = config.getBoost(boostable);
if (boost.isExpired())
boost.expire();
}
});
Tasks.repeatAsync(TickTime.MINUTE, TickTime.MINUTE, () -> {
BoostConfig config = BoostConfig.get();
if (config.getBoosts().isEmpty())
return;
DiscordHandler.editMessage();
});
}
@Path("[page]")
void list(@Arg("1") int page) {
if (config.getBoosts().isEmpty())
error("There are no active server boosts");
line();
send(PREFIX + "Active server boosts");
Map<Boostable, LocalDateTime> timeLeft = new HashMap<>() {{
for (Boostable boostable : config.getBoosts().keySet())
put(boostable, config.getBoost(boostable).getExpiration());
}};
BiFunction<Boostable, String, JsonBuilder> formatter = (type, index) -> {
Boost boost = config.getBoost(type);
return json(" &6" + boost.getMultiplierFormatted() + " &e" + camelCase(type) + " &7- " + boost.getNickname() + " &3(" + boost.getTimeLeft() + ")");
};
paginate(Utils.sortByValueReverse(timeLeft).keySet(), formatter, "/boosts", page);
}
@Path("menu")
void menu() {
if (booster.getNonExpiredBoosts().isEmpty())
error("You do not have any boosts! Purchase them at &e" + Costume.STORE_URL);
new BoostMenu().open(player());
}
@Path("give <player> <type> <multiplier> <seconds> [amount]")
void give(Booster booster, Boostable type, double multiplier, Timespan seconds, @Arg("1") int amount) {
for (int i = 0; i < amount; i++)
booster.add(type, multiplier, seconds.getOriginal());
service.save(booster);
send(PREFIX + "Gave " + amount + " " + plural(camelCase(type) + " boost", amount) + " to " + booster.getNickname());
}
@Confirm
@Permission("group.staff")
@Path("cancel <type> [--refund]")
void cancel(Boostable type, @Switch boolean refund) {
if (!config.hasBoost(type))
error("There is no active " + camelCase(type) + " boost");
Boost boost = config.getBoost(type);
boost.cancel();
if (refund)
boost.getBooster().add(type, boost.getMultiplier(), boost.getDurationLeft());
service.save(boost.getBooster());
send(PREFIX + "Cancelled " + boost.getNickname() + "'s " + boost.getMultiplierFormatted() + " "
+ camelCase(type) + " boost" + (refund ? " and refunded the time left" : ""));
}
@Confirm
@Permission("group.seniorstaff")
@Path("start <type> <multiplier> <duration>")
void start(Boostable type, double multiplier, int duration) {
if (config.hasBoost(type))
cancel(type, true);
Booster booster = service.get(Dev.KODA.getUuid());
Boost boost = booster.add(type, multiplier, duration);
boost.activate();
service.save(booster);
send(PREFIX + "Started a server " + boost.getMultiplierFormatted() + " " + camelCase(type)
+ " boost for " + Timespan.of(boost.getDuration()).format(FormatType.LONG));
}
@AllArgsConstructor
private static class BoostMenu extends MenuUtils implements InventoryProvider {
private final Boostable type;
private final BoostMenu previousMenu;
@Override
public void open(Player player, int page) {
SmartInventory.builder()
.provider(this)
.title("Boosts")
.size(6, 9)
.build()
.open(player, page);
}
public BoostMenu() {
this(null);
}
public BoostMenu(Boostable type) {
this.type = type;
this.previousMenu = null;
}
@Override
public void init(Player player, InventoryContents contents) {
final BoostConfigService configService = new BoostConfigService();
final BoostConfig config = configService.get0();
final BoosterService service = new BoosterService();
final Booster booster = service.get(player);
if (previousMenu == null)
addCloseItem(contents);
else
addBackItem(contents, e -> previousMenu.open(player));
List<ClickableItem> items = new ArrayList<>();
if (type == null)
for (Boostable boostable : Boostable.values()) {
int boosts = booster.getNonExpiredBoosts(boostable).size();
if (boosts > 0) {
ItemBuilder item = boostable.getDisplayItem().lore("&3" + StringUtils.plural(boosts + " boost", boosts) + " available");
items.add(ClickableItem.from(item.build(), e -> new BoostMenu(boostable, this).open(player)));
}
}
else
for (Boost boost : booster.get(type)) {
ItemBuilder item = boost.getDisplayItem();
if (boost.isActive()) {
item.lore("", "&6&lActive &7- &e" + boost.getTimeLeft());
contents.set(0, 4, ClickableItem.empty(item.build()));
} else if (boost.canActivate()) {
if (config.hasBoost(boost.getType())) {
item.lore("", "&cCannot activate, another boost is already active");
items.add(ClickableItem.empty(item.build()));
} else {
item.lore("&3Duration: &e" + Timespan.of(boost.getDuration()).format(FormatType.LONG), "", "&eClick to activate");
items.add(ClickableItem.from(item.build(), e -> ConfirmationMenu.builder()
.title("Activate " + StringUtils.camelCase(boost.getType()) + " Boost")
.onConfirm(e2 -> {
boost.activate();
open(player);
})
.onCancel(e2 -> open(player))
.open(player)));
}
}
}
paginator(player, contents, items);
}
}
private double get(Boostable experience) {
return BoostConfig.multiplierOf(experience);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onMcMMOExpGain(McMMOPlayerXpGainEvent event) {
event.setRawXpGained((float) (event.getRawXpGained() * get(Boostable.MCMMO_EXPERIENCE)));
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onExpGain(PlayerPickupExperienceEvent event) {
ExperienceOrb orb = event.getExperienceOrb();
orb.setExperience((int) Math.round(orb.getExperience() * get(Boostable.EXPERIENCE)));
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onJoin(PlayerJoinEvent event) {
Tasks.wait(TickTime.SECOND.x(2), () -> {
if (!event.getPlayer().isOnline())
return;
Set<Boostable> boosts = BoostConfig.get().getBoosts().keySet();
if (boosts.isEmpty())
return;
PlayerUtils.runCommand(event.getPlayer(), "boosts");
});
}
}
| 34.558052 | 150 | 0.719952 |
1a00df053fced78366e96bbf17f483b69359761a | 15,319 | /*
* Copyright 2016 Huawei Technologies Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openo.sdno.acwanservice.transformer;
import java.util.ArrayList;
import java.util.List;
import org.openo.sdno.model.networkmodel.servicetypes.BgpPeer;
import org.openo.sdno.model.networkmodel.servicetypes.HubAc;
import org.openo.sdno.model.networkmodel.servicetypes.L3Ac;
import org.openo.sdno.model.networkmodel.servicetypes.L3Acs;
import org.openo.sdno.model.networkmodel.servicetypes.L3Vpn;
import org.openo.sdno.model.networkmodel.servicetypes.MplsTe;
import org.openo.sdno.model.networkmodel.servicetypes.Protocol;
import org.openo.sdno.model.networkmodel.servicetypes.StaticRoute;
import org.openo.sdno.model.networkmodel.servicetypes.TopoService;
import org.openo.sdno.model.networkmodel.servicetypes.TunnelService;
import org.openo.sdno.model.uniformsbi.comnontypes.enums.RouteType;
import org.openo.sdno.model.uniformsbi.l3vpn.BgpRoute;
import org.openo.sdno.model.uniformsbi.l3vpn.BgpRoutes;
import org.openo.sdno.model.uniformsbi.l3vpn.HubGroup;
import org.openo.sdno.model.uniformsbi.l3vpn.IsisRoute;
import org.openo.sdno.model.uniformsbi.l3vpn.Route;
import org.openo.sdno.model.uniformsbi.l3vpn.Routes;
import org.openo.sdno.model.uniformsbi.l3vpn.SpokeAc;
import org.openo.sdno.model.uniformsbi.l3vpn.SpokeGroup;
import org.openo.sdno.model.uniformsbi.l3vpn.StaticRoutes;
/**
* class for transforming network to service model<br>
*
* @author
* @version SDNO 0.5 August 22, 2016
*/
public class NetToSerTransformer {
private static String TOPOLOGY_TYPE = "fullMesh";
private NetToSerTransformer() {
}
/**
* Transform model from network to service
* <br>
*
* @param l3VpnConfig is a network model VPN configuration
* @return service instance of uniform SBI
* @since SDNO 0.5
*/
public static org.openo.sdno.model.uniformsbi.l3vpn.L3Vpn transformModel(L3Vpn l3Vpn) {
org.openo.sdno.model.uniformsbi.l3vpn.L3Vpn nbil3Vpn = new org.openo.sdno.model.uniformsbi.l3vpn.L3Vpn();
nbil3Vpn.setUuid(l3Vpn.getId());
nbil3Vpn.setName(l3Vpn.getName());
nbil3Vpn.setAdminStatusFromString(l3Vpn.getAdminStatus());
// Topology set to hubSpoke as controller model does not support topology
nbil3Vpn.setDescription(l3Vpn.getName());
if(l3Vpn.getFrr() != null) {
nbil3Vpn.setFrr(Boolean.valueOf(l3Vpn.getFrr()));
}
org.openo.sdno.model.uniformsbi.l3vpn.DiffServ diffServ = new org.openo.sdno.model.uniformsbi.l3vpn.DiffServ();
if(l3Vpn.getDiffServ() != null) {
diffServ.setColor(l3Vpn.getDiffServ().getColor());
diffServ.setMode(l3Vpn.getDiffServ().getMode());
diffServ.setServiceClass(l3Vpn.getDiffServ().getServiceClass());
}
nbil3Vpn.setDiffServ(diffServ);
org.openo.sdno.model.uniformsbi.l3vpn.TopologyService topologyService =
transformTopoService(l3Vpn.getTopoService());
nbil3Vpn.setTopologyService(topologyService);
nbil3Vpn.setTopology(TOPOLOGY_TYPE);
org.openo.sdno.model.uniformsbi.l3vpn.L3LoopbackIfs l3Loopbackifs =
new org.openo.sdno.model.uniformsbi.l3vpn.L3LoopbackIfs();
nbil3Vpn.setL3Loopbackifs(l3Loopbackifs);
org.openo.sdno.model.uniformsbi.l3vpn.L3Acs l3Acs = transformAcs(l3Vpn.getAcs());
nbil3Vpn.setAcs(l3Acs);
nbil3Vpn.setIpMtu(l3Vpn.getIpMtu());
nbil3Vpn.setTunnelService(transformTunnelService(l3Vpn.getTunnelService()));
return nbil3Vpn;
}
/**
* Transform attachment circuits associated with the VPN from network to service
* <br>
*
* @param acs is a network attachment circuits
* @return service instance of attachment circuits
* @since SDNO 0.5
*/
private static org.openo.sdno.model.uniformsbi.l3vpn.L3Acs transformAcs(L3Acs acs) {
org.openo.sdno.model.uniformsbi.l3vpn.L3Acs l3Acs = new org.openo.sdno.model.uniformsbi.l3vpn.L3Acs();
List<org.openo.sdno.model.uniformsbi.l3vpn.L3Ac> listL3Ac = new ArrayList<>();
for(L3Ac l3ac : acs.getL3Ac()) {
org.openo.sdno.model.uniformsbi.l3vpn.L3Ac ctrlrl3ac = new org.openo.sdno.model.uniformsbi.l3vpn.L3Ac();
ctrlrl3ac.setUuid(l3ac.getId());
ctrlrl3ac.setNeId(l3ac.getNeId());
if(l3ac.getL2Access() != null) {
org.openo.sdno.model.uniformsbi.l3vpn.L2Access l2access =
new org.openo.sdno.model.uniformsbi.l3vpn.L2Access();
l2access.setL2AccessType(l3ac.getL2Access().getAccessType());
l2access.setDot1qVlanBitmap(l3ac.getL2Access().getDot1q().getVlanId());
l2access.setPushVlanId(String.valueOf(l3ac.getL2Access().getDot1q().getVlanId()));
ctrlrl3ac.setL2Access(l2access);
}
if(l3ac.getL3Access() != null) {
org.openo.sdno.model.uniformsbi.l3vpn.L3Access l3Access =
new org.openo.sdno.model.uniformsbi.l3vpn.L3Access();
l3Access.setIpv4Address(l3ac.getL3Access().getAddress());
Routes routes = new Routes();
List<Route> routeList = new ArrayList<>();
if(l3ac.getL3Access().getStaticRoutes() != null) {
Route route = new Route();
StaticRoutes sroutes = new StaticRoutes();
List<org.openo.sdno.model.uniformsbi.l3vpn.StaticRoute> staticRouteList = new ArrayList<>();
for(StaticRoute staticRoute : l3ac.getL3Access().getStaticRoutes()) {
org.openo.sdno.model.uniformsbi.l3vpn.Route nbiRoute =
new org.openo.sdno.model.uniformsbi.l3vpn.Route();
nbiRoute.setRouteType(RouteType.STATIC.getAlias());
org.openo.sdno.model.uniformsbi.l3vpn.StaticRoute sr =
new org.openo.sdno.model.uniformsbi.l3vpn.StaticRoute();
sr.setIpPrefix(staticRoute.getIpPrefix());
sr.setNextHop(staticRoute.getNextHop());
staticRouteList.add(sr);
}
sroutes.setStaticRoute(staticRouteList);
route.setStaticRoutes(sroutes);
route.setRouteType("static");
routeList.add(route);
}
if(l3ac.getL3Access().getProtocols() != null) {
for(Protocol protocol : l3ac.getL3Access().getProtocols()) {
if(protocol.getBgp() != null) {
Route route = new Route();
BgpRoutes bgps = new BgpRoutes();
List<BgpRoute> bgpRouteList = new ArrayList<>();
for(BgpPeer bgp : protocol.getBgp()) {
BgpRoute bgproute = new BgpRoute();
bgproute.setAdvertiseCommunity(bgp.getAdvertiseCommunity());
bgproute.setAdvertiseExtCommunity(bgp.getAdvertiseExtCommunity());
bgproute.setHoldTime(bgp.getHoldTime());
bgproute.setKeepaliveTime(bgp.getKeepAliveTime());
bgproute.setPassword(bgp.getPassword());
bgproute.setPeerIp(bgp.getPeerIp());
bgproute.setRemoteAs(bgp.getRemoteAs());
bgpRouteList.add(bgproute);
}
bgps.setBgpRoute(bgpRouteList);
route.setBgpRoutes(bgps);
routeList.add(route);
}
if(protocol.getIsis() != null) {
Route route = new Route();
IsisRoute isis = new IsisRoute();
isis.setNetworkEntity(protocol.getIsis().getNetworkEntity());
route.setIsisRoute(isis);
routeList.add(route);
}
if(protocol.getOspf() != null) {
// TODO OSPF
}
}
}
routes.setRoute(routeList);
l3Access.setRoutes(routes);
ctrlrl3ac.setL3Access(l3Access);
}
listL3Ac.add(ctrlrl3ac);
}
l3Acs.setL3Ac(listL3Ac);
return l3Acs;
}
/**
* Transform tunnel service of l3vpn from network to service model
* <br>
*
* @param tunnelService is a network tunnel service
* @return service instance of uniform sbi's tunnel service
* @since SDNO 0.5
*/
private static org.openo.sdno.model.uniformsbi.base.TunnelService
transformTunnelService(TunnelService tunnelService) {
org.openo.sdno.model.uniformsbi.base.TunnelService ts =
new org.openo.sdno.model.uniformsbi.base.TunnelService();
ts.setType(tunnelService.getType());
if(tunnelService.getAutoSelect() != null) {
org.openo.sdno.model.uniformsbi.base.AutoSelectPolicy autoSelectPolicy =
new org.openo.sdno.model.uniformsbi.base.AutoSelectPolicy();
autoSelectPolicy.setLoadBalanceNumber(tunnelService.getAutoSelect().getLoadBalanceNumber());
ts.setAutoSelect(autoSelectPolicy);
}
if(tunnelService.getMplsTe() != null) {
ts.setMplsTe(transformMplsTe(tunnelService.getMplsTe()));
}
return ts;
}
/**
* Transform MPLS traffic engineering data from network to service model
* <br>
*
* @param mplsTe is a network MPLS traffic engineering data
* @return service instance of uniform sbi's MPLS traffic engineering data
* @since SDNO 0.5
*/
private static org.openo.sdno.model.uniformsbi.base.MplsTePolicy transformMplsTe(MplsTe mplsTe) {
org.openo.sdno.model.uniformsbi.base.MplsTePolicy mplsObj =
new org.openo.sdno.model.uniformsbi.base.MplsTePolicy();
mplsObj.setBandwidth(mplsTe.getBandwidth());
mplsObj.setManageProtocol(mplsTe.getManageProtocol());
mplsObj.setSignalType(mplsTe.getSignalType());
mplsObj.setSharing(mplsTe.getSharing());
mplsObj.setBesteffort(mplsTe.getBestEffort());
mplsObj.setBfdEnable(mplsTe.getBfdEnable());
mplsObj.setCoRoute(mplsTe.getCoRoute());
if(mplsTe.getPathProtectPolicy() != null) {
org.openo.sdno.model.uniformsbi.base.PathProtectPolicy ppp =
new org.openo.sdno.model.uniformsbi.base.PathProtectPolicy();
ppp.setBandwidthMode(mplsTe.getPathProtectPolicy().getBandwidthMode());
ppp.setHotStandbyEnable(mplsTe.getPathProtectPolicy().getHotStandby());
ppp.setRevertive(mplsTe.getPathProtectPolicy().getRevertive());
ppp.setWtr(mplsTe.getPathProtectPolicy().getWtr());
mplsObj.setPathProtectPolicy(ppp);
}
if(mplsTe.getPathConstraint() != null) {
org.openo.sdno.model.uniformsbi.base.PathConstraint pathConstraint =
new org.openo.sdno.model.uniformsbi.base.PathConstraint();
pathConstraint.setHoldupPriority(mplsTe.getPathConstraint().getHoldupPriority());
pathConstraint.setLatency(mplsTe.getPathConstraint().getLatency());
pathConstraint.setSetupPriority(mplsTe.getPathConstraint().getSetupPriority());
mplsObj.setPathConstraint(pathConstraint);
}
return mplsObj;
}
/**
* Transform topology service from network to service model
* <br>
*
* @param topologyService is a network topology service
* @return service instance of uniform sbi's topology service
* @since SDNO 0.5
*/
private static org.openo.sdno.model.uniformsbi.l3vpn.TopologyService
transformTopoService(TopoService topologyService) {
if(topologyService == null) {
return null;
}
org.openo.sdno.model.uniformsbi.l3vpn.TopologyService topoService =
new org.openo.sdno.model.uniformsbi.l3vpn.TopologyService();
org.openo.sdno.model.uniformsbi.l3vpn.HubGroups hubGroup =
new org.openo.sdno.model.uniformsbi.l3vpn.HubGroups();
SpokeGroup spokeGroup = new SpokeGroup();
if(topologyService.getHubSpoke() != null) {
TOPOLOGY_TYPE = "hubSpoke";
if(topologyService.getHubSpoke().getHubGroup() != null) {
hubGroup.setHubGroup(transformHubGroup(topologyService.getHubSpoke().getHubGroup()));
}
if(topologyService.getHubSpoke().getSpokeGroup() != null) {
spokeGroup.setLocalBridge(topologyService.getHubSpoke().getSpokeGroup().getLocalBridge());
spokeGroup
.setSpokeAcs(transformSpokeGroup(topologyService.getHubSpoke().getSpokeGroup().getSpokeAcs()));
}
topoService.setSpokeGroup(spokeGroup);
topoService.setHubGroups(hubGroup);
}
return topoService;
}
/**
* Transform spoke attachment circuits from network to service model
* <br>
*
* @param spokeAcs is a network spoke attachment circuits
* @return service instance of uniform sbi's spoke attachment circuits
* @since SDNO 0.5
*/
private static List<SpokeAc>
transformSpokeGroup(List<org.openo.sdno.model.networkmodel.servicetypes.SpokeAc> spokeAcs) {
List<SpokeAc> nbispokeAcs = new ArrayList<>();
for(org.openo.sdno.model.networkmodel.servicetypes.SpokeAc spokeAc : spokeAcs) {
SpokeAc acs = new SpokeAc();
acs.setAcId(spokeAc.getAcId());
nbispokeAcs.add(acs);
}
return nbispokeAcs;
}
/**
* Transform hub attachment circuits from network to service model
* <br>
*
* @param hubGroup is a network hub attachment circuits
* @return service instance of uniform sbi's hub attachment circuits
* @since SDNO 0.5
*/
private static List<HubGroup> transformHubGroup(List<HubAc> hubGroup) {
List<HubGroup> hubAcs = new ArrayList<>();
for(HubAc hubgrp : hubGroup) {
HubGroup hubac = new HubGroup();
hubac.setAcId(hubgrp.getAcId());
hubac.setHubDirection(hubgrp.getHubDirection());
hubAcs.add(hubac);
}
return hubAcs;
}
}
| 42.201102 | 119 | 0.625563 |
cc08c82b65f4633bd46b632101b0af9dbc0de73e | 268 | package de.adorsys.xs2a.adapter.service.model;
public class UpdatePsuAuthentication {
private PsuData psuData;
public PsuData getPsuData() {
return psuData;
}
public void setPsuData(PsuData psuData) {
this.psuData = psuData;
}
}
| 19.142857 | 46 | 0.679104 |
2931eafbdb2c16246031eda913ba6dac9630dde1 | 462 | package com.twitter.finatra.json.internal.caseclass.validation.validators;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.twitter.finatra.validation.Validation;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ PARAMETER })
@Retention(RUNTIME)
@Validation(validatedBy = CountryCodeValidator.class)
public @interface CountryCodeInternal {
}
| 27.176471 | 74 | 0.831169 |
e134b38f34e37603f36f1b236a9ae5f5d187acf1 | 2,675 | /**
* Copyright 2011 Peter Murray-Rust et. al.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.contentmine.graphics.svg;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.contentmine.eucl.euclid.Real2Range;
import org.contentmine.graphics.AbstractCMElement;
import nu.xom.Element;
import nu.xom.Node;
/** supports defs
*
* @author pm286
*
*/
public class SVGDefs extends SVGElement {
private static final Logger LOG = Logger.getLogger(SVGDefs.class);
static {
LOG.setLevel(Level.DEBUG);
}
public final static String ALL_DEFS_XPATH = ".//svg:defs";
public final static String TAG ="defs";
/** constructor
*/
public SVGDefs() {
super(TAG);
init();
}
/** constructor
*/
public SVGDefs(SVGElement element) {
super(element);
}
/** constructor
*/
public SVGDefs(Element element) {
super((SVGElement) element);
}
/**
* copy node .
*
* @return Node
*/
public nu.xom.Element copy() {
return new SVGDefs(this);
}
/**
* @return tag
*/
public String getTag() {
return TAG;
}
public static void removeDefs(AbstractCMElement svgElement) {
List<SVGDefs> defsList = extractSelfAndDescendantDefs(svgElement);
for (SVGDefs defs : defsList) {
defs.detach();
}
}
public static List<SVGDefs> extractSelfAndDescendantDefs(AbstractCMElement svgElem) {
return SVGDefs.extractDefss(SVGUtil.getQuerySVGElements(svgElem, ALL_DEFS_XPATH));
}
/** makes a new list composed of the defs in the list
*
* @param elements
* @return
*/
public static List<SVGDefs> extractDefss(List<SVGElement> elements) {
List<SVGDefs> defsList = new ArrayList<SVGDefs>();
for (AbstractCMElement element : elements) {
if (element instanceof SVGDefs) {
defsList.add((SVGDefs) element);
}
}
return defsList;
}
/** return null
*
*/
public Real2Range getBoundingBox() {
return null;
}
}
| 22.291667 | 87 | 0.650467 |
15e890924cb45d86ac429c399dc5901672ddab4c | 6,169 | /**
* MIT License
* <p>
* Copyright (c) 2017-2018 nuls.io
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.nuls.db.dao.impl.mybatis;
import com.github.pagehelper.PageHelper;
import io.nuls.core.utils.str.StringUtils;
import io.nuls.db.dao.TransactionLocalDataService;
import io.nuls.db.dao.impl.mybatis.mapper.TransactionLocalMapper;
import io.nuls.db.dao.impl.mybatis.util.SearchOperator;
import io.nuls.db.dao.impl.mybatis.util.Searchable;
import io.nuls.db.entity.TransactionLocalPo;
import io.nuls.db.transactional.annotation.DbSession;
import io.nuls.db.transactional.annotation.PROPAGATION;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Niels
* @date 2017/11/22
*/
@DbSession(transactional = PROPAGATION.NONE)
public class TransactionLocalDaoImpl extends BaseDaoImpl<TransactionLocalMapper, String, TransactionLocalPo> implements TransactionLocalDataService {
public TransactionLocalDaoImpl() {
super(TransactionLocalMapper.class);
}
@Override
protected Searchable getSearchable(Map<String, Object> params) {
//todo
return null;
}
@Override
public List<TransactionLocalPo> getTxs(Long blockHeight) {
Searchable searchable = new Searchable();
searchable.addCondition("block_height", SearchOperator.eq, blockHeight);
PageHelper.orderBy("create_time asc");
return getMapper().selectList(searchable);
}
@Override
public List<TransactionLocalPo> getTxs(Long startHeight, Long endHeight) {
Searchable searchable = new Searchable();
searchable.addCondition("block_height", SearchOperator.gte, startHeight);
searchable.addCondition("block_height", SearchOperator.lte, endHeight);
PageHelper.orderBy("block_height asc, create_time asc");
return getMapper().selectList(searchable);
}
@Override
public List<TransactionLocalPo> getTxs(Long blockHeight, String address, int type, int pageNumber, int pageSize) {
Searchable searchable = new Searchable();
// Condition condition = Condition.custom("(e.address = c.address or e.address = d.address)");
// searchable.addCondition(condition);
if (type != 0) {
searchable.addCondition("a.type", SearchOperator.eq, type);
}
if (blockHeight != null) {
searchable.addCondition("a.block_height", SearchOperator.eq, blockHeight);
}
if (StringUtils.isNotBlank(address)) {
searchable.addCondition("e.address", SearchOperator.eq, address);
}
if (pageNumber == 0 & pageSize == 0) {
PageHelper.orderBy("a.block_height desc, a.tx_index desc, b.in_index asc, c.out_index asc");
return getMapper().selectByAddress(searchable);
}
PageHelper.startPage(pageNumber, pageSize);
PageHelper.orderBy("a.create_time desc");
List<String> txHashList = getMapper().selectTxHashListRelation(searchable);
if (txHashList.isEmpty()) {
return new ArrayList<>();
}
searchable = new Searchable();
searchable.addCondition("a.hash", SearchOperator.in, txHashList);
PageHelper.orderBy("a.block_height desc, a.tx_index desc, b.in_index asc, c.out_index asc");
List<TransactionLocalPo> localPoList = getMapper().selectByAddress(searchable);
return localPoList;
}
@Override
public List<TransactionLocalPo> getTxs(String address, int type) {
return getTxs(null, address, type, 0, 0);
}
@Override
public Long getTxsCount(Long blockHeight, String address, int type) {
Searchable searchable = new Searchable();
if (StringUtils.isBlank(address)) {
if (type != 0) {
searchable.addCondition("type", SearchOperator.eq, type);
}
if (blockHeight != null) {
searchable.addCondition("block_height", SearchOperator.eq, blockHeight);
}
return getMapper().selectCount(searchable);
}
if (type != 0) {
searchable.addCondition("a.type", SearchOperator.eq, type);
}
if (blockHeight != null) {
searchable.addCondition("a.block_height", SearchOperator.eq, blockHeight);
}
searchable.addCondition("e.address", SearchOperator.eq, address);
return getMapper().selectCountByAddress(searchable);
}
@Override
public List<TransactionLocalPo> getUnConfirmTxs() {
Searchable searchable = new Searchable();
searchable.addCondition("txStatus", SearchOperator.eq, TransactionLocalPo.UNCONFIRM);
PageHelper.orderBy("create_time asc");
return getMapper().selectLocalTxs(searchable);
}
@Override
@DbSession
public void deleteUnCofirmTx(String txHash) {
Searchable searchable = new Searchable();
searchable.addCondition("txStatus", SearchOperator.eq, TransactionLocalPo.UNCONFIRM);
searchable.addCondition("hash", SearchOperator.eq, txHash);
getMapper().deleteBySearchable(searchable);
}
}
| 40.585526 | 149 | 0.69136 |
546fe120c9feca066d2a72b0430f7d8d446e54cd | 3,050 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.devcamera;
import android.graphics.PointF;
import android.graphics.RectF;
import android.hardware.camera2.params.Face;
/**
*
* Face coordinates. Normalized 0 to 1, and in native sensor orientation, which so far seems to be
* landscape.
*
*/
public class NormalizedFace {
public RectF bounds;
public PointF leftEye;
public PointF rightEye;
public PointF mouth;
public NormalizedFace(Face face, int dX, int dY, int offX, int offY) {
if (face.getLeftEyePosition() != null) {
leftEye = new PointF();
leftEye.x = (float) (face.getLeftEyePosition().x - offX) / dX;
leftEye.y = (float) (face.getLeftEyePosition().y - offY) / dY;
}
if (face.getRightEyePosition() != null) {
rightEye = new PointF();
rightEye.x = (float) (face.getRightEyePosition().x - offX) / dX;
rightEye.y = (float) (face.getRightEyePosition().y - offY) / dY;
}
if (face.getMouthPosition() != null) {
mouth = new PointF();
mouth.x = (float) (face.getMouthPosition().x - offX) / dX;
mouth.y = (float) (face.getMouthPosition().y - offY) / dY;
}
if (face.getBounds() != null) {
bounds = new RectF();
bounds.left = (float) (face.getBounds().left - offX) / dX;
bounds.top = (float) (face.getBounds().top - offY) / dY;
bounds.right = (float) (face.getBounds().right - offX) / dX;
bounds.bottom = (float) (face.getBounds().bottom - offY) / dY;
}
}
public void mirrorInX() {
if (leftEye != null) {
leftEye.x = 1f - leftEye.x;
}
if (rightEye != null) {
rightEye.x = 1f - rightEye.x;
}
if (mouth != null) {
mouth.x = 1f - mouth.x;
}
float oldLeft = bounds.left;
bounds.left = 1f - bounds.right;
bounds.right = 1f - oldLeft;
}
/**
* Typically required for front camera
*/
public void mirrorInY() {
if (leftEye != null) {
leftEye.y = 1f - leftEye.y;
}
if (rightEye != null) {
rightEye.y = 1f - rightEye.y;
}
if (mouth != null) {
mouth.y = 1f - mouth.y;
}
float oldTop = bounds.top;
bounds.top = 1f - bounds.bottom;
bounds.bottom = 1f - oldTop;
}
}
| 33.152174 | 99 | 0.574754 |
ced72923c76cd2063b3e713b2ff639fd210f6874 | 1,924 | package life.catalogue.es.query;
import life.catalogue.es.EsNameUsage;
import life.catalogue.es.EsReadTestBase;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class PrefixQueryTest extends EsReadTestBase {
@Before
public void before() {
destroyAndCreateIndex();
}
@Test
public void author() {
EsNameUsage doc = new EsNameUsage();
String s = " tHiS iS a LoNg string with spaces";
// This field is indexed using the IGNORE_CASE analyzer.
doc.setAuthorshipComplete(s);
indexRaw(doc);
Query query = new StandardAsciiQuery("authorshipComplete", "LoNg");
List<EsNameUsage> result = queryRaw(query);
assertEquals(1, result.size());
}
@Test
public void authorNoMatch() {
EsNameUsage doc = new EsNameUsage();
String s = " tHiS iS a LoNg string with spaces";
// This field is indexed using the IGNORE_CASE analyzer.
doc.setAuthorshipComplete(s);
indexRaw(doc);
Query query = new BoolQuery().must(new StandardAsciiQuery("authorshipComplete", "LoN"));
List<EsNameUsage> result = queryRaw(query);
assertEquals(0, result.size());
}
@Test
public void usageId() {
EsNameUsage doc = new EsNameUsage();
String s = " tHiS iS a LoNg string with spaces";
// This field is indexed as-is.
doc.setUsageId(s);
indexRaw(doc);
Query query = new PrefixQuery("usageId", s);
List<EsNameUsage> result = queryRaw(query);
assertEquals(1, result.size());
}
@Test
public void usageId2() {
EsNameUsage doc = new EsNameUsage();
String s = " tHiS iS a LoNg string with spaces";
// This field is indexed as-is.
doc.setUsageId(s);
indexRaw(doc);
Query query = new PrefixQuery("usageId", s.substring(0, 10));
List<EsNameUsage> result = queryRaw(query);
assertEquals(1, result.size());
}
}
| 28.294118 | 92 | 0.674116 |
39994e252e65db3d3062cafbc92f4e0284cb8ff2 | 2,456 | /*
* Copyright 2000-2005 JetBrains s.r.o.
*
* 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.intellij.javascript;
import javax.annotation.Nonnull;
import org.jetbrains.annotations.NonNls;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.Expression;
import com.intellij.codeInsight.template.ExpressionContext;
import com.intellij.codeInsight.template.Macro;
import com.intellij.codeInsight.template.Result;
import com.intellij.codeInsight.template.TextResult;
import com.intellij.lang.javascript.JavaScriptBundle;
import com.intellij.lang.javascript.psi.JSFunction;
import com.intellij.lang.javascript.psi.JSFunctionExpression;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
public class JSMethodNameMacro extends Macro
{
@Override
@NonNls
public String getName()
{
return "jsMethodName";
}
@Override
public String getPresentableName()
{
return JavaScriptBundle.message("js.methodname.macro.description");
}
@Override
@NonNls
public String getDefaultValue()
{
return "";
}
@Override
public Result calculateResult(@Nonnull Expression[] params, ExpressionContext context)
{
final PsiElement elementAtCaret = JSClassNameMacro.findElementAtCaret(context);
if(elementAtCaret != null)
{
JSFunction function = PsiTreeUtil.getParentOfType(elementAtCaret, JSFunction.class);
if(function instanceof JSFunctionExpression)
{
function = ((JSFunctionExpression) function).getFunction();
}
if(function != null)
{
final String name = function.getName();
if(name != null)
{
return new TextResult(name);
}
}
}
return null;
}
@Override
public Result calculateQuickResult(@Nonnull Expression[] params, ExpressionContext context)
{
return null;
}
@Override
public LookupElement[] calculateLookupItems(@Nonnull Expression[] params, ExpressionContext context)
{
return null;
}
}
| 26.12766 | 101 | 0.763029 |
07a07a583cebaf2ad7817281a76780f276f04647 | 1,456 | package com.gzczy.concurrent.cas;
import lombok.Data;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
/**
* @Description UnSafe反射调用测试
* 实际生产切勿使用UnSafe魔法类!!!!
* @Author chenzhengyu
* @Date 2020-11-28 18:59
*/
public class UnsafeAccessor {
static Unsafe unsafe;
static {
try {
//通过反射得到Unsafe对象
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
static Unsafe getUnsafe() {
return unsafe;
}
public static void main(String[] args) throws Exception {
Unsafe unsafe = getUnsafe();
Field id = Student.class.getDeclaredField("id");
Field name = Student.class.getDeclaredField("name");
// 获得成员变量的偏移量
long idOffset = UnsafeAccessor.unsafe.objectFieldOffset(id);
long nameOffset = UnsafeAccessor.unsafe.objectFieldOffset(name);
Student student = new Student();
System.out.println(student.toString());
//通过unsafe底层类 找到内存的地址进行数据替换
unsafe.compareAndSwapInt(student, idOffset,0,1);
unsafe.compareAndSwapObject(student,nameOffset,null, "czy");
System.out.println(student.toString());
}
}
@Data
class Student {
volatile int id;
volatile String name;
}
| 26.962963 | 73 | 0.649038 |
d86ed8e266f88be69669d302873ee7ed708ad677 | 1,906 | package datastructures.toolbox.UN;
/**
* Cola Array ( Queue )
*
* Estructura basada en arrays,
* Consta de 1 array.
*/
interface QueueGen<T> {
abstract public boolean isEmpty();
abstract public boolean isFull();
abstract public int numInside();
abstract public T peek();
abstract public T dequeue();
abstract public void enqueue(T item);
}
public class Queue<T> implements QueueGen<T> {
private static final int N = 5;
private int front, rear, count;
private T[] qarray;
public Queue() {
this(N);
}
public Queue(int N) {
front = rear = count = 0;
qarray = (T[]) new Object[N];
}
/**
* saca un elemento.
* Maneja Excepción de espacio.
* @param {}.
* @return{Type} - Éxito del proceso.
**/
public T dequeue() {
T item = null;
if (isEmpty())
throw new RuntimeException("la cola esta vacia");
else {
item = qarray[front];
front = (front + 1) % N;
count--;
}
return item;
}
/**
* inserta un elemento.
* Maneja Excepción de espacio.
* @param {Type}.
* @return{} -Exito del proceso.
**/
public void enqueue(T item) {
if (isFull())
throw new RuntimeException("no hay espacio");
else {
qarray[rear] = item;
rear = (rear + 1) % N;
count++;
}
}
public T peek(){
return qarray[front];
}
/**
* retorna si la cola esta vacia o no.
* @param {}.
* @return{Boolean} -esta vacia.
**/
public boolean isEmpty() {
return count <= 0;
}
/**
* retorna si la cola esta llena o no.
* @param {}.
* @return{Boolean} -esta llena.
**/
public boolean isFull() {
return count >= qarray.length;
}
/**
* retorna la cantidad de elementos en la cola.
* @param {}.
* @return{Intiger} -numero elementos en la cola.
**/
public int numInside() {
return count;
}
} | 20.717391 | 55 | 0.568206 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.