_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q177500
ObservableServlet.write
test
public static Observable<Void> write(final Observable<byte[]> data, final ServletOutputStream out) { return Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { Observable<Void> events = create(out).onBackpressureBuffer(); Observable<Void> writeobs = Observable.zip(data, events, (b, aVoid) -> { try { out.write(b); } catch (IOException ioe) { Exceptions.propagate(ioe); } return null; }); writeobs.subscribe(subscriber); } }); }
java
{ "resource": "" }
q177501
MetricsServiceImpl.addTags
test
@Override public Observable<Void> addTags(Metric<?> metric, Map<String, String> tags) { try { checkArgument(tags != null, "Missing tags"); checkArgument(isValidTagMap(tags), "Invalid tags; tag key is required"); } catch (Exception e) { return Observable.error(e); } return dataAccess.insertIntoMetricsTagsIndex(metric, tags).concatWith(dataAccess.addTags(metric, tags)) .toList().map(l -> null); }
java
{ "resource": "" }
q177502
MetricsServiceImpl.verifyAndCreateTempTables
test
public void verifyAndCreateTempTables() { ZonedDateTime currentBlock = ZonedDateTime.ofInstant(Instant.ofEpochMilli(DateTimeService.now.get().getMillis()), UTC) .with(DateTimeService.startOfPreviousEvenHour()); ZonedDateTime lastStartupBlock = currentBlock.plus(6, ChronoUnit.HOURS); verifyAndCreateTempTables(currentBlock, lastStartupBlock).await(); }
java
{ "resource": "" }
q177503
NamespaceListener.getNamespaceId
test
public String getNamespaceId(String namespaceName) { return namespaces.computeIfAbsent(namespaceName, n -> getProjectId(namespaceName, token)); }
java
{ "resource": "" }
q177504
TokenAuthenticator.isQuery
test
private boolean isQuery(HttpServerExchange serverExchange) { if (serverExchange.getRequestMethod().toString().equalsIgnoreCase("GET") || serverExchange.getRequestMethod().toString().equalsIgnoreCase("HEAD")) { // all GET requests are considered queries return true; } else if (serverExchange.getRequestMethod().toString().equalsIgnoreCase("POST")) { // some POST requests may be queries we need to check. if (postQuery != null && postQuery.matcher(serverExchange.getRelativePath()).find()) { return true; } else { return false; } } else { return false; } }
java
{ "resource": "" }
q177505
TokenAuthenticator.sendAuthenticationRequest
test
private void sendAuthenticationRequest(HttpServerExchange serverExchange, PooledConnection connection) { AuthContext context = serverExchange.getAttachment(AUTH_CONTEXT_KEY); String verb = getVerb(serverExchange); String resource; // if we are not dealing with a query if (!isQuery(serverExchange)) { // is USER_WRITE_ACCESS is disabled, then use the legacy check. // Otherwise check using the actual resource (eg 'hawkular-metrics', 'hawkular-alerts', etc) if (USER_WRITE_ACCESS.equalsIgnoreCase("true")) { resource = RESOURCE; } else { resource= resourceName; } } else { resource = RESOURCE; } context.subjectAccessReview = generateSubjectAccessReview(context.tenant, verb, resource); ClientRequest request = buildClientRequest(context); context.clientRequestStarting(); connection.sendRequest(request, new RequestReadyCallback(serverExchange, connection)); }
java
{ "resource": "" }
q177506
TokenAuthenticator.getVerb
test
private String getVerb(HttpServerExchange serverExchange) { // if its a query type verb, then treat as a GET type call. if (isQuery(serverExchange)) { return VERBS.get(GET); } else { String verb = VERBS.get(serverExchange.getRequestMethod()); if (verb == null) { log.debugf("Unhandled http method '%s'. Checking for read access.", serverExchange.getRequestMethod()); verb = VERBS_DEFAULT; } return verb; } }
java
{ "resource": "" }
q177507
TokenAuthenticator.generateSubjectAccessReview
test
private String generateSubjectAccessReview(String namespace, String verb, String resource) { ObjectNode objectNode = objectMapper.createObjectNode(); objectNode.put("apiVersion", "v1"); objectNode.put("kind", KIND); objectNode.put("resource", resource); objectNode.put("verb", verb); objectNode.put("namespace", namespace); return objectNode.toString(); }
java
{ "resource": "" }
q177508
TokenAuthenticator.onRequestResult
test
private void onRequestResult(HttpServerExchange serverExchange, PooledConnection connection, boolean allowed) { connectionPools.get(serverExchange.getIoThread()).release(connection); // Remove attachment early to make it eligible for GC AuthContext context = serverExchange.removeAttachment(AUTH_CONTEXT_KEY); apiLatency.update(context.getClientResponseTime(), NANOSECONDS); authLatency.update(context.getLatency(), NANOSECONDS); if (allowed) { serverExchange.dispatch(containerHandler); } else { endExchange(serverExchange, FORBIDDEN); } }
java
{ "resource": "" }
q177509
TokenAuthenticator.onRequestFailure
test
private void onRequestFailure(HttpServerExchange serverExchange, PooledConnection connection, IOException e, boolean retry) { log.debug("Client request failure", e); IoUtils.safeClose(connection); ConnectionPool connectionPool = connectionPools.get(serverExchange.getIoThread()); connectionPool.release(connection); AuthContext context = serverExchange.getAttachment(AUTH_CONTEXT_KEY); if (context.retries < MAX_RETRY && retry) { context.retries++; PooledConnectionWaiter waiter = createWaiter(serverExchange); if (!connectionPool.offer(waiter)) { endExchange(serverExchange, INTERNAL_SERVER_ERROR, TOO_MANY_PENDING_REQUESTS); } } else { endExchange(serverExchange, INTERNAL_SERVER_ERROR, CLIENT_REQUEST_FAILURE); } }
java
{ "resource": "" }
q177510
ConfigurationService.init
test
public void init(RxSession session) { this.session = session; findConfigurationGroup = session.getSession() .prepare("SELECT name, value FROM sys_config WHERE config_id = ?") .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); findConfigurationValue = session.getSession() .prepare("SELECT value FROM sys_config WHERE config_id = ? AND name= ?") .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); updateConfigurationValue = session.getSession().prepare( "INSERT INTO sys_config (config_id, name, value) VALUES (?, ?, ?)") .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); deleteConfigurationValue = session.getSession().prepare( "DELETE FROM sys_config WHERE config_id =? and name = ?") .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); deleteConfiguration = session.getSession().prepare( "DELETE FROM sys_config WHERE config_id = ?") .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); }
java
{ "resource": "" }
q177511
JobsService.findScheduledJobs
test
public Observable<JobDetails> findScheduledJobs(Date timeSlice, rx.Scheduler scheduler) { return session.executeAndFetch(findAllScheduled.bind(), scheduler) .filter(filterNullJobs) .filter(row -> row.getTimestamp(0).compareTo(timeSlice) <= 0) .map(row -> createJobDetails( row.getUUID(1), row.getString(2), row.getString(3), row.getMap(4, String.class, String.class), getTrigger(row.getUDTValue(5)), JobStatus.fromCode(row.getByte(6)), timeSlice)) .collect(HashMap::new, (Map<UUID, SortedSet<JobDetails>> map, JobDetails details) -> { SortedSet<JobDetails> set = map.get(details.getJobId()); if (set == null) { set = new TreeSet<>((JobDetails d1, JobDetails d2) -> Long.compare(d1.getTrigger().getTriggerTime(), d2.getTrigger().getTriggerTime())); } set.add(details); map.put(details.getJobId(), set); }) .flatMap(map -> Observable.from(map.entrySet())) .map(entry -> entry.getValue().first()); }
java
{ "resource": "" }
q177512
BucketPoint.toList
test
public static <T extends BucketPoint> List<T> toList(Map<Long, T> pointMap, Buckets buckets, BiFunction<Long, Long, T> emptyBucketFactory) { List<T> result = new ArrayList<>(buckets.getCount()); for (int index = 0; index < buckets.getCount(); index++) { long from = buckets.getBucketStart(index); T bucketPoint = pointMap.get(from); if (bucketPoint == null) { long to = from + buckets.getStep(); bucketPoint = emptyBucketFactory.apply(from, to); } result.add(bucketPoint); } return result; }
java
{ "resource": "" }
q177513
Utils.endExchange
test
public static void endExchange(HttpServerExchange exchange, int statusCode, String reasonPhrase) { exchange.setStatusCode(statusCode); if (reasonPhrase != null) { exchange.setReasonPhrase(reasonPhrase); } exchange.endExchange(); }
java
{ "resource": "" }
q177514
DataAccessImpl.findAllDataFromBucket
test
@Override public Observable<Observable<Row>> findAllDataFromBucket(long timestamp, int pageSize, int maxConcurrency) { PreparedStatement ts = getTempStatement(MetricType.UNDEFINED, TempStatement.SCAN_WITH_TOKEN_RANGES, timestamp); // The table does not exists - case such as when starting Hawkular-Metrics for the first time just before // compression kicks in. if(ts == null || prepMap.floorKey(timestamp) == 0L) { return Observable.empty(); } return Observable.from(getTokenRanges()) .map(tr -> rxSession.executeAndFetch( ts .bind() .setToken(0, tr.getStart()) .setToken(1, tr.getEnd()) .setFetchSize(pageSize))); }
java
{ "resource": "" }
q177515
Buckets.fromStep
test
public static Buckets fromStep(long start, long end, long step) { checkTimeRange(start, end); checkArgument(step > 0, "step is not positive: %s", step); if (step > (end - start)) { return new Buckets(start, step, 1); } long quotient = (end - start) / step; long remainder = (end - start) % step; long count; if (remainder == 0) { count = quotient; } else { count = quotient + 1; } checkArgument(count <= Integer.MAX_VALUE, "Computed number of buckets is too big: %s", count); return new Buckets(start, step, (int) count); }
java
{ "resource": "" }
q177516
DefaultRocketMqProducer.sendMsg
test
public boolean sendMsg(Message msg) { SendResult sendResult = null; try { sendResult = producer.send(msg); } catch (Exception e) { logger.error("send msg error", e); } return sendResult != null && sendResult.getSendStatus() == SendStatus.SEND_OK; }
java
{ "resource": "" }
q177517
DefaultRocketMqProducer.sendOneWayMsg
test
public void sendOneWayMsg(Message msg) { try { producer.sendOneway(msg); } catch (Exception e) { logger.error("send msg error", e); } }
java
{ "resource": "" }
q177518
DefaultRocketMqProducer.sendDelayMsg
test
public boolean sendDelayMsg(String topic, String tag, Message msg, int delayLevel) { msg.setDelayTimeLevel(delayLevel); SendResult sendResult = null; try { sendResult = producer.send(msg); } catch (Exception e) { logger.error("send msg error", e); } return sendResult != null && sendResult.getSendStatus() == SendStatus.SEND_OK; }
java
{ "resource": "" }
q177519
MockJedis.scan
test
@Override public ScanResult<String> scan(String cursor, ScanParams params) { // We need to extract the MATCH argument from the scan params Collection<byte[]> rawParams = params.getParams(); // Raw collection is a list of byte[], made of: key1, value1, key2, value2, etc. boolean isKey = true; String match = null; boolean foundMatchKey = false; // So, we run over the list, where any even index is a key, and the following data is its value. for (byte[] raw : rawParams) { if (isKey) { String key = new String(raw); if (key.equals(new String(MATCH.raw))) { // What really interests us is the MATCH key. foundMatchKey = true; } } // As soon as we've found the MATCH key, we can stop searching. else if (foundMatchKey) { match = new String(raw); break; } isKey = !isKey; } // Our simple implementation of SCAN is really a plain wrapper for KEYS, // relying on the current mock implementation of the pattern search. return new ScanResult<String>("0", new ArrayList<String>(keys(match))); }
java
{ "resource": "" }
q177520
Config.setValue
test
public void setValue(String property, Value value) { this.valueByProperty.put(property.toLowerCase(), value); }
java
{ "resource": "" }
q177521
ZipBuilder.add
test
public String add(File file, boolean preserveExternalFileName) { File existingFile = checkFileExists(file); String result = zipPathFor(existingFile, preserveExternalFileName); entries.put(existingFile, result); return result; }
java
{ "resource": "" }
q177522
ZipBuilder.replace
test
public void replace(File file, boolean preserveExternalFileName, String text) { String path = entries.containsKey(file) ? entries.remove(file) : zipPathFor(file, preserveExternalFileName); entries.put(text, path); }
java
{ "resource": "" }
q177523
ZipBuilder.build
test
public File build() throws IOException { if (entries.isEmpty()) { throw new EmptyZipException(); } String fileName = "import_configuration" + System.currentTimeMillis() + ".zip"; File result = new File(TEMP_DIR.toFile(), fileName); try (ZipOutputStream zip = new ZipOutputStream( Files.newOutputStream(result.toPath(), StandardOpenOption.CREATE_NEW))) { customization.init(entries.values(), this::streamFor); for (Entry<Object, String> entry : entries.entrySet()) { try (InputStream input = toInputStream(entry.getKey())) { addEntry(ExtraZipEntry.of(entry.getValue(), customization.customize(entry.getValue(), input)), zip); } } customization.extraEntries().forEach(entry -> addEntry(entry, zip)); zip.closeEntry(); } return result; }
java
{ "resource": "" }
q177524
Generator.generate
test
public Metrics generate(C component, DataBuffer product) throws IOException { return generate(Collections.singletonList(component), product); }
java
{ "resource": "" }
q177525
InfoArchiveRestClient.fetchContent
test
@Override @Deprecated public ContentResult fetchContent(String contentId) throws IOException { try { String contentResource = resourceCache.getCiResourceUri(); URIBuilder builder = new URIBuilder(contentResource); builder.setParameter("cid", contentId); URI uri = builder.build(); return restClient.get(uri.toString(), contentResultFactory); } catch (URISyntaxException e) { throw new IllegalStateException("Failed to create content resource uri.", e); } }
java
{ "resource": "" }
q177526
InfoArchiveRestClient.fetchOrderContent
test
@Override @Deprecated public ContentResult fetchOrderContent(OrderItem orderItem) throws IOException { String downloadUri = Objects.requireNonNull( Objects.requireNonNull(orderItem, "Missing order item").getUri(LINK_DOWNLOAD), "Missing download URI"); String fetchUri = restClient.uri(downloadUri) .addParameter("downloadToken", "") .build(); return restClient.get(fetchUri, contentResultFactory); }
java
{ "resource": "" }
q177527
InfoArchiveRestClient.uploadTransformation
test
@Override @Deprecated public LinkContainer uploadTransformation(ExportTransformation exportTransformation, InputStream zip) throws IOException { String uri = exportTransformation.getUri(LINK_EXPORT_TRANSFORMATION_ZIP); return restClient.post(uri, LinkContainer.class, new BinaryPart("file", zip, "stylesheet.zip")); }
java
{ "resource": "" }
q177528
FileGenerator.generate
test
public FileGenerationMetrics generate(Iterator<C> components) throws IOException { File result = fileSupplier.get(); return new FileGenerationMetrics(result, generate(components, new FileBuffer(result))); }
java
{ "resource": "" }
q177529
UniqueDirectory.in
test
public static File in(File parentDir) { File result = new File(parentDir, UUID.randomUUID() .toString()); if (!result.mkdirs()) { throw new RuntimeIoException(new IOException("Could not create directory: " + result)); } return result; }
java
{ "resource": "" }
q177530
BaseBuilder.end
test
public P end() { parent.addChildObject(English.plural(object.getType()), object); return parent; }
java
{ "resource": "" }
q177531
StringTemplate.registerAdaptor
test
protected <S> void registerAdaptor(STGroup group, Class<S> type, ModelAdaptor adaptor) { group.registerModelAdaptor(type, adaptor); }
java
{ "resource": "" }
q177532
StringTemplate.registerRenderer
test
protected <S> void registerRenderer(STGroup group, Class<S> type, AttributeRenderer attributeRenderer) { group.registerRenderer(type, attributeRenderer); }
java
{ "resource": "" }
q177533
StringTemplate.prepareTemplate
test
protected ST prepareTemplate(ST prototype, D domainObject, Map<String, ContentInfo> contentInfo) { ST template = new ST(prototype); template.add(MODEL_VARIABLE, domainObject); template.add(CONTENT_VARIABLE, contentInfo); return template; }
java
{ "resource": "" }
q177534
BatchSipAssembler.add
test
public synchronized void add(D domainObject) throws IOException { if (shouldStartNewSip(domainObject)) { startSip(); } assembler.add(domainObject); }
java
{ "resource": "" }
q177535
ConfigurationObject.setProperty
test
public void setProperty(String name, Object value) { properties.put(name, toJsonValue(value)); }
java
{ "resource": "" }
q177536
ConfigurationObject.addChildObject
test
public void addChildObject(String collection, ConfigurationObject childObject) { childObjects.computeIfAbsent(collection, ignored -> new ArrayList<>()).add(childObject); }
java
{ "resource": "" }
q177537
FileSupplier.fromDirectory
test
public static Supplier<File> fromDirectory(File dir, String prefix, String suffix) { return new Supplier<File>() { private int count; @Override public File get() { return new File(ensureDir(dir), String.format("%s%d%s", prefix, ++count, suffix)); } }; }
java
{ "resource": "" }
q177538
IOStreams.copy
test
public static void copy(InputStream in, OutputStream out, int bufferSize, HashAssembler hashAssembler) throws IOException { byte[] buffer = new byte[bufferSize]; int numRead = Objects.requireNonNull(in, "Missing input").read(buffer); if (numRead == 0) { throw new IllegalArgumentException("Missing content"); } Objects.requireNonNull(out, "Missing output"); while (numRead > 0) { out.write(buffer, 0, numRead); hashAssembler.add(buffer, numRead); numRead = in.read(buffer); } }
java
{ "resource": "" }
q177539
XmlUtil.parse
test
public static Document parse(File file) { if (!file.isFile()) { throw new IllegalArgumentException("Missing file: " + file.getAbsolutePath()); } try { try (InputStream stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) { return parse(stream); } } catch (IOException e) { throw new IllegalArgumentException("Failed to parse " + file.getAbsolutePath(), e); } }
java
{ "resource": "" }
q177540
XmlUtil.parse
test
public static Document parse(Reader reader) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { return documentBuilder.parse(new InputSource(reader)); } catch (SAXException | IOException e) { throw new IllegalArgumentException("Failed to parse XML document", e); } finally { documentBuilder.reset(); } }
java
{ "resource": "" }
q177541
XmlUtil.elementsIn
test
public static Stream<Element> elementsIn(Element parent) { return nodesIn(parent).filter(n -> n.getNodeType() == Node.ELEMENT_NODE) .map(n -> (Element)n); }
java
{ "resource": "" }
q177542
XmlUtil.nodesIn
test
public static Stream<Node> nodesIn(Element parent) { return StreamSupport.stream(new ChildNodesSpliterator(parent), false); }
java
{ "resource": "" }
q177543
XmlUtil.getFirstChildElement
test
public static Element getFirstChildElement(Element parent, String... childNames) { return firstOf(namedElementsIn(parent, childNames)); }
java
{ "resource": "" }
q177544
XmlUtil.namedElementsIn
test
public static Stream<Element> namedElementsIn(Element parent, String... childNames) { return elementsIn(parent).filter(e -> isName(e, childNames)); }
java
{ "resource": "" }
q177545
XmlUtil.validate
test
public static void validate(InputStream xml, InputStream xmlSchema, String humanFriendlyDocumentType) throws IOException { try { newXmlSchemaValidator(xmlSchema).validate(new StreamSource(Objects.requireNonNull(xml))); } catch (SAXException e) { throw new ValidationException("Invalid " + humanFriendlyDocumentType, e); } }
java
{ "resource": "" }
q177546
FileArchiver.main
test
public static void main(String[] args) { try { Arguments arguments = new Arguments(args); File root = new File(arguments.next("content")); if (!root.isDirectory()) { root = new File("."); } String rootPath = root.getCanonicalPath(); String sip = arguments.next("build/files.zip"); new FileArchiver().run(rootPath, sip); } catch (IOException e) { e.printStackTrace(System.out); System.exit(1); } }
java
{ "resource": "" }
q177547
ContentBuilder.as
test
public ContentBuilder<P> as(InputStream content) { try { return as(IOUtils.toString(content, StandardCharsets.UTF_8)); } catch (IOException e) { throw new IllegalArgumentException("Failed to read content", e); } }
java
{ "resource": "" }
q177548
ContentBuilder.fromResource
test
public ContentBuilder<P> fromResource(String name) { try (InputStream content = ContentBuilder.class.getResourceAsStream(name)) { return as(content); } catch (IOException e) { throw new IllegalArgumentException("Failed to read resource: " + name, e); } }
java
{ "resource": "" }
q177549
Unzip.andProcessEntry
test
public <T> T andProcessEntry(String entry, Function<InputStream, T> processor) { try (ZipFile zipFile = new ZipFile(zip)) { return processEntry(zipFile, entry, processor); } catch (IOException e) { throw new RuntimeIoException(e); } }
java
{ "resource": "" }
q177550
QSStringUtil.asciiCharactersEncoding
test
public static String asciiCharactersEncoding(String str) throws QSException { if (QSStringUtil.isEmpty(str)) { return ""; } try { String encoded = URLEncoder.encode(str, QSConstant.ENCODING_UTF8); encoded = encoded.replace("%2F", "/"); encoded = encoded.replace("%3D", "="); encoded = encoded.replace("+", "%20"); encoded = encoded.replace("%3A", ":"); return encoded; } catch (UnsupportedEncodingException e) { throw new QSException("UnsupportedEncodingException:", e); } }
java
{ "resource": "" }
q177551
RequestHandler.setSignature
test
public void setSignature(String accessKey, String signature, String gmtTime) throws QSException { builder.setHeader(QSConstant.HEADER_PARAM_KEY_DATE, gmtTime); setSignature(accessKey, signature); }
java
{ "resource": "" }
q177552
Base64.removeWhiteSpace
test
private static int removeWhiteSpace(char[] data) { if (data == null) { return 0; } // count characters that's not whitespace int newSize = 0; int len = data.length; for (int i = 0; i < len; i++) { if (!isWhiteSpace(data[i])) { data[newSize++] = data[i]; } } return newSize; }
java
{ "resource": "" }
q177553
UploadManager.sign
test
private void sign(RequestHandler requestHandler) throws QSException { if (callBack != null) { String signed = callBack.onSignature(requestHandler.getStringToSignature()); if (!QSStringUtil.isEmpty(signed)) requestHandler.setSignature(callBack.onAccessKey(), signed); String correctTime = callBack.onCorrectTime(requestHandler.getStringToSignature()); if (correctTime != null && correctTime.trim().length() > 0) requestHandler.getBuilder().setHeader(QSConstant.HEADER_PARAM_KEY_DATE, correctTime); } }
java
{ "resource": "" }
q177554
UploadManager.setData
test
private void setData(String objectKey, Recorder recorder) { if (recorder == null) return; String upload = new Gson().toJson(uploadModel); recorder.set(objectKey, upload.getBytes()); }
java
{ "resource": "" }
q177555
UploadManager.completeMultiUpload
test
private void completeMultiUpload(String objectKey, String fileName, String eTag, String uploadID, long length) throws QSException { CompleteMultipartUploadInput completeMultipartUploadInput = new CompleteMultipartUploadInput(uploadID, partCounts, 0); completeMultipartUploadInput.setContentLength(length); // Set content disposition to the object. if (!QSStringUtil.isEmpty(fileName)) { try { String keyName = QSStringUtil.percentEncode(fileName, "UTF-8"); completeMultipartUploadInput.setContentDisposition(String.format( "attachment; filename=\"%s\"; filename*=utf-8''%s", keyName, keyName)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } // Set the Md5 info to the object. if (!QSStringUtil.isEmpty(eTag)) { completeMultipartUploadInput.setETag(eTag); } RequestHandler requestHandler = bucket.completeMultipartUploadRequest(objectKey, completeMultipartUploadInput); sign(requestHandler); Bucket.CompleteMultipartUploadOutput send = (Bucket.CompleteMultipartUploadOutput) requestHandler.send(); if (send.getStatueCode() == 200 || send.getStatueCode() == 201) { uploadModel.setUploadComplete(true); setData(objectKey, recorder); } // Response callback. if (callBack != null) callBack.onAPIResponse(objectKey, send); }
java
{ "resource": "" }
q177556
FavoriteAction.invoke
test
@Override public void invoke(final ActionRequest req, final ActionResponse res) throws IOException { final NotificationEntry entry = getTarget(); final String notificationId = entry.getId(); final Set<String> favoriteNotices = this.getFavoriteNotices(req); if (favoriteNotices.contains(notificationId)) { favoriteNotices.remove(notificationId); } else { favoriteNotices.add(notificationId); } setFavoriteNotices(req, favoriteNotices); }
java
{ "resource": "" }
q177557
JpaNotificationService.addEntryState
test
public void addEntryState(PortletRequest req, String entryId, NotificationState state) { if (usernameFinder.isAuthenticated(req)) { final String username = usernameFinder.findUsername(req); String idStr = entryId.replaceAll(ID_PREFIX, ""); // remove the prefix JpaEntry jpaEntry = notificationDao.getEntry(Long.parseLong(idStr)); if (jpaEntry != null) { JpaEvent event = new JpaEvent(); event.setEntry(jpaEntry); event.setState(state); event.setTimestamp(new Timestamp(new Date().getTime())); event.setUsername(username); notificationDao.createOrUpdateEvent(event); } else { throw new IllegalArgumentException("JpaEntry not found"); } } }
java
{ "resource": "" }
q177558
SSPToken.hasExpired
test
public boolean hasExpired() { long now = System.currentTimeMillis(); if (created + (expiresIn * 1000) + TIMEOUT_BUFFER > now) { return false; } return true; }
java
{ "resource": "" }
q177559
JPANotificationRESTController.getNotification
test
@RequestMapping(value = "/{notificationId}", method = RequestMethod.GET) @ResponseBody public EntryDTO getNotification(HttpServletResponse response, @PathVariable("notificationId") long id, @RequestParam(value = "full", required = false, defaultValue = "false") boolean full) { EntryDTO notification = restService.getNotification(id, full); if (notification == null) { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } return notification; }
java
{ "resource": "" }
q177560
JPANotificationRESTController.getAddressees
test
@RequestMapping(value = "/{notificationId}/addressees", method = RequestMethod.GET) @ResponseBody public Set<AddresseeDTO> getAddressees(@PathVariable("notificationId") long id) { return restService.getAddressees(id); }
java
{ "resource": "" }
q177561
JPANotificationRESTController.getAddressee
test
@RequestMapping(value = "/{notificationId}/addressees/{addresseeId}", method = RequestMethod.GET) @ResponseBody public AddresseeDTO getAddressee(HttpServletResponse resp, @PathVariable("notificationId") long notificationId, @PathVariable("addresseeId") long addresseeId) { AddresseeDTO dto = restService.getAddressee(addresseeId); if (dto == null) { resp.setStatus(HttpStatus.NOT_FOUND.value()); return null; } return dto; }
java
{ "resource": "" }
q177562
JPANotificationRESTController.getEventsByNotification
test
@RequestMapping(value = "/{notificationId}/events", method = RequestMethod.GET) @ResponseBody public List<EventDTO> getEventsByNotification(@PathVariable("notificationId") long id) { return restService.getEventsByNotification(id); }
java
{ "resource": "" }
q177563
JPANotificationRESTController.getEvent
test
@RequestMapping(value = "/{notificationId}/events/{eventId}", method = RequestMethod.GET) @ResponseBody public EventDTO getEvent(HttpServletResponse response, @PathVariable("notificationId") long notificationId, @PathVariable("eventId") long eventId) { EventDTO event = restService.getEvent(eventId); if (event == null) { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } return event; }
java
{ "resource": "" }
q177564
JPANotificationRESTController.getSingleNotificationRESTUrl
test
private String getSingleNotificationRESTUrl(HttpServletRequest request, long id) { String path = request.getContextPath() + REQUEST_ROOT + id; try { URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), path); return url.toExternalForm(); } catch (MalformedURLException e) { // if it fails, just return a relative path. Not ideal, but better than nothing... log.warn("Error building Location header", e); return path; } }
java
{ "resource": "" }
q177565
JpaNotificationDao.getEntry
test
@Override @Transactional(readOnly=true) public JpaEntry getEntry(long entryId) { Validate.isTrue(entryId > 0, "Invalid entryId: " + entryId); JpaEntry rslt = entityManager.find(JpaEntry.class, entryId); return rslt; }
java
{ "resource": "" }
q177566
SSPApi.getAuthenticationToken
test
private synchronized SSPToken getAuthenticationToken(boolean forceUpdate) throws MalformedURLException, RestClientException { if (authenticationToken != null && !authenticationToken.hasExpired() && !forceUpdate) { return authenticationToken; } String authString = getClientId() + ":" + getClientSecret(); String authentication = new Base64().encodeToString(authString.getBytes()); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, BASIC + " " + authentication); // form encode the grant_type... MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(GRANT_TYPE, CLIENT_CREDENTIALS); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers); URL authURL = getAuthenticationURL(); authenticationToken = restTemplate.postForObject(authURL.toExternalForm(), request, SSPToken.class); return authenticationToken; }
java
{ "resource": "" }
q177567
NotificationResponse.size
test
@JsonIgnore @XmlTransient public int size() { return categories.stream() .map(NotificationCategory::getEntries) .mapToInt(List::size) .sum(); }
java
{ "resource": "" }
q177568
NotificationResponse.addCategories
test
private void addCategories(List<NotificationCategory> newCategories) { if (newCategories == null) { return; } // Start with a deep copy of the method parameter to simplify remaining logic newCategories = newCategories.parallelStream().map(NotificationCategory::cloneNoExceptions).collect(Collectors.toList()); // Create a map of current categories by title for processing Map<String, NotificationCategory> catsByName = this.categories.parallelStream().collect(toMap(c -> c.getTitle().toLowerCase(), c -> c)); // Split new categories between those that match an existing category and those that are completely new Map<Boolean, List<NotificationCategory>> matchingNewCats = newCategories.stream() .collect(partitioningBy(c -> catsByName.containsKey(c.getTitle().toLowerCase()))); // Add new entries to existing categories matchingNewCats.get(Boolean.TRUE).stream() .forEachOrdered(c -> catsByName.get(c.getTitle().toLowerCase()).addEntries(c.getEntries())); // Add new categories this.categories.addAll(matchingNewCats.get(Boolean.FALSE)); }
java
{ "resource": "" }
q177569
SSPTaskNotificationService.fetch
test
@Override public NotificationResponse fetch(PortletRequest req) { PortletPreferences preferences = req.getPreferences(); String enabled = preferences.getValue(SSP_NOTIFICATIONS_ENABLED, "false"); if (!"true".equalsIgnoreCase(enabled)) { return new NotificationResponse(); } String personId = getPersonId(req); if (personId == null) { // Not all students will have active SSP records, // so if no entry is found in SSP, just return an // empty response set. return new NotificationResponse(); } String urlFragment = getActiveTaskUrl(); SSPApiRequest<String> request = new SSPApiRequest<>(urlFragment, String.class) .addUriParameter("personId", personId); ResponseEntity<String> response; try { response = sspApi.doRequest(request); } catch (Exception e) { log.error("Error reading SSP Notifications: " + e.getMessage()); return notificationError(e.getMessage()); } if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) { log.error("Error reading SSP Notifications: " + response); return notificationError(response.getBody()); } NotificationResponse notification = mapToNotificationResponse(req, response); return notification; }
java
{ "resource": "" }
q177570
SSPTaskNotificationService.notificationError
test
private NotificationResponse notificationError(String errorMsg) { NotificationError error = new NotificationError(); error.setError(errorMsg); error.setSource(getClass().getSimpleName()); NotificationResponse notification = new NotificationResponse(); notification.setErrors(Arrays.asList(error)); return notification; }
java
{ "resource": "" }
q177571
SSPTaskNotificationService.mapToNotificationResponse
test
private NotificationResponse mapToNotificationResponse(PortletRequest request, ResponseEntity<String> response) { Configuration config = Configuration.builder().options( Option.DEFAULT_PATH_LEAF_TO_NULL ).build(); ReadContext readContext = JsonPath .using(config) .parse(response.getBody()); // check the status embedded in the response too... String success = readContext.read(SUCCESS_QUERY); // grr. SSP returns this as a string... if (!"true".equalsIgnoreCase(success)) { String error = readContext.read(MESSAGE_QUERY); return notificationError(error); } // read the actual tasks... Object rows = readContext.read(ROWS_QUERY); if (!(rows instanceof JSONArray)) { throw new RuntimeException("Expected 'rows' to be an array of tasks"); } String source = getNotificationSource(request); List<NotificationEntry> list = new ArrayList<>(); for (int i = 0; i < ((JSONArray)rows).size(); i++) { NotificationEntry entry = mapNotificationEntry(readContext, i, source); if (entry != null) { attachActions(request, entry); list.add(entry); } } // build the notification response... NotificationResponse notification = new NotificationResponse(); if (!list.isEmpty()) { NotificationCategory category = getNotificationCategory(request); category.addEntries(list); notification.setCategories(Arrays.asList(category)); } return notification; }
java
{ "resource": "" }
q177572
SSPTaskNotificationService.mapNotificationEntry
test
private NotificationEntry mapNotificationEntry(ReadContext readContext, int index, String source) { boolean completed = readContext.read(format(ROW_COMPLETED_QUERY_FMT, index), Boolean.class); if (completed) { return null; } NotificationEntry entry = new NotificationEntry(); entry.setSource(source); String id = readContext.read(format(ROW_ID_QUERY_FMT, index)); entry.setId(id); String title = readContext.read(format(ROW_NAME_QUERY_FMT, index)); entry.setTitle(title); String desc = readContext.read(format(ROW_DESCRIPTION_QUERY_FMT, index)); entry.setBody(desc); String link = readContext.read(format(ROW_LINK_QUERY_FMT, index)); URL fixedLink = normalizeLink(link); if (fixedLink != null) { entry.setUrl(fixedLink.toExternalForm()); } Date createDate = readContext.read(format("$.rows[%d].createdDate", index), Date.class); Map<NotificationState, Date> states = new HashMap<>(); states.put(NotificationState.ISSUED, createDate); try { // the date is in an odd format, need to parse by hand... String dateStr = readContext.read(format(ROW_DUE_DATE_QUERY_FMT, index)); if (!StringUtils.isBlank(dateStr)) { synchronized (dateFormat) { Date dueDate = dateFormat.parse(dateStr); entry.setDueDate(dueDate); } } } catch (Exception e) { log.warn("Error parsing due date. Ignoring", e); } return entry; }
java
{ "resource": "" }
q177573
SSPTaskNotificationService.attachActions
test
private void attachActions(PortletRequest request, NotificationEntry entry) { PortletPreferences prefs = request.getPreferences(); String stringVal = prefs.getValue(SSP_NOTIFICATIONS_ENABLE_MARK_COMPLETED, "false"); boolean enableMarkCompleted = ("true".equalsIgnoreCase(stringVal)); List<NotificationAction> actions = new ArrayList<>(); if (enableMarkCompleted) { MarkTaskCompletedAction action = new MarkTaskCompletedAction(entry.getId()); actions.add(action); } entry.setAvailableActions(actions); }
java
{ "resource": "" }
q177574
SSPTaskNotificationService.normalizeLink
test
private URL normalizeLink(String link) { try { if (StringUtils.isEmpty(link)) { return null; } if (link.startsWith("/")) { return sspApi.getSSPUrl(link, true); } if (link.startsWith("http://") || link.startsWith("https://")) { return new URL(link); } // if all else fails, just tack on http:// and see if the URL parser can handle // it. Perhaps, not ideal... return new URL("http://" + link); } catch (MalformedURLException e) { log.warn("Bad URL from SSP Entry: " + link, e); return null; } }
java
{ "resource": "" }
q177575
SSPTaskNotificationService.getNotificationCategory
test
private NotificationCategory getNotificationCategory(PortletRequest request) { PortletPreferences preferences = request.getPreferences(); String title = preferences.getValue(NOTIFICATION_CATEGORY_PREF, DEFAULT_CATEGORY); NotificationCategory category = new NotificationCategory(); category.setTitle(title); return category; }
java
{ "resource": "" }
q177576
SSPTaskNotificationService.getNotificationSource
test
private String getNotificationSource(PortletRequest req) { PortletPreferences preferences = req.getPreferences(); String source = preferences.getValue(NOTIFICATION_SOURCE_PREF, DEFAULT_NOTIFICATION_SOURCE); return source; }
java
{ "resource": "" }
q177577
ReadAction.invoke
test
@Override public void invoke(final ActionRequest req, final ActionResponse res) throws IOException { final NotificationEntry entry = getTarget(); final String notificationId = entry.getId(); final Set<String> readNotices = this.getReadNotices(req); if (readNotices.contains(notificationId)) { readNotices.remove(notificationId); } else { readNotices.add(notificationId); } setReadNotices(req, readNotices); }
java
{ "resource": "" }
q177578
ClassLoaderResourceNotificationService.readFromFile
test
private NotificationResponse readFromFile(String filename) { NotificationResponse rslt; logger.debug("Preparing to read from file: {}", filename); URL location = getClass().getClassLoader().getResource(filename); if (location != null) { try { File f = new File(location.toURI()); rslt = mapper.readValue(f, NotificationResponse.class); } catch (Exception e) { String msg = "Failed to read the data file: " + location; logger.error(msg, e); rslt = prepareErrorResponse(getName(), msg); } } else { String msg = "Data file not found: " + filename; rslt = prepareErrorResponse(getName(), msg); } return rslt; }
java
{ "resource": "" }
q177579
SSPSchoolIdPersonLookup.getSchoolId
test
private String getSchoolId(PortletRequest request) { PortletPreferences prefs = request.getPreferences(); String schoolIdAttributeName = prefs.getValue("SSPTaskNotificationService.schoolIdAttribute", "schoolId"); Map<String, String> userInfo = (Map<String, String>)request.getAttribute(PortletRequest.USER_INFO); String studentId = userInfo.get(schoolIdAttributeName); if (!StringUtils.isEmpty(studentId)) { return studentId; } // if not found, fall back to username. studentId = userInfo.get(USERNAME_ATTRIBUTE); return studentId; }
java
{ "resource": "" }
q177580
SSPSchoolIdPersonLookup.extractUserId
test
private String extractUserId(String studentId, ResponseEntity<String> response) { Configuration config = Configuration.builder().options( Option.DEFAULT_PATH_LEAF_TO_NULL ).build(); ReadContext readContext = JsonPath .using(config) .parse(response.getBody()); String success = readContext.read(SUCCESS_QUERY); // SSP passes this as a string... if (!"true".equalsIgnoreCase(success)) { return null; } int count = readContext.read(RESULTS_QUERY, Integer.class); if (count != 1) { // couldn't find a single unique result. Bail now... log.warn("Expected a single unique result for " + studentId + ". Found " + count); return null; } String id = readContext.read(STUDENT_ID_QUERY); return id; }
java
{ "resource": "" }
q177581
HideAction.invoke
test
@Override public void invoke(final ActionRequest req, final ActionResponse res) throws IOException { final NotificationEntry entry = getTarget(); /* * The HideAction works like a toggle */ if (!isEntrySnoozed(entry, req)) { // Hide it... hide(entry, req); } else { // Un-hide it... unhide(entry, req); } }
java
{ "resource": "" }
q177582
NotificationEntry.getAttributesMap
test
@JsonIgnore public Map<String,List<String>> getAttributesMap() { Map<String,List<String>> rslt = new HashMap<>(); for (NotificationAttribute a : attributes) { rslt.put(a.getName(), a.getValues()); } return rslt; }
java
{ "resource": "" }
q177583
UtilTrig_F64.normalize
test
public static void normalize( GeoTuple3D_F64 p ) { double n = p.norm(); p.x /= n; p.y /= n; p.z /= n; }
java
{ "resource": "" }
q177584
Intersection3D_I32.contained
test
public static boolean contained( Box3D_I32 boxA , Box3D_I32 boxB ) { return( boxA.p0.x <= boxB.p0.x && boxA.p1.x >= boxB.p1.x && boxA.p0.y <= boxB.p0.y && boxA.p1.y >= boxB.p1.y && boxA.p0.z <= boxB.p0.z && boxA.p1.z >= boxB.p1.z ); }
java
{ "resource": "" }
q177585
DistancePointTriangle3D_F64.closestPoint
test
public void closestPoint(Point3D_F64 P , Point3D_F64 closestPt ) { // D = B-P GeometryMath_F64.sub(B, P, D); a = E0.dot(E0); b = E0.dot(E1); c = E1.dot(E1); d = E0.dot(D); e = E1.dot(D); double det = a * c - b * b; s = b * e - c * d; t = b * d - a * e; if (s + t <= det) { if (s < 0) { if (t < 0) { region4(); } else { region3(); } } else if (t < 0) { region5(); } else { region0(det); } } else { if (s < 0) { region2(); } else if (t < 0) { region6(); } else { region1(); } } closestPt.x = B.x + s*E0.x + t*E1.x; closestPt.y = B.y + s*E0.y + t*E1.y; closestPt.z = B.z + s*E0.z + t*E1.z; }
java
{ "resource": "" }
q177586
DistancePointTriangle3D_F64.sign
test
public double sign( Point3D_F64 P ) { GeometryMath_F64.cross(E1,E0,N); // dot product of double d = N.x*(P.x-B.x) + N.y*(P.y-B.y) + N.z*(P.z-B.z); return Math.signum(d); }
java
{ "resource": "" }
q177587
Se3_F64.set
test
public void set( Se3_F64 se ) { R.set( se.getR() ); T.set( se.getT() ); }
java
{ "resource": "" }
q177588
Se3_F64.set
test
public void set(double x , double y , double z , EulerType type , double rotA , double rotB , double rotC ) { T.set(x,y,z); ConvertRotation3D_F64.eulerToMatrix(type,rotA,rotB,rotC,R); }
java
{ "resource": "" }
q177589
UtilPolygons2D_F64.convert
test
public static void convert( Rectangle2D_F64 input , Polygon2D_F64 output ) { if (output.size() != 4) throw new IllegalArgumentException("polygon of order 4 expected"); output.get(0).set(input.p0.x, input.p0.y); output.get(1).set(input.p1.x, input.p0.y); output.get(2).set(input.p1.x, input.p1.y); output.get(3).set(input.p0.x, input.p1.y); }
java
{ "resource": "" }
q177590
UtilPolygons2D_F64.convert
test
public static void convert( Polygon2D_F64 input , Quadrilateral_F64 output ) { if( input.size() != 4 ) throw new IllegalArgumentException("Expected 4-sided polygon as input"); output.a.set(input.get(0)); output.b.set(input.get(1)); output.c.set(input.get(2)); output.d.set(input.get(3)); }
java
{ "resource": "" }
q177591
UtilPolygons2D_F64.bounding
test
public static void bounding( Quadrilateral_F64 quad , Rectangle2D_F64 rectangle ) { rectangle.p0.x = Math.min(quad.a.x,quad.b.x); rectangle.p0.x = Math.min(rectangle.p0.x,quad.c.x); rectangle.p0.x = Math.min(rectangle.p0.x,quad.d.x); rectangle.p0.y = Math.min(quad.a.y,quad.b.y); rectangle.p0.y = Math.min(rectangle.p0.y,quad.c.y); rectangle.p0.y = Math.min(rectangle.p0.y,quad.d.y); rectangle.p1.x = Math.max(quad.a.x,quad.b.x); rectangle.p1.x = Math.max(rectangle.p1.x,quad.c.x); rectangle.p1.x = Math.max(rectangle.p1.x,quad.d.x); rectangle.p1.y = Math.max(quad.a.y,quad.b.y); rectangle.p1.y = Math.max(rectangle.p1.y,quad.c.y); rectangle.p1.y = Math.max(rectangle.p1.y,quad.d.y); }
java
{ "resource": "" }
q177592
UtilPolygons2D_F64.bounding
test
public static void bounding( Polygon2D_F64 polygon , Rectangle2D_F64 rectangle ) { rectangle.p0.set(polygon.get(0)); rectangle.p1.set(polygon.get(0)); for (int i = 0; i < polygon.size(); i++) { Point2D_F64 p = polygon.get(i); if( p.x < rectangle.p0.x ) { rectangle.p0.x = p.x; } else if( p.x > rectangle.p1.x ) { rectangle.p1.x = p.x; } if( p.y < rectangle.p0.y ) { rectangle.p0.y = p.y; } else if( p.y > rectangle.p1.y ) { rectangle.p1.y = p.y; } } }
java
{ "resource": "" }
q177593
UtilPolygons2D_F64.center
test
public static Point2D_F64 center( Quadrilateral_F64 quad , Point2D_F64 center ) { if( center == null ) center = new Point2D_F64(); center.x = quad.a.x + quad.b.x + quad.c.x + quad.d.x; center.y = quad.a.y + quad.b.y + quad.c.y + quad.d.y; center.x /= 4.0; center.y /= 4.0; return center; }
java
{ "resource": "" }
q177594
UtilPolygons2D_F64.vertexAverage
test
public static void vertexAverage(Polygon2D_F64 input, Point2D_F64 average ) { average.setIdx(0,0); for (int i = 0; i < input.size(); i++) { Point2D_F64 v = input.vertexes.data[i]; average.x += v.x; average.y += v.y; } average.x /= input.size(); average.y /= input.size(); }
java
{ "resource": "" }
q177595
UtilPolygons2D_F64.convexHull
test
public static void convexHull( List<Point2D_F64> points , Polygon2D_F64 hull ) { Point2D_F64[] array = new Point2D_F64[points.size()]; for (int i = 0; i < points.size(); i++) { array[i] = points.get(i); } AndrewMonotoneConvexHull_F64 andrew = new AndrewMonotoneConvexHull_F64(); andrew.process(array,array.length,hull); }
java
{ "resource": "" }
q177596
UtilPolygons2D_F64.removeAlmostParallel
test
public static void removeAlmostParallel( Polygon2D_F64 polygon , double tol ) { for (int i = 0; i < polygon.vertexes.size(); ) { int j = (i+1)%polygon.vertexes.size(); int k = (i+2)%polygon.vertexes.size(); Point2D_F64 p0 = polygon.vertexes.get(i); Point2D_F64 p1 = polygon.vertexes.get(j); Point2D_F64 p2 = polygon.vertexes.get(k); double angle = UtilVector2D_F64.acute(p1.x-p0.x,p1.y-p0.y,p2.x-p1.x,p2.y-p1.y); if( angle <= tol) { polygon.vertexes.remove(j); if( j < i ) i = polygon.vertexes.size()-1; } else { i++; } } }
java
{ "resource": "" }
q177597
UtilPolygons2D_F64.averageOfClosestPointError
test
public static double averageOfClosestPointError(Polygon2D_F64 model , Polygon2D_F64 target , int numberOfSamples ) { LineSegment2D_F64 line = new LineSegment2D_F64(); double cornerLocationsB[] = new double[target.size()+1]; double totalLength = 0; for (int i = 0; i < target.size(); i++) { Point2D_F64 b0 = target.get(i%target.size()); Point2D_F64 b1 = target.get((i+1)%target.size()); cornerLocationsB[i] = totalLength; totalLength += b0.distance(b1); } cornerLocationsB[target.size()] = totalLength; Point2D_F64 pointOnB = new Point2D_F64(); double error = 0; int cornerB = 0; for (int k = 0; k < numberOfSamples; k++) { // Find the point on B to match to a point on A double location = totalLength*k/numberOfSamples; while (location > cornerLocationsB[cornerB + 1]) { cornerB++; } Point2D_F64 b0 = target.get(cornerB); Point2D_F64 b1 = target.get((cornerB+1)%target.size()); double locationCornerB = cornerLocationsB[cornerB]; double fraction = (location-locationCornerB)/(cornerLocationsB[cornerB+1]-locationCornerB); pointOnB.x = (b1.x-b0.x)*fraction + b0.x; pointOnB.y = (b1.y-b0.y)*fraction + b0.y; // find the best fit point on A to the point in B double best = Double.MAX_VALUE; for (int i = 0; i < model.size()+1; i++) { line.a = model.get(i%model.size()); line.b = model.get((i+1)%model.size()); double d = Distance2D_F64.distance(line,pointOnB); if( d < best ) { best = d; } } error += best; } return error/numberOfSamples; }
java
{ "resource": "" }
q177598
AreaIntersectionPolygon2D_F64.computeArea
test
public double computeArea(Polygon2D_F64 a , Polygon2D_F64 b ) { ssss = 0; sclx = 0; scly = 0; return inter(a,b); }
java
{ "resource": "" }
q177599
Intersection2D_F64.contains
test
public static boolean contains( Quadrilateral_F64 quad , Point2D_F64 pt ) { return containTriangle(quad.a, quad.b, quad.d, pt) || containTriangle(quad.b, quad.c, quad.d, pt); }
java
{ "resource": "" }