id
stringlengths
7
14
text
stringlengths
1
37.2k
216204232_22
public Spitter findOne(long id) { eturn jdbcTemplate.queryForObject( SELECT_SPITTER + " where id=?", new SpitterRowMapper(), id); }
216231037_5
@PostMapping("/hero/new") public String addNewHero(@ModelAttribute("newHero") NewHeroModel newHeroModel) { Hero hero = newHeroModel.getHero(); String repositoryName = newHeroModel.getRepository(); heroService.addHeroToRepository(hero, repositoryName); return "redirect:/hero"; }
216526613_4
@Override public void rotate() { locker.executeWithLock(this::doRotate); }
216840838_64
@Nullable public Stigma extractStigma(@Nonnull final RawStigmaToken stigmaToken) { Assert.notNull(stigmaToken, "stigmaToken must not be null"); final JWT jwt; try { jwt = JWTParser.parse(stigmaToken.getValue()); } catch (ParseException e) { if (logger.isDebugEnabled()) { logger.debug("Parsing stigma token to JWT failed.", e); } return null; } final DecryptedToken decryptedToken = tokenDecrypter.decrypt(jwt); if (!decryptedToken.isValid()) { if (logger.isDebugEnabled()) { logger.debug("Failed to decrypt token: " + decryptedToken); } return null; } final ParsedToken parsedToken = tokenParser.parse(decryptedToken); if (!parsedToken.isValid()) { if (logger.isDebugEnabled()) { logger.debug("Failed to parse token: " + parsedToken); } return null; } if (logger.isTraceEnabled()) { logger.trace("Extracting stigma from token: " + parsedToken); } return parsedToken.getStigma(); }
216898288_0
public static DataStream<HeapAlert> computeHeapAlerts(DataStream<HeapMetrics> statsInput, ParameterTool params) { return statsInput.flatMap(new AlertingFunction(params)).name("Create Alerts"); }
217054700_44
public static byte[] merge(byte[] ... byteArrays){ ByteArrayOutputStream outputStream = new ByteArrayOutputStream( ); try { for(byte[] a: byteArrays ){ outputStream.write( a ); } } catch (IOException e){ log.debug("Failed to merge"); } return outputStream.toByteArray( ); }
217157573_2
@Override public boolean removeListener(BlobStoreListener listener) { Boolean result = listeners.remove(listener); cache.get().values().forEach(entry->{entry.store.removeListener(listener);}); StoreAndConfig defaultEntry = defaultCache.get(); if(Objects.nonNull(defaultEntry)) { defaultEntry.store.removeListener(listener); } return result; }
217172162_0
@Override public List<User> getUsers() { return userRepository.findAll(); }
217275258_265
public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception { int index = 0; long headersLength = 0; int nameLength = 0; int valueLength = 0; byte state = READ_HEADER_REPRESENTATION; boolean huffmanEncoded = false; CharSequence name = null; HeaderType headerType = null; IndexType indexType = IndexType.NONE; while (in.isReadable()) { switch (state) { case READ_HEADER_REPRESENTATION: byte b = in.readByte(); if (maxDynamicTableSizeChangeRequired && (b & 0xE0) != 0x20) { // HpackEncoder MUST signal maximum dynamic table size change throw MAX_DYNAMIC_TABLE_SIZE_CHANGE_REQUIRED; } if (b < 0) { // Indexed Header Field index = b & 0x7F; switch (index) { case 0: throw DECODE_ILLEGAL_INDEX_VALUE; case 0x7F: state = READ_INDEXED_HEADER; break; default: HpackHeaderField indexedHeader = getIndexedHeader(index); headerType = validate(indexedHeader.name, headerType, validateHeaders); headersLength = addHeader(headers, indexedHeader.name, indexedHeader.value, headersLength); } } else if ((b & 0x40) == 0x40) { // Literal Header Field with Incremental Indexing indexType = IndexType.INCREMENTAL; index = b & 0x3F; switch (index) { case 0: state = READ_LITERAL_HEADER_NAME_LENGTH_PREFIX; break; case 0x3F: state = READ_INDEXED_HEADER_NAME; break; default: // Index was stored as the prefix name = readName(index); headerType = validate(name, headerType, validateHeaders); nameLength = name.length(); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; } } else if ((b & 0x20) == 0x20) { // Dynamic Table Size Update index = b & 0x1F; if (index == 0x1F) { state = READ_MAX_DYNAMIC_TABLE_SIZE; } else { setDynamicTableSize(index); state = READ_HEADER_REPRESENTATION; } } else { // Literal Header Field without Indexing / never Indexed indexType = ((b & 0x10) == 0x10) ? IndexType.NEVER : IndexType.NONE; index = b & 0x0F; switch (index) { case 0: state = READ_LITERAL_HEADER_NAME_LENGTH_PREFIX; break; case 0x0F: state = READ_INDEXED_HEADER_NAME; break; default: // Index was stored as the prefix name = readName(index); headerType = validate(name, headerType, validateHeaders); nameLength = name.length(); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; } } break; case READ_MAX_DYNAMIC_TABLE_SIZE: setDynamicTableSize(decodeULE128(in, (long) index)); state = READ_HEADER_REPRESENTATION; break; case READ_INDEXED_HEADER: HpackHeaderField indexedHeader = getIndexedHeader(decodeULE128(in, index)); headerType = validate(indexedHeader.name, headerType, validateHeaders); headersLength = addHeader(headers, indexedHeader.name, indexedHeader.value, headersLength); state = READ_HEADER_REPRESENTATION; break; case READ_INDEXED_HEADER_NAME: // Header Name matches an entry in the Header Table name = readName(decodeULE128(in, index)); headerType = validate(name, headerType, validateHeaders); nameLength = name.length(); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; break; case READ_LITERAL_HEADER_NAME_LENGTH_PREFIX: b = in.readByte(); huffmanEncoded = (b & 0x80) == 0x80; index = b & 0x7F; if (index == 0x7f) { state = READ_LITERAL_HEADER_NAME_LENGTH; } else { if (index > maxHeaderListSizeGoAway - headersLength) { headerListSizeExceeded(maxHeaderListSizeGoAway); } nameLength = index; state = READ_LITERAL_HEADER_NAME; } break; case READ_LITERAL_HEADER_NAME_LENGTH: // Header Name is a Literal String nameLength = decodeULE128(in, index); if (nameLength > maxHeaderListSizeGoAway - headersLength) { headerListSizeExceeded(maxHeaderListSizeGoAway); } state = READ_LITERAL_HEADER_NAME; break; case READ_LITERAL_HEADER_NAME: // Wait until entire name is readable if (in.readableBytes() < nameLength) { throw notEnoughDataException(in); } name = readStringLiteral(in, nameLength, huffmanEncoded); headerType = validate(name, headerType, validateHeaders); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; break; case READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX: b = in.readByte(); huffmanEncoded = (b & 0x80) == 0x80; index = b & 0x7F; switch (index) { case 0x7f: state = READ_LITERAL_HEADER_VALUE_LENGTH; break; case 0: headerType = validate(name, headerType, validateHeaders); headersLength = insertHeader(headers, name, EMPTY_STRING, indexType, headersLength); state = READ_HEADER_REPRESENTATION; break; default: // Check new header size against max header size if ((long) index + nameLength > maxHeaderListSizeGoAway - headersLength) { headerListSizeExceeded(maxHeaderListSizeGoAway); } valueLength = index; state = READ_LITERAL_HEADER_VALUE; } break; case READ_LITERAL_HEADER_VALUE_LENGTH: // Header Value is a Literal String valueLength = decodeULE128(in, index); // Check new header size against max header size if ((long) valueLength + nameLength > maxHeaderListSizeGoAway - headersLength) { headerListSizeExceeded(maxHeaderListSizeGoAway); } state = READ_LITERAL_HEADER_VALUE; break; case READ_LITERAL_HEADER_VALUE: // Wait until entire value is readable if (in.readableBytes() < valueLength) { throw notEnoughDataException(in); } CharSequence value = readStringLiteral(in, valueLength, huffmanEncoded); headerType = validate(name, headerType, validateHeaders); headersLength = insertHeader(headers, name, value, indexType, headersLength); state = READ_HEADER_REPRESENTATION; break; default: throw new Error("should not reach here state: " + state); } } // we have read all of our headers, and not exceeded maxHeaderListSizeGoAway see if we have // exceeded our actual maxHeaderListSize. This must be done here to prevent dynamic table // corruption if (headersLength > maxHeaderListSize) { headerListSizeExceeded(streamId, maxHeaderListSize, true); } if (state != READ_HEADER_REPRESENTATION) { throw connectionError(COMPRESSION_ERROR, "Incomplete header block fragment."); } }
217311696_5
@Override public Collection<Object> values() { return environmentProperties.get().values(); }
217419171_3
@Override public boolean convert(ConverterRequest request, ConverterResult result, Object target) { SCMTrigger scmTrigger = (SCMTrigger) target; String cronValue = scmTrigger.getSpec(); ModelASTTrigger modelASTTrigger = new ModelASTTrigger( this ); modelASTTrigger.setName( "pollSCM" ); modelASTTrigger.setArgs( Arrays.asList(ModelASTValue.fromConstant( cronValue, this )) ); ModelASTUtils.addTrigger( result.getModelASTPipelineDef(), modelASTTrigger ); return true; }
217479559_0
public void stop(int timeoutMillis) { running = false; if (debug) { System.err.println("Stopping the HTTPS server (timeout " + timeoutMillis + " ms)"); } httpsServer.stop(timeoutMillis); }
217587403_3
public static Component translate(Component text, Locale locale) { return RENDERER.render(text, locale); }
218062029_1
public static File getToolsJar() { if (!JavaVersionUtil.isLessThanJava9()) { return null; } String javaHomeDir = getJavaHomeDir(); File toolsJar = new File(javaHomeDir, "lib/tools.jar"); if (!toolsJar.exists()) { toolsJar = new File(javaHomeDir, "../lib/tools.jar"); } if (!toolsJar.exists()) { toolsJar = new File("../../lib/tools.jar"); } if (!toolsJar.exists()) { throw new IllegalArgumentException("Can not find tools.jar under java.home"); } return toolsJar; }
218396611_54
@Override public Repository newInstance(String name, String url) { URI uri = URI.create(url); String scheme = uri.getScheme(); if (!"hdfs".equalsIgnoreCase(scheme)) { throw new IllegalArgumentException("Invalid hdfs url: " + url); } String path = uri.getPath(); String fileName = Paths.get(path).toFile().getName(); boolean isDirectory = !FilenameUtils.isArchiveFile(fileName); if (!isDirectory) { fileName = FilenameUtils.getNamePart(fileName); } String modelName = null; String artifactId = null; String query = uri.getQuery(); if (query != null) { Matcher matcher = NAME_PATTERN.matcher(query); if (matcher.find()) { modelName = matcher.group(1); } matcher = ARTIFACT_PATTERN.matcher(query); if (matcher.find()) { artifactId = matcher.group(1); } } if (artifactId == null) { artifactId = fileName; } if (modelName == null) { modelName = artifactId; } if (path.isEmpty()) { path = "/"; } try { uri = new URI( "hdfs", uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null); } catch (URISyntaxException e) { throw new AssertionError(e); } return new HdfsRepository(config, name, uri, path, artifactId, modelName, isDirectory); }
218804581_3
public static List<String> tokenize(String value, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { List<String> tokens = new ArrayList<>(); if (value == null) { return tokens; } String[] st = value.split(delimiters); for (String token : st) { if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return tokens; }
218912806_9
public boolean completeTaskByTaskID(String taskID){ try { processEngine.getTaskService() .complete(taskID); } catch (ActivitiObjectNotFoundException e) { logger.info("[任务完成操作失败] " + e.getMessage()); return false; } logger.info("[任务完成操作成功] [taskID=" + taskID + "]"); return true; }
219180652_0
@Override public String toString() { StringJoiner sj = new StringJoiner(","); for (Entry<String, String> e : getProperties().entrySet()){ sj.add(e.getKey() + "=" + e.getValue()); } return getFullId() + "[" + sj.toString() + "]"; }
219255094_0
@Override public Optional<ProductInfo> findById(String productId) { return repository.findById(productId); }
219454065_18
public void markNotified(@NonNull NotificationType type) { Validate.notNull(type); Optional.ofNullable(getNotifications().get(type)) .ifPresent(settings -> { Validate.isTrue(settings.isActive()); settings.markNotified(); }); }
219701790_135
@Procedure(name = "gds.alpha.similarity.cosine.stream", mode = READ) @Description(DESCRIPTION) public Stream<SimilarityResult> cosineStream( @Name(value = "graphName") Object graphNameOrConfig, @Name(value = "configuration", defaultValue = "{}") Map<String, Object> configuration ) { return stream(graphNameOrConfig, configuration); }
220248572_1
public static String getExtensionName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot >-1) && (dot < (filename.length() - 1))) { return filename.substring(dot + 1); } } return filename; }
220262191_21
@Override protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { String path = request.getRequestURI(); Map<String, String> headerKeyValueMap = new HashMap<>(); ShadowTrafficConfig shadowTrafficConfig = shadowTrafficConfigHelper.getConfig(); // If shadow traffic is disabled then don't bother matching patterns nor invoke the filter if (shadowTrafficConfig == null || !shadowTrafficConfig.isEnabled()) { return true; } // If this was already shadow traffic, do not invoke the filter Enumeration<?> headerNames = request.getHeaderNames(); // There is no way to optimize this as it's required to go through each header :( if (headerNames != null) { while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); if (null != key) { headerKeyValueMap.put(key, null != value ? value.toLowerCase() : null); if (value != null && key.equalsIgnoreCase(ShadowTrafficAdapter.IS_SHADOW_TRAFFIC_KEY) && value.equalsIgnoreCase(ShadowTrafficAdapter.IS_SHADOW_TRAFFIC_VALUE)) { return true; } // Only care about the shadow traffic key } } } if (CollectionUtils.isEmpty(shadowTrafficConfig.getInclusionPatterns())) { return true; } for (ShadowTrafficConfig.InclusionPattern inclusionPattern : shadowTrafficConfig.getInclusionPatterns()) { if (inclusionPattern != null) { try { Pattern compiledExclusionPattern = Pattern.compile(inclusionPattern.getRequestURI()); // If the path and method match the configured inclusion pattern then allow the shadow traffic through if (compiledExclusionPattern.matcher(path).matches() && (inclusionPattern.getMethod().equals(ALL_METHODS) || request.getMethod().equalsIgnoreCase(inclusionPattern.getMethod()))) { List<HeaderPattern> headerPatterns = inclusionPattern.getHeaderPattern(); if (CollectionUtils.isEmpty(headerPatterns)) { return false; } else { for (HeaderPattern headerPattern : headerPatterns) { if (null != headerPattern && null != headerPattern.getHeaderKey() && null != headerPattern.getHeaderValue() && headerKeyValueMap.containsKey(headerPattern.getHeaderKey().toLowerCase())) { Pattern headerValuePattern = Pattern.compile(headerPattern.getHeaderValue().toLowerCase()); String requestHeaderActualValue = headerKeyValueMap.get(headerPattern.getHeaderKey().toLowerCase()); if (StringUtils.isNotBlank(requestHeaderActualValue) && headerValuePattern.matcher(requestHeaderActualValue).matches()) { return false; } } } } } } catch (PatternSyntaxException pse) { // give a better log warning for invalid syntax LOGGER.warn("Invalid pattern syntax configured", pse); } catch (Exception ex) { // if anything else unexpected happens then just ignore the inclusion pattern LOGGER.warn("Invalid inclusion pattern", ex); } } } // default return true; }
220952727_4
public List<AppEnvCluster> findClusters(String env, long appId) { return appEnvClusterRepository.findByAppIdAndEnv(appId, env); }
221155810_2
@Override public List<KisiDto> getAll() { List<Kisi> kisiler = kisiRepository.findAll(); List<KisiDto> kisiDtos = new ArrayList<>(); kisiler.forEach(it -> { KisiDto kisiDto =new KisiDto(); kisiDto.setId(it.getId()); kisiDto.setAdi(it.getAdi()); kisiDto.setSoyadi(it.getSoyadi()); kisiDto.setAdresler( it.getAdresleri() != null ? it.getAdresleri().stream().map(Adres::getAdres).collect(Collectors.toList()) : null); kisiDtos.add(kisiDto); }); return kisiDtos; }
221881722_45
public double getValue() { return value; }
221992547_32
public List<Neighbor> getNearNeighborsInSample(double[] point, double distanceThreshold) { checkNotNull(point, "point must not be null"); checkArgument(distanceThreshold > 0, "distanceThreshold must be greater than 0"); if (!isOutputReady()) { return Collections.emptyList(); } Function<RandomCutTree, Visitor<Optional<Neighbor>>> visitorFactory = tree -> new NearNeighborVisitor(point, distanceThreshold); return traverseForest(point, visitorFactory, Neighbor.collector()); }
222008690_16
@NotNull @Override public List<? extends JpsModulePropertiesSerializer<?>> getModulePropertiesSerializers() { return Collections.emptyList(); }
222136267_86
public void apply(ItemStack to) { Validate.notNull(to, "itemstack cannot be null"); Validate.isTrue(to.getType() == Material.POTION, "given itemstack is not a potion"); to.setDurability(toDamageValue()); }
222455446_0
@Transactional(readOnly = true) public UserResponse getUser(Integer userId) { final Optional<TestUser> user = userRepository.findById(userId); return user.map(UserService::toUserResponse).orElseThrow(NotFoundException::new); }
222514148_1
public boolean isClass() { return isClass; }
222530720_33
@Override public void start(ModuleContext context) { applicationContext = new SpringApplicationBuilder(SpringWebInitiator.class) .web(WebApplicationType.SERVLET) .resourceLoader(new DefaultResourceLoader(context.getModule().getClassLoader())) .run(); }
222578036_1
@Override public List<String> getColumnNames(String tableName, String datasource) { DatabaseMetaData metaData = null; List<String> columnNames = Lists.newArrayList(); ResultSet rs = null; try { metaData = conn.getMetaData(); rs = metaData.getColumns(conn.getCatalog(), null, tableName, "%"); while (rs.next()) { columnNames.add(rs.getString("COLUMN_NAME")); // 获取字段的数据类型 rs.getString("TYPE_NAME") } } catch (SQLException e) { logger.error("[getColumnNames Exception] --> " + "the exception message is:" + e.getMessage()); } finally { JdbcUtils.close(rs); } return columnNames; }
222710815_0
public ContextAssert containsOnly(Context other) { Map.Entry<Object, Object>[] otherArray = other.stream().toArray(ARRAY_GENERATOR); //we use containsOnly and not containsExactlyInAnyOrder because we don't care about duplicates iterables.assertContainsOnly(info, actualAsList, otherArray); return this; }
223482145_0
@Override public void handleRequest(InputStream is, OutputStream os, Context context) throws IOException { LambdaLogger logger = context.getLogger(); String input = Utils.toString(is); try { Request request = GSON.fromJson(input, Request.class); String url = request.getInputImageUrl(); String artifactId = request.getArtifactId(); Map<String, String> filters = request.getFilters(); Criteria<Image, Classifications> criteria = Criteria.builder() .setTypes(Image.class, Classifications.class) .optArtifactId(artifactId) .optFilters(filters) .build(); try (ZooModel<Image, Classifications> model = ModelZoo.loadModel(criteria); Predictor<Image, Classifications> predictor = model.newPredictor()) { Image image = ImageFactory.getInstance().fromUrl(url); List<Classifications.Classification> result = predictor.predict(image).topK(5); os.write(GSON.toJson(result).getBytes(StandardCharsets.UTF_8)); } } catch (RuntimeException | ModelException | TranslateException e) { logger.log("Failed handle input: " + input); logger.log(e.toString()); String msg = "{\"status\": \"invoke failed: " + e.toString() + "\"}"; os.write(msg.getBytes(StandardCharsets.UTF_8)); } }
223551095_1807
@Override public Result execute() throws UnsupportedPropertyException, SystemException, NoSuchResourceException, NoSuchParentResourceException { queryForResources(); return getResult(null); }
223850259_0
public void send(){ String message="Hello World:"+ DateUtil.now(); log.info("FwSender:"+message); //第一个参数是topic,第二个参数是内容 amqpTemplate.convertAndSend("hello",message); }
223898372_5
public FileFilterConfig parse() throws DocumentException { FileFilterConfig fileFilter = new FileFilterConfig(); SAXReader reader = new SAXReader(); Document doc = reader.read(configPath.toFile()); Element root = doc.getRootElement(); for (Iterator i = root.elementIterator("filter"); i.hasNext(); ) { Element element = (Element) i.next(); String isActiveValue = element.attributeValue("isactive"); if (isActiveValue != null && isActiveValue.equals("true")) { fileFilter.setActive(true); } for (Iterator rules = element.elementIterator("rule"); rules.hasNext(); ) { Element ruleElement = (Element) rules.next(); String rule = ruleElement.attributeValue("value"); if (rule != null) { fileFilter.addRule(rule); } } } return fileFilter; }
224061261_10
@Override public void handleResponse(Event event) { HttpServletNetworkResponseEvent responseEvent = (HttpServletNetworkResponseEvent) event; Segment currentSegment = getSegment(); // No need to log since a Context Missing Error will already be recorded if (currentSegment == null) { return; } // Add the status code // Obtain the status code of the underlying http response. If it failed, it's a fault. Map<String, Object> responseAttributes = new HashMap<>(); int statusCode = responseEvent.getStatusCode(); // Check if the status code was a fault. switch (statusCode / 100) { case 2: // Server OK break; case 4: // Exception currentSegment.setError(true); if (statusCode == 429) { currentSegment.setThrottle(true); } break; case 5: // Fault currentSegment.setFault(true); break; } responseAttributes.put(STATUS_KEY, statusCode); currentSegment.putHttp(RESPONSE_KEY, responseAttributes); endSegment(); }
224235390_87
@Override public void serialize(final GenericRecord record, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { gen.writeRawValue(getJsonString(record, record.getSchema())); }
224256826_30
@Override public Translation<List<Acknowledgeable<W>>, Acknowledgeable<W>> apply(List<Acknowledgeable<W>> buffer) { List<Acknowledgeable<W>> nonCanceledBuffer = WorkBuffers.collectNonCanceledAcknowledgeable(buffer, Acknowledgeable::acknowledge); try { return tryTranslate(nonCanceledBuffer) .map(result -> Translation.withResult(buffer, result)) .orElseGet(() -> Translation.noResult(buffer)); } catch (Throwable error) { handleNonCanceledTranslationError(nonCanceledBuffer, error); return Translation.noResult(buffer); } }
224537036_84
@Override public DeliveryResponse getResources(InputPayload inputPayload, MessageHeaders headers) { log.debug("Getting resources for following SRNs and headers : {}, {}", inputPayload, headers); String authorizationToken = extractHeaderByName(headers, OsduHeader.AUTHORIZATION); String partition = extractHeaderByName(headers, OsduHeader.PARTITION); authenticationService.checkAuthentication(authorizationToken, partition); Map<String, Future<ProcessingResult>> srnToFutureMap = inputPayload.getSrns().stream() .distinct() .collect(Collectors.toMap(Function.identity(), srn -> dataProcessingJob.process(srn, authorizationToken, partition))); List<ProcessingResult> results = srnToFutureMap.entrySet().stream() .map(this::getProcessingResult) .collect(Collectors.toList()); return resultDataConverter.convertProcessingResults(results); }
224764811_71
@Subscribe public void onGameTick(GameTick tick) { // update the lingering presence of npcs in the slayer xp consideration list Iterator<NPCPresence> presenceIterator = lingeringPresences.iterator(); while (presenceIterator.hasNext()) { NPCPresence presence = presenceIterator.next(); presence.tickExistence(); if (!presence.shouldExist()) { // log.debug("Lingering presence of " + presence.toString() + " expired"); presenceIterator.remove(); } } Widget npcDialog = client.getWidget(WidgetInfo.DIALOG_NPC_TEXT); if (npcDialog != null && canMatchDialog) { String npcText = Text.sanitizeMultilineText(npcDialog.getText()); //remove color and linebreaks final Matcher mAssign = NPC_ASSIGN_MESSAGE.matcher(npcText); // amount, name, (location) final Matcher mAssignFirst = NPC_ASSIGN_FIRST_MESSAGE.matcher(npcText); // name, number final Matcher mAssignBoss = NPC_ASSIGN_BOSS_MESSAGE.matcher(npcText); // name, number, points final Matcher mCurrent = NPC_CURRENT_MESSAGE.matcher(npcText); // name, (location), amount if (mAssign.find()) { String name = mAssign.group("name"); int amount = Integer.parseInt(mAssign.group("amount")); String location = mAssign.group("location"); setTask(name, amount, amount, true, location, 0); canMatchDialog = false; forcedWait = FORCED_WAIT; } else if (mAssignFirst.find()) { int amount = Integer.parseInt(mAssignFirst.group(2)); setTask(mAssignFirst.group(1), amount, amount, true, 0); canMatchDialog = false; forcedWait = FORCED_WAIT; } else if (mAssignBoss.find()) { int amount = Integer.parseInt(mAssignBoss.group(2)); setTask(mAssignBoss.group(1), amount, amount, true, 0); canMatchDialog = false; forcedWait = FORCED_WAIT; points = Integer.parseInt(mAssignBoss.group(3).replaceAll(",", "")); } else if (mCurrent.find()) { String name = mCurrent.group("name"); int amount = Integer.parseInt(mCurrent.group("amount")); String location = mCurrent.group("location"); setTask(name, amount, currentTask.getInitialAmount(), false, location, 0); canMatchDialog = false; forcedWait = FORCED_WAIT; } } else if (npcDialog == null) { if (forcedWait <= 0) { canMatchDialog = true; } forcedWait--; } // If a timeout is configured for showing slayer stats if (config.statTimeout() != 0) { // If the timer has not started, start it now if (infoTimer == null) { infoTimer = Instant.now(); } Duration timeSinceInfobox = Duration.between(infoTimer, Instant.now()); Duration statTimeout = Duration.ofMinutes(config.statTimeout()); if (timeSinceInfobox.compareTo(statTimeout) >= 0) { removeCounter(); } } taggedNpcsDiedPrevTick = taggedNpcsDiedThisTick; taggedNpcsDiedThisTick = 0; }
224846645_331
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NativeSettingsImpl that = (NativeSettingsImpl) o; return Objects.equals(name, that.name) && Objects.equals(compilerFlags, that.compilerFlags); }
225191103_1
@GET @Path("/{id}") public Response getOne(@PathParam("id") Long id) { String entity = service.get(id.intValue()); if (entity == null) { return Response .status(Response.Status.NOT_FOUND) .build(); } return Response .status(Response.Status.OK) .entity(entity) .build(); }
225545609_1
public PoolString after(PoolString other) { if (other.isEmpty()) { return this; } Preconditions.checkArgument(other.base == base); Preconditions.checkArgument(other.startIndex == startIndex); if (other.endIndex == endIndex) { return empty; } Preconditions.checkArgument(other.endIndex < endIndex); return new PoolString(base, other.endIndex, endIndex); }
225625782_51
static UnixDomainHttpEndpoint parseFrom(URI endpoint) { final Path path = Paths.get(endpoint.getPath()); final int sockPathIndex = indexOfSockFile(path); final String filePath = "/" + path.subpath(0, sockPathIndex + 1).toString(); final File unixDomainFile = new File(filePath); if (sockPathIndex == path.getNameCount() - 1) { return new UnixDomainHttpEndpoint(unixDomainFile, "/"); } String pathSegment = "/" + path.subpath(sockPathIndex + 1, path.getNameCount()).toString(); return new UnixDomainHttpEndpoint(unixDomainFile, pathSegment); }
225818900_8
public static String createEndpointOptionsFromProperties(Map<String, String> props, String prefix) { return props.keySet().stream() .filter(k -> k.startsWith(prefix)) .map(k -> k.replace(prefix, "") + "=" + props.get(k)) .reduce((o1, o2) -> o1 + "&" + o2) .map(result -> result.isEmpty() ? "" : "?" + result) .orElse(""); }
226089680_38
@Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } log.info("Web application fully configured"); }
226116772_0
Map queryFromAliyun(String domain) { //拼接查询地址 String queryDomain = "http://panda.www.net.cn/cgi-bin/check.cgi?area_domain=" + domain; //请求万网接口进行查询 ResponseEntity<Map> forEntity = null; try { forEntity = restTemplate.getForEntity(queryDomain, Map.class); } catch (RestClientException e) { e.printStackTrace(); log.error(MessageConstant.API_PARSING_EXCEPTION, e); return null; } HttpStatus statusCode = forEntity.getStatusCode(); //判断查询结果 if (!forEntity.getStatusCode().toString().contains("200") || forEntity.getBody() == null) { log.error(MessageConstant.API_PARSING_EXCEPTION); return null; } //返回查询结果 return forEntity.getBody(); }
226364580_7
public static WebMercatorTile forQuadkey(String quadKey) throws IllegalArgumentException { if (!QUADKEY_REGEXP.matcher(quadKey).matches()) { throw new IllegalArgumentException("Invalid quadkey."); } int level = quadKey.length(); int x = 0; int y = 0; int depth = Math.min(MAX_LEVEL, quadKey.length()); for (int index = 0; index < depth; ++index) { y <<= 1; x <<= 1; char nextChar = quadKey.charAt(index); if ('1' == nextChar) { x++; } else if ('2' == nextChar) { y++; } else if ('3' == nextChar) { x++; y++; } } return new WebMercatorTile(level, x, y); }
226861344_62
@SuppressWarnings("unchecked") public List<E> poll(BitSet queueIds) throws InterruptedException { ArrayList<E> re = new ArrayList<>(queueIds.cardinality()); for (int id = queueIds.nextSetBit(0); id >= 0; id = queueIds.nextSetBit(id + 1)) { DalQueue dalqueue = queues[id]; if (dalqueue == null) { unReadyQueue(id, dalqueue); continue; } E x = (E) dalqueue.queue.poll(); if (x != null) { dalqueue.count.getAndDecrement(); dalqueue.modCount.getAndIncrement(); re.add(x); } if (dalqueue.count.get() == 0) { unReadyQueue(id, dalqueue); } } return re; }
227063129_281
List<RangerPolicy> getPolicies(final String serviceName, final String policyName) { if(LOG.isDebugEnabled()) { LOG.debug("==> RangerValidator.getPolicies(" + serviceName + ", " + policyName + ")"); } List<RangerPolicy> policies = null; try { SearchFilter filter = new SearchFilter(); if (StringUtils.isNotBlank(policyName)) { filter.setParam(SearchFilter.POLICY_NAME, policyName); } filter.setParam(SearchFilter.SERVICE_NAME, serviceName); policies = _store.getPolicies(filter); } catch (Exception e) { LOG.debug("Encountred exception while retrieving service from service store!", e); } if(LOG.isDebugEnabled()) { int count = policies == null ? 0 : policies.size(); LOG.debug("<== RangerValidator.getPolicies(" + serviceName + ", " + policyName + "): count[" + count + "], " + policies); } return policies; }
227131980_94
public static <T> MultivaluedMap<String, T> sanitizeHeaders(MultivaluedMap<String, T> headers) { MultivaluedMap<String, T> sanitizedHeaders = new MultivaluedHashMap<>(); headers.forEach( (key, value) -> { if (AUTHORIZATION.equalsIgnoreCase(key)) { sanitizedHeaders.put( key, value.stream() .map(h -> (T) sanitizeAuthorizationHeader(h.toString())) .collect(Collectors.toList())); } else if (SET_COOKIE.equalsIgnoreCase(key) || COOKIE.equalsIgnoreCase(key)) { sanitizedHeaders.putSingle(key, (T) "…"); } else { sanitizedHeaders.put(key, value); } }); return sanitizedHeaders; }
227144695_1
public static double[][] approxJacobian(double[] x, Vector2VectorFunc func, double... arg) { final int n = x.length; final double[] f0; if (arg != null && arg.length > 0) { f0 = func.apply(x, arg); } else { f0 = func.apply(x); } final double[][] jac = new double[n][f0.length]; final double[] dx = new double[n]; for (int i = 0; i < n; i++) { dx[i] = Jacobian.epsilon; final double[] add = new double[n]; for (int j = 0; j < n; j++) { add[j] = x[j] + dx[j]; } for (int j = 0; j < f0.length; j++) { if (arg != null && arg.length > 0) { jac[i][j] = (func.apply(add, arg)[j] - f0[j]) / Jacobian.epsilon; } else { jac[i][j] = (func.apply(add)[j] - f0[j]) / Jacobian.epsilon; } } dx[i] = 0; } return jac; }
228257340_39
@Override public boolean getConsentable() { return consentable; }
228959889_0
public byte[] hashBytes(byte[] var1) { return newHasher().hashBytes(var1); }
228976248_2
@ApiOperation(value = "获取菜单", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/getMenu", method = RequestMethod.POST, produces = {"application/json"}) public MsgResponseBody<MenuInfo> getMenu() { return MsgResponseBody.success().setResult(menuService.getMenu()); }
229095535_2
@Override public UserDetails updatePassword(UserDetails user, String newPassword) { return userService .findOneByEmail(user.getUsername()) .map( u -> { LOGGER.info( "Upgrading password {} for user {} to {}", user.getPassword(), user.getUsername(), newPassword); u.setPassword(newPassword); return new AuthenticatedUser(userService.save(u)); }) .orElseThrow( () -> new UsernameNotFoundException("No user found for " + user.getUsername())); }
229869608_0
@Nonnull private String toFilename( @Nonnull final TypeElement typeElement ) { return GeneratorUtil.getGeneratedClassName( typeElement, "", "" ).toString().replace( ".", "/" ); }
229913994_216
public void completeTx(SendRequest req) throws InsufficientMoneyException { lock.lock(); try { checkArgument(!req.completed, "Given SendRequest has already been completed."); // Calculate the amount of value we need to import. Coin value = Coin.ZERO; for (TransactionOutput output : req.tx.getOutputs()) { value = value.add(output.getValue()); } log.info("Completing send tx with {} outputs totalling {} and a fee of {}/kB", req.tx.getOutputs().size(), value.toFriendlyString(), req.feePerKb.toFriendlyString()); // If any inputs have already been added, we don't need to get their value from wallet Coin totalInput = Coin.ZERO; for (TransactionInput input : req.tx.getInputs()) if (input.getConnectedOutput() != null) totalInput = totalInput.add(input.getConnectedOutput().getValue()); else log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee."); value = value.subtract(totalInput); List<TransactionInput> originalInputs = new ArrayList<>(req.tx.getInputs()); // Check for dusty sends and the OP_RETURN limit. if (req.ensureMinRequiredFee && !req.emptyWallet) { // Min fee checking is handled later for emptyWallet. int opReturnCount = 0; for (TransactionOutput output : req.tx.getOutputs()) { if (output.isDust()) throw new DustySendRequested(); if (ScriptPattern.isOpReturn(output.getScriptPubKey())) ++opReturnCount; } if (opReturnCount > 1) // Only 1 OP_RETURN per transaction allowed. throw new MultipleOpReturnRequested(); } // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us // with the actual outputs that'll be used to gather the required amount of value. In this way, users // can customize coin selection policies. The call below will ignore immature coinbases and outputs // we don't have the keys for. List<TransactionOutput> candidates = calculateAllSpendCandidates(true, req.missingSigsMode == MissingSigsMode.THROW); CoinSelection bestCoinSelection; TransactionOutput bestChangeOutput = null; List<Coin> updatedOutputValues = null; if (!req.emptyWallet) { // This can throw InsufficientMoneyException. FeeCalculation feeCalculation = calculateFee(req, value, originalInputs, req.ensureMinRequiredFee, candidates); bestCoinSelection = feeCalculation.bestCoinSelection; bestChangeOutput = feeCalculation.bestChangeOutput; updatedOutputValues = feeCalculation.updatedOutputValues; } else { // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output // of the total value we can currently spend as determined by the selector, and then subtracting the fee. checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only."); CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; bestCoinSelection = selector.select(params.getMaxMoney(), candidates); candidates = null; // Selector took ownership and might have changed candidates. Don't access again. req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered); log.info(" emptying {}", bestCoinSelection.valueGathered.toFriendlyString()); } for (TransactionOutput output : bestCoinSelection.gathered) req.tx.addInput(output); if (req.emptyWallet) { final Coin feePerKb = req.feePerKb == null ? Coin.ZERO : req.feePerKb; if (!adjustOutputDownwardsForFee(req.tx, bestCoinSelection, feePerKb, req.ensureMinRequiredFee)) throw new CouldNotAdjustDownwards(); } if (updatedOutputValues != null) { for (int i = 0; i < updatedOutputValues.size(); i++) { req.tx.getOutput(i).setValue(updatedOutputValues.get(i)); } } if (bestChangeOutput != null) { req.tx.addOutput(bestChangeOutput); log.info(" with {} change", bestChangeOutput.getValue().toFriendlyString()); } // Now shuffle the outputs to obfuscate which is the change. if (req.shuffleOutputs) req.tx.shuffleOutputs(); // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs. if (req.signInputs) signTransaction(req); // Check size. final int size = req.tx.unsafeBitcoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) throw new ExceededMaxTransactionSize(); // Label the transaction as being self created. We can use this later to spend its change output even before // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much // point - the user isn't interested in a confidence transition they made themselves. req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); // Label the transaction as being a user requested payment. This can be used to render GUI wallet // transaction lists more appropriately, especially when the wallet starts to generate transactions itself // for internal purposes. req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT); // Record the exchange rate that was valid when the transaction was completed. req.tx.setExchangeRate(req.exchangeRate); req.tx.setMemo(req.memo); req.completed = true; log.info(" completed: {}", req.tx); } finally { lock.unlock(); } }
230080058_1
public static Map<String, Object> flatMap(@NonNull Map<String, Object> map, String joinKey) { return recursiveFlat(map, joinKey, new ArrayList<>()); }
230236469_32
public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); }
231329990_0
@Nonnull @Override public VertxTcpClient createNetwork(@Nonnull TcpClientProperties properties) { VertxTcpClient client = new VertxTcpClient(properties.getId()); initClient(client, properties); return client; }
231349973_3
public static void generatorZjmiecOACode(String url,String modelName){ File file = new File(url); List<ExcelApi2Code> excelApi2Codes = EasypoiUtil.importExcel(file, ExcelApi2Code.class,new ImportParams()); System.out.println("WorkflowRequestTableField[] wrtf = new WorkflowRequestTableField[" + excelApi2Codes.size() +"]"); int i = 0; for (ExcelApi2Code excelApi2Code: excelApi2Codes) { System.out.println("/**"); System.out.println(" * "+excelApi2Code.getDescription().toString()); System.out.println(" */"); System.out.println("wrti["+i+"] = new WorkflowRequestTableField();"); System.out.println("wrti["+i+"].setFieldName(\""+excelApi2Code.getLocalFild()+"\");"); System.out.println("wrti["+i+"].setFieldValue("+excelApi2Code.getLocalFild()+");"); System.out.println("wrti["+i+"].setView(true);//字段是否可见"); System.out.println("wrti["+i+"].setEdit(true);//字段是否可编辑"); System.out.println(" "); i++; } }
231519592_3
@Override public Response execute(RefrigeratorInitCommand cmd) { refrigeratorMapper.truncate(); RefrigeratorRandomProfile refrigeratorRandomProfile = new RefrigeratorRandomProfile(); //先把大象全家都装进冰箱... refrigeratorMapper.save(refrigeratorRandomProfile.randomAnimal()); refrigeratorMapper.save(refrigeratorRandomProfile.randomAnimal()); refrigeratorMapper.save(refrigeratorRandomProfile.randomAnimal()); refrigeratorMapper.save(refrigeratorRandomProfile.randomAnimal()); refrigeratorMapper.save(refrigeratorRandomProfile.randomAnimal()); refrigeratorMapper.save(refrigeratorRandomProfile.randomSpace()); refrigeratorMapper.save(refrigeratorRandomProfile.randomSpace()); refrigeratorMapper.save(refrigeratorRandomProfile.randomSpace()); return Response.buildSuccess(); }
231533573_2
public TubeBaseSessionFactory(final ClientFactory clientFactory, final TubeClientConfig tubeClientConfig) throws TubeClientException { super(); this.checkConfig(tubeClientConfig); this.tubeClientConfig = tubeClientConfig; RpcConfig config = new RpcConfig(); config.put(RpcConstants.RPC_LQ_STATS_DURATION, tubeClientConfig.getLinkStatsDurationMs()); config.put(RpcConstants.RPC_LQ_FORBIDDEN_DURATION, tubeClientConfig.getLinkStatsForbiddenDurationMs()); config.put(RpcConstants.RPC_LQ_MAX_ALLOWED_FAIL_COUNT, tubeClientConfig.getLinkStatsMaxAllowedFailTimes()); config.put(RpcConstants.RPC_LQ_MAX_FAIL_FORBIDDEN_RATE, tubeClientConfig.getLinkStatsMaxForbiddenRate()); config.put(RpcConstants.RPC_SERVICE_UNAVAILABLE_FORBIDDEN_DURATION, tubeClientConfig.getUnAvailableFbdDurationMs()); this.rpcServiceFactory = new RpcServiceFactory(clientFactory, config); this.producerManager = new ProducerManager(this, this.tubeClientConfig); this.brokerRcvQltyStats = new DefaultBrokerRcvQltyStats(this.getRpcServiceFactory(), this.tubeClientConfig); logger.info(new StringBuilder(512) .append("Created Session Factory, the config is: ") .append(tubeClientConfig.toJsonString()).toString()); }
232306581_4
public static long crc32(byte[] data, int offset, int len) { long crc = 0xFFFFFFFFL; long[][] table = init(UT_CRC_32_SLICE_8_TABLE_THREAD_LOCAL.get()); /* Calculate byte-by-byte up to an 8-byte aligned address. After this consume the input 8-bytes at a time. */ // In C code, it needs to align to be CPU friendly, but in Java, // this is meaningless, so comment this snippet. // while (len > 0 && (reinterpret_cast<uintptr_t>(buf) & 7) != 0) { // ut_crc32_8_sw(&crc, &buf, &len); //} while (len >= 128) { /* This call is repeated 16 times. 16 * 8 = 128. */ for (int i = 0; i < 16; i++) { long dataInt = fromByteArray(data, offset); crc = utCrc3264LowSw(crc, dataInt, table); offset += 8; len -= 8; } } while (len >= 8) { long dataInt = fromByteArray(data, offset); crc = utCrc3264LowSw(crc, dataInt, table); offset += 8; len -= 8; } while (len > 0) { crc = utCrc328Sw(crc, data[offset] & 0xFFL, table); offset++; len--; } return (~crc) & 0xFFFFFFFFL; }
232664319_8
List<String> getStatements() { List<String> availableStatements = this.statements; if (availableStatements == null) { synchronized (this) { availableStatements = this.statements; if (availableStatements == null) { this.statements = readStatements(); availableStatements = this.statements; } } } return availableStatements; }
232697780_1
public Object instantiate() { try { return constructor.newInstance(parameters.toArray()); } catch (Exception e) { throw new InstantiationFailure(e); } }
232712706_9
@Override public void watch(WatchType type, LongConsumer consumer) { switch (type) { case SCHEMAVERSION: etcdClient.watch(SCHEMA_VERSION_PATH, false, consumer); break; case SCHEMATASK: etcdClient.watch(TASK_LIST, true, consumer); break; case PRIVERSION: etcdClient.watch(PRI_VERSION_PATH, false, consumer); break; case PRITASK: etcdClient.watch(TASK_PRI_LIST, true, consumer); break; case INDEXTASK: etcdClient.watch(TASK_INDEX_ROOT, true, consumer); break; default: break; } }
233941256_356
public DateRange getRange(String dateRangeString) throws ParseException { if (dateRangeString == null || dateRangeString.isEmpty()) throw new IllegalArgumentException("Passing empty Strings is not allowed"); String[] dateArr = dateRangeString.split("-"); if (dateArr.length > 2 || dateArr.length < 1) return null; // throw new IllegalArgumentException("Only Strings containing two Date separated by a '-' or a single Date are allowed"); ParsedCalendar from = parseDateString(dateArr[0]); ParsedCalendar to; if (dateArr.length == 2) to = parseDateString(dateArr[1]); else // faster and safe? // to = new ParsedCalendar(from.parseType, (Calendar) from.parsedCalendar.clone()); to = parseDateString(dateArr[0]); return new DateRange(from, to); }
234365176_2
public static List<Token> tokenize(InputStream in) throws SexpParserException, IOException { return SexpTokenizer.tokenize(in); }
234816965_2
@GetMapping("/api/pokemons/{number}") public ResponseEntity find(@PathVariable final int number) { return ResponseEntity.ok() .body(pokemonService.find(number)) ; }
234994470_5
@GET @Produces(MediaType.APPLICATION_JSON) @Path(ResourceDefinitions.Path.Common.SEARCH_FULL_PATH) @Timed(name = MediaService.MetricsDefinitions.SearchAudio.TIMER_NAME, displayName = METRICS_PREFIX + '.' + MediaService.MetricsDefinitions.SearchAudio.TIMER_NAME, description = MediaService.MetricsDefinitions.SearchAudio.TIMER_DESCRIPTION) public Multi<Audio> searchAudio( @PathParam(ResourceDefinitions.SEARCH_TEXT_PARAMETER) String searchText) { getLogger().debug("Invoking searchAudio... Search text: {}", searchText); return createResponse(getMediaService().searchAudio(searchText)); }
235013588_0
@GetMapping("/") public String imHealthy() { return "{healthy:true}"; }
235035304_9
public static String[] getHosts(String mongoUri) { Matcher m = MONGO_URI_PATTERN.matcher(mongoUri); if (m.find()) { return Optional.ofNullable(m.group(2)) .map(hosts -> hosts.split(",")) .orElseThrow(() -> new RuntimeException("unsupported mongo uri")); } else { throw new RuntimeException("unsupported mongo uri"); } }
235406671_1
public Difficulty getNextJobDifficulty(Miner miner) { // when few shares have been submitted, use the starting difficulty if (miner.getValidSharesSubmitted() < wait) { return new Difficulty(startDiff); } // hashrate = hashes submitted / connection time BigInteger hashrate = miner.getHashesSubmitted().divide(BigInteger.valueOf(miner.getConnectionPeriod())); BigInteger difficulty = hashrate.multiply(shareTargetTime); return new Difficulty(difficulty.max(minDiff)); }
235577942_315
public boolean hasManagerPrivilegeForDepartment(Long departmentId) { UserContextRole userRole = userRoleFromContextService.getUserRoleInUnitId(departmentId); return userRole.isHigherAuthorityTypeThan(UserContextRole.OKRMEMBER); }
235590282_3
public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { return userDTOs.stream() .filter(Objects::nonNull) .map(this::userDTOToUser) .collect(Collectors.toList()); }
235957092_0
public RLParams getParams(String jsonStr) { JSONObject jsonParams = new JSONObject(jsonStr); RLParams params = new RLParams(); if (jsonParams.has("params")) { JSONArray paramList = jsonParams.getJSONArray("params"); for (int i = 0; i < paramList.length(); i++){ JSONObject jsonParam = paramList.getJSONObject(i); String varName = jsonParam.getString("name"); String stringType = jsonParam.getString("type"); Object value; JSONArray jsonArray; switch (stringType) { case "string": value = jsonParam.getString("val"); params.add(varName, value); break; case "bool": value = jsonParam.getBoolean("val"); params.add(varName, value); break; case "long": value = jsonParam.getLong("val"); params.add(varName, value); break; case "int": value = jsonParam.getInt("val"); params.add(varName, value); break; case "double": value = jsonParam.getDouble("val"); params.add(varName, value); break; case "string_array": List<String> strArr = new ArrayList<String>(); jsonArray = jsonParam.getJSONArray("val"); for (int j = 0; j < jsonArray.length(); j++){ strArr.add(jsonArray.getString(j)); } params.add(varName, strArr); break; case "bool_array": List<Boolean> boolArr = new ArrayList<Boolean>(); jsonArray = jsonParam.getJSONArray("val"); for (int j = 0; j < jsonArray.length(); j++){ boolArr.add(jsonArray.getBoolean(j)); } params.add(varName, boolArr); break; case "int_array": List<Integer> intArr = new ArrayList<Integer>(); jsonArray = jsonParam.getJSONArray("val"); for (int j = 0; j < jsonArray.length(); j++){ intArr.add(jsonArray.getInt(j)); } params.add(varName, intArr); break; case "double_array": List<Double> doubleArr = new ArrayList<Double>(); jsonArray = jsonParam.getJSONArray("val"); for (int j = 0; j < jsonArray.length(); j++){ doubleArr.add(jsonArray.getDouble(j)); } params.add(varName, doubleArr); break; } } return params; } else { throw new JSONException("Object needs to have params as root"); } }
235979171_1
public Try<FileInputStream> tryStreamFileSubjects() { File file = new File(this.config.getString("avro.subjects.yaml")); return Try .ofFailable(() -> new FileInputStream(file)) .onFailure((t) -> logger.error("Fail to load the yaml file, it may not exist.", t)); }
236336373_3
@Override ;
236431478_5
@PostMapping("text") public String text(@RequestBody String text){ return text; }
237265610_7
public Collection<TimeRange> query(Collection<Event> events, MeetingRequest request) { throw new UnsupportedOperationException("TODO: Implement this method."); }
237355002_0
@RequestMapping("/add") @ResponseBody public ReturnT<String> add(XxlJobInfo jobInfo) { return xxlJobService.add(jobInfo); }
238661958_7
@PutMapping("/{id}") public void update(@RequestHeader(Constants.GRANT_HEADER) PureGrant grant, @PathVariable("id") String prescriptionId, @RequestBody Prescription prescription) { if (StringUtils.isNotBlank(prescription.getId()) && !StringUtils.equals(prescriptionId, prescription.getId())) { throw new BadRequestException("Prescription id is not valid"); } this.prescriptionService.update(prescription, grant); }
239025775_39
public static BodyPublisher ofObject(Object object, @Nullable MediaType mediaType) { TypeRef<?> runtimeType = TypeRef.from(object.getClass()); Encoder encoder = Encoder.getEncoder(runtimeType, mediaType) .orElseThrow(() -> unsupportedConversion(runtimeType, mediaType)); return encoder.toBody(object, mediaType); }
239132730_0
@Override public Object pack(Object obj) throws Exception { final BeanComparator comparator = new BeanComparator("lowestSetBit"); // create queue with numbers and basic comparator final PriorityQueue<Object> queue = new PriorityQueue<Object>(2, comparator); // stub data for replacement later queue.add(new BigInteger("1")); queue.add(new BigInteger("1")); // switch method called by comparator ReflectionHelper.setFieldValue(comparator, "property", "outputProperties"); // switch contents of queue final Object[] queueArray = (Object[]) ReflectionHelper.getFieldValue(queue, "queue"); queueArray[0] = obj; queueArray[1] = obj; return queue; }
239499581_3
@Override public List<SqlCreateTable> sqlTableParser(String ddlSql) throws Exception { List<SqlCreateTable> result = new LinkedList<>(); SqlNodeList nodeList = SqlUtils.parseSql(ddlSql); for (SqlNode sqlNode : nodeList) { if (sqlNode instanceof SqlCreateTable) { result.add((SqlCreateTable) sqlNode); SqlNodeList columnList = ((SqlCreateTable) sqlNode).getColumnList(); List<SqlTableColumn> tableColumnList = new ArrayList<>(); List<SqlBasicCall> basicCallList = new ArrayList<>(); Map<String,String> tableColumnInfo = new LinkedHashMap<>(); List<String> basicCallInfo = new ArrayList<>(); for (SqlNode sqlNode1: columnList) { if (sqlNode1 instanceof SqlTableColumn) { tableColumnList.add((SqlTableColumn) sqlNode1); SqlIdentifier name = ((SqlTableColumn) sqlNode1).getName(); SqlDataTypeSpec type = ((SqlTableColumn) sqlNode1).getType(); tableColumnInfo.put(name.toString(), type.toString()); } if (sqlNode1 instanceof SqlBasicCall) { basicCallList.add((SqlBasicCall) sqlNode1); System.out.println(sqlNode1.toString()); basicCallInfo.add(sqlNode1.toString()); } } } } return result; }
240292120_0
public static String createStringTypeGUID() { return HEX_IPV4_ADDR + RANDOM_SEED + Long.toHexString(System.currentTimeMillis()) + hexCycleSequence(); }
240818625_0
public static JsonAdapter.Factory create() { return new Factory(new Random()); }
241565088_0
public static BigInteger exactDivide(BigInteger dividend, BigInteger divisor) { if (divisor.signum() == 0) { throw new ArithmeticException("BigInteger divide by zero"); } return INSTANCE.get().exactDivImpl(dividend, divisor); }
242737551_29
@PUT @Path("/{id}") @Transactional @Operation(description = "Update a todo") @APIResponses({ @APIResponse(responseCode = "204", description = "Todo updated"), @APIResponse(responseCode = "400", description = "Invalid request data", content = @Content(schema = @Schema(implementation = ApplicationErrorsDTO.class))), @APIResponse(responseCode = "404", description = "Todo with given id does not exist"), @APIResponse(responseCode = "500", description = "Internal server error", content = @Content(schema = @Schema(implementation = ApplicationErrorDTO.class))) }) public Response updateTodo(@Parameter(description = "todo identifier") @PathParam("id") @Min(1) @Max(10000) final Long todoId, @RequestBody(description = "modified todo", required = true, content = @Content(schema = @Schema(implementation = ModifiedTodo.class))) @Valid @ConvertGroup(to = UpdateTodoValidationGroup.class) final ModifiedTodo modifiedTodo) { LOG.info("Update todo with id {} ({})", todoId, modifiedTodo); Optional<Todo> foundTodo = repository.find(todoId); if (!foundTodo.isPresent()) { LOG.warn("Todo with id {} not found", todoId); return Response.status(Status.NOT_FOUND).build(); } Todo todo = foundTodo.get(); todo.updateTodo(modifiedTodo.getTitle(), modifiedTodo.getDescription(), modifiedTodo.getDueDate(), modifiedTodo.getDone()); repository.update(todo); LOG.info("Todo updated"); return Response.status(Status.NO_CONTENT).build(); }
244294736_5
@Override public String getConsumerMetaData(MetadataIdentifier key) { return doGetMetaData(key); }
244419190_1
public Iterable<Integer> getMaxTemperatures(LocalDate fromDate, LocalDate toDate, String location) throws IOException { Iterable<DailyWeatherInfo> weatherInfos = weatherApi.pastWeather(fromDate, toDate, location); return QueriesEager.map(weatherInfos, dwi -> dwi.getTempMaxC()); }
244941906_7
static boolean matchCoupling(final CouplingFilter filter, final MethodCoupling coupling) { return matchString(filter.getSourcePackagePattern(), coupling.getSource().getPackageName()) && matchString(filter.getSourceClassPattern(), coupling.getSource().getSimpleClassName()) && matchString(filter.getSourceMethodPattern(), coupling.getSource().getMethodName()) && matchString(filter.getTargetPackagePattern(), coupling.getTarget().getPackageName()) && matchString(filter.getTargetClassPattern(), coupling.getTarget().getSimpleClassName()) && matchString(filter.getTargetMethodPattern(), coupling.getTarget().getMethodName()); }
246041169_0
public boolean call(String button) { int begin = getAFloor(); int end = getAFloor(); int buttonPressedFloor = getAFloor(); if (button.equalsIgnoreCase("Up")) // For Up { return (begin <= buttonPressedFloor && buttonPressedFloor < end) || (begin < buttonPressedFloor && buttonPressedFloor <= end); } else return (begin >= buttonPressedFloor && buttonPressedFloor > end) || (begin > buttonPressedFloor && buttonPressedFloor >= end); //For Down }
246630390_1
@Override public byte[] merge(Map<String, Object> keys, Iterator<byte[]> files) { return ParquetHelper.mergeFiles(files); }
246677383_5
public void buildExpressionNotation(String expressionBegin, String expressionEnd) { this.expressionNotationBegin = expressionBegin; this.expressionNotationEnd = expressionEnd; String regexExpression = Pattern.quote(expressionNotationBegin) + EXPRESSION_PART + Pattern.quote(expressionNotationEnd); expressionNotationPattern = Pattern.compile(regexExpression); }