id
stringlengths
7
14
text
stringlengths
1
37.2k
8744004_2
@POST @Path("/permissions") public Response permissions(String body, @Context GraphDatabaseService db) throws IOException { String[] splits = body.split(","); PermissionRequest ids = new PermissionRequest(splits[0], splits[1]); Set<String> documents = new HashSet<String>(); Set<Node> documentNodes = new HashSet<Node>(); List<Node> groupNodes = new ArrayList<Node>(); Set<Node> parentNodes = new HashSet<Node>(); HashMap<Node, ArrayList<Node>> foldersAndDocuments = new HashMap<Node, ArrayList<Node>>(); IndexHits<Node> uid = db.index().forNodes("Users").get("unique_id", ids.userAccountUid); IndexHits<Node> docids = db.index().forNodes("Documents").query("unique_id:(" + ids.documentUids + ")"); try { for ( Node node : docids ) { documentNodes.add(node); } } finally { docids.close(); } Node user = uid.getSingle(); if ( user != null && documentNodes.size() > 0) { for ( Relationship relationship : user.getRelationships( RelTypes.IS_MEMBER_OF, Direction.OUTGOING ) ) { groupNodes.add(relationship.getEndNode()); } Iterator listIterator ; do { listIterator = documentNodes.iterator(); Node document = (Node) listIterator.next(); listIterator.remove(); //Check against user Node found = getAllowed(document, user); if (found != null) { if (foldersAndDocuments.get(found) != null) { for(Node docs : foldersAndDocuments.get(found)) { documents.add(docs.getProperty("unique_id").toString()); } } else { documents.add(found.getProperty("unique_id").toString()); } } //Check against user Groups for (Node group : groupNodes){ found = getAllowed(document, group); if (found != null) { if (foldersAndDocuments.get(found) != null) { for(Node docs : foldersAndDocuments.get(found)) { documents.add(docs.getProperty("unique_id").toString()); } } else { documents.add(found.getProperty("unique_id").toString()); } } } // Did not find a security relationship, go up the folder chain Relationship parentRelationship = document.getSingleRelationship(RelTypes.HAS_CHILD_CONTENT,Direction.INCOMING); if (parentRelationship != null){ Node parent = parentRelationship.getStartNode(); ArrayList<Node> myDocs = foldersAndDocuments.get(document); if(myDocs == null) myDocs = new ArrayList<Node>(); ArrayList<Node> existingDocs = foldersAndDocuments.get(parent); if(existingDocs == null) existingDocs = new ArrayList<Node>(); for (Node myDoc:myDocs) { existingDocs.add(myDoc); } if (myDocs.isEmpty()) existingDocs.add(document); foldersAndDocuments.put(parent, existingDocs); parentNodes.add(parent); } if(listIterator.hasNext() == false){ documentNodes.clear(); for( Node parentNode : parentNodes){ documentNodes.add(parentNode); } parentNodes.clear(); listIterator = documentNodes.iterator(); } } while (listIterator.hasNext()); } else {documents.add("Error: User or Documents not found");} uid.close(); return Response.ok().entity(objectMapper.writeValueAsString(documents)).build(); }
8750145_6
;
8751650_2
public static BpmManager newInstance() { BpmManager bpmManager = ServiceRegistryUtil.getSingleService(BpmManager.class); if (bpmManager == null) throw new RuntimeException(Messages.i18n.format("WorkflowFactory.MissingBPMProvider")); //$NON-NLS-1$ return bpmManager; }
8752400_20
@Override public void setOutputBaclavaFile(String filename) throws RemoteException { if (status != Initialized) throw new IllegalStateException("not initializing"); if (filename != null) outputBaclavaFile = validateFilename(filename); else outputBaclavaFile = null; outputBaclava = filename; }
8757198_2
public V calculate(V start, V a, V b) { List<LcaRequestResponse<V>> list = new LinkedList<LcaRequestResponse<V>>(); list.add(new LcaRequestResponse<V>(a, b)); return calculate(start, list).get(0); }
8759133_1
@VisibleForTesting String[] findFilterLocations(AbstractConfiguration config) { String[] locations = config.getStringArray("zuul.filters.locations"); if (locations == null) { locations = new String[]{"inbound", "outbound", "endpoint"}; } String[] filterLocations = Arrays.stream(locations) .map(String::trim) .filter(blank.negate()) .toArray(String[]::new); if (filterLocations.length != 0) { LOG.info("Using filter locations: "); for (String location : filterLocations) { LOG.info(" " + location); } } return filterLocations; }
8772570_1
@Override public String getName() { return NAME; }
8777778_3
void basicReject(long deliveryTag, boolean requeue) throws IOException { Map<Long, MsgResponse> rejections = deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(rejections, MsgResult.REJECT, false, requeue); rejections.clear(); }
8786725_102
@Override public void deviceLeft(NetworkDevice device) { if (device == null || device.getNetworkDeviceName() == null || device.getNetworkDeviceType() == null) return; // Remove what services this device has. logger.info("Device "+device.getNetworkDeviceName()+" of type "+device.getNetworkDeviceType()+" leaving."); String host = connectionManagerControlCenter.getHost(device.getNetworkDeviceName()); List<UpDevice> devices = deviceDao.list(host,device.getNetworkDeviceType()); if (devices != null && !devices.isEmpty()){ UpDevice upDevice = devices.get(0); List<DriverModel> returnedDrivers = driverManager.list(null, upDevice.getName()); if (returnedDrivers != null && !returnedDrivers.isEmpty()){ for (DriverModel rdd : returnedDrivers){ driverManager.delete(rdd.id(), rdd.device()); } } deviceDao.delete(upDevice.getName()); logger.info( String.format("Device '%s' left", upDevice.getName())); } else { logger.info("Device not found in database."); } }
8791847_17
@Override public int size() { return size; }
8794298_9
public <T> T get(final JsonRpcClientTransport transport, final String handle, final Class<T>... classes) { for (Class<T> clazz : classes) { typeChecker.isValidInterface(clazz); } return (T) Proxy.newProxyInstance(JsonRpcInvoker.class.getClassLoader(), classes, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return JsonRpcInvoker.this.invoke(handle, transport, method, args); } }); }
8824082_4
public T mapNodeProperties(final NodeRef nodeRef, final Map<QName, Serializable> properties) { try { T mappedObject = this.mappedClass.newInstance(); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); afterBeanWrapperInitialized(bw); for (Map.Entry<QName, PropertyDescriptor> entry : mappedQNames.entrySet()) { QName qName = entry.getKey(); PropertyDescriptor pd = entry.getValue(); if (pd != null) { bw.setPropertyValue(pd.getName(), properties.get(qName)); } } if (configurer != null) { configurer.configure(nodeRef, mappedObject); } return mappedObject; } catch (Throwable e) { throw new RuntimeException(e); } }
8853829_0
public double getTotal() { double total = 0; for (Product product : products) { total += product.getPrice(); } return total; }
8859474_6
List<JPackage> getHierarchyPackages(List<JavaPackage> packages) { Map<String, JPackage> pkgMap = new HashMap<>(); for (JavaPackage pkg : packages) { addPackage(pkgMap, new JPackage(pkg, wrapper)); } // merge packages without classes boolean repeat; do { repeat = false; for (JPackage pkg : pkgMap.values()) { List<JPackage> innerPackages = pkg.getInnerPackages(); if (innerPackages.size() == 1 && pkg.getClasses().isEmpty()) { JPackage innerPkg = innerPackages.get(0); pkg.setInnerPackages(innerPkg.getInnerPackages()); pkg.setClasses(innerPkg.getClasses()); String innerName = '.' + innerPkg.getName(); pkg.updateBothNames(pkg.getFullName() + innerName, pkg.getName() + innerName, wrapper); innerPkg.setInnerPackages(Collections.emptyList()); innerPkg.setClasses(Collections.emptyList()); repeat = true; break; } } } while (repeat); // remove empty packages pkgMap.values().removeIf(pkg -> pkg.getInnerPackages().isEmpty() && pkg.getClasses().isEmpty()); // use identity set for collect inner packages Set<JPackage> innerPackages = Collections.newSetFromMap(new IdentityHashMap<>()); for (JPackage pkg : pkgMap.values()) { innerPackages.addAll(pkg.getInnerPackages()); } // find root packages List<JPackage> rootPkgs = new ArrayList<>(); for (JPackage pkg : pkgMap.values()) { if (!innerPackages.contains(pkg)) { rootPkgs.add(pkg); } } Collections.sort(rootPkgs); return rootPkgs; }
8903055_2
public String getParameterName() { return parameterName; }
8914350_60
public void run() { boolean sent = false; boolean retried = false; long startTS = System.currentTimeMillis(); for (int i = 0; i < config.getRetryCount(); ++i) { ConnectionPool.SuroConnection connection = connectionPool.chooseConnection(); if (connection == null) { continue; } try { Result result = connection.send(messageSet); if (result != null && result.getResultCode() == ResultCode.OK && result.isSetMessage()) { sent = true; connectionPool.endConnection(connection); retried = i > 0; break; } else { log.error("Server is not stable: " + connection.getServer().toString()); connectionPool.markServerDown(connection); try { Thread.sleep(Math.min(i + 1, 5) * 100); } catch (InterruptedException e) {} // ignore an exception } } catch (Exception e) { log.error("Exception in send: " + e.getMessage(), e); connectionPool.markServerDown(connection); client.updateSenderException(); } } if (sent){ client.updateSendTime(System.currentTimeMillis() - startTS); client.updateSentDataStats(messageSet, retried); } else { for (Message m : new MessageSetReader(messageSet)) { client.restore(m); } } }
8920316_6
public List<Favorite> favorites() { List<Favorite> favorites = new ArrayList<>(); try { Preferences forProject = preferences(false); if (forProject != null) { String[] s = forProject.childrenNames(); for (String ch : s) { Preferences forFile = forProject.node(ch); if (forFile != null) { int val = forFile.getInt("value", 0); String name = forFile.get("name", null); if (val > 0 && name != null) { Favorite fav = new Favorite(val, name); favorites.add(fav); } } } } } catch (BackingStoreException ex) { Exceptions.printStackTrace(ex); } Collections.sort(favorites); return favorites; }
8967798_296
public S getCurrent() { S result = null; QueryParameters params = innerGetCurrent(); try { result = processor.toBean(params, this.type); } catch (MjdbcException ex) { throw new MjdbcRuntimeException(ex); } return result; }
8975145_19
public long[] sampleNumbers(Track track, Movie movie) { List<TimeToSampleBox.Entry> entries = track.getDecodingTimeEntries(); double trackLength = 0; for (Track thisTrack : movie.getTracks()) { double thisTracksLength = getDuration(thisTrack) / thisTrack.getTrackMetaData().getTimescale(); if (trackLength < thisTracksLength) { trackLength = thisTracksLength; } } int fragmentCount = (int) Math.ceil(trackLength / fragmentLength) - 1; if (fragmentCount < 1) { fragmentCount = 1; } long fragments[] = new long[fragmentCount]; Arrays.fill(fragments, -1); fragments[0] = 1; long time = 0; int samples = 0; for (TimeToSampleBox.Entry entry : entries) { for (int i = 0; i < entry.getCount(); i++) { int currentFragment = (int) (time / track.getTrackMetaData().getTimescale() / fragmentLength) + 1; if (currentFragment >= fragments.length) { break; } fragments[currentFragment] = samples++ + 1; time += entry.getDelta(); } } long last = samples + 1; // fill all -1 ones. for (int i = fragments.length - 1; i >= 0; i--) { if (fragments[i] == -1) { fragments[i] = last; } last = fragments[i]; } return fragments; }
9001689_0
@Override public void run(boolean resume) { for(AbstractTrivialInconsistencyFinder checker : incFinders){ //apply inverse functionality checker only if UNA is applied if(!(checker instanceof InverseFunctionalityBasedInconsistencyFinder) || isApplyUniqueNameAssumption()){ try { checker.run(resume); fireNumberOfConflictsFound(checker.getExplanations().size()); if(checker.terminationCriteriaSatisfied()){ break; } } catch (Exception e) { e.printStackTrace(); } } } if(!terminationCriteriaSatisfied()){ fireFinished(); completed = true; } }
9004636_25
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; FellowPlayer other = (FellowPlayer) obj; if (mId != other.mId) return false; if (mNickname == null) { if (other.mNickname != null) return false; } else if (!mNickname.equals(other.mNickname)) return false; if (Double.doubleToLongBits(mOrientation) != Double.doubleToLongBits(other.mOrientation)) return false; if (mStatus == null) { if (other.mStatus != null) return false; } else if (!mStatus.equals(other.mStatus)) return false; return true; }
9020655_0
public static <T> boolean isPresent(T t){ Optional<T>optionalObj = Optional.fromNullable(t); return optionalObj.isPresent(); }
9025424_4
public Entry metadata(String path, int fileLimit, String hash, boolean list, String rev) throws DropboxException { assertAuthenticated(); if (fileLimit <= 0) { fileLimit = METADATA_DEFAULT_LIMIT; } String[] params = { "file_limit", String.valueOf(fileLimit), "hash", hash, "list", String.valueOf(list), "rev", rev, "locale", session.getLocale().toString() }; String url_path = "/metadata/" + session.getAccessType() + path; @SuppressWarnings("unchecked") Map<String, Object> dirinfo = (Map<String, Object>) RESTUtility.request(RequestMethod.GET, session.getAPIServer(), url_path, VERSION, params, session); return new Entry(dirinfo); }
9028249_4
public static void put(String path, String key, String value) { Properties properties = getPropertiesFromPath(path); if (null == properties) { return; } properties.put(key, value); writeProperties(path, properties); }
9040104_3
public static License read(final String license) { final String trimmedLicense = license.trim(); if (sLicenses.containsKey(trimmedLicense)) { return sLicenses.get(trimmedLicense); } else { throw new IllegalStateException(String.format("no such license available: %s, did you forget to register it?", trimmedLicense)); } }
9048042_0
public Boolean call() { if (!used.getAndSet(true)) { initContext(); notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>(); compilerMain.setAPIMode(true); // 编译器入口 com.sun.tools.javac.main.Main.compile(String[], Context, List<JavaFileObject>, Iterable<? extends Processor>) result = compilerMain.compile(args, context, fileObjects, processors); cleanup(); return result == 0; } else { throw new IllegalStateException("multiple calls to method 'call'"); } }
9054533_480
public StateId createStateId(String name) { if (createdStateIds.containsKey(name)) return createdStateIds.get(name); if (stateIndexCounter >= activityStates[0].length) { activityStates = new Object[nuActivities][stateIndexCounter + 1]; vehicleDependentActivityStates = new Object[nuActivities][nuVehicleTypeKeys][stateIndexCounter + 1]; routeStatesArr = new Object[vrp.getVehicles().size() + 2][stateIndexCounter+1]; vehicleDependentRouteStatesArr = new Object[vrp.getVehicles().size() + 2][nuVehicleTypeKeys][stateIndexCounter+1]; problemStates = new Object[stateIndexCounter+1]; } StateId id = StateFactory.createId(name, stateIndexCounter); incStateIndexCounter(); createdStateIds.put(name, id); return id; }
9064832_13
public Iterator<DBObject> doubleUnwind() { BasicDBObject unwindSizes = new BasicDBObject("$unwind", "$sizes"); BasicDBObject unwindColors = new BasicDBObject("$unwind", "$colors"); BasicDBObjectBuilder group = new BasicDBObjectBuilder(); group.push("$group"); group.push("_id"); group.add("size", "$sizes"); group.add("color", "$colors"); group.pop(); group.push("count"); group.add("$sum", 1); group.pop(); group.pop(); return col.aggregate(unwindSizes, unwindColors, group.get()).results().iterator(); }
9067712_42
public int readSmallUint(int offset) { byte[] buf = this.buf; int result = (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | ((buf[offset+3]) << 24); if (result < 0) { throw new ExceptionWithContext("Encountered small uint that is out of range at offset 0x%x", offset); } return result; }
9078409_10
public static <T> CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize) { return wrap(Iterators.limit(iterator, limitSize), iterator); }
9078421_24
public AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz) { AccumuloFeatureConfig featureConfig = classToTransform.get(clazz); if(featureConfig == null) { for(Map.Entry<Class, AccumuloFeatureConfig> clazzes : classToTransform.entrySet()) { if(clazzes.getKey().isAssignableFrom(clazz)) { featureConfig = clazzes.getValue(); classToTransform.put(clazz, featureConfig); } } } return featureConfig; }
9090323_0
public static String canonicalize(final String path) { final int length = path.length(); int lastSlash = -1; StringBuilder builder = null; for (int i=0; i<length; ++i) { char c = path.charAt(i); if ((c == SLASH) || (i == length - 1)) { if (i > 0) { // neighboring slash? if ((c == SLASH) && (lastSlash == i-1)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } } else { ZNodeLabel label = ZNodeLabel.validated(path, lastSlash+1, (c == SLASH) ? i : i+1); if (ZNodeLabel.self().equals(label)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } } else if (ZNodeLabel.parent().equals(label)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } int buildLength = builder.length(); assert (builder.charAt(buildLength -1) == SLASH); int parentSlash = -1; for (int j = buildLength-2; j >= 0; j--) { if (builder.charAt(j) == SLASH) { parentSlash = j; break; } } if (parentSlash < 0) { throw new IllegalArgumentException(String.format("missing parent at index %d of %s", i, path)); } builder.delete(parentSlash + 1, buildLength); } else { if (builder != null) { builder.append(path, lastSlash+1, i+1); } } } } if (c == SLASH) { lastSlash = i; } } } String canonicalized; // trailing slash? if (builder == null) { canonicalized = ((length > 1) && (path.charAt(length - 1) == SLASH)) ? path.substring(0, length - 1) : path; } else { int buildLength = builder.length(); if ((buildLength > 1) && (builder.charAt(buildLength - 1) == SLASH)) { builder.deleteCharAt(buildLength - 1); } canonicalized = builder.toString(); } if (canonicalized.isEmpty()) { throw new IllegalArgumentException(String.format("empty canonicalized path for %s", path)); } if (canonicalized.charAt(0) != SLASH) { throw new IllegalArgumentException(String.format("not absolute path for %s", path)); } return canonicalized; }
9120355_0
public static String getFullName(Class c) { if (c == null) { throw new IllegalArgumentException("class cannot be null"); } StringBuilder name = new StringBuilder(); name.append(c.getPackage().getName()).append("."); Class klaus = c; List<Class> enclosingClasses = new ArrayList<Class>(); while ((klaus = klaus.getEnclosingClass()) != null) { enclosingClasses.add(klaus); } for (int i = enclosingClasses.size() - 1; i >= 0; i--) { name.append(enclosingClasses.get(i).getSimpleName()).append("."); } name.append(c.getSimpleName()); return name.toString(); }
9121658_5
public static PrefixMapping usedPrefixes(Query query, PrefixMapping global) { PrefixMapping local = query.getPrefixMapping(); PrefixMapping pm = global == null ? local : new PrefixMapping2(global, local); PrefixMapping result = usedReferencePrefixes(query, pm); return result; }
9143933_12
@Override public boolean remove(V v){ // Remove all edges related to v Set<GraphEdge<V, E>> edges = this.connected.get(v); if (edges == null) return false; for(Iterator<GraphEdge<V,E>> it = edges.iterator(); it.hasNext(); ){ // Remove the edge in the list of the selected vertex GraphEdge<V,E> edge = it.next(); it.remove(); V v2 = edge.getVertex1().equals(v) ? edge.getVertex2() : edge.getVertex1(); for(Iterator<GraphEdge<V,E>> it2 = this.connected.get(v2).iterator(); it2.hasNext();){ GraphEdge<V,E> edge2 = it2.next(); if (edge2.getVertex1().equals(v) || edge2.getVertex2().equals(v)){ it2.remove(); } } } this.connected.remove(v); return true; }
9158616_17
@Override public EncounterTransaction.DrugOrder mapDrugOrder(DrugOrder openMRSDrugOrder) { EncounterTransaction.DrugOrder drugOrder = new EncounterTransaction.DrugOrder(); drugOrder.setUuid(openMRSDrugOrder.getUuid()); if (openMRSDrugOrder.getCareSetting() != null) { drugOrder.setCareSetting(CareSettingType.valueOf(openMRSDrugOrder.getCareSetting().getCareSettingType().toString())); } drugOrder.setAction(openMRSDrugOrder.getAction().name()); drugOrder.setOrderType(openMRSDrugOrder.getOrderType().getName()); Order previousOrder = openMRSDrugOrder.getPreviousOrder(); if (previousOrder != null && StringUtils.isNotBlank(previousOrder.getUuid())) { drugOrder.setPreviousOrderUuid(previousOrder.getUuid()); } drugOrder.setDrugNonCoded(openMRSDrugOrder.getDrugNonCoded()); if (openMRSDrugOrder.getDrug() != null){ EncounterTransaction.Drug encounterTransactionDrug = new DrugMapper1_12().map(openMRSDrugOrder.getDrug()); drugOrder.setDrug(encounterTransactionDrug); } drugOrder.setDosingInstructionType(openMRSDrugOrder.getDosingType().getName()); drugOrder.setDuration(openMRSDrugOrder.getDuration()); drugOrder.setDurationUnits(getConceptName(openMRSDrugOrder.getDurationUnits())); drugOrder.setConcept(conceptMapper.map(openMRSDrugOrder.getConcept())); drugOrder.setScheduledDate(openMRSDrugOrder.getScheduledDate()); drugOrder.setDateActivated(openMRSDrugOrder.getDateActivated()); drugOrder.setEffectiveStartDate(openMRSDrugOrder.getEffectiveStartDate()); drugOrder.setAutoExpireDate(openMRSDrugOrder.getAutoExpireDate()); drugOrder.setEffectiveStopDate(openMRSDrugOrder.getEffectiveStopDate()); drugOrder.setDateStopped(openMRSDrugOrder.getDateStopped()); EncounterTransaction.DosingInstructions dosingInstructions = new EncounterTransaction.DosingInstructions(); dosingInstructions.setDose(openMRSDrugOrder.getDose()); dosingInstructions.setDoseUnits(getConceptName(openMRSDrugOrder.getDoseUnits())); dosingInstructions.setRoute(getConceptName(openMRSDrugOrder.getRoute())); dosingInstructions.setAsNeeded(openMRSDrugOrder.getAsNeeded()); if (openMRSDrugOrder.getFrequency() != null) { dosingInstructions.setFrequency(openMRSDrugOrder.getFrequency().getName()); } if (openMRSDrugOrder.getQuantity() != null) { dosingInstructions.setQuantity(openMRSDrugOrder.getQuantity()); } dosingInstructions.setQuantityUnits(getConceptName(openMRSDrugOrder.getQuantityUnits())); dosingInstructions.setAdministrationInstructions(openMRSDrugOrder.getDosingInstructions()); drugOrder.setDosingInstructions(dosingInstructions); drugOrder.setInstructions(openMRSDrugOrder.getInstructions()); drugOrder.setCommentToFulfiller(openMRSDrugOrder.getCommentToFulfiller()); drugOrder.setVoided(openMRSDrugOrder.getVoided()); drugOrder.setVoidReason(openMRSDrugOrder.getVoidReason()); drugOrder.setOrderNumber(openMRSDrugOrder.getOrderNumber()); drugOrder.setOrderReasonConcept(conceptMapper.map(openMRSDrugOrder.getOrderReason())); drugOrder.setOrderReasonText(openMRSDrugOrder.getOrderReasonNonCoded()); OrderGroup openMRSOrderGroup = openMRSDrugOrder.getOrderGroup(); if(openMRSOrderGroup != null) { EncounterTransaction.OrderGroup orderGroup = new EncounterTransaction.OrderGroup(openMRSOrderGroup.getUuid()); EncounterTransaction.OrderSet orderSet = new EncounterTransaction.OrderSet(openMRSOrderGroup.getOrderSet().getUuid()); orderGroup.setOrderSet(orderSet); drugOrder.setOrderGroup(orderGroup); drugOrder.setSortWeight(openMRSDrugOrder.getSortWeight()); } return drugOrder; }
9165045_20
@Override public ShapePath read(Resource resource) { checkNotNull(resource); ShapePathImpl.ShapePathImplBuilder shapePathBuilder = ShapePathImpl.builder(); shapePathBuilder.element(resource); shapePathBuilder.jenaPath(readPath(resource)); return shapePathBuilder.build(); }
9178484_0
static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); }
9196478_7
@Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; }
9239163_1
@Override public void stop(Future<Void> stopFuture) throws Exception { classLoader = null; parent = null; Future<Void> future = Future.future(); future.setHandler(result -> { // Destroy the service locator ServiceLocatorFactory.getInstance().destroy(locator); locator = null; // Pass result to the stop future if (result.succeeded()) { stopFuture.complete(); } else { stopFuture.fail(future.cause()); } }); try { // Stop the real verticle if (realVerticle != null) { realVerticle.stop(future); } else { future.complete(); } } catch (Throwable t) { future.fail(t); } }
9239473_13
@Override public Set<Class<?>> getComponents() { Set<Class<?>> set = new HashSet<>(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); Consumer<JsonArray> reader = array -> { if (array != null && array.size() > 0) { for (int i = 0; i < array.size(); i++) { try { set.add(cl.loadClass(array.getString(i))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } }; JsonArray features = config.getJsonArray(CONFIG_FEATURES, null); JsonArray components = config.getJsonArray(CONFIG_COMPONENTS, null); reader.accept(features); reader.accept(components); return set; }
9270640_1
public boolean isAuthor(){ for (UserRoleType role : getRoles()) { if (role == UserRoleType.ROLE_AUTHOR){ return true; } } return false; }
9272141_1
public boolean inScope() { List<?> l = this.lists.get(); return l != null && !l.isEmpty(); }
9272724_6
private void rollback(MongoDatabase db, Document agg) { CountDownLatch latch = new CountDownLatch(backupQueryForCollection.size() - 1); Document rollbacks = new Document(); agg.append("rollback", rollbacks); for (String s : backupQueryForCollection.keySet()) { MongoCollection<Document> from = db.getCollection(backupCollectionName(s)); MongoCollection<Document> to = db.getCollection(s); Document thisCollection = new Document(); rollbacks.append(s, thisCollection); AtomicInteger batchCount = new AtomicInteger(); from.find().batchCursor((cursor, thrown) -> { if (thrown != null) { latch.countDown(); return; } cursor.setBatchSize(50); cursor.next((List<Document> l, Throwable t2) -> { List<ReplaceOneModel<Document>> replacements = new ArrayList<>(); if (l == null) { latch.countDown(); } else { int ct = batchCount.incrementAndGet(); thisCollection.append("batch-" + ct, l.size()); for (Document d : l) { replacements.add(new ReplaceOneModel<>(new Document("_id", d.getObjectId("_id")), d)); } to.bulkWrite(replacements, (bwr, th2) -> { if (th2 != null) { thisCollection.append("batch-" + ct + "-failed", true); thisCollection.append("batch-" + ct + "-succeeded", appendThrowable(th2)); } else { thisCollection.append("batch-" + ct + "-succeeded", l.size()); } }); } }); }); } try { latch.await(); } catch (InterruptedException ex) { Exceptions.chuck(ex); } }
9283641_26
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
9289335_6
public static void main(String[] args) { System.out.println("Executing batch"); // arg validation if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } // batch processing try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { // task to repeat System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { // error handling System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); }
9291388_5
public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); }
9294731_46
protected Collection<SosTimeseries> getAvailableTimeseries(XmlObject result_xb, SosTimeseries timeserie, SOSMetadata metadata) throws XmlException, IOException { ArrayList<SosTimeseries> timeseries = new ArrayList<SosTimeseries>(); StringBuilder sb = new StringBuilder(); sb.append("declare namespace gda='"); sb.append(SoapSOSRequestBuilder_200.SOS_GDA_10_NS); sb.append("'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"); //String queryExpression = "declare namespace gda='http://www.opengis.net/sosgda/1.0'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"; XmlObject[] response = result_xb.selectPath(sb.toString()); if (response == null || response.length ==0) { sb = new StringBuilder(); sb.append("declare namespace gda='"); sb.append(SoapSOSRequestBuilder_200.SOS_GDA_10_PREFINAL_NS); sb.append("'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"); //queryExpression = "declare namespace gda='http://www.opengis.net/sos/2.0'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"; response = result_xb.selectPath(sb.toString()); } for (XmlObject xmlObject : response) { SosTimeseries addedtimeserie = new SosTimeseries(); String feature = getAttributeOfChildren(xmlObject, "featureOfInterest", "href").trim(); String phenomenon = getAttributeOfChildren(xmlObject, "observedProperty", "href").trim(); String procedure = getAttributeOfChildren(xmlObject, "procedure", "href").trim(); addedtimeserie.setFeature(new Feature(feature, metadata.getServiceUrl())); addedtimeserie.setPhenomenon(new Phenomenon(phenomenon, metadata.getServiceUrl())); addedtimeserie.setProcedure(new Procedure(procedure, metadata.getServiceUrl())); // create the category for every parameter constellation out of phenomenon and procedure String category = getLastPartOf(phenomenon) + " (" + getLastPartOf(procedure) + ")"; addedtimeserie.setCategory(new Category(category, metadata.getServiceUrl())); addedtimeserie.setOffering(new Offering(timeserie.getOfferingId(), metadata.getServiceUrl())); addedtimeserie.setSosService(new SosService(timeserie.getServiceUrl(), metadata.getVersion())); addedtimeserie.getSosService().setLabel(metadata.getTitle()); timeseries.add(addedtimeserie); } return timeseries; }
9306260_2
@Override public void validate(ConfigHelper configHelper) throws RuntimeException { for (String propertyName : configHelper.getPropertyNames()) { Class<?> desiredType = configHelper.getPropertyType(propertyName); if (desiredType == null) { // Unreferenced property -- no type information, skip validation continue; } if (desiredType == Object.class) { // Object.class is the default, skip validation continue; } String propertyValue = configHelper.getRaw(propertyName); String symbolValue = symbolSource.expandSymbols(propertyValue); // This will throw RuntimeException if type can't be coerced typeCoercer.coerce(symbolValue, desiredType); } }
9318794_6
@Process(actionType = FollowLogFile.class) public void follow(final Dispatcher.Channel channel) { if (activeLogFile == null) { channel.nack(new IllegalStateException("Unable to follow: No active log file!")); return; } navigate(new NavigateInLogFile(TAIL), channel); activeLogFile.setFollow(true); startFollowing(activeLogFile); }
9327416_435
public List<String> readLinks(final JsonReader reader, final EdmEntitySet entitySet) throws EntityProviderException { List<String> links = null; int openedObjects = 0; try { String nextName; if (reader.peek() == JsonToken.BEGIN_ARRAY) { nextName = FormatJson.RESULTS; } else { reader.beginObject(); openedObjects++; nextName = reader.nextName(); } if (FormatJson.D.equals(nextName)) { if (reader.peek() == JsonToken.BEGIN_ARRAY) { nextName = FormatJson.RESULTS; } else { reader.beginObject(); openedObjects++; nextName = reader.nextName(); } } FeedMetadataImpl feedMetadata = new FeedMetadataImpl(); if (FormatJson.COUNT.equals(nextName)) { JsonFeedConsumer.readInlineCount(reader, feedMetadata); nextName = reader.nextName(); } if (FormatJson.RESULTS.equals(nextName)) { links = readLinksArray(reader); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(FormatJson.RESULTS).addContent(nextName)); } if (reader.hasNext() && reader.peek() == JsonToken.NAME) { if (FormatJson.COUNT.equals(reader.nextName())) { JsonFeedConsumer.readInlineCount(reader, feedMetadata); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(FormatJson.COUNT).addContent(nextName)); } } for (; openedObjects > 0; openedObjects--) { reader.endObject(); } reader.peek(); // to assert end of document } catch (final IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } catch (final IllegalStateException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } return links; }
9327555_9
public String downloadFaviconFromPage(String pageUrl, String directory, String fileName) { // Try to extract the favicon URL from the page specified in the feed String faviconUrl = null; try { final FaviconExtractor extractor = new FaviconExtractor(pageUrl); new ReaderHttpClient() { @Override public Void process(InputStream is) throws Exception { extractor.readPage(is); return null; } }.open(new URL(pageUrl)); faviconUrl = extractor.getFavicon(); } catch (Exception e) { log.error("Error extracting icon from feed HTML page", e); } // Attempt to download a valid favicon from the HTML page String localFilename = null; if (faviconUrl != null) { localFilename = downloadFavicon(faviconUrl, directory, fileName); } // Attempt to download a valid favicon from guessed URLs final List<String> filenameList = ImmutableList.of( "favicon.png", "favicon.gif", "favicon.ico", "favicon.jpg", "favicon.jpeg"); Iterator<String> iterator = filenameList.iterator(); while (localFilename == null && iterator.hasNext()) { String filename = iterator.next(); faviconUrl = getFaviconUrl(pageUrl, filename); localFilename = downloadFavicon(faviconUrl, directory, fileName); } if (log.isInfoEnabled()) { if (localFilename != null) { log.info(MessageFormat.format("Favicon successfully downloaded to {0}", localFilename)); } else { log.info(MessageFormat.format("Cannot find a valid favicon for feed {0} at page {1} or at the domain root", fileName, pageUrl)); } } return localFilename; }
9340593_0
public Model validate(OntModel toBeValidated, String query) { OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); NIFNamespaces.addRLOGPrefix(model); model.setNsPrefix("mylog", logPrefix); QueryExecution qe = QueryExecutionFactory.create(query, toBeValidated); ResultSet rs = qe.execSelect(); for (; rs.hasNext(); ) { QuerySolution qs = rs.next(); Resource relatedResource = qs.getResource("resource"); Resource logLevel = qs.getResource("logLevel"); Literal message = qs.getLiteral("message"); RLOGIndividuals rli; String uri = logLevel.getURI(); if (RLOGIndividuals.FATAL.getUri().equals(uri)) { rli = RLOGIndividuals.FATAL; } else if (RLOGIndividuals.ERROR.getUri().equals(uri)) { rli = RLOGIndividuals.ERROR; } else if (RLOGIndividuals.WARN.getUri().equals(uri)) { rli = RLOGIndividuals.WARN; } else if (RLOGIndividuals.INFO.getUri().equals(uri)) { rli = RLOGIndividuals.INFO; } else if (RLOGIndividuals.DEBUG.getUri().equals(uri)) { rli = RLOGIndividuals.DEBUG; } else if (RLOGIndividuals.TRACE.getUri().equals(uri)) { rli = RLOGIndividuals.TRACE; } else { rli = RLOGIndividuals.ALL; } String m = (message == null) ? "null at " + relatedResource : message.getString(); model.add(RLOGSLF4JBinding.log(logPrefix, m, rli, this.getClass().getCanonicalName(), relatedResource.getURI(), (quiet) ? null : log)); } return model; }
9342582_1
@RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") public String showProfile() { return "profile"; }
9349244_1
public static void stopRateDialog(final Context context){ setOptOut(context, true); }
9349347_3
public static String padRight(String inputString, int size, char paddingChar) { final String stringToPad; if (inputString == null) { stringToPad = ""; } else { stringToPad = inputString; } StringBuilder padded = new StringBuilder(stringToPad); while (padded.length() < size) { padded.append(paddingChar); } return padded.toString(); }
9349893_0
public static String getOperatingSystem(String operatingSystemIndentifier) { // JOptionPane.showMessageDialog(null, operatingSystemIndentifier, "Info", // JOptionPane.ERROR_MESSAGE); if ("linux".equalsIgnoreCase(operatingSystemIndentifier)) { return OS_LINUX; } if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("windows")) { return OS_WINDOWS; } else if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("mac os x")) { return OS_MACOSX; } else { return OS_UNSUPPORTED; } }
9365128_63
@Override public String toString() { double valuePan = getNumber().doubleValue(); final double scaleFactor = getScaleFactor().doubleValue(); int i = getBasePower(); if (valuePan > 1.0) { // need to scale the value down while (valuePan >= scaleFactor && i < getMaxPower()) { valuePan = valuePan / scaleFactor; i++; } } else { while (valuePan < 1.0 && i > getMinPower()) { valuePan = valuePan * scaleFactor; i--; } } return String.format(Locale.US, "%.2f", valuePan) + " " + getScalePrefix(i) + getUnit(); }
9369619_41
public ObjectMapper mapper() { return mapper; }
9373411_52
protected IdentifierData cast(Type goalType, IdentifierData oldId) throws IntermediateCodeGeneratorException { if (oldId.getIdentifier().startsWith("#")) { IdentifierData tmpId = icg.generateTempIdentifier(oldId.getType()); icg.addQuadruple(QuadrupleFactoryJb.generateAssignment(tmpId, oldId)); oldId = tmpId; } IdentifierData newId = icg.generateTempIdentifier(goalType); icg.addQuadruple(QuadrupleFactoryJb.generateCast(newId, oldId)); return newId; }
9386489_21
public String apply(String text, String logLevel) { if (System.getProperties().containsKey(OFF_SWITCH)) { return text; } boolean displayDebugInfo = showDebugInfo(); if (config == null) config = configLoader.loadConfiguration(displayDebugInfo); String result = text; if (displayDebugInfo) System.out.println("Original log Text: [" + text + "]"); for (LogEntryFilter filter : filters) { LogEntryFilter.Context context = new LogEntryFilter.Context( result, config, displayDebugInfo, logLevel ); result = filter.filter(context); if (displayDebugInfo) System.out.println("Log text filtered by " + filter + ": [" + result + "]"); if (StringUtils.isBlank(result)) { return result; } } return result; }
9408774_14
public Log defaultLogger() { return (level, debug) -> (level == LogLevel.ERROR ? SYS_ERR : SYS_OUT) .print(level, debug); }
9431801_1
@Override public void executeCommand(final RunJobRequest request) { this.request = request; this.workflowId = contextProvider .getDecisionContext() .getWorkflowContext() .getWorkflowExecution() .getWorkflowId(); final String masterRoleName = "dm-master-role-" + workflowId; final String agentProfileName = "dm-profile-" + workflowId; new TryFinally() { @Override protected void doFinally() { Promise<Void> done = Promise.Void(); if (workerId != null) { done = ec2Activities.terminateInstance(workerId, request.getIdentity()); } done = ec2Activities.deleteInstanceProfile(agentProfileName, request.getIdentity(), done); controlActivities.deleteRole(masterRoleName, done); } @Override protected void doTry() { String taskListName = "dm-agent-tl-" + workflowId; Promise<String> masterRoleArn = controlActivities.createAgentControllerRole( masterRoleName, taskListName, request.getIdentity()); Promise<Void> profileCreated = ec2Activities.createAgentInstanceProfile( Promise.asPromise(agentProfileName), masterRoleArn, Promise.asPromise(request.getIdentity())); Promise<String> userData = controlActivities.createAgentUserData(masterRoleArn, Promise.asPromise(taskListName)); Promise<String> workerId = launchInstances(agentProfileName, userData, profileCreated); Promise<Void> set = setWorkerId(workerId); Promise<Void> ready = waitUntilWorkerReady(workerId, set); Promise<String> actionId = controlActivities.notifyActionStarted( "AgentActivities.runJob", "Start running command on instance", ready); Promise<JobResult> result = agentActivities.runJob( request.getJob(), new ActivitySchedulingOptions() .withTaskList(taskListName) .withStartToCloseTimeoutSeconds( request.getWorkerOptions().getJobTimeoutSeconds()), actionId); reportResult(actionId, result); } }; }
9434210_1
@Override public UriBuilder replaceQueryParam(String name, Object... values) { checkSsp(); if (queryParams == null) { queryParams = UriComponent.decodeQuery(query.toString(), false); query.setLength(0); } name = encode(name, UriComponent.Type.QUERY_PARAM); queryParams.remove(name); if (values == null) { return this; } for (Object value : values) { if (value == null) { throw new IllegalArgumentException("One or more of query value parameters are null"); } queryParams.add(name, encode(value.toString(), UriComponent.Type.QUERY_PARAM)); } return this; }
9454656_0
public String render() { STGroupFile templateGroup = new STGroupFile(templateGroupFile); ST template = templateGroup.getInstanceOf(templateName); if (template == null) { throw new IllegalStateException( String.format( "The template named [%s] does not exist in the template group [%s]", templateName, templateGroupFile)); } for (Map.Entry<String, String> entry : variables.entrySet()) { try { template.add(entry.getKey(), entry.getValue()); } catch (IllegalArgumentException e) { // no parameter to this template } } for (Map.Entry<String, Map<String, String>> entry : services.entrySet()) { try { template.add(entry.getKey(), entry.getValue()); } catch (IllegalArgumentException e) { // no parameter to this template } } for (Entry<String, List<Map<String, String>>> entry : serviceCollections .entrySet()) { try { template.add(entry.getKey(), new MockCluster(entry.getValue())); } catch (IllegalArgumentException e) { // no parameter to this template } } return template.render(); }
9467906_299
public static void notStartsWithText(String textToSearch, String substring, String message) { if (!StringUtils.isEmpty(textToSearch) && !StringUtils.isEmpty(substring) && textToSearch.startsWith(substring)) { throw new IllegalArgumentException(message); } }
9478484_0
@Override public List<Issue> getIssues() { return Arrays.asList(InjectedFieldInJobNotTransientDetector.ISSUE); }
9502782_0
@Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); }
9519880_0
public String getHandledExceptionList() { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); List<Element> simpleMappingException = null; simpleMappingException = XmlUtils.findElements(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop", root); Validate.notNull(simpleMappingException, "There aren't Exceptions handled by the application."); StringBuilder exceptionList = new StringBuilder("Handled Exceptions:\n"); for (Element element : simpleMappingException) { exceptionList.append(element.getAttribute("key") + "\n"); } return exceptionList.toString(); }
9530230_2
public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; }
9545480_17
public Invoker create(Object service, Invoker rootInvoker) { List<Method> timedmethods = new ArrayList<>(); List<Method> meteredmethods = new ArrayList<>(); List<Method> exceptionmeteredmethods = new ArrayList<>(); for (Method m : service.getClass().getMethods()) { if (m.isAnnotationPresent(Timed.class)) { timedmethods.add(m); } if (m.isAnnotationPresent(Metered.class)) { meteredmethods.add(m); } if (m.isAnnotationPresent(ExceptionMetered.class)) { exceptionmeteredmethods.add(m); } } Invoker invoker = rootInvoker; if (timedmethods.size() > 0) { invoker = this.timed(invoker, timedmethods); } if (meteredmethods.size() > 0) { invoker = this.metered(invoker, meteredmethods); } if (exceptionmeteredmethods.size() > 0) { invoker = this.exceptionMetered(invoker, exceptionmeteredmethods); } return invoker; }
9546194_0
public String sayHello() { return "Hello world!"; }
9553726_84
public static BigDecimal calculate(RateAndPeriods rateAndPeriods) { Objects.requireNonNull(rateAndPeriods); // (1-(1+r)^n)/1-(1+rate) final BigDecimal ONE = CalculationContext.one(); BigDecimal div = ONE.min(ONE.add(rateAndPeriods.getRate().get())); BigDecimal factor = ONE.subtract(ONE.add(rateAndPeriods.getRate().get()).pow(rateAndPeriods.getPeriods())) .divide(div, CalculationContext.mathContext()); return ONE.add(factor); }
9577793_0
public static Builder builder (String resource) { return new Builder(resource); }
9580819_6
@Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); }
9583260_14
@Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); }
9587486_0
public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; //Loop through stateMemberPositionArray (which contains positions sorted in ascending order), //inserting the relative (from the minimal boundary) boundaries and absolute edit distance //and T values in to the corresponding indices of the relevant arrays for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } ///// }
9602474_1
public String getRepositoryName() throws RepositoryException{ Session repositorySession = newSession(); try { return repositorySession.getRepository().getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME); } finally { repositorySession.logout(); } }
9617158_0
public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } }
9619226_23
public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; }
9634917_6
public String getPathwayCommonsURL() { EnrichmentMap map = emManager.getEnrichmentMap(network.getSUID()); if(map == null) return null; int port = Integer.parseInt(cy3props.getProperties().getProperty("rest.port")); String pcBaseUri = propertyManager.getValue(PropertyManager.PATHWAY_COMMONS_URL); String nodeLabel = getNodeLabel(map); try { String returnPath; if(node == null) returnPath = "/enrichmentmap/expressions/heatmap"; else returnPath = String.format("/enrichmentmap/expressions/%s/%s", network.getSUID(), node.getSUID()); String returnUri = new URIBuilder() .setScheme("http") .setHost("localhost") .setPath(returnPath) .setPort(port) .build() .toString(); String pcUri = new URIBuilder(pcBaseUri) .addParameter("uri", returnUri) .addParameter("q", nodeLabel) .build() .toString(); return pcUri; } catch(URISyntaxException e) { e.printStackTrace(); return null; } }
9650789_1
public String getXML() { StringBuilder retval = new StringBuilder(); retval.append( " " + XMLHandler.addTagValue( "connection", databaseMeta == null ? "" : databaseMeta.getName() ) ); retval.append( " " + XMLHandler.addTagValue( "schema", schemaName ) ); retval.append( " " + XMLHandler.addTagValue( "table", tablename ) ); retval.append( " " + XMLHandler.addTagValue( "specify_fields", specifyFields ) ); retval.append( " <fields>" ).append( Const.CR ); //$NON-NLS-1$ for ( int i = 0; i < fieldDatabase.length; i++ ) { retval.append( " <field>" ).append( Const.CR ); //$NON-NLS-1$ retval.append( " " ).append( XMLHandler.addTagValue( "column_name", fieldDatabase[i] ) ); //$NON-NLS-1$ //$NON-NLS-2$ retval.append( " " ).append( XMLHandler.addTagValue( "stream_name", fieldStream[i] ) ); //$NON-NLS-1$ //$NON-NLS-2$ retval.append( " </field>" ).append( Const.CR ); //$NON-NLS-1$ } retval.append( " </fields>" ).append( Const.CR ); //$NON-NLS-1$ retval.append( " " + XMLHandler.addTagValue( "exceptions_filename", exceptionsFileName ) ); retval.append( " " + XMLHandler.addTagValue( "rejected_data_filename", rejectedDataFileName ) ); retval.append( " " + XMLHandler.addTagValue( "abort_on_error", abortOnError ) ); retval.append( " " + XMLHandler.addTagValue( "direct", direct ) ); retval.append( " " + XMLHandler.addTagValue( "stream_name", streamName ) ); return retval.toString(); }
9657943_0
@GET @Produces(MediaType.APPLICATION_JSON) public String getStats() { StatsManager statsManager = this.statsManager; if (this.statsManager != null) { return JSONSerializer.serializeStatistics(statsManager.getStatistics()).toJSONString(); } return new JSONObject().toJSONString(); }
9665465_253
@Override V getValue(int index) { return values[index]; }
9667687_64
public ExecutionResult findAdminForResource( String resourceName ) { String query = "MATCH (resource:Resource {name:{resourceName}})\n" + "MATCH p=(resource)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(company)\n" + " -[:CHILD_OF*0..3]->()<-[:ALLOWED_INHERIT]-()<-[:MEMBER_OF]-(admin)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN admin.name AS admin\n" + "UNION\n" + "MATCH (resource:Resource {name:{resourceName}})\n" + "MATCH p=(resource)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(company)\n" + " <-[:ALLOWED_DO_NOT_INHERIT]-()<-[:MEMBER_OF]-(admin)\n" + "RETURN admin.name AS admin"; Map<String, Object> params = new HashMap<>(); params.put( "resourceName", resourceName ); return executionEngine.execute( query, params ); }
9685461_21
public String executePostUrl() throws IOException { return executePostUrl(""); }
9702026_7
public static Path getUserIgnoreDir() { return getUserSubdirectory(IGNORE_DIRECTORY_NAME); }
9706311_22
public Gateway select() { return closestGateway(); }
9708055_10
public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { // comment s.nextLine(); } else { structures.add(name); } } s.close(); return structures; }
9713275_247
public void markDirectoryAs(Path directory, Tag tag) { if (!isDirectory(directory)) { logger.warn("Directory {} not valid, aborting.", directory); return; } try { int addCount = 0; Iterator<Path> iter = Files.newDirectoryStream(directory).iterator(); while (iter.hasNext()) { Path current = iter.next(); if (Files.isRegularFile(current)) { markAs(current, tag); addCount++; } } logger.info("Added {} images from {} to filter list", addCount, directory); } catch (IOException e) { logger.error("Failed to add images to filter list, {}", e); } }
9721255_36
public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { // This does not need to be locked. log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); }
9731550_14
public int decode(InputStream iStream, boolean explicit) throws IOException { int codeLength = 0; if (explicit) { codeLength += id.decodeAndCheck(iStream); } BerLength length = new BerLength(); codeLength += length.decode(iStream); if (length.val < 1 || length.val > 8) { throw new IOException("Decoded length of BerInteger is not correct"); } byte[] byteCode = new byte[length.val]; if (iStream.read(byteCode, 0, length.val) < length.val) { throw new IOException("Error Decoding BerInteger"); } codeLength += length.val; val = (byteCode[0] & 0x80) == 0x80 ? -1 : 0; for (int i = 0; i < length.val; i++) { val <<= 8; val |= byteCode[i] & 0xff; } return codeLength; }
9737832_10
public static <T> List<T> myGenerate(MySupplier<T> supplier, int count) { List<T> result = new ArrayList<>(); for (int i = 0; i < count; i++) { result.add(supplier.get()); } return result; }
9754885_0
public ScorePair(MatchingConfig mc) { this.mc = mc; vt = new VectorTable(mc); modifiers = new ArrayList<Modifier>(); observed_vectors = new Hashtable<MatchVector, Long>(); }
9754983_22
public User username(String username) { this.username = username; return this; }
9755019_5
public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage, int investmentInMinutes) { Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create(); for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage, analysis.getViolations())) { double profit = profitCalculator.calculateProfit(violation); if (Math.round(profit) > 0) { violationsByProfit.put(profit, violation); } } List<Double> allProfits = new ArrayList<Double>(); for (Double profit : violationsByProfit.keySet()) { int numberOfViolations = violationsByProfit.get(profit).size(); for (int i = 0; i < numberOfViolations; i++) { allProfits.add(profit); } } Collections.sort(allProfits, new DescendingComparator<Double>()); Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet(); int toInvest = investmentInMinutes; int invested = 0; for (double profit : allProfits) { List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit)); Collections.sort(violations, new ViolationByRemediationCostsComparator()); for (QualityViolation violation : violations) { int remediationCost = violation.getRemediationCosts(); if (remediationCost <= toInvest) { invested += remediationCost; toInvest -= remediationCost; QualityRequirement requirement = violation.getRequirement(); investmentPlanEntries.add(new QualityInvestmentPlanEntry( requirement.getMetricIdentifier(), requirement.getOperator() + " " + requirement.getThreshold(), violation.getArtefact().getName(), violation.getArtefact().getShortClassName(), (int) Math.round(profit), remediationCost)); } } } final int overallProfit = calculateOverallProfit(investmentPlanEntries); return new QualityInvestmentPlan(basePackage, invested, overallProfit, calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries); }
9775946_3
public static <T> T initElements(WebDriver driver, Class<T> clazz) { T instance = instantiatePage(driver, clazz); return initElements(driver, instance); }
9779351_36
public Token read() throws IOException, LexerException { int index = in_stream.getPosition(); int line = in_stream.getLine(); int col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { // end of stream! throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of input stream when parsing operator"); } // If we have a '.' may be a literal, in which case don't want to consume here if (next == '.') { int tmp = in_stream.peek(2); if (tmp > 0 && Character.isDigit(tmp)) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Literal float encountered when operator '.' expected"); } } // Everything else we consume the first char, check it and next char cur = (char)in_stream.read(); next = in_stream.peek(); switch (cur) { case '+': switch (next) { case '+': in_stream.read(); return factory.create(TokenType.Increment, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.PlusAssign, index, line, col, 2); } return factory.create(TokenType.Plus, index, line, col); case '-': switch (next) { case '-': in_stream.read(); return factory.create(TokenType.Decrement, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.MinusAssign, index, line, col, 2); } return factory.create(TokenType.Minus, index, line, col); case '*': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.TimesAssign, index, line, col, 2); default: break; } return factory.create(TokenType.Times, index, line, col); case '/': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.DivAssign, index, line, col, 2); } return factory.create(TokenType.Div, index, line, col); case '%': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.ModAssign, index, line, col, 2); } return factory.create(TokenType.Mod, index, line, col); case '&': switch (next) { case '&': in_stream.read(); return factory.create(TokenType.LogicalAnd, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.BitwiseAndAssign, index, line, col, 2); } return factory.create(TokenType.BitwiseAnd, index, line, col); case '|': switch (next) { case '|': in_stream.read(); return factory.create(TokenType.LogicalOr, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.BitwiseOrAssign, index, line, col, 2); } return factory.create(TokenType.BitwiseOr, index, line, col); case '^': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.XorAssign, index, line, col, 2); case '^': in_stream.read(); if (in_stream.peek() == '=') { in_stream.read(); return factory.create(TokenType.PowAssign, index, line, col, 3); } return factory.create(TokenType.Pow, index, line, col, 2); } return factory.create(TokenType.Xor, index, line, col); case '!': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.NotEqual, index, line, col, 2); // != case '<': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.UnorderedOrGreater, index, line, col, 3); // !<= case '>': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.Unordered, index, line, col, 4); // !<>= } return factory.create(TokenType.UnorderedOrEqual, index, line, col, 3); // !<> } return factory.create(TokenType.UnorderedGreaterOrEqual, index, line, col, 2); // !< case '>': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.UnorderedOrLess, index, line, col, 3); // !>= default: break; } return factory.create(TokenType.UnorderedLessOrEqual, index, line, col, 2); // !> } return factory.create(TokenType.Not, index, line, col); case '~': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.TildeAssign, index, line, col, 2); } return factory.create(TokenType.Tilde, index, line, col); case '=': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.Equal, index, line, col, 2); case '>': in_stream.read(); return factory.create(TokenType.GoesTo, index, line, col, 2); } return factory.create(TokenType.Assign, index, line, col); case '<': switch (next) { case '<': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.ShiftLeftAssign, index, line, col, 3); default: break; } return factory.create(TokenType.ShiftLeft, index, line, col, 2); case '>': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.LessEqualOrGreater, index, line, col, 3); default: break; } return factory.create(TokenType.LessOrGreater, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.LessEqual, index, line, col, 2); } return factory.create(TokenType.LessThan, index, line, col); case '>': switch (next) { case '>': in_stream.read(); int p = in_stream.peek(); if (p != -1) { switch ((char)p) { case '=': in_stream.read(); return factory.create(TokenType.ShiftRightAssign, index, line, col, 3); case '>': in_stream.read(); int q = in_stream.peek(); if (q != -1 && q == '=') { in_stream.read(); return factory.create(TokenType.TripleRightShiftAssign, index, line, col, 4); } return factory.create(TokenType.ShiftRightUnsigned, index, line, col, 3); // >>> } } return factory.create(TokenType.ShiftRight, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.GreaterEqual, index, line, col, 2); } return factory.create(TokenType.GreaterThan, index, line, col); case '?': return factory.create(TokenType.Question, index, line, col); case '$': return factory.create(TokenType.Dollar, index, line, col); case ';': return factory.create(TokenType.Semicolon, index, line, col); case ':': return factory.create(TokenType.Colon, index, line, col); case ',': return factory.create(TokenType.Comma, index, line, col); case '.': if (next == '.') { in_stream.read(); int p = in_stream.peek(); if (p != -1 && p == '.') { in_stream.read(); return factory.create(TokenType.TripleDot, index, line, col, 3); } return factory.create(TokenType.DoubleDot, index, line, col, 2); } return factory.create(TokenType.Dot, index, line, col); case ')': return factory.create(TokenType.CloseParenthesis, index, line, col); case '(': return factory.create(TokenType.OpenParenthesis, index, line, col); case ']': return factory.create(TokenType.CloseSquareBracket, index, line, col); case '[': return factory.create(TokenType.OpenSquareBracket, index, line, col); case '}': return factory.create(TokenType.CloseCurlyBrace, index, line, col); case '{': return factory.create(TokenType.OpenCurlyBrace, index, line, col); case '#': return factory.create(TokenType.Hash, index, line, col); default: return null; } }
9797598_3
public List<MultiFactorAuthenticationRequestContext> resolve(@NotNull final Authentication authentication, @NotNull final WebApplicationService targetService) { String authenticationMethodAttributeName = null; final List<MultiFactorAuthenticationRequestContext> list = new ArrayList<>(); if (authentication != null && targetService != null) { final ServiceMfaData serviceMfaData = getServicesAuthenticationData(targetService); if (serviceMfaData == null || !serviceMfaData.isValid()) { logger.debug("No specific mfa role service attributes found"); return list; } logger.debug("Found MFA Role: {}", serviceMfaData); authenticationMethodAttributeName = serviceMfaData.attributeName; final Object mfaAttributeValueAsObject = authentication.getPrincipal().getAttributes().get(serviceMfaData.attributeName); if (mfaAttributeValueAsObject != null) { if (mfaAttributeValueAsObject instanceof String) { final String mfaAttributeValue = mfaAttributeValueAsObject.toString(); final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext( serviceMfaData, mfaAttributeValue, targetService); if (ctx != null) { list.add(ctx); } } else if (mfaAttributeValueAsObject instanceof List) { final List<String> mfaAttributeValues = (List<String>) mfaAttributeValueAsObject; for (final String mfaAttributeValue : mfaAttributeValues) { final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext( serviceMfaData, mfaAttributeValue, targetService); if (ctx != null) { list.add(ctx); } } } else if (mfaAttributeValueAsObject instanceof Collection) { final Collection mfaAttributeValues = (Collection) mfaAttributeValueAsObject; for (final Object mfaAttributeValue : mfaAttributeValues) { final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext( serviceMfaData, String.valueOf(mfaAttributeValue), targetService); if (ctx != null) { list.add(ctx); } } } else { logger.debug("No MFA attribute found."); } } } if (list.isEmpty()) { logger.debug("No multifactor authentication requests could be resolved based on [{}].", authenticationMethodAttributeName); return null; } return list; }
9800160_329
@Override public Representation createRepresentation(String cloudId, String representationName, String providerId) throws ProviderNotExistsException, RecordNotExistsException { Date now = new Date(); DataProvider dataProvider; // check if data provider exists if ((dataProvider = uis.getProvider(providerId)) == null) { throw new ProviderNotExistsException(String.format("Provider %s does not exist.", providerId)); } if (uis.existsCloudId(cloudId)) { Representation rep = recordDAO.createRepresentation(cloudId, representationName, providerId, now); return rep; } else { throw new RecordNotExistsException(cloudId); } }