id
stringlengths
7
14
text
stringlengths
1
37.2k
170604542_3
public Game findGameById(Long id) throws InvalidGameIdException { Game game = gameRepository.findById(id).orElse(null); if (game == null) { throw new InvalidGameIdException("Invalid game of id: " + id.toString()); } return game; }
170682516_0
public CmsConfig getConfigById(String id){ Optional<CmsConfig> optional = cmsConfigRepository.findById(id); if(optional.isPresent()){ CmsConfig cmsConfig = optional.get(); return cmsConfig; } return null; }
170829387_12
public void authenticate(AuthenticationFlowContext context) { LoginFormsProvider form = context.form(); Map<String, String> params = generateParameters(context.getRealm(), context.getUriInfo().getBaseUri()); context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, params.get(WebAuthnConstants.CHALLENGE)); UserModel user = context.getUser(); boolean isUserIdentified = false; if (user != null) { // in 2 Factor Scenario where the user has already identified isUserIdentified = true; form.setAttribute("authenticators", new WebAuthnAuthenticatorsBean(user)); } else { // in ID-less & Password-less Scenario // NOP } params.put("isUserIdentified", Boolean.toString(isUserIdentified)); params.forEach(form::setAttribute); context.challenge(form.createForm("webauthn.ftl")); }
170883666_59
public GrokMatcher compile(final String expression) { Objects.requireNonNull(expression, "expression can't be null"); LOG.info("Starting to compile grok matcher expression : {}", expression); ArrayList<GrokPattern> patterns = new ArrayList<>(); final String regex = compileRegex(expression, patterns); LOG.info("Grok expression compiled to regex : {}", regex); return new GrokMatcher(patterns, regex); }
170887039_76
@Override public <K extends Key<T>> CompletableFuture<Void> deleteAll(final Set<K> keys) { Objects.requireNonNull(keys); final List<Delete> deletes = keysToDeletes(keys); return table.deleteAll(deletes); }
171042873_88
@ConditionalOnProperty(value = "scheduling.enabled", havingValue = "true") @Scheduled(cron = "0 * * * * *") @Retryable public void send() { List<Metric> metrics = metricService.collect(); metricService.send(metrics); }
171116174_14
@Override public boolean equals(Object o) { if (this == o) return true; if (!getClass().isInstance(o)) return false; return getId() != null && getId().equals(((JpaEntity) o).getId()); }
171132936_6
public static String deleteCRLFOnce(String input) { return input.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1").replaceAll("^((\r\n)|\n)", ""); }
171638792_0
@Override public void clearInvalidApi(String serviceId, Collection<String> codes) { if (StringUtils.isBlank(serviceId)) { return; } List<String> invalidApiIds = baseApiService.listObjs(new QueryWrapper<BaseApi>().select("api_id").eq("service_id", serviceId).notIn(codes!=null&&!codes.isEmpty(),"api_code", codes), e -> e.toString()); if (invalidApiIds != null) { // 防止删除默认api invalidApiIds.remove("1"); invalidApiIds.remove("2"); // 获取无效的权限 if (invalidApiIds.isEmpty()) { return; } List<String> invalidAuthorityIds = listObjs(new QueryWrapper<BaseAuthority>().select("authority_id").in("api_id", invalidApiIds), e -> e.toString()); if (invalidAuthorityIds != null && !invalidAuthorityIds.isEmpty()) { // 移除关联数据 baseAuthorityAppMapper.delete(new QueryWrapper<BaseAuthorityApp>().in("authority_id", invalidAuthorityIds)); baseAuthorityActionMapper.delete(new QueryWrapper<BaseAuthorityAction>().in("authority_id", invalidAuthorityIds)); baseAuthorityRoleMapper.delete(new QueryWrapper<BaseAuthorityRole>().in("authority_id", invalidAuthorityIds)); baseAuthorityUserMapper.delete(new QueryWrapper<BaseAuthorityUser>().in("authority_id", invalidAuthorityIds)); // 移除权限数据 this.removeByIds(invalidAuthorityIds); // 移除接口资源 baseApiService.removeByIds(invalidApiIds); } } }
171867537_7
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add("Access-Control-Allow-Origin", "*"); responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); responseContext.getHeaders().add("Access-Control-Max-Age", "-1"); responseContext.getHeaders().add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); }
172090523_83
@Override public <T extends Enum<T>> T getEnum(Class<T> enumClass) throws MatchbookSDKParsingException { if (isNotNullValue()) { try { String value = jsonParser.getValueAsString().toUpperCase().replace('-', '_'); try { return Enum.valueOf(enumClass, value); } catch (IllegalArgumentException iae) { return Enum.valueOf(enumClass, "UNKNOWN"); } } catch (IOException e) { throw new MatchbookSDKParsingException(e); } } return null; }
172472737_0
@Override public void close() { operations.close(); }
172494483_1
public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterAnnotation(CurrentUser.class) != null && methodParameter.getParameterType().equals(User.class); }
172513597_2
@Override public Integer build(IContext context, Class<Integer> booleanClass) { final String string = super.contactInt(context); return Integer.valueOf(string); }
172695826_2
@Override public boolean verifySignature(byte[] message, byte[] sigBytes) { try { EdDSAEngine sgr = new EdDSAEngine(MessageDigest.getInstance("SHA-512")); sgr.initVerify(new EdDSAPublicKey(new EdDSAPublicKeySpec(keySpec.getA(), ed25519))); sgr.update(message); return sgr.verify(sigBytes); } catch (Exception e) { throw new RuntimeException(e); } }
172743796_31
@Override public Map<String, Set<String>> get() { return supplier.get(); }
172750723_127
@Override public void record(long value, Labels labels) { BoundInstrument boundInstrument = bind(labels); boundInstrument.record(value); boundInstrument.unbind(); }
172835741_1
@Override public boolean testConnection() throws MangleException { log.debug("Validating test connection with Datadog using the specified tokens"); ResponseEntity<String> response = (ResponseEntity<String>) this .get(MetricProviderConstants.DATADOG_API_VALIDATE_API_APP_KEYS, String.class); if (StringUtils.isEmpty(response)) { throw new MangleException(ErrorCode.UNABLE_TO_CONNECT_TO_DATADOG_INSTANCE); } log.debug("Test connection completed and status: " + response.getStatusCode().value()); if (!(response.getStatusCode().value() == 200)) { throw new MangleException(ErrorCode.AUTH_FAILURE_TO_DATADOG); } return response.getStatusCode().value() == 200; }
172865576_60
@ApiImplicitParams({ @ApiImplicitParam(name = "Authorization", value = "用户登录凭证", paramType = "header", dataType = "string", defaultValue = "Bearer ", required = true), }) @PutMapping("/{id}") @OperationRecord(type = OperationRecordLog.OperationType.UPDATE, resource = OperationRecordLog.OperationResource.IOS_VERSION, description = OperationRecordLog.OperationDescription.UPDATE_IOS_VERSION) public ServiceResult update(@RequestBody IosVersionRequestDTO iosVersionRequestDTO, @PathVariable int id) { if (id < 1) { return ServiceResultConstants.NEED_PARAMS; } String appVersion = iosVersionRequestDTO.getAppVersion(); String allowLowestVersion = iosVersionRequestDTO.getAllowLowestVersion(); //校验版本区间 if (StringUtilsExt.hasNotBlank(allowLowestVersion, appVersion)) { if (basicService.compareVersion(appVersion, allowLowestVersion) < 0) { return ServiceResultConstants.ALLOWLOWESTVERSION_BIG_THAN_APPVERSION; } } IosVersion iosVersion = new IosVersion(); BeanUtils.copyProperties(iosVersionRequestDTO, iosVersion); iosVersion.setId(id); return iosVersionService.update(iosVersion); }
172981843_7
@Override public ProducerDestination provisionProducerDestination(String name, ExtendedProducerProperties<SqsProducerProperties> properties) throws ProvisioningException { CreateTopicResult createTopicResult = amazonSNSAsync.createTopic(name); return new SqsProducerDestination(name, createTopicResult.getTopicArn()); }
173075460_3
public void sendMessage(Message message) throws UserNotInGroupException { checkUserInGroup(message.getSender()); messages.add(message); for(User user: users) { user.receiveMessage(message); } }
173167316_16
public void setAvailableKeys(@NotNull List<String> availableKeys) { this.availableKeys = availableKeys; }
173228436_63
public void putInt(long index, int value) { PropertyPage page = getOrCreatePage(getPageID(index)); int n = page.getSize(); page.addInt(getPageOffset(index), value); numProperties += page.getSize() - n; }
173230987_13
public String calculateDownstreamPath(final String receivedRequestUri) { // This function is required to join httpDownStreamPathPrefix with receivedRequestURI // remove any duplicate "/" // Not have an ending "/" if the path // assumes httpdownstreamPathPrefix does not include =,?,& // has a leading "/" as required by vertx String result = "/" + httpDownstreamPathPrefix + "/" + receivedRequestUri; result = result.replaceAll("/+", "/"); return result.length() == 1 ? result : result.replaceAll("/$", ""); }
173306807_22
@Override public Pair<T, T> crossover(T parentA, T parentB) { Set<String> union = new HashSet<>(); for (ParameterizableString p : parentA.getParameterizableStrings()) { union.add(p.getFactoryId()); } for (ParameterizableString p : parentB.getParameterizableStrings()) { union.add(p.getFactoryId()); } //this crossover allows for more from one parent than another //we can change if we want exclusive passing of traits List<String> uniques = new ArrayList<>(union); Collections.shuffle(uniques); List<String> childA = new ArrayList<>(); int numA = MathUtil.RANDOM.nextInt(minSetSize, maxSetSize); int sz = numA >= uniques.size() ? uniques.size() : numA; for (int i = 0; i < sz; i++) { childA.add(uniques.get(i)); } Collections.shuffle(uniques); List<String> childB = new ArrayList<>(); int numB = MathUtil.RANDOM.nextInt(minSetSize, maxSetSize); sz = numB >= uniques.size() ? uniques.size() : numB; for (int i = 0; i < sz; i++) { childB.add(uniques.get(i)); } return Pair.of( (T)buildCrossOver(childA, parentA, parentB), (T)buildCrossOver(childB, parentA, parentB) ); }
173327149_0
public static void doImageReplace(String filePath, byte[] content) { Args.notNull(filePath, "原始文件路径不为空"); ReplaceImageClientHandler operHandler = new ReplaceImageClientHandler(); operHandler.doReplaceImage(filePath, content); }
173335706_175
@ApiOperation(value = "delete", notes = "DELETE_DATA_SOURCE_NOTES") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "DATA_SOURCE_ID", required = true, dataType = "Int", example = "100") }) @GetMapping(value = "/delete") @ResponseStatus(HttpStatus.OK) @ApiException(DELETE_DATA_SOURCE_FAILURE) public Result delete(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("id") int id) { logger.info("delete datasource,login user:{}, id:{}", loginUser.getUserName(), id); return dataSourceService.delete(loginUser, id); }
173409096_54
public void setClassLoader(ClassLoader classloader) { this.classloader = classloader; }
173534034_11
public static CodeRequest newCodeRequest(HarRequest harRequest) throws Exception { return new CodeRequest(harRequest); }
173572330_47
@Override public final void getSize(@NonNull SizeReadyCallback cb) { sizeDeterminer.getSize(cb); }
173721564_1
@SuppressWarnings("unchecked") public static <T extends Message> T newMessageByProtoClassName(final String className, final byte[] bs) { final MethodHandle handle = PARSE_METHODS_4PROTO.get(className); if (handle == null) { throw new MessageClassNotFoundException(className + " not found"); } try { return (T) handle.invoke(bs); } catch (Throwable t) { throw new SerializationException(t); } }
173756598_3
public synchronized Transaction makeTransaction(String fromAddress, String toAddress, long value) throws ServerException { Wallet from = walletRepository.findByAddress(fromAddress); Wallet to = walletRepository.findByAddress(toAddress); if (from == null || to == null) throw new ServerException("Wrong address"); if (from.getBalance() < value) throw new ServerException("Not enough money!"); long fromBalance = from.getBalance(); long toBalance = to.getBalance(); fromBalance -= value; toBalance += value; Transaction transaction = new Transaction(); transaction.setSource(from); transaction.setValue(value); from.setBalance(fromBalance); to.setBalance(toBalance); transactionRepository.save(transaction); walletRepository.saveAll(List.of(from,to)); eturn transaction; }
173833378_0
@Get("/{name}") public String index(final String name) { return "Hello, " + name + ". From " + embeddedServer.getHost() + ":" + embeddedServer.getPort() + "\n"; }
173952800_1
public ComputedValues evaluateForAll(VariableEnvironment environment, Expression expression) throws Exception { return evaluate(environment, VariableEnvironment.NO_VALUE_SET_SELECTED, expression, false); }
174011880_1
public List<ParsingElement> load(boolean reload) { if (isLoaded() && !reload) { return getParsingElements(); } Map<String, Object> map = configLoader.readConfiguration(); fillParameters(map); MapWrapper mainMap = new MapWrapper(map, null); extendToExternalConfig(mainMap); mainMap.getField(RESULT, true); fillParameters(map); fillFunctions(map); fillDefinitions(map); fillTransformation(map); fillRoot(map); isLoaded = true; return getParsingElements(); }
174065041_172
@Transactional(propagation = Propagation.REQUIRED) public void deleteMetadataEntitiesInProject(Long projectId, String entityClassName) { Objects.requireNonNull(projectId); if (StringUtils.hasText(entityClassName)) { MetadataClass metadataClass = loadClass(entityClassName); metadataEntityDao.deleteMetadataClassFromProject(projectId, metadataClass.getId()); } else { metadataEntityDao.deleteMetadataFromFolder(projectId); } }
174097909_25
public double getTotalUtilizationOfCpu(double time) { return getCloudletScheduler().getTotalUtilizationOfCpu(time); }
174098511_6
public boolean passwordMatchesHash(final String password, final String hash) { final byte[] decodedHash = base64Decoder.decode(hash); final int salt = ByteBuffer.wrap(decodedHash).getInt(); return convertPasswordToHash(password, salt).equals(hash); }
174104865_0
public static String getAddressInLocal(String ip) { if (StrUtil.equals(ip, IpUtil.LOCAL_INNER_LOOP_IP)) { ip = IpUtil.LOCAL_IP; } String address = ""; boolean ipAddress = Util.isIpAddress(ip); if (!ipAddress) { return address; } try { DbConfig config = new DbConfig(); DbSearcher searcher = new DbSearcher(config, ResourceUtil.getResource("ip/ip2region.db").getFile()); DataBlock dataBlock = searcher.memorySearch(ip); // dataBlock格式:城市Id|国家|区域|省份|城市|ISP // region格式:国家|区域|省份|城市|ISP // region例如:中国|0|浙江省|杭州市|电信 String region = dataBlock.getRegion(); // 按 | 切分 List<String> regionList = Splitter.on("|").splitToList(region); // 过滤为 0 的数据 List<String> regionListFilter = regionList.stream() .filter(s -> !StrUtil.equals("0", s)) .distinct() .collect(Collectors.toList()); // 再用 | 拼接回来 address = Joiner.on("|").join(regionListFilter); } catch (Exception e) { log.error("【获取地理位置】发生异常:", e); } return address; }
174185245_79
public ComplexNumber[] root(int n) { if (n <= 0) { throw new IllegalArgumentException("Cannot calculate negative roots."); } double magnitude = Math.pow(getMagnitude(), 1.0 / n); double angle = getAngle() / n; double angleStep = 2 * Math.PI / n; ComplexNumber[] roots = new ComplexNumber[n]; for (int index = 0; index < n; ++index) { roots[index] = fromMagnitudeAndAngle(magnitude, angle + index * angleStep); } return roots; }
174314296_1
public JsonNode jsonName(JsonNode nameNode) { Country country = countriesService.getByName(nameNode.get("name").asText()).iterator().next(); ObjectMapper mapper = new ObjectMapper(); JsonNode retNode = mapper.convertValue(country, JsonNode.class); return retNode; }
174353676_0
@POST public Response add(MagicData magic) { String id = UUID.randomUUID().toString(); LOGGER.info("Magic is going on ..." + magic); magicStore.putAsync(id, new HPMagic(id, magic.getCaster(), magic.getCurse(), magic.isInHogwarts())); return Response.ok().status(201).build(); }
174354196_1
@PutMapping(value = "/{id}", produces = "application/json") public Produto update(@PathVariable("id") long id, @RequestBody Produto produto) { return storage.update(id, produto); }
174373244_0
@GET @Fallback(fallbackMethod = "fallback") // better use FallbackHandler @Timeout(500) public List<Legume> list() { final List resultList = manager.createQuery("SELECT l FROM Legume l").getResultList(); return resultList; }
174398263_151
@Override public void cleanUp() { mUrlConnection = null; }
174633794_0
public synchronized static JavaDoc read(File sourceDir, List<String> compilePaths) { return read(Arrays.asList(sourceDir), compilePaths); }
174912621_0
@Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } // TODO: 2019/3/26 请解决数据量大的问题,加一个时间范围刷选,处理可以同上面todo逻辑一致 if (dashboardProperties.getApplication().isEnable()) { List<MetricEntity> list = metricEntityRepository.findByApp(app); List<String> resourceList = new ArrayList<>(); for (MetricEntity entity : list) { if (!resourceList.contains(entity.getResource())) { resourceList.add(entity.getResource()); } } return resourceList; } // resource -> timestamp -> metric Map<String, ConcurrentLinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); for (Entry<String, ConcurrentLinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } // Order by last minute b_qps DESC. return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); }
174912738_6
@Override public List<Item> collect(Object source) { if (source == null){ return Collections.emptyList(); } List<Item> result = Lists.newArrayList(); ReflectionUtils.doWithFields(source.getClass(), field -> { Class fieldCls = field.getType(); if (Changer.class.isAssignableFrom(fieldCls)){ field.setAccessible(true); Object value = field.get(source); if (value != null){ result.add(new Item(field.getName(), value)); } } }); return result; }
175050767_27
public static String extractEtherAddressFromUri(String uri) throws InvalidEthereumAddressException { String uriWithoutSchema = uri.replaceFirst("ethereum:", ""); uriWithoutSchema = Numeric.cleanHexPrefix(uriWithoutSchema); if (uriWithoutSchema.length() != 40) { throw new InvalidEthereumAddressException( "Invalid address. The Ethereum address does not match the 40 char length!"); } boolean hasChecksum = !uriWithoutSchema.equals(uriWithoutSchema.toLowerCase()) && !uriWithoutSchema.equals(uriWithoutSchema.toUpperCase()); uriWithoutSchema = Numeric.prependHexPrefix(uriWithoutSchema); if (hasChecksum) { if (!uriWithoutSchema.equals(Keys.toChecksumAddress(uriWithoutSchema))) { throw new InvalidEthereumAddressException("Wrong checksum. The Ethereum address is invalid!"); } } return uriWithoutSchema; }
175055878_2
@Override public Optional<BigDecimal> getAverageRating(final UUID gameId) { return this.resolveBoardGameGeekId(gameId) .map(bggId -> this.bggClient.getItemsWithRating(bggId)) .map(Items::getItems) .map(List::stream) .flatMap(Stream::findFirst) .map(ItemWithStatistics::getStatistics) .map(Statistics::getRatings) .map(Ratings::getAverage) .map(BigDecimalValue::getValue); }
175062989_0
static void loadElf(ElfHeader elf, Program program, List<Option> options, MessageLog log, MemoryConflictHandler handler, TaskMonitor monitor) throws IOException, CancelledException { ElfProgramBuilder elfProgramBuilder = new ElfProgramBuilder(elf, program, options, log, handler); elfProgramBuilder.load(monitor); }
175193018_1
public static boolean isAsciiAlpha(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); }
175482179_3
protected void setRect(@NonNull DirectionalRect rect, int start, int top, int end, int bottom) { rect.set(isRtl, parentWidth, start, top, end, bottom); }
175544925_723
@Deprecated public static SslContext newServerContext(File certChainFile, File keyFile) throws SSLException { return newServerContext(certChainFile, keyFile, null); }
175559661_26
@ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = "/user", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void createUser(@RequestBody WormholeUser user, HttpServletResponse response) { if (userRepository.findOneByUserName(user.getUserName()) != null) { String message = user.getUserName() + "is already exsit"; throw new WormholeRequestException(message); } user.setCreateTime(new Date()); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); user.setPassword(encoder.encode(user.getPassword().trim())); user.setLastPasswordResetDate(new Date().getTime()); BaseDocumentUtil.generateID(user); userRepository.save(user); }
175804011_5
public static <T,U,R> Stream<R> merge(Stream<T> seq1, Stream<U> seq2, BiPredicate<T,U> pred, BiFunction<T,U,R> transf, U defaultVal) { // TODO return null; }
175889566_2
public Map<String, Object> getValues() { return values; }
175914805_0
public static void transToTsfile(String dirPath, String tsPath) { try { File f = new File(tsPath); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } try (TsFileWriter tsFileWriter = new TsFileWriter(f)) { File[] csvFiles = new File(dirPath).listFiles(); for (File csvFile : csvFiles) { try (BufferedReader csvReader = new BufferedReader(new FileReader(csvFile))) { String header = csvReader.readLine(); String[] sensorFull = Arrays .copyOfRange(header.split(","), 1, header.split(",").length); ArrayList<String> sensorList = new ArrayList<>(Arrays.asList(sensorFull)); String device = sensorList.get(0).substring(0, sensorList.get(0).lastIndexOf('.')); for (int i = 0; i < sensorList.size(); i++) { sensorList.set(i, sensorList.get(i).replace(device, "").substring(1)); } List<TSDataType> tsDataTypes = Arrays.asList(new TSDataType[sensorList.size()]); String intRegex = "[0-9]+"; String floatRegex = "[0-9]+.[0-9]+"; String line; while ((line = csvReader.readLine()) != null) { // construct TSRecord long time = Long.parseLong(line.split(",")[0]); TSRecord tsRecord = new TSRecord(time, device); String[] points = Arrays.copyOfRange(line.split(","), 1, line.split(",").length); for (int i = 0; i < points.length; i++) { if (points[i].matches(intRegex)) { if (tsDataTypes.get(i) == null) { tsDataTypes.set(i, TSDataType.INT64); try { tsFileWriter.addMeasurement(new MeasurementSchema(sensorList.get(i), TSDataType.INT64, TSEncoding.TS_2DIFF)); } catch (Exception e) { // } DataPoint intPoint = new LongDataPoint(sensorList.get(i), Long.parseLong(points[i])); tsRecord.addTuple(intPoint); } else { DataPoint intPoint = new LongDataPoint(sensorList.get(i), Long.parseLong(points[i])); tsRecord.addTuple(intPoint); } } else if (points[i].matches(floatRegex)) { if (tsDataTypes.get(i) == null) { tsDataTypes.set(i, TSDataType.FLOAT); try { tsFileWriter.addMeasurement(new MeasurementSchema(sensorList.get(i), TSDataType.FLOAT, TSEncoding.GORILLA)); } catch (Exception e) { // } DataPoint floatPoint = new FloatDataPoint(sensorList.get(i), Float.parseFloat(points[i])); tsRecord.addTuple(floatPoint); } else { DataPoint floatPoint = new FloatDataPoint(sensorList.get(i), Float.parseFloat(points[i])); tsRecord.addTuple(floatPoint); } } else { if (!points[i].equals("")) { if (tsDataTypes.get(i) == null) { tsDataTypes.set(i, TSDataType.TEXT); try { tsFileWriter.addMeasurement(new MeasurementSchema(sensorList.get(i), TSDataType.TEXT, TSEncoding.PLAIN)); } catch (Exception e) { // } DataPoint textPoint = new StringDataPoint(sensorList.get(i), Binary.valueOf(points[i])); tsRecord.addTuple(textPoint); } else { DataPoint textPoint = new StringDataPoint(sensorList.get(i), Binary.valueOf(points[i])); tsRecord.addTuple(textPoint); } } } } tsFileWriter.write(tsRecord); } } } } } catch (Exception e) { e.printStackTrace(); } }
175961394_11
public Optional<Object[]> resolve(final Method testMethod, final Example.Builder example) { // TODO fchovich MOVE LOGIC FROM THE RESOLVER. CREATE CONVERTIBLES BEFORE. return this.parameterConverterResolver .resolveConverters(testMethod, example) .flatMap(c -> this.resolveParameters(testMethod, example, c)); }
176135637_75
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() != ChatMessageType.SERVER && event.getType() != ChatMessageType.FILTERED) { return; } String chatMsg = Text.removeTags(event.getMessage()); //remove color and linebreaks if (chatMsg.startsWith(CHAT_BRACELET_SLAUGHTER)) { Matcher mSlaughter = CHAT_BRACELET_SLAUGHTER_REGEX.matcher(chatMsg); amount++; slaughterChargeCount = mSlaughter.find() ? Integer.parseInt(mSlaughter.group(1)) : SLAUGHTER_CHARGE; config.slaughter(slaughterChargeCount); } if (chatMsg.startsWith(CHAT_BRACELET_EXPEDITIOUS)) { Matcher mExpeditious = CHAT_BRACELET_EXPEDITIOUS_REGEX.matcher(chatMsg); amount--; expeditiousChargeCount = mExpeditious.find() ? Integer.parseInt(mExpeditious.group(1)) : EXPEDITIOUS_CHARGE; config.expeditious(expeditiousChargeCount); } if (chatMsg.startsWith(CHAT_BRACELET_EXPEDITIOUS_CHARGE)) { Matcher mExpeditious = CHAT_BRACELET_EXPEDITIOUS_CHARGE_REGEX.matcher(chatMsg); if (!mExpeditious.find()) { return; } expeditiousChargeCount = Integer.parseInt(mExpeditious.group(1)); config.expeditious(expeditiousChargeCount); } if (chatMsg.startsWith(CHAT_BRACELET_SLAUGHTER_CHARGE)) { Matcher mSlaughter = CHAT_BRACELET_SLAUGHTER_CHARGE_REGEX.matcher(chatMsg); if (!mSlaughter.find()) { return; } slaughterChargeCount = Integer.parseInt(mSlaughter.group(1)); config.slaughter(slaughterChargeCount); } if (chatMsg.endsWith("; return to a Slayer master.")) { Matcher mComplete = CHAT_COMPLETE_MESSAGE.matcher(chatMsg); List<String> matches = new ArrayList<>(); while (mComplete.find()) { matches.add(mComplete.group(0).replaceAll(",", "")); } switch (matches.size()) { case 0: streak = 1; break; case 1: streak = Integer.parseInt(matches.get(0)); break; case 3: streak = Integer.parseInt(matches.get(0)); points = Integer.parseInt(matches.get(2)); break; default: log.warn("Unreachable default case for message ending in '; return to Slayer master'"); } setTask("", 0, 0); return; } if (chatMsg.equals(CHAT_GEM_COMPLETE_MESSAGE) || chatMsg.equals(CHAT_CANCEL_MESSAGE) || chatMsg.equals(CHAT_CANCEL_MESSAGE_JAD)) { setTask("", 0, 0); return; } if (config.showSuperiorNotification() && chatMsg.equals(CHAT_SUPERIOR_MESSAGE)) { notifier.notify(CHAT_SUPERIOR_MESSAGE); return; } Matcher mProgress = CHAT_GEM_PROGRESS_MESSAGE.matcher(chatMsg); if (mProgress.find()) { String name = mProgress.group("name"); int gemAmount = Integer.parseInt(mProgress.group("amount")); String location = mProgress.group("location"); setTask(name, gemAmount, initialAmount, location); return; } final Matcher bracerProgress = COMBAT_BRACELET_TASK_UPDATE_MESSAGE.matcher(chatMsg); if (bracerProgress.find()) { final int taskAmount = Integer.parseInt(bracerProgress.group(1)); setTask(taskName, taskAmount, initialAmount); // Avoid race condition (combat brace message goes through first before XP drop) amount++; } }
176206805_10
public void checkAccess(ThreadGroup g) { if (g == null) { throw new NullPointerException("thread group can't be null"); } checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION); }
176291010_75
@ReactProp(name = PROP_ACCESSIBILITY_ROLE) public void setAccessibilityRole(@Nonnull T view, @Nullable String accessibilityRole) { if (accessibilityRole == null) { return; } view.setTag(R.id.accessibility_role, AccessibilityRole.fromValue(accessibilityRole)); }
176724609_0
@Override public DataxConfig getJobInfo(Integer id) { HashMap<String,Object> params = new HashMap<>(); params.put("id",id); List<Map<String, Object>> jobInfos = dataxDao.getJobInfo(params); if(ObjectUtils.isEmpty(jobInfos)){ return null; } Map<String, Object> map = jobInfos.get(0); return TypeUtils.castToJavaBean(map, DataxConfig.class); }
176770877_0
public void parse() throws Exception { // TODO: Verify compatible OpenAPI version. logger.info("Parsing definitions."); this.generateAlgodIndexerObjects(root); // Generate classes from the return types which have more than one return element logger.info("Parsing responses."); this.generateReturnTypes(root); // Generate the algod methods logger.info("Parsing paths."); this.generateQueryMethods(); publisher.terminate(); }
177104472_11
@Override public Publisher register(PublisherRegistration registration, String... data) { if (!init.get()) { throw new IllegalStateException("Client needs to be initialized before using."); } if (null == registration) { throw new IllegalArgumentException("Registration can not be null."); } if (StringUtils.isBlank(registration.getDataId())) { throw new IllegalArgumentException("DataId can not be null"); } if (StringUtils.isBlank(registration.getGroup())) { registration.setGroup(DEFAULT_GROUP); } Publisher publisher = registrationPublisherMap.get(registration); if (null != publisher) { throwDuplicateException(registration, publisher); } publisher = new DefaultPublisher(registration, workerThread, registryClientConfig); ((DefaultPublisher) publisher).setAuthManager(authManager); Publisher oldPublisher = registrationPublisherMap.putIfAbsent(registration, publisher); if (null != oldPublisher) { throwDuplicateException(registration, oldPublisher); } registerCache.addRegister(publisher); publisher.republish(data); LOGGER.info("[api] Regist publisher success, dataId: {}, group: {}, registerId: {}", publisher.getDataId(), publisher.getGroup(), publisher.getRegistId()); return publisher; }
177177812_0
public static String getStringDate(Date date) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); int month = getMonth(date); StringBuilder stringBuilder = new StringBuilder(); calendar.setTime(date); stringBuilder.append(calendar.get(Calendar.DAY_OF_MONTH)); stringBuilder.append("-"); stringBuilder.append(month); //here add 1 to display ( Jan is 0 ) stringBuilder.append("-"); stringBuilder.append(calendar.get(Calendar.YEAR)); return stringBuilder.toString(); }
177503596_3
@Override public List<User> findTenantAdmins(UUID tenantId, TextPageLink pageLink) { return DaoUtil.convertDataList( userRepository .findUsersByAuthority( fromTimeUUID(tenantId), NULL_UUID_STR, pageLink.getIdOffset() == null ? NULL_UUID_STR : fromTimeUUID(pageLink.getIdOffset()), Objects.toString(pageLink.getTextSearch(), ""), Authority.TENANT_ADMIN, new PageRequest(0, pageLink.getLimit()))); }
177547877_1
public boolean isStatusResponse(String json) throws CouldNotReadJsonException { if (StringUtils.isBlank(json)) { return false; } String id = getRawId(json); return StringUtils.startsWithIgnoreCase(id, TmRpcMethod.STATUS.getMethodString()); }
177672258_0
public static <T, E> T getKeyByValue(Map<T, E> map, E value) { for (Map.Entry<T, E> entry : map.entrySet()) { if (Objects.equals(value, entry.getValue())) { return entry.getKey(); } } return null; }
177745239_136
@Override public void apply(AsgQuery query, AsgStrategyContext context) { // phase 1 - group all Eprops to EPropGroups AsgQueryUtil.elements(query, Quant1.class).forEach(quant -> { List<AsgEBase<EProp>> ePropsAsgChildren = AsgQueryUtil.nextAdjacentDescendants(quant, EProp.class); List<EProp> eProps = Stream.ofAll(ePropsAsgChildren).map(AsgEBase::geteBase).toJavaList(); if (!eProps.isEmpty()) { EPropGroup ePropGroup = new EPropGroup( Stream.ofAll(eProps).map(EProp::geteNum).min().get(), quant.geteBase().getqType(), eProps); ePropsAsgChildren.forEach(quant::removeNextChild); quant.addNextChild(new AsgEBase<>(ePropGroup)); } else { List<AsgEBase<EPropGroup>> ePropsGroupAsgChildren = AsgQueryUtil.nextAdjacentDescendants(quant, EPropGroup.class); Optional<AsgEBase<EBase>> ancestor = AsgQueryUtil.ancestor(quant, asgEBase -> asgEBase.geteBase() instanceof ETyped, asgEBase -> !(asgEBase.geteBase() instanceof Rel)); if (ePropsGroupAsgChildren.isEmpty() && ancestor.isPresent() && quant.geteBase().getqType().equals(QuantType.all)) { EPropGroup ePropGroup = new EPropGroup(Stream.ofAll(AsgQueryUtil.eNums(query)).max().get() + 1); AsgEBase<? extends EBase> ePropGroupAsgEbase = new AsgEBase<>(ePropGroup); quant.addNextChild(ePropGroupAsgEbase); } } } ); // phase 2 - group all EpropGroups to other EpropGroups AsgQueryUtil.elements(query, Quant1.class).forEach(this::groupEpropGroups); }
177751597_24
@Override public void put(byte[] key, TransactionRetCapsule item) { if (BooleanUtils.toBoolean(Args.getInstance().getStorage().getTransactionHistoreSwitch())) { super.put(key, item); } }
178002723_4
public List<FileContent> descriptorToString(FileDescriptorSet descriptorSet) { List<FileContent> result = new LinkedList<>(); for (FileDescriptorProto protoFileDesc : descriptorSet.getFileList()) { StringBuilder buffer = new StringBuilder(); buffer.append("syntax = \"").append(protoFileDesc.getSyntax()).append("\";\n"); for (Entry<FieldDescriptor, Object> opt : protoFileDesc.getOptions().getAllFields().entrySet()) { buffer.append("option ").append(opt.getKey().getName()).append(" = ").append(opt.getValue()).append(";\n"); } buffer.append("package ").append(protoFileDesc.getPackage()).append(";\n"); buffer.append("\n"); for (DescriptorProto msgType : protoFileDesc.getMessageTypeList()) { buffer.append("message ").append(msgType.getName()).append(" {\n"); for (FieldDescriptorProto field : msgType.getFieldList()) { String type = getType(field.getType()); buffer.append(" ") .append(toLabel(field.getLabel())) .append(type) .append(" ") .append(field.getName()) .append(" = ") .append(field.getNumber()) .append(";\n"); } buffer.append("}\n\n"); } boolean firstService = true; for (ServiceDescriptorProto serviceDesc : protoFileDesc.getServiceList()) { if (!firstService) { buffer.append("\n"); } firstService = false; buffer.append("service ").append(serviceDesc.getName()).append(" {\n"); for (MethodDescriptorProto method : serviceDesc.getMethodList()) { buffer.append(" rpc ") .append(method.getName()) .append("("); if (method.getClientStreaming()) buffer.append("stream "); buffer.append(method.getInputType()) .append(") returns ("); if (method.getServerStreaming()) buffer.append("stream "); buffer .append(method.getOutputType()) .append(");\n"); } buffer.append("}\n"); } result.add(new FileContent(protoFileDesc.getName(), buffer.toString())); } return result; }
178064729_22
@Override public boolean test(String httpText) { return this.patterns.stream() .anyMatch(p -> p.matcher(httpText).matches()); }
178169608_2
public static Optional<SnykTestStatus> unmarshall(Path path) throws IOException { if (path == null) { return Optional.empty(); } try (JsonParser parser = JSON_FACTORY.createParser(path.toFile())) { JsonToken token = parser.nextToken(); if (token == JsonToken.START_ARRAY) { List<SnykTestStatus> testStatuses = new ArrayList<>(); while (parser.nextToken() != JsonToken.END_ARRAY) { testStatuses.add(readTestResult(parser)); } return Optional.of(aggregateTestResults(testStatuses)); } else if (token == JsonToken.START_OBJECT) { return Optional.of(readTestResult(parser)); } else { return Optional.empty(); } } }
178173999_39
public synchronized void addListener(NeuralNetworkEventListener listener) { if (listener == null) throw new IllegalArgumentException("listener is null!"); listeners.add(listener); }
178313880_0
public DataTable sqlQuery(String sql) { try { executeBeforeSqlQuery(sql); if (sql2ExecutionPlanCache != null) { TableExecutionPlan executionPlan = sql2ExecutionPlanCache .getIfPresent( cacheKeyPrefix + sql); if (executionPlan != null) { return implement(executionPlan.getBindable(), executionPlan.getRowType(), calciteCatalogReader.getTypeFactory()); } } TableExecutionPlan executionPlan = toExecutionPlan(sql); DataTable dt = implement(executionPlan.getBindable(), executionPlan.rowType, calciteCatalogReader.getTypeFactory()); if (sql2ExecutionPlanCache != null) { sql2ExecutionPlanCache.put(cacheKeyPrefix + sql, executionPlan); } executeAfterSqlQuery(sql); return dt; } catch (Throwable t) { throw new RuntimeException( "current rootSchema:" + rootSchema.getTableNames(), t); } }
178461625_308
@Override public void join() throws CompletionException, InterruptedException { try { join(10, TimeUnit.SECONDS); } catch (TimeoutException ex) { throw new RuntimeException("Default timeout triggered for blocking call to AsyncCompletion::join()", ex); } }
178503192_2
public void delete(Integer index) { this.checkIndexOutOfBound(index); Node<T> wantDeleteLastNode = head; for (int i = 0; i < index; i++) { wantDeleteLastNode = wantDeleteLastNode.next; } wantDeleteLastNode.next = wantDeleteLastNode.next.next; this.length -= 1; }
178518612_3
public static String generate(String ftl, Object dataModel){ try { Template template = getTemplate(ftl); return buildResult(template, dataModel); } catch (IOException e) { logger.error("Error: {}\n{}", e.getMessage(), e.getStackTrace()); } catch (TemplateException e) { logger.error("Error: {}\n{}", e.getMessage(), e.getStackTrace()); } return null; }
178760528_3
public Topology buildTopology(Properties envProps) { final StreamsBuilder builder = new StreamsBuilder(); final String inputTopic = envProps.getProperty("input.topic.name"); final String outputTopic = envProps.getProperty("output.topic.name"); final String joinTopic = envProps.getProperty("join.topic.name"); final Serde<Long> longSerde = Serdes.Long(); final Serde<String> stringSerde = Serdes.String(); final boolean addFilter = Boolean.parseBoolean(envProps.getProperty("add.filter")); final boolean addNames = Boolean.parseBoolean(envProps.getProperty("add.names")); KStream<Long, String> inputStream = builder.stream(inputTopic, Consumed.with(longSerde, stringSerde)) .selectKey((k, v) -> Long.parseLong(v.substring(0, 1))); if (addFilter) { inputStream = inputStream.filter((k, v) -> k != 100L); } final KStream<Long, String> joinedStream; final KStream<Long, Long> countStream; if (!addNames) { countStream = inputStream.groupByKey(Grouped.with(longSerde, stringSerde)) .count() .toStream(); joinedStream = inputStream.join(countStream, (v1, v2) -> v1 + v2.toString(), JoinWindows.of(Duration.ofMillis(100)), StreamJoined.with(longSerde, stringSerde, longSerde)); } else { countStream = inputStream.groupByKey(Grouped.with("count", longSerde, stringSerde)) .count(Materialized.as("the-counting-store")) .toStream(); joinedStream = inputStream.join(countStream, (v1, v2) -> v1 + v2.toString(), JoinWindows.of(Duration.ofMillis(100)), StreamJoined.with(longSerde, stringSerde, longSerde) .withName("join").withStoreName("the-join-store")); } joinedStream.to(joinTopic, Produced.with(longSerde, stringSerde)); countStream.map((k,v) -> KeyValue.pair(k.toString(), v.toString())).to(outputTopic, Produced.with(stringSerde, stringSerde)); return builder.build(); }
178830383_11
@Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { if (body instanceof Consents) { Consents consents = (Consents) body; MDC.put("iban", getIbans(consents).toString()); MDC.put("consentModel", getModel(consents)); } else { logger.warn("Unexpected body type {} for create consent", body.getClass()); } return body; }
178845642_0
@Override @Cacheable(key = "#name", cacheNames = "my-redis-cache2") public String getName(String name) { System.out.println(name); return name; }
178922614_6
public static List<TestData> parse(Path testFile) throws IOException { Reader reader = Files.newBufferedReader(testFile); try { return parse(testFile.getFileName().toString(), reader); } catch (RuntimeException e) { throw new RuntimeException("Failed parsing '" + testFile + "'", e); } }
179002056_18
@Override public void run() { try { switch (method) { case "get": runGet(); break; case "delete": runDelete(); break; case "put": runPut(); break; case "scan": runScan(); break; } } catch (IllegalArgumentException e) { terminal.println(e.getMessage()); } }
179494421_7
public static Optional<Array> createArray(Type type) { return createArray(null, type, false); }
179502880_327
boolean areEqualDownToSeconds(Date date1, Date date2) { final boolean bothNull = (date1 == null && date2 == null); final boolean bothNotNull = (date1 != null && date2 != null); return bothNull || (bothNotNull && (date1.getTime() / 1000) == (date2.getTime() / 1000)); }
179541399_2
public TDPath parse(String str) { TDPath path = new TDPath(); if (StringUtil.isEmpty(str)) return path; if (str.endsWith("#")) // Ignore the last # which indicate "key" of the map str = str.substring(0, str.length() - 1); if (str.indexOf('#') < 0) { if (parseParts(str, path, true)) return path; path.setDocPath(str); path.addParts(Part.ofRoot()); } else { String[] strs = str.split("#"); if (!strs[0].isEmpty()) path.setDocPath(strs[0]); parseParts(strs[1], path,false); } return path; }
179849363_8
@Override public void fill(InputFile file, SensorContext context, AntlrContext antlrContext) { try { if (!(file instanceof DefaultInputFile)) { return; } NewCpdTokens newCpdTokens = context.newCpdTokens().onFile(file); List<? extends Token> tokens = antlrContext.getAllTokens(); DefaultInputFile defaultInputFile = (DefaultInputFile) file; for (Token token : tokens) { try { final String text = token.getText(); if (token.getType() == -1 || token.getStartIndex() >= token.getStopIndex() || StringUtils.isEmpty(text)) { continue; } final TextRange range = defaultInputFile.newRange(token.getStartIndex(), token.getStopIndex() + 1); defaultInputFile.validate(range); newCpdTokens.addToken(range, text); } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Cannot add range: {} on file {} for token {}", e, file, token); } } } synchronized (context) { newCpdTokens.save(); } } catch (Throwable e) { LOGGER.warn("Error adding cpd tokens on " + file, e); } }
179925476_3
@NotNull @Override public Single<M> getLatest(P params) { return networkDataSource.getAndUpdate(params, cacheDataSource) .map(TimeStampedData::getModel) .toSingle(); }
179952747_0
static String capitalize(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); }
180317496_6
@DELETE @RolesAllowed("admin") public Response delete(@QueryParam("id") Long customerId) { customerRepository.deleteCustomer(customerId); return Response.status(204).build(); }
180526285_34
@Override public Mono<Endpoints> detectEndpoints(Instance instance) { Registration registration = instance.getRegistration(); String managementUrl = registration.getManagementUrl(); if (managementUrl == null || Objects.equals(registration.getServiceUrl(), managementUrl)) { return Mono.empty(); } return instanceWebClient.instance(instance) .get() .uri(managementUrl) .exchange() .flatMap(response -> { if (response.statusCode().is2xxSuccessful() && response.headers() .contentType() .map(actuatorMediaType::isCompatibleWith) .orElse(false)) { return response.bodyToMono(Response.class); } else { return response.bodyToMono(Void.class).then(Mono.empty()); } }) .flatMap(this::convert); }
180537027_5
public T eraseAllFormCustomExtensions(final T resource) { List<Extension> extensions = resource.getExtensions().values().stream().map(extension -> { if (extension instanceof EnterpriseExtension) { https://github.com/SAP/scimono/issues/77 EnterpriseExtension enterpriseExtension = (EnterpriseExtension) extension; Manager manager = enterpriseExtension.getManager(); if (manager != null) { Manager managerWithoutDisplayName = new Manager.Builder().setDisplayName(null).build(); return new EnterpriseExtension.Builder(enterpriseExtension).setManager(managerWithoutDisplayName).build(); } return extension; } Map<String, Object> attributes = extension.getAttributes(); Schema customSchema = schemaAPI.getSchema(extension.getUrn()); if (customSchema == null) { throw new SCIMException(SCIMException.Type.INVALID_SYNTAX, String.format("Schema '%s' does not exist.", extension.getUrn()), Response.Status.BAD_REQUEST); } removeReadOnlyAttributes(customSchema.toAttribute(), attributes); return new Extension.Builder(extension).setAttributes(attributes).build(); }).collect(Collectors.toList()); return resource.builder().removeExtensions().addExtensions(extensions).build(); }
180588003_85
@Override public ConsentWorkflow identifyConsent(String encryptedConsentId, String authorizationId, boolean strict, String consentCookieString, BearerTokenTO bearerToken) { // Parse and verify the consent cookie. ConsentReference consentReference = referencePolicy.fromRequest(encryptedConsentId, authorizationId, consentCookieString, strict); CmsAisConsentResponse cmsConsentResponse = loadConsentByRedirectId(consentReference); ConsentWorkflow workflow = new ConsentWorkflow(cmsConsentResponse, consentReference); AisConsentTO aisConsentTO = consentMapper.toTo(cmsConsentResponse.getAccountConsent()); workflow.setAuthResponse(new ConsentAuthorizeResponse(aisConsentTO)); workflow.getAuthResponse().setAuthorisationId(cmsConsentResponse.getAuthorisationId()); workflow.getAuthResponse().setEncryptedConsentId(encryptedConsentId); if (bearerToken != null) { SCAConsentResponseTO scaConsentResponseTO = new SCAConsentResponseTO(); scaConsentResponseTO.setBearerToken(bearerToken); workflow.setScaResponse(scaConsentResponseTO); } return workflow; }
180757477_5
static Optional<Type> backgroundFunctionTypeArgument( Class<? extends BackgroundFunction<?>> functionClass) { // If this is BackgroundFunction<Foo> then the user must have implemented a method // accept(Foo, Context), so we look for that method and return the type of its first argument. // We must be careful because the compiler will also have added a synthetic method // accept(Object, Context). return Arrays.stream(functionClass.getMethods()) .filter(m -> m.getName().equals("accept") && m.getParameterCount() == 2 && m.getParameterTypes()[1] == Context.class && m.getParameterTypes()[0] != Object.class) .map(m -> m.getGenericParameterTypes()[0]) .findFirst(); }
180773046_12
@Override public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { try { String text = p.readValueAs(String.class); return text == null ? null : converter.convert(text); } catch (Exception e) { throw new JsonParseException(p, "Could not parse node as instant", e); } }
180834808_1
public InjectorService getInjectorService() { Map<String, InjectorService> beansOfType = context.getBeansOfType(InjectorService.class); if (beansOfType.entrySet().isEmpty()) { throw new NoSuchBeanDefinitionException("No InjectorType found"); } return beansOfType.entrySet().iterator().next().getValue(); }
180961537_0
@Bean public Supplier<Loan> supplyLoan(){ Supplier<Loan> loanSupplier = () -> { Loan loan = new Loan(UUID.randomUUID().toString(), names.get(new Random().nextInt(names.size())), amounts.get(new Random().nextInt(amounts.size()))); log.info("{} {} for ${} for {}", loan.getStatus(), loan.getUuid(), loan.getAmount(), loan.getName()); return loan; }; return loanSupplier; }
181194375_2
public PluggableLoggerFactory addLogger(LoggerChannel logger, Level level) { mSortedLoggers.add(new SortedLogger(logger, level.toInt())); Collections.sort(mSortedLoggers, mSortedLoggersComparator); return this; }
181286172_8
static int convertRomanToArabicNumber(String roman) { roman = roman.toUpperCase(); int sum = 0; int current = 0; int previous = 0; for (int index = roman.length() - 1; index >= 0; index--) { if (doesSymbolsContainsRomanCharacter(roman, index)) { current = getSymbolValue(roman, index); if (current < previous) { sum -= current; } else { sum += current; } previous = current; } else { throw new IllegalArgumentException( String.format("Invalid roman character %s ", getCharValue(roman, index))); } } return sum; }