id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
181322928_0
|
@Override
public List<MonitorBean> getAll(String app, String id) {
if (app == null || id == null) {
throw new TicketServerException(ResultEnum.ERROR);
}
Set<String> pres = template.keys(MonitorService.getMonitorPreKeys(app, id));
if (pres == null) {
throw new TicketServerException(ResultEnum.ERROR);
}
Map<String, MonitorBean> map = new HashMap<>(); //key:DateTime
pres.forEach(s -> {
String pre = opsForValue.get(s);
MonitorBean monitorBean = new MonitorBean();
monitorBean.setApp(app);
monitorBean.setId(id);
monitorBean.setPre(Integer.parseInt(pre == null ? String.valueOf(0) : pre));
String after = opsForValue.get(s.replace(PRE, AFTER));
monitorBean.setAfter(Integer.parseInt(after == null ? String.valueOf(0) : after));
monitorBean.setLocalDateTime(DateTimeUtil.parse(s.substring(s.lastIndexOf(MonitorService.DATE) + MonitorService.DATE.length())));
if (map.containsKey(monitorBean.getDateTime())) {
monitorBean.setPre(monitorBean.getPre() + map.get(monitorBean.getDateTime()).getPre());
monitorBean.setAfter(monitorBean.getAfter() + map.get(monitorBean.getDateTime()).getAfter());
}
map.put(monitorBean.getDateTime(), monitorBean);
});
return new ArrayList<>(map.values());
}
|
181400274_0
|
@Bean
@ConditionalOnMissingBean(DefaultMQProducer.class)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = {"name-server", "producer.group"})
public DefaultMQProducer defaultMQProducer(RocketMQProperties rocketMQProperties) {
RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
String nameServer = rocketMQProperties.getNameServer();
String groupName = producerConfig.getGroup();
Assert.hasText(nameServer, "[rocketmq.name-server] must not be null");
Assert.hasText(groupName, "[rocketmq.producer.group] must not be null");
DefaultMQProducer producer;
String ak = rocketMQProperties.getProducer().getAccessKey();
String sk = rocketMQProperties.getProducer().getSecretKey();
if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) {
producer = new DefaultMQProducer(groupName, new AclClientRPCHook(new SessionCredentials(ak, sk)),
rocketMQProperties.getProducer().isEnableMsgTrace(),
rocketMQProperties.getProducer().getCustomizedTraceTopic());
producer.setVipChannelEnabled(false);
} else {
producer = new DefaultMQProducer(groupName, rocketMQProperties.getProducer().isEnableMsgTrace(),
rocketMQProperties.getProducer().getCustomizedTraceTopic());
}
producer.setNamesrvAddr(nameServer);
producer.setSendMsgTimeout(producerConfig.getSendMessageTimeout());
producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMessageBodyThreshold());
producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryNextServer());
return producer;
}
|
181445409_46
|
@Override
public HttpServerOptions apply(HttpServerOptions options) {
Ssl ssl = factory.getSsl();
if (ssl == null) {
return options;
}
options.setSsl(ssl.isEnabled());
options.setKeyCertOptions(keyCertOptionsAdapter(ssl));
options.setTrustOptions(trustOptionsAdapter(ssl));
propertyMapper.from(ssl.getClientAuth())
.whenNonNull()
.as(this::clientAuthAdapter)
.to(options::setClientAuth);
propertyMapper.from(ssl.getEnabledProtocols())
.whenNonNull()
.as(Arrays::asList)
.as(LinkedHashSet::new)
.to(options::setEnabledSecureTransportProtocols);
propertyMapper.from(ssl.getCiphers())
.whenNonNull()
.as(Arrays::stream)
.to(stream -> stream.forEach(options::addEnabledCipherSuite));
return options;
}
|
181519091_56
|
@NonNull
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BlottingPaper createItem(@NonNull @Valid @RequestBody BlottingPaper input) {
return this.service.createItem(input);
}
|
181683494_110
|
public void splitSegment(String context, List<String> clientIds, String processorName) {
Map<ClientSegmentPair, SegmentStatus> clientToTracker =
buildClientToTrackerMap(clientIds, processorName, REGULAR_ORDER);
Integer biggestSegment = clientToTracker.values().stream()
.min(Comparator.comparingInt(SegmentStatus::getOnePartOf))
.map(SegmentStatus::getSegmentId)
.orElseThrow(() -> new IllegalArgumentException(
"No segments found for processor name [" + processorName + "]"
));
applicationEventPublisher.publishEvent(new SplitSegmentRequest(
NOT_PROXIED,
context,
getClientIdForSegment(clientToTracker, biggestSegment)
.orElseThrow(() -> new IllegalArgumentException("No client found which has a claim on segment [" + biggestSegment + "]")),
processorName,
biggestSegment
));
}
|
181777958_2
|
public static int[] count(Map<String, Integer> dictionary, String s) {
int[] result = new int[dictionary.size()];
VectorText.tokenize(s).forEach(w -> {
if (dictionary.containsKey(w)) {
result[dictionary.get(w)]++;
}
});
return result;
}
|
181840596_0
|
public Element fromSDP(final String sdpData) throws XMLException {
final String[] sdp = sdpData.split(LINE);
final Element jingle = ElementFactory.create("jingle");
jingle.setXMLNS("urn:xmpp:jingle:1");
/ jingle.addChild(ElementFactory.create("sdp", Base64.encode(sdpData.getBytes()), SDP.TIGASE_SDP_XMLNS));
String[] groups = findContentsNames(sdp);
for (String groupName : groups) {
final String[] mediaLines = getMediaLines(groupName, sdp);
String[] m = mediaLines[0].substring(2).split(" ");
final String mediaType = m[0];
JingleContent content = new JingleContent(ElementFactory.create("content"));
jingle.addChild(content);
content.setAttribute("name", groupName);
content.setAttribute("senders", "both");
content.setAttribute("creator", "responder");
Description description = new Description(ElementFactory.create("description"));
description.setAttribute("xmlns", "urn:xmpp:jingle:apps:rtp:1");
description.setAttribute("media", mediaType);
content.addChild(description);
findLine("a=rtcp-mux", mediaLines, line -> description.addChild(ElementFactory.create("rtcp-mux")));
String[] payloadIds = Arrays.copyOfRange(m, 3, m.length);
for (String payloadId : payloadIds) {
Payload payload = createPayload(payloadId, mediaLines);
description.addChild(payload);
}
// transport
content.addChild(fromSDPTransport(mediaLines));
}
String grLine = findLine("a=group:", sdp);
if (grLine != null) {
String[] g = grLine.substring(8).split(" ");
Element group = ElementFactory.create("group", null, "urn:xmpp:jingle:apps:grouping:0");
group.setAttribute("semantics", g[0]);
for (int i = 1; i < g.length; i++) {
Element c = ElementFactory.create("content");
c.setAttribute("name", g[i]);
group.addChild(c);
}
jingle.addChild(group);
}
return jingle;
}
|
181845258_121
|
public PullResult getOpMessage(int queueId, long offset, int nums) {
String group = TransactionalMessageUtil.buildConsumerGroup();
String topic = TransactionalMessageUtil.buildOpTopic();
SubscriptionData sub = new SubscriptionData(topic, "*");
return getMessage(group, topic, queueId, offset, nums, sub);
}
|
181888758_2
|
public void run(String... args) throws Exception {
CommandLine cmd = parseCommandLine(args);
String inputFile = cmd.getOptionValue("input");
String outputFile = cmd.getOptionValue("output");
String yml = FileUtils.readFileToString(new File(inputFile), (String)null);
Service service = fromYaml(yml, Service.class);
String asciidoc = ServiceToJSon.toAsciidoc(service);
FileUtils.write(new File(outputFile), asciidoc, (String) null);
}
|
181997557_0
|
public byte[] update(byte[] input, int offset, int inputLength) {
int reserveToApply = Math.min(reserve.length, inputLength);
int reserveToRelease = Math.max(reserveToApply - capacity(), 0);
byte[] output = new byte[reserveToRelease + (inputLength - reserveToApply)];
read(output, 0, reserveToRelease);
System.arraycopy(input, offset, output, reserveToRelease, inputLength - reserveToApply);
write(input, offset + (inputLength - reserveToApply), reserveToApply);
return output;
}
|
182006329_182
|
@Override
public boolean open(String topic, String channelName) throws BrokerException {
log.info("open topic: {} channelName: {}", topic, channelName);
ParamCheckUtils.validateTopicName(topic);
validateChannelName(channelName);
try {
return fabricDelegate.getFabricMap().get(channelName).createTopic(topic);
} catch (BrokerException e) {
if (e.getCode() == ErrorCode.TOPIC_ALREADY_EXIST.getCode()) {
return true;
}
throw e;
}
}
|
182082980_6
|
public Map<String, SshUri> getSshKeysByHostname() {
return extractNestedProperties(sshUriProperties);
}
|
182200911_1
|
public static String create() {
return Base64Utils.encodeToUrlSafeString(UUID.randomUUID().toString().getBytes());
}
|
182454442_4
|
public GenericScimResource trimRetrievedResource(final T returnedResource) {
return trimReturned(returnedResource, null, null);
}
|
182813463_18
|
public String convert(String format, Object value) {
String str = "";
if (value instanceof String) {
str = csvConverter("-var-file=%s ", (String) value);
}
return str;
}
|
182842409_47
|
public String getFullyQualifiedDatabaseName() {
return this.fullyQualifiedDbName;
}
|
183285709_18
|
static List<SocketAddress> getSeedAddress() {
List<SocketAddress> seedAddresses = null;
try {
String s = conf.getString("netifi.client.seedAddresses");
if (s != null) {
seedAddresses = new ArrayList<>();
String[] split = s.split(",");
for (String a : split) {
String[] split1 = a.split(":");
if (split1.length == 2) {
String host = split1[0];
try {
int port = Integer.parseInt(split1[1]);
seedAddresses.add(InetSocketAddress.createUnresolved(host, port));
} catch (NumberFormatException fe) {
throw new IllegalStateException("invalid seed address: " + a);
}
} else {
throw new IllegalStateException("invalid seed address: " + a);
}
}
}
} catch (ConfigException.Missing m) {
}
return seedAddresses;
}
|
183382045_2
|
@Override
public ServiceCall<NotUsed, String> proxyViaHttp(String id) {
return req -> helloService.hello(id).invoke();
}
|
183462598_0
|
@Override
public String generateCode(String phone) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxLength; i++) {
int index = random.nextInt(arr.size());
sb.append(arr.get(index));
if (sb.length() >= minLength) {
if (random.nextBoolean()) {
break;
}
}
}
return sb.toString();
}
|
183523285_12
|
public boolean deregisterQuery(String targetApp, String subId, String query) {
appToSubscriptionMap.computeIfPresent(targetApp, (k, v) -> {
v.deregisterQuery(subId, query);
return v;
});
return true;
}
|
183536958_1
|
@Override
public Jwt buildJwt(Date issued, Date expiration) {
String kid = issuerDid.getDid() + "#" + issuerDid.getKeyId();
return new Jwt.Builder()
.alg(issuerDid.getAlgorithm())
.kid(kid)
.iss(issuerDid.getDid())
.iat(issued)
.exp(expiration)
.type(getTypes())
.credential(credentials)
.nonce(nonce)
.jti(jti)
.version(version)
.build();
}
|
183646665_3
|
@Override
public boolean deepEquals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Step)) {
return false;
}
Step step = (Step) o;
if (this.id != null ? !this.id.equals(step.id) : step.id != null) {
return false;
}
if (this.metadataId != null ? !this.metadataId.equals(step.metadataId) : step.id != null) {
return false;
}
if (this.name != null ? !this.name.equals(step.name) : step.name != null) {
return false;
}
if (this.type != null ? !this.type.equals(step.type) : step.type != null) {
return false;
}
if (this.description != null
? !this.description.equals(step.description)
: step.description != null) {
return false;
}
return this.config != null ? this.config.equals(step.config) : step.config == null;
}
|
183863609_0
|
@GetMapping("/employees")
private Flux<Employee> getAllEmpployees() {
return employeeService.findAll();
}
|
183916330_0
|
@SuppressWarnings("unused")
public void insertPair(ArrayList<Object> key, long value)
throws IOException, MiniDBException,
IllegalStateException {
if(root == null)
{throw new IllegalStateException("Can't insert to null tree");}
conf.padKey(key);
// check if our root is full
if(root.isFull(conf)) {
// allocate a new *internal* node, to be placed as the
// *left* child of the new root
aChild = this.root;
TreeInternalNode node_buf = new TreeInternalNode(TreeNode.TreeNodeType.TREE_ROOT_INTERNAL,
generateFirstAvailablePageIndex(conf));
node_buf.addPointerAt(0, aChild.getPageIndex());
this.root = node_buf;
// split root.
splitTreeNode(node_buf, 0);
writeFileHeader(conf);
insertNonFull(node_buf, key, value);
}
else
{insertNonFull(root, key, value);}
}
|
183933015_15
|
@Override
public Status read(String tableName, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
StatementType type = new StatementType(StatementType.Type.READ, tableName, 1, "", getShardIndexByKey(key));
PreparedStatement readStatement = cachedStatements.get(type);
if (readStatement == null) {
readStatement = createAndCacheReadStatement(type, key);
}
readStatement.setString(1, key);
ResultSet resultSet = readStatement.executeQuery();
if (!resultSet.next()) {
resultSet.close();
return Status.NOT_FOUND;
}
if (result != null && fields != null) {
for (String field : fields) {
String value = resultSet.getString(field);
result.put(field, new StringByteIterator(value));
}
}
resultSet.close();
return Status.OK;
} catch (SQLException e) {
System.err.println("Error in processing read of table " + tableName + ": " + e);
return Status.ERROR;
}
}
|
183937162_747
|
public String readUnicodeString(long index) throws IOException {
StringBuffer buffer = new StringBuffer();
while (index < length()) {
int ch = readUnsignedShort(index);
if (ch == 0) {
break;
}
buffer.append((char) ch);
index += 2;
}
return buffer.toString().trim();
}
|
184033608_9
|
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody
Long addProject(@RequestBody @Valid Projekt projekt) {
LOG.info("POST called on /projects resource");
projektRepository.save(projekt);
LOG.info("Projekt successfully saved into DB with id " + projekt.getId());
return projekt.getId();
}
|
184035533_3
|
@NotNull
@Override
public CompassConfig parse(@NotNull final VirtualFile file,
@NotNull final String importPathsRoot,
@Nullable final PsiManager psiManager) {
return ReadAction.compute(() -> {
PsiFile psiFile = psiManager != null ? psiManager.findFile(file) : null;
if (psiFile != null) {
final List<String> importPaths = new ArrayList<>();
final List<String> additionalImportPaths = new ArrayList<>();
final RubyPsiInterpreter interpreter = new RubyPsiInterpreter(true);
interpreter.interpret(psiFile, arguments -> {
final String cmdName = arguments.getCommand();
if (ADD_IMPORT_PATH_CALL.equals(cmdName)) {
final RPsiElement firstArgument = ContainerUtil.getFirstItem(arguments.getArguments());
if (firstArgument instanceof RStringLiteral) {
importPaths.add(normalizePath(((RStringLiteral)firstArgument).getContent(), importPathsRoot));
}
}
else if (ADDITIONAL_IMPORT_PATHS_ASSIGNMENT.equalsIgnoreCase(cmdName)) {
final RAssignmentExpression assignment = RAssignmentExpressionNavigator.getAssignmentByLeftPart(arguments.getCallElement());
if (assignment != null) {
additionalImportPaths.clear();
final RPsiElement value = assignment.getValue();
if (value instanceof RArray) {
for (RPsiElement element : ((RArray)value).getElements()) {
if (element instanceof RStringLiteral) {
additionalImportPaths.add(normalizePath(((RStringLiteral)element).getContent(), importPathsRoot));
}
}
}
}
}
});
importPaths.addAll(additionalImportPaths);
return new CompassConfig(importPaths);
}
return CompassConfig.EMPTY_COMPASS_CONFIG;
});
}
|
184219031_10
|
@Override
public String name() {
return "hint";
}
|
184265896_209
|
protected Rectangle getMonthBoundsAtLocation(int x, int y) {
if (!calendarGrid.contains(x, y))
return null;
int calendarRow = (y - calendarGrid.y) / fullCalendarHeight;
int calendarColumn = (x - calendarGrid.x) / fullCalendarWidth;
return new Rectangle(calendarGrid.x + calendarColumn * fullCalendarWidth,
calendarGrid.y + calendarRow * fullCalendarHeight, calendarWidth, calendarHeight);
}
|
184285250_188
|
public static String l(long v, int width) {
return pad(Long.toString(v), width, true);
}
|
184301969_5
|
public static PathData findShortestPath(Graph graph, String sourceNodeIdentifier, String targetNodeIdentifier) throws ArrayStoreException {
return findShortestPath(graph, graph.getNode(sourceNodeIdentifier), graph.getNode(targetNodeIdentifier));
}
|
184386453_0
|
public String translate(String text, String lang) {
Translation translationResult = translateApi.translate(text, TranslateOption.targetLanguage(lang));
return translationResult.getTranslatedText();
}
|
184429237_0
|
@Override
public Void handleRequest(S3Event event, Context context)
{
logger = context.getLogger();
try {
initialize();
logger.log(String.format(
"Parameters: hostname [%s:%d] index [%s], username [%s], pipeline [%s], ssl/tls [%b]",
ELASTIC_HOSTNAME, ELASTIC_PORT, ELASTIC_INDEX, ELASTIC_USERNAME, ELASTIC_PIPELINE, ELASTIC_HTTPS));
RestHighLevelClient es = client(ELASTIC_HOSTNAME, ELASTIC_PORT, ELASTIC_USERNAME, ELASTIC_PASSWORD, ELASTIC_HTTPS);
AmazonS3 s3Client = getS3Client();
BulkProcessor processor = processor(es, BULK_ACTIONS, BULK_CONCURRENCY);
try {
process(es, s3Client, event, processor, ELASTIC_INDEX, ELASTIC_PIPELINE);
}
finally {
logger.log("Finished processing; flushing any remaining logs...");
processor.flush();
processor.awaitClose(60L, TimeUnit.SECONDS);
logger.log("Elasticsearch processor shut down");
}
}
catch (Exception e) {
logger.log(String.format("%s\n%s", e.getMessage(), trace(e)));
}
return null;
}
|
184471389_18
|
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
// Skip filter if there isn't any selector in the URL
String selector = slingRequest.getRequestPathInfo().getSelectorString();
if (selector == null) {
chain.doFilter(request, response);
return;
}
// Skip filter on AEM author
WCMMode wcmMode = WCMMode.fromRequest(request);
if (!WCMMode.DISABLED.equals(wcmMode)) {
chain.doFilter(request, response);
return;
}
Resource page = slingRequest.getResource();
LOGGER.debug("Checking sub-pages for {}", slingRequest.getRequestURI());
Resource subPage = UrlProviderImpl.toSpecificPage(page, selector);
if (subPage != null) {
RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(subPage);
dispatcher.forward(slingRequest, response);
return;
}
chain.doFilter(request, response);
}
|
184496771_3
|
@Override
public ProgressEvent<ResourceModel, CallbackContext> handleRequest(
final AmazonWebServicesClientProxy proxy,
final ResourceHandlerRequest<ResourceModel> request,
final CallbackContext callbackContext,
final Logger logger) {
final SesClient client = ClientBuilder.getClient();
final ResourceModel model = request.getDesiredResourceState();
try {
final DeleteConfigurationSetRequest deleteConfigurationSetRequest = DeleteConfigurationSetRequest.builder()
.configurationSetName(model.getName())
.build();
proxy.injectCredentialsAndInvokeV2(deleteConfigurationSetRequest, client::deleteConfigurationSet);
logger.log(String.format("%s [%s] deleted successfully",
ResourceModel.TYPE_NAME, getPrimaryIdentifier(model).toString()));
} catch (final ConfigurationSetDoesNotExistException e) {
throw new CfnNotFoundException(ResourceModel.TYPE_NAME, model.getName());
}
return ProgressEvent.defaultSuccessHandler(null);
}
|
184569540_75
|
public String getFullName() {
return getFullName(null);
}
|
184650438_19
|
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
final String PARAMETER_OFFSET = "_commerce_offset";
final String PARAMETER_LIMIT = "_commerce_limit";
final String PARAMETER_COMMERCE_TYPE = "_commerce_commerce_type";
final Config cfg = new Config(request.getResource().getChild(Config.DATASOURCE));
final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
final String itemRT = cfg.get("itemResourceType", String.class);
final long offset = ex.get(cfg.get("offset", "0"), long.class);
final long limit = ex.get(cfg.get("limit", "20"), long.class);
final String commerceType = ex.get(cfg.get("commerceType", "product"), String.class);
Map<String, Object> queryParameters = new HashMap<>(request.getParameterMap());
queryParameters.put(PARAMETER_OFFSET, String.valueOf(offset));
queryParameters.put(PARAMETER_LIMIT, String.valueOf(limit));
queryParameters.put(PARAMETER_COMMERCE_TYPE, commerceType);
final String rootPath = request.getParameter("root");
String rootCategoryId = new CatalogSearchSupport(request.getResourceResolver()).findCategoryId(rootPath);
if (rootCategoryId != null) {
queryParameters.put(CATEGORY_ID_PARAMETER, rootCategoryId);
queryParameters.put(CATEGORY_PATH_PARAMETER, rootPath);
}
String queryString = new ObjectMapper().writeValueAsString(queryParameters);
try {
Iterator<Resource> virtualResults = request.getResourceResolver().findResources(queryString, VIRTUAL_PRODUCT_QUERY_LANGUAGE);
final DataSource ds = new SimpleDataSource(new TransformIterator<>(virtualResults, r -> new ResourceWrapper(r) {
public String getResourceType() {
return itemRT;
}
}));
request.setAttribute(DataSource.class.getName(), ds);
} catch (Exception x) {
response.sendError(500, x.getMessage());
LOGGER.error("Error finding resources", x);
}
}
|
185170825_0
|
public long nextId() {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new IllegalStateException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// the sequence is overflowed
timestamp = blockUtilNextMillis();
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
return ((timestamp - startEpoch) << timestampLeftShift) |
(dataCenterId << dataCenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
|
185218009_0
|
public static AdditionalBuildCommands load(Path file) throws IOException {
logger.entering(file);
AdditionalBuildCommands result = new AdditionalBuildCommands();
result.contents = new HashMap<>();
try (BufferedReader reader = Files.newBufferedReader(file)) {
List<String> buffer = new ArrayList<>();
String currentSection = null;
String line;
while ((line = reader.readLine()) != null) {
logger.finest(line);
String sectionStart = result.checkForSectionHeader(line);
//skip any lines that come before the first section header
if (currentSection != null && sectionStart == null) {
//collect lines inside current section
buffer.add(line);
} else if (currentSection != null) {
//while in a section, found next section start (save last section, and start new section)
logger.fine("IMG-0015", buffer.size(), currentSection);
result.contents.put(currentSection, buffer);
buffer = new ArrayList<>();
currentSection = sectionStart;
} else if (sectionStart != null) {
//current section was null, but found new section start
currentSection = sectionStart;
}
}
if (currentSection != null && !buffer.isEmpty()) {
//finished reading file, store the remaining lines that were read for the section
logger.fine("IMG-0015", buffer.size(), currentSection);
result.contents.put(currentSection, buffer);
}
} catch (IOException ioe) {
logger.severe("IMG-0013", file.getFileName());
throw ioe;
}
logger.exiting();
return result;
}
|
185263418_0
|
@NotNull
public static SchemaTransformer transform(final GraphQLSchema schema) {
return new SchemaTransformer(schema);
}
|
185267261_2
|
@CrossOrigin
@RequestMapping(value = L10NAPIV1.UPDATE_TRANSLATION_L10N, method = RequestMethod.POST, produces = { API.API_CHARSET })
@ResponseStatus(HttpStatus.OK)
public APIResponseDTO updateTranslation(
@RequestBody UpdateTranslationDTO updateTranslationDTO,
@PathVariable(APIParamName.PRODUCT_NAME) String productName,
@PathVariable(APIParamName.VERSION) String version, HttpServletRequest request) {
LOGGER.info("The request url is "
+ request.getRequestURL()
+ (request.getQueryString() == null ? "" : "?"
+ request.getQueryString()));
ObjectMapper mapper = new ObjectMapper();
String requestJson = "";
try {
requestJson = mapper.writeValueAsString(updateTranslationDTO);
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
LOGGER.info("The request content is {}", requestJson);
APIResponseDTO response = new APIResponseDTO();
if (StringUtils.isEmpty(updateTranslationDTO)
|| StringUtils.isEmpty(updateTranslationDTO.getData())
|| StringUtils.isEmpty(updateTranslationDTO.getData()
.getTranslation())) {
response.setResponse(APIResponseStatus.BAD_REQUEST);
return response;
}
UpdateTranslationDataDTO updateTranslationDataDTO = updateTranslationDTO
.getData();
List<TranslationDTO> translationList = updateTranslationDataDTO
.getTranslation();
if (StringUtils.isEmpty(updateTranslationDataDTO.getProductName())
|| !updateTranslationDataDTO.getProductName().equals(
productName)) {
response.setResponse(APIResponseStatus.BAD_REQUEST);
return response;
}
if (StringUtils.isEmpty(updateTranslationDataDTO.getVersion())
|| !updateTranslationDataDTO.getVersion().equals(version)) {
response.setResponse(APIResponseStatus.BAD_REQUEST);
return response;
}
List<ComponentMessagesDTO> componentMessagesDTOList = new ArrayList<ComponentMessagesDTO>();
for (TranslationDTO translationDTO : translationList) {
if (StringUtils.isEmpty(translationDTO)) {
response.setResponse(APIResponseStatus.BAD_REQUEST);
return response;
}
ComponentMessagesDTO componentMessagesDTO = new ComponentMessagesDTO();
componentMessagesDTO.setProductName(updateTranslationDataDTO
.getProductName());
componentMessagesDTO.setVersion(updateTranslationDataDTO
.getVersion());
componentMessagesDTO.setComponent(translationDTO.getComponent());
componentMessagesDTO.setLocale(translationDTO.getLocale());
componentMessagesDTO.setMessages(translationDTO.getMessages());
componentMessagesDTO.setId(System.currentTimeMillis());
componentMessagesDTOList.add(componentMessagesDTO);
}
List<TranslationDTO> translationDTOList = null;
try {
translationDTOList = translationSyncServerService
.updateBatchTranslation(componentMessagesDTOList);
} catch (L10nAPIException e) {
response.setResponse(APIResponseStatus.INTERNAL_SERVER_ERROR);
LOGGER.error(e.getMessage(), e);
}
if (translationDTOList != null && translationDTOList.size() > 0) {
response.setData(translationDTOList);
response.setResponse(APIResponseStatus.OK);
}
saveCreationInfo(updateTranslationDTO);
return response;
}
|
185394887_8
|
public static <O> MultiArray<O> wrap(final O elements, final int[] dimensions) {
return wrap(elements, 0, dimensions);
}
|
185475705_6
|
private RawSchema parse() throws SyntaxError {
RawSchemaBuilder rawSchemaBuilder = new RawSchemaBuilder();
nextToken(); // first token
while (currentToken != TokenType.EOF) {
switch (currentToken) {
case INTERFACE:
rawSchemaBuilder.addInterface(parseEntity());
break;
case ENTITY:
rawSchemaBuilder.addEntity(parseEntity());
break;
}
}
return rawSchemaBuilder.build();
}
|
185565206_0
|
public static String findConnectorLibPath(String dbType) {
DbType type = DbType.valueOf(dbType);
URL resource = Thread.currentThread().getContextClassLoader().getResource("logback.xml");
_LOG.info("jar resource: {}", resource);
if (resource != null) {
try {
File file = new File(resource.toURI().getRawPath() + "/../lib/" + type.getConnectorJarFile());
return URLDecoder.decode(file.getCanonicalPath(), Charset.forName("UTF-8").displayName());
} catch (Exception e) {
throw new RuntimeException("找不到驱动文件,请联系开发者");
}
} else {
throw new RuntimeException("lib can't find");
}
}
|
185576294_6
|
@Override
public synchronized void event(
long gen, String eventName, String tagName, long tagId, long nanoTime) {
writeNnss(gen + EVENT_N2S2_OP, nanoTime, tagId, eventName, tagName);
}
|
185739179_51
|
@Override
public void execute(SensorContext context) {
if (shouldExecuteOnProject()) {
for (RuleViolation violation : executor.execute()) {
pmdViolationRecorder.saveViolation(violation, context);
}
}
}
|
185796725_67
|
public final static char toUpperAscii(char c) {
if (isLowercaseAlpha(c)) {
c -= (char) 0x20;
}
return c;
}
|
185821779_6
|
@Override
public OAuthUser take() {
var user = userSessionRepository.take().getUser();
if (user instanceof OAuthUser) {
return (OAuthUser) user;
}
throw new NoUserFoundException("No OAuth users found in the repository.");
}
|
185828241_1
|
public boolean exists(long id) {
String sqlQuery = "select count(*) from employees where id = ?";
//noinspection ConstantConditions: return value is always an int, so NPE is impossible here
int result = jdbcTemplate.queryForObject(sqlQuery, Integer.class, id);
return result == 1;
}
|
185871137_25
|
@SuppressWarnings("unchecked")
@Override
public <T> T decode(Response response, Class<T> type) {
try {
if (byte[].class.equals(type)) {
return (T) response.toByteArray();
} else if (InputStream.class.isAssignableFrom(type)) {
/* return a byte array input stream */
return (T) response.body();
}
/* no body */
if (response == null || response.body() == null) {
return null;
}
/* dispatch to the sub classes */
return this.decodeInternal(response, type);
} catch (Exception ex) {
throw new FeignException("Error decoding the Response", ex,
this.getClass().getName() + "#decode");
}
}
|
186128056_7
|
@DeleteMapping("/{id}")
public ResponseEntity<Void> resign(@PathVariable long id) {
if (employeeRepository.findById(id).isPresent()) {
employeeRepository.deleteById(id);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
}
}
|
186282860_2
|
public String convert(String input, boolean capitalize) {
return transliterate(input, capitalize);
}
|
186347363_1
|
public void revokeToken(TokenTypeHint tokenTypeHint, String token, String clientId) {
if (TokenTypeHint.refresh_token.equals(tokenTypeHint)) {
revokeRefreshToken(token, clientId);
} else {
revokeAccessToken(token, clientId);
}
}
|
186361323_1
|
public static String firstCharToUpperCase(String str) {
char firstChar = str.charAt(0);
if (firstChar >= 'a' && firstChar <= 'z') {
char[] arr = str.toCharArray();
arr[0] -= ('a' - 'A');
return new String(arr);
}
return str;
}
|
186387230_2
|
;
|
186525996_1
|
public Friend() {
}
|
186556620_53
|
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
|
186642789_1
|
public EmployeeFixed findEmployeeById(String id)
{
return this.employees.stream()
.filter(e -> e.getId().equals(id))
.findFirst()
.orElse(null);
}
|
186955716_0
|
public Flux<Reservation> getAllReservations() {
return this.client.get()
.uri("http://localhost:8080/reservations")
.retrieve()
.bodyToFlux(Reservation.class);
}
|
186978836_31
|
public static String getKeyTenant(String dataId, String group, String tenant) {
return doGetKey(dataId, group, tenant);
}
|
187556247_613
|
public void openFile() {
openFile( false );
}
|
187590023_3
|
@CacheEvict(value = "people", key = "#id")
@Override
public void remove(Long id) {
log.info("删除了id、key为" + id + "的数据缓存");
}
|
187595602_12
|
static ProxyProvider createInternalProxy(final DeploymentConfiguration config, final RegistryQueryResult queryResult) throws IOException {
final String autoConfigUrl = queryResult.getValue(AUTO_CONFIG_URL_VAL);
if (autoConfigUrl != null) {
LOG.debug("Registry value '{}' specified. Will use pac based proxy with pac url '{}'.", AUTO_CONFIG_URL_VAL, autoConfigUrl);
return new PacBasedProxyProvider(new URL(autoConfigUrl), PacProxyCache.createFor(config));
} else {
final boolean proxyEnabledValue = queryResult.getValueAsBoolean(PROXY_ENABLED_VAL);
if (proxyEnabledValue) {
final String proxyServerValue = queryResult.getValue(PROXY_SERVER_REGISTRY_VAL);
if (proxyServerValue != null) {
LOG.debug("Proxy server(s) defined ( registry value '" + PROXY_SERVER_REGISTRY_VAL + "'). Will use configured proxy.");
final ProxyConfigurationImpl proxyConfiguration = getProxyConfiguration(queryResult);
return new ConfigBasedProvider(proxyConfiguration);
} else {
//TODO: is this correct?
LOG.debug("No proxy server defined ( registry value '" + PROXY_SERVER_REGISTRY_VAL + "'). Will use direct proxy.");
return DirectProxyProvider.getInstance();
}
} else {
LOG.debug("Proxy disabled ( registry value '" + PROXY_ENABLED_VAL + "'). Will use direct proxy.");
return DirectProxyProvider.getInstance();
}
}
}
|
187648701_0
|
protected static void generateDiff(OpObject editObject, String field, Map<String, Object> change,
Map<String, Object> current, Map<String, Object> oldM, Map<String, Object> newM) {
TreeSet<String> removedTags = new TreeSet<>(oldM.keySet());
removedTags.removeAll(newM.keySet());
for(String removedTag : removedTags) {
change.put(field + addQuotes(removedTag), OpBlockChain.OP_CHANGE_DELETE);
current.put(field + addQuotes(removedTag), oldM.get(removedTag));
}
for(String tag : newM.keySet()) {
Object po = oldM.get(tag);
Object no = newM.get(tag);
if(!OUtils.equals(po, no)) {
change.put(field + addQuotes(tag), set(no));
if(po != null) {
current.put(field + addQuotes(tag), po);
}
}
}
}
|
187765477_5
|
@Override
public LoadedResource loadIfModified(HttpResourceId resourceId, SourceVersion version) {
var cacheControl = resourceId.getCacheControl();
if (version == SourceVersion.EMPTY || cacheControl == CacheControlStrategy.NONE) {
return loadResource(resourceId);
} else if (cacheControl == CacheControlStrategy.ETAG) {
return loadResource(resourceId, singletonList(new BasicHeader(HttpHeaders.IF_NONE_MATCH, version.val().toString())));
} else if (cacheControl == CacheControlStrategy.IF_MODIFIED_SINCE) {
return loadResource(resourceId, singletonList(new BasicHeader(HttpHeaders.IF_MODIFIED_SINCE, lastModifiedValue(version.val()))));
} else if (cacheControl == CacheControlStrategy.LAST_MODIFIED_HEAD ||
cacheControl == CacheControlStrategy.ETAG_HEAD) {
if (isChanged(resourceId, version)) {
return loadResource(resourceId);
}
}
return null;
}
|
187767967_2
|
@Override
public boolean isCollection(Type type) {
if (type instanceof Class)
{
var clazz = (Class)type;
if (clazz.isArray()) {
return true;
}
if (Collection.class.isAssignableFrom(clazz)) {
return true;
}
}
else if (type instanceof ParameterizedType)
{
return isCollection(((ParameterizedType) type).getRawType());
}
return false;
}
|
187873041_1
|
@Override
public Collection<IPermissionGroup> getGroups() {
for (IPermissionGroup permissionGroup : this.permissionGroupsMap.values()) {
if (this.testPermissionGroup(permissionGroup)) {
this.updateGroup(permissionGroup);
}
}
return this.permissionGroupsMap.values();
}
|
187946264_2
|
public static <T extends ServerResponse> RouterFunction<T> route(
RequestPredicate predicate, HandlerFunction<T> handlerFunction) {
return new DefaultRouterFunction<>(predicate, handlerFunction);
}
|
187972412_38
|
@Override
public List<MessageView> queryMessageByTopic(String topic, final long begin, final long end) {
DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(MixAll.TOOLS_CONSUMER_GROUP, null);
List<MessageView> messageViewList = Lists.newArrayList();
try {
String subExpression = "*";
consumer.start();
Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues(topic);
for (MessageQueue mq : mqs) {
long minOffset = consumer.searchOffset(mq, begin);
long maxOffset = consumer.searchOffset(mq, end);
READQ:
for (long offset = minOffset; offset <= maxOffset; ) {
try {
if (messageViewList.size() > 2000) {
break;
}
PullResult pullResult = consumer.pull(mq, subExpression, offset, 32);
offset = pullResult.getNextBeginOffset();
switch (pullResult.getPullStatus()) {
case FOUND:
List<MessageView> messageViewListByQuery = Lists.transform(pullResult.getMsgFoundList(), new Function<MessageExt, MessageView>() {
@Override
public MessageView apply(MessageExt messageExt) {
messageExt.setBody(null);
return MessageView.fromMessageExt(messageExt);
}
});
List<MessageView> filteredList = Lists.newArrayList(Iterables.filter(messageViewListByQuery, new Predicate<MessageView>() {
@Override
public boolean apply(MessageView messageView) {
if (messageView.getStoreTimestamp() < begin || messageView.getStoreTimestamp() > end) {
logger.info("begin={} end={} time not in range {} {}", begin, end, messageView.getStoreTimestamp(), new Date(messageView.getStoreTimestamp()).toString());
}
return messageView.getStoreTimestamp() >= begin && messageView.getStoreTimestamp() <= end;
}
}));
messageViewList.addAll(filteredList);
break;
case NO_MATCHED_MSG:
case NO_NEW_MSG:
case OFFSET_ILLEGAL:
break READQ;
}
}
catch (Exception e) {
break;
}
}
}
Collections.sort(messageViewList, new Comparator<MessageView>() {
@Override
public int compare(MessageView o1, MessageView o2) {
if (o1.getStoreTimestamp() - o2.getStoreTimestamp() == 0) {
return 0;
}
return (o1.getStoreTimestamp() > o2.getStoreTimestamp()) ? -1 : 1;
}
});
return messageViewList;
}
catch (Exception e) {
throw Throwables.propagate(e);
}
finally {
consumer.shutdown();
}
}
|
188055485_6
|
@Override
public CommonResult listItemsByCollectionIdAndProjectId(ProjectParam projectParam){
Integer collectionId = projectParam.getCollectionId();
Integer projectId = projectParam.getProjectId();
List<HashMap> projectDetails;
if(collectionId.toString().startsWith("2")){
projectDetails = inspectionMapper.listItems(collectionId, projectId);
}
else if(collectionId.toString().startsWith("3")){
projectDetails= examinationMapper.listItems(collectionId, projectId);
}
else
return CommonResult.fail(E_801);
return CommonResult.success(projectDetails);
}
|
188058370_0
|
public static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
|
188081982_21
|
public Hand hand(CardSet cardSet) {
List<Card> handCards = cardSet.getSortedCards();
// Figure our high card by same color
SUIT colorCandidate = handCards.get(0).getSuit();
boolean allSameColor = handCards.stream()
.allMatch(card -> card.getSuit().equals(colorCandidate));
if (allSameColor){
// Check for straight flush
int firstOrdinal = handCards.get(0).getRank().ordinal();
int secondOrdinal = handCards.get(1).getRank().ordinal();
int thirdOrdinal = handCards.get(2).getRank().ordinal();
int fourthOrdinal = handCards.get(3).getRank().ordinal();
int fifthOrdinal = handCards.get(4).getRank().ordinal();
if (firstOrdinal + 1 == secondOrdinal
&& secondOrdinal + 1 == thirdOrdinal
&& thirdOrdinal + 1 == fourthOrdinal
&& fourthOrdinal + 1 == fifthOrdinal)
return new Hand(STRAIGHT_FLUSH, handCards);
else
return new Hand(FLUSH, handCards);
}
else{
// Check for possible x of a kind
Map<RANK, List<Card>> cardsByRank = handCards.stream().collect(groupingBy(Card::getRank));
List<RANK> ranks = cardsByRank.keySet()
.stream()
.collect(Collectors.toList());
if (ranks.size() == 5){
// Check for straight
int firstOrdinal = handCards.get(0).getRank().ordinal();
int secondOrdinal = handCards.get(1).getRank().ordinal();
int thirdOrdinal = handCards.get(2).getRank().ordinal();
int fourthOrdinal = handCards.get(3).getRank().ordinal();
int fifthOrdinal = handCards.get(4).getRank().ordinal();
if (firstOrdinal + 1 == secondOrdinal
&& secondOrdinal + 1 == thirdOrdinal
&& thirdOrdinal + 1 == fourthOrdinal
&& fourthOrdinal + 1 == fifthOrdinal)
return new Hand(STRAIGHT, handCards);
}
if (ranks.size() == 2){
// Look for four of a kind
if (cardsByRank.get(ranks.get(0)).size() == 4 ||
cardsByRank.get(ranks.get(1)).size() == 4)
return new Hand(FOUR_OF_A_KIND, handCards);
// Look for full house
else {
return new Hand(FULL_HOUSE, handCards);
}
} else if (ranks.size() == 3){
// Look for 3 of a kind
if (cardsByRank.get(ranks.get(0)).size() == 3 ||
cardsByRank.get(ranks.get(1)).size() == 3 ||
cardsByRank.get(ranks.get(2)).size() == 3)
return new Hand(THREE_OF_A_KIND, handCards);
// Look for 2 pairs
if (cardsByRank.get(ranks.get(0)).size() == 1 ||
cardsByRank.get(ranks.get(1)).size() == 1 ||
cardsByRank.get(ranks.get(2)).size() == 1)
return new Hand(TWO_PAIRS, handCards);
} else if (ranks.size() == 4){
return new Hand(ONE_PAIR, handCards);
} else {
return new Hand(HIGH_CARD, handCards);
}
}
return new Hand(HIGH_CARD, handCards);
}
|
188223092_16
|
public void addModel(final String modeluri, final EObject model) throws IOException {
final Resource resource = resourceSet.createResource(createURI(modeluri));
resourceSet.getResources().add(resource);
resource.getContents().add(model);
resource.save(null);
}
|
188228592_362
|
public static Builder newBuilder(String name) {
return new Builder(name);
}
|
188229074_0
|
@Override
@RolesAllowed(ApplicationAccessControlConfig.PERMISSION_SAVE_KEY_LIST)
public KeyListEto saveKeyList(KeyListEto keyList) {
Objects.requireNonNull(keyList, "keyList");
KeyListEntity keyListEntity = getBeanMapper().map(keyList, KeyListEntity.class);
KeyList entity = keyList;
Long id = keyList.getId();
if (id != null) {
KeyListEntity keyListFromDb = getKeyListRepository().find(id);
verifyKeyNotModified(keyList, keyListFromDb);
entity = keyListFromDb;
}
String permission = entity.getPermission();
if ((permission != null) && !permission.isEmpty()) {
requireAnyPermission(permission, ApplicationAccessControlConfig.GROUP_ADMIN);
}
KeyListEntity resultEntity = getKeyListRepository().save(keyListEntity);
LOG.debug("KeyList with id '{}' has been created.", resultEntity.getId());
return getBeanMapper().map(resultEntity, KeyListEto.class);
}
|
188279001_0
|
public PokemonResponse assemble(Pokemon data) {
return PokemonResponse.builder()
.name(data.getName())
.abilities(data.getAbilities())
.baseExperience(data.getBaseExperience())
.weight(data.getWeight())
.height(data.getHeight())
.build();
}
|
188292946_0
|
public static <T> T get(Class<T> supplier) {
return getSupplier(requireNonNull(supplier, "supplier is required"));
}
|
188402392_0
|
@Override
public byte[] getValue(List<String> tagNames, String returnTimestamp, boolean excludeNullValue,
String nullValueString) throws ProcessException {
try {
if (opcClient == null) {
throw new ProcessException("OPC Client is null. OPC UA service was not enabled properly.");
}
// TODO: Throw more descriptive exception when parsing fails
ArrayList<NodeId> nodeIdList = new ArrayList<>();
tagNames.forEach((tagName) -> nodeIdList.add(NodeId.parse(tagName)));
List<DataValue> rvList = opcClient.readValues(0, TimestampsToReturn.Both, nodeIdList).get();
StringBuilder serverResponse = new StringBuilder();
for (int i = 0; i < tagNames.size(); i++) {
String valueLine;
valueLine = writeCsv(tagNames.get(i), returnTimestamp, rvList.get(i), excludeNullValue, nullValueString);
serverResponse.append(valueLine);
}
return serverResponse.toString().trim().getBytes();
} catch (Exception e) {
throw new ProcessException(e);
}
}
|
188429680_19
|
public boolean isMultiSentenceInstruction() {
int fromIndex = 0;
int dotInd;
while ((dotInd = instructionUtterance.indexOf(".", fromIndex)) >= 0){
if (!instructionUtterance.substring(dotInd + 1).trim().isEmpty() && // The dot isn't the end of the utterance.
StringUtils.isBlank(instructionUtterance.substring(dotInd + 1,dotInd + 2))) // the character after the dot is a whitespace.
return true;
fromIndex =dotInd+1;
}
return false;
}
|
188534881_1
|
Optional<String> select(String version) {
if (version.isEmpty()) {
// of nullable since map could be empty
return Optional.ofNullable(m.lastEntry().getValue());
}
// strip "v" at head of string
version = version.substring(1);
int separatorIndex = version.indexOf(".");
if (separatorIndex != -1) {
// major, minor both given
// example "v2.1"
// do exact match
String[] mm = version.split("[.]");
int major = Integer.parseInt(mm[0]);
int minor = Integer.parseInt(mm[1]);
return Optional.ofNullable(m.get(new APIVersion(major, minor)));
}
// only major given, find highest minor
int major = Integer.parseInt(version);
Map.Entry<APIVersion, String> entry = m.floorEntry(new APIVersion(major, Integer.MAX_VALUE));
if (entry == null || entry.getKey().major != major) {
return Optional.empty();
}
return Optional.of(entry.getValue());
}
|
188592933_0
|
public Optional<Long> nextDelay() {
if (lastAttemptIndex == 0) {
lastAttemptIndex++;
return Optional.of(0L);
}
if (genericRetry.getMaxAttempts() > -1 && lastAttemptIndex >= genericRetry.getMaxAttempts()) {
return Optional.empty();
}
if (lastAttemptIndex > 1) {
currentInterval = (long) (currentInterval * genericRetry.getIntervalMultiplier());
if (genericRetry.getMaxInterval() > -1 && currentInterval > genericRetry.getMaxInterval()) {
currentInterval = genericRetry.getMaxInterval();
}
}
lastAttemptIndex++;
return Optional.of(currentInterval);
}
|
188643956_0
|
public static Inventory create(String productId, String productName) {
return Inventory.builder()
.id(newUuid())
.productId(productId)
.productName(productName)
.remains(0)
.createdAt(Instant.now())
.build();
}
|
188644064_0
|
public static Product create(String name, String description, BigDecimal price, String categoryId) {
Product product = Product.builder()
.id(newUuid())
.name(name)
.description(description)
.price(price)
.createdAt(Instant.now())
.inventory(0)
.categoryId(categoryId)
.build();
product.raiseEvent(new ProductCreatedEvent(product.getId(), name, description, price, product.getCreatedAt()));
return product;
}
|
188857939_0
|
public void upload(Object openAPI, boolean merge) throws IOException {
Map<String, Object> send = new HashMap<>(4);
send.put("type", "swagger");
send.put("token", projectToken);
send.put("merge", merge);
send.put("json", mapper.writeValueAsString(openAPI));
HttpClientUtil.getHttpclient().execute(getHttpPost(yapiUrl + IMPUT, mapper.writeValueAsString(send)));
}
|
189010032_0
|
@Override
@Cacheable(cacheNames = "UserDetails",
unless = "#username == null",
cacheManager = "JDKCacheManager")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Assert.notNull(username, "用户名不能为空");
User user = userService.selectByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<Role> roles = roleService.selectByUser(user);
Assert.notEmpty(roles, "用户没有被分配角色");
List<Menu> menus = menuService.selectByRoles(roles);
Assert.notEmpty(menus, "角色没有被分配菜单");
return UserUtils.convertToUserDetails(user, roles, menus);
}
|
189012247_10
|
@Override
public List<IKafkaMessageHandler<T>> getForTopicOrFail(String topic) {
List<IKafkaMessageHandler<T>> topicKafkaMessageHandlers = getForTopic(topic);
if (topicKafkaMessageHandlers.isEmpty()) {
throw new IllegalStateException("No handler found for topic '" + topic + "'.");
}
return topicKafkaMessageHandlers;
}
|
189027594_176
|
@Override
public String decryptCardCode(String encryptCode) throws WxErrorException {
JsonObject param = new JsonObject();
param.addProperty("encrypt_code", encryptCode);
String responseContent = this.wxMpService.post(CARD_CODE_DECRYPT, param.toString());
JsonElement tmpJsonElement = new JsonParser().parse(responseContent);
JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
JsonPrimitive jsonPrimitive = tmpJsonObject.getAsJsonPrimitive("code");
return jsonPrimitive.getAsString();
}
|
189191730_26
|
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(pattern.pattern(), patternType);
return result;
}
|
189204070_1
|
@Override
public List<Room> findRoomsByType(String type) {
if (roomTypes.contains(type)) {
return roomRepo.findRoomsByRoomType(type);
} else {
throw new RoomServiceException("Room type: " + type + " not found!");
}
}
|
189356507_1
|
@Override
protected void closeClient() {
if (client != null) {
// close the producer.
while (true) {
try {
client.close();
break;
} catch (InterruptedException e) {
// ignore interrupt signal to avoid io thread leaking.
} catch (ProducerException e) {
LOGGER.warn("Exception caught when closing client", e);
break;
}
}
client = null;
}
}
|
189556566_0
|
public static String getSizeString(long size){
if(size < 1024){
return String.format(Locale.getDefault(), "%d B", size);
}else if(size < 1024 * 1024){
float sizeK = size / 1024f;
return String.format(Locale.getDefault(), "%.2f KB", sizeK);
}else if(size < 1024 * 1024 * 1024){
float sizeM = size / (1024f * 1024f);
return String.format(Locale.getDefault(), "%.2f MB", sizeM);
}else if(size / 1024 < 1024 * 1024 * 1024){
float sizeG = size / (1024f * 1024f * 1024f);
return String.format(Locale.getDefault(), "%.2f GB", sizeG);
}
return null;
}
|
189605649_51
|
@SuppressWarnings("WeakerAccess")
public boolean containsAssetType(MediaAssetType assetType) {
return mediaAssetTypes.isEmpty()
|| mediaAssetTypes.contains(assetType)
|| mediaAssetTypes.contains(MediaAssetType.All);
}
|
189734293_0
|
@Override
public String toString() {
return "MethodEvent{" +
"className='" + className + '\'' +
", methodAccessFlag=" + methodAccessFlag +
", methodName='" + methodName + '\'' +
", methodDesc='" + methodDesc + '\'' +
", isEnter=" + isEnter +
", eventTimeMillis=" + eventTimeMillis +
", type=" + type +
'}';
}
|
189841989_2
|
public static <T> Stream<List<Optional<T>>> combinations(List<T> list) {
long n = (long) Math.pow(2, list.size());
return StreamSupport.stream(new Spliterators.AbstractSpliterator<>(n, Spliterator.SIZED) {
long i = 0;
@Override
public boolean tryAdvance(Consumer<? super List<Optional<T>>> action) {
if (i < n) {
List<Optional<T>> out = new ArrayList<>(Long.bitCount(i));
for (int bit = 0; bit < list.size(); bit++) {
if ((i & (1 << bit)) != 0) {
out.add(Optional.of(list.get(bit)));
} else {
out.add(Optional.empty());
}
}
action.accept(out);
++i;
return true;
} else {
return false;
}
}
}, false);
}
|
189845277_4
|
public static Builder route() {
return new RouterFunctionBuilder();
}
|
190100311_0
|
@Nonnull
@Override
public String create() throws IdentityException {
Validate.notNull(account.getUsername(), "username must be set");
Validate.notNull(account.getFirstName(), "first name must be set");
Validate.notNull(account.getLastName(), "last name must be set");
Validate.notNull(account.getPasswordHash(), "password must be set");
Validate.notNull(account.getEmail(), "email must be set");
Validate.notNull(account.getDescription(), "description must be set");
long nowMs = systemService.currentTimeMillis();
account.setCreateTs(nowMs);
account.setUpdateTs(nowMs);
account.setEmailVerified(false);
storage.createAccount(account);
return account.getUsername();
}
|
190168097_216
|
@ChaosExperiment(experimentType = ExperimentType.STATE)
public void restartInstance (Experiment experiment) {
experiment.setCheckContainerHealth(() -> awsRDSPlatform.getInstanceStatus(dbInstanceIdentifier));
awsRDSPlatform.restartInstance(dbInstanceIdentifier);
}
|
190197552_1
|
public URI getUri() {
return this.uri;
}
|
190209753_0
|
public static double pow2(int p) {
if (p < 0) {
return 1.0 / (1L << -p);
}
if (p > 0) {
return 1L << p;
}
return 1.0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.