code
stringlengths
73
34.1k
label
stringclasses
1 value
public Tree putObject(String path, Object value) { return putObjectInternal(path, getNodeValue(value), false); }
java
public static Instance readInstance(File f) { try (Reader in = makeIn(f)) { return readInstance(in); } catch (IOException e) { throw new IllegalArgumentException(e); } }
java
public static Instance readInstance(Reader r) { try { InstanceConverter c = new InstanceConverter(); return c.fromJSON(r); } catch (JSONConverterException e) { throw new IllegalArgumentException(e); } }
java
public static void write(Instance instance, File f) { try (OutputStreamWriter out = makeOut(f)) { write(instance, out); } catch (IOException e) { throw new IllegalArgumentException(e); } }
java
public static void write(Instance instance, Appendable a) { try { InstanceConverter c = new InstanceConverter(); c.toJSON(instance).writeJSONString(a); } catch (IOException | JSONConverterException e) { throw new IllegalArgumentException(e); } }
java
public static ReconfigurationPlan readReconfigurationPlan(File f) { try (Reader in = makeIn(f)) { return readReconfigurationPlan(in); } catch (IOException e) { throw new IllegalArgumentException(e); } }
java
public static ReconfigurationPlan readReconfigurationPlan(Reader r) { try { ReconfigurationPlanConverter c = new ReconfigurationPlanConverter(); return c.fromJSON(r); } catch (JSONConverterException e) { throw new IllegalArgumentException(e); } }
java
public Collection<Node> getAssociatedPGroup(Node u) { for (Collection<Node> pGrp : pGroups) { if (pGrp.contains(u)) { return pGrp; } } return Collections.emptySet(); }
java
static public Collection<URI> removeRedundantPaths(Collection<URI> uris) { List<URI> result = new ArrayList<URI>(); for (URI uri : uris) { String path = uri.getPath(); if (!path.endsWith("/")) { //$NON-NLS-1$ path += "/"; //$NON-NLS-1$ } boolean addIt = true; for (int i = 0; i < result.s...
java
static Object convert(Object object, Class<?> otherType) { if (otherType == BigDecimal.class) { if (object instanceof BigInteger) { return new BigDecimal((BigInteger) object); } else if (object instanceof Number) { return BigDecimal.valueOf(((Number) object).doubleValue()); } ...
java
public InputStream getInputStream(HttpServletRequest request, MutableObject<byte[]> sourceMapResult) throws IOException { // Check bytes before filename when reading and reverse order when setting. // The following local variables intentionally hide the instance variables. byte[] bytes = this.bytes; byte[] ...
java
public InputStream tryGetInputStream(HttpServletRequest request, MutableObject<byte[]> sourceMapResult) throws IOException { InputStream result = null; // Check bytes before filename when reading and reverse order when setting if (bytes != null || filename != null) { try { result = getInputStream(requ...
java
public void setData(byte[] bytes, byte[] sourceMap) { this.sourceMap = sourceMap; sourceMapSize = sourceMap != null ? sourceMap.length : 0; setBytes(bytes); }
java
public synchronized void delete(final ICacheManager mgr) { delete = true; if (filename != null) { mgr.deleteFileDelayed(filename); } }
java
public void persist(final ICacheManager mgr) throws IOException { if (delete) return; if (sourceMapSize == 0) { // No source map. Just stream the file mgr.createCacheFileAsync("layer.", //$NON-NLS-1$ new ByteArrayInputStream(bytes), new CreateCompletionCallback(mgr)); } else { // cache...
java
public void register(ConstraintConverter<? extends Constraint> c) { java2json.put(c.getSupportedConstraint(), c); json2java.put(c.getJSONId(), c); }
java
public Constraint fromJSON(Model mo, JSONObject in) throws JSONConverterException { checkKeys(in, "id"); Object id = in.get("id"); ConstraintConverter<? extends Constraint> c = json2java.get(id.toString()); if (c == null) { throw new JSONConverterException("No converter avail...
java
public JSONObject toJSON(Constraint o) throws JSONConverterException { ConstraintConverter c = java2json.get(o.getClass()); if (c == null) { throw new JSONConverterException("No converter available for a constraint with the '" + o.getClass() + "' className"); } return c.toJSO...
java
public List<SatConstraint> listFromJSON(Model mo, JSONArray in) throws JSONConverterException { List<SatConstraint> l = new ArrayList<>(in.size()); for (Object o : in) { if (!(o instanceof JSONObject)) { throw new JSONConverterException("Expected an array of JSONObject but go...
java
public JSONArray toJSON(Collection<SatConstraint> e) throws JSONConverterException { JSONArray arr = new JSONArray(); for (SatConstraint cstr : e) { arr.add(toJSON(cstr)); } return arr; }
java
public synchronized void clear() { _layerCache.clear(); _moduleCache.clear(); _gzipCache.clear(); for (IGenericCache cache : _namedCaches.values()) { cache.clear(); } }
java
public String toGrammarRules() { StringBuffer sb = new StringBuffer(); System.out.println("R0 -> " + this.r0String); for (int i = 1; i <= this.theRules.size(); i++) { RePairRule r = this.theRules.get(i); sb.append(THE_R).append(r.ruleNumber).append(" -> ").append(r.toRuleString()).append(" : ") ...
java
public GrammarRules toGrammarRulesData() { GrammarRules res = new GrammarRules(); GrammarRuleRecord r0 = new GrammarRuleRecord(); r0.setRuleNumber(0); r0.setRuleString(this.r0String); r0.setExpandedRuleString(this.r0ExpandedString); r0.setOccurrences(new int[] { 0 }); r0.setMeanLength(-1);...
java
public void buildIntervals(SAXRecords records, double[] originalTimeSeries, int slidingWindowSize) { records.buildIndex(); for (int ruleIdx = 1; ruleIdx <= this.theRules.size(); ruleIdx++) { RePairRule rr = this.theRules.get(ruleIdx); String[] split = rr.expandedRuleString.split(" "); ...
java
private static Class<?> fromPrimitive(Class<?> clazz) { Class<?> clazz2 = PRIMITIVE_TO_CLASS.get(clazz); return clazz2 == null ? clazz : clazz2; }
java
private static DiagnosticGroup findNamedDiagnosticGroup(String name) { final String sourceMethod = "findNamedDiagnosticGroup"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[]{name}); } DiagnosticGroup...
java
protected String postcss(HttpServletRequest request, String css, IResource res) throws IOException { if (threadScopes == null) { return css; } Context cx = Context.enter(); Scriptable threadScope = null; String result = null; try { threadScope = threadScopes.poll(SCOPE_POOL_TIMEOUT_SECONDS, Ti...
java
protected Scriptable createThreadScope(Context cx, Scriptable protoScope) { // Create the scope object Scriptable scope = cx.newObject(protoScope); scope.setPrototype(protoScope); scope.setParentScope(null); // Set "global" variable to point to global scope scope.put("global", scope, scope); //$NO...
java
public String dequote(String in) { String result = in.trim(); if (result.charAt(0) == '"' && result.charAt(result.length()-1) == '"') { return result.substring(1, result.length()-1); } if (result.charAt(0) == '\'' && result.charAt(result.length()-1) == '\'') { return result.substring(1, result.lengt...
java
public tr tr(int index) { while (trList.size() <= index) { trList.add(new tr()); } return trList.get(index); }
java
public tr addTr(Map<String, Object> attrMap) { tr tr = new tr(); tr.setAttr(attrMap); trList.add(tr); return tr; }
java
public <T extends AbstractJaxb> TableBuilder addTr(List<Object> tdList) throws TagTypeUnmatchException { return addTr(tdList, null); }
java
@SuppressWarnings("unchecked") public <T extends AbstractJaxb> TableBuilder addTr(List<Object> tdList, Map<String, Object> attrMap) throws TagTypeUnmatchException { tr tr = new tr(); tr.setAttr(attrMap); for (Object obj : tdList) { if (obj instanceof String) { ...
java
public tbody tbody(int index) { while (tbodyList.size() <= index) { tbodyList.add(new tbody()); } return tbodyList.get(index); }
java
public TableBuilder addTbody(List<List<Object>> trList) throws TagTypeUnmatchException { addTbody(trList, null); return this; }
java
public Table build() { Table table = new Table(); Thead _thead = thead.buildThead(); if (_thead != null) { table.setThead(_thead); } Tfoot _tfoot = tfoot.buildTfoot(); if (_tfoot != null) { table.setTfoot(_tfoot); } for (tbody _tbod...
java
protected String getVersion() { Manifest manifest = ManifestLoader.loadManifest(getClass()); String versionNumber = null; if (manifest != null) { versionNumber = ManifestLoader.getValue(manifest, Attributes.Name.IMPLEMENTATION_VERSION); if (versionNumber == null) { versionNumber = Manif...
java
protected void setValueInternal(String argument, char separator, GenericType<?> propertyType) { if (this.valueAlreadySet) { CliOptionDuplicateException exception = new CliOptionDuplicateException(getParameterContainer().getName()); CliStyleHandling.EXCEPTION.handle(getLogger(), exception); } //...
java
public static TIntIntHashMap makeVMIndex(Collection<Instance> instances) { TIntIntHashMap index = new TIntIntHashMap(); int p = 0; for (Instance i : instances) { Mapping m = i.getModel().getMapping(); for (Node n : m.getOnlineNodes()) { for (VM v : m.getRu...
java
public static TIntIntHashMap makeNodeIndex(Collection<Instance> instances) { TIntIntHashMap index = new TIntIntHashMap(); int p = 0; for (Instance i : instances) { Mapping m = i.getModel().getMapping(); for (Node n : m.getOfflineNodes()) { index.put(n.id()...
java
public void initialize(AbstractDetectorStreamProvider provider, DetectorStreamProcessor lastProcessor) { List<DetectorStreamProcessorFactory> factoryList = provider.getProcessorFactoryList(); int factoryCount = factoryList.size(); DetectorStreamBufferImpl buffer = new DetectorStreamBufferImpl(lastProce...
java
@Override protected String doInBackground(String... params) { // get the string from params, which is an array String user = params[0]; String password = params[1]; String bugTitle = params[2]; String bugDescription = params[3]; String deviceInfo = params[4]; ...
java
@Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result.equals("ok")) { progress.dismiss(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mActivity.showDoneAnimation(); } else { ...
java
public static void main(String[] args) throws Exception { getparseArticle(); geoparseUppercaseArticle(); resolveStanfordEntities(); // And we're done... System.out.println("\n\"That's all folks!\""); }
java
private static void getparseArticle() throws Exception { // Instantiate a CLAVIN GeoParser using the StanfordExtractor GeoParser parser = GeoParserFactory.getDefault("./IndexDirectory", new StanfordExtractor(), 1, 1, false); // Unstructured text file about Somalia to be geoparsed ...
java
private static void resolveStanfordEntities() throws IOException, ClavinException { /*##################################################################### * * Start with Stanford NER -- no need to get CLAVIN involved for now. * *#############################################...
java
public Set<String> getDependentFeatures() throws IOException { final boolean entryExitLogging = log.isLoggable(Level.FINER); final String methodName = "getDependentFeatures"; //$NON-NLS-1$ if (entryExitLogging) { log.entering(DependencyList.class.getName(), methodName); } if (!initialized) { init...
java
public void setLabel(String label) { final boolean entryExitLogging = log.isLoggable(Level.FINER); final String methodName = "setLabel"; //$NON-NLS-1$ if (entryExitLogging) { log.entering(DependencyList.class.getName(), methodName, new Object[]{label}); } this.label = label; if (entryExitLogging) ...
java
synchronized void initialize() throws IOException { if (initialized) { return; } final boolean traceLogging = log.isLoggable(Level.FINEST); final boolean entryExitLogging = log.isLoggable(Level.FINER); final String methodName = "initialize"; //$NON-NLS-1$ if (entryExitLogging) { log.entering(D...
java
void expandDependencies(String name, ModuleDepInfo depInfo, ModuleDeps expandedDependencies) throws IOException { final String methodName = "expandDependencies"; //$NON-NLS-1$ final boolean traceLogging = log.isLoggable(Level.FINEST); final boolean entryExitLogging = log.isLoggable(Level.FINER); if (entryEx...
java
private Model makeModel() { Model mo = new DefaultModel(); Mapping mapping = mo.getMapping(); int nbNodes = 300; int nbVMs = 6 * nbNodes; //Memory usage/consumption in GB ShareableResource rcMem = new ShareableResource("mem"); //A resource representing the band...
java
@Override public boolean applyAction(Model c) { if (c.getMapping().isOffline(node)) { c.getMapping().addOnlineNode(node); return true; } return false; }
java
@Override public boolean applyAction(Model m) { Mapping map = m.getMapping(); if (map.isOnline(node) && map.isRunning(vm) && map.getVMLocation(vm).equals(node)) { map.addReadyVM(vm); return true; } return false; }
java
static String formatMessage(String fmt, Object[] args) { MessageFormat formatter = new MessageFormat(fmt); Format[] formats = formatter.getFormatsByArgumentIndex(); StringBuffer msg = new StringBuffer(); formatter.format(args, msg, null); if (args.length > formats.length) { // We have extra arguement...
java
static void logResuming(String callerClass, String callerMethod, Object waitObj, long start) { long elapsed = (System.currentTimeMillis() - start)/1000; log.logp(Level.WARNING, callerClass, callerMethod, Messages.SignalUtil_2, new Object[]{Thread.currentThread().getId(), elapsed, waitObj}); }
java
protected boolean writeResponse(InputStream in, HttpServletRequest request, HttpServletResponse response) throws IOException { final String sourceMethod = "writeResponse"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.cla...
java
void logException(HttpServletRequest req, Level level, String sourceMethod, Throwable t) { if (log.isLoggable(level)) { StringBuffer sb = new StringBuffer(); // add the request URI and query args String uri = req.getRequestURI(); if (uri != null) { sb.append(uri); String queryArgs = req.get...
java
public String getPropValue (String propName){ String propValue = null; propValue = System.getProperty(propName); IServiceReference[] refs = null; if (propValue == null) { try { refs = getPlatformServices().getServiceReferences(IVariableResolver.class.getName(), "(name=" + getName() + ")"); //$NON-...
java
protected void notifyRequestListeners(RequestNotifierAction action, HttpServletRequest req, HttpServletResponse resp) throws IOException { // notify any listeners that the config has been updated IServiceReference[] refs = null; try { refs = getPlatformServices().getServiceReferences(IRequestListener.class...
java
protected void notifyConfigListeners(long seq) throws IOException { IServiceReference[] refs = null; try { refs = getPlatformServices().getServiceReferences(IConfigListener.class.getName(), "(name="+getName()+")"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (PlatformServicesException e) { if (log.isLoggable(...
java
protected void registerExtension(IAggregatorExtension ext, IAggregatorExtension before) { final String sourceMethod = "registerExtension"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[...
java
public void initialize(IConfig config) throws Exception { // Check last-modified times of resources in the overrides folders. These resources // are considered to be dynamic in a production environment and we want to // detect new/changed resources in these folders on startup so that we can clear // c...
java
protected Map<String, URI> getPathsAndAliases(InitParams initParams) { final String sourceMethod = "getPahtsAndAliases"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{initParams}); ...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected void registerLayerListener() { Dictionary dict = new Properties(); dict.put("name", getName()); //$NON-NLS-1$ registrations.add(getPlatformServices().registerService( ILayerListener.class.getName(), new AggregatorLayerListener(this), dict)); }
java
public BooleanTerm andWith(BooleanTerm other) { if (isFalse() || other.isFalse()) { // anding with false, the result is false return BooleanTerm.FALSE; } if (other.isTrue()) { // anding with true, the result is unchanged return this; } if (isTrue()) { // anding with true, other is unc...
java
static public byte[] zip(InputStream in) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); VariableGZIPOutputStream compress = new VariableGZIPOutputStream(bos, 10240); // is 10k too big? compress.setLevel(Deflater.BEST_COMPRESSION); Writer writer = new OutputStreamWriter(compre...
java
static public byte[] unzip(InputStream in) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); CopyUtil.copy(new GZIPInputStream(in), bos); return bos.toByteArray(); }
java
public static String bind(String message, Object binding) { return internalBind(message, null, String.valueOf(binding), null); }
java
public static void initializeMessages(final String bundleName, final Class clazz) { if (System.getSecurityManager() == null) { load(bundleName, clazz); return; } AccessController.doPrivileged(new PrivilegedAction() { public Object run() { load(bundleName, clazz); return null; } }); }
java
private Number parseNumber(String numberValue, Object valueSource) throws WrongValueTypeException { try { Double d = Double.valueOf(numberValue); return this.mathUtil.toSimplestNumber(d); } catch (NumberFormatException e) { throw new WrongValueTypeException(e, numberValue, valueSource, Number...
java
public List<LocationOccurrence> extractLocationNames(String text) { if (text == null) throw new IllegalArgumentException("text input to extractLocationNames should not be null"); // extract entities as <Entity Type, Start Index, Stop Index> return convertNERtoCLAVIN(namedEntityRecog...
java
public static List<LocationOccurrence> convertNERtoCLAVIN (List<Triple<String, Integer, Integer>> entities, String text) { List<LocationOccurrence> locations = new ArrayList<LocationOccurrence>(); if (entities != null) { // iterate over each entity Triple for (Tripl...
java
protected String getFunctionDescription(String functionName) { String className = getClass().getSimpleName(); StringBuilder buffer = new StringBuilder(functionName.length() + className.length() + 4); buffer.append(FUNCTION_NAME_PREFIX); buffer.append(functionName); buffer.append(" ["); buffer.a...
java
public BooleanFormula andWith(BooleanFormula other) { if (other.isTrue()) { return this; } if (other.isFalse() || isFalse()) { if (booleanTerms == null) { booleanTerms = new HashSet<BooleanTerm>(); } else { booleanTerms.clear(); } isSimplified = true; return this; } if (...
java
public boolean removeTerms(Set<BooleanTerm> toRemove) { boolean modified = false; if (toRemove == null || toRemove.iterator() == null) { modified = booleanTerms == null || size() != 0; booleanTerms = new HashSet<BooleanTerm>(); } else if (booleanTerms != null) { modified = removeAll(toRemove); }...
java
@Override public boolean addAll(Collection<? extends BooleanTerm> terms) { boolean modified = false; // a null booleanTerms means that the expression is // already true, so no need to modify it if (terms == null) { modified = booleanTerms != null; booleanTerms = null; } else if (booleanTerms !=...
java
public static TaskMonitor build(IntVar start, IntVar duration, IntVar end) { return new TaskMonitor(start, duration, end); }
java
@Override public boolean containsNode(long id) { return nodeIdMapping.containsKey(id) && !isRemoved(nodes.get(nodeIdMapping.get(id))); }
java
@Override public boolean applyAction(Model m) { Mapping map = m.getMapping(); if (!map.contains(id)) { map.addReadyVM(id); return true; } return false; }
java
public void visitResourceNames(String packageName, boolean includeSubPackages, ClassLoader classLoader, ResourceVisitor visitor) { try { String path = packageName.replace('.', '/'); if (path.isEmpty()) { LOG.debug("Scanning entire classpath..."); } else { LOG.trace("Scanning for r...
java
public boolean setPartitions(Collection<Collection<Node>> parts) { if (!isDisjoint(parts)) { return false; } partitions = parts; return true; }
java
public int run(String... args) { CliParser parser = getParserBuilder().build(this); try { CliModeObject mode = parser.parseParameters(args); if (this.help) { assert (mode.getId().equals(CliMode.ID_HELP)); printHelp(parser); return 0; } validate(mode); retur...
java
public static <T> List<T> sortedCollection(Collection<T> coll) { List<T> list = new LinkedList<T>(coll); Collections.sort(list, new UComp<T>()); return list; }
java
public static <T> String stringImg(Collection<T> coll) { StringBuffer buffer = new StringBuffer(); buffer.append("[ "); for(T t : sortedCollection(coll)) { buffer.append(t); buffer.append(" "); } buffer.append("]"); return buffer.toString(); }
java
public static <T> String stringImg(T[] v) { if(v == null) return "null"; StringBuffer buffer = new StringBuffer(); Arrays.sort(v, new UComp<T>()); for(int i=0; i<v.length; i++) { buffer.append(v[i]); buffer.append("\n"); } return buffer.toString(); }
java
@Override public List<Sync> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) { if (!checkConformance(t, args)) { return Collections.emptyList(); } @SuppressWarnings("unchecked") List<VM> s = (List<VM>) params[0].transform(this, t, args.get(0)); if (s == nu...
java
public static int getPrecisionFormat(@Nonnull final String mapcode) throws UnknownPrecisionFormatException { // First, decode to ASCII. final String decodedMapcode = convertStringToPlainAscii(mapcode).toUpperCase(); // Syntax needs to be OK. if (!PATTERN_MAPCODE.matcher(decodedMapcode)...
java
public static boolean isValidMapcodeFormat(@Nonnull final String mapcode) throws IllegalArgumentException { checkNonnull("mapcode", mapcode); try { // Throws an exception if the format is incorrect. getPrecisionFormat(mapcode.toUpperCase()); return true; } cat...
java
public static boolean containsTerritory(@Nonnull final String mapcode) throws IllegalArgumentException { checkMapcodeCode("mapcode", mapcode); return PATTERN_TERRITORY.matcher(mapcode.toUpperCase().trim()).find(); }
java
@Nonnull static String convertStringToPlainAscii(@Nonnull final String string) { return Decoder.decodeUTF16(string.toUpperCase()); }
java
public static RePairGrammar buildGrammar(SAXRecords saxRecords) { RePairGrammar grammar = NewRepair.parse(saxRecords.getSAXString(SPACE)); return grammar; }
java
public static RePairGrammar buildGrammar(String inputString) { RePairGrammar grammar = NewRepair.parse(inputString); return grammar; }
java
public String getValue(String name) { String result = null; for (InitParam initParam : initParams) { if (initParam.getName().equals(name)) { result = initParam.getValue(); break; } } return result; }
java
public Collection<String> getNames() { Collection<String> names = new HashSet<String>(); for (InitParam initParam : initParams) { names.add(initParam.getName()); } return names; }
java
public void setRefreshDelayInSeconds(int refreshDelayInSeconds) { ValueOutOfRangeException.checkRange(Integer.valueOf(refreshDelayInSeconds), MIN_DELAY, Integer.valueOf(Integer.MAX_VALUE), getClass().getSimpleName() + ".refreshDelayInSeconds"); this.refreshDelayInSeconds = refreshDelayInSeconds; ...
java
public void register(ModelViewConverter<? extends ModelView> c) { java2json.put(c.getSupportedView(), c); json2java.put(c.getJSONId(), c); }
java
public ModelView fromJSON(Model mo, JSONObject in) throws JSONConverterException { checkKeys(in, ModelViewConverter.IDENTIFIER); Object id = in.get(ModelViewConverter.IDENTIFIER); ModelViewConverter<? extends ModelView> c = json2java.get(id.toString()); if (c == null) { throw...
java
public JSONObject toJSON(ModelView o) throws JSONConverterException { ModelViewConverter c = java2json.get(o.getClass()); if (c == null) { throw new JSONConverterException("No converter available for a view with the '" + o.getClass() + "' className"); } return c.toJSON(o); ...
java
public DistanceElement getElement(long id) { if (!vector.containsKey(id)) vector.put(id, new DistanceElement(id)); return vector.get(id); }
java
public void printPathTo(long targetId) { System.out.println(getPath(targetId).stream().map(String::valueOf).reduce((s1, s2) -> s1 + " -> " + s2).get()); }
java