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
ef71068ea10835127557d46f3a7cc2b66b35ce4a
165
package com.minimal.common.sdk.sequence; /** * ID生成器 * @author wubin * */ public interface IdGenerator { /** * 获取新的ID * @return ID */ long nextId(); }
10.3125
40
0.606061
ac4d6955c5b8595ac8384ae260a728b1ec648d08
1,681
package date; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; /** * Created by Junior on 17/06/2020. */ public class LocalDateExample { public static void main(String[] args ){ LocalDate localDate = LocalDate.now(); System.out.println(localDate); System.out.println("Day of week " + localDate.getDayOfWeek().name()); System.out.println("Day of week " + localDate.getDayOfWeek().ordinal()); System.out.println("Month " + localDate.getMonth().getValue()); System.out.println("Month " + localDate.getMonthValue()); System.out.println("Year " + localDate.getYear()); LocalDate localDate1 = LocalDate.of(2012,5,15); System.out.println("Month " + localDate1.getMonthValue()); System.out.println("Year " + localDate1.getYear()); LocalDate localDate2 = LocalDate.parse("2015-05-10"); System.out.println("Month " + localDate2.getMonthValue()); System.out.println("Year " + localDate2.getYear()); System.out.println("Day of Month " + localDate2.plusDays(5).getDayOfMonth()); //Immutable System.out.println("Day of Month " + localDate2.getDayOfMonth()); System.out.println(LocalDate.parse("2016-06-12").atStartOfDay()); System.out.println(LocalDate.parse("2016-06-12").with(TemporalAdjusters.firstDayOfMonth())); System.out.println(LocalDate.parse("2016-06-12").with(TemporalAdjusters.lastDayOfMonth())); System.out.println(LocalDate.parse("2016-06-12").isAfter(LocalDate.of(2018, 4, 11))); System.out.println(LocalDate.parse("2016-06-12").isBefore(LocalDate.of(2018, 4, 11))); } }
36.543478
100
0.66508
616890571a33d54bcc9742fb7bf7e2ac62d67b28
3,948
/* * Copyright (c) 2010-2016 Dmytro Pishchukhin (http://knowhowlab.org) * * 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.knowhowlab.maven.plugins.keepass.dao; import de.slackspace.openkeepass.KeePassDatabase; import de.slackspace.openkeepass.domain.KeePassFile; import de.slackspace.openkeepass.exception.KeePassDatabaseUnreadable; import org.knowhowlab.maven.plugins.keepass.dao.filter.*; import java.io.File; import java.util.List; import java.util.UUID; import static java.util.UUID.fromString; /** * @author dpishchukhin. */ public class KeePassDAO { private final KeePassDatabase keePassDatabase; private KeePassFile keePassFile; public KeePassDAO(File file) { keePassDatabase = KeePassDatabase.getInstance(file); } public static UUID convertToUUID(String digits) { if (!digits.contains("-")) { return fromString(digits.replaceAll( "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } else { return fromString(digits); } } public KeePassDAO open(String password) { try { keePassFile = keePassDatabase.openDatabase(password); return this; } catch (KeePassDatabaseUnreadable e) { throw new IllegalArgumentException("Invalid password?", e); } } public KeePassDAO open(String password, File keyFile) { try { keePassFile = keePassDatabase.openDatabase(password, keyFile); return this; } catch (KeePassDatabaseUnreadable e) { throw new IllegalArgumentException("Invalid password and/or key file?", e); } } public KeePassDAO open(File keyFile) { try { keePassFile = keePassDatabase.openDatabase(keyFile); return this; } catch (KeePassDatabaseUnreadable e) { throw new IllegalArgumentException("Invalid key file?", e); } } public KeePassGroup getRootGroup() { return new KeePassGroup(keePassFile.getRoot()); } public KeePassGroup getGroup(UUID uuid) { return new GroupWalker(getRootGroup()).findAny(new GroupUUIDFilter(uuid)); } public KeePassEntry getEntry(UUID uuid) { return new KeePassEntry(keePassFile.getEntryByUUID(uuid)); } public List<KeePassGroup> getGroupsByName(String name) { return new GroupWalker(getRootGroup()).findAll(new GroupNameFilter(name)); } public List<KeePassEntry> getEntriesByTitle(String title) { return getEntriesByTitle(getRootGroup(), title); } public List<KeePassEntry> getEntriesByTitle(KeePassGroup group, String title) { return new EntryWalker(group).findAll(new EntryTitleFilter(title)); } public List<KeePassEntry> getEntriesByTitleRegex(String regex) { return getEntriesByTitleRegex(getRootGroup(), regex); } public List<KeePassEntry> getEntriesByTitleRegex(KeePassGroup group, String regex) { return new EntryWalker(group).findAll(new EntryTitleRegexFilter(regex)); } public List<KeePassGroup> getGroupsByNameRegex(String regex) { return new GroupWalker(getRootGroup()).findAll(new GroupNameRegexFilter(regex)); } public List<KeePassGroup> getGroupsByPath(String path) { return new GroupWalker(getRootGroup()).findAll(new GroupPathFilter(path.split("/"))); } }
33.457627
93
0.679331
fcd0f66e1f068cd82446b6de4653bf48f27305db
1,079
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:paascloud快速搭建企业级分布式微服务平台 * 类名称:OrderItemVo.java * 创建人:刘兆明 * 联系方式:paascloud.net@gmail.com * 开源地址: https://github.com/paascloud * 博客地址: http://blog.paascloud.net * 项目官网: http://paascloud.net */ package com.jemmy.apis.omc.model.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * The class Order item vo. * * @author paascloud.net@gmail.com */ @Data public class OrderItemVo implements Serializable { private static final long serialVersionUID = -8309014197153665106L; private String orderNo; private Long productId; private String productName; private String productImage; private BigDecimal currentUnitPrice; private Integer quantity; private BigDecimal totalPrice; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; }
22.957447
68
0.76089
885ea4e44747c3592795dcd6041e1325a1ea2aae
656
package com.item.ag; import junit.framework.TestCase; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; // https://stackoverflow.com/questions/11397522/when-to-use-weak-and-phantom-references-in-java public class ConceptPhantomReference extends TestCase { public static void testPhantomReference() throws IllegalArgumentException, InterruptedException { Object obj = new Object(); ReferenceQueue<Object> refQueue = new ReferenceQueue<>(); PhantomReference<Object> phantomObj = new PhantomReference<Object>(obj, refQueue); obj = null; obj = phantomObj.get(); assertNull(obj); } }
26.24
99
0.742378
a014e981867cf6b1aaaf1730fcfe3c0cc35c5048
345
package edu.vcu.cyber.dashboard.util; import org.graphstream.graph.Graph; import java.io.File; public class GraphFileUtil { /** * Saves a graph, including all attributes and positions to * the specified file to be used again later */ public static void saveGraph(Graph graph, File outputFile) { //TODO: needs implementation } }
17.25
60
0.736232
97b2a95ea7b00d75a46ec7929a5637026a9ed9c8
1,334
package com.liurui.rabbitmq.message.producer; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; import org.springframework.util.Assert; import java.util.Map; import java.util.Objects; /** * @author liu-rui * @date 2019-08-27 16:48 * @description */ @Slf4j public class MessageProducerImpl implements MessageProducer { private Map<String, MessageSender> messageSenderMap = Maps.newHashMap(); @Override public void send(String key, Object data) { send(key, "", data); } @Override public void send(String key, String routingKey, Object data) { Assert.notNull(key, "key is null"); Assert.notNull(routingKey, "routingKey is not null"); Assert.notNull(data, "data is null"); final MessageSender messageSender = messageSenderMap.get(key); if (Objects.isNull(messageSender)) { throw new IllegalArgumentException("key无效,找不到对应的消息配置"); } if (log.isInfoEnabled()) { log.info("发送消息 key:{} 内容:{}", key, data); } messageSender.send(routingKey, data); } public void add(String key, MessageSender messageSender) { Assert.notNull(key, "key is null"); Assert.notNull(messageSender, "MessageSender is null"); messageSenderMap.put(key, messageSender); } }
28.382979
76
0.663418
4ff49497149c0f28395f7b331fbdfa0ffbc2550c
5,042
package com.oc.hawk.container.runtime.port.driven.facade; import com.google.common.collect.Maps; import com.oc.hawk.container.api.command.CreateRuntimeInfoSpecCommand; import com.oc.hawk.container.api.command.StopRuntimeInfoCommand; import com.oc.hawk.container.api.event.ContainerDomainEventType; import com.oc.hawk.container.domain.config.ContainerConfiguration; import com.oc.hawk.container.domain.facade.InfrastructureLifeCycleFacade; import com.oc.hawk.container.domain.model.app.ServiceApp; import com.oc.hawk.container.domain.model.app.ServiceAppRule; import com.oc.hawk.container.domain.model.app.ServiceAppVersion; import com.oc.hawk.container.domain.model.runtime.config.BaseInstanceConfig; import com.oc.hawk.container.domain.model.runtime.config.InstanceConfig; import com.oc.hawk.container.domain.service.InstanceConfigDecoratorFacade; import com.oc.hawk.container.domain.service.RuntimeInstanceConfigDecoratorService; import com.oc.hawk.container.runtime.application.representation.InstanceRuntimeRepresentation; import com.oc.hawk.container.runtime.port.driven.facade.feign.KubernetesGateway; import com.oc.hawk.ddd.event.DomainEvent; import com.oc.hawk.ddd.event.EventPublisher; import com.oc.hawk.kubernetes.api.constants.RuntimeInfoDTO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; @Component @Slf4j @RequiredArgsConstructor public class KubernetesInfrastructureLifeCycleFacade implements InfrastructureLifeCycleFacade { private final KubernetesGateway kubernetesGateway; private final EventPublisher eventPublisher; private final ContainerConfiguration containerConfiguration; private final InstanceRuntimeRepresentation instanceRuntimeRepresentation; private InstanceConfigDecoratorFacade instanceConfigDecoratorFacade; @PostConstruct public void startup() { instanceConfigDecoratorFacade = new RuntimeInstanceConfigDecoratorService(containerConfiguration); } @Override public void start(InstanceConfig config) { instanceConfigDecoratorFacade.decorate(config); final CreateRuntimeInfoSpecCommand createRuntimeInfoSpecCommand = instanceRuntimeRepresentation.runtimeInfoSpecCommand(config); eventPublisher.publishDomainEvent(DomainEvent.byData(config.getId().getId(), ContainerDomainEventType.INSTANCE_STARTED, createRuntimeInfoSpecCommand)); } @Override public void stop(InstanceConfig config) { BaseInstanceConfig baseConfig = (BaseInstanceConfig) config.getBaseConfig(); final long id = baseConfig.getId().getId(); StopRuntimeInfoCommand command = new StopRuntimeInfoCommand(id, baseConfig.getNamespace(), baseConfig.getName().getName(), baseConfig.getProjectId()); eventPublisher.publishDomainEvent(DomainEvent.byData(id, ContainerDomainEventType.INSTANCE_STOPPED, command)); } @Override public Map<Long, Integer> countRuntimeByProject(String namespace) { List<RuntimeInfoDTO> runtimeInfo; try { runtimeInfo = kubernetesGateway.queryRuntimeInfo(namespace, null, null, false); } catch (RuntimeException e) { runtimeInfo = null; log.warn("Disconnect with kubernetes server, due to network issue..."); } if (runtimeInfo == null || runtimeInfo.isEmpty()) { return null; } Map<Long, Long> result = runtimeInfo .stream() .map(RuntimeInfoDTO::getProjectId) .filter(Objects::nonNull) .map(Long::parseLong) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); return Maps.transformValues(result, Math::toIntExact); } @Override public void scale(ServiceAppVersion version) { InstanceConfig config = version.getConfig(); BaseInstanceConfig baseConfig = (BaseInstanceConfig) config.getBaseConfig(); kubernetesGateway.scaleService(baseConfig.getName().getName(), version.getApp().getNamespace(), version.getScale()); } @Override public void applyServiceAppRules(ServiceApp app, List<String> versionNames, List<ServiceAppRule> appRules) { // ServiceAppRuleConverter converter = new DefaultServiceAppRuleConvert(); // // HawkHttpPolicyRequestDTO hawkHttpPolicyRequestDTO = new HawkHttpPolicyRequestDTO(); // hawkHttpPolicyRequestDTO.setServiceName(app.getName()); // hawkHttpPolicyRequestDTO.setNamespace(app.getNamespace()); // hawkHttpPolicyRequestDTO.setVersions(versionNames); // // List<HawkHttpPolicyDTO> policy = appRules.stream().map(converter::convertHttpRule).collect(Collectors.toList()); // // hawkHttpPolicyRequestDTO.setPolicy(policy); // // // kubernetesGateway.applyServiceAppRules(hawkHttpPolicyRequestDTO); } }
44.619469
159
0.767751
d88c9e261f8ee37e49961087ccdc3312bb70922d
5,664
package core; import SportPlanner.*; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; public class TrainingDay { private String date; // dd.mm.yyyy private FitnessTraining fitnessTraining; private DistanceTraining distanceTraining; public TrainingDay() { } public TrainingDay(String dateString) { // day with date only this.setDate(dateString); } public TrainingDay(String dateString, FitnessTraining training) { // day with fitness training only this.setFitnessTraining(training); this.setDate(dateString); } public TrainingDay(String dateString, DistanceTraining distanceTraining) { // day with distance training only this.setDistanceTraining(distanceTraining); this.setDate(dateString); } public TrainingDay(String dateString, DistanceTraining distanceTraining, FitnessTraining fitnessTraining) { // day with both types of training this.setDistanceTraining(distanceTraining); this.setFitnessTraining(fitnessTraining); this.setDate(dateString); } public String getDate() { return date; } public void validateDateFormat(String dateString) throws IllegalArgumentException { // dd.MM.yyyy if(dateString.charAt(2) != '.' && dateString.charAt(5) != '.') throw new IllegalArgumentException("Invalid date format. Supported date format is dd.MM.yyyy"); String day = "" + dateString.charAt(0) + dateString.charAt(1); String month = "" + dateString.charAt(3) + dateString.charAt(4); String year = "" + dateString.charAt(6) + dateString.charAt(7) + dateString.charAt(8) + dateString.charAt(9); int yearNumber = Integer.parseInt(year); int dayNumber = Integer.parseInt(day); int monthNumber = Integer.parseInt(month); if (yearNumber < 2001 || yearNumber > 3000) throw new IllegalArgumentException("you can't add trainings earlier than 2001 and later than 3000"); if ( dayNumber < 1 || dayNumber > 31) throw new IllegalArgumentException("Invalid day. Supported date format is dd.MM.yyyy"); if ( monthNumber < 1 || monthNumber > 12) throw new IllegalArgumentException("Invalid month. Supported date format is dd.MM.yyyy"); } public void setDate(String dateString) throws IllegalArgumentException { try{ validateDateFormat(dateString); } catch (IllegalArgumentException e){ throw e; } this.date = dateString; } public FitnessTraining getFitnessTraining() { return fitnessTraining; } public DistanceTraining getDistanceTraining() { return distanceTraining; } public void setFitnessTraining(FitnessTraining fitnessTraining) { this.fitnessTraining = fitnessTraining; } public void setDistanceTraining(DistanceTraining distanceTraining) { this.distanceTraining = distanceTraining; } public boolean isLater(String strDate){ DateFormat formatter; Date newDate, date; formatter = new SimpleDateFormat("dd.mm.yyyy"); try { validateDateFormat(strDate); newDate = formatter.parse(strDate); date = formatter.parse(this.date); if (date.compareTo(newDate) == -1){ return false; } else return true; } catch (java.text.ParseException e ){ System.out.println("Blad"); return false; } } @Override public String toString() { StringBuilder sb = new StringBuilder(""); sb.append(date).append("\n"); if( fitnessTraining != null ) sb.append(fitnessTraining).append("\n"); if( distanceTraining != null ) sb.append(distanceTraining).append("\n"); return sb.toString(); } public static void main(String[] args) { DistanceTrainingMaker distanceDirector = new DistanceTrainingMaker(); DistanceSportBuilder distanceBuilder = new DistanceTrainingBuilder(); distanceDirector.setDistanceTraining(distanceBuilder); distanceDirector.makeDistanceTraining(1000, 1000, 500); DistanceTraining distanceTraining = distanceDirector.getDistanceTraining(); FitnessTrainingMaker fitnessDirector = new FitnessTrainingMaker(); FitnessSportBuilder fitnessBuilder = new FitnessTrainingBuilder(); fitnessDirector.setFitnessTraining(fitnessBuilder); Exercise exercise1 = new Exercise.ExerciseBuilder("Pull ups") .time(120) .reps(20) .buildExercise(); Exercise exercise2 = new Exercise.ExerciseBuilder("Push Ups") .time(30) .reps(10) .buildExercise(); fitnessDirector.makeFitnessTraining(150, 200, 2); fitnessDirector.makeExercise(exercise2); fitnessDirector.makeExercise(exercise1); FitnessTraining fitnessTraining = fitnessDirector.getFitnessTraining(); TrainingDay trainingDay1 = new TrainingDay("18.04.2018", distanceTraining); TrainingDay trainingDay2 = new TrainingDay("19.04.2018", fitnessTraining); TrainingDay trainingDay3 = new TrainingDay("21.04.2018", distanceTraining, fitnessTraining); Planner planner = new Planner(3); planner.addDay(trainingDay1); planner.addDay(trainingDay2); planner.addDay(trainingDay3); System.out.println(planner); } }
32.930233
112
0.650071
67580f1df4cd591e84419e188ae30eceda79db03
982
package com.zoromatic.timetable; import java.util.Locale; import android.app.Application; import android.content.res.Resources; import android.util.DisplayMetrics; public class ZoromaticTimetableApplication extends Application { @Override public void onCreate() { super.onCreate(); String lang = Preferences.getLanguageOptions(this); if (lang.equals("")) { String langDef = Locale.getDefault().getLanguage(); if (!langDef.equals("")) lang = langDef; else lang = "en"; Preferences.setLanguageOptions(this, lang); } // Change locale settings in the application Resources res = getBaseContext().getResources(); DisplayMetrics dm = res.getDisplayMetrics(); android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang.toLowerCase()); res.updateConfiguration(conf, dm); } }
28.882353
72
0.639511
5437d794c6ba9736337731fc12e15c04272d8045
11,545
package com.xueyi.common.core.utils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.xueyi.common.core.constant.basic.BaseConstants; import com.xueyi.common.core.exception.base.BaseException; import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; /** * 树结构组装工具类 * * @author xueyi */ public class TreeUtils { /** * 构建树结构 * 存在默认参数 详见BaseConstants.Entity * IdName = ID | FIdName = PARENT_ID | childrenName = CHILDREN | topNode = TOP_NODE | killScattered = false | killNoneChild = true * * @param list 组装列表 * @return 树结构列表 */ public static <T> List<T> buildTree(List<T> list) { return buildTree(list, BaseConstants.Entity.ID.getCode(), BaseConstants.Entity.PARENT_ID.getCode(), BaseConstants.Entity.CHILDREN.getCode(), BaseConstants.TOP_ID, false, true); } /** * 构建树结构 * 存在默认参数 详见BaseConstants.Entity * IdName = ID | FIdName = PARENT_ID | childrenName = CHILDREN | topNode = TOP_NODE | killNoneChild = true * * @param list 组装列表 * @param killScattered 是否移除无法追溯到顶级节点 (true 是 | false 否) * @return 树结构列表 */ public static <T> List<T> buildTree(List<T> list, boolean killScattered) { return buildTree(list, BaseConstants.Entity.ID.getCode(), BaseConstants.Entity.PARENT_ID.getCode(), BaseConstants.Entity.CHILDREN.getCode(), BaseConstants.TOP_ID, killScattered, true); } /** * 构建树结构 * 存在默认参数 详见BaseConstants.Entity * IdName = ID | FIdName = PARENT_ID | childrenName = CHILDREN | topNode = TOP_NODE * * @param list 组装列表 * @param killScattered 是否移除无法追溯到顶级节点 (true 是 | false 否) * @param killNoneChild 是否移除空子节点集合 * @return 树结构列表 */ public static <T> List<T> buildTree(List<T> list, boolean killScattered, boolean killNoneChild) { return buildTree(list, BaseConstants.Entity.ID.getCode(), BaseConstants.Entity.PARENT_ID.getCode(), BaseConstants.Entity.CHILDREN.getCode(), BaseConstants.TOP_ID, killScattered, killNoneChild); } /** * 构建树结构 * 存在默认参数 详见BaseConstants.Entity * IdName = ID | FIdName = PARENT_ID | childrenName = CHILDREN | killNoneChild = true * * @param list 组装列表 * @param topNode 顶级节点 * @param killScattered 是否移除无法追溯到顶级节点 (true 是 | false 否) * @return 树结构列表 */ public static <T> List<T> buildTree(List<T> list, Serializable topNode, boolean killScattered) { return buildTree(list, BaseConstants.Entity.ID.getCode(), BaseConstants.Entity.PARENT_ID.getCode(), BaseConstants.Entity.CHILDREN.getCode(), topNode, killScattered, true); } /** * 构建树结构 * * @param list 组装列表 * @param IdName Id字段名称 * @param FIdName 父级Id字段名称 * @param childrenName children字段名称 * @param topNode 顶级节点 * @param killScattered 是否移除无法追溯到顶级节点 (true 是 | false 否) * @param killNoneChild 是否移除空子节点集合 * @return 树结构列表 */ public static <T> List<T> buildTree(List<T> list, String IdName, String FIdName, String childrenName, Serializable topNode, boolean killScattered, boolean killNoneChild) { List<T> returnList = new ArrayList<>(); List<Long> tempList = new ArrayList<>(); T top = null; boolean hasTopNode = false; try { if (CollUtil.isNotEmpty(list)) { int IdKey = 0; for (T vo : list) { if (IdKey == 0) IdKey = checkAttribute(vo, IdName, IdKey); Field Id = depthRecursive(vo, IdKey).getDeclaredField(IdName); Id.setAccessible(true); if (ObjectUtil.equal(Id.get(vo), topNode)) { hasTopNode = true; top = vo; list.remove(vo); break; } } for (T vo : list) { Field Id = depthRecursive(vo, IdKey).getDeclaredField(IdName); Id.setAccessible(true); tempList.add((Long) Id.get(vo)); } int FIdKey = 0; for (T vo : list) { if (FIdKey == 0) FIdKey = checkAttribute(vo, FIdName, FIdKey); Field FId = depthRecursive(vo, FIdKey).getDeclaredField(FIdName); FId.setAccessible(true); // 如果是顶级节点, 遍历该父节点的所有子节点 if (!tempList.contains((Long) FId.get(vo))) { recursionFn(list, vo, IdName, FIdName, childrenName, killNoneChild); returnList.add(vo); } } } } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } if (returnList.isEmpty()) { returnList = list; } if (killScattered) { deleteNoTopNode(returnList, FIdName, topNode); } if (hasTopNode && ObjectUtil.isNotNull(top)) { List<T> topList = new ArrayList<>(); try { Field children = depthRecursive(top, checkAttribute(top, childrenName, 0)).getDeclaredField(childrenName); children.setAccessible(true); if (killNoneChild) { if (CollUtil.isNotEmpty(returnList)) children.set(top, returnList); } else { children.set(top, returnList); } topList.add(top); return topList; } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } return returnList; } /** * 检查是否存在属性 */ private static <T> int checkAttribute(T t, String fieldName, int key) { Class<?> clazz = t.getClass(); while (Object.class != clazz) { key++; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (StrUtil.equals(fieldName, field.getName())) { return key; } } clazz = clazz.getSuperclass(); } throw new BaseException(StrUtil.format("对象不存在属性{}", fieldName)); } /** * 递归泛型深度 */ private static <T> Class<?> depthRecursive(T t, int key) { Class<?> clazz = t.getClass(); int i = 1; while (i < key) { clazz = clazz.getSuperclass(); i++; } return clazz; } /** * 递归列表 */ private static <T> void recursionFn(List<T> list, T t, String IdName, String FIdName, String childrenName, boolean killNoneChild) { // 得到子节点列表 List<T> childList = getChildList(list, t, IdName, FIdName); try { Field children = depthRecursive(t, checkAttribute(t, childrenName, 0)).getDeclaredField(childrenName); children.setAccessible(true); if (killNoneChild) { if (CollUtil.isNotEmpty(childList)) children.set(t, childList); } else { children.set(t, childList); } } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } for (T tChild : childList) { if (hasChild(list, tChild, IdName, FIdName)) { recursionFn(list, tChild, IdName, FIdName, childrenName, killNoneChild); } } } /** * 得到子节点列表 */ private static <T> List<T> getChildList(List<T> list, T t, String IdName, String FIdName) { List<T> tList = new ArrayList<T>(); Iterator<T> it = list.iterator(); try { while (it.hasNext()) { T n = (T) it.next(); Field Id = depthRecursive(t, checkAttribute(t, IdName, 0)).getDeclaredField(IdName); Id.setAccessible(true); Field FId = depthRecursive(n, checkAttribute(n, FIdName, 0)).getDeclaredField(FIdName); FId.setAccessible(true); if (ObjectUtil.isNotNull((Long) FId.get(n)) && ((Long) FId.get(n)).longValue() == ((Long) Id.get(t)).longValue()) { tList.add(n); } } } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } return tList; } /** * 判断是否有子节点 */ private static <T> boolean hasChild(List<T> list, T t, String IdName, String FIdName) { return getChildList(list, t, IdName, FIdName).size() > 0; } /** * 删除无法溯源至顶级节点的值 */ private static <T> void deleteNoTopNode(List<T> list, String FIdName, Serializable topNode) { list.removeIf(vo -> { try { Field FId = depthRecursive(vo, checkAttribute(vo, FIdName, 0)).getDeclaredField(FIdName); FId.setAccessible(true); return !Objects.equals(FId.get(vo), topNode); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } return false; }); } /** * 获取树结构叶子节点集合 * 存在默认参数 详见BaseConstants.Entity * childrenName = CHILDREN * * @param list 组装列表 * @return 叶子节点集合 */ public static <T> List<T> getLeafNodes(List<T> list) { return getLeafNodes(list, BaseConstants.Entity.CHILDREN.getCode()); } /** * 获取树结构叶子节点集合 * 存在默认参数 详见BaseConstants.Entity * * @param list 组装列表 * @param childrenName children字段名称 * @return 叶子节点集合 */ public static <T> List<T> getLeafNodes(List<T> list, String childrenName) { List<T> returnList = new ArrayList<>(); try { if (CollUtil.isNotEmpty(list)) { T t = list.stream().findFirst().orElse(null); assert t != null; int childrenKey = checkAttribute(t, childrenName, 0); recursionLeafFn(returnList, list, childrenName, childrenKey); } } catch (Exception ignored) { } return returnList; } /** * 递归列表 */ private static <T> void recursionLeafFn(List<T> returnList, List<T> list, String childrenName, int childrenKey) { for (T vo : list) { try { Field children = depthRecursive(vo, childrenKey).getDeclaredField(childrenName); children.setAccessible(true); List<T> childList = (List<T>) children.get(vo); if (CollUtil.isEmpty(childList)) { returnList.add(vo); } else { recursionLeafFn(returnList, childList, childrenName, childrenKey); } } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } } }
34.879154
175
0.537375
6b137180628c8505eba209dd7d02de28d7f2e7ed
470
package com.jzy.model.dto.search; import lombok.Data; import java.io.Serializable; /** * @author JinZhiyun * @ClassName SearchCondition * @Description 查询的的条件 * @Date 2019/7/25 9:12 * @Version 1.0 **/ @Data public class SearchCondition implements Serializable { private static final long serialVersionUID = 8924463935049190517L; /** * 第一条件:类别 */ private String condition1; /** * 第二条件:升降序 */ private String condition2; }
16.785714
70
0.670213
014fc9e5a34de7f9f0f8ff6c292b81dbe4a55695
216
package cn.bootx.goods.mq; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * 消息发送器 * @author xxm * @date 2021/4/22 */ @Slf4j @RequiredArgsConstructor public class MessageSender { }
14.4
38
0.74537
3e19b3472ac7fee8a8bd65f27f97cf581f416f04
1,995
package at.ac.tuwien.big.xmlintelledit.intelledit.test; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.mwe.utils.StandaloneSetup; import org.eclipse.ocl.ParserException; import org.eclipse.ocl.ecore.OCL; import org.eclipse.ocl.ecore.OCL.Helper; import org.eclipse.ocl.ecore.OCLExpression; import org.eclipse.ocl.ecore.delegate.OCLDelegateDomain; import org.eclipse.ocl.ecore.delegate.OCLInvocationDelegateFactory; import org.eclipse.ocl.ecore.delegate.OCLSettingDelegateFactory; import at.ac.tuwien.big.xmlintelledit.intelledit.oclgen.OCLBooleanExpressionEvaluator; public class InterpretingOCLBooleanExpressionEvaluator implements OCLBooleanExpressionEvaluator<Object> { static { //Just to be able to call everything for OCL new StandaloneSetup().setPlatformUri("./"); // CompleteOCLStandaloneSetup.doSetup(); // OCLinEcoreStandaloneSetup.doSetup(); // OCLstdlibStandaloneSetup.doSetup(); String oclDelegateURI = OCLDelegateDomain.OCL_DELEGATE_URI; EOperation.Internal.InvocationDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI, new OCLInvocationDelegateFactory.Global()); EStructuralFeature.Internal.SettingDelegate.Factory.Registry.INSTANCE.put(oclDelegateURI, new OCLSettingDelegateFactory.Global()); OCL.initialize(null); } private final OCLExpression oclExpression; public InterpretingOCLBooleanExpressionEvaluator(EClassifier context, String oclExpression) { OCL ocl = OCL.newInstance(); Helper oclHelper = ocl.createOCLHelper(); oclHelper.setContext(context); try { this.oclExpression = oclHelper.createQuery(oclExpression); } catch (ParserException ex) { throw new RuntimeException(ex); } } @Override public boolean isValid(Object context) { OCL ocl = OCL.newInstance(); return ocl.check(context, oclExpression); } @Override public EStructuralFeature findErrorFeature(Object self) { return null; } }
33.813559
105
0.803008
9157d601432bb3e3d08cc18475722acda3deb48d
2,505
package com.server.Puzzle.domain.user.service.Impl; import com.server.Puzzle.domain.user.domain.User; import com.server.Puzzle.domain.user.domain.UserLanguage; import com.server.Puzzle.domain.user.dto.UserUpdateDto; import com.server.Puzzle.domain.user.repository.UserLanguageRepository; import com.server.Puzzle.domain.user.repository.UserRepository; import com.server.Puzzle.domain.user.service.UserService; import com.server.Puzzle.global.enumType.Language; import com.server.Puzzle.global.exception.CustomException; import com.server.Puzzle.global.util.CurrentUserUtil; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import static com.server.Puzzle.global.exception.ErrorCode.IS_ALREADY_USER; import static com.server.Puzzle.global.exception.ErrorCode.USER_NOT_FOUND; @RequiredArgsConstructor @Service public class UserServiceImpl implements UserService { private final CurrentUserUtil currentUserUtil; private final UserRepository userRepository; private final UserLanguageRepository userLanguageRepo; @Transactional @Override public void logout() { currentUserUtil.getCurrentUser().updateRefreshToken(null); } @Override public void delete() { User currentUser = currentUserUtil.getCurrentUser(); User savedUser = userRepository.findByName(currentUser.getName()) .orElseThrow(() -> new CustomException(USER_NOT_FOUND)); userRepository.delete(savedUser); } @Transactional @Override public void infoRegistration(UserUpdateDto userInfo) { User user = currentUserUtil.getCurrentUser(); if(!user.isFirstVisited()) throw new CustomException(IS_ALREADY_USER); List<Language> languageList = userInfo.getLanguage(); userLanguageRepo.deleteAllByUserId(user.getId()); for (Language language : languageList) { userLanguageRepo.save(UserLanguage.builder() .user(user) .language(language) .build()); } user .updateName(userInfo.getName()) .updateEmail(userInfo.getEmail()) .updateImageUrl(userInfo.getImageUrl()) .updateBio(userInfo.getBio()) .updateUrl(userInfo.getUrl()) .updateIsFirstVisited(false) .updateField(userInfo.getField()); } }
33.851351
75
0.707784
53e9bcfc4d31c2cfaed0ff532af9a6fe6357ca90
2,480
/** * Copyright (c) 2020, Alexander Kapralov */ package ru.capralow.dt.coverage.internal.ui.annotation; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.osgi.util.NLS; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.ILine; import ru.capralow.dt.coverage.internal.ui.UiMessages; /** * Annotation object that includes its position information to avoid internal * mappings. */ public class CoverageAnnotation extends Annotation { private static final String FULL_COVERAGE = "ru.capralow.dt.coverage.ui.fullCoverageAnnotation"; //$NON-NLS-1$ private static final String PARTIAL_COVERAGE = "ru.capralow.dt.coverage.ui.partialCoverageAnnotation"; //$NON-NLS-1$ private static final String NO_COVERAGE = "ru.capralow.dt.coverage.ui.noCoverageAnnotation"; //$NON-NLS-1$ private static String getAnnotationID(ILine line) { switch (line.getStatus()) { case ICounter.FULLY_COVERED: return FULL_COVERAGE; case ICounter.PARTLY_COVERED: return PARTIAL_COVERAGE; case ICounter.NOT_COVERED: return NO_COVERAGE; default: throw new AssertionError(line.getStatus()); } } private final Position position; private final ILine line; public CoverageAnnotation(int offset, int length, ILine line) { super(getAnnotationID(line), false, null); this.line = line; position = new Position(offset, length); } public ILine getLine() { return line; } public Position getPosition() { return position; } @Override public String getText() { final ICounter branches = line.getBranchCounter(); switch (branches.getStatus()) { case ICounter.NOT_COVERED: return NLS.bind(UiMessages.AnnotationTextAllBranchesMissed_message, Integer.valueOf(branches.getMissedCount())); case ICounter.FULLY_COVERED: return NLS.bind(UiMessages.AnnotationTextAllBranchesCovered_message, Integer.valueOf(branches.getTotalCount())); case ICounter.PARTLY_COVERED: return NLS.bind(UiMessages.AnnotationTextSomeBranchesMissed_message, Integer.valueOf(branches.getMissedCount()), Integer.valueOf(branches.getTotalCount())); default: return null; } } }
29.879518
120
0.672581
5667018b6ecda7ff312e5d73aa775d3384493e69
141
package com.chess.game; public enum PieceStatus { INVALID_MOVE, ONE_MOVE, TAKES, CASTLING, PROMOTION, EN_PASSANT, }
12.818182
25
0.652482
58cab0b5d8cf541917af46b8fe3354e584791309
4,605
package cn.krait.nabo.behavior; import android.animation.Animator; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; import com.google.android.material.floatingactionbutton.FloatingActionButton; /** * @author 权那他(Kraity) * @date 2019/8/1. * GitHub:https://github.com/kraity * WebSite:https://krait.cn * email:kraits@qq.com */ public class DefaultBehavior extends FloatingActionButton.Behavior { private boolean isAnimateIng = false; // 是否正在动画 private boolean isShow = true; // 是否已经显示 public DefaultBehavior(Context context, AttributeSet attrs) { super(); } //只有当返回值为true才会执行下面的方法,例如onNestedScroll @Override public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull FloatingActionButton child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { return super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type) ||axes== ViewCompat.SCROLL_AXIS_VERTICAL; } //滑动时调用该方法 //dxConsumed: 表示view消费了x方向的距离长度 //dyConsumed: 表示view消费了y方向的距离长度 //消费的距离是指实际滚动的距离 /* * coordinatorLayout - the CoordinatorLayout parent of the view this Behavior is associated with child - the child view of the CoordinatorLayout this Behavior is associated with target - the descendant view of the CoordinatorLayout performing the nested scroll dxConsumed - horizontal pixels consumed by the target's own scrolling operation dyConsumed - vertical pixels consumed by the target's own scrolling operation dxUnconsumed - horizontal pixels not consumed by the target's own scrolling operation, but requested by the user dyUnconsumed - vertical pixels not consumed by the target's own scrolling operation, but requested by the user type - the type of input which cause this scroll event */ @Override public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull FloatingActionButton child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { //界面向下滑动,fab动画结束,且正在显示 //隐藏Fab if ((dyConsumed>0||dyUnconsumed>0)&&!isAnimateIng&&isShow){ AnimatorUtil.hideFab(child,new AnimateListener()); } //界面向上滑动,fab动画结束,且隐藏 //显示Fab else if ((dyConsumed<0||dyUnconsumed<0)&&!isAnimateIng&&!isShow){ AnimatorUtil.showFab(child,new AnimateListener()); } } public class AnimateListener implements Animator.AnimatorListener { @Override public void onAnimationStart(Animator animation) { isAnimateIng=true; isShow=!isShow; } @Override public void onAnimationEnd(Animator animation) { isAnimateIng=false; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } } public static class AnimatorUtil { private static AccelerateDecelerateInterpolator LINEAR_INTERRPLATOR =new AccelerateDecelerateInterpolator(); static void showFab(View view, DefaultBehavior.AnimateListener... listener){ if (listener.length!=0){ view.animate() .scaleX(1f) .scaleY(1f) .alpha(1f) .setDuration(300) .setInterpolator(LINEAR_INTERRPLATOR) .setListener(listener[0]) .start(); }else { view.animate() .scaleX(1f) .scaleY(1f) .alpha(1f) .setDuration(300) .setInterpolator(LINEAR_INTERRPLATOR) .start(); } } static void hideFab(View view, DefaultBehavior.AnimateListener listener){ view.animate() .scaleX(0f) .scaleY(0f) .alpha(0f) .setDuration(300) .setInterpolator(LINEAR_INTERRPLATOR) .setListener(listener) .start(); } } }
36.547619
215
0.633008
0d2e56cec286bb64336e59e46e8585c8a3097751
1,045
package me.dablakbandit.dabcore.utils; import java.util.concurrent.atomic.AtomicBoolean; public class MemoryUtil { private static AtomicBoolean memory = new AtomicBoolean(false); public static boolean isMemoryFree(){ return !memory.get(); } public static boolean isMemoryLimited(){ return memory.get(); } public static int calculateMemory(){ long heapSize = Runtime.getRuntime().totalMemory(); long heapMaxSize = Runtime.getRuntime().maxMemory(); if(heapSize < heapMaxSize){ return Integer.MAX_VALUE; } long heapFreeSize = Runtime.getRuntime().freeMemory(); int size = (int) ((heapFreeSize * 100) / heapMaxSize); if(size > (100 - 95)){ memoryPlentifulTask(); return Integer.MAX_VALUE; } return size; } public static void memoryLimitedTask() { memory.set(true); } public static void memoryPlentifulTask() { memory.set(false); } }
26.125
67
0.607656
5ddf349401d6f1e9d2d5c98cf04b009e65a9afae
2,174
package net.bolbat.kit.config; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.configureme.annotations.DontConfigure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link Configuration} abstract functionality. * * @author Alexandr Bolbat */ public abstract class AbstractConfiguration implements Configuration { /** * Generated SerialVersionUID. */ @DontConfigure private static final long serialVersionUID = -8251774226206047496L; /** * {@link Logger} instance. */ @DontConfigure private static final Logger LOGGER = LoggerFactory.getLogger(AbstractConfiguration.class); /** * Listeners. */ @DontConfigure private final transient List<ConfigurationListener> listeners = new CopyOnWriteArrayList<>(); /** * Get listeners. * * @return listeners */ public List<ConfigurationListener> getListeners() { return new ArrayList<>(listeners); } /** * Register listener. * * @param listener * {@link ConfigurationListener} instance */ public void registerListener(final ConfigurationListener listener) { if (listener != null) listeners.add(listener); } /** * Unregister listener. * * @param listener * {@link ConfigurationListener} instance */ public void unregisterListener(final ConfigurationListener listener) { if (listener != null) listeners.remove(listener); } /** * Unregister all listeners. */ public void unregisterListeners() { listeners.clear(); } /** * Fire 'configurationChanged' event for registered listeners. */ protected void fireConfigurationChanged() { if (listeners.isEmpty()) return; for (final ConfigurationListener listener : listeners) { if (listener == null) continue; try { listener.configurationChanged(); // CHECKSTYLE:OFF } catch (final RuntimeException e) { // CHECKSTYLE:ON final String cName = this.getClass().getName(); final String lName = listener.getClass().getName(); LOGGER.warn("Configuration[" + cName + "] 'configurationChanged' event for listener[" + lName + "] fail.", e); } } } }
22.183673
114
0.698712
eec55a7ccaae2e76ac2fe97c63ae20f7d67af4b8
797
package com.bnp.paribas.app.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Getter @Setter @Builder @EqualsAndHashCode @Data @Embeddable public class ProdutoCosifPK implements Serializable { private static final long serialVersionUID = -6610161973818739325L; @Column(name = "COD_PRODUTO",length = 4, nullable = false) private String codProduto; @Column(name = "COD_COSIF",length = 11, nullable = false) private String codCosif; public ProdutoCosifPK(String codProduto,String codCosif) { this.codCosif = codCosif; this.codProduto = codProduto; } public ProdutoCosifPK() { } }
20.435897
68
0.760351
113fc13c5ad658dd6e2c1ca0ded7833076cbcd4d
13,756
/* * Copyright 2015-2016 The OpenDCT Authors. All Rights Reserved * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 opendct.nanohttpd.serializer; import com.google.gson.*; import opendct.capture.CaptureDevice; import opendct.channel.ChannelLineup; import opendct.channel.ChannelManager; import opendct.config.Config; import opendct.config.options.DeviceOption; import opendct.config.options.DeviceOptionException; import opendct.nanohttpd.pojo.JsonException; import opendct.nanohttpd.pojo.JsonOption; import opendct.sagetv.SageTVDeviceCrossbar; import opendct.sagetv.SageTVManager; import opendct.sagetv.SageTVPoolManager; import opendct.tuning.discovery.DiscoveredDevice; import opendct.tuning.discovery.DiscoveryManager; import java.lang.reflect.Type; public class CaptureDevicesSerializer implements JsonSerializer<DiscoveredDevice[]> { public static final String ID = "id"; public static final String ENABLED = "enabled"; public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String LOADED = "loaded"; public static final String POOL_NAME = "poolName"; public static final String POOL_MERIT = "poolMerit"; public static final String LINEUP_NAME = "lineupName"; public static final String LAST_CHANNEL = "lastChannel"; public static final String RECORDING_START = "recordingStart"; public static final String PRODUCED_PACKETS = "producedPackets"; public static final String RECORDED_BYTES = "recordedBytes"; public static final String RECORDING_FILENAME = "recordingFilename"; public static final String RECORDING_QUALITY = "recordingQuality"; public static final String INTERNAL_LOCKED = "internalLocked"; public static final String EXTERNAL_LOCKED = "externalLocked"; public static final String OFFLINE_CHANNEL_SCAN_ENABLED = "offlineChannelScanEnabled"; public static final String UPLOAD_ID = "uploadId"; public static final String SIGNAL_STRENGTH = "signalStrength"; public static final String BROADCAST_STANDARD = "broadcastStandard"; public static final String COPY_PROTECTION = "copyProtection"; public static final String CONSUMER = "consumer"; public static final String CONSUMER_CANONICAL = "consumerCanonical"; public static final String TRANSCODE_PROFILE = "transcodeProfile"; public static final String DEVICE_TYPE = "deviceType"; public static final String SAGETV_DEVICE_CROSSBAR = "sagetvCrossbars"; public static final String OPTIONS = "options"; // Enable or disable devices. public static final String ENABLE_DEVICE = "enableDevice"; public static final String DISABLE_DEVICE = "disableDevice"; private final static DeviceOptionSerializer deviceOptionSerializer = new DeviceOptionSerializer(); private final static SageTVDeviceTypesSerializer deviceTypesSerializer = new SageTVDeviceTypesSerializer(); @Override public JsonElement serialize(DiscoveredDevice[] src, Type typeOfSrc, JsonSerializationContext context) { JsonArray jsonObject = new JsonArray(); for (DiscoveredDevice device : src) { JsonObject object = new JsonObject(); object.addProperty(ID, device.getId()); object.addProperty(ENABLED, DiscoveryManager.isDevicePermitted(device.getId())); object.addProperty(NAME, device.getFriendlyName()); object.addProperty(DESCRIPTION, device.getDescription()); CaptureDevice captureDevice = SageTVManager.getSageTVCaptureDevice(device.getId()); DeviceOption options[] = device.getOptions(); if (captureDevice != null) { object.addProperty(LOADED, true); if (SageTVPoolManager.isUsePools()) { object.addProperty(POOL_NAME, captureDevice.getPoolName()); object.addProperty(POOL_MERIT, captureDevice.getPoolMerit()); } object.addProperty(LINEUP_NAME, captureDevice.getChannelLineup()); object.addProperty(LAST_CHANNEL, captureDevice.getLastChannel()); object.addProperty(RECORDING_START, captureDevice.getRecordStart()); object.addProperty(PRODUCED_PACKETS, captureDevice.getProducedPackets()); object.addProperty(RECORDED_BYTES, captureDevice.getRecordedBytes()); String recordingFilename = captureDevice.getRecordFilename(); object.addProperty(RECORDING_FILENAME, recordingFilename != null ? recordingFilename : ""); object.addProperty(RECORDING_QUALITY, captureDevice.getRecordQuality()); object.addProperty(INTERNAL_LOCKED, captureDevice.isInternalLocked()); object.addProperty(EXTERNAL_LOCKED, captureDevice.isExternalLocked()); object.addProperty(OFFLINE_CHANNEL_SCAN_ENABLED, captureDevice.isOfflineChannelScan()); object.addProperty(UPLOAD_ID, captureDevice.getRecordUploadID()); object.addProperty(SIGNAL_STRENGTH, captureDevice.getSignalStrength()); object.addProperty(COPY_PROTECTION, captureDevice.getCopyProtection().toString()); object.addProperty(CONSUMER, Config.getConsumerFriendlyForCanonical(captureDevice.getConsumerName())); object.addProperty(CONSUMER_CANONICAL, captureDevice.getConsumerName()); object.addProperty(TRANSCODE_PROFILE, captureDevice.getTranscodeProfile()); object.addProperty(DEVICE_TYPE, captureDevice.getEncoderDeviceType().toString()); object.add(SAGETV_DEVICE_CROSSBAR, deviceTypesSerializer.serialize(captureDevice.getSageTVDeviceCrossbars(), SageTVDeviceCrossbar.class, context)); } else { object.addProperty(LOADED, false); } object.add(OPTIONS, deviceOptionSerializer.serialize(options, DeviceOption.class, context)); jsonObject.add(object); } return jsonObject; } public static void addProperty(JsonObject object, String property, DiscoveredDevice device, CaptureDevice captureDevice) { switch (property) { case NAME: object.addProperty(NAME, device.getFriendlyName()); break; case ENABLED: object.addProperty(ENABLED, DiscoveryManager.isDevicePermitted(device.getId())); break; case DESCRIPTION: object.addProperty(DESCRIPTION, device.getDescription()); break; case OPTIONS: object.add(OPTIONS, deviceOptionSerializer.serialize(device.getOptions(), DeviceOption.class, null)); break; case LOADED: object.addProperty(LOADED, captureDevice != null); break; case POOL_NAME: object.addProperty(POOL_NAME, captureDevice.getPoolName()); break; case POOL_MERIT: object.addProperty(POOL_MERIT, captureDevice.getPoolMerit()); break; case LINEUP_NAME: object.addProperty(LINEUP_NAME, captureDevice.getChannelLineup()); break; case LAST_CHANNEL: object.addProperty(LAST_CHANNEL, captureDevice.getLastChannel()); break; case RECORDING_START: object.addProperty(RECORDING_START, captureDevice.getRecordStart()); break; case PRODUCED_PACKETS: object.addProperty(PRODUCED_PACKETS, captureDevice.getProducedPackets()); break; case RECORDED_BYTES: object.addProperty(RECORDED_BYTES, captureDevice.getRecordedBytes()); break; case RECORDING_FILENAME: object.addProperty(RECORDING_FILENAME, captureDevice.getRecordFilename()); break; case RECORDING_QUALITY: object.addProperty(RECORDING_QUALITY, captureDevice.getRecordQuality()); break; case INTERNAL_LOCKED: object.addProperty(INTERNAL_LOCKED, captureDevice.isInternalLocked()); break; case EXTERNAL_LOCKED: object.addProperty(EXTERNAL_LOCKED, captureDevice.isExternalLocked()); break; case OFFLINE_CHANNEL_SCAN_ENABLED: object.addProperty(OFFLINE_CHANNEL_SCAN_ENABLED, captureDevice.isOfflineChannelScan()); break; case UPLOAD_ID: object.addProperty(UPLOAD_ID, captureDevice.getRecordUploadID()); break; case SIGNAL_STRENGTH: object.addProperty(SIGNAL_STRENGTH, captureDevice.getSignalStrength()); break; case COPY_PROTECTION: object.addProperty(COPY_PROTECTION, captureDevice.getCopyProtection().toString()); break; case CONSUMER: object.addProperty(CONSUMER, captureDevice.getConsumerName()); break; case TRANSCODE_PROFILE: object.addProperty(TRANSCODE_PROFILE, captureDevice.getTranscodeProfile()); break; case DEVICE_TYPE: object.addProperty(DEVICE_TYPE, captureDevice.getEncoderDeviceType().toString()); break; case SAGETV_DEVICE_CROSSBAR: object.add(SAGETV_DEVICE_CROSSBAR, deviceTypesSerializer.serialize(captureDevice.getSageTVDeviceCrossbars(), SageTVDeviceCrossbar.class, null)); break; } } public static synchronized JsonException setProperty(JsonOption jsonOption, CaptureDevice captureDevice) { String newValue = jsonOption.getValue(); switch (jsonOption.getProperty()) { case POOL_NAME: if (!captureDevice.getPoolName().equals(newValue)) { captureDevice.setPoolName(newValue); SageTVPoolManager.addPoolCaptureDevice(newValue, captureDevice.toString()); SageTVPoolManager.resortMerits(newValue); } break; case POOL_MERIT: int newMerit; try { newMerit = Integer.parseInt(newValue); } catch (NumberFormatException e) { return new JsonException(POOL_MERIT, "'" + newValue + "' is not an integer."); } if (captureDevice.getPoolMerit() != newMerit) { captureDevice.setPoolMerit(newMerit); SageTVPoolManager.resortMerits(captureDevice.getPoolName()); } break; case LINEUP_NAME: ChannelLineup lineup = ChannelManager.getChannelLineup(newValue); if (lineup == null) { return new JsonException(LINEUP_NAME, "The '" + newValue + "' lineup does not exist."); } if (captureDevice.isOfflineChannelScan()) { ChannelManager.removeDeviceFromOfflineScan(captureDevice.getChannelLineup(), captureDevice.getEncoderName()); ChannelManager.addDeviceToOfflineScan(newValue, captureDevice.getEncoderName()); } captureDevice.setChannelLineup(newValue); break; case OFFLINE_CHANNEL_SCAN_ENABLED: if (!"false".equalsIgnoreCase(newValue) && !"true".equalsIgnoreCase(newValue)) { return new JsonException(OFFLINE_CHANNEL_SCAN_ENABLED, "'" + newValue + "' is not boolean."); } boolean channelScan = "true".equalsIgnoreCase(newValue); if (channelScan) { ChannelManager.addDeviceToOfflineScan(captureDevice.getChannelLineup(), captureDevice.getEncoderName()); } else { ChannelManager.removeDeviceFromOfflineScan(captureDevice.getChannelLineup(), captureDevice.getEncoderName()); } break; case CONSUMER: try { String value = Config.getConsumerCanonicalForFriendly(newValue); if (value != null) { newValue = value; } captureDevice.setConsumerName(newValue); } catch (DeviceOptionException e) { return new JsonException(CONSUMER, e.getMessage()); } break; case TRANSCODE_PROFILE: try { captureDevice.setTranscodeProfile(newValue); } catch (DeviceOptionException e) { return new JsonException(TRANSCODE_PROFILE, e.getMessage()); } break; case DISABLE_DEVICE: if (!"true".equalsIgnoreCase(newValue)) { break; } DiscoveryManager.disableCaptureDevice(captureDevice.getEncoderUniqueHash()); break; } return null; } }
47.930314
163
0.643646
32633fd3f862f045c5db5afc575ff274a6bcdcb6
2,247
package com.seek.hrm.api; import android.content.Intent; import android.util.Log; import android.widget.Toast; import com.seek.hrm.Activities.LoginActivity; import com.seek.hrm.Activities.MainActivity; import com.seek.hrm.Network.IDataResultCallback; import com.seek.hrm.Network.IResultCallback; import com.seek.hrm.Network.RetrofitClient; import com.seek.hrm.POJO.HistoryMeasure; import com.seek.hrm.Parsing.CreateHistoryResponse; import com.seek.hrm.Parsing.HistoriesResponse; import com.seek.hrm.Parsing.LoginResponse; import com.seek.hrm.Session.LoginSession; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class HistoryService { public static void createHistory(int result, IResultCallback callback) { Call<CreateHistoryResponse> call = RetrofitClient.getInstance().getAppService().createHistory(result); call.enqueue(new Callback<CreateHistoryResponse>() { @Override public void onResponse(Call<CreateHistoryResponse> call, Response<CreateHistoryResponse> response) { if (response.isSuccessful()) { callback.onSuccess(true); } else { callback.onSuccess(false); } } @Override public void onFailure(Call<CreateHistoryResponse> call, Throwable t) { callback.onSuccess(false); } }); } public static void getHistory( IDataResultCallback<List<HistoryMeasure>> callback) { Call<HistoriesResponse> call = RetrofitClient.getInstance().getAppService().getHistoryList(); call.enqueue(new Callback<HistoriesResponse>() { @Override public void onResponse(Call<HistoriesResponse> call, Response<HistoriesResponse> response) { if (response.isSuccessful()) { callback.onSuccess(true,response.body().getHistoryMeasure()); } else { callback.onSuccess(false,null); } } @Override public void onFailure(Call<HistoriesResponse> call, Throwable t) { callback.onSuccess(false,null); } }); } }
34.569231
111
0.660881
eb07b5faab4d41c9a9651021932d86b1120315af
3,817
/** * Copyright (c) Orange. All Rights Reserved. * <p> * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.orange.lo.sample.sigfox2lo; import static com.orange.lo.sdk.rest.devicemanagement.Inventory.XCONNECTOR_DEVICES_PREFIX; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.orange.lo.sample.sigfox2lo.sigfox.model.DataUpDto; import com.orange.lo.sdk.LOApiClient; import com.orange.lo.sdk.externalconnector.DataManagementExtConnector; import com.orange.lo.sdk.externalconnector.model.DataMessage; import com.orange.lo.sdk.rest.devicemanagement.Inventory; import com.orange.lo.sdk.rest.model.Device; import com.orange.lo.sdk.rest.model.Group; @SpringBootTest(classes = {Sigfox2loTestConfiguration.class}) @AutoConfigureMockMvc @ExtendWith({SpringExtension.class, MockitoExtension.class}) class Sigfox2loControllerTest { @Autowired private LOApiClient loApiClient; @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; private Inventory inventory; private DataManagementExtConnector dataManagementExtConnector; @BeforeEach void setUp() { inventory = loApiClient.getDeviceManagement().getInventory(); dataManagementExtConnector = loApiClient.getDataManagementExtConnector(); } @Test void shouldPassDataToLoApiWhenDataUpIsEndpointIsCalled() throws Exception { DataUpDto dataUpDto = getDataUpDto(); String dataUpJson = objectMapper.writeValueAsString(dataUpDto); Device device = new Device().withId(XCONNECTOR_DEVICES_PREFIX + dataUpDto.getDevice()).withName("N0D3ID1-name").withGroup(new Group().withId("0ZWkDm")); mockMvc.perform(post("/dataUp") .contentType(MediaType.APPLICATION_JSON) .content(dataUpJson) ).andExpect(status().isOk()); verify(inventory, times(1)) .createDevice(device); verify(dataManagementExtConnector, times(1)) .sendMessage(eq(dataUpDto.getDevice()), argThat(dataMessage -> haveSameValue(dataUpJson, dataMessage))); } private DataUpDto getDataUpDto() { DataUpDto dataUpDto = new DataUpDto(); dataUpDto.setDevice("N0D3ID1"); dataUpDto.setDeviceTypeId("5fc8c7d80"); dataUpDto.setSeqNumber(10L); dataUpDto.setTime(1610964015L); dataUpDto.setData("abcDFE01"); return dataUpDto; } private boolean haveSameValue(String dataUpJson, DataMessage dataMessage) { String ca = null; try { ca = objectMapper.writeValueAsString(dataMessage.getValue()); } catch (JsonProcessingException e) { e.printStackTrace(); } return dataUpJson.equalsIgnoreCase(ca); } }
39.760417
161
0.751375
f63865446a009da44d7073c9a53e145f9e75b939
3,077
// // This file was generated by the Eclipse Implementation of JAXB, v3.0.1 // See https://eclipse-ee4j.github.io/jaxb-ri // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2021.07.26 at 12:23:07 PM YEKT // package com.sankdev.edbind; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; /** * Реквизиты плательщика или получателя в электронных платежных сообщениях сокращенного формата * * <p>Java class for CustomerRUBrf complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CustomerRUBrf"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Bank" type="{urn:cbr-ru:ed:v2.0}BankRU"/&gt; * &lt;/sequence&gt; * &lt;attribute name="INN" type="{urn:cbr-ru:ed:leaftypes:v2.0}INNIDTextType" /&gt; * &lt;attribute name="PersonalAcc" type="{urn:cbr-ru:ed:leaftypes:v2.0}AccountNumberRUIDType" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CustomerRUBrf", propOrder = { "bank" }) public class CustomerRUBrf { @XmlElement(name = "Bank", required = true) protected BankRU bank; @XmlAttribute(name = "INN") protected String inn; @XmlAttribute(name = "PersonalAcc") protected String personalAcc; /** * Gets the value of the bank property. * * @return * possible object is * {@link BankRU } * */ public BankRU getBank() { return bank; } /** * Sets the value of the bank property. * * @param value * allowed object is * {@link BankRU } * */ public void setBank(BankRU value) { this.bank = value; } /** * Gets the value of the inn property. * * @return * possible object is * {@link String } * */ public String getINN() { return inn; } /** * Sets the value of the inn property. * * @param value * allowed object is * {@link String } * */ public void setINN(String value) { this.inn = value; } /** * Gets the value of the personalAcc property. * * @return * possible object is * {@link String } * */ public String getPersonalAcc() { return personalAcc; } /** * Sets the value of the personalAcc property. * * @param value * allowed object is * {@link String } * */ public void setPersonalAcc(String value) { this.personalAcc = value; } }
24.228346
106
0.59441
8ff949baaa11e767f4890d085b91cfd8e637dc38
19,095
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.hop.ui.trans.steps.execsqlrow; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.apache.hop.core.Const; import org.apache.hop.core.util.Utils; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.row.RowMetaInterface; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.trans.TransMeta; import org.apache.hop.trans.step.BaseStepMeta; import org.apache.hop.trans.step.StepDialogInterface; import org.apache.hop.trans.steps.execsqlrow.ExecSQLRowMeta; import org.apache.hop.ui.core.dialog.ErrorDialog; import org.apache.hop.ui.trans.step.BaseStepDialog; public class ExecSQLRowDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = ExecSQLRowMeta.class; // for i18n purposes, needed by Translator2!! private boolean gotPreviousFields = false; private CCombo wConnection; private Label wlInsertField; private Text wInsertField; private FormData fdlInsertField, fdInsertField; private Label wlUpdateField; private Text wUpdateField; private FormData fdlUpdateField, fdUpdateField; private Label wlDeleteField; private Text wDeleteField; private FormData fdlDeleteField, fdDeleteField; private Label wlReadField; private Text wReadField; private FormData fdlReadField, fdReadField; private Label wlSQLFieldName; private CCombo wSQLFieldName; private FormData fdlSQLFieldName, fdSQLFieldName; private FormData fdAdditionalFields; private Label wlCommit; private Text wCommit; private FormData fdlCommit, fdCommit; private Group wAdditionalFields; private ExecSQLRowMeta input; private Label wlSQLFromFile; private Button wSQLFromFile; private FormData fdlSQLFromFile, fdSQLFromFile; private Label wlSendOneStatement; private Button wSendOneStatement; private FormData fdlSendOneStatement, fdSendOneStatement; public ExecSQLRowDialog( Shell parent, Object in, TransMeta transMeta, String sname ) { super( parent, (BaseStepMeta) in, transMeta, sname ); input = (ExecSQLRowMeta) in; } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook( shell ); setShellImage( shell, input ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.Shell.Label" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname = new Label( shell, SWT.RIGHT ); wlStepname.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.Stepname.Label" ) ); props.setLook( wlStepname ); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment( 0, 0 ); fdlStepname.right = new FormAttachment( middle, -margin ); fdlStepname.top = new FormAttachment( 0, margin ); wlStepname.setLayoutData( fdlStepname ); wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wStepname.setText( stepname ); props.setLook( wStepname ); wStepname.addModifyListener( lsMod ); fdStepname = new FormData(); fdStepname.left = new FormAttachment( middle, 0 ); fdStepname.top = new FormAttachment( 0, margin ); fdStepname.right = new FormAttachment( 100, 0 ); wStepname.setLayoutData( fdStepname ); // Connection line wConnection = addConnectionLine( shell, wStepname, middle, margin ); if ( input.getDatabaseMeta() == null && transMeta.nrDatabases() == 1 ) { wConnection.select( 0 ); } wConnection.addModifyListener( lsMod ); // Commit line wlCommit = new Label( shell, SWT.RIGHT ); wlCommit.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.Commit.Label" ) ); props.setLook( wlCommit ); fdlCommit = new FormData(); fdlCommit.left = new FormAttachment( 0, 0 ); fdlCommit.top = new FormAttachment( wConnection, margin ); fdlCommit.right = new FormAttachment( middle, -margin ); wlCommit.setLayoutData( fdlCommit ); wCommit = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wCommit ); wCommit.addModifyListener( lsMod ); fdCommit = new FormData(); fdCommit.left = new FormAttachment( middle, 0 ); fdCommit.top = new FormAttachment( wConnection, margin ); fdCommit.right = new FormAttachment( 100, 0 ); wCommit.setLayoutData( fdCommit ); wlSendOneStatement = new Label( shell, SWT.RIGHT ); wlSendOneStatement.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.SendOneStatement.Label" ) ); props.setLook( wlSendOneStatement ); fdlSendOneStatement = new FormData(); fdlSendOneStatement.left = new FormAttachment( 0, 0 ); fdlSendOneStatement.top = new FormAttachment( wCommit, margin ); fdlSendOneStatement.right = new FormAttachment( middle, -margin ); wlSendOneStatement.setLayoutData( fdlSendOneStatement ); wSendOneStatement = new Button( shell, SWT.CHECK ); wSendOneStatement.setToolTipText( BaseMessages.getString( PKG, "ExecSQLRowDialog.SendOneStatement.Tooltip" ) ); props.setLook( wSendOneStatement ); fdSendOneStatement = new FormData(); fdSendOneStatement.left = new FormAttachment( middle, 0 ); fdSendOneStatement.top = new FormAttachment( wCommit, margin ); fdSendOneStatement.right = new FormAttachment( 100, 0 ); wSendOneStatement.setLayoutData( fdSendOneStatement ); wSendOneStatement.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // SQLFieldName field wlSQLFieldName = new Label( shell, SWT.RIGHT ); wlSQLFieldName.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.SQLFieldName.Label" ) ); props.setLook( wlSQLFieldName ); fdlSQLFieldName = new FormData(); fdlSQLFieldName.left = new FormAttachment( 0, 0 ); fdlSQLFieldName.right = new FormAttachment( middle, -margin ); fdlSQLFieldName.top = new FormAttachment( wSendOneStatement, 2 * margin ); wlSQLFieldName.setLayoutData( fdlSQLFieldName ); wSQLFieldName = new CCombo( shell, SWT.BORDER | SWT.READ_ONLY ); wSQLFieldName.setEditable( true ); props.setLook( wSQLFieldName ); wSQLFieldName.addModifyListener( lsMod ); fdSQLFieldName = new FormData(); fdSQLFieldName.left = new FormAttachment( middle, 0 ); fdSQLFieldName.top = new FormAttachment( wSendOneStatement, 2 * margin ); fdSQLFieldName.right = new FormAttachment( 100, -margin ); wSQLFieldName.setLayoutData( fdSQLFieldName ); wSQLFieldName.addFocusListener( new FocusListener() { public void focusLost( org.eclipse.swt.events.FocusEvent e ) { } public void focusGained( org.eclipse.swt.events.FocusEvent e ) { Cursor busy = new Cursor( shell.getDisplay(), SWT.CURSOR_WAIT ); shell.setCursor( busy ); get(); shell.setCursor( null ); busy.dispose(); } } ); wlSQLFromFile = new Label( shell, SWT.RIGHT ); wlSQLFromFile.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.SQLFromFile.Label" ) ); props.setLook( wlSQLFromFile ); fdlSQLFromFile = new FormData(); fdlSQLFromFile.left = new FormAttachment( 0, 0 ); fdlSQLFromFile.top = new FormAttachment( wSQLFieldName, margin ); fdlSQLFromFile.right = new FormAttachment( middle, -margin ); wlSQLFromFile.setLayoutData( fdlSQLFromFile ); wSQLFromFile = new Button( shell, SWT.CHECK ); wSQLFromFile.setToolTipText( BaseMessages.getString( PKG, "ExecSQLRowDialog.SQLFromFile.Tooltip" ) ); props.setLook( wSQLFromFile ); fdSQLFromFile = new FormData(); fdSQLFromFile.left = new FormAttachment( middle, 0 ); fdSQLFromFile.top = new FormAttachment( wSQLFieldName, margin ); fdSQLFromFile.right = new FormAttachment( 100, 0 ); wSQLFromFile.setLayoutData( fdSQLFromFile ); wSQLFromFile.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { input.setChanged(); } } ); // /////////////////////////////// // START OF Additional Fields GROUP // // /////////////////////////////// wAdditionalFields = new Group( shell, SWT.SHADOW_NONE ); props.setLook( wAdditionalFields ); wAdditionalFields.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.wAdditionalFields.Label" ) ); FormLayout AdditionalFieldsgroupLayout = new FormLayout(); AdditionalFieldsgroupLayout.marginWidth = 10; AdditionalFieldsgroupLayout.marginHeight = 10; wAdditionalFields.setLayout( AdditionalFieldsgroupLayout ); // insert field wlInsertField = new Label( wAdditionalFields, SWT.RIGHT ); wlInsertField.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.InsertField.Label" ) ); props.setLook( wlInsertField ); fdlInsertField = new FormData(); fdlInsertField.left = new FormAttachment( 0, margin ); fdlInsertField.right = new FormAttachment( middle, -margin ); fdlInsertField.top = new FormAttachment( wSQLFromFile, margin ); wlInsertField.setLayoutData( fdlInsertField ); wInsertField = new Text( wAdditionalFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wInsertField ); wInsertField.addModifyListener( lsMod ); fdInsertField = new FormData(); fdInsertField.left = new FormAttachment( middle, 0 ); fdInsertField.top = new FormAttachment( wSQLFromFile, margin ); fdInsertField.right = new FormAttachment( 100, 0 ); wInsertField.setLayoutData( fdInsertField ); // Update field wlUpdateField = new Label( wAdditionalFields, SWT.RIGHT ); wlUpdateField.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.UpdateField.Label" ) ); props.setLook( wlUpdateField ); fdlUpdateField = new FormData(); fdlUpdateField.left = new FormAttachment( 0, margin ); fdlUpdateField.right = new FormAttachment( middle, -margin ); fdlUpdateField.top = new FormAttachment( wInsertField, margin ); wlUpdateField.setLayoutData( fdlUpdateField ); wUpdateField = new Text( wAdditionalFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wUpdateField ); wUpdateField.addModifyListener( lsMod ); fdUpdateField = new FormData(); fdUpdateField.left = new FormAttachment( middle, 0 ); fdUpdateField.top = new FormAttachment( wInsertField, margin ); fdUpdateField.right = new FormAttachment( 100, 0 ); wUpdateField.setLayoutData( fdUpdateField ); // Delete field wlDeleteField = new Label( wAdditionalFields, SWT.RIGHT ); wlDeleteField.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.DeleteField.Label" ) ); props.setLook( wlDeleteField ); fdlDeleteField = new FormData(); fdlDeleteField.left = new FormAttachment( 0, margin ); fdlDeleteField.right = new FormAttachment( middle, -margin ); fdlDeleteField.top = new FormAttachment( wUpdateField, margin ); wlDeleteField.setLayoutData( fdlDeleteField ); wDeleteField = new Text( wAdditionalFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wDeleteField ); wDeleteField.addModifyListener( lsMod ); fdDeleteField = new FormData(); fdDeleteField.left = new FormAttachment( middle, 0 ); fdDeleteField.top = new FormAttachment( wUpdateField, margin ); fdDeleteField.right = new FormAttachment( 100, 0 ); wDeleteField.setLayoutData( fdDeleteField ); // Read field wlReadField = new Label( wAdditionalFields, SWT.RIGHT ); wlReadField.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.ReadField.Label" ) ); props.setLook( wlReadField ); fdlReadField = new FormData(); fdlReadField.left = new FormAttachment( 0, 0 ); fdlReadField.right = new FormAttachment( middle, -margin ); fdlReadField.top = new FormAttachment( wDeleteField, margin ); wlReadField.setLayoutData( fdlReadField ); wReadField = new Text( wAdditionalFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wReadField ); wReadField.addModifyListener( lsMod ); fdReadField = new FormData(); fdReadField.left = new FormAttachment( middle, 0 ); fdReadField.top = new FormAttachment( wDeleteField, margin ); fdReadField.right = new FormAttachment( 100, 0 ); wReadField.setLayoutData( fdReadField ); fdAdditionalFields = new FormData(); fdAdditionalFields.left = new FormAttachment( 0, margin ); fdAdditionalFields.top = new FormAttachment( wSQLFromFile, 2 * margin ); fdAdditionalFields.right = new FormAttachment( 100, -margin ); wAdditionalFields.setLayoutData( fdAdditionalFields ); // /////////////////////////////// // END OF Additional Fields GROUP // // /////////////////////////////// // Some buttons wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); setButtonPositions( new Button[] { wOK, wCancel }, margin, wAdditionalFields ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; wCancel.addListener( SWT.Selection, lsCancel ); wOK.addListener( SWT.Selection, lsOK ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wStepname.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); getData(); input.setChanged( changed ); // Set the shell size, based upon previous time... setSize(); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { wCommit.setText( "" + input.getCommitSize() ); if ( input.getSqlFieldName() != null ) { wSQLFieldName.setText( input.getSqlFieldName() ); } if ( input.getDatabaseMeta() != null ) { wConnection.setText( input.getDatabaseMeta().getName() ); } if ( input.getUpdateField() != null ) { wUpdateField.setText( input.getUpdateField() ); } if ( input.getInsertField() != null ) { wInsertField.setText( input.getInsertField() ); } if ( input.getDeleteField() != null ) { wDeleteField.setText( input.getDeleteField() ); } if ( input.getReadField() != null ) { wReadField.setText( input.getReadField() ); } wSQLFromFile.setSelection( input.isSqlFromfile() ); wSendOneStatement.setSelection( input.IsSendOneStatement() ); wStepname.selectAll(); wStepname.setFocus(); } private void cancel() { stepname = null; input.setChanged( changed ); dispose(); } private void ok() { if ( Utils.isEmpty( wStepname.getText() ) ) { return; } input.setCommitSize( Const.toInt( wCommit.getText(), 0 ) ); stepname = wStepname.getText(); // return value input.setSqlFieldName( wSQLFieldName.getText() ); // copy info to TextFileInputMeta class (input) input.setDatabaseMeta( transMeta.findDatabase( wConnection.getText() ) ); input.setInsertField( wInsertField.getText() ); input.setUpdateField( wUpdateField.getText() ); input.setDeleteField( wDeleteField.getText() ); input.setReadField( wReadField.getText() ); input.setSqlFromfile( wSQLFromFile.getSelection() ); input.SetSendOneStatement( wSendOneStatement.getSelection() ); if ( input.getDatabaseMeta() == null ) { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage( BaseMessages.getString( PKG, "ExecSQLRowDialog.InvalidConnection.DialogMessage" ) ); mb.setText( BaseMessages.getString( PKG, "ExecSQLRowDialog.InvalidConnection.DialogTitle" ) ); mb.open(); return; } dispose(); } private void get() { if ( !gotPreviousFields ) { gotPreviousFields = true; try { String sqlfield = wSQLFieldName.getText(); wSQLFieldName.removeAll(); RowMetaInterface r = transMeta.getPrevStepFields( stepname ); if ( r != null ) { wSQLFieldName.removeAll(); wSQLFieldName.setItems( r.getFieldNames() ); } if ( sqlfield != null ) { wSQLFieldName.setText( sqlfield ); } } catch ( HopException ke ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "ExecSQLRowDialog.FailedToGetFields.DialogTitle" ), BaseMessages .getString( PKG, "ExecSQLRowDialog.FailedToGetFields.DialogMessage" ), ke ); } } } }
39.290123
115
0.692694
b6ec64a6754e21592384efd17492871e116fea95
6,019
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.spaceship; import com.jme3.app.SimpleApplication; import com.jme3.asset.AssetManager; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.font.BitmapFont; import com.jme3.font.BitmapText; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.control.AbstractControl; import com.jme3.scene.control.Control; import java.io.IOException; import java.util.LinkedList; import java.util.List; /** * * @author mifth */ public class AimingControl extends AbstractControl { private SimpleApplication app; private AssetManager asm; private List<Spatial> list; private float timer; private Camera cam; private Node player; private Spatial aim; private BitmapText ch; private Vector2f centerCam; private float distanceToRemove; public AimingControl(SimpleApplication app, Node player) { this.app = app; asm = this.app.getAssetManager(); cam = app.getCamera(); this.player = player; list = new LinkedList<Spatial>(); timer = 0f; centerCam = new Vector2f(cam.getWidth() / 2, cam.getHeight() / 2); distanceToRemove = 300f; BitmapFont guiFont = asm.loadFont("Interface/Fonts/Default.fnt"); ch = new BitmapText(guiFont, false); ch.setSize(guiFont.getCharSet().getRenderedSize()); ch.setColor(new ColorRGBA(1f, 0.35f, 0.1f, 0.8f)); } public void addToSelection(Spatial sp) { list.add(sp); } public void removeFromSelection(Spatial sp) { list.remove(sp); } public void setAim() { Spatial aimPossible = null; // Vector3f aimScreenPos = cam.getScreenCoordinates(aim.getWorldTranslation()); // float aimWorldDistance = player.getWorldTranslation().distance(aim.getWorldTranslation()); // float aimScreenDistance = centerCam.distance(new Vector2f(aimScreenPos.getX(), aimScreenPos.getY())); for (Spatial sp : list) { Vector3f spScreenPos = cam.getScreenCoordinates(sp.getWorldTranslation()); float spWorldDistance = player.getWorldTranslation().distance(sp.getWorldTranslation()); float spScreenDistance = centerCam.distance(new Vector2f(spScreenPos.getX(), spScreenPos.getY())); // Possible AIM Searching if (aim == null && spScreenPos.getZ() < 1f && spScreenDistance <= (cam.getHeight() * 0.5) * 0.6f && spScreenPos.getZ() < distanceToRemove) { if (aimPossible == null) { aimPossible = sp; } else if (aimPossible != null) { float aimPosibleWorldDistance = player.getWorldTranslation().distance(aimPossible.getWorldTranslation()); if (spWorldDistance < aimPosibleWorldDistance) { aimPossible = sp; } } } else if (aim != null && spScreenPos.getZ() < 1f && spScreenDistance <= (cam.getHeight() * 0.5) * 0.6f && !sp.equals(aim) && spScreenPos.getZ() < distanceToRemove) { float aimPosibleWorldDistance = player.getWorldTranslation().distance(aim.getWorldTranslation()); if (spWorldDistance < aimPosibleWorldDistance) { aimPossible = sp; } } } // set Aim if (aimPossible != null) { aim = aimPossible; } } public Spatial getAim() { return aim; } @Override protected void controlUpdate(float tpf) { // timer += tpf * 3f; // // if (timer > 5f) { // timer = 0; // } if (aim != null) { Vector3f screenPos = cam.getScreenCoordinates(aim.getWorldTranslation()); float worldDistance = player.getWorldTranslation().distance(aim.getWorldTranslation()); float screenDistance = centerCam.distance(new Vector2f(screenPos.getX(), screenPos.getY())); // System.out.println(screenPos.getZ()); if (screenDistance <= (cam.getHeight() * 0.5) * 0.6f && screenPos.getZ() < 1f) { ch.setText("Selected: " + aim.getName()); ch.setLocalTranslation(cam.getScreenCoordinates(aim.getLocalTranslation())); app.getGuiNode().attachChild(ch); } else { app.getGuiNode().detachChild(ch); } if (worldDistance > distanceToRemove) { aim = null; } } else if (aim == null) { app.getGuiNode().detachChild(ch); } } @Override protected void controlRender(RenderManager rm, ViewPort vp) { //Only needed for rendering-related operations, //not called when spatial is culled. } public Control cloneForSpatial(Spatial spatial) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule in = im.getCapsule(this); //TODO: load properties of this Control, e.g. //this.value = in.readFloat("name", defaultValue); } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule out = ex.getCapsule(this); //TODO: save properties of this Control, e.g. //out.write(this.value, "name", defaultValue); } }
32.711957
132
0.604585
3cb32fe9e2e87d600681573c36c8cef607505e9a
10,378
package org.hswebframework.iot.interaction.vertx.client; import com.alibaba.fastjson.JSON; import io.vertx.core.Vertx; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.eventbus.ReplyException; import io.vertx.core.eventbus.ReplyFailure; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.hswebframework.iot.interaction.core.ErrorCode; import org.hswebframework.iot.interaction.core.IotCommand; import org.hswebframework.iot.interaction.core.IotCommandSender; import org.hswebframework.iot.interaction.events.CommandSendEvent; import org.hswebframework.iot.interaction.events.DeviceConnectEvent; import org.hswebframework.iot.interaction.events.DeviceDisconnectEvent; import org.hswebframework.web.BusinessException; import org.hswebframework.web.concurrent.counter.Counter; import org.hswebframework.web.concurrent.counter.CounterManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Date; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; /** * @author zhouhao * @since 1.0.0 */ @Component @Slf4j public class HashMapClientRepository implements ClientRepository, IotCommandSender { @Autowired private Vertx vertx; private Map<String, Client> repository = new ConcurrentHashMap<>(); @Autowired private CounterManager counterManager; private Map<String, MessageConsumer<?>> consumerMap = new ConcurrentHashMap<>(); private long timeout = 10 * 60 * 1000L; @Autowired private ApplicationEventPublisher eventPublisher; @Override public Client getClient(String idOrClientId) { Client client = repository.get(idOrClientId); if (client != null) { //客户端太久没有ping if (System.currentTimeMillis() - client.lastPingTime() > timeout) { log.debug("客户端[{}]链接失效,上一次ping时间:{} ", idOrClientId, client.lastPingTime()); unregister(client.getClientId()); return null; } } return client; } protected Client doRegister(Client client) { log.debug("注册客户端:{}", client); repository.put(client.getClientId(), client); //如果id和clientId不同,则同时注册 if (!client.getClientId().equals(client.getId())) { repository.put(client.getId(), client); } //发布设备连接给spring事件 eventPublisher.publishEvent(new DeviceConnectEvent(client.getClientId(), new Date())); if (vertx.isClustered()) { //集群下通过eventBus来接收从集群的其他节点发来的命令 /* 场景: 1. 集群中有2个节点A,B 2. 客户端[client_0001]注册到了节点A,节点A会在eventBus订阅事件,地址[iot-command-client_0001] 3. 节点B接收到了来自其他服务(plugin-server)向客户端[client_0001]发送指令的请求 4. 节点B发现客户端[client_0001]并没有在节点B中注册 5. 节点B往eventBus中的地址[iot-command-client_0001]发送CommandSendEvent事件 6. 节点A接收到事件,向注册到本地的客户端[client_0001]发送命令,并回复发送情况 */ MessageConsumer consumer = vertx.eventBus() .consumer(createCommandSendEventAddress(client.getClientId()), msg -> { Object event = msg.body(); try { log.info("接收到从eventBus发送的命令:{}", event); if (event instanceof String) { event = JSON.parseObject(((String) event), CommandSendEvent.class); } if (event instanceof CommandSendEvent) { CommandSendEvent e = ((CommandSendEvent) event); boolean success = doLocalSend(e.getTopic(), e.getClientId(), e.getCommand()); if (success) { msg.reply("ok"); } else { msg.reply("客户端未注册"); } } } catch (Exception e) { log.warn(e.getMessage(), e); msg.reply("error:" + e.getMessage()); } }); consumerMap.put(client.getClientId(), consumer); } counter.add(1L); return client; } @Override public Client register(Client client) { Client old = getClient(client.getClientId()); if (null != old) { doUnregister(old.getClientId(), (success) -> { doRegister(client); }); } else { doRegister(client); } return old; } private Counter counter; @PostConstruct public void init() { counter = counterManager.getCounter("iot-device-client-counter"); } @Override public long total() { return counter.get(); } protected boolean doLocalSend(String topic, String clientId, IotCommand command) { Client client = getClient(clientId); if (null != client) { log.debug("向客户端[{}]发送指令:{}", clientId, command); //注册在本地则直接推送 client.send(topic, command); return true; } else { log.warn("设备[{}]未注册,发送命令失败:[{}]", clientId, command); return false; } } public Client doUnregister(String idOrClientId, Consumer<Boolean> supplier) { Client old = repository.remove(idOrClientId); if (old != null) { log.debug("注销客户端:{}", old); repository.remove(old.getId()); repository.remove(old.getClientId()); if (vertx.isClustered()) { Optional.ofNullable(consumerMap.get(old.getClientId())) .ifPresent(consumer -> consumer.unregister(result -> { supplier.accept(result.succeeded()); if (result.succeeded()) { log.debug("unregister event bus consumer:[{}] success ", old.getClientId()); } else { log.error("unregister event bus consumer:[{}] error ", old.getClientId(), result.cause()); } })); } else { supplier.accept(true); } //发布连接断开事件给spring eventPublisher.publishEvent(new DeviceDisconnectEvent(old.getClientId(), new Date())); old.close(); counter.getAndAdd(-1L); } else { supplier.accept(false); } return old; } @Override public Client unregister(String idOrClientId) { return doUnregister(idOrClientId, (success) -> { }); } protected String createCommandSendEventAddress(String clientId) { return "iot-command-".concat(clientId); } @Override @SneakyThrows public void send(String topic, String clientId, IotCommand command) { command.tryValidate(); Client client = getClient(clientId); if (null != client) { doLocalSend(topic, clientId, command); } else if (vertx.isClustered()) { //集群下使用eventBus发送事件 String address = createCommandSendEventAddress(clientId); log.debug("尝试向集群中的其他节点发送客户端[{}]命令:{}", clientId, command); CountDownLatch latch = new CountDownLatch(1); AtomicReference<Throwable> errorReference = new AtomicReference<>(); vertx.eventBus() .send(address, CommandSendEvent.builder() .topic(topic) .clientId(clientId) .command(command) .build() .toJSONString(), handler -> { try { if (handler.succeeded()) { log.debug("成功向集群中的其他节点发送客户端[{}]命令:{},节点返回:{}", clientId, command, handler.result().body()); Object body = handler.result().body(); if (!"ok".equals(body)) { errorReference.set(new BusinessException("设备未注册", ErrorCode.unregistered.getValue())); } } else { errorReference.set(handler.cause()); } } finally { latch.countDown(); } }); try { boolean success = latch.await(10, TimeUnit.SECONDS); if (!success) { throw new BusinessException("等待执行超时", ErrorCode.timeout.getValue()); } } catch (Exception e) { log.warn(e.getMessage(), e); return; } //判断错误原因 Throwable error = errorReference.get(); if (error != null) { if (error instanceof ReplyException) { ReplyFailure failure = ((ReplyException) error).failureType(); switch (failure) { case TIMEOUT: throw new BusinessException("等待执行超时", ErrorCode.timeout.getValue()); case NO_HANDLERS: throw new BusinessException("设备未注册", ErrorCode.unregistered.getValue()); default: throw new BusinessException("发送指令失败:" + failure, ErrorCode.unknown.getValue()); } } throw error; } } else { throw new BusinessException("设备未注册", ReplyFailure.NO_HANDLERS.name()); } } }
39.015038
131
0.533725
7efb1c4888e6a5a61ff64df4f280615767118fdf
1,323
package ie.gmit.sw.ds.server; import java.io.File; import java.util.ArrayList; import java.util.List; /** * This class contains methods to return a List of files in a folder. * @author RnDMizeD * @version 1.0 */ public class FolderReader { private String path; /** * Construct a FolderReader for given path. * @param path the path where files will be read from. */ public FolderReader(String path){ this.path = path; } /** * * @return current path. */ public String getPath() { return path; } /** * * @param path Set the path. */ public void setPath(String path) { this.path = path; } /** * This method returns a List of files * @return List of Strings containing file names and directories. */ public List<String> getList() { List<String> list = new ArrayList<>(); File[] listOfFiles = getFileArray(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { list.add("File " + listOfFiles[i].getName()); } else if (listOfFiles[i].isDirectory()) { list.add("Directory " + listOfFiles[i].getName()); } } return list; } /** * * @return a File array of files of a folder. */ private File[] getFileArray() { File folder = new File(path); return folder.listFiles(); } }
22.05
70
0.619048
993908890f6f8114073f8f1c9aa6402b1869f199
793
package com.iniesta.ditoolfx.core; import io.micronaut.context.BeanContext; import javafx.fxml.FXMLLoader; import javax.inject.Singleton; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URL; @Singleton public class LoaderFXMLFactory { private final BeanContext beanContext; public LoaderFXMLFactory(BeanContext beanContext) { this.beanContext = beanContext; } public FXMLLoader get(URL location){ FXMLLoader loader = new FXMLLoader(location); loader.setControllerFactory(this::getControllerFactory); return loader; } /** * With Micronaut DI... * @param clazz * @param <T> * @return */ private <T> T getControllerFactory(Class<T> clazz) { return beanContext.getBean(clazz); } }
22.027778
60
0.740227
fd54769584e01c4d5356bd3d014baa6c8e60fdc7
1,266
/* Project Termux UX Package java.com.pomaretta.termux.Menu Version 1.0 Author Carlos Pomares Date 2021-03-18 DESCRIPTION */ package com.github.pomaretta.termux.Menu; import java.io.BufferedReader; import com.github.pomaretta.termux.Command.DefaultCommandParser; import com.github.pomaretta.termux.Error.ErrorLog; /** * @author Carlos Pomares */ public abstract class SelectionInteractiveMenu extends DefaultInteractiveMenu { /** * The selection menu. */ protected SelectionMenu selectionMenu; /** * * Allows to create a loop within the selection menu that will show up * the selection menu within the option menu. * * @param e the errorlog. * @param o the option menu. * @param p the command parser. * @param r the reader for user input. * @param s the shell. * @param sm the selection menu. */ public SelectionInteractiveMenu(ErrorLog e, DefaultMenu o, DefaultCommandParser p, BufferedReader r, String s, SelectionMenu sm) { super(e, o, p, r, s); this.selectionMenu = sm; } @Override protected void loopBlock() { selectionMenu.show(); optionMenu.show(); } }
22.607143
134
0.64218
db9f99681886fc4c63bd078649943c237cd189c5
1,126
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.glass.ui.gtk; import com.sun.glass.ui.Clipboard; import com.sun.glass.ui.SystemClipboard; import java.util.HashMap; final class GtkSystemClipboard extends SystemClipboard { public GtkSystemClipboard() { super(Clipboard.SYSTEM); init(); } @Override protected void close() { super.close(); dispose(); } private native void init(); private native void dispose(); @Override protected native boolean isOwner(); @Override protected native void pushToSystem(HashMap<String, Object> cacheData, int supportedActions); @Override protected native void pushTargetActionToSystem(int actionDone); @Override protected native Object popFromSystem(String mimeType); @Override protected native int supportedSourceActionsFromSystem(); @Override protected native String[] mimesFromSystem(); }
16.80597
96
0.666963
046237aa23e8c16d735ae88a1e99a92be176b3cf
3,115
package utils; public class MessageTools { public static byte[] copyOf(byte[] message) { if (message==null) return null; byte[] copy = new byte[message.length]; for (int i = 0; i < message.length; i++) { copy[i] = message[i]; } return copy; } public static boolean equal(byte[] a, byte[] b) { if( a.length != b.length ) return false; for( int i=0; i<a.length; ++i) if( a[i] != b[i] ) return false; return true; } public static byte[] getZeroMessage(int messageSize) { byte[] zeroVector = new byte[messageSize]; for (int i = 0; i < zeroVector.length; i++) { zeroVector[i] = 0x00; } return zeroVector; } /** * Concatenates messages in a way that makes it possible to unambiguously * split the message into the original messages (it adds length of the * first message at the beginning of the returned message). */ public static byte[] concatenate(byte[] m1, byte[] m2) { // Concatenated Message --> byte[0-3] = Integer, Length of Message 1 byte[] out = new byte[m1.length + m2.length + 4]; // 4 bytes for length byte[] len = intToByteArray(m1.length); // copy all bytes to output array int j = 0; for( int i=0; i<len.length; ++i ) out[j++] = len[i]; for( int i=0; i<m1.length; ++i ) out[j++] = m1[i]; for( int i=0; i<m2.length; ++i ) out[j++] = m2[i]; return out; } /** * Simply concatenates the messages (without adding any information for * de-concatenation). */ public static byte[] raw_concatenate(byte[] a, byte[] b) { byte[] result = new byte[a.length + b.length]; int j = 0; for( int i=0; i<a.length; ++i ) result[j++] = a[i]; for( int i=0; i<b.length; ++i ) result[j++] = b[i]; return result; } /** * Projection of the message to its two parts (part 1 = position 0, part 2 = position 1) Structure of the expected data: 1 Byte Identifier [0x01], 4 Byte * length of m1, m1, m2 */ private static byte[] project(byte[] message, int position) { try { int len = byteArrayToInt(message); if (len > (message.length - 4)) return new byte[]{}; // Something is wrong with the message! if (position == 0) { byte[] m1 = new byte[len]; for (int i = 0; i < len; i ++) m1[i] = message[i + 4]; return m1; } else if (position == 1) { byte[] m2 = new byte[message.length - len - 4]; for (int i = 0; i < message.length - len - 4; i ++) m2[i] = message[i + 4 + len]; return m2; } else return new byte[]{}; } catch (Exception e) { return new byte[]{}; } } public static byte[] first(byte[] in) { return project(in, 0); } public static byte[] second(byte[] in) { return project(in, 1); } public static final int byteArrayToInt(byte [] b) { return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF); } public static final byte[] intToByteArray(int value) { return new byte[] { (byte)(value >>> 24), (byte)(value >>> 16), (byte)(value >>> 8), (byte)value}; } }
28.577982
154
0.570144
d2010e8eb121a2621933a38a68780d17c0f48b4e
1,669
package netty.tomcat.servlet; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.util.CharsetUtil; import java.net.URLDecoder; import java.util.List; import java.util.Map; /** * @author: 程序员七哥 * @date: 2021-12-13 * @description: 自定义请求类 */ public class CustomHttpRequest { private HttpRequest httpRequest; private ChannelHandlerContext channelHandlerContext; public CustomHttpRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext) { this.httpRequest = httpRequest; this.channelHandlerContext = channelHandlerContext; } /** * 获取请求的URI,其中是包含请求路径与请求参数的 * @return */ public String getUri() { // 需要使用 URLDecoder 进行解码,否则中文会乱码 return URLDecoder.decode(httpRequest.uri(),CharsetUtil.UTF_8); } /** * 获取请求方式(POST、GET等) */ public String getMethod() { return httpRequest.method().name(); } // 获取所有请求参数列表 public Map<String, List<String>> getParameters() { QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri()); return decoder.parameters(); } // 获取到请求路径 public String getPath() { return new QueryStringDecoder(httpRequest.uri()).path(); } // 获取指定名称的参数 public List<String> getParameters(String name) { return this.getParameters().get(name); } public String getParameter(String name) { List<String> list = this.getParameters(name); if(list == null) { return null; } return list.get(0); } }
24.544118
100
0.666866
b2b60a3289b2cddedab669b0d1c28e89bf7cd969
1,203
package net.floodlightcontroller.hand; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * * @author wallnerryan * */ public class HANDResource extends ServerResource { @Get("json") public Object handleRequest(){ IHANDService hand = (IHANDService)getContext().getAttributes(). get(IHANDService.class.getCanonicalName()); //Retrieve the operation demanded in the REST url. String foo = (String) getRequestAttributes().get("foo"); if (foo.equalsIgnoreCase("status")){ return hand.isHANDEnabled(); } else if (foo.equalsIgnoreCase("enable")){ hand.enableHAND(true); return "{\"result\" : \"success\", \"details\" : \"HAND is running\"}"; } else if (foo.equalsIgnoreCase("disable")){ hand.enableHAND(false); return "{\"result\" : \"success\", \"details\" : \"HAND is stopped\"}"; } else if (foo.equalsIgnoreCase("messages")){ if(hand.getMessages().isEmpty()){ return "There are currently no administrative messages."; } else{ return hand.getMessages(); } } //If {foo} does not match any option return "{\"status\" : \"failure\", \"details\" : \"invalid operation\"}"; } }
22.277778
75
0.652535
1ea782e6ce4aa83054a2b8671e1918734efab952
2,839
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 2002, 2013. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.plaf.synth; import java.awt.Graphics; import javax.swing.*; import javax.swing.text.*; import javax.swing.plaf.ComponentUI; /** * Provides the Synth L&amp;F UI delegate for * {@link javax.swing.JPasswordField}. * * @author Shannon Hickey * @since 1.7 */ public class SynthPasswordFieldUI extends SynthTextFieldUI { /** * Creates a UI for a JPasswordField. * * @param c the JPasswordField * @return the UI */ public static ComponentUI createUI(JComponent c) { return new SynthPasswordFieldUI(); } /** * Fetches the name used as a key to look up properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name ("PasswordField") */ @Override protected String getPropertyPrefix() { return "PasswordField"; } /** * Creates a view (PasswordView) for an element. * * @param elem the element * @return the view */ @Override public View create(Element elem) { return new PasswordView(elem); } /** * {@inheritDoc} */ @Override void paintBackground(SynthContext context, Graphics g, JComponent c) { context.getPainter().paintPasswordFieldBackground(context, g, 0, 0, c.getWidth(), c.getHeight()); } /** * {@inheritDoc} */ @Override public void paintBorder(SynthContext context, Graphics g, int x, int y, int w, int h) { context.getPainter().paintPasswordFieldBorder(context, g, x, y, w, h); } /** * {@inheritDoc} */ @Override protected void installKeyboardActions() { super.installKeyboardActions(); ActionMap map = SwingUtilities.getUIActionMap(getComponent()); if (map != null && map.get(DefaultEditorKit.selectWordAction) != null) { Action a = map.get(DefaultEditorKit.selectLineAction); if (a != null) { map.put(DefaultEditorKit.selectWordAction, a); } } } }
23.857143
80
0.569567
6184dea85bc5d9f4f4fe47e22f4a459d896ef2cb
875
package com.bbstone.comm.model; import com.bbstone.comm.dto.req.AuthStartReq; import lombok.Data; @Data public class ServerAuthInfo { private AuthStartReq authStartReq; // md5(connInfo.ip+connInfo.port+connInfo.username) private String connId; // R2: server generated random code private String srvRand; /** * used for double side authentication * * client used srvRand and client provided password to calc srvRandAnswer, * server will calc the srvRandAnswer again with the username's password store in server side, * if client srvRandAnswer same as server calc value, this field has value */ private String srvRandAnswer; /** * after srvRandAnswer field set, server generate accessToken for client */ private String accessToken; public ServerAuthInfo() {} public ServerAuthInfo(String connId) { this.connId = connId; } }
21.875
95
0.745143
d8f34c07f1995393ff30a6a92cd03234635b03f7
2,469
package dsn.dev.java; import java.util.Iterator; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.concurrent.locks.*; public class Serverlet extends Clientlet { public Serverlet(String name, int task_bucket_count) { super(task_bucket_count); _name = name; lock = new ReentrantLock(); handlers = new ConcurrentHashMap<TaskCode, RpcRequestCallbackHandler>(); } public void Unregister() { Iterator<Entry<TaskCode, RpcRequestCallbackHandler>> iter = handlers.entrySet().iterator(); while (iter.hasNext()) { Entry<TaskCode, RpcRequestCallbackHandler> entry = iter.next(); UnregisterRpcHandler(entry.getKey()); } } public static void RpcRequestCallback(long req, int index) { RpcRequestCallbackHandler cb = (RpcRequestCallbackHandler) GlobalInterOpLookupTable.Get(index); cb.callback(req); } protected boolean RegisterRpcHandler(TaskCode code, String name, RpcRequestHandler handler) { RpcRequestCallbackHandler cb = new RpcRequestCallbackHandler(handler); int index = GlobalInterOpLookupTable.Put(cb); boolean r = Nativecalls.dsn_rpc_register_handler(code.Code(), name, index); Logging.dassert(r, "rpc handler registration failed for " + code.ToString()); lock.lock(); try { handlers.put(code, cb); } finally { lock.unlock(); } return r; } protected boolean RegisterRpcHandler(TaskCode code, String name, RpcRequestHandlerOneWay handler) { RpcRequestCallbackHandler cb = new RpcRequestCallbackHandler(handler); int index = GlobalInterOpLookupTable.Put(cb); boolean r = Nativecalls.dsn_rpc_register_handler(code.Code(), name, index); Logging.dassert(r, "rpc handler registration failed for " + code.ToString()); lock.lock(); try { handlers.put(code, cb); } finally { lock.unlock(); } return r; } protected boolean UnregisterRpcHandler(TaskCode code) { Nativecalls.dsn_rpc_unregiser_handler(code.Code()); return true; } protected void Reply(RpcWriteStream response) { Logging.dassert(response.IsFlushed(), "RpcWriteStream must be flushed after write in the same thread"); Nativecalls.dsn_rpc_reply(response.handle()); } public String Name() { return _name; } private String _name; private ConcurrentHashMap<TaskCode, RpcRequestCallbackHandler> handlers; private Lock lock; }
27.433333
108
0.703524
42b6fcf2077c62a60a7b0f4fa721c1ac34b45894
1,093
package io.codegen.gwt.jsonoverlay.processor.builder; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.TypeElement; import javax.lang.model.util.SimpleAnnotationValueVisitor8; import io.codegen.gwt.jsonoverlay.processor.model.JavaType; public class JsonSubTypesVisitor extends SimpleAnnotationValueVisitor8<Map<String, JavaType>, Void> { private final Consumer<TypeElement> consumer; public JsonSubTypesVisitor(Consumer<TypeElement> consumer) { this.consumer = consumer; } @Override protected Map<String, JavaType> defaultAction(Object o, Void p) { throw new UnsupportedOperationException(); } public Map<String, JavaType> visitArray(List<? extends AnnotationValue> values, Void v) { return values.stream() .map(value -> value.accept(new JsonSubTypeVisitor(consumer), null)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } }
32.147059
101
0.741995
49246e6f5e56ee609c78d1504e937d86f65147cf
5,910
package tests.broskiclan.bcutil; import lombok.SneakyThrows; import org.apache.commons.codec.binary.Hex; import org.broskiclan.bcutil.io.CFiles; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; public class IOTests { private File file; @Before @SneakyThrows public void setup() { this.file = new File("test.txt"); Files.write(file.toPath(), Arrays.asList( "hello world. lorem ipsum uwu lol", "pls no ioException", "now some totally gibberish stuff here:", "0xfduewjdewjdoijaskifduei9239jdkojokjd0i23ujdi23joidjek", "32hsaijidu389quwsdjcdjsakjdkok03qu0isjdksnakowjdi9uwqd", "fh4ew9udjkdkwplksioewuauiojckjepokfopsaidoiufoiewjjaisydf", "ewihoijdeiowjdfioewjdioewjdiouewiofjuihfiudcsdhewuidehwiudh", "fhewiuhdijasghiueu7fdhjsncja9udeijdioweuiduojasijfeu3udfoih", "fhewiudxehfuwhdiuhweuifhewiojdewiuhduehwudgudviklpsxkjsakjd", "0xfduewjdewjdoijaskifduei9239jdkojokjd0i23ujdi23joidjek", "32hsaijidu389quwsdjcdjsakjdkok03qu0isjdksnakowjdi9uwqd", "fh4ew9udjkdkwplksioewuauiojckjepokfopsaidoiufoiewjjaisydf", "ewihoijdeiowjdfioewjdioewjdiouewiofjuihfiudcsdhewuidehwiudh", "fhewiuhdijasghiueu7fdhjsncja9udeijdioweuiduojasijfeu3udfoih", "fhewiudxehfuwhdiuhweuifhewiojdewiuhduehwudgudviklpsxkjsakjd", "0xfduewjdewjdoijaskifduei9239jdkojokjd0i23ujdi23joidjek", "32hsaijidu389quwsdjcdjsakjdkok03qu0isjdksnakowjdi9uwqd", "fh4ew9udjkdkwplksioewuauiojckjepokfopsaidoiufoiewjjaisydf", "ewihoijdeiowjdfioewjdioewjdiouewiofjuihfiudcsdhewuidehwiudh", "fhewiuhdijasghiueu7fdhjsncja9udeijdioweuiduojasijfeu3udfoih", "fhewiudxehfuwhdiuhweuifhewiojdewiuhduehwudgudviklpsxkjsakjd", "0xfduewjdewjdoijaskifduei9239jdkojokjd0i23ujdi23joidjek", "32hsaijidu389quwsdjcdjsakjdkok03qu0isjdksnakowjdi9uwqd", "fh4ew9udjkdkwplksioewuauiojckjepokfopsaidoiufoiewjjaisydf", "ewihoijdeiowjdfioewjdioewjdiouewiofjuihfiudcsdhewuidehwiudh", "fhewiuhdijasghiueu7fdhjsncja9udeijdioweuiduojasijfeu3udfoih", "fhewiudxehfuwhdiuhweuifhewiojdewiuhduehwudgudviklpsxkjsakjd" )); } @Test @SneakyThrows public void file_encryption_and_decryption() { var k = KeyGenerator.getInstance("AES"); k.init(256); SecretKey key = k.generateKey(); var ci = Cipher.getInstance("AES/GCM/NoPadding"); byte[] iv = new byte[64]; new SecureRandom().nextBytes(iv); ci.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv)); System.out.println("PRINTING FILE CONTENTS =========================================================================================================================================================================\n" + new String(Files.readAllBytes(file.toPath())) + "================================================================================================================================================================================================"); System.out.println("ENCRYPTING..."); CFiles.encrypt(file.toPath(), key, ci); System.out.println("PRINTING FILE CONTENTS (HEX) (ISO-8859-1) ===========================================================================================================================================================================================================\n" + new String(new Hex(StandardCharsets.ISO_8859_1).encode(Files.readAllBytes(file.toPath())), StandardCharsets.ISO_8859_1) + "\n============================================================================================================================================================================================================================================================="); System.out.println("DECRYPTING..."); ci.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv)); byte[] bytes = CFiles.decrypt(file.toPath(), key, ci); System.out.println("PRINTING FILE CONTENTS =========================================================================================================================================================================\n" + new String(bytes) + "================================================================================================================================================================================================"); } @Test @SneakyThrows public void file_checksums() { System.out.println("Finding checksum of test.txt..."); System.out.println("CHECKSUM: " + new String( new Hex(StandardCharsets.ISO_8859_1).encode(CFiles.getChecksum(Paths.get("test.txt"))), StandardCharsets.ISO_8859_1 )); System.out.println("================================================================================================="); System.out.println("Finding checksum of ./target... (fixed)"); System.out.println("CHECKSUM: " + new String( new Hex(StandardCharsets.ISO_8859_1).encode(CFiles.getChecksum(Paths.get("target/"), MessageDigest.getInstance("SHA3-512"), CFiles.ChecksumPolicy.CONTENTS_AND_LOCATION, false)), StandardCharsets.ISO_8859_1 )); System.out.println("================================================================================================="); System.out.println("Finding checksum of ./target... (recursive)"); System.out.println("CHECKSUM: " + new String( new Hex(StandardCharsets.ISO_8859_1).encode(CFiles.getChecksum(Paths.get("target/"), MessageDigest.getInstance("SHA3-512"), CFiles.ChecksumPolicy.CONTENTS_AND_LOCATION, true)), StandardCharsets.ISO_8859_1 )); } @After @SneakyThrows public void cleanup() { Files.delete(Paths.get("test.txt")); } }
51.391304
272
0.596616
668be491d3c9bd0dfce4095e6127d88901c92a3a
396
package class11; public class Tecnico extends Aluno { private int registroProfissional; public void praticar() { System.out.println("Praticando seus conhecimentos!"); } public int getRegistroProfissional() { return registroProfissional; } public void setRegistroProfissional(int registroProfissional) { this.registroProfissional = registroProfissional; } }
20.842105
65
0.739899
ea77e6910171c676b4377882ec7bbe71de4ec8ec
1,770
package edu.ifes.ci.si.les.scl.models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.Digits; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = false) @Entity public class Funcionario extends Usuario implements Serializable{ private static final long serialVersionUID = 1L; @Column(length = 20) @NotBlank(message = "Login do Funcionario deve ser preenchido") @Size(min = 2, max = 20, message = "Login do Funcionario deve ter entre 2 a 20 caracteres") private String login; @Column(length = 20) @NotBlank(message = "Senha do Funcionario deve ser preenchida") @Size(min = 3, max = 20, message = "Senha do Funcionario deve ter entre 3 a 20 caracteres") private String senha; @Column(length = 20) @NotBlank(message = "Cargo do Funcionario deve ser preenchido") @Size(min = 2, max = 20, message = "Cargo do Funcionario deve ter entre 2 a 20 caracteres") private String cargo; @DecimalMin(value = "0.00") @Digits(integer = 6, fraction = 2) private Double salario; @Size(max = 2000000) private String foto; @Builder public Funcionario(Integer id, String nome, String rua, Integer numero, Bairro bairro, String login, String senha, String cargo, Double salario) { super(id, nome, rua, numero, bairro); this.login = login; this.senha = senha; this.salario = salario; this.cargo = cargo; } }
30.517241
150
0.735593
c403b8cc4358115f91f078e4755d4031224aa40e
9,701
package de.mindyourbyte.alphalapse; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.Button; import com.sony.scalar.sysutil.ScalarInput; public class NonTouchNumberPicker extends Button { public NumberPickerChanged getCallback() { return callback; } public void setCallback(NumberPickerChanged callback) { this.callback = callback; } public interface NumberPickerChanged { void onPickerValueChanged(int value); } public NonTouchNumberPicker(Context context) { super(context); updateText(); } public NonTouchNumberPicker(Context context, AttributeSet attrs) { super(context, attrs); TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.NonTouchNumberPicker); initializeAttributes(attributes); updateText(); } public NonTouchNumberPicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.NonTouchNumberPicker, defStyle, 0); initializeAttributes(attributes); updateText(); } private void initializeAttributes(TypedArray attributes) { MinValue = attributes.getInteger(R.styleable.NonTouchNumberPicker_minValue, Integer.MIN_VALUE + 1); MaxValue = attributes.getInteger(R.styleable.NonTouchNumberPicker_maxValue, Integer.MAX_VALUE - 1); setPostfix(attributes.getString(R.styleable.NonTouchNumberPicker_postfix)); } private NumberPickerChanged callback; private int Value; private int MaxValue = Integer.MAX_VALUE - 2; private int MinValue = Integer.MIN_VALUE + 1; private String Postfix = ""; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (event.getScanCode()) { case ScalarInput.ISV_KEY_UP: return onUpKeyDown(); case ScalarInput.ISV_KEY_DOWN: return onDownKeyDown(); case ScalarInput.ISV_KEY_LEFT: return onLeftKeyDown(); case ScalarInput.ISV_KEY_RIGHT: return onRightKeyDown(); case ScalarInput.ISV_KEY_ENTER: return onEnterKeyDown(); case ScalarInput.ISV_KEY_FN: return onFnKeyDown(); case ScalarInput.ISV_KEY_AEL: return onAelKeyDown(); case ScalarInput.ISV_KEY_MENU: case ScalarInput.ISV_KEY_SK1: return onMenuKeyDown(); case ScalarInput.ISV_KEY_S1_1: return onFocusKeyDown(); case ScalarInput.ISV_KEY_S1_2: return true; case ScalarInput.ISV_KEY_S2: return onShutterKeyDown(); case ScalarInput.ISV_KEY_PLAY: return onPlayKeyDown(); case ScalarInput.ISV_KEY_STASTOP: return onMovieKeyDown(); case ScalarInput.ISV_KEY_CUSTOM1: return onC1KeyDown(); case ScalarInput.ISV_KEY_DELETE: case ScalarInput.ISV_KEY_SK2: return onDeleteKeyDown(); case ScalarInput.ISV_KEY_LENS_ATTACH: return onLensAttached(); case ScalarInput.ISV_DIAL_1_CLOCKWISE: case ScalarInput.ISV_DIAL_1_COUNTERCW: return onUpperDialChanged(getDialStatus(ScalarInput.ISV_DIAL_1_STATUS) / 22); case ScalarInput.ISV_DIAL_2_CLOCKWISE: case ScalarInput.ISV_DIAL_2_COUNTERCW: return onLowerDialChanged(getDialStatus(ScalarInput.ISV_DIAL_2_STATUS) / 22); case ScalarInput.ISV_KEY_MODE_DIAL: return onModeDialChanged(getDialStatus(ScalarInput.ISV_KEY_MODE_DIAL)); default: return super.onKeyDown(keyCode, event); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (event.getScanCode()) { case ScalarInput.ISV_KEY_UP: return onUpKeyUp(); case ScalarInput.ISV_KEY_DOWN: return onDownKeyUp(); case ScalarInput.ISV_KEY_LEFT: return onLeftKeyUp(); case ScalarInput.ISV_KEY_RIGHT: return onRightKeyUp(); case ScalarInput.ISV_KEY_ENTER: return onEnterKeyUp(); case ScalarInput.ISV_KEY_FN: return onFnKeyUp(); case ScalarInput.ISV_KEY_AEL: return onAelKeyUp(); case ScalarInput.ISV_KEY_MENU: case ScalarInput.ISV_KEY_SK1: return onMenuKeyUp(); case ScalarInput.ISV_KEY_S1_1: return onFocusKeyUp(); case ScalarInput.ISV_KEY_S1_2: return true; case ScalarInput.ISV_KEY_S2: return onShutterKeyUp(); case ScalarInput.ISV_KEY_PLAY: return onPlayKeyUp(); case ScalarInput.ISV_KEY_STASTOP: return onMovieKeyUp(); case ScalarInput.ISV_KEY_CUSTOM1: return onC1KeyUp(); case ScalarInput.ISV_KEY_DELETE: case ScalarInput.ISV_KEY_SK2: return onDeleteKeyUp(); case ScalarInput.ISV_KEY_LENS_ATTACH: return onLensDetached(); case ScalarInput.ISV_DIAL_1_CLOCKWISE: case ScalarInput.ISV_DIAL_1_COUNTERCW: return true; case ScalarInput.ISV_DIAL_2_CLOCKWISE: case ScalarInput.ISV_DIAL_2_COUNTERCW: return true; case ScalarInput.ISV_KEY_MODE_DIAL: return true; default: return super.onKeyUp(keyCode, event); } } protected int getDialStatus(int key) { return ScalarInput.getKeyStatus(key).status; } protected boolean onUpKeyDown() { return false; } protected boolean onUpKeyUp() { return false; } protected boolean onDownKeyDown() { return false; } protected boolean onDownKeyUp() { return false; } protected boolean onLeftKeyDown() { return false; } protected boolean onLeftKeyUp() { return false; } protected boolean onRightKeyDown() { return false; } protected boolean onRightKeyUp() { return false; } protected boolean onEnterKeyDown() { return false; } protected boolean onEnterKeyUp() { return false; } protected boolean onFnKeyDown() { return false; } protected boolean onFnKeyUp() { return false; } protected boolean onAelKeyDown() { return false; } protected boolean onAelKeyUp() { return false; } protected boolean onMenuKeyDown() { return false; } protected boolean onMenuKeyUp() { return false; } protected boolean onFocusKeyDown() { return false; } protected boolean onFocusKeyUp() { return false; } protected boolean onShutterKeyDown() { return false; } protected boolean onShutterKeyUp() { return false; } protected boolean onPlayKeyDown() { return false; } protected boolean onPlayKeyUp() { return false; } protected boolean onMovieKeyDown() { return false; } protected boolean onMovieKeyUp() { return false; } protected boolean onC1KeyDown() { return false; } protected boolean onC1KeyUp() { return false; } protected boolean onLensAttached() { return false; } protected boolean onLensDetached() { return false; } protected boolean onUpperDialChanged(int value) { shiftValueBy(value * 10); return true; } protected boolean onLowerDialChanged(int value) { shiftValueBy(value); return true; } private void shiftValueBy(int value) { int newValue = getValue() + value; if (newValue > getMaxValue()) { newValue = getMinValue(); } else if(newValue < getMinValue()) { newValue = getMaxValue(); } setValue(newValue); } protected boolean onModeDialChanged(int value) { return false; } protected boolean onDeleteKeyDown() { return false; } protected boolean onDeleteKeyUp() { return false; } public int getValue() { return Value; } public void setValue(int value) { Value = value; clampValue(); if (callback != null){ callback.onPickerValueChanged(getValue()); } } public int getMaxValue() { return MaxValue; } public void setMaxValue(int maxValue) { MaxValue = maxValue; clampValue(); } public int getMinValue() { return MinValue; } public void setMinValue(int minValue) { MinValue = minValue; clampValue(); } private void clampValue() { int oldValue = Value; Value = Math.min(Math.max(getMinValue(), Value), getMaxValue()); updateText(); } private void updateText() { StringBuilder text = new StringBuilder(Integer.toString(Value)); if (getPostfix() != null){ text.append(getPostfix()); } setText(text.toString()); } public String getPostfix() { return Postfix; } public void setPostfix(String postfix) { Postfix = postfix; updateText(); } }
35.92963
118
0.609628
08d53e48f299bd621b4a2c54b4060c6d60c9a868
3,107
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.stunner.core.client.session.command.impl; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Default; import javax.inject.Inject; import org.kie.workbench.common.stunner.core.client.service.ClientDiagramService; import org.kie.workbench.common.stunner.core.client.service.ClientRuntimeError; import org.kie.workbench.common.stunner.core.client.service.ServiceCallback; import org.uberfire.client.workbench.widgets.common.ErrorPopupPresenter; import org.uberfire.ext.editor.commons.client.file.exports.TextContent; import org.uberfire.ext.editor.commons.client.file.exports.TextFileExport; @Dependent @Default public class ExportToBpmnSessionCommand extends AbstractExportSessionCommand { private final ClientDiagramService clientDiagramService; private final ErrorPopupPresenter errorPopupPresenter; private final TextFileExport textFileExport; protected ExportToBpmnSessionCommand() { this(null, null, null); } @Inject public ExportToBpmnSessionCommand(final ClientDiagramService clientDiagramService, final ErrorPopupPresenter errorPopupPresenter, final TextFileExport textFileExport) { super(true); this.clientDiagramService = clientDiagramService; this.errorPopupPresenter = errorPopupPresenter; this.textFileExport = textFileExport; } @SuppressWarnings("unchecked") @Override protected void export(final String fileName) { clientDiagramService.getRawContent(getSession().getCanvasHandler().getDiagram(), new ServiceCallback<String>() { @Override public void onSuccess(String rawContent) { textFileExport.export(TextContent.create(rawContent), fileName); } @Override public void onError(ClientRuntimeError error) { errorPopupPresenter.showMessage(error.getMessage()); } }); } }
43.760563
104
0.621178
7386626cb412667bc879752eaf709001767beba2
1,143
package io.gameoftrades.model.markt.actie; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class VerkoopActieTest extends AbstractActieTest { @Test public void zouMoetenKunnenVerkopen() { HandelsPositie positie = new HandelsPositie(wereld, stad2, 10, 10, 4); // 1+2+1 positie = new KoopActie(h2).voerUit(positie); positie = new BeweegActie(kaart, stad2, stad1, new MockPad()).voerUit(positie); VerkoopActie verkoopActie = new VerkoopActie(h4); assertTrue(verkoopActie.isMogelijk(positie)); HandelsPositie result = verkoopActie.voerUit(positie); assertEquals(10, result.getRuimte()); assertEquals(40, result.getKapitaal()); assertEquals(30, result.getTotaalWinst()); assertEquals("{}", String.valueOf(result.getVoorraad())); assertEquals(4, result.getTotaalActie()); assertFalse(result.isGestopt()); assertTrue(result.isKlaar()); assertEquals("[stenen]", result.getUniekeGoederen().toString()); } }
35.71875
87
0.698163
522d87cb3b5f9d8b6519e9f185f750dcaccbc7e1
7,100
/* BinderConnection.java Copyright (c) 2017 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager.core.plugin; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import org.deviceconnect.android.IDConnectCallback; import org.deviceconnect.android.IDConnectPlugin; import org.deviceconnect.android.manager.core.BuildConfig; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Logger; /** * バインダーによる接続. * * @author NTT DOCOMO, INC. */ public class BinderConnection extends AbstractConnection { private final ComponentName mPluginName; private final IDConnectCallback mCallback; private ServiceConnection mServiceConnection; private IDConnectPlugin mPlugin; private Future<ConnectingResult> mRunningTask; private ExecutorService mExecutor = Executors.newSingleThreadExecutor(); private Logger mLogger = Logger.getLogger("dconnect.manager"); public BinderConnection(final Context context, final String pluginId, final ComponentName target, final IDConnectCallback callback) { super(context, pluginId); mPluginName = target; mCallback = callback; } @Override public ConnectionType getType() { return ConnectionType.BINDER; } @Override public synchronized void connect() throws ConnectingException { if (BuildConfig.DEBUG) { mLogger.info("BinderConnection.connect: " + mPluginName.getPackageName()); } if (!(ConnectionState.DISCONNECTED == getState() || ConnectionState.SUSPENDED == getState())) { return; } setConnectingState(); ConnectingResult result; try { mRunningTask = mExecutor.submit(new ConnectingTask()); result = mRunningTask.get(); mRunningTask = null; } catch (InterruptedException e) { setSuspendedState(ConnectionError.CANCELED); throw new ConnectingException("Connection procedure was canceled."); } catch (ExecutionException e) { setSuspendedState(ConnectionError.INTERNAL_ERROR); throw new ConnectingException(e); } if (result.mError == null) { mPlugin = result.mPlugin; mServiceConnection = result.mServiceConnection; setConnectedState(); } else { setSuspendedState(result.mError); throw new ConnectingException("Failed to bind with plugin: " + mPluginName); } } @Override public void disconnect() { synchronized (this) { if (ConnectionState.CONNECTED == getState()) { try { mContext.unbindService(mServiceConnection); } catch (Exception e) { // ignore. } mServiceConnection = null; mPlugin = null; } setDisconnectedState(); } } @Override public void send(final Intent message) throws MessagingException { if (BuildConfig.DEBUG) { mLogger.info("BinderConnection.send: sending: target = " + mPluginName.getPackageName()); } synchronized (this) { if (ConnectionState.SUSPENDED == getState()) { throw new MessagingException(MessagingException.Reason.CONNECTION_SUSPENDED); } if (ConnectionState.CONNECTED != getState()) { throw new MessagingException(MessagingException.Reason.NOT_CONNECTED); } } try { mPlugin.sendMessage(message); if (BuildConfig.DEBUG) { mLogger.info("BinderConnection.send: sent: target = " + mPluginName.getPackageName()); } } catch (RemoteException e) { throw new MessagingException(e, MessagingException.Reason.NOT_CONNECTED); } } private class ConnectingTask implements Callable<ConnectingResult> { @Override public ConnectingResult call() throws Exception { if (BuildConfig.DEBUG) { mLogger.info("ConnectingTask.call: " + mPluginName); } final Object lockObj = new Object(); final ConnectingResult result = new ConnectingResult(); Intent intent = new Intent(); intent.setComponent(mPluginName); final ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(final ComponentName componentName, final IBinder binder) { if (BuildConfig.DEBUG) { mLogger.info("onServiceConnected: componentName = " + componentName + ", binder = " + binder); } try { IDConnectPlugin plugin = IDConnectPlugin.Stub.asInterface(binder); plugin.registerCallback(mCallback); synchronized (lockObj) { result.mIsComplete = true; result.mPlugin = plugin; result.mServiceConnection = this; lockObj.notifyAll(); } } catch (RemoteException e) { e.printStackTrace(); // TODO エラーハンドリング } } @Override public void onServiceDisconnected(final ComponentName componentName) { if (BuildConfig.DEBUG) { mLogger.info("onServiceDisconnected: componentName = " + componentName); } synchronized (BinderConnection.this) { mServiceConnection = null; mPlugin = null; setSuspendedState(ConnectionError.TERMINATED); } } }; boolean canBind = mContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); if (!canBind) { result.mError = ConnectionError.NOT_PERMITTED; return result; } synchronized (lockObj) { lockObj.wait(2000); } if (!result.mIsComplete) { result.mError = ConnectionError.NOT_RESPONDED; } return result; } } private class ConnectingResult { boolean mIsComplete; IDConnectPlugin mPlugin; ServiceConnection mServiceConnection; ConnectionError mError; } }
34.634146
118
0.58831
1ac4f3743e576e708868812ebfc00257741863e8
1,257
package me.burninghandsapp.familyportal.repositories; import me.burninghandsapp.familyportal.models.BlogPostRatings; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface BlogPostRatingsRepository extends JpaRepository<BlogPostRatings,Integer> { @Query(value = "select count(u) from BlogPostRatings u where u.id=:rateByUserId") Integer findCountByRateBy(@Param("rateByUserId") Integer rateByUserId); @Query(value = "select count(u) from BlogPostRatings u where u.rateBy.id=:rateByUserId and u.blogItem.id=:blogItemId") Integer findCountByRateByAndBlog(@Param("blogItemId") Integer blogItemId,@Param("rateByUserId") Integer rateByUserId); @Query(value = "select u from BlogPostRatings u where u.blogItem.id=:blogItemId and u.rateBy.id=:rateByUserId") BlogPostRatings findByBlog(@Param("blogItemId") Integer blogItemId,@Param("rateByUserId") Integer rateByUserId); @Query(value = "select AVG(u.rate) from BlogPostRatings u where u.blogItem.id=:blogItemId") Integer findAvgByBlog(@Param("blogItemId") Integer blogItemId); }
50.28
122
0.797932
6bf00d4e53f9c483af51fdee3b2394a34e2e4200
411
package com.atguigu.gmall.oms.mapper; import com.atguigu.gmall.oms.entity.OrderOperateHistoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 订单操作历史记录 * * @author liuxiaofeng * @email xfliu@atguigu.com * @date 2020-04-23 14:24:54 */ @Mapper public interface OrderOperateHistoryMapper extends BaseMapper<OrderOperateHistoryEntity> { }
22.833333
90
0.785888
8a27dc0d9de0576d1643920364fe3c3b80883bd4
673
package com.mshams.cs.problems.legacy; public class Operations extends Problem { public int negate(int n) { int sign = n > 0 ? -1 : 1; int neg = 0; while (n > 0) { neg += sign; n += sign; } return neg; } public int subtract(int a, int b) { return a + negate(b); } public int multiply(int a, int b) { if (a < b) { int t = a; a = b; b = t; } int sign = 1; if ((a < 0 || b < 0) && !(a < 0 && b < 0)) { sign = -1; } int mul = 0; for (int x = 0; x < Math.abs(b); x++) { mul += a; } return sign < 0 ? negate(mul) : mul; } @Override void run() { } }
14.955556
48
0.444279
2187f9b8151fe92acf0434c1832f1b05979fb147
15,614
/* * Copyright 2013 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.google.appengine.tck.memcache; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import com.google.appengine.api.memcache.AsyncMemcacheService; import com.google.appengine.api.memcache.Expiration; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheService.CasValues; import com.google.appengine.api.memcache.MemcacheService.IdentifiableValue; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.appengine.api.memcache.Stats; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Tests Async Memcache. * * @author hchen@google.com (Hannah Chen) */ @RunWith(Arquillian.class) public class MemcacheAsync2Test extends CacheTestBase { private MemcacheService memcache; private AsyncMemcacheService asyncMemcache; @Before public void setUp() { memcache = MemcacheServiceFactory.getMemcacheService(); asyncMemcache = MemcacheServiceFactory.getAsyncMemcacheService(); memcache.clearAll(); } /** * Tests single put/get. */ @Test public void testPutAndGetBasic() { verifyAsyncGet(KEY1, STR_VALUE); } /** * Tests different data type put/get. */ @Test public void testPutAndGetTypes() { for (Object key : TEST_DATA) { assertNull(memcache.get(key)); for (Object value : TEST_DATA) { verifyAsyncGet(key, value); } } } @Test public void testGetArray1() { Future<Void> future = asyncMemcache.put(KEY1, ARRAY1); waitOnFuture(future); assertArrayEquals(ARRAY1, (int[]) memcache.get(KEY1)); } @Test public void testGetArray2() { Future<Void> future = asyncMemcache.put(KEY1, ARRAY2); waitOnFuture(future); assertArrayEquals(ARRAY2, (Object[]) memcache.get(KEY1)); } @Test public void testDelete() { memcache.put(KEY1, STR_VALUE); Future<Boolean> future = asyncMemcache.delete(KEY1); waitOnFuture(future); assertNull("key1 should hold null", memcache.get(KEY1)); } @Test public void testDeleteNoReAddTime() { String key = createTimeStampKey("testDeleteNoReAddTime"); memcache.put(key, STR_VALUE); assertNotNull(memcache.get(key)); // delete and do not allow re-add for another 10 seconds. Future<Boolean> future = asyncMemcache.delete(key, 10 * 1000); waitOnFuture(future); assertNull("key should be null", memcache.get(KEY1)); // re-add should fail since within 10 seconds. assertFalse(memcache.put(key, STR_VALUE, null, MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT)); assertNull("key should be null because of policy.", memcache.get(KEY1)); } @Test public void testPutAll() { Map<Object, Object> data = createSmallBatchData(); Future<Void> future = asyncMemcache.putAll(data); waitOnFuture(future); Map<Object, Object> fetched = memcache.getAll(data.keySet()); assertEquals("All the keys inserted should exist.", data, fetched); } @Test public void testDeleteAll() { Map<Object, Object> data = createSmallBatchData(); memcache.putAll(data); Future<Set<Object>> future = asyncMemcache.deleteAll(data.keySet()); Set<Object> deletedKeys = waitOnFuture(future); assertEquals(data.keySet(), deletedKeys); } @Test public void testDeleteAllNoReAddTime() { Map<Object, Object> cacheDat = createSmallBatchData(); memcache.putAll(cacheDat); Future<Set<Object>> future = asyncMemcache.deleteAll(cacheDat.keySet(), 10 * 1000); waitOnFuture(future); Map<Object, Object> retValues = memcache.getAll(cacheDat.keySet()); assertEquals("All keys should be deleted.", 0, retValues.size()); memcache.putAll(cacheDat, null, MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT); Map<Object, Object> retValuesAfter = memcache.getAll(cacheDat.keySet()); assertEquals("No keys should be added because of policy.", 0, retValuesAfter.size()); } @Test public void testCancel() { Map<Object, Object> data = createSmallBatchData(); Future<Void> future = asyncMemcache.putAll(data); boolean cancelled = future.cancel(true); // There's no guarantee that the cancel succeeds on the backend, so just verify that the // fundamental future api works. assertTrue(future.isDone()); // Should always be true once cancel() returns. if (cancelled) { assertTrue(future.isCancelled()); } } @Test public void testIncrementAll() { Map<Object, Long> map = createLongBatchData(); memcache.putAll(map); long delta = 10; Future<Map<Object, Long>> future = asyncMemcache.incrementAll(map.keySet(), delta); Map<Object, Long> returned = waitOnFuture(future); Map<Object, Object> expected = new HashMap<Object, Object>(); for (Map.Entry<Object, Long> entry : map.entrySet()) { expected.put(entry.getKey(), entry.getValue() + delta); } assertEquals(expected, returned); Map<Object, Object> fetched = memcache.getAll(map.keySet()); assertEquals(expected, fetched); } @Test public void testIncrementAllInitValue() { Map<Object, Long> map = createLongBatchData(); memcache.putAll(map); long delta = 10; Long initVal = -111L; Map<Object, Long> expected = copyMapIncrementLongValue(map, delta); // Add the key which doesn't exist yet. String nonExistentKey = "testIncrementAllInitValue-" + System.currentTimeMillis(); expected.put(nonExistentKey, initVal + delta); Future<Map<Object, Long>> future = asyncMemcache.incrementAll(expected.keySet(), delta, initVal); Map<Object, Long> returned = waitOnFuture(future); assertEquals(expected, returned); Map<Object, Object> fetched = memcache.getAll(expected.keySet()); assertEquals(expected, fetched); } @Test public void testIncrementAllFromMap() { Map<Object, Long> map = createLongBatchData(); memcache.putAll(map); Map<Object, Long> incMap = createRandomIncrementMap(map); Future<Map<Object, Long>> future = asyncMemcache.incrementAll(incMap); Map<Object, Long> returned = waitOnFuture(future); Map<Object, Long> expected = createMapFromIncrementMap(map, incMap); assertEquals(expected, returned); Map<Object, Object> fetched = memcache.getAll(map.keySet()); assertEquals(expected, fetched); } @Test public void testIncrementAllFromMapInitValue() { Map<Object, Long> map = createLongBatchData(); memcache.putAll(map); Map<Object, Long> incMap = createRandomIncrementMap(map); Map<Object, Long> expected = createMapFromIncrementMap(map, incMap); Long initVal = -111L; // Add the key which doesn't exist yet. String nonExistentKey = "testIncrementAllFromMapInitValue-" + System.currentTimeMillis(); incMap.put(nonExistentKey, 123L); expected.put(nonExistentKey, initVal + 123L); Future<Map<Object, Long>> future = asyncMemcache.incrementAll(incMap, initVal); Map<Object, Long> returned = waitOnFuture(future); assertEquals(expected, returned); Map<Object, Object> fetched = memcache.getAll(incMap.keySet()); assertEquals(expected, fetched); } @Test public void testGetIdentifiables() { memcache.put(KEY1, STR_VALUE); Future<IdentifiableValue> future = asyncMemcache.getIdentifiable(KEY1); IdentifiableValue identVal = waitOnFuture(future); assertEquals(STR_VALUE, identVal.getValue()); // batch versions Map<Object, Object> map = new HashMap<Object, Object>(); for (Object key : TEST_DATA) { map.put(key, key); } waitOnFuture(asyncMemcache.putAll(map)); Future<Map<Object, IdentifiableValue>> futureMap = asyncMemcache.getIdentifiables(Arrays.asList(TEST_DATA)); Map<Object, IdentifiableValue> ivMap = waitOnFuture(futureMap); for (Object key : ivMap.keySet()) { assertEquals(key, ivMap.get(key).getValue()); } } @Test public void testPutIfUntouched() { final String TS_KEY = createTimeStampKey("testPutIfUntouched"); memcache.put(TS_KEY, STR_VALUE); IdentifiableValue oldOriginalIdValue = memcache.getIdentifiable(TS_KEY); final String NEW_VALUE = "new-" + STR_VALUE; Future<Boolean> future; Boolean valueWasStored; // Store NEW_VALUE if no other value stored since oldOriginalIdValue was retrieved. // memcache.get() has not been called, so this put should succeed. future = asyncMemcache.putIfUntouched(TS_KEY, oldOriginalIdValue, NEW_VALUE); valueWasStored = waitOnFuture(future); assertEquals(true, valueWasStored); assertEquals(NEW_VALUE, memcache.get(TS_KEY)); // NEW_VALUE was stored so this put should not happen. final String ANOTHER_VALUE = "another-" + STR_VALUE; future = asyncMemcache.putIfUntouched(TS_KEY, oldOriginalIdValue, ANOTHER_VALUE); valueWasStored = waitOnFuture(future); assertEquals(false, valueWasStored); assertNotSame(ANOTHER_VALUE, memcache.get(TS_KEY)); assertEquals(NEW_VALUE, memcache.get(TS_KEY)); } @Test public void testPutIfUntouchedMap() { // batch versions Object[] testDat = {1, STR_VALUE}; Map<Object, Object> inputDat = new HashMap<Object, Object>(); for (Object key : testDat) { inputDat.put(key, key); } memcache.putAll(inputDat); Set<Object> set; Map<Object, CasValues> updateDat = new HashMap<Object, CasValues>(); for (Object key : testDat) { updateDat.put(key, new CasValues(memcache.getIdentifiable(key), "new value")); } Future<Set<Object>> futureSet = asyncMemcache.putIfUntouched(updateDat); set = waitOnFuture(futureSet); assertEquals(2, set.size()); assertEquals("new value", memcache.get(testDat[0])); futureSet = asyncMemcache.putIfUntouched(updateDat); set = waitOnFuture(futureSet); assertEquals(0, set.size()); } @Test public void testPutIfUntouchedExpire() { final String TS_KEY = createTimeStampKey("testPutIfUntouched"); memcache.put(TS_KEY, STR_VALUE); IdentifiableValue oldOriginalIdValue = memcache.getIdentifiable(TS_KEY); final String NEW_VALUE = "new-" + STR_VALUE; Future<Boolean> future; Boolean valueWasStored; // Store NEW_VALUE if no other value stored since oldOriginalIdValue was retrieved. // memcache.get() has not been called, so this put should succeed. future = asyncMemcache.putIfUntouched(TS_KEY, oldOriginalIdValue, NEW_VALUE, Expiration.byDeltaSeconds(1)); valueWasStored = waitOnFuture(future); assertEquals(true, valueWasStored); assertEquals(NEW_VALUE, memcache.get(TS_KEY)); // Value should not be stored after expiration period. sync(3000); assertNull(memcache.get(TS_KEY)); } @Test public void testPutIfUntouchedMapExpire() { // batch versions Object[] testDat = {1, STR_VALUE}; Map<Object, Object> inputDat = new HashMap<Object, Object>(); for (Object key : testDat) { inputDat.put(key, key); } memcache.putAll(inputDat); Set<Object> set; Map<Object, CasValues> updateDat = new HashMap<Object, CasValues>(); for (Object key : testDat) { updateDat.put(key, new CasValues(memcache.getIdentifiable(key), "new value", Expiration.byDeltaSeconds(60 * 60))); } Future<Set<Object>> futureSet = asyncMemcache.putIfUntouched(updateDat, Expiration.byDeltaMillis(1000)); set = waitOnFuture(futureSet); assertEquals(2, set.size()); assertEquals("new value", memcache.get(testDat[0])); sync(3000); assertNull(memcache.get(testDat)); } @Test public void testStatistics() { Future<Stats> future = asyncMemcache.getStatistics(); Stats stats = waitOnFuture(future); assertNotNull("Stats should never be null.", stats); // Only verify that all stats are non-negative. assertTrue(stats.getBytesReturnedForHits() > -1L); assertTrue(stats.getHitCount() > -1L); assertTrue(stats.getItemCount() > -1L); assertTrue(stats.getMaxTimeWithoutAccess() > -1); assertTrue(stats.getMissCount() > -1L); assertTrue(stats.getTotalItemBytes() > -1L); } @Test public void testAsyncWithNamespace() { String namespace = "namespace-123"; AsyncMemcacheService ams = MemcacheServiceFactory.getAsyncMemcacheService(namespace); String key = "some-random-key"; String value = "some-random-value"; waitOnFuture(ams.put(key, value)); // non-namespaced lookup Assert.assertFalse(memcache.contains(key)); MemcacheService ms = MemcacheServiceFactory.getMemcacheService(namespace); Assert.assertEquals(value, ms.get(key)); } private void verifyAsyncGet(Object key, Object value) { Future<Void> putFuture = asyncMemcache.put(key, value); waitOnFuture(putFuture); Future<Object> getFuture = asyncMemcache.get(key); waitOnFuture(getFuture); assertFalse("future shouldn't be cancelled", getFuture.isCancelled()); assertEquals(value, memcache.get(key)); } // A debugging aid to show cache stats along with a failure message @SuppressWarnings("unused") private String failure(String msg) { Stats statistics = memcache.getStatistics(); StringBuilder sb = new StringBuilder(); sb .append(msg) .append(" (") .append(statistics.getItemCount()) .append("/") .append(statistics.getHitCount()) .append("/") .append(statistics.getMissCount()) .append(")"); return sb.toString(); } }
36.143519
126
0.661009
9b9fd2671f372edad2dd78297f46bfcc1ace79f0
3,033
//View.java //(C) Joseph Mack 2011, jmack (at) wm7d (dot) net, released under GPL v3 (or any later version) //inspired by Joseph Bergin's MVC gui at http://csis.pace.edu/~bergin/mvc/mvcgui.html //View is an Observer import java.awt.Button; import java.awt.Panel; import java.awt.Frame; import java.awt.TextField; import java.awt.Label; import java.awt.event.WindowEvent; //for CloseListener() import java.awt.event.WindowAdapter; //for CloseListener() import java.lang.Integer; //int from Model is passed as an Integer import java.util.Observable; //for update(); import java.awt.event.ActionListener; //for addController() class View implements java.util.Observer { //attributes as must be visible within class private TextField myTextField; private Button button; //private Model model; //Joe: Model is hardwired in, //needed only if view initialises model (which we aren't doing) View() { System.out.println("View()"); //frame in constructor and not an attribute as doesn't need to be visible to whole class Frame frame = new Frame("simple MVC"); frame.add("North", new Label("counter")); myTextField = new TextField(); frame.add("Center", myTextField); //panel in constructor and not an attribute as doesn't need to be visible to whole class Panel panel = new Panel(); button = new Button("PressMe"); panel.add(button); frame.add("South", panel); frame.addWindowListener(new CloseListener()); frame.setSize(200,100); frame.setLocation(100,100); frame.setVisible(true); } //View() // Called from the Model public void update(Observable obs, Object obj) { //who called us and what did they send? //System.out.println ("View : Observable is " + obs.getClass() + ", object passed is " + obj.getClass()); //model Pull //ignore obj and ask model for value, //to do this, the view has to know about the model (which I decided I didn't want to do) //uncomment next line to do Model Pull //myTextField.setText("" + model.getValue()); //model Push //parse obj myTextField.setText("" + ((Integer)obj).intValue()); //obj is an Object, need to cast to an Integer } //update() //to initialise TextField public void setValue(int v){ myTextField.setText("" + v); } //setValue() public void addController(ActionListener controller){ System.out.println("View : adding controller"); button.addActionListener(controller); //need instance of controller before can add it as a listener } //addController() //uncomment to allow controller to use view to initialise model //public void addModel(Model m){ // System.out.println("View : adding model"); // this.model = m; //} //addModel() public static class CloseListener extends WindowAdapter { public void windowClosing(WindowEvent e) { e.getWindow().setVisible(false); System.exit(0); } //windowClosing() } //CloseListener } //View
32.612903
113
0.676558
4c50ee15cec4a4910e07eb9400db9ce56afc868b
4,388
package com.exasol.projectkeeper.validators.dependencies; import static com.exasol.projectkeeper.shared.dependencies.ProjectDependency.Type.*; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.maven.model.*; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import com.exasol.errorreporting.ExaError; import com.exasol.projectkeeper.pom.MavenModelFromRepositoryReader; import com.exasol.projectkeeper.shared.dependencies.*; import com.exasol.projectkeeper.shared.dependencies.License; /** * This class reads all dependencies of a pom file (including the plugins) together with their license. */ public class ProjectDependencyReader { private final MavenModelFromRepositoryReader artifactModelReader; /** * Create a new instance of {@link ProjectDependencyReader}. * * @param artifactModelReader maven dependency reader */ public ProjectDependencyReader(final MavenModelFromRepositoryReader artifactModelReader) { this.artifactModelReader = artifactModelReader; } /** * Read the dependencies of the pom file (including plugins). * * @param project maven project * @return list of dependencies */ public ProjectDependencies readDependencies(final MavenProject project) { final List<ProjectDependency> dependencies = getDependenciesIncludingPlugins(project.getModel()) .map(dependency -> getLicense(dependency, project)).collect(Collectors.toList()); return new ProjectDependencies(dependencies); } private Stream<Dependency> getDependenciesIncludingPlugins(final Model model) { return Stream.concat(model.getDependencies().stream(), model.getBuild().getPlugins().stream().map(this::convertPluginToDependency)); } private Dependency convertPluginToDependency(final Plugin plugin) { final var dependency = new Dependency(); dependency.setGroupId(plugin.getGroupId()); dependency.setArtifactId(plugin.getArtifactId()); dependency.setVersion(plugin.getVersion()); dependency.setScope("plugin"); return dependency; } private ProjectDependency getLicense(final Dependency dependency, final MavenProject project) { try { final var dependenciesPom = this.artifactModelReader.readModel(dependency.getArtifactId(), dependency.getGroupId(), dependency.getVersion(), project.getRemoteArtifactRepositories()); final List<License> licenses = dependenciesPom.getLicenses().stream() .map(license -> new License(license.getName(), license.getUrl())).collect(Collectors.toList()); return new ProjectDependency(getDependencyName(dependenciesPom), dependenciesPom.getUrl(), licenses, mapScopeToDependencyType(dependency.getScope())); } catch (final ProjectBuildingException exception) { throw new IllegalStateException(ExaError.messageBuilder("E-PK-MPC-49") .message("Failed to get license information for dependency {{groupId}}:{{artifactId}}.", dependency.getGroupId(), dependency.getArtifactId()) .toString(), exception); } } private String getDependencyName(final Model dependenciesPom) { if (dependenciesPom.getName() == null || dependenciesPom.getName().isBlank()) { return dependenciesPom.getArtifactId(); } else { return dependenciesPom.getName(); } } private ProjectDependency.Type mapScopeToDependencyType(final String scope) { if (scope == null) { return COMPILE; } else { switch (scope) { case "compile": case "provided": case "system": case "import": return COMPILE; case "test": return TEST; case "runtime": return RUNTIME; case "plugin": return PLUGIN; default: throw new IllegalStateException(ExaError.messageBuilder("F-PK-MPC-54") .message("Unimplemented dependency scope {{scope}}.", scope).ticketMitigation().toString()); } } } }
41.396226
116
0.668186
2c7ab45efae0bf60096dd5464b0191d2f18b84e7
3,116
package com.team766.hal.mock; import com.team766.hal.AnalogInputReader; import com.team766.hal.CANSpeedController; import com.team766.hal.CameraInterface; import com.team766.hal.CameraReader; import com.team766.hal.Clock; import com.team766.hal.DigitalInputReader; import com.team766.hal.EncoderReader; import com.team766.hal.GyroReader; import com.team766.hal.JoystickReader; import com.team766.hal.PositionReader; import com.team766.hal.RelayOutput; import com.team766.hal.RobotProvider; import com.team766.hal.SolenoidController; import com.team766.hal.SpeedController; import com.team766.hal.wpilib.SystemClock; public class TestRobotProvider extends RobotProvider{ private boolean m_hasDriverStationUpdate = false; private CANSpeedController[] canMotors = new CANSpeedController[64]; @Override public SpeedController getMotor(int index) { if(motors[index] == null) motors[index] = new Victor(index); return motors[index]; } @Override public CANSpeedController getCANMotor(int index, CANSpeedController.Type type) { if(canMotors[index] == null) canMotors[index] = new Talon(index); return canMotors[index]; } @Override public EncoderReader getEncoder(int index1, int index2) { if(encoders[index1] == null) encoders[index1] = new Encoder(index1, index2); return encoders[index1]; } @Override public SolenoidController getSolenoid(int index) { if(solenoids[index] == null) solenoids[index] = new Solenoid(index); return solenoids[index]; } @Override public GyroReader getGyro(int index) { if(gyros[0] == null) gyros[0] = new Gyro(); return gyros[0]; } @Override public CameraReader getCamera(String id, String value) { if(!cams.containsKey(id)) cams.put(id, new Camera()); return cams.get(id); } @Override public JoystickReader getJoystick(int index) { if(joysticks[index] == null) joysticks[index] = new Joystick(); return joysticks[index]; } @Override public DigitalInputReader getDigitalInput(int index) { if(digInputs[index] == null) digInputs[index] = new DigitalInput(); return digInputs[index]; } @Override public CameraInterface getCamServer() { return null; } @Override public AnalogInputReader getAnalogInput(int index) { if(angInputs[index] == null) angInputs[index] = new AnalogInput(); return angInputs[index]; } public RelayOutput getRelay(int index) { if(relays[index] == null) relays[index] = new Relay(index); return relays[index]; } @Override public PositionReader getPositionSensor() { if (positionSensor == null) positionSensor = new PositionSensor(); return positionSensor; } @Override public Clock getClock() { // TODO Replace this with a controlled clock return SystemClock.instance; } @Override public boolean hasNewDriverStationData() { boolean result = m_hasDriverStationUpdate; m_hasDriverStationUpdate = false; return result; } public void setHasNewDriverStationData() { m_hasDriverStationUpdate = true; } }
25.540984
82
0.717908
4f8c88d2f55562c5cb94386fe8485fb6593367a3
7,363
package org.robolectric.res; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.WatchService; import java.nio.file.attribute.UserPrincipalLookupService; import java.nio.file.spi.FileSystemProvider; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Stream; import javax.annotation.concurrent.GuardedBy; import org.robolectric.util.Util; @SuppressWarnings({"NewApi", "AndroidJdkLibsChecker"}) abstract public class Fs { @GuardedBy("ZIP_FILESYSTEMS") private static final Map<Path, FsWrapper> ZIP_FILESYSTEMS = new HashMap<>(); /** @deprecated Use {@link File#toPath()} instead. */ @Deprecated public static Path newFile(File file) { return file.toPath(); } /** @deprecated Use {@link #fromUrl(String)} instead. */ @Deprecated public static Path fileFromPath(String path) { return Fs.fromUrl(path); } public static FileSystem forJar(URL url) { return forJar(Paths.get(toUri(url))); } public static FileSystem forJar(Path jarFile) { try { return getJarFs(jarFile); } catch (IOException e) { throw new RuntimeException(e); } } /** * Use this method instead of {@link Paths#get(String, String...)} or {@link Paths#get(URI)}. * * <p>Supports "file:path", "jar:file:jarfile.jar!/path", and plain old paths. * * <p>For JAR files, automatically open and cache filesystems. */ public static Path fromUrl(String urlString) { if (urlString.startsWith("file:") || urlString.startsWith("jar:")) { URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new RuntimeException("Failed to resolve path from " + urlString, e); } return fromUrl(url); } else { return Paths.get(urlString); } } /** Isn't this what {@link Paths#get(URI)} should do? */ public static Path fromUrl(URL url) { try { switch (url.getProtocol()) { case "file": return Paths.get(url.toURI()); case "jar": String[] parts = url.getPath().split("!", 0); Path jarFile = Paths.get(new URI(parts[0]).toURL().getFile()); FileSystem fs = getJarFs(jarFile); return fs.getPath(parts[1].substring(1)); default: throw new IllegalArgumentException("unsupported fs type for '" + url + "'"); } } catch (Exception e) { throw new RuntimeException("Failed to resolve path from " + url, e); } } public static URI toUri(URL url) { try { return url.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException("invalid URL: " + url, e); } } static String baseNameFor(Path path) { String name = path.getFileName().toString(); int dotIndex = name.indexOf("."); return dotIndex >= 0 ? name.substring(0, dotIndex) : name; } public static InputStream getInputStream(Path path) throws IOException { // otherwise we get ClosedByInterruptException, meh if (path.toUri().getScheme().equals("file")) { return new BufferedInputStream(new FileInputStream(path.toFile())); } return new BufferedInputStream(Files.newInputStream(path)); } public static byte[] getBytes(Path path) throws IOException { return Util.readBytes(getInputStream(path)); } public static Path[] listFiles(Path path) throws IOException { try (Stream<Path> list = Files.list(path)) { return list.toArray(Path[]::new); } } public static Path[] listFiles(Path path, final Predicate<Path> filter) throws IOException { try (Stream<Path> list = Files.list(path)) { return list.filter(filter).toArray(Path[]::new); } } public static String[] listFileNames(Path path) { File[] files = path.toFile().listFiles(); if (files == null) return null; String[] strings = new String[files.length]; for (int i = 0; i < files.length; i++) { strings[i] = files[i].getName(); } return strings; } public static Path join(Path path, String... pathParts) { for (String pathPart : pathParts) { path = path.resolve(pathPart); } return path; } public static String externalize(Path path) { if (path.getFileSystem().provider().getScheme().equals("file")) { return path.toString(); } else { return path.toUri().toString(); } } /** Returns a reference-counted Jar FileSystem, possibly one that was previously returned. */ private static FileSystem getJarFs(Path jarFile) throws IOException { Path key = jarFile.toAbsolutePath(); synchronized (ZIP_FILESYSTEMS) { FsWrapper fs = ZIP_FILESYSTEMS.get(key); if (fs == null) { fs = new FsWrapper(FileSystems.newFileSystem(key, (ClassLoader) null), key); fs.incrRefCount(); ZIP_FILESYSTEMS.put(key, fs); } else { fs.incrRefCount(); } return fs; } } @SuppressWarnings("NewApi") private static class FsWrapper extends FileSystem { private final FileSystem delegate; private final Path jarFile; @GuardedBy("this") private int refCount; public FsWrapper(FileSystem delegate, Path jarFile) { this.delegate = delegate; this.jarFile = jarFile; } synchronized void incrRefCount() { refCount++; } synchronized void decrRefCount() throws IOException { if (--refCount == 0) { synchronized (ZIP_FILESYSTEMS) { ZIP_FILESYSTEMS.remove(jarFile); } delegate.close(); } } @Override public FileSystemProvider provider() { return delegate.provider(); } @Override public void close() throws IOException { decrRefCount(); } @Override public boolean isOpen() { return delegate.isOpen(); } @Override public boolean isReadOnly() { return delegate.isReadOnly(); } @Override public String getSeparator() { return delegate.getSeparator(); } @Override public Iterable<Path> getRootDirectories() { return delegate.getRootDirectories(); } @Override public Iterable<FileStore> getFileStores() { return delegate.getFileStores(); } @Override public Set<String> supportedFileAttributeViews() { return delegate.supportedFileAttributeViews(); } @Override public Path getPath(String first, String... more) { return delegate.getPath(first, more); } @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { return delegate.getPathMatcher(syntaxAndPattern); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { return delegate.getUserPrincipalLookupService(); } @Override public WatchService newWatchService() throws IOException { return delegate.newWatchService(); } } }
27.371747
95
0.659785
1cc4c42fa1a82aaa3affc9b8bddaf0a8d40cb375
1,848
package c.t; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.os.Build; import java.util.ArrayList; class a { /* renamed from: c.t.a$a reason: collision with other inner class name */ interface AbstractC0062a { void onAnimationPause(Animator animator); void onAnimationResume(Animator animator); } static void a(Animator animator) { if (Build.VERSION.SDK_INT >= 19) { animator.pause(); return; } ArrayList<Animator.AnimatorListener> listeners = animator.getListeners(); if (listeners != null) { int size = listeners.size(); for (int i2 = 0; i2 < size; i2++) { Animator.AnimatorListener animatorListener = listeners.get(i2); if (animatorListener instanceof AbstractC0062a) { ((AbstractC0062a) animatorListener).onAnimationPause(animator); } } } } static void a(Animator animator, AnimatorListenerAdapter animatorListenerAdapter) { if (Build.VERSION.SDK_INT >= 19) { animator.addPauseListener(animatorListenerAdapter); } } static void b(Animator animator) { if (Build.VERSION.SDK_INT >= 19) { animator.resume(); return; } ArrayList<Animator.AnimatorListener> listeners = animator.getListeners(); if (listeners != null) { int size = listeners.size(); for (int i2 = 0; i2 < size; i2++) { Animator.AnimatorListener animatorListener = listeners.get(i2); if (animatorListener instanceof AbstractC0062a) { ((AbstractC0062a) animatorListener).onAnimationResume(animator); } } } } }
32.421053
87
0.59145
5580eb0f1ebd1de2198103aeae507b1b98362a82
1,414
package quickcarpet.mixin.fabricApi; import net.fabricmc.fabric.impl.registry.sync.RegistrySyncManager; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import quickcarpet.QuickCarpet; @Mixin(value = RegistrySyncManager.class) public class RegistrySyncManagerMixin { private static final ThreadLocal<Identifier> currentRegistry = new ThreadLocal<>(); @Redirect(method = "createAndPopulateRegistryMap", at = @At( value = "INVOKE", target = "Lnet/minecraft/util/registry/Registry;get(Lnet/minecraft/util/Identifier;)Ljava/lang/Object;" )) private static <T> T quickcarpet$redirectGetRegistry(Registry<T> registry, Identifier id) { currentRegistry.set(id); return registry.get(id); } @Redirect(method = "createAndPopulateRegistryMap", at = @At( value = "INVOKE", target = "Lnet/minecraft/util/registry/Registry;getId(Ljava/lang/Object;)Lnet/minecraft/util/Identifier;" )) private static <T> Identifier quickcarpet$redirectGetId(Registry<T> mutableRegistry, T entry) { Identifier id = mutableRegistry.getId(entry); if (QuickCarpet.getInstance().isIgnoredForRegistrySync(currentRegistry.get(), id)) return null; return id; } }
41.588235
113
0.739745
883c2e1691019a48c831bf2cb14a1415be669b9c
2,661
/* * Copyright 2000-2017 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.buildServer.nuget.server.trigger.impl.queue; import com.intellij.openapi.diagnostic.Logger; import jetbrains.buildServer.nuget.server.trigger.impl.checker.PackageChecker; import jetbrains.buildServer.nuget.server.trigger.impl.settings.PackageCheckerSettings; import jetbrains.buildServer.nuget.server.trigger.impl.source.NuGetSourceChecker; import jetbrains.buildServer.util.NamedDaemonThreadFactory; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author Eugene Petrenko (eugene.petrenko@gmail.com) * Date: 30.09.11 14:30 */ public class PackageChangesCheckerThread { private static final Logger LOG = Logger.getInstance(PackageChangesCheckerThread.class.getName()); private final ScheduledExecutorService myExecutor; private final PackageCheckQueue myHolder; private final Collection<PackageChecker> myCheckers; private final NuGetSourceChecker myPreChecker; public PackageChangesCheckerThread(@NotNull final PackageCheckQueue holder, @NotNull final PackageCheckerSettings settings, @NotNull final Collection<PackageChecker> checkers, @NotNull final NuGetSourceChecker preChecker) { myHolder = holder; myCheckers = checkers; myPreChecker = preChecker; myExecutor = Executors.newScheduledThreadPool(settings.getCheckerThreads(), new NamedDaemonThreadFactory("NuGet Packages Version Checker")); } public void stopPackagesCheck() { myExecutor.shutdownNow(); try { myExecutor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.debug("Interrupted wait of NuGet packages checker executor service shutdown. ", e); } } public void startPackagesCheck() { new PackageChangesCheckerThreadTask(myHolder, myExecutor, myCheckers, myPreChecker).postCheckTask(); } }
40.318182
144
0.753476
49997f3b43b4d3b318167a39ffdae91a9bd6e7aa
1,791
package org.zv.fintrack.support; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import junit.framework.TestCase; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.XmlDataSet; import org.dbunit.IDatabaseTester; import org.dbunit.JndiDatabaseTester; /** * Base class for test cases, where data is loaded manually. * * @author arju */ public abstract class LoadDataTestCaseSupport extends TestCase { /** * Target database. */ private static final String JNDI_DATASET = "java:openejb/Resource/fintrackDB"; /** * Used to cleanup database etc. */ private IDatabaseTester databaseTester; /** * Call this first whenever need to access JNDI or logging. * * @return initial context. * @throws NamingException */ protected Context getContext() throws NamingException { return new InitialContext(); } /** * Call this 1st to enable JNDI and logging */ @Override protected void setUp() throws Exception { super.setUp(); getContext(); } /** * Loads data set from xml file. Performs CLEAR_INSERT operation on database. * * @param filename * @throws Exception */ protected void loadData(String filename) throws Exception { IDataSet dataSet = new XmlDataSet(ClassLoader.getSystemClassLoader().getResourceAsStream(filename)); databaseTester = new JndiDatabaseTester(JNDI_DATASET); databaseTester.setDataSet(dataSet); databaseTester.onSetup(); } /** * Unload data. Performs CLEAR operation on loaded database. * * @throws Exception */ protected void unloadData() throws Exception { if (databaseTester != null) { databaseTester.onTearDown(); } databaseTester = null; } }
24.202703
102
0.704076
c1b4638c5dc7531c463d968f572d7fa3dc4f954b
12,370
/******************************************************************************* * Copyright (c) 2007, 2018 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Michael Scharf (Wind River) - initial API and implementation *******************************************************************************/ package org.eclipse.tm.internal.terminal.model; import org.eclipse.tm.terminal.model.ITerminalTextData; /** * Collects the changes of the {@link ITerminalTextData} * * @noextend This class is not intended to be subclassed by clients. * @noreference This class is not intended to be referenced by clients. * @noinstantiate This class is not intended to be instantiated by clients. * This class used to be package-protected. It is public only for access by the Unit Tests. */ public class SnapshotChanges implements ISnapshotChanges { /** * The first line changed */ private int fFirstChangedLine; /** * The last line changed */ private int fLastChangedLine; private int fScrollWindowStartLine; private int fScrollWindowSize; private int fScrollWindowShift; /** * true, if scrolling should not tracked anymore */ private boolean fScrollDontTrack; /** * The lines that need to be copied * into the snapshot (lines that have * not changed don't have to be copied) */ private boolean[] fChangedLines; private int fInterestWindowSize; private int fInterestWindowStartLine; private boolean fDimensionsChanged; private boolean fTerminalHasChanged; private boolean fCursorHasChanged; public SnapshotChanges(int nLines) { setChangedLinesLength(nLines); fFirstChangedLine = Integer.MAX_VALUE; fLastChangedLine = -1; } public SnapshotChanges(int windowStart, int windowSize) { setChangedLinesLength(windowStart + windowSize); fFirstChangedLine = Integer.MAX_VALUE; fLastChangedLine = -1; fInterestWindowStartLine = windowStart; fInterestWindowSize = windowSize; } /** * This is used in asserts to throw an {@link RuntimeException}. * This is useful for tests. * @return never -- throws an exception */ private boolean throwRuntimeException() { throw new RuntimeException(); } /** * @param line * @param size * @return true if the range overlaps with the interest window * @nooverride This method is not intended to be re-implemented or extended by clients. * @noreference This method is not intended to be referenced by clients. * It used to be package protected, and it is public only for Unit Tests. */ public boolean isInInterestWindow(int line, int size) { if (fInterestWindowSize <= 0) return true; if (line + size <= fInterestWindowStartLine || line >= fInterestWindowStartLine + fInterestWindowSize) return false; return true; } /** * @param line * @return true if the line is within the interest window * @nooverride This method is not intended to be re-implemented or extended by clients. * @noreference This method is not intended to be referenced by clients. * It used to be package protected, and it is public only for Unit Tests. */ public boolean isInInterestWindow(int line) { if (fInterestWindowSize <= 0) return true; if (line < fInterestWindowStartLine || line >= fInterestWindowStartLine + fInterestWindowSize) return false; return true; } /** * @param line * @return the line within the window * @nooverride This method is not intended to be re-implemented or extended by clients. * @noreference This method is not intended to be referenced by clients. * It used to be package protected, and it is public only for Unit Tests. */ public int fitLineToWindow(int line) { if (fInterestWindowSize <= 0) return line; if (line < fInterestWindowStartLine) return fInterestWindowStartLine; return line; } /** * The result is only defined if {@link #isInInterestWindow(int, int)} returns true! * @param line the line <b>before</b> {@link #fitLineToWindow(int)} has been called! * @param size * @return the adjusted size. * @nooverride This method is not intended to be re-implemented or extended by clients. * @noreference This method is not intended to be referenced by clients. * It used to be package protected, and it is public only for Unit Tests. * * <p>Note:</p> {@link #fitLineToWindow(int)} has to be called on the line to * move the window correctly! */ public int fitSizeToWindow(int line, int size) { if (fInterestWindowSize <= 0) return size; if (line < fInterestWindowStartLine) { size -= fInterestWindowStartLine - line; line = fInterestWindowStartLine; } if (line + size > fInterestWindowStartLine + fInterestWindowSize) size = fInterestWindowStartLine + fInterestWindowSize - line; return size; } @Override public void markLineChanged(int line) { if (!isInInterestWindow(line)) return; line = fitLineToWindow(line); if (line < fFirstChangedLine) fFirstChangedLine = line; if (line > fLastChangedLine) fLastChangedLine = line; // in case the terminal got resized we expand // don't remember the changed line because // there is nothing to copy if (line < getChangedLineLength()) { setChangedLine(line, true); } } @Override public void markLinesChanged(int line, int n) { if (n <= 0 || !isInInterestWindow(line, n)) return; // do not exceed the bounds of fChangedLines // the terminal might have been resized and // we can only keep changes for the size of the // previous terminal n = fitSizeToWindow(line, n); line = fitLineToWindow(line); int m = Math.min(line + n, getChangedLineLength()); for (int i = line; i < m; i++) { setChangedLine(i, true); } // this sets fFirstChangedLine as well markLineChanged(line); // this sets fLastChangedLine as well markLineChanged(line + n - 1); } @Override public void markCursorChanged() { fCursorHasChanged = true; } @Override public void convertScrollingIntoChanges() { markLinesChanged(fScrollWindowStartLine, fScrollWindowSize); fScrollWindowStartLine = 0; fScrollWindowSize = 0; fScrollWindowShift = 0; } @Override public boolean hasChanged() { if (fFirstChangedLine != Integer.MAX_VALUE || fLastChangedLine > 0 || fScrollWindowShift != 0 || fDimensionsChanged || fCursorHasChanged) return true; return false; } @Override public void markDimensionsChanged() { fDimensionsChanged = true; } @Override public boolean hasDimensionsChanged() { return fDimensionsChanged; } @Override public boolean hasTerminalChanged() { return fTerminalHasChanged; } @Override public void setTerminalChanged() { fTerminalHasChanged = true; } @Override public void scroll(int startLine, int size, int shift) { size = fitSizeToWindow(startLine, size); startLine = fitLineToWindow(startLine); // let's track only negative shifts if (fScrollDontTrack) { // we are in a state where we cannot track scrolling // so let's simply mark the scrolled lines as changed markLinesChanged(startLine, size); } else if (shift >= 0) { // we cannot handle positive scroll // forget about clever caching of scroll events doNotTrackScrollingAnymore(); // mark all lines inside the scroll region as changed markLinesChanged(startLine, size); } else { // we have already scrolled if (fScrollWindowShift < 0) { // we have already scrolled if (fScrollWindowStartLine == startLine && fScrollWindowSize == size) { // we are scrolling the same region again? fScrollWindowShift += shift; scrollChangesLinesWithNegativeShift(startLine, size, shift); } else { // mark all lines in the old scroll region as changed doNotTrackScrollingAnymore(); // mark all lines changed, because markLinesChanged(startLine, size); } } else { // first scroll in this change -- we just notify it fScrollWindowStartLine = startLine; fScrollWindowSize = size; fScrollWindowShift = shift; scrollChangesLinesWithNegativeShift(startLine, size, shift); } } } /** * Some incompatible scrolling occurred. We cannot do the * scroll optimization anymore... */ private void doNotTrackScrollingAnymore() { if (fScrollWindowSize > 0) { // convert the current scrolling into changes markLinesChanged(fScrollWindowStartLine, fScrollWindowSize); fScrollWindowStartLine = 0; fScrollWindowSize = 0; fScrollWindowShift = 0; } // don't be clever on scrolling anymore fScrollDontTrack = true; } /** * Scrolls the changed lines data * * @param line * @param n * @param shift must be negative! */ private void scrollChangesLinesWithNegativeShift(int line, int n, int shift) { assert shift < 0 || throwRuntimeException(); // scroll the region // don't run out of bounds! int m = Math.min(line + n + shift, getChangedLineLength() + shift); for (int i = line; i < m; i++) { setChangedLine(i, hasLineChanged(i - shift)); // move the first changed line up. // We don't have to move the maximum down, // because with a shift scroll, the max is moved // my the next loop in this method if (i < fFirstChangedLine && hasLineChanged(i)) { fFirstChangedLine = i; } } // mark the "opened" lines as changed for (int i = Math.max(0, line + n + shift); i < line + n; i++) { markLineChanged(i); } } @Override public void setAllChanged(int height) { fScrollWindowStartLine = 0; fScrollWindowSize = 0; fScrollWindowShift = 0; fFirstChangedLine = fitLineToWindow(0); fLastChangedLine = fFirstChangedLine + fitSizeToWindow(0, height) - 1; // no need to keep an array of changes anymore setChangedLinesLength(0); } @Override public int getFirstChangedLine() { return fFirstChangedLine; } @Override public int getLastChangedLine() { return fLastChangedLine; } @Override public int getScrollWindowStartLine() { return fScrollWindowStartLine; } @Override public int getScrollWindowSize() { return fScrollWindowSize; } @Override public int getScrollWindowShift() { return fScrollWindowShift; } @Override public void copyChangedLines(ITerminalTextData dest, ITerminalTextData source) { int n = Math.min(fLastChangedLine + 1, source.getHeight()); for (int i = fFirstChangedLine; i < n; i++) { if (hasLineChanged(i)) dest.copyLine(source, i, i); } } @Override public int getInterestWindowSize() { return fInterestWindowSize; } @Override public int getInterestWindowStartLine() { return fInterestWindowStartLine; } @Override public void setInterestWindow(int startLine, int size) { int oldStartLine = fInterestWindowStartLine; int oldSize = fInterestWindowSize; fInterestWindowStartLine = startLine; fInterestWindowSize = size; if (oldSize > 0) { int shift = oldStartLine - startLine; if (shift == 0) { if (size > oldSize) { // add lines to the end markLinesChanged(oldStartLine + oldSize, size - oldSize); } // else no lines within the window have changed } else if (Math.abs(shift) < size) { if (shift < 0) { // we can scroll scroll(startLine, oldSize, shift); // mark the lines at the end as new for (int i = oldStartLine + oldSize; i < startLine + size; i++) { markLineChanged(i); } } else { // we cannot shift positive -- mark all changed markLinesChanged(startLine, size); } } else { // no scrolling possible markLinesChanged(startLine, size); } } } @Override public boolean hasLineChanged(int line) { if (line < fChangedLines.length) return fChangedLines[line]; // since the height of the terminal could // have changed but we have tracked only changes // of the previous terminal height, any line outside // the the range of the previous height has changed return isInInterestWindow(line); } int getChangedLineLength() { return fChangedLines.length; } void setChangedLine(int line, boolean changed) { fChangedLines[line] = changed; } void setChangedLinesLength(int length) { fChangedLines = new boolean[length]; } }
29.312796
104
0.702506
a2b20a26e6f50d19b05678dac371ad3cecf32d46
144
package spoon.test.refactoring.parameter.testclasses; public interface IFaceT { @TestHierarchy("R_method1") void method1(Double p1); }
20.571429
54
0.756944
3ddc7d11738521b157ecc5a0fcd6c3ec11c121c1
1,335
package io.github.selcukes.extent.report.tests.steps; import io.cucumber.java.*; import io.github.selcukes.commons.logging.Logger; import io.github.selcukes.commons.logging.LoggerFactory; import static io.github.selcukes.extent.report.Reporter.getReport; public class ReporterHooks { Logger logger = LoggerFactory.getLogger(ReporterHooks.class); @Before public void beforeTest(Scenario scenario) { getReport().start(); //Initialise Extent Report and start recording logRecord // .initSnapshot(driver); //Initialise Full page screenshot logger.info(() -> "Starting Scenario .." + scenario.getName()); getReport().attachAndRestart(); // Attach INFO logs and restart logRecord } @BeforeStep public void beforeStep() { logger.info(() -> "Before Step"); getReport().attachAndRestart(); // Attach INFO logs and restart logRecord } @AfterStep public void afterStep() { getReport().attachAndRestart(); // Attach INFO logs and restart logRecord // getReport().attachScreenshot(); //Attach Full page screenshot } @After public void afterTest(Scenario scenario) { logger.info(() -> "Completed Scenario .." + scenario.getName()); getReport().attachAndClear(); // Attach INFO logs and clear logRecord } }
32.560976
85
0.686891
fa8a67fbc374abfe584b01005ae67a6174a93e28
3,383
package org.bf2.admin.kafka.systemtest.json; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.vertx.core.buffer.Buffer; import org.bf2.admin.kafka.admin.model.Types; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class ModelDeserializer { private static final ObjectMapper MAPPER = new ObjectMapper(); public ModelDeserializer() { MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); } public <T> T deserializeResponse(Buffer responseBuffer, Class<T> clazz) { T deserialized = null; try { deserialized = MAPPER.readValue(responseBuffer.toString(), clazz); } catch (JsonProcessingException e) { e.printStackTrace(); } return deserialized; } public <T> String serializeBody(T object) { try { return MAPPER.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } public Set<String> getNames(Buffer responseBuffer) { Set<String> names = null; try { Types.TopicList topicList = MAPPER.readValue(responseBuffer.toString(), Types.TopicList.class); names = new HashSet<>(); for (Types.Topic topic : topicList.getItems()) { names.add(topic.getName()); } } catch (JsonProcessingException e) { e.printStackTrace(); } return names; } public List<String> getGroupsId(Buffer responseBuffer) { List<String> groupsID = null; try { groupsID = MAPPER.readValue(responseBuffer.toString(), new TypeReference<List<Types.ConsumerGroupDescription>>() { }) .stream().map(Types.ConsumerGroup::getGroupId).collect(Collectors.toList()); } catch (JsonProcessingException e) { e.printStackTrace(); } return groupsID; } public List<Types.TopicPartitionResetResult> getResetResult(Buffer responseBuffer) { List<Types.TopicPartitionResetResult> res = null; try { res = MAPPER.readValue(responseBuffer.toString(), new TypeReference<Types.PagedResponse<Types.TopicPartitionResetResult>>() { }).getItems(); } catch (JsonProcessingException e) { return Collections.emptyList(); } return res; } public Types.ConsumerGroupDescription getGroupDesc(Buffer responseBuffer) { Types.ConsumerGroupDescription groupsDesc = null; try { groupsDesc = MAPPER.readValue(responseBuffer.toString(), Types.ConsumerGroupDescription.class); } catch (JsonProcessingException e) { e.printStackTrace(); } return groupsDesc; } public Map<String, Object> getError(Buffer responseBuffer) { try { return MAPPER.readValue(responseBuffer.toString(), new TypeReference<Map<String, Object>>() { }); } catch (JsonProcessingException e) { e.printStackTrace(); return Collections.emptyMap(); } } }
34.171717
152
0.65031
241133c8026e88e233426b9346405d8ef5e6fb8b
1,010
package com.simplegame.server.bus.swap; import com.simplegame.core.message.Message; import com.simplegame.server.executor.Route; import com.simplegame.server.message.IRouteHelper; /** * * @Author zeusgooogle@gmail.com * @sine 2015年6月19日 下午6:18:36 * */ public class BusRouteHelper implements IRouteHelper { @Override public Route getRoute(Message message) { Route route = null; switch (message.getDest().getValue()) { case 1: route = new Route("bus_cache"); route.setData(message.getRoleId()); break; case 2: route = new Route("stage_control"); route.setData(message.getRoleId()); break; case 5: route = new Route("bus_init"); route.setData(message.getRoleId()); break; case 7: route = new Route("system"); route.setData(message.getRoleId()); break; } return route; } }
24.047619
53
0.573267
c54be1751f75471507495fdeedd8b7f772080e49
2,233
package com.github.qq120011676.ladybird.web.date.autoconfigure; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @Data @ConfigurationProperties(prefix = "ladybird.request-date") public class RequestDateFormatProperties { /** * 解析Date时间格式 */ private String datePattern = "yyyy-MM-dd HH:mm:ss z"; /** * 解析Date时间时区 */ private String dateTimeZone = "GMT+8"; /** * Date是否严格解析时间 false则严格解析 true宽松解析 */ private boolean dateLenient = true; /** * Date是否允许空字符串(false不允许 true允许) */ private boolean dateAllowEmpty = true; /** * Date自动匹配长度 */ private boolean datePatternLengthAuto = true; /** * 解析LocalDate时间格式 */ private String localDatePattern = "yyyy-MM-dd"; /** * 解析LocalDate时间时区 */ private String localDateTimeZone = "GMT+8"; /** * LocalDate是否严格解析时间 false则严格解析 true宽松解析 */ private boolean localDateLenient = true; /** * LocalDate是否允许空字符串(false不允许 true允许) */ private boolean localDateAllowEmpty = true; /** * LocalDate自动匹配长度 */ private boolean localDatePatternLengthAuto = true; /** * 解析LocalDateTime时间格式 */ private String localDateTimePattern = "yyyy-MM-dd HH:mm:ss z"; /** * 解析LocalDateTime时间时区 */ private String localDateTimeTimeZone = "GMT+8"; /** * LocalDateTime是否严格解析时间 false则严格解析 true宽松解析 */ private boolean localDateTimeLenient = true; /** * LocalDateTime是否允许空字符串(false不允许 true允许) */ private boolean localDateTimeAllowEmpty = true; /** * LocalDateTime自动匹配长度 */ private boolean localDateTimePatternLengthAuto = true; /** * 解析Date时间格式 */ private String localTimePattern = "HH:mm:ss"; /** * 解析LocalTime时间时区 */ private String localTimeTimeZone = "GMT+8"; /** * LocalTime是否严格解析时间 false则严格解析 true宽松解析 */ private boolean localTimeLenient = true; /** * LocalTime是否允许空字符串(false不允许 true允许) */ private boolean localTimeAllowEmpty = true; /** * LocalTime自动匹配长度 */ private boolean localTimePatternLengthAuto = true; }
20.3
75
0.633229
350b65ac8f43f4b5eadc99d7e29e0d6969fca53e
337
package org.apache.spark.streaming.receiver; public class StopReceiver$ implements org.apache.spark.streaming.receiver.ReceiverMessage { /** * Static reference to the singleton instance of this Scala object. */ public static final StopReceiver$ MODULE$ = null; public StopReceiver$ () { throw new RuntimeException(); } }
37.444444
92
0.747774
90c5ac9b0f4087a42b3a108a10337a881e4997ed
3,328
package com.company; import java.time.format.DateTimeFormatter; import java.util.Scanner; import java.time.LocalDateTime; public class Menu { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss"); double Deuda =0; Scanner sc = new Scanner(System.in); Capacidadprestar cp = new Capacidadprestar(); public String Option (int index, String name[],String pw[], double cash[] , int row ) { double cap; cap = cp.moneyMax(row,cash);; while (true) { System.out.println("\u001B[0m################################ Menu m################################"); System.out.println("\u001B[0m Nota: Ingrese el numero de la acción que desea realizar"); System.out.println("\u001B[0m 1.) Movimientos de saldo"); System.out.println("\u001B[0m 2.) Solicitar un Crédito"); System.out.println("\u001B[0m 3.) Cambiar Contraseña"); System.out.println("\u001B[0m 4.) Salir"); System.out.println("\u001B[0m Ingrese la opción de menu a la que desea ingresar: "); String menu = sc.nextLine(); switch (menu) { case "1": MovimientoCuenta.MovimientoCuentaUser1(); System.out.println("\u001B[31m Su saldo actual es de "+ cash[index]); break; case "2": System.out.println("\u001B[31m ###################Solicitud de prestamos###################"); System.out.println("\u001B[31m Todas las transacciones seran recibidas y revisadas en un plazo de 96 Horas"); System.out.println("\u001B[31m Ingrese el monto que desea que desea recibir"); double monto = sc.nextInt(); sc.nextLine(); Deuda = (monto * 0.30) + monto + Deuda; if ( cap >= monto){ cap= cap - monto; cash[index] +=monto; System.out.println("\u001B[31m Su saldo tras el prestamo realizado es de: "+ cash[index]); System.out.println("\u001B[31m Le correspondera pagar para saldar la deuda un total de "+ Deuda); } else { System.out.println("\u001B[31m IMPOSIBLE REALIZAR TRANSACCIÓN"); } break; case "3": System.out.println("\u001B[31m Por favor actualizar su contraseña"); pw[index]= sc.nextLine(); System.out.println("\u001B[31m La contraseña actualizada es: " + pw[index] ); break; case "4": System.out.println("\u001B[0m######## Salir ########"); System.out.println("\u001B[32m Gracias por preferir al banco xyz "); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss"); System.out.println("\u001B[32m Sesión cerrada a las "+ dtf.format(LocalDateTime.now()) ); System.exit(0); break; default: System.out.println("\u001B[31m La opción seleccionada es invalida "); } } } }
51.2
130
0.507212
7c6053552baf5648cf641d8a6eb436d18bb66d16
188
package github_day01; /** * Created by wangyuhao on 2017/6/13. */ public class HelloGit { public static void main(String... args) { System.out.println("hello git"); } }
17.090909
45
0.632979
91a5730326b7646a1b458fe8886c20bf28a00af3
95,711
/* * This file was automatically generated by EvoSuite * Sat Nov 07 20:19:07 GMT 2020 */ package org.objectweb.asm.jip; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; import org.objectweb.asm.jip.AnnotationVisitor; import org.objectweb.asm.jip.Attribute; import org.objectweb.asm.jip.ByteVector; import org.objectweb.asm.jip.ClassWriter; import org.objectweb.asm.jip.Label; import org.objectweb.asm.jip.MethodWriter; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class MethodWriter_ESTest extends MethodWriter_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test000() throws Throwable { int[] intArray0 = new int[1]; intArray0[0] = 2; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 1, 2); assertEquals(3, int0); } /** //Test case number: 1 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test001() throws Throwable { byte[] byteArray0 = new byte[9]; byteArray0[2] = (byte)106; int int0 = MethodWriter.readInt(byteArray0, 0); assertEquals(27136, int0); } /** //Test case number: 2 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test002() throws Throwable { byte[] byteArray0 = new byte[9]; byteArray0[1] = (byte)1; int int0 = MethodWriter.readInt(byteArray0, 0); assertEquals(65536, int0); } /** //Test case number: 3 /*Coverage entropy=1.3641953134285743 */ @Test(timeout = 4000) public void test003() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); methodWriter0.visitInsn(22); methodWriter0.visitTryCatchBlock(label0, label0, label0, ",WB5)\"L@"); int int0 = methodWriter0.getSize(); assertEquals(43, int0); } /** //Test case number: 4 /*Coverage entropy=0.3250829733914482 */ @Test(timeout = 4000) public void test004() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[8]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = "}*.j]ruh*~eJZE%}{xV"; stringArray0[2] = "_v0+PP|~}U"; stringArray0[3] = "7!k-E)52L"; stringArray0[4] = "[]"; stringArray0[5] = "0!k#E2b522"; stringArray0[6] = ",WB5)\"L@"; stringArray0[7] = "_v0+PP|~}U"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "0!k#E2b522", "}*.j]ruh*~eJZE%}{xV", "0!k#E2b522", stringArray0, false, false); methodWriter0.classReaderOffset = 2; methodWriter0.classReaderLength = 3; int int0 = methodWriter0.getSize(); assertEquals(9, int0); } /** //Test case number: 5 /*Coverage entropy=1.2380167995379123 */ @Test(timeout = 4000) public void test005() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisiblePatameterAnnotations"; Label label0 = new Label(); label0.status = (-457); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisiblePatameterAnnotations", ",WB5)\"L@", "RuntimeInvisiblePatameterAnnotations", stringArray0, false, true); methodWriter0.visitTryCatchBlock(label0, label0, label0, "Exceptions"); // Undeclared exception! try { methodWriter0.visitMaxs(1, (-834)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 8 // verifyException("org.objectweb.asm.jip.Type", e); } } /** //Test case number: 6 /*Coverage entropy=1.3625462282849843 */ @Test(timeout = 4000) public void test006() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3070); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitTypeInsn(47, "RuntimeInvisibleParameterAnnotations"); methodWriter0.visitLabel(label0); methodWriter0.visitLocalVariable(".JAR", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", label0, label0, 3); } /** //Test case number: 7 /*Coverage entropy=1.4531084284149927 */ @Test(timeout = 4000) public void test007() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntmeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntmeInvisibleParameterAnnotations", ",WB)\"L", "RuntmeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitLabel(label0); Label[] labelArray0 = new Label[2]; labelArray0[0] = label0; labelArray0[1] = label0; methodWriter0.visitTableSwitchInsn((-195), (-195), label0, labelArray0); assertEquals(2, labelArray0.length); } /** //Test case number: 8 /*Coverage entropy=1.0594782926538544 */ @Test(timeout = 4000) public void test008() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitIincInsn(1, (-128)); } /** //Test case number: 9 /*Coverage entropy=1.0594782926538544 */ @Test(timeout = 4000) public void test009() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitIincInsn(1, 127); } /** //Test case number: 10 /*Coverage entropy=1.3568735896254884 */ @Test(timeout = 4000) public void test010() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitFieldInsn(2, ",WB5)\"L@", "7!k-E)52L", "7!k-E)52L"); methodWriter0.visitLdcInsn(1); } /** //Test case number: 11 /*Coverage entropy=1.061208440905252 */ @Test(timeout = 4000) public void test011() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitLdcInsn(1); } /** //Test case number: 12 /*Coverage entropy=1.1922589317770562 */ @Test(timeout = 4000) public void test012() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); Label label0 = new Label(); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitJumpInsn(1, label0); } /** //Test case number: 13 /*Coverage entropy=1.0551016181686423 */ @Test(timeout = 4000) public void test013() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "/rzSEDk-4R", stringArray0, true, false); Label label0 = new Label(); // Undeclared exception! try { methodWriter0.visitJumpInsn(722, label0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 722 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 14 /*Coverage entropy=1.197445930168231 */ @Test(timeout = 4000) public void test014() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); Label label0 = new Label(); methodWriter0.visitJumpInsn(15, label0); methodWriter0.visitJumpInsn(2, label0); } /** //Test case number: 15 /*Coverage entropy=1.0549201679861442 */ @Test(timeout = 4000) public void test015() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52L"; stringArray0[1] = "pY)c]yY!Z,n?oU}lJ"; stringArray0[2] = "pY)c]yY!Z,n?oU}lJ"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7!k-E)52L", "7!k-E)52L", "pY)c]yY!Z,n?oU}lJ", stringArray0, true, false); methodWriter0.visitMethodInsn(4396, " q?t7k?REP", "Dg\"YnE1qDrb", "7!k-E)52L"); } /** //Test case number: 16 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test016() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitTypeInsn(1757, "RuntimeInvisibleParameterAnnotations"); } /** //Test case number: 17 /*Coverage entropy=1.037814604446326 */ @Test(timeout = 4000) public void test017() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntmeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntmeInvisibleParameterAnnotations", ",WB)\"L", "RuntmeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitVarInsn(2, 1); } /** //Test case number: 18 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test018() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-1215)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "RuntimeInvisibleParametrAnnotations", "FUsQ56i", "RuntimeInvisibleParametrAnnotations", (String[]) null, false, false); methodWriter0.visitIntInsn((-1215), (-585)); } /** //Test case number: 19 /*Coverage entropy=1.3364250972172522 */ @Test(timeout = 4000) public void test019() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52,"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163697), "7!k-E)52,", "7!k-E)52,", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitFieldInsn(2, ",WB5)\"L@", "7!k-E)52,", ",WB5)\"L@"); methodWriter0.visitIntInsn(186, 76); } /** //Test case number: 20 /*Coverage entropy=1.0397207708399179 */ @Test(timeout = 4000) public void test020() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitIntInsn(1048575, (-46)); } /** //Test case number: 21 /*Coverage entropy=1.2498367981128 */ @Test(timeout = 4000) public void test021() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitMultiANewArrayInsn("Exceptions", 3331); methodWriter0.visitInsn(1); } /** //Test case number: 22 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test022() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); byte[] byteArray0 = classWriter0.toByteArray(); int int0 = MethodWriter.readUnsignedShort(byteArray0, 2); assertEquals(47806, int0); } /** //Test case number: 23 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test023() throws Throwable { byte[] byteArray0 = new byte[6]; byteArray0[2] = (byte)24; short short0 = MethodWriter.readShort(byteArray0, 2); assertEquals((short)6144, short0); } /** //Test case number: 24 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test024() throws Throwable { byte[] byteArray0 = new byte[8]; byteArray0[2] = (byte) (-117); short short0 = MethodWriter.readShort(byteArray0, 2); assertEquals((short) (-29952), short0); } /** //Test case number: 25 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test025() throws Throwable { byte[] byteArray0 = new byte[9]; byteArray0[0] = (byte)5; int int0 = MethodWriter.readInt(byteArray0, 0); assertEquals(83886080, int0); } /** //Test case number: 26 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test026() throws Throwable { int[] intArray0 = new int[0]; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 247, 247); assertEquals(0, int0); } /** //Test case number: 27 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test027() throws Throwable { // Undeclared exception! try { MethodWriter.writeShort((byte[]) null, 2, (-1215)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 28 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test028() throws Throwable { byte[] byteArray0 = new byte[2]; // Undeclared exception! try { MethodWriter.writeShort(byteArray0, 2867, 2867); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 2867 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 29 /*Coverage entropy=0.9591824302739718 */ @Test(timeout = 4000) public void test029() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3070); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitVarInsn(169, 1392510721); fail("Expecting exception: RuntimeException"); } catch(RuntimeException e) { // // JSR/RET are not supported with computeFrames option // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 30 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test030() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, true, true); // Undeclared exception! try { methodWriter0.visitVarInsn((-3511), 2); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 31 /*Coverage entropy=0.9591824302739718 */ @Test(timeout = 4000) public void test031() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitTypeInsn((-416), " "); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 32 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test032() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "SourceDebugExtension", "RuntimeInvisibleParameterAnnotations", "AnnotationDefault", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitTypeInsn(187, (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 33 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test033() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); Label[] labelArray0 = new Label[1]; // Undeclared exception! try { methodWriter0.visitTableSwitchInsn((-1792), 218, (Label) null, labelArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 34 /*Coverage entropy=0.8082699580001821 */ @Test(timeout = 4000) public void test034() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitParameterAnnotation(3082, (String) null, true); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 35 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test035() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3072); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 49, "&0RA.9b;O)Z_", "&0RA.9b;O)Z_", "RuntimeInvisibleParametesAnnotations", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitMultiANewArrayInsn((String) null, 1); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 36 /*Coverage entropy=1.052922565938695 */ @Test(timeout = 4000) public void test036() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); // Undeclared exception! try { methodWriter0.visitMethodInsn(Integer.MAX_VALUE, ",WB5)\"L@", ",WB5)\"L@", "LineNumberTable"); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 37 /*Coverage entropy=1.0220830508128 */ @Test(timeout = 4000) public void test037() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[5]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = "RuntimeInvisibleParameterAnnotations"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; stringArray0[4] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1241579778, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitMethodInsn(168, "RuntimeVisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations"); fail("Expecting exception: RuntimeException"); } catch(RuntimeException e) { // // JSR/RET are not supported with computeFrames option // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 38 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test038() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, true, true); // Undeclared exception! try { methodWriter0.visitMethodInsn((-2295), (String) null, ">T|9bQ", (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 39 /*Coverage entropy=1.182323923910242 */ @Test(timeout = 4000) public void test039() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitTryCatchBlock((Label) null, (Label) null, (Label) null, "RuntimeInvisibleParameterAnnotations"); // Undeclared exception! try { methodWriter0.visitMaxs(186, 2); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 40 /*Coverage entropy=0.47413931305783735 */ @Test(timeout = 4000) public void test040() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3035); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, ">T|9bQ", ">T|9bQ", "@W]H _VAZ&v<", stringArray0, false, false); int[] intArray0 = new int[0]; Label[] labelArray0 = new Label[6]; // Undeclared exception! try { methodWriter0.visitLookupSwitchInsn(label0, intArray0, labelArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 0 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 41 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test041() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitLineNumber((-1792), (Label) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 42 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test042() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-1215)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "@W]H _VAZ&v<", "@W]H _VAZ&v<", "@W]H _VAZ&v<", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitLdcInsn((Object) null); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // value null // verifyException("org.objectweb.asm.jip.ClassWriter", e); } } /** //Test case number: 43 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test043() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4057); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1578), "*a@!uFL", "*a@!uFL", "org.objectweb.asm.jip.CgassAdapter", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitLabel((Label) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 44 /*Coverage entropy=0.9591824302739718 */ @Test(timeout = 4000) public void test044() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitJumpInsn(169, label0); fail("Expecting exception: RuntimeException"); } catch(RuntimeException e) { // // JSR/RET are not supported with computeFrames option // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 45 /*Coverage entropy=0.9591824302739718 */ @Test(timeout = 4000) public void test045() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitInsn((-5029)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 46 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test046() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); // Undeclared exception! try { methodWriter0.visitInsn((-268435456)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -268435456 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 47 /*Coverage entropy=0.9591824302739718 */ @Test(timeout = 4000) public void test047() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitIincInsn((-1999), 2810); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1999 // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 48 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test048() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52,"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163697), "7!k-E)52,", "7!k-E)52,", ",WB5)\"L@", stringArray0, true, false); // Undeclared exception! try { methodWriter0.visitFieldInsn((byte) (-1), "7!k-E)52,", "WSoAx", ""); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 49 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test049() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 4493, "7m!k-E)52L", "7m!k-E)52L", "7m!k-E)52L", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitFieldInsn(1315, "JSR/RET are not supported with computeFrames option", "7m!k-E)52L", (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 50 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test050() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "Ljava/lang/Synthetic;", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitAttribute((Attribute) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 51 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test051() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitAnnotation((String) null, false); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 52 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test052() throws Throwable { // Undeclared exception! try { MethodWriter.readUnsignedShort((byte[]) null, 362); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 53 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test053() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); byte[] byteArray0 = classWriter0.toByteArray(); // Undeclared exception! try { MethodWriter.readUnsignedShort(byteArray0, 2594); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 2594 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 54 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test054() throws Throwable { // Undeclared exception! try { MethodWriter.readShort((byte[]) null, 2); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 55 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test055() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); byte[] byteArray0 = classWriter0.toByteArray(); // Undeclared exception! try { MethodWriter.readShort(byteArray0, 3057); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 3057 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 56 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test056() throws Throwable { // Undeclared exception! try { MethodWriter.readInt((byte[]) null, (-1792)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 57 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test057() throws Throwable { byte[] byteArray0 = new byte[1]; // Undeclared exception! try { MethodWriter.readInt(byteArray0, (byte) (-23)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -23 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 58 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test058() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4129); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1565), "Ljva/lang/y=h4tic;", "Ljva/lang/y=h4tic;", "~q=<,<rARwG", stringArray0, false, false); // Undeclared exception! try { methodWriter0.put((ByteVector) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 59 /*Coverage entropy=0.3250829733914482 */ @Test(timeout = 4000) public void test059() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "@W]H _VAZ&v<", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", stringArray0, false, false); ByteVector byteVector0 = new ByteVector(3057); byteVector0.length = (-155); // Undeclared exception! try { methodWriter0.put(byteVector0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 60 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test060() throws Throwable { int[] intArray0 = new int[9]; // Undeclared exception! try { MethodWriter.getNewOffset(intArray0, intArray0, (Label) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 61 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test061() throws Throwable { // Undeclared exception! try { MethodWriter.getNewOffset((int[]) null, (int[]) null, 373, 19); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 62 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test062() throws Throwable { int[] intArray0 = new int[1]; int[] intArray1 = new int[8]; // Undeclared exception! try { MethodWriter.getNewOffset(intArray1, intArray0, 248, (-243)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 1 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 63 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test063() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; MethodWriter methodWriter0 = null; try { methodWriter0 = new MethodWriter(classWriter0, 186, stringArray0[1], stringArray0[3], "RuntimeVisibleParameterAnnotations", stringArray0, false, false); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 64 /*Coverage entropy=1.4059404255713561 */ @Test(timeout = 4000) public void test064() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); Label label0 = new Label(); Label[] labelArray0 = new Label[0]; methodWriter0.visitTableSwitchInsn((-1847163660), (-1613), label0, labelArray0); methodWriter0.visitLabel(label0); } /** //Test case number: 65 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test065() throws Throwable { Label label0 = new Label(); label0.status = 1548; int[] intArray0 = new int[1]; MethodWriter.getNewOffset(intArray0, intArray0, label0); assertEquals(1, intArray0.length); } /** //Test case number: 66 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test066() throws Throwable { int[] intArray0 = new int[1]; intArray0[0] = 248; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 248, 3); assertEquals((-493), int0); } /** //Test case number: 67 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test067() throws Throwable { Label label0 = new Label(); int[] intArray0 = new int[1]; intArray0[0] = 188; MethodWriter.getNewOffset(intArray0, intArray0, label0); assertArrayEquals(new int[] {188}, intArray0); } /** //Test case number: 68 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test068() throws Throwable { int[] intArray0 = new int[6]; intArray0[0] = (-834); int int0 = MethodWriter.getNewOffset(intArray0, intArray0, (-834), 707); assertEquals(1541, int0); } /** //Test case number: 69 /*Coverage entropy=0.889328100642881 */ @Test(timeout = 4000) public void test069() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3073); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 8, "RuntimeInvisibleParameterAnnotations", "RuntimeVisibleAnnotations", ">T|9bQ", stringArray0, false, false); methodWriter0.visitVarInsn(132, 2); methodWriter0.visitTryCatchBlock(label0, label0, label0, ">T|9bQ"); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 70 /*Coverage entropy=1.0070249002094114 */ @Test(timeout = 4000) public void test070() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitVarInsn(1315, 1); methodWriter0.visitFrame((-1870), (-1792), (Object[]) null, 1048575, (Object[]) null); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 71 /*Coverage entropy=0.6709854676998301 */ @Test(timeout = 4000) public void test071() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "@W]H _VAZ&v<", "kKJ*2nvN*p`=^Ot2", (String[]) null, false, false); methodWriter0.visitIincInsn(3057, 63); methodWriter0.visitLineNumber(63, label0); ByteVector byteVector0 = new ByteVector(512); methodWriter0.put(byteVector0); } /** //Test case number: 72 /*Coverage entropy=0.728530236250064 */ @Test(timeout = 4000) public void test072() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 206, "@W]H _VAZ&v<", "RuntimeInvisibleParameterAnnotations", "$YL", (String[]) null, false, false); methodWriter0.visitTypeInsn(4057, "ConstantValue"); methodWriter0.visitLocalVariable("ConstantValue", "RuntimeInvisibleParameterAnnotations", "t:;", label0, label0, 937); ByteVector byteVector0 = new ByteVector(186); methodWriter0.put(byteVector0); } /** //Test case number: 73 /*Coverage entropy=0.6150342641411843 */ @Test(timeout = 4000) public void test073() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitAnnotation("RuntimeInvisibleParameterAnnotations", false); ByteVector byteVector0 = classWriter0.pool; methodWriter0.put(byteVector0); } /** //Test case number: 74 /*Coverage entropy=1.0020521615058064 */ @Test(timeout = 4000) public void test074() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntmeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntmeInvisibleParameterAnnotations", ",WB)\"L", "RuntmeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitAnnotation("rpOo^.vfo-$LC_", true); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 75 /*Coverage entropy=1.14225140799707 */ @Test(timeout = 4000) public void test075() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); Attribute attribute0 = new Attribute("RuntimeInvisibleParameterAnnotations"); methodWriter0.visitAttribute(attribute0); // Undeclared exception! try { methodWriter0.getSize(); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Attribute", e); } } /** //Test case number: 76 /*Coverage entropy=0.8259567010149779 */ @Test(timeout = 4000) public void test076() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3110); String[] stringArray0 = new String[1]; stringArray0[0] = "]6z5.u'F[77y?nYN?}"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3110, "]6z5.u'F[77y?nYN?}", ",WB)\"L", "]6z5.u'F[77y?nYN?}", stringArray0, false, false); methodWriter0.visitAnnotation("rpOo^.vfo-$LC_", false); int int0 = methodWriter0.getSize(); assertEquals(38, int0); } /** //Test case number: 77 /*Coverage entropy=1.14225140799707 */ @Test(timeout = 4000) public void test077() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "]6z5.u'F[77y?nYN?}"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "]6z5.u'F[77y?nYN?}", ",WB)\"L", "]6z5.u'F[77y?nYN?}", stringArray0, false, true); methodWriter0.visitAnnotation("rpOo^.vfo-$LC_", true); int int0 = methodWriter0.getSize(); assertEquals(38, int0); } /** //Test case number: 78 /*Coverage entropy=1.1422156821538791 */ @Test(timeout = 4000) public void test078() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); methodWriter0.visitAnnotationDefault(); int int0 = methodWriter0.getSize(); assertEquals(22, int0); } /** //Test case number: 79 /*Coverage entropy=0.953822233933542 */ @Test(timeout = 4000) public void test079() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisileParameterAnnotations", "@W]H _VAZ&v<", "kKJ*2nvN*p`=^Ot2", (String[]) null, false, false); methodWriter0.visitIincInsn(3057, 63); methodWriter0.visitLineNumber(63, label0); int int0 = methodWriter0.getSize(); assertEquals(64, int0); } /** //Test case number: 80 /*Coverage entropy=1.4671026455870264 */ @Test(timeout = 4000) public void test080() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); methodWriter0.visitInsn(22); methodWriter0.visitLocalVariable("{", ">", ">", label0, label0, 2); int int0 = methodWriter0.getSize(); assertEquals(71, int0); } /** //Test case number: 81 /*Coverage entropy=0.9957374991778267 */ @Test(timeout = 4000) public void test081() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; String[] stringArray1 = new String[4]; stringArray1[0] = "(.4"; stringArray1[1] = "7!k-E)52L"; stringArray1[2] = ",WB5)\"L@"; stringArray1[3] = "x[>7d"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "AZ!!i}?", "(.4", "AZ!!i}?", stringArray1, false, false); // Undeclared exception! try { methodWriter0.visitFrame(1, 9, stringArray0, 1, stringArray1); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 82 /*Coverage entropy=1.1856606559693668 */ @Test(timeout = 4000) public void test082() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); Label label0 = new Label(); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitLabel(label0); methodWriter0.visitMaxs(1509950721, (-2078427741)); } /** //Test case number: 83 /*Coverage entropy=1.2077414983211279 */ @Test(timeout = 4000) public void test083() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); Label label0 = new Label(); methodWriter0.visitTryCatchBlock(label0, (Label) null, label0, "7!k-E)52L"); methodWriter0.visitMaxs((-834), (-323)); } /** //Test case number: 84 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test084() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "@W]H _VAZ&v<", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitMaxs(2, (-1792)); } /** //Test case number: 85 /*Coverage entropy=0.900908873225472 */ @Test(timeout = 4000) public void test085() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitLineNumber(2, label0); methodWriter0.visitLineNumber(1617, label0); } /** //Test case number: 86 /*Coverage entropy=1.0465634069578553 */ @Test(timeout = 4000) public void test086() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3070); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitLocalVariable(",WB5)\"L@", "D:9icpL-a", "TwGJ(;n-P|GLd4u", label0, label0, 3); } /** //Test case number: 87 /*Coverage entropy=0.6901856760188042 */ @Test(timeout = 4000) public void test087() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4129); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1565), "Ljva/lang/y=h4tic;", "Ljva/lang/y=h4tic;", "Ljva/lang/y=h4tic;", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitLocalVariable("Ljva/lang/y=h4tic;", "Ljva/lang/y=h4tic;", "{", label0, label0, (-1565)); methodWriter0.visitLocalVariable("*r1JN]QYXXB6", "{", "Ljva/lang/y=h4tic;", label0, label0, 4129); } /** //Test case number: 88 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test088() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", stringArray0, true, true); // Undeclared exception! try { methodWriter0.visitLocalVariable("ConstantValue", "StackMapTable", "LocalVariableTable", (Label) null, (Label) null, (-1847163660)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 89 /*Coverage entropy=1.052922565938695 */ @Test(timeout = 4000) public void test089() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); Label label0 = new Label(); methodWriter0.visitLocalVariable("Kg.c", "7!k-E)52L", (String) null, label0, label0, 22); } /** //Test case number: 90 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test090() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, true); methodWriter0.visitTryCatchBlock((Label) null, label0, label0, "java/lang/Throwable"); methodWriter0.visitTryCatchBlock(label0, label0, label0, "java/lang/Throwable"); } /** //Test case number: 91 /*Coverage entropy=0.923840705630872 */ @Test(timeout = 4000) public void test091() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); Label label0 = new Label(); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitTryCatchBlock(label0, label0, label0, (String) null); } /** //Test case number: 92 /*Coverage entropy=0.47522160361112115 */ @Test(timeout = 4000) public void test092() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitMultiANewArrayInsn("{>qWe?GXiJ2c.p}n;Mx", (-1792)); ByteVector byteVector0 = classWriter0.pool; methodWriter0.put(byteVector0); } /** //Test case number: 93 /*Coverage entropy=1.483124116028697 */ @Test(timeout = 4000) public void test093() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); Label label0 = new Label(); Label[] labelArray0 = new Label[1]; labelArray0[0] = label0; methodWriter0.visitTableSwitchInsn(0, 171, label0, labelArray0); assertEquals(1, labelArray0.length); } /** //Test case number: 94 /*Coverage entropy=0.47413931305783735 */ @Test(timeout = 4000) public void test094() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, ">T|9bQ", ">T|9bQ", "@W]H _VAZ&v<", stringArray0, false, false); int[] intArray0 = new int[3]; Label[] labelArray0 = new Label[1]; // Undeclared exception! try { methodWriter0.visitLookupSwitchInsn(label0, intArray0, labelArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 95 /*Coverage entropy=0.7356219397587946 */ @Test(timeout = 4000) public void test095() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); int[] intArray0 = new int[0]; Label[] labelArray0 = new Label[0]; methodWriter0.visitLookupSwitchInsn(label0, intArray0, labelArray0); assertArrayEquals(new int[] {}, intArray0); } /** //Test case number: 96 /*Coverage entropy=0.6890092384766586 */ @Test(timeout = 4000) public void test096() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "@W]H _VAZ&v<", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitIincInsn(24, (-1792)); } /** //Test case number: 97 /*Coverage entropy=0.6730116670092565 */ @Test(timeout = 4000) public void test097() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-1215)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "RuntimeInvisibleParameterAnnotations", "FUsQ56i", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitIincInsn(1, 2033); } /** //Test case number: 98 /*Coverage entropy=1.0397207708399179 */ @Test(timeout = 4000) public void test098() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitIincInsn(1473, 2); } /** //Test case number: 99 /*Coverage entropy=1.0376517997982746 */ @Test(timeout = 4000) public void test099() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitIincInsn(1936, 1936); methodWriter0.visitIincInsn(1936, 3057); } /** //Test case number: 100 /*Coverage entropy=1.353040174936477 */ @Test(timeout = 4000) public void test100() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52L"; stringArray0[1] = "pY)c]yY!Z,n?oU}lJ"; stringArray0[2] = "pY)c]yY!Z,n?oU}lJ"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7!k-E)52L", "7!k-E)52L", "pY)c]yY!Z,n?oU}lJ", stringArray0, true, false); methodWriter0.visitMethodInsn((-1026), "qB!9z S_mj", "P *fQ]q9#'v(\"si", "pY)c]yY!Z,n?oU}lJ"); methodWriter0.visitLdcInsn("P *fQ]q9#'v(\"si"); } /** //Test case number: 101 /*Coverage entropy=1.0220830508128 */ @Test(timeout = 4000) public void test101() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisiblePatameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisiblePatameterAnnotations", ",WB5)\"L@", "RuntimeInvisiblePatameterAnnotations", stringArray0, false, true); methodWriter0.visitLdcInsn("RuntimeInvisiblePatameterAnnotations"); } /** //Test case number: 102 /*Coverage entropy=0.6730116670092565 */ @Test(timeout = 4000) public void test102() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitLdcInsn("RuntimeInvisibleParameterAnnotations"); } /** //Test case number: 103 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test103() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "@W]H _VAZ&v<", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitLabel(label0); } /** //Test case number: 104 /*Coverage entropy=1.053276210360839 */ @Test(timeout = 4000) public void test104() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3070); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitLabel(label0); methodWriter0.visitTypeInsn(47, "RuntimeInvisibleParameterAnnotations"); methodWriter0.visitLabel(label0); } /** //Test case number: 105 /*Coverage entropy=0.3250829733914482 */ @Test(timeout = 4000) public void test105() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); Label label0 = new Label(); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", stringArray0, false, false); label0.status = (-2078427741); methodWriter0.visitLabel(label0); } /** //Test case number: 106 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test106() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitJumpInsn(39, label0); } /** //Test case number: 107 /*Coverage entropy=1.2107659179740389 */ @Test(timeout = 4000) public void test107() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 13, ".s.IFJDCS", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, false, true); methodWriter0.visitLabel(label0); methodWriter0.visitJumpInsn(2, label0); } /** //Test case number: 108 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test108() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitJumpInsn(187, (Label) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 109 /*Coverage entropy=1.0549201679861442 */ @Test(timeout = 4000) public void test109() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52,"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163697), "7!k-E)52,", "7!k-E)52,", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitMethodInsn(186, "7!k-E)52,", "7!k-E)52,", "7!k-E)52,"); } /** //Test case number: 110 /*Coverage entropy=1.305102654481216 */ @Test(timeout = 4000) public void test110() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); methodWriter0.visitMethodInsn(178, "java/lang/Throwable", "java/lang/Throwable", ",WB5)\"L@"); methodWriter0.visitVarInsn(178, 2); } /** //Test case number: 111 /*Coverage entropy=0.6517565611726531 */ @Test(timeout = 4000) public void test111() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[3]; stringArray0[0] = "[]"; stringArray0[1] = "7!k-E)52L"; stringArray0[2] = "Signature"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3, "7!k-E)52L", "Z>:-hbG)q%1aqS\"S!bl", ",WB5)\"L@", stringArray0, false, false); methodWriter0.visitMethodInsn(186, "i!PIo*sO", "j-Cnv-bZqH", "[]"); } /** //Test case number: 112 /*Coverage entropy=1.2490828438192967 */ @Test(timeout = 4000) public void test112() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitMultiANewArrayInsn(",WB5)\"L@", (-330)); methodWriter0.visitFieldInsn((-1), "7!k-E)52L", ",WB5)\"L@", "7!k-E)52L"); } /** //Test case number: 113 /*Coverage entropy=1.061208440905252 */ @Test(timeout = 4000) public void test113() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52,"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163697), "7!k-E)52,", "7!k-E)52,", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitFieldInsn(2, "a<u", "N", "Deprecated"); } /** //Test case number: 114 /*Coverage entropy=0.900908873225472 */ @Test(timeout = 4000) public void test114() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitFieldInsn(2, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "org.objectweb.asm.jip.Handler"); } /** //Test case number: 115 /*Coverage entropy=1.0710185424099148 */ @Test(timeout = 4000) public void test115() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); methodWriter0.visitFieldInsn(3057, "java/lang/Throwable", "org.objectweb.asm.jip.MethodWriter", "java/lang/Throwable"); } /** //Test case number: 116 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test116() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitFieldInsn(2, "}~[{9TZVl8\"", "(^aWAh<>(kx", "*Ll.|XQ^wW#[6Mx"); } /** //Test case number: 117 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test117() throws Throwable { ClassWriter classWriter0 = new ClassWriter(138); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitTypeInsn(2, ",WB5)\"L@"); } /** //Test case number: 118 /*Coverage entropy=1.0787272851742622 */ @Test(timeout = 4000) public void test118() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitTypeInsn((-1683), "P *fQ]q9#'v(\"si"); methodWriter0.visitFrame(3, (-1683), (Object[]) null, 33, (Object[]) null); int int0 = methodWriter0.getSize(); assertEquals(46, int0); } /** //Test case number: 119 /*Coverage entropy=1.7355078289053207 */ @Test(timeout = 4000) public void test119() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; Label label0 = new Label(); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitTryCatchBlock(label0, label0, label0, "RuntimeInvisibleParameterAnnotations"); Label[] labelArray0 = new Label[2]; labelArray0[0] = label0; labelArray0[1] = label0; methodWriter0.visitTableSwitchInsn(1, 16777219, label0, labelArray0); methodWriter0.visitVarInsn(16777219, 16777219); methodWriter0.visitTableSwitchInsn((-3029), (-3029), label0, labelArray0); assertEquals(2, labelArray0.length); } /** //Test case number: 120 /*Coverage entropy=1.0405805589833304 */ @Test(timeout = 4000) public void test120() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = ",WB5)\"L@"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", stringArray0, true, true); methodWriter0.visitVarInsn(55, 68); } /** //Test case number: 121 /*Coverage entropy=1.061208440905252 */ @Test(timeout = 4000) public void test121() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = "7!k-E)52L"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, true); methodWriter0.visitVarInsn(22, 498); } /** //Test case number: 122 /*Coverage entropy=1.0315837194926705 */ @Test(timeout = 4000) public void test122() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitVarInsn(2, 1048575); } /** //Test case number: 123 /*Coverage entropy=0.9888252503713348 */ @Test(timeout = 4000) public void test123() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); methodWriter0.visitVarInsn(178, 2); } /** //Test case number: 124 /*Coverage entropy=1.0717300941124526 */ @Test(timeout = 4000) public void test124() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3057, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitVarInsn(3057, 521); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 3057 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 125 /*Coverage entropy=1.2498367981128 */ @Test(timeout = 4000) public void test125() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 176, "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitMultiANewArrayInsn("7!k-E)52L", 2); methodWriter0.visitIntInsn(86, 178); } /** //Test case number: 126 /*Coverage entropy=0.9591824302739718 */ @Test(timeout = 4000) public void test126() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); // Undeclared exception! try { methodWriter0.visitIntInsn(267386880, 0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 127 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test127() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitIntInsn(17, (-4070)); } /** //Test case number: 128 /*Coverage entropy=1.0397207708399179 */ @Test(timeout = 4000) public void test128() throws Throwable { ClassWriter classWriter0 = new ClassWriter(186); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1847163660), "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); methodWriter0.visitInsn(169); } /** //Test case number: 129 /*Coverage entropy=1.2110440167801229 */ @Test(timeout = 4000) public void test129() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, ",WB5)\"L@", ",WB5)\"L@", ",WB5)\"L@", (String[]) null, false, true); methodWriter0.visitInsn(172); } /** //Test case number: 130 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test130() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitInsn(69); } /** //Test case number: 131 /*Coverage entropy=0.6682484776645385 */ @Test(timeout = 4000) public void test131() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "Ljava/lang/Synthetic;", "RuntimeVisibleParameterAnnotations", "Ljava/lang/Synthetic;", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitFrame(0, (-3), stringArray0, 15, stringArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 0 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 132 /*Coverage entropy=0.8556886672556694 */ @Test(timeout = 4000) public void test132() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3070); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", stringArray0, false, false); methodWriter0.visitFrame(4, (-1276), stringArray0, (-1276), stringArray0); assertEquals(1, stringArray0.length); } /** //Test case number: 133 /*Coverage entropy=0.6774944044487072 */ @Test(timeout = 4000) public void test133() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "Ljava/lang/Synthetic;", "RuntimeVisibleParameterAnnotations", "Ljava/lang/Synthetic;", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitFrame(0, 3910, stringArray0, 15, stringArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 0 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 134 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test134() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", "@W]H _VAZ&v<", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitFrame(2, 2, (Object[]) null, (-1683), (Object[]) null); methodWriter0.visitFrame(3, (-1683), (Object[]) null, 33, (Object[]) null); } /** //Test case number: 135 /*Coverage entropy=1.0304089991452012 */ @Test(timeout = 4000) public void test135() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", "(X|EOiB8{", "RuntimeInvisibleParameterAnnotations", stringArray0, false, false); methodWriter0.visitFrame(21, 3082, stringArray0, 21, stringArray0); methodWriter0.visitMethodInsn(4306, "RuntimeInvisibleParameterAnnotations", "org.objectweb.asm.jip.Edge", "RuntimeInvisibleParameterAnnotations"); methodWriter0.visitFrame(2, (-1320), stringArray0, 2, stringArray0); assertEquals(1, stringArray0.length); } /** //Test case number: 136 /*Coverage entropy=0.6236548495681085 */ @Test(timeout = 4000) public void test136() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1315, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); methodWriter0.visitFrame(1, (-155), (Object[]) null, 1, (Object[]) null); // Undeclared exception! try { methodWriter0.visitFrame((-320), (-2135), (Object[]) null, 2, (Object[]) null); fail("Expecting exception: IllegalStateException"); } catch(IllegalStateException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 137 /*Coverage entropy=0.8082699580001821 */ @Test(timeout = 4000) public void test137() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3082); String[] stringArray0 = new String[1]; stringArray0[0] = "RuntimeInvisibleParameterAnnotations"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3082, "RuntimeInvisibleParameterAnnotations", ",WB5)\"L@", "RuntimeInvisibleParameterAnnotations", stringArray0, false, true); methodWriter0.visitFrame(21, 3082, stringArray0, 21, stringArray0); assertEquals(1, stringArray0.length); } /** //Test case number: 138 /*Coverage entropy=0.9809896824453154 */ @Test(timeout = 4000) public void test138() throws Throwable { ClassWriter classWriter0 = new ClassWriter(176); String[] stringArray0 = new String[4]; stringArray0[0] = ",WB5)\"L@"; stringArray0[1] = ",WB5)\"L@"; stringArray0[2] = ",WB5)\"L@"; stringArray0[3] = "7!k-E)52L"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 176, "7!k-E)52L", "7!k-E)52L", ",WB5)\"L@", stringArray0, true, false); // Undeclared exception! try { methodWriter0.visitParameterAnnotation(178, "7!k-E)52L", true); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 9 // verifyException("org.objectweb.asm.jip.Type", e); } } /** //Test case number: 139 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test139() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3085); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "Ljava/lang/Synthetic;", (String[]) null, false, false); AnnotationVisitor annotationVisitor0 = methodWriter0.visitParameterAnnotation((-2049), "Ljava/lang/Synthetic;", false); assertNotNull(annotationVisitor0); } /** //Test case number: 140 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test140() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1315); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1792), "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitParameterAnnotation((-4078), "{>qWe?GXiJ2c.p}n;Mx", false); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 36 // verifyException("org.objectweb.asm.jip.Type", e); } } /** //Test case number: 141 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test141() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3057); MethodWriter methodWriter0 = null; try { methodWriter0 = new MethodWriter(classWriter0, 49, "<init>", "&dzN1doZ7uF [", "RuntimeInvisibleParameterAnnotations", (String[]) null, false, true); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 142 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test142() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4096); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1578), "*a@!uFL", "", "org.objectweb.asm.jip.ClassAdapter", stringArray0, false, false); MethodWriter methodWriter1 = null; try { methodWriter1 = new MethodWriter(classWriter0, (-1578), "", "", "*a@!uFL", stringArray0, true, false); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 143 /*Coverage entropy=0.3250829733914482 */ @Test(timeout = 4000) public void test143() throws Throwable { ClassWriter classWriter0 = new ClassWriter((byte) (-13)); String[] stringArray0 = new String[6]; stringArray0[0] = ">T|9bQ"; stringArray0[1] = "org.objectweb.asm.jip.ClassWriter"; stringArray0[2] = ">T|9bQ"; stringArray0[3] = "org.objectweb.asm.jip.ClassWriter"; stringArray0[4] = "org.objectweb.asm.jip.ClassWriter"; stringArray0[5] = "_vbkP!"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "_vbkP!", ".jar", "org.objectweb.asm.jip.ClassWriter", stringArray0, false, false); methodWriter0.visitEnd(); } /** //Test case number: 144 /*Coverage entropy=0.6451964504030799 */ @Test(timeout = 4000) public void test144() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4057); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1578), "*a@!uFL", "*a@!uFL", "org.objectweb.asm.jip.CgassAdapter", stringArray0, false, false); methodWriter0.visitAnnotationDefault(); ByteVector byteVector0 = classWriter0.pool; methodWriter0.put(byteVector0); } /** //Test case number: 145 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test145() throws Throwable { byte[] byteArray0 = new byte[12]; int int0 = MethodWriter.readInt(byteArray0, (byte)0); assertEquals(0, int0); } /** //Test case number: 146 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test146() throws Throwable { byte[] byteArray0 = new byte[4]; short short0 = MethodWriter.readShort(byteArray0, (byte)0); assertEquals((short)0, short0); } /** //Test case number: 147 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test147() throws Throwable { byte[] byteArray0 = new byte[12]; MethodWriter.writeShort(byteArray0, 0, 3192); assertEquals(12, byteArray0.length); } /** //Test case number: 148 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test148() throws Throwable { ClassWriter classWriter0 = new ClassWriter(4096); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 49, "RuntimeVisibleParameterAnnotations", "*a@!uFL", "f\";uicJ", stringArray0, false, false); methodWriter0.visitCode(); } /** //Test case number: 149 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test149() throws Throwable { byte[] byteArray0 = new byte[12]; int int0 = MethodWriter.readUnsignedShort(byteArray0, 0); assertEquals(0, int0); } }
37.097287
226
0.652652
e89f124c648bb648d137f4f2bdff43cf615a0f99
646
package com.platform.weixinUtils.message.req; /** * 图片的实体类 */ public class Image { //图片链接(由系统生成) private String PicUrl; //图片消息媒体id,可以调用多媒体文件下载接口拉取数据。 private String MediaId; //消息id,64位整型 private long MsgId; public String getPicUrl() { return PicUrl; } public void setPicUrl(String picUrl) { PicUrl = picUrl; } public String getMediaId() { return MediaId; } public void setMediaId(String mediaId) { MediaId = mediaId; } public long getMsgId() { return MsgId; } public void setMsgId(long msgId) { MsgId = msgId; } }
16.15
45
0.592879
3d5758b2161824e27f74775d4501b4001fb7611e
1,474
package com.zyw.horrarndoo.yizhi.adapter; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.chad.library.adapter.base.BaseViewHolder; import com.zyw.horrarndoo.sdk.utils.StringUtils; import com.zyw.horrarndoo.yizhi.R; import com.zyw.horrarndoo.yizhi.model.bean.douban.movie.child.PersonBean; import java.util.List; /** * Created by Horrarndoo on 2017/10/18. * <p> */ public class MovieDetailAdapter extends BaseCompatAdapter<PersonBean, BaseViewHolder> { public MovieDetailAdapter(@LayoutRes int layoutResId, @Nullable List<PersonBean> data) { super(layoutResId, data); } public MovieDetailAdapter(@Nullable List<PersonBean> data) { super(data); } public MovieDetailAdapter(@LayoutRes int layoutResId) { super(layoutResId); } @Override protected void convert(BaseViewHolder helper, PersonBean item) { helper.setText(R.id.tv_person_name, item.getName()); helper.setText(R.id.tv_person_type, item.getType()); try { //避免空指针异常 if (StringUtils.isEmpty(item.getAvatars().getLarge())) return; Glide.with(mContext).load(item.getAvatars().getLarge()).crossFade().into((ImageView) helper.getView(R.id.iv_avatar_photo)); } catch (Exception e) { e.printStackTrace(); } } }
29.48
96
0.686567
74fd60b405df8f7d7bdb603fe2d701c7cedfeaac
915
/* * Copyright (c) 2022 Airbyte, Inc., all rights reserved. */ package io.airbyte.oauth.flows.google; import io.airbyte.oauth.BaseOAuthFlow; import io.airbyte.oauth.flows.BaseOAuthFlowTest; import java.util.List; public class GoogleSearchConsoleOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { return new GoogleSearchConsoleOAuthFlow(getConfigRepository(), getHttpClient(), this::getConstantState); } @Override protected String getExpectedConsentUrl() { return "https://accounts.google.com/o/oauth2/v2/auth?client_id=test_client_id&redirect_uri=https%3A%2F%2Fairbyte.io&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fwebmasters.readonly&access_type=offline&state=state&include_granted_scopes=true&prompt=consent"; } @Override protected List<String> getExpectedOutputPath() { return List.of("authorization"); } }
31.551724
283
0.785792
913db7dcb59c99fde70a87137f9c23b6fddd7afe
3,191
package com.ergonautics.ergonautics.storage; import com.ergonautics.ergonautics.models.Board; import com.ergonautics.ergonautics.models.SerializableBoardWrapper; import com.ergonautics.ergonautics.models.SerializableWrapper; import com.ergonautics.ergonautics.models.SerializeableRealmListWrapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import io.realm.RealmList; /** * Created by patrickgrayson on 8/24/16. * http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array */ public class Serializer { public static byte[] serialize(Object toSerialize){ SerializableWrapper wrapper = getWrapperForObject(toSerialize); if(wrapper != null){ //Object needed to be wrapped for serialization toSerialize = wrapper; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; byte[] myBytes = null; try { out = new ObjectOutputStream(bos); out.writeObject(toSerialize); myBytes = bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // ignore close exception } try { bos.close(); } catch (IOException ex) { // ignore close exception } } return myBytes; } public static Object deserialize(byte [] toDeserialize){ ByteArrayInputStream bis = new ByteArrayInputStream(toDeserialize); ObjectInput in = null; Object result = null; try { in = new ObjectInputStream(bis); result = in.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); } catch (IOException ex) { // ignore close exception } try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } } if(result instanceof SerializableWrapper){ result = getObjectFromWrapper((SerializableWrapper) result); } return result; } private static SerializableWrapper getWrapperForObject(Object toWrap){ if(toWrap instanceof Board){ return SerializableBoardWrapper.fromBoard((Board) toWrap); } else if(toWrap instanceof RealmList){ return SerializeableRealmListWrapper.fromRealmList((RealmList) toWrap); } else { return null; } } private static Object getObjectFromWrapper(SerializableWrapper wrapper){ return wrapper.unwrap(); } }
30.682692
84
0.591351
d516d916f664812033f440cd543383154c6b8762
3,555
package javaCourse.addressbook.tests; /** * Created by Nadejda.Fedorova on 12.06.2016. */ import javaCourse.addressbook.model.ContactData; import javaCourse.addressbook.model.Contacts; import javaCourse.addressbook.model.GroupData; import javaCourse.addressbook.model.Groups; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class ContactToGroupTests extends TestBase { @BeforeMethod public void ensurePreconditions() { // удаляем все группы до начала теста вместе со всеми их связями // чтобы не проверять потом наличие связей // удаляем все, чтобы гарантировать, что среди групп нет групп с тем же именем, // по которому будем выбирать потом контакты Groups before = app.db().groups(); int ind = before.size(); if (ind > 0) { app.goTo().groupPage(); while(ind > 0) { // отмечаем все группы app.group().selectAnyGroupByInd(ind); ind -- ; } // удаляем все группы app.group().deleteSelectedGroups(); } // создаем новую группу, чтобы было куда добавить контакт // который можно идентифицировать по имени app.goTo().groupPage(); app.group().create(new GroupData().withName("test 10") .withHeader("header 10").withFooter("footer 10")); // создаем новый контакт, чтобы точно был хотя бы один контакт, который ни в одной группе app.goTo().homePage(); app.contact().create(new ContactData().withFirstName("FirstName 10").withLastName("LastName 10")); } @Test public void testContactToGroup() { Groups groups = app.db().groups(); // находим id новой группы (ее номер максимальный) int newGroupId = (groups.stream().mapToInt((g) -> g.getId()).max().getAsInt()); // находим саму новую группу GroupData newGroup = app.db().group(newGroupId).iterator().next(); app.goTo().homePage(); // находим все контакты не включенные в группы app.group().filterContactsNoGroup(); Contacts noGroupBefore = app.contact().all(); // выбираем любой контакт ContactData modifiedContact = noGroupBefore.iterator().next(); // добавляем контакт в новую группу app.contact().addToGroup(modifiedContact, newGroup); // находим все контакты включенные в новую группу в интерфейсе app.group().filterContactsByGroup(newGroup); // находим все контакты включенные в новую группу в базе данных GroupData newGroupAfter = app.db().group(newGroupId).iterator().next(); Contacts newGroupMembersAfter = newGroupAfter.getContacts(); // В новой группе должен быть один контакт Assert.assertTrue(newGroupMembersAfter.size() == 1); // В новую группу входит именно измененный контакт Assert.assertTrue(newGroupMembersAfter.contains(modifiedContact)); // находим все контакты не включенные в группы через UI // проверяю условие не по БД, ибо не умею еще находить контакты не включенные // ни в одну группу по БД при помощи Hibernate ORM app.group().filterContactsNoGroup(); Contacts noGroupAfter = app.contact().all(); // среди контактов без групп стало на один контакт меньше assertThat(noGroupBefore.size()-1, equalTo(noGroupAfter.size())); // пропал имененно измененный контакт assertThat(noGroupBefore.without(modifiedContact), equalTo(noGroupAfter)); verifyContactListInUI(); } }
39.5
103
0.698172
59f9f632ba59f1c4ddbdefa995fea2a99433a20d
577
package com.sdl.ecommerce.odata.client; import com.sdl.ecommerce.api.LocalizationService; import org.springframework.stereotype.Component; import java.net.URI; import java.util.Map; /** * TestLocalizationService * * @author nic */ public class TestLocalizationService implements LocalizationService { @Override public Map<URI, Object> getAllClaims() { return null; } @Override public String getLocale() { return "en_GB"; } @Override public String getLocalizedConfigProperty(String name) { return null; } }
18.03125
69
0.694974
8ec91859e18236fba4cfc40d28723f98982751e4
1,650
package fr.jmini.eadoc.converter; import java.util.Collections; import org.asciidoctor.ast.StructuralNode; import org.junit.Test; import fr.jmini.asciidoctorj.converter.code.CodeTestingUtility; import fr.jmini.eadoc.EStructuralNode; import fr.jmini.eadoc.EadocFactory; public class EadocCodeGeneratorStructuralNodeTest { @Test public void testStructuralNode() throws Exception { StructuralNode eStructuralNode = createEadoc(); EadocCodeGenerator generator = new EadocCodeGenerator(); StringBuilder sb = new StringBuilder(); generator.createStructuralNodeCode(sb, eStructuralNode); CodeTestingUtility.testGeneratedCode(sb.toString(), this.getClass()); } // tag::generated-code[] public EStructuralNode createEadoc() { EStructuralNode eStructuralNode1 = EadocFactory.eINSTANCE.createEStructuralNode(); eStructuralNode1.setId("my-id"); eStructuralNode1.setNodeName(null); eStructuralNode1.setParent(null); eStructuralNode1.setContext("context"); eStructuralNode1.setDocument(null); eStructuralNode1.setInline(false); eStructuralNode1.setBlock(false); eStructuralNode1.setAttributes(Collections.emptyMap()); eStructuralNode1.setRoles(Collections.emptyList()); eStructuralNode1.setReftext(null); eStructuralNode1.setTitle("my-title"); eStructuralNode1.setStyle("my-style"); eStructuralNode1.setLevel(2); eStructuralNode1.setContentModel("simple"); eStructuralNode1.setSourceLocation(null); return eStructuralNode1; } // end::generated-code[] }
35.869565
90
0.725455
0341420802698c4b1654153bede47627613b6456
3,288
package me.crespel.karaplan.config; import java.lang.reflect.Type; import java.security.Principal; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.data.domain.Pageable; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import com.fasterxml.classmate.TypeResolver; import springfox.documentation.builders.AlternateTypeBuilder; import springfox.documentation.builders.AlternateTypePropertyBuilder; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.AlternateTypeRule; import springfox.documentation.schema.AlternateTypeRuleConvention; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import static com.google.common.collect.Lists.*; import static springfox.documentation.schema.AlternateTypeRules.*; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .ignoredParameterTypes(Principal.class) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.ant("/api/**")) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("KaraPlan REST API") .description("All operations are exposed as JSON and require an OAuth 2.0 Access Token granted by the configured OAuth Authorization Server.") .version("1.0") .build(); } /* Pageable interface support from springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration */ @Bean public AlternateTypeRuleConvention pageableConvention( final TypeResolver resolver, final RepositoryRestConfiguration restConfiguration) { return new AlternateTypeRuleConvention() { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public List<AlternateTypeRule> rules() { return newArrayList( newRule(resolver.resolve(Pageable.class), resolver.resolve(pageableMixin(restConfiguration))) ); } }; } private Type pageableMixin(RepositoryRestConfiguration restConfiguration) { return new AlternateTypeBuilder() .fullyQualifiedClassName( String.format("%s.generated.%s", Pageable.class.getPackage().getName(), Pageable.class.getSimpleName())) .withProperties(newArrayList( property(Integer.class, restConfiguration.getPageParamName()), property(Integer.class, restConfiguration.getLimitParamName()), property(String.class, restConfiguration.getSortParamName()) )) .build(); } private AlternateTypePropertyBuilder property(Class<?> type, String name) { return new AlternateTypePropertyBuilder() .withName(name) .withType(type) .withCanRead(true) .withCanWrite(true); } }
33.55102
147
0.759428
26229d37c5a409bae26aff0b618a3f6fde7d5aea
175
package conf; import org.springframework.context.annotation.Configuration; @Configuration public class WebMvcConfig extends CoreWebMvcConfig { // Docker specific }
19.444444
61
0.788571
61dc5d29403d98c957e2e14f14624450f323bd94
7,880
package us.ihmc.robotics.math.trajectories; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.After; import org.junit.Before; import org.junit.Test; import us.ihmc.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest; import us.ihmc.euclid.referenceFrame.FrameQuaternion; import us.ihmc.euclid.referenceFrame.FrameVector3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.referenceFrame.tools.ReferenceFrameTools; import us.ihmc.yoVariables.registry.YoVariableRegistry; import us.ihmc.robotics.trajectories.providers.ConstantOrientationProvider; import us.ihmc.robotics.trajectories.providers.OrientationProvider; public class ProviderBasedConstantOrientationTrajectoryGeneratorTest { private static final double EPSILON = 1e-10; private String namePrefix = "namePrefix"; private ReferenceFrame referenceFrame; private OrientationProvider orientationProvider; private double finalTime; private FrameQuaternion frameOrientation; private ProviderBasedConstantOrientationTrajectoryGenerator provider; private static int globalCounter = 0; @Before public void setUp() { referenceFrame = ReferenceFrame.constructARootFrame("rootFrame!"); frameOrientation = new FrameQuaternion(referenceFrame); orientationProvider = new ConstantOrientationProvider(frameOrientation); } @After public void tearDown() { frameOrientation = null; referenceFrame = null; orientationProvider = null; ReferenceFrameTools.clearWorldFrameTree(); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testConstructor() { try { finalTime = -5.0; provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); fail(); } catch (RuntimeException rte) { } finalTime = 0.0; provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); finalTime = Double.POSITIVE_INFINITY; provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); try { provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, null); fail(); } catch (NullPointerException npe) { } } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testIsDone() { provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); provider.initialize(); provider.compute(finalTime); assertFalse(provider.isDone()); provider.compute(finalTime + EPSILON); assertTrue(provider.isDone()); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testGet() { provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); FrameQuaternion orientationToPack = new FrameQuaternion(); provider.getOrientation(orientationToPack); assertEquals(referenceFrame, orientationToPack.getReferenceFrame()); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testPackAngularVelocity() { provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); FrameVector3D angularVelocityToPack = new FrameVector3D(ReferenceFrame.getWorldFrame(), 10.0, 10.0, 10.0); assertFalse(referenceFrame.equals(angularVelocityToPack.getReferenceFrame())); provider.getAngularVelocity(angularVelocityToPack); assertEquals(0.0, angularVelocityToPack.getX(), EPSILON); assertEquals(0.0, angularVelocityToPack.getY(), EPSILON); assertEquals(0.0, angularVelocityToPack.getZ(), EPSILON); assertSame(referenceFrame, angularVelocityToPack.getReferenceFrame()); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testPackAngularAcceleration() { provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); FrameVector3D angularAccelerationToPack = new FrameVector3D(ReferenceFrame.getWorldFrame(), 10.0, 10.0, 10.0); assertFalse(referenceFrame.equals(angularAccelerationToPack.getReferenceFrame())); provider.getAngularAcceleration(angularAccelerationToPack); assertEquals(0.0, angularAccelerationToPack.getX(), EPSILON); assertEquals(0.0, angularAccelerationToPack.getY(), EPSILON); assertEquals(0.0, angularAccelerationToPack.getZ(), EPSILON); assertSame(referenceFrame, angularAccelerationToPack.getReferenceFrame()); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testPackAngularData() { FrameQuaternion orientationToPack = new FrameQuaternion(referenceFrame); orientationToPack.setYawPitchRollIncludingFrame(referenceFrame, 4.4, 3.3, 1.4); provider = new ProviderBasedConstantOrientationTrajectoryGenerator(namePrefix, referenceFrame, orientationProvider, finalTime, createRegistry()); provider.getOrientation(orientationToPack); assertEquals(referenceFrame, orientationToPack.getReferenceFrame()); provider.getOrientation(orientationToPack); assertEquals(referenceFrame, orientationToPack.getReferenceFrame()); FrameVector3D angularVelocityToPack = new FrameVector3D(ReferenceFrame.getWorldFrame(), 10.0, 10.0, 10.0); FrameVector3D angularAccelerationToPack = new FrameVector3D(ReferenceFrame.getWorldFrame(), 10.0, 10.0, 10.0); assertFalse(referenceFrame.equals(angularVelocityToPack.getReferenceFrame())); assertTrue(ReferenceFrame.getWorldFrame().equals(angularVelocityToPack.getReferenceFrame())); assertFalse(referenceFrame.equals(angularAccelerationToPack.getReferenceFrame())); assertTrue(ReferenceFrame.getWorldFrame().equals(angularAccelerationToPack.getReferenceFrame())); provider.getAngularData(orientationToPack, angularVelocityToPack, angularAccelerationToPack); assertEquals(0.0, orientationToPack.getYaw(), EPSILON); assertEquals(0.0, orientationToPack.getPitch(), EPSILON); assertEquals(0.0, orientationToPack.getRoll(), EPSILON); assertSame(referenceFrame, orientationToPack.getReferenceFrame()); assertEquals(0.0, angularVelocityToPack.getX(), EPSILON); assertEquals(0.0, angularVelocityToPack.getY(), EPSILON); assertEquals(0.0, angularVelocityToPack.getZ(), EPSILON); assertSame(referenceFrame, angularVelocityToPack.getReferenceFrame()); assertEquals(0.0, angularAccelerationToPack.getX(), EPSILON); assertEquals(0.0, angularAccelerationToPack.getY(), EPSILON); assertEquals(0.0, angularAccelerationToPack.getZ(), EPSILON); assertSame(referenceFrame, angularAccelerationToPack.getReferenceFrame()); } private YoVariableRegistry createRegistry() { YoVariableRegistry registry = new YoVariableRegistry("registry" + globalCounter); globalCounter++; return registry; } }
40.618557
157
0.754315
cff7309c05cd003c0c1ca751145d814fb79c13d8
2,767
package top.lizhistudio.androidlua; import top.lizhistudio.androidlua.exception.LuaTypeError; public interface LuaContext { int MAX_STACK = 1000000; int REGISTRY_INDEX = -1001000; int REGISTRY_INDEX_MAIN_THREAD = 1; int REGISTRY_INDEX_GLOBALS = 2; int MULTI_RESULT = -1; long toPointer(int index); long toLong(int index) throws LuaTypeError; double toDouble(int index)throws LuaTypeError; String toString(int index)throws LuaTypeError; byte[] toBytes(int index)throws LuaTypeError; boolean toBoolean(int index); LuaObjectAdapter toLuaObjectAdapter(int index)throws LuaTypeError; void push(long v); void push(double v); void push(String v); void push(byte[] v); void push(boolean v); void push(LuaFunctionAdapter v); void push(LuaObjectAdapter v); void pushNil(); void pushValue(int index); int getTable(int tableIndex); void setTable(int tableIndex); int getGlobal(String key); void setGlobal(String key); int rawGet(int tableIndex); void rawSet(int tableIndex); int getTop(); void setTop(int n); void pop(int n); int type(int index); boolean isInteger(int index); boolean isLuaObjectAdapter(int index); void loadFile(String filePath,CODE_TYPE mode) ; void loadBuffer(byte[] code,String chunkName,CODE_TYPE mode); void pCall(int argNumber, int resultNumber, int errorFunctionIndex); void createTable(int arraySize,int dictionarySize); void destroy(); void interrupt(); enum CODE_TYPE{ TEXT_BINARY(0),TEXT(1),BINARY(2); private final int code; CODE_TYPE(int code) { this.code = code; } public int getCode() { return code; } } enum VALUE_TYPE{ NONE(-1), NIL(0), BOOLEAN(1), LIGHT_USERDATA(2), NUMBER(3), STRING(4), TABLE(5), FUNCTION(6), USERDATA(7), THREAD(8); private final int code; VALUE_TYPE(int code){ this.code = code; } public int getCode(){return code;} public static VALUE_TYPE valueOf(int code) { switch (code) { case -1:return NONE; case 0:return NIL; case 1:return BOOLEAN; case 2:return LIGHT_USERDATA; case 3:return NUMBER; case 4:return STRING; case 5:return TABLE; case 6:return FUNCTION; case 7:return USERDATA; case 8:return THREAD; } throw new RuntimeException(String.format("The code '%d' can't to type 'VALUE_TYPE'",code)); } } }
28.234694
103
0.599566
7508afa85f8d2083db827c1eb6bcaa780312a3e0
140
package dev.fiki.forgehax.api.cmd.listener; public class Listeners { public static IOnUpdate onUpdate(IOnUpdate o) { return o; } }
17.5
49
0.728571
558817a4713500abcb67ca3fd7beea2a52d29e02
3,629
/* * * * Copyright 2010-2016 OrientDB LTD (info(-at-)orientdb.com) * * * * 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.orientechnologies.orient.etl.extractor; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.serializer.OJSONReader; import com.orientechnologies.orient.etl.OETLExtractedItem; import java.io.IOException; import java.io.Reader; import java.text.ParseException; import java.util.NoSuchElementException; public class OETLJsonExtractor extends OETLAbstractSourceExtractor { protected OJSONReader jsonReader; protected Character first = null; protected OETLExtractedItem next; @Override public String getName() { return "json"; } @Override public boolean hasNext() { if (next != null) return true; if (jsonReader == null) return false; try { next = fetchNext(); return next != null; } catch (Exception e) { throw new OETLExtractorException("[JSON extractor] error on extract json", e); } } @Override public OETLExtractedItem next() { if (next != null) { final OETLExtractedItem ret = next; next = null; return ret; } if (!hasNext()) throw new NoSuchElementException("EOF"); try { return fetchNext(); } catch (Exception e) { throw new OETLExtractorException("[JSON extractor] error on extract json", e); } } @Override public void extract(final Reader iReader) { super.extract(iReader); try { final int read = reader.read(); if (read == -1) return; first = (char) read; if (first == '[') first = null; else if (first == '{') total = 1; else throw new OETLExtractorException("[JSON extractor] found unexpected character '" + first + "' at the beginning of input"); jsonReader = new OJSONReader(reader); } catch (Exception e) { throw new OETLExtractorException(e); } } @Override public ODocument getConfiguration() { return new ODocument().fromJSON("{parameters:[],output:'ODocument'}"); } @Override public String getUnit() { return "entries"; } protected OETLExtractedItem fetchNext() throws IOException, ParseException { if (!jsonReader.hasNext()) return null; String value = jsonReader.readString(new char[] { '}', ']' }, true); if (first != null) { // USE THE FIRST CHAR READ value = first + value; first = null; } if (total == 1 && jsonReader.lastChar() == '}') { jsonReader = null; } else if (total != 1 && jsonReader.lastChar() == ']') { if (!value.isEmpty()) value = value.substring(0, value.length() - 1); jsonReader = null; } else { jsonReader.readNext(OJSONReader.NEXT_IN_ARRAY); if (jsonReader.lastChar() == ']') jsonReader = null; } value = value.trim(); if (value.isEmpty()) return null; return new OETLExtractedItem(current++, new ODocument().fromJSON(value)); } }
26.107914
130
0.64205
7e25730032a7116097bb1487ff3df7525d71f724
1,502
package com.wgmc.whattobuy.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.wgmc.whattobuy.R; import com.wgmc.whattobuy.pojo.ShoppingList; import com.wgmc.whattobuy.service.ShoplistService; import java.util.Observable; import java.util.Observer; /** * Created by notxie on 11.03.17. */ public class StandardShoppingListAdapter extends ArrayAdapter<ShoppingList> implements Observer { public StandardShoppingListAdapter(Context context) { super(context, R.layout.list_item_shoplist_standard, ShoplistService.getInstance().getShoppingLists()); } @Override public void update(Observable observable, Object o) { } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.list_item_shoplist_standard, parent, false); ShoppingList item = getItem(position); if (item != null) { ((TextView) v.findViewById(R.id.shoplist_extended_list_item_name)).setText(item.getName()); ((TextView) v.findViewById(R.id.shoplist_extended_list_item_shopname)).setText(item.getWhereToBuy().getName()); } return v; } }
31.957447
123
0.745672
a05fabfa94e5a58622d1c85eebcf90b5e8937ce3
1,376
package com.google.android.gms.location.places.internal; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.data.DataHolder; import com.google.android.gms.location.places.PlacePhotoMetadata; import com.google.android.gms.location.places.PlacePhotoResult; public class zzr extends zzu implements PlacePhotoMetadata { private final String zzaOg = getString("photo_fife_url"); public zzr(DataHolder dataHolder, int i) { super(dataHolder, i); } public /* synthetic */ Object freeze() { return zzyN(); } public CharSequence getAttributions() { return zzI("photo_attributions", null); } public int getMaxHeight() { return zzz("photo_max_height", 0); } public int getMaxWidth() { return zzz("photo_max_width", 0); } public PendingResult<PlacePhotoResult> getPhoto(GoogleApiClient client) { return getScaledPhoto(client, getMaxWidth(), getMaxHeight()); } public PendingResult<PlacePhotoResult> getScaledPhoto(GoogleApiClient client, int width, int height) { return zzyN().getScaledPhoto(client, width, height); } public PlacePhotoMetadata zzyN() { return new zzq(this.zzaOg, getMaxWidth(), getMaxHeight(), getAttributions(), this.zzahw); } }
31.272727
106
0.710756
abe36d946d6dd81056c22cbf1db34557ee18d32e
1,288
package com.malin.learnfragment.fragment; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.Toast; import com.malin.learnfragment.R; public class TitleFragment extends Fragment implements View.OnClickListener { private ImageButton mLeftImageButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_title, container, false); initView(rootView); bingListener(); return rootView; } private void initView(View rootView) { mLeftImageButton = (ImageButton) rootView.findViewById(R.id.id_title_left_btn); } private void bingListener() { mLeftImageButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.id_title_left_btn: { Toast.makeText(getActivity(), "I am an ImageButton in TitleFragment ! ", Toast.LENGTH_SHORT).show(); break; } default: { break; } } } }
24.769231
116
0.666925
f813c4e831360f86c74d5722702e3d87363b1a53
686
package com.jaquadro.minecraft.gardencontainers.item; import com.jaquadro.minecraft.gardencontainers.block.BlockMediumPot; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemMultiTexture; public class ItemMediumPot extends ItemMultiTexture { public ItemMediumPot (Block block) { super(block, block, getSubTypes(block)); } private static String[] getSubTypes (Block block) { if (block instanceof BlockMediumPot) return ((BlockMediumPot) block).getSubTypes(); return new String[0]; } @Override public void registerIcons (IIconRegister register) { } }
29.826087
68
0.740525
18d0b1e06d5bed441b1a43bed9a01c18a159e3d0
2,023
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.data.util; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Streams; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.minecraft.data.models.model.TextureMapping; import net.minecraft.data.models.model.TextureSlot; import net.minecraft.resources.ResourceLocation; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; /** * Copy of {@link net.minecraft.data.models.model.ModelTemplate} with support for generating item predicate overrides. */ public class ModelWithOverrides { private final ResourceLocation parent; private final TextureSlot[] requiredTextures; public ModelWithOverrides(ResourceLocation parent, TextureSlot... requiredTextures) { this.parent = parent; this.requiredTextures = requiredTextures; } public void create(ResourceLocation modelId, TextureMapping textures, OverrideHolder overrides, BiConsumer<ResourceLocation, Supplier<JsonElement>> consumer) { Map<TextureSlot, ResourceLocation> textureMap = Streams.concat(Arrays.stream(this.requiredTextures), textures.getForced()) .collect(ImmutableMap.toImmutableMap(Function.identity(), textures::get)); consumer.accept(modelId, () -> { JsonObject ret = new JsonObject(); ret.addProperty("parent", parent.toString()); if (!textureMap.isEmpty()) { JsonObject textureJson = new JsonObject(); textureMap.forEach((k, path) -> textureJson.addProperty(k.getId(), path.toString())); ret.add("textures", textureJson); } JsonArray overridesJson = overrides.toJson(); if (overridesJson != null) { ret.add("overrides", overridesJson); } return ret; }); } }
34.87931
160
0.762234
dda99fb47f61171386026856ca62949a99a94ca2
1,767
package com.github.jinahya.assertj.validation; /*- * #%L * assertj-bean-validation-generic * %% * Copyright (C) 2021 Jinahya, 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. * #L% */ import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.params.converter.ArgumentConversionException; import org.junit.jupiter.params.converter.ArgumentConverter; import static com.github.jinahya.assertj.validation.BeanAssertions.assertBean; import static com.github.jinahya.assertj.validation.BeanAssertions.assertThat; import static com.github.jinahya.assertj.validation.BeanWrapper.bean; import static java.util.concurrent.ThreadLocalRandom.current; public class BeanAssertArgumentConverter implements ArgumentConverter { @Override public Object convert(final Object source, final ParameterContext context) throws ArgumentConversionException { final BeanAssert va; switch (current().nextInt(3)) { case 0: va = assertThat(source); break; case 1: va = assertThat(bean(source)); break; default: va = assertBean(source); break; } return va; } }
33.980769
115
0.697793
9eaf7e9a7be25aa3467eb996fe4726bf1d2ce5ff
6,792
package snake.multi.net; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import snake.multi.Level; import snake.multi.Pickup; import snake.multi.Snake; import snake.multi.SnakeApp; public class SnakeServer { private List<SynchronizedReader> readers; private List<SynchronizedWriter> writers; private Map<String, ClientHandler> clients; private JFrame frame; private JPanel connectionsPanel; private JPanel cards; public static void main(String[] args) throws IOException, InterruptedException { new SnakeServer().acceptConnections(); } public SnakeServer() { readers = new ArrayList<SynchronizedReader>(); writers = new ArrayList<SynchronizedWriter>(); clients = new HashMap<String, ClientHandler>(); connectionsPanel = new JPanel(); connectionsPanel.setLayout(new BoxLayout(connectionsPanel, BoxLayout.Y_AXIS)); connectionsPanel.setPreferredSize(new Dimension(640, 480)); JLabel label = new JLabel("Connected Clients:"); JButton startGameBtn = new JButton("Start Game"); startGameBtn.addActionListener(new StartGameBtnListener()); cards = new JPanel(); cards.setLayout(new CardLayout()); cards.add(connectionsPanel, "ConnectionsPanel"); ((CardLayout) cards.getLayout()).show(cards, "ConnectionsPanel"); frame = new JFrame(); frame.setTitle("Snake Server"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(cards, BorderLayout.CENTER); frame.getContentPane().add(label, BorderLayout.NORTH); frame.getContentPane().add(startGameBtn, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } public void acceptConnections() throws IOException, InterruptedException { ServerSocket serversock = new ServerSocket(9000); do { Socket socket = serversock.accept(); SynchronizedWriter writer = new SynchronizedWriter(new PrintWriter( socket.getOutputStream())); SynchronizedReader reader = new SynchronizedReader( new BufferedReader(new InputStreamReader( socket.getInputStream()))); readers.add(reader); writers.add(writer); ClientHandler client = new ClientHandler(reader); Thread thread = new Thread(client); thread.start(); } while (!serversock.isClosed()); } public class GameThread implements Runnable { public void run() { tellAll("GAME START"); // setup game loop int width = 640; int height = 480; int items = 10; Level level = new Level(width, height); tellAll("PLAYERS: " + clients.size()); Iterator<ClientHandler> it = clients.values().iterator(); for (int i = 0; i < clients.size(); i++) { ClientHandler client = it.next(); Snake snake = client.getSnake(); level.addSnake(snake); snake.setStartPosition(8 * i, 8); tellAll("PLAYER: " + snake.getName() + " " + snake.getColor().getRGB() + " " + (8 * i) + " " + 8); } tellAll("ITEMS: " + items); for (int i = 0; i < items; i++) { int x = (int) (Math.random() * width / SnakeApp.blocksize); int y = (int) (Math.random() * height / SnakeApp.blocksize); level.addPickup(new Pickup(x, y, i)); tellAll("PICKUP: " + x + " " + y + " " + i); } int interval = 500; long runstart, runstop; boolean running = true; cards.add(level, "GameView"); ((CardLayout) cards.getLayout()).show(cards, "GameView"); frame.setIgnoreRepaint(true); // do game loop (until someone is hit) while (running) { runstart = System.currentTimeMillis(); // do game updates level.doUpdate(); for (Snake s : level.getSnakes()) { tellAll("DIRECTION: " + s.getName() + " " + s.getDirection()); } // check collisions List<String> collisions = level.checkCollisions(); if (collisions.size() > 0 && collisions.get(0).equals("LEVEL COMPLETED")) { running = false; } for (String collision : collisions) { String[] tokens = collision.split("\\s+"); if (tokens[0].equals("CRASH:")) { clients.get(tokens[1]).snake.setStatus(Snake.CRASHED); } tellAll(collision); } // do transition steps to make things smooth for (int i = 0; i < 10; i++) { if (runstart == 0) { runstart = System.currentTimeMillis(); } level.doStep(); // show updates frame.repaint(); // sleep runstop = System.currentTimeMillis(); try { Thread.sleep(interval / 10 - (runstop - runstart)); } catch (InterruptedException e) { e.printStackTrace(); } runstart = 0; } } // tell all the clients to quit tellAll("SHUTDOWN"); for (ClientHandler client : clients.values()) { client.setRunning(false); } } } private void tellAll(String line) { for (SynchronizedWriter writer : writers) { writer.println(line); } } private class StartGameBtnListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { Thread t = new Thread(new GameThread()); t.start(); } } private class ClientHandler implements Runnable { private SynchronizedReader reader; private Snake snake; private String name; private boolean running; public ClientHandler(SynchronizedReader r) throws IOException { this.running = true; this.reader = r; String player = reader.readLine(); if (player.toUpperCase().startsWith("PLAYER:")) { String[] tokens = player.split("\\s+"); name = tokens[1]; Color color = new Color(Integer.parseInt(tokens[2])); snake = new Snake(name, color); clients.put(name, this); JLabel clientLabel = new JLabel(name); clientLabel.setForeground(color); connectionsPanel.add(clientLabel); connectionsPanel.revalidate(); } } @Override public void run() { String line = null; String[] tokens = null; try { while (running) { line = reader.readLine(); tokens = line.split("\\s+"); if (tokens[0].toUpperCase().equals("DIRECTION:") && tokens[1].equals(name)) { snake.setDirection(Integer.parseInt(tokens[2])); } } } catch (IOException e) { e.printStackTrace(); } } public void setRunning(boolean running) { this.running = running; } public Snake getSnake() { return snake; } } }
26.325581
75
0.673587
e12b6c45cab8fbe4edfaa14db3a760f0945f05d9
3,340
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.hazelcast.cache.impl.record; import com.hazelcast.cache.impl.CacheEntriesWithCursor; import com.hazelcast.cache.impl.CacheKeysWithCursor; import com.hazelcast.internal.eviction.EvictableStore; import com.hazelcast.internal.iteration.IterationPointer; import com.hazelcast.internal.serialization.Data; import java.util.Map; /** * Contract point for storing {@link CacheRecord}s. * * @param <K> type of the key of {@link CacheRecord} to be stored * @param <V> type of the value of {@link CacheRecord} to be stored */ public interface CacheRecordMap<K extends Data, V extends CacheRecord> extends Map<K, V>, EvictableStore<K, V> { /** * Sets the entry counting behaviour. * Because, records on backup partitions should not be counted. * * @param enable enables the entry counting behaviour if it is <tt>true</tt>, otherwise disables. */ void setEntryCounting(boolean enable); /** * Fetch minimally {@code size} keys from the {@code pointers} position. * The key is fetched on-heap. * The method may return less keys if iteration has completed. * <p> * NOTE: The implementation is free to return more than {@code size} items. * This can happen if we cannot easily resume from the last returned item * by receiving the {@code tableIndex} of the last item. The index can * represent a bucket with multiple items and in this case the returned * object will contain all items in that bucket, regardless if we exceed * the requested {@code size}. * * @param pointers the pointers defining the state of iteration * @param size the minimal count of returned items, unless iteration has completed * @return fetched keys and the new iteration state */ CacheKeysWithCursor fetchKeys(IterationPointer[] pointers, int size); /** * Fetch minimally {@code size} items from the {@code pointers} position. * Both the key and value are fetched on-heap. * <p> * NOTE: The implementation is free to return more than {@code size} items. * This can happen if we cannot easily resume from the last returned item * by receiving the {@code tableIndex} of the last item. The index can * represent a bucket with multiple items and in this case the returned * object will contain all items in that bucket, regardless if we exceed * the requested {@code size}. * * @param pointers the pointers defining the state of iteration * @param size the minimal count of returned items * @return fetched entries and the new iteration state */ CacheEntriesWithCursor fetchEntries(IterationPointer[] pointers, int size); }
41.75
101
0.713473
6fd0c4e4e19848f7a2b6ed67bd957da0f04fb65e
650
package com.novoda.magicmirror.settings; import android.preference.PreferenceActivity; import com.novoda.magicmirror.R; import java.util.Arrays; import java.util.List; public class SettingsActivity extends PreferenceActivity { private static final List<String> PREFERENCE_FRAGMENTS = Arrays.asList( TwitterPreferences.class.getName() ); @Override protected boolean isValidFragment(String fragmentName) { return PREFERENCE_FRAGMENTS.contains(fragmentName); } @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.preference_headers, target); } }
23.214286
75
0.746154
e44b20e28d5ec7fb9d31c126d05cc9819a32ad8f
3,342
package se.sundsvall.disturbance.service.message.util; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import generated.se.sundsvall.messaging.Sender; import se.sundsvall.disturbance.integration.db.model.AffectedEntity; class SendMessageUtilsTest { @ParameterizedTest @CsvSource({ // All these parameter rows will be processed in the test below, one by one. // Each row will trigger a new invocation of the test method, with the method params: partyId,reference "partyId-1,reference-1", "partyId-2,reference-2", "partyId-3,reference-3", "partyId-4,reference-4", "partyId-5,reference-5", "partyId-6,reference-6", }) void getReferenceByPartyId(String partyId, String expectedReference) { // Set up a list of AffectedEntities. final var affected1 = new AffectedEntity(); affected1.setPartyId("partyId-1"); affected1.setReference("reference-1"); final var affected2 = new AffectedEntity(); affected2.setPartyId("partyId-2"); affected2.setReference("reference-2"); final var affected3 = new AffectedEntity(); affected3.setPartyId("partyId-3"); affected3.setReference("reference-3"); final var affected4 = new AffectedEntity(); affected4.setPartyId("partyId-4"); affected4.setReference("reference-4"); final var affected5 = new AffectedEntity(); affected5.setPartyId("partyId-5"); affected5.setReference("reference-5"); final var affected6 = new AffectedEntity(); affected6.setPartyId("partyId-6"); affected6.setReference("reference-6"); final var affectedEntityList = List.of(affected1, affected2, affected3, affected4, affected5, affected6); final var fetchedReference = SendMessageUtils.getReferenceByPartyId(affectedEntityList, partyId); assertThat(fetchedReference).isEqualTo(expectedReference); } @Test void getReferenceByPartyIdReturnsEmptyStringWhenNotFound() { final var affectedEntity1 = new AffectedEntity(); affectedEntity1.setPartyId("partyId-1"); affectedEntity1.setReference("reference-1"); final var affectedEntity2 = new AffectedEntity(); affectedEntity2.setPartyId("partyId-2"); affectedEntity2.setReference("reference-2"); final var result = SendMessageUtils.getReferenceByPartyId(List.of(affectedEntity1, affectedEntity2), "does-not-exist-in-list"); assertThat(result).isEmpty(); } @Test void createMessage() { final var sender = new Sender() .emailAddress("senderEmailAddress") .emailName("senderEmailAddress") .smsName("smsName"); final var partyId = "partyId"; final var subject = "subject"; final var messageText = "message"; final var message = SendMessageUtils.createMessage(sender, partyId, subject, messageText); assertThat(message).isNotNull(); assertThat(message.getSender()).isNotNull(); assertThat(message.getSender().getEmailName()).isEqualTo(sender.getEmailName()); assertThat(message.getSender().getEmailAddress()).isEqualTo(sender.getEmailAddress()); assertThat(message.getSender().getSmsName()).isEqualTo(sender.getSmsName()); assertThat(message.getPartyId()).isEqualTo(partyId); assertThat(message.getSubject()).isEqualTo(subject); assertThat(message.getMessage()).isEqualTo(messageText); } }
33.42
129
0.763914
8d85dc53602b625869441e3f3d23ab692f56f04c
15,890
package com.example.administrator.ustc_health; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.ble.DeviceControlService; import com.example.administrator.ble.ScanBleActivity; import com.example.administrator.file.FileActivity; import com.example.administrator.friends.MyFriendsActivity; import com.example.administrator.login.LoginActivity; import com.example.administrator.set.ProFileActivity; import com.example.administrator.set.SetActivity; import de.hdodenhof.circleimageview.CircleImageView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private LinearLayout menu_my; private LinearLayout menu_file; private LinearLayout menu_friends; private ImageView iv_my; private ImageView iv_file; private ImageView iv_friends; private TextView tv_my; private TextView tv_file; private TextView tv_friends; private Fragment myFragment; private Fragment fileFragment; private Fragment friendsFragment; private final static String TAG = MainActivity.class .getSimpleName(); byte[] scan; public static String mDeviceName; public static String mDeviceAddress; public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME"; public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS"; //BLe控制服务 private ServiceConnection serCon; DeviceControlService devConService; private BluetoothAdapter mBluetoothAdapter; private static final int REQUEST_ENABLE_BT = 1; public static String str01 = "0", str02 = "0"; private static TextView tv_toolbar_state; CircleImageView myImage; static ImageView iv_toolbar_refresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //判断是否支持ble initBle(); final Intent intent = getIntent(); if (intent != null) { mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME); mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS); scan = intent.getByteArrayExtra("scan"); if (scan != null) { str01 = String.valueOf(scan[19] & 0xff); str02 = String.valueOf((scan[26] & 0xff) * 256 + (scan[25] & 0xff)); } Log.d(TAG, "EXTRAS_DEVICE_NAME:" + mDeviceName + " EXTRAS_DEVICE_ADDRESS:" + mDeviceAddress); } //绑定服务 initService(); // 初始化控件 initView(); // 初始化底部按钮事件 initEvent(); // 初始化并设置当前Fragment initFragment(0); //检查程序是否为第一次运行 if (checkIsFirstRun()) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.mipmap.ic_warning_amber); builder.setTitle("第一次运行"); builder.setMessage("此设备为第一次运行,是否扫描BLE?"); builder.setPositiveButton("是", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intDet = new Intent(); intDet.setClass(MainActivity.this, ScanBleActivity.class); startActivity(intDet); } }); builder.setNegativeButton("否", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "不扫描", Toast.LENGTH_SHORT).show(); } }); builder.show(); } else { SharedPreferences sharedPreferences = this.getSharedPreferences("share", MODE_PRIVATE); String device_name = sharedPreferences.getString("DEVICE_NAME", ""); Log.d(TAG, device_name); if (device_name.equals("")) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.mipmap.ic_warning_amber); builder.setTitle("是否扫描绑定BLE"); builder.setMessage("此设备还没绑定BLE,是否前去绑定?"); builder.setPositiveButton("是", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intDet = new Intent(); intDet.setClass(MainActivity.this, ScanBleActivity.class); startActivity(intDet); } }); builder.setNegativeButton("否", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "不绑定", Toast.LENGTH_SHORT).show(); } }); builder.show(); } else { mDeviceAddress = device_name; } } } //检查程序是否为第一次运行 private boolean checkIsFirstRun() { // 通过检查程序中的缓存文件判断程序是否是第一次运行 SharedPreferences sharedPreferences = this.getSharedPreferences("share", MODE_PRIVATE); boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true); if (isFirstRun) { SharedPreferences.Editor editor = sharedPreferences.edit(); Log.d(TAG, "第一次运行"); // Toast.makeText(MainActivity.this, "第一次运行!", Toast.LENGTH_LONG).show(); editor.putBoolean("isFirstRun", false); editor.commit(); } else { Log.d(TAG, "不是第一次运行!"); // Toast.makeText(MainActivity.this, "不是第一次运行!", Toast.LENGTH_LONG).show(); } return isFirstRun; } private void initService() { serCon = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { devConService = ((DeviceControlService.LocalBinder) service).getService(); } @Override public void onServiceDisconnected(ComponentName componentName) { } }; Intent devConServiceIntent = new Intent(this, DeviceControlService.class); boolean isbind = bindService(devConServiceIntent, serCon, BIND_AUTO_CREATE);//绑定 if (isbind) { Log.d(TAG, "bindService success!!"); } else { Log.d(TAG, "bindService failed!!"); } } //是否支持BLE private boolean initBle() { //1.android:required="false",判断系统是否支持BLE if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "此设备不支持BLE", Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.mipmap.ic_warning_amber); builder.setTitle("退出对话框"); builder.setMessage("此设备不支持BLE,是否退出?"); builder.setPositiveButton("是", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "此设备支持BLE", Toast.LENGTH_SHORT).show(); finish(); } }); builder.setNegativeButton("否", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "此设备不支持BLE", Toast.LENGTH_SHORT).show(); } }); builder.show(); } //2.获取BluetoothAdapter final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); //3.判断是否支持蓝牙,并打开蓝牙 if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return true; } return false; } private void initView() { //Toolbar初始化 final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); // 底部菜单5个Linearlayout menu_my = (LinearLayout) findViewById(R.id.ly_my); menu_file = (LinearLayout) findViewById(R.id.ly_file); menu_friends = (LinearLayout) findViewById(R.id.ly_friends); // 底部菜单5个ImageView iv_my = (ImageView) findViewById(R.id.iv_my); iv_file = (ImageView) findViewById(R.id.iv_file); iv_friends = (ImageView) findViewById(R.id.iv_friends); // 底部菜单5个菜单标题 tv_my = (TextView) findViewById(R.id.tv_my); tv_file = (TextView) findViewById(R.id.tv_file); tv_friends = (TextView) findViewById(R.id.tv_friends); tv_toolbar_state = (TextView) findViewById(R.id.tv_toolbar_state); myImage = (CircleImageView) findViewById(R.id.iv_toolbar_my); iv_toolbar_refresh = (ImageView) findViewById(R.id.iv_toolbar_refresh); iv_toolbar_refresh.setVisibility(View.GONE); } // 设置按钮监听 private void initEvent() { menu_my.setOnClickListener(this); menu_friends.setOnClickListener(this); menu_file.setOnClickListener(this); myImage.setOnClickListener(this); iv_toolbar_refresh.setOnClickListener(this); } private void initFragment(int index) { // 由于是引用了V4包下的Fragment,所以这里的管理器要用getSupportFragmentManager获取 FragmentManager fragmentManager = getSupportFragmentManager(); // 开启事务 FragmentTransaction transaction = fragmentManager.beginTransaction(); // 隐藏所有Fragment hideFragment(transaction); switch (index) { case 0: if (myFragment == null) { myFragment = new MyhealthActivity(); transaction.add(R.id.frame_content, myFragment); } else { transaction.show(myFragment); } break; case 3: if (fileFragment == null) { fileFragment = new FileActivity(); transaction.add(R.id.frame_content, fileFragment); } else { transaction.show(fileFragment); } break; case 4: if (friendsFragment == null) { friendsFragment = new MyFriendsActivity(); transaction.add(R.id.frame_content, friendsFragment); } else { transaction.show(friendsFragment); } break; default: break; } // 提交事务 transaction.commit(); } private void hideFragment(FragmentTransaction transaction) { if (myFragment != null) { transaction.hide(myFragment); } if (friendsFragment != null) { transaction.hide(friendsFragment); } if (fileFragment != null) { transaction.hide(fileFragment); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_share: Intent intent = new Intent(); intent.setClass(MainActivity.this, SetActivity.class); startActivity(intent); break; case R.id.scan: intent = new Intent(); intent.setClass(MainActivity.this, ScanBleActivity.class); startActivity(intent); break; case R.id.reg: intent = new Intent(); intent.setClass(MainActivity.this, LoginActivity.class); startActivity(intent); break; } return super.onOptionsItemSelected(item); } //重置按钮颜色 private void restartBotton() { // ImageView置为灰色 iv_my.setImageResource(R.mipmap.me1); iv_file.setImageResource(R.mipmap.find1); iv_friends.setImageResource(R.mipmap.contact1); // TextView置为灰色 tv_my.setTextColor(0xffA6A6A6); tv_file.setTextColor(0xffA6A6A6); tv_friends.setTextColor(0xffA6A6A6); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ly_my: restartBotton(); iv_my.setImageResource(R.mipmap.me); tv_my.setTextColor(0xff008000); initFragment(0); break; case R.id.ly_file: restartBotton(); iv_file.setImageResource(R.mipmap.find); tv_file.setTextColor(0xff008000); initFragment(3); break; case R.id.ly_friends: restartBotton(); iv_friends.setImageResource(R.mipmap.contact); tv_friends.setTextColor(0xff008000); initFragment(4); break; case R.id.iv_toolbar_my: Intent intent = new Intent(); intent.setClass(MainActivity.this, ProFileActivity.class); startActivity(intent); break; } } @Override protected void onDestroy() { super.onDestroy(); unbindService(serCon);//解除绑定,否则会报异常 } @Override protected void onStop() { super.onStop(); } @Override protected void onResume() { super.onResume(); } //service通知Activity扫描 public static class MyBroadcastReceiver01 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Toast.makeText(context, "已经连接到设备", Toast.LENGTH_SHORT).show(); tv_toolbar_state.setText("已连接"); iv_toolbar_refresh.setVisibility(View.GONE); } } public static class MyBroadcastReceiver02 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Toast.makeText(context, "已经连接到设备", Toast.LENGTH_SHORT).show(); tv_toolbar_state.setText("未连接"); //iv_toolbar_refresh.setVisibility(View.VISIBLE); iv_toolbar_refresh.setVisibility(View.GONE); } } }
36.69746
105
0.609377
4a02bd97a194e0a77b5bee686bd8016ea6a4026f
732
package nam.ui.userInterface; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; import nam.ui.UserInterface; import nam.ui.design.AbstractEventManager; import nam.ui.design.SelectionContext; @SessionScoped @Named("userInterfaceEventManager") public class UserInterfaceEventManager extends AbstractEventManager<UserInterface> implements Serializable { @Inject private SelectionContext selectionContext; @Override public UserInterface getInstance() { return selectionContext.getSelection("userInterface"); } public void removeUserInterface() { UserInterface userInterface = getInstance(); fireRemoveEvent(userInterface); } }
22.181818
108
0.811475
d06382443bfe8063edaf8dbff4b98f53269ffff7
1,103
package com.seezoon.dao.modules.sys.entity; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import com.seezoon.dao.framework.entity.PageCondition; import com.seezoon.dao.framework.sort.annotation.SortField; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 登录日志 * * @author seezoon-generator 2021年4月18日 上午1:30:18 */ @Getter @Setter @ToString @SortField({"userId:t.user_id", "userName:t.user_name", "loginTime:t.login_time", "ip:t.ip"}) public class SysLoginLogCondition extends PageCondition { /** * 用户ID */ @ApiModelProperty(value = "用户ID") private Integer userId; /** * 账号 */ @ApiModelProperty(value = "账号") private String userName; /** * 登录结果 */ @ApiModelProperty(value = "登录结果") private Integer result; /** * IP地址 */ @ApiModelProperty(value = "IP地址") private String ip; @NotEmpty @Size(min = 2, max = 2) @ApiModelProperty(value = "登录日期") private String[] loginDateRange; }
21.627451
93
0.67815
42a7148aa486b9662ca9f63078ba81ba2736918d
549
package cn.xiaowenjie.beans; import lombok.Data; /** * Created by Administrator on 2020/4/29. * <p> * by author wz * <p> * cn.xiaowenjie.beans */ @Data public class PageObject { private int pageNo; private int pageSize; private int schoolId; public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } }
15.685714
43
0.613843
4f897e333ca235ed826f66269572f9b39dec4b9d
5,636
package ethos.model.players.skills.crafting; import java.util.HashMap; import java.util.Map; import ethos.model.players.Player; import ethos.model.players.mode.ModeType; public class Enchantment { private static final Enchantment SINGLETON = new Enchantment(); private Enchantment() { } public enum Enchant { SAPPHIRE_RING(1637, 2550, 7, 18, 719, 114, 1), SAPPHIRE_AMULET(1694, 1727, 7, 18, 719, 114, 1), SAPPHIRE_NECKLACE(1656, 3853, 7, 18, 719, 114, 1), EMERALD_RING(1639, 2552, 27, 37, 719, 114, 2), EMERALD_AMULET(1696, 1729, 27, 37, 719, 114, 2), EMERALD_NECKLACE(1658, 5521, 27, 37, 719, 114, 2), RUBY_RING(1641, 2568, 47, 59, 720, 115, 3), RUBY_AMULET(1698, 1725, 47, 59, 720, 115, 3), RUBY_NECKLACE(1660, 11194, 47, 59, 720, 115, 3), DIAMOND_RING(1643, 2570, 57, 67, 720, 115, 4), DIAMOND_AMULET(1700, 1731, 57, 67, 720, 115, 4), DIAMOND_NECKLACE(1662, 11090, 57, 67, 720, 115, 4), DRAGONSTONE_RING(1645, 2572, 68, 78, 721, 116, 5), DRAGONSTONE_AMULET(1702, 1712, 68, 78, 721, 116, 5), DRAGONSTONE_NECKLACE(1664, 11105, 68, 78, 721, 116, 5), DRAGONSTONE_BRACELET(11115, 11126, 68, 78, 721, 116, 5), ONYX_RING(6575, 6583, 87, 97, 721, 452, 6), ONYX_AMULET(6581, 6585, 87, 97, 721, 452, 6), ONYX_NECKLACE(6577, 11128, 87, 97, 721, 452, 6), ONYX_BRACELET(11130, 11133, 87, 97, 721, 116, 6), ZENYTE_RING(19538, 19550, 87, 97, 721, 452, 6), ZENYTE_NECKLACE(19535, 19547, 87, 97, 721, 452, 6), ZENYTE_AMULET(19541, 19553, 87, 97, 721, 452, 6), ZENYTE_BRACELET(19532, 19544, 93, 110, 721, 452, 6); int unenchanted, enchanted, levelReq, xpGiven, anim, gfx, reqEnchantmentLevel; private Enchant(int unenchanted, int enchanted, int levelReq, int xpGiven, int anim, int gfx, int reqEnchantmentLevel) { this.unenchanted = unenchanted; this.enchanted = enchanted; this.levelReq = levelReq; this.xpGiven = xpGiven; this.anim = anim; this.gfx = gfx; this.reqEnchantmentLevel = reqEnchantmentLevel; } public int getUnenchanted() { return unenchanted; } public int getEnchanted() { return enchanted; } public int getLevelReq() { return levelReq; } public int getXp() { return xpGiven; } public int getAnim() { return anim; } public int getGFX() { return gfx; } public int getELevel() { return reqEnchantmentLevel; } private static final Map<Integer, Enchant> enc = new HashMap<Integer, Enchant>(); public static Enchant forId(int itemID) { return enc.get(itemID); } static { for (Enchant en : Enchant.values()) { enc.put(en.getUnenchanted(), en); } } } private enum EnchantSpell { SAPPHIRE(1155), EMERALD(1165), RUBY(1176), DIAMOND(1180), DRAGONSTONE(1187), ONYX(6003); int spell; private EnchantSpell(int spell) { this.spell = spell; } public int getSpell() { return spell; } public static final Map<Integer, EnchantSpell> ens = new HashMap<Integer, EnchantSpell>(); public static EnchantSpell forId(int id) { return ens.get(id); } static { for (EnchantSpell en : EnchantSpell.values()) { ens.put(en.getSpell(), en); } } } private boolean hasRunes(Player player, int spellID) { switch (spellID) { case 1155: if (!player.getCombat().checkMagicReqs(56)) { return false; } break; case 1165: if (!player.getCombat().checkMagicReqs(57)) { return false; } break; case 1176: if (!player.getCombat().checkMagicReqs(58)) { return false; } break; case 1180: if (!player.getCombat().checkMagicReqs(59)) { return false; } break; case 1187: if (!player.getCombat().checkMagicReqs(60)) { return false; } break; case 6003: if (!player.getCombat().checkMagicReqs(61)) { return false; } break; } return true; } private int getEnchantmentLevel(int spellID) { switch (spellID) { case 1155: // Lvl-1 enchant sapphire return 1; case 1165: // Lvl-2 enchant emerald return 2; case 1176: // Lvl-3 enchant ruby return 3; case 1180: // Lvl-4 enchant diamond return 4; case 1187: // Lvl-5 enchant dragonstone return 5; case 6003: // Lvl-6 enchant onyx return 6; } return 0; } public void enchantItem(Player player, int itemID, int spellID) { Enchant enc = Enchant.forId(itemID); EnchantSpell ens = EnchantSpell.forId(spellID); if (enc == null || ens == null) { return; } /*if (enc.equals(Enchant.DRAGONSTONE_RING)) { player.sendMessage("This item cannot be enchanted into a 'ring of wealth' at this time. However, the ring"); player.sendMessage("of wealth can be bought through the voting, donation and achievement store."); return; }*/ if (player.playerLevel[player.playerMagic] >= enc.getLevelReq()) { if (player.getItems().playerHasItem(enc.getUnenchanted(), 1)) { if (hasRunes(player, spellID)) { if (getEnchantmentLevel(spellID) == enc.getELevel()) { player.getItems().deleteItem(enc.getUnenchanted(), 1); player.getItems().addItem(enc.getEnchanted(), 1); player.getPA().addSkillXP(enc.getXp(), player.playerMagic, true); player.startAnimation(enc.getAnim()); player.gfx100(enc.getGFX()); player.getPA().sendFrame106(6); } else { player.sendMessage("You can only enchant this jewelry using a level-" + enc.getELevel() + " enchantment spell!"); } } else { } } } else { player.sendMessage("You need a magic level of at least " + enc.getLevelReq() + " to cast this spell."); } } public static Enchantment getSingleton() { return SINGLETON; } }
24.828194
122
0.655962
105e7758f5031b5085a9fbf7b7f12a400fa5bef5
4,607
/* * This code / file / algorithm is completely free to use and modify as necessary. * Any attribution is welcome and highly appriciated. */ package io.onclave.nsga.ii.api; import io.onclave.nsga.ii.interfaces.IObjectiveFunction; import io.onclave.nsga.ii.objectivefunction.SCH_1; import io.onclave.nsga.ii.objectivefunction.SCH_2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * @author Debabrata Acharya <debabrata.acharya@icloud.com> * @version 2.0 * @since 2.0 */ public class Configuration { /** * this class is never supposed to be instantiated */ private Configuration() { } public static int POPULATION_SIZE = 100; public static int GENERATIONS = 25; public static int CHROMOSOME_LENGTH = 20; public static String X_AXIS_TITLE = "X-AXIS"; public static String Y_AXIS_TITLE = "Y-AXIS"; public static final double ACTUAL_MIN = 0; public static double ACTUAL_MAX = 0; public static final double NORMALIZED_MIN = 0; public static final double NORMALIZED_MAX = 2; public static final float CROSSOVER_PROBABILITY = 0.7f; public static final float MUTATION_PROBABILITY = 0.03f; public static List<IObjectiveFunction> objectives = null; public static void configure() { Configuration.buildObjectives(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); Reporter.reportAlgorithmStart(); try { switch (bufferedReader.readLine()) { case "1": Configuration.setDefaultAxisTitles(); Reporter.reportDefaultConfiguration(); break; case "2": Reporter.reportCustomConfigurationStartInput(); Configuration.setCustomConfiguration(bufferedReader); Configuration.setCustomAxisTitles(bufferedReader); Reporter.reportCustomConfiguration(); break; default: Reporter.reportWrongInput(); break; } Configuration.ACTUAL_MAX = Math.pow(2, CHROMOSOME_LENGTH) - 1; } catch (IOException e) { Reporter.reportIOException(); } } public static void setObjectives(List<IObjectiveFunction> objectives) { Configuration.objectives = objectives; } public static String getXaxisTitle() { return Configuration.X_AXIS_TITLE; } public static String getYaxisTitle() { return Configuration.Y_AXIS_TITLE; } private static void setDefaultAxisTitles() { Configuration.X_AXIS_TITLE = Configuration.objectives.get(0).objectiveFunctionTitle(); Configuration.Y_AXIS_TITLE = Configuration.objectives.get(1).objectiveFunctionTitle(); } private static void setCustomAxisTitles(final BufferedReader bufferedReader) throws IOException { System.out.print("\nDo you want to provide axis titles? (y/n): "); switch (bufferedReader.readLine()) { case "y": System.out.print("\nEnter X-Axis Title: "); Configuration.X_AXIS_TITLE = bufferedReader.readLine(); System.out.print("Enter Y-Axis Title: "); Configuration.Y_AXIS_TITLE = bufferedReader.readLine(); break; case "n": break; default: Reporter.reportWrongInput(); break; } } private static void setCustomConfiguration(final BufferedReader bufferedReader) throws IOException { System.out.print("Enter the chromosome length to work with: "); Configuration.CHROMOSOME_LENGTH = Integer.parseInt(bufferedReader.readLine()); System.out.print("Enter population size: "); Configuration.POPULATION_SIZE = Integer.parseInt(bufferedReader.readLine()); System.out.print("Enter number of generations: "); Configuration.GENERATIONS = Integer.parseInt(bufferedReader.readLine()); } /** * this method sets the objective functions over which the algorithm is to operate. * it is a list of IObjectionFunction objects. */ private static void buildObjectives() { List<IObjectiveFunction> newObjectives = new ArrayList<>(); newObjectives.add(0, new SCH_1()); newObjectives.add(1, new SCH_2()); Configuration.setObjectives(newObjectives); } }
30.509934
104
0.648578
3b18c3bc093a7a48f953112fe8db8b6f2ac7a2f7
1,537
package Customers; import java.util.Scanner; public class LegalPerson extends Customer { private String name; private String registrationCode; // cod caen private String bankAccount; // cui public LegalPerson(String email,Address address, String name, String registrationCode, String bankAccount) { super(email, address); this.name = name; this.registrationCode = registrationCode; this.bankAccount = bankAccount; } // create from input public LegalPerson(Scanner scanner) { super(scanner); System.out.println("Please enter legal person info."); System.out.println("Name: "); this.name = scanner.nextLine(); System.out.println("Registration code: "); this.registrationCode = scanner.nextLine(); System.out.println("Bank account: "); this.bankAccount = scanner.nextLine(); } @Override public String toString() { String simpleCustomerInfo = super.toString(); return String.format("%s%s%s%s%s", simpleCustomerInfo, "Legal person information\n", "Name: " + this.name + "\n", "Registration code: " + this.registrationCode + "\n", "Bank account: " + this.bankAccount + "\n"); } public String getName() {return this.name;} public String getRegistrationCode() {return this.registrationCode;} public String getBankAccount() {return bankAccount;} }
30.137255
110
0.612882
ceef20963ae2dde0fee4993ab99665348f70c900
4,290
/* * Copyright (c) 2015-2016 William Bittle http://www.praisenter.org/ * 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 Praisenter 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.praisenter.data.slide.text; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.Date; import org.praisenter.Watchable; import org.praisenter.data.Copyable; import org.praisenter.data.Identifiable; import org.praisenter.data.json.SimpleDateFormatJsonDeserializer; import org.praisenter.data.json.SimpleDateFormatJsonSerializer; import org.praisenter.data.slide.ReadOnlySlideComponent; import org.praisenter.data.slide.ReadOnlySlideRegion; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; /** * A component to show the current date and time based on a given format. * @author William Bittle * @version 3.0.0 */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY) @JsonTypeName(value = "dateTimeComponent") public final class DateTimeComponent extends TimedTextComponent implements ReadOnlyDateTimeComponent, ReadOnlyTimedTextComponent, ReadOnlyTextComponent, ReadOnlySlideComponent, ReadOnlySlideRegion, Copyable, Identifiable { private final ObjectProperty<SimpleDateFormat> dateTimeFormat; public DateTimeComponent() { this.dateTimeFormat = new SimpleObjectProperty<>(); this.text.bind(Bindings.createStringBinding(() -> { DateFormat format = this.dateTimeFormat.get(); if (format == null) format = SimpleDateFormat.getDateInstance(); return format.format(Date.from(this.now.get().atZone(ZoneId.systemDefault()).toInstant())); }, this.dateTimeFormat, this.now)); } @Override public DateTimeComponent copy() { DateTimeComponent dtc = new DateTimeComponent(); this.copyTo(dtc); dtc.dateTimeFormat.set(this.dateTimeFormat.get()); return dtc; } @Override @JsonProperty @JsonSerialize(using = SimpleDateFormatJsonSerializer.class) public SimpleDateFormat getDateTimeFormat() { return this.dateTimeFormat.get(); } @JsonProperty @JsonDeserialize(using = SimpleDateFormatJsonDeserializer.class) public void setDateTimeFormat(SimpleDateFormat format) { this.dateTimeFormat.set(format); } @Override @Watchable(name = "dateTimeFormat") public ObjectProperty<SimpleDateFormat> dateTimeFormatProperty() { return this.dateTimeFormat; } }
42.058824
223
0.7669
d793cb9268d975f9e5e6663be316e20ead79cbb0
675
package de.bitsharesmunich.adapters; import com.google.common.primitives.UnsignedLong; import java.util.Comparator; import de.bitsharesmunich.database.HistoricalTransferEntry; /** * Created by nelson on 12/14/16. */ public class TransferAmountComparator implements Comparator<HistoricalTransferEntry> { @Override public int compare(HistoricalTransferEntry lhs, HistoricalTransferEntry rhs) { UnsignedLong lhsAmount = lhs.getHistoricalTransfer().getOperation().getAssetAmount().getAmount(); UnsignedLong rhsAmount = rhs.getHistoricalTransfer().getOperation().getAssetAmount().getAmount(); return lhsAmount.compareTo(rhsAmount); } }
30.681818
105
0.774815