_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q18400
DBProperties.initialize
train
public static void initialize() { if (InfinispanCache.get().exists(DBProperties.CACHENAME)) { InfinispanCache.get().<String, String>getCache(DBProperties.CACHENAME).clear(); } else { InfinispanCache.get().<String, String>getCache(DBProperties.CACHENAME) .addListener(new CacheLogListener(DBProperties.LOG)); } DBProperties.cacheOnStart(); }
java
{ "resource": "" }
q18401
MessageStatusHolder.getReadCount
train
public static int getReadCount(final Long _userId) { int ret = 0; if (MessageStatusHolder.CACHE.userID2Read.containsKey(_userId)) { ret = MessageStatusHolder.CACHE.userID2Read.get(_userId); } return ret; }
java
{ "resource": "" }
q18402
MessageStatusHolder.getUnReadCount
train
public static int getUnReadCount(final Long _userId) { int ret = 0; if (MessageStatusHolder.CACHE.userID2UnRead.containsKey(_userId)) { ret = MessageStatusHolder.CACHE.userID2UnRead.get(_userId); } return ret; }
java
{ "resource": "" }
q18403
Bezier.setNode
train
public void setNode(int number, Vector3D v) { setNode(number, v.getX(), v.getY(), v.getZ()); }
java
{ "resource": "" }
q18404
Bezier.setAnchorColor
train
public void setAnchorColor(int index, Color color) { if (index <= 0) { if (startColor == null) { startColor = new RGBColor(0.0, 0.0, 0.0); } setGradation(true); this.startColor = color; } else if (index >= 1) { if (endColor == null) { endColor = new RGBColor(0.0, 0.0, 0.0); } setGradation(true); this.endColor = color; } }
java
{ "resource": "" }
q18405
Text.getWidth
train
public final double getWidth(int line) { if (strArray.length == 0) return 0.0; try { return textRenderer.getBounds(strArray[line]).getWidth(); } catch (GLException e) { reset = true; } return 0.0; }
java
{ "resource": "" }
q18406
Text.setFont
train
public final void setFont(Font font) { this.font = font; textRenderer = new TextRenderer(font.getAWTFont(), true, true); }
java
{ "resource": "" }
q18407
Evaluation.getPermissionSet
train
public static PermissionSet getPermissionSet(final Instance _instance) throws EFapsException { Evaluation.LOG.debug("Evaluation PermissionSet for {}", _instance); final Key accessKey = Key.get4Instance(_instance); final PermissionSet ret = AccessCache.getPermissionCache().get(accessKey); Evaluation.LOG.debug("Evaluated PermissionSet {}", ret); return ret; }
java
{ "resource": "" }
q18408
Evaluation.getPermissionSet
train
public static PermissionSet getPermissionSet(final Instance _instance, final boolean _evaluate) throws EFapsException { Evaluation.LOG.debug("Retrieving PermissionSet for {}", _instance); final Key accessKey = Key.get4Instance(_instance); final PermissionSet ret; if (AccessCache.getPermissionCache().containsKey(accessKey)) { ret = AccessCache.getPermissionCache().get(accessKey); } else if (_evaluate) { ret = new PermissionSet().setPersonId(accessKey.getPersonId()).setCompanyId(accessKey.getCompanyId()) .setTypeId(accessKey.getTypeId()); Evaluation.eval(ret); AccessCache.getPermissionCache().put(accessKey, ret); } else { ret = null; } Evaluation.LOG.debug("Retrieved PermissionSet {}", ret); return ret; }
java
{ "resource": "" }
q18409
Evaluation.getStatus
train
public static Status getStatus(final Instance _instance) throws EFapsException { Evaluation.LOG.debug("Retrieving Status for {}", _instance); long statusId = 0; if (_instance.getType().isCheckStatus()) { final Cache<String, Long> cache = AccessCache.getStatusCache(); if (cache.containsKey(_instance.getKey())) { statusId = cache.get(_instance.getKey()); } else { final PrintQuery print = new PrintQuery(_instance); print.addAttribute(_instance.getType().getStatusAttribute()); print.executeWithoutAccessCheck(); final Long statusIdTmp = print.getAttribute(_instance.getType().getStatusAttribute()); statusId = statusIdTmp == null ? 0 : statusIdTmp; cache.put(_instance.getKey(), statusId); } } final Status ret = statusId > 0 ? Status.get(statusId) : null; Evaluation.LOG.debug("Retrieve Status: {}", ret); return ret; }
java
{ "resource": "" }
q18410
Evaluation.evalStatus
train
public static void evalStatus(final Collection<Instance> _instances) throws EFapsException { Evaluation.LOG.debug("Evaluating Status for {}", _instances); if (CollectionUtils.isNotEmpty(_instances)) { final Cache<String, Long> cache = AccessCache.getStatusCache(); final List<Instance> instances = _instances.stream().filter(inst -> !cache.containsKey(inst.getKey())) .collect(Collectors.toList()); if (!instances.isEmpty()) { final Attribute attr = instances.get(0).getType().getStatusAttribute(); final MultiPrintQuery multi = new MultiPrintQuery(instances); multi.addAttribute(attr); multi.executeWithoutAccessCheck(); while (multi.next()) { final Long statusId = multi.getAttribute(attr); cache.put(multi.getCurrentInstance().getKey(), statusId == null ? 0 : statusId); } } } }
java
{ "resource": "" }
q18411
RU.addZerosBefore
train
public static String addZerosBefore(String orderNo, int count) { if (orderNo == null) { return "";// orderNo = ""; } if (orderNo.length() > count) { orderNo = "?" + orderNo.substring(orderNo.length() - count - 1, orderNo.length() - 1); } else { int le = orderNo.length(); for (int i = 0; i < count - le; i++) { orderNo = "0" + orderNo; } } return orderNo; }
java
{ "resource": "" }
q18412
Import.getSeries
train
public Map<String, Set<DataPoint>> getSeries() { return new HashMap<String, Set<DataPoint>>(store); }
java
{ "resource": "" }
q18413
Import.addDataPoint
train
public void addDataPoint(String series, DataPoint dataPoint) { DataSet set = store.get(series); if (set == null) { set = new DataSet(); store.put(series, set); } set.add(dataPoint); }
java
{ "resource": "" }
q18414
Import.addDataPointSet
train
public void addDataPointSet(String series, Set<DataPoint> dataPoints) { DataSet set = store.get(series); if (set == null) { set = new DataSet(dataPoints); store.put(series, set); } else { set.addAll(dataPoints); } }
java
{ "resource": "" }
q18415
Import.serialize
train
public JSONObject serialize(Map<String, Object> out) { JSONObject json = new JSONObject(); json.put("device_id", deviceId); json.put("project_id", projectId); out.put("device_id", deviceId); out.put("project_id", projectId); JSONArray sourcesArr = new JSONArray(); List<String> sourceNames = new ArrayList<String>(store.keySet()); Collections.sort(sourceNames); for (String k : sourceNames) { JSONObject temp = new JSONObject(); temp.put("name", k); JSONArray dataArr = new JSONArray(); for (DataPoint d : store.get(k)) { dataArr.put(d.toJson()); } temp.put("data", dataArr); sourcesArr.put(temp); } json.put("sources", sourcesArr); out.put("sources", sourcesArr); return json; }
java
{ "resource": "" }
q18416
Polygon.getVertex
train
public Vector3D getVertex(int index) { tmpV.setX(cornerX.get(index)); tmpV.setY(cornerY.get(index)); tmpV.setZ(cornerZ.get(index)); calcG(); return tmpV; }
java
{ "resource": "" }
q18417
Polygon.removeVertex
train
public void removeVertex(int index) { this.cornerX.remove(index); this.cornerY.remove(index); this.cornerZ.remove(index); if (isGradation() == true) this.cornerColor.remove(index); setNumberOfCorner(this.cornerX.size()); calcG(); }
java
{ "resource": "" }
q18418
Polygon.setVertex
train
public void setVertex(int i, double x, double y, double z) { this.cornerX.set(i, x); this.cornerY.set(i, y); this.cornerZ.set(i, z); calcG(); }
java
{ "resource": "" }
q18419
Polygon.setCornerColor
train
public void setCornerColor(int index, Color color) { if (cornerColor == null) { for (int i = 0; i < cornerX.size(); i++) { cornerColor.add(new RGBColor(this.fillColor.getRed(), this.fillColor.getGreen(), this.fillColor.getBlue(), this.fillColor.getAlpha())); } setGradation(true); } if (cornerColor.size() < cornerX.size()) { while (cornerColor.size() != cornerX.size()) { cornerColor.add(new RGBColor(this.fillColor.getRed(), this.fillColor.getGreen(), this.fillColor.getBlue(), this.fillColor.getAlpha())); } } cornerColor.set(index, color); }
java
{ "resource": "" }
q18420
DataPointParser.parse
train
public static List<DataPoint> parse(int[] values, long ts) { List<DataPoint> ret = new ArrayList<DataPoint>(values.length); for (int v : values) { ret.add(new DataPoint(ts, v)); } return ret; }
java
{ "resource": "" }
q18421
Accumulation.when
train
@SuppressWarnings("unchecked") @SafeVarargs public static <G, ERR> Or<G, Every<ERR>> when(Or<? extends G, ? extends Every<? extends ERR>> or, Function<? super G, ? extends Validation<ERR>>... validations) { return when(or, Stream.of(validations)); }
java
{ "resource": "" }
q18422
Accumulation.withGood
train
public static <A, B, ERR, RESULT> Or<RESULT, Every<ERR>> withGood( Or<? extends A, ? extends Every<? extends ERR>> a, Or<? extends B, ? extends Every<? extends ERR>> b, BiFunction<? super A, ? super B, ? extends RESULT> function) { if (allGood(a, b)) return Good.of(function.apply(a.get(), b.get())); else { return getBads(a, b); } }
java
{ "resource": "" }
q18423
Lines.getVertex
train
public Vector3D getVertex(int i) { tmpV.setX(x.get(i)); tmpV.setY(y.get(i)); tmpV.setZ(z.get(i)); calcG(); return tmpV; }
java
{ "resource": "" }
q18424
Lines.removeVertex
train
public void removeVertex(int i) { this.x.remove(i); this.y.remove(i); this.z.remove(i); this.colors.remove(i); calcG(); }
java
{ "resource": "" }
q18425
Lines.setVertex
train
public void setVertex(int i, double x, double y) { this.x.set(i, x); this.y.set(i, y); this.z.set(i, 0d); calcG(); }
java
{ "resource": "" }
q18426
Lines.setStartCornerColor
train
public void setStartCornerColor(Color color) { if (startColor == null) { startColor = new RGBColor(0.0, 0.0, 0.0); } setGradation(true); this.startColor = color; }
java
{ "resource": "" }
q18427
Lines.setEndCornerColor
train
public void setEndCornerColor(Color color) { if (endColor == null) { endColor = new RGBColor(0.0, 0.0, 0.0); } setGradation(true); this.endColor = color; }
java
{ "resource": "" }
q18428
Lines.setCornerColor
train
public void setCornerColor(int index, Color color) { if (!cornerGradation) { cornerGradation = true; } colors.set(index, color); }
java
{ "resource": "" }
q18429
NFAState.hasTransitionTo
train
public boolean hasTransitionTo(CharRange condition, NFAState<T> state) { Set<Transition<NFAState<T>>> set = transitions.get(condition); if (set != null) { for (Transition<NFAState<T>> tr : set) { if (state.equals(tr.getTo())) { return true; } } } return false; }
java
{ "resource": "" }
q18430
NFAState.getConditionsTo
train
public RangeSet getConditionsTo(NFAState<T> state) { RangeSet rs = new RangeSet(); for (CharRange range : transitions.keySet()) { if (range != null) { Set<Transition<NFAState<T>>> set2 = transitions.get(range); for (Transition<NFAState<T>> tr : set2) { if (state.equals(tr.getTo())) { rs.add(range); } } } } return rs; }
java
{ "resource": "" }
q18431
NFAState.isSingleEpsilonOnly
train
public static boolean isSingleEpsilonOnly(Set<Transition<NFAState>> set) { if (set.size() != 1) { return false; } for (Transition<NFAState> tr : set) { if (tr.isEpsilon()) { return true; } } return false; }
java
{ "resource": "" }
q18432
NFAState.isDeadEnd
train
boolean isDeadEnd(Set<NFAState<T>> nfaSet) { for (Set<Transition<NFAState<T>>> set : transitions.values()) { for (Transition<NFAState<T>> t : set) { if (!nfaSet.contains(t.getTo())) { return false; } } } return true; }
java
{ "resource": "" }
q18433
NFAState.constructDFA
train
public DFAState<T> constructDFA(Scope<DFAState<T>> dfaScope) { Map<Set<NFAState<T>>,DFAState<T>> all = new HashMap<>(); Deque<DFAState<T>> unmarked = new ArrayDeque<>(); Set<NFAState<T>> startSet = epsilonClosure(dfaScope); DFAState<T> startDfa = new DFAState<>(dfaScope, startSet); all.put(startSet, startDfa); unmarked.add(startDfa); while (!unmarked.isEmpty()) { DFAState<T> dfa = unmarked.pop(); for (CharRange c : dfa.possibleMoves()) { Set<NFAState<T>> moveSet = dfa.nfaTransitsFor(c); if (!moveSet.isEmpty()) { Set<NFAState<T>> newSet = epsilonClosure(dfaScope, moveSet); DFAState<T> ndfa = all.get(newSet); if (ndfa == null) { ndfa = new DFAState<>(dfaScope, newSet); all.put(newSet, ndfa); unmarked.add(ndfa); } dfa.addTransition(c, ndfa); } } } // optimize for (DFAState<T> dfa : all.values()) { dfa.removeTransitionsFromAcceptImmediatelyStates(); } for (DFAState<T> dfa : all.values()) { dfa.removeDeadEndTransitions(); } for (DFAState<T> dfa : startDfa) { dfa.optimizeTransitions(); } return startDfa; }
java
{ "resource": "" }
q18434
NFAState.getConditions
train
RangeSet getConditions() { RangeSet is = new RangeSet(); for (CharRange ic : transitions.keySet()) { if (ic != null) { is.add(ic); } } return is; }
java
{ "resource": "" }
q18435
NFAState.epsilonTransitions
train
private Set<NFAState<T>> epsilonTransitions(StateVisitSet<NFAState<T>> marked) { marked.add(this); Set<NFAState<T>> set = new HashSet<>(); for (NFAState<T> nfa : epsilonTransit()) { if (!marked.contains(nfa)) { set.add(nfa); set.addAll(nfa.epsilonTransitions(marked)); } } return set; }
java
{ "resource": "" }
q18436
NFAState.epsilonClosure
train
public Set<NFAState<T>> epsilonClosure(Scope<DFAState<T>> scope) { Set<NFAState<T>> set = new HashSet<>(); set.add(this); return epsilonClosure(scope, set); }
java
{ "resource": "" }
q18437
NFAState.addTransition
train
public void addTransition(RangeSet rs, NFAState<T> to) { for (CharRange c : rs) { addTransition(c, to); } edges.add(to); to.inStates.add(this); }
java
{ "resource": "" }
q18438
NFAState.addTransition
train
public Transition<NFAState<T>> addTransition(CharRange condition, NFAState<T> to) { Transition<NFAState<T>> t = new Transition<>(condition, this, to); Set<Transition<NFAState<T>>> set = transitions.get(t.getCondition()); if (set == null) { set = new HashSet<>(); transitions.put(t.getCondition(), set); } set.add(t); edges.add(to); to.inStates.add(this); return t; }
java
{ "resource": "" }
q18439
NFAState.addEpsilon
train
public void addEpsilon(NFAState<T> to) { Transition<NFAState<T>> t = new Transition<>(this, to); Set<Transition<NFAState<T>>> set = transitions.get(null); if (set == null) { set = new HashSet<>(); transitions.put(null, set); } set.add(t); edges.add(to); to.inStates.add(this); }
java
{ "resource": "" }
q18440
AbstractValueSelect.addChildValueSelect
train
public void addChildValueSelect(final AbstractValueSelect _valueSelect) throws EFapsException { if (this.child == null) { this.child = _valueSelect; _valueSelect.setParentValueSelect(this); } else { this.child.addChildValueSelect(_valueSelect); } }
java
{ "resource": "" }
q18441
AbstractValueSelect.getValue
train
public Object getValue(final List<Object> _objectList) throws EFapsException { final List<Object> ret = new ArrayList<Object>(); for (final Object object : _objectList) { ret.add(getValue(object)); } return _objectList.size() > 0 ? (ret.size() > 1 ? ret : ret.get(0)) : null; }
java
{ "resource": "" }
q18442
SQLRunner.preparePrint
train
private void preparePrint(final AbstractPrint _print) throws EFapsException { for (final Select select : _print.getSelection().getAllSelects()) { for (final AbstractElement<?> element : select.getElements()) { if (element instanceof AbstractDataElement) { ((AbstractDataElement<?>) element).append2SQLSelect(sqlSelect); } } } if (sqlSelect.getColumns().size() > 0) { for (final Select select : _print.getSelection().getAllSelects()) { for (final AbstractElement<?> element : select.getElements()) { if (element instanceof AbstractDataElement) { ((AbstractDataElement<?>) element).append2SQLWhere(sqlSelect.getWhere()); } } } if (_print instanceof ObjectPrint) { addWhere4ObjectPrint((ObjectPrint) _print); } else if (_print instanceof ListPrint) { addWhere4ListPrint((ListPrint) _print); } else { addTypeCriteria((QueryPrint) _print); addWhere4QueryPrint((QueryPrint) _print); } addCompanyCriteria(_print); } }
java
{ "resource": "" }
q18443
SQLRunner.addTypeCriteria
train
private void addTypeCriteria(final QueryPrint _print) { final MultiValuedMap<TableIdx, TypeCriteria> typeCriterias = MultiMapUtils.newListValuedHashMap(); final List<Type> types = _print.getTypes().stream() .sorted((type1, type2) -> Long.compare(type1.getId(), type2.getId())) .collect(Collectors.toList()); for (final Type type : types) { final String tableName = type.getMainTable().getSqlTable(); final TableIdx tableIdx = sqlSelect.getIndexer().getTableIdx(tableName); if (tableIdx.isCreated()) { sqlSelect.from(tableIdx.getTable(), tableIdx.getIdx()); } if (type.getMainTable().getSqlColType() != null) { typeCriterias.put(tableIdx, new TypeCriteria(type.getMainTable().getSqlColType(), type.getId())); } } if (!typeCriterias.isEmpty()) { final SQLWhere where = sqlSelect.getWhere(); for (final TableIdx tableIdx : typeCriterias.keySet()) { final Collection<TypeCriteria> criterias = typeCriterias.get(tableIdx); final Iterator<TypeCriteria> iter = criterias.iterator(); final TypeCriteria typeCriteria = iter.next(); final Criteria criteria = where.addCriteria(tableIdx.getIdx(), typeCriteria.sqlColType, iter.hasNext() ? Comparison.IN : Comparison.EQUAL, String.valueOf(typeCriteria.id), Connection.AND); while (iter.hasNext()) { criteria.value(String.valueOf(iter.next().id)); } } } }
java
{ "resource": "" }
q18444
SQLRunner.executeUpdates
train
private void executeUpdates() throws EFapsException { ConnectionResource con = null; try { con = Context.getThreadContext().getConnectionResource(); for (final Entry<SQLTable, AbstractSQLInsertUpdate<?>> entry : updatemap.entrySet()) { ((SQLUpdate) entry.getValue()).execute(con); } } catch (final SQLException e) { throw new EFapsException(SQLRunner.class, "executeOneCompleteStmt", e); } }
java
{ "resource": "" }
q18445
SQLRunner.executeSQLStmt
train
@SuppressWarnings("unchecked") protected boolean executeSQLStmt(final ISelectionProvider _sqlProvider, final String _complStmt) throws EFapsException { SQLRunner.LOG.debug("SQL-Statement: {}", _complStmt); boolean ret = false; List<Object[]> rows = new ArrayList<>(); boolean cached = false; if (runnable.has(StmtFlag.REQCACHED)) { final QueryKey querykey = QueryKey.get(Context.getThreadContext().getRequestId(), _complStmt); final Cache<QueryKey, Object> cache = QueryCache.getSqlCache(); if (cache.containsKey(querykey)) { final Object object = cache.get(querykey); if (object instanceof List) { rows = (List<Object[]>) object; } cached = true; } } if (!cached) { ConnectionResource con = null; try { con = Context.getThreadContext().getConnectionResource(); final Statement stmt = con.createStatement(); final ResultSet rs = stmt.executeQuery(_complStmt); final ArrayListHandler handler = new ArrayListHandler(Context.getDbType().getRowProcessor()); rows = handler.handle(rs); rs.close(); stmt.close(); } catch (final SQLException e) { throw new EFapsException(SQLRunner.class, "executeOneCompleteStmt", e); } if (runnable.has(StmtFlag.REQCACHED)) { final ICacheDefinition cacheDefinition = new ICacheDefinition() { @Override public long getLifespan() { return 5; } @Override public TimeUnit getLifespanUnit() { return TimeUnit.MINUTES; } }; QueryCache.put(cacheDefinition, QueryKey.get(Context.getThreadContext().getRequestId(), _complStmt), rows); } } for (final Object[] row : rows) { for (final Select select : _sqlProvider.getSelection().getAllSelects()) { select.addObject(row); } ret = true; } return ret; }
java
{ "resource": "" }
q18446
EventQueueManager.processTedQueue
train
void processTedQueue() { int totalProcessing = context.taskManager.calcWaitingTaskCountInAllChannels(); if (totalProcessing >= TaskManager.LIMIT_TOTAL_WAIT_TASKS) { logger.warn("Total size of waiting tasks ({}) already exceeded limit ({}), skip this iteration (2)", totalProcessing, TaskManager.LIMIT_TOTAL_WAIT_TASKS); return; } Channel channel = context.registry.getChannelOrMain(Model.CHANNEL_QUEUE); int maxTask = context.taskManager.calcChannelBufferFree(channel); maxTask = Math.min(maxTask, 50); Map<String, Integer> channelSizes = new HashMap<String, Integer>(); channelSizes.put(Model.CHANNEL_QUEUE, maxTask); List<TaskRec> heads = tedDao.reserveTaskPortion(channelSizes); if (heads.isEmpty()) return; for (final TaskRec head : heads) { logger.debug("exec eventQueue for '{}', headTaskId={}", head.key1, head.taskId); channel.workers.execute(new TedRunnable(head) { @Override public void run() { processEventQueue(head); } }); } }
java
{ "resource": "" }
q18447
EventQueueManager.processEventQueue
train
private void processEventQueue(final TaskRec head) { final TedResult headResult = processEvent(head); TaskConfig tc = context.registry.getTaskConfig(head.name); if (tc == null) { context.taskManager.handleUnknownTasks(asList(head)); return; } TaskRec lastUnsavedEvent = null; TedResult lastUnsavedResult = null; // try to execute next events, while head is reserved. some events may be created while executing current if (headResult.status == TedStatus.DONE) { outer: for (int i = 0; i < 10; i++) { List<TaskRec> events = tedDaoExt.eventQueueGetTail(head.key1); if (events.isEmpty()) break outer; for (TaskRec event : events) { TaskConfig tc2 = context.registry.getTaskConfig(event.name); if (tc2 == null) break outer; // unknown task, leave it for later TedResult result = processEvent(event); // DONE - final status, on which can continue with next event if (result.status == TedStatus.DONE) { saveResult(event, result); } else { lastUnsavedEvent = event; lastUnsavedResult = result; break outer; } } } } // first save head, otherwise unique index will fail final TedResult finalLastUnsavedResult = lastUnsavedResult; final TaskRec finalLastUnsavedEvent = lastUnsavedEvent; tedDaoExt.runInTx(new Runnable() { @Override public void run() { try { saveResult(head, headResult); if (finalLastUnsavedResult != null) { saveResult(finalLastUnsavedEvent, finalLastUnsavedResult); } } catch (Exception e) { logger.error("Error while finishing events queue execution", e); } } }); }
java
{ "resource": "" }
q18448
SystemUtil.getAllProperties
train
static public String[] getAllProperties() { java.util.Properties prop = System.getProperties(); java.util.ArrayList<String> list = new java.util.ArrayList<String>(); java.util.Enumeration<?> enumeration = prop.propertyNames(); while (enumeration.hasMoreElements()) { list.add((String)enumeration.nextElement()); } return list.toArray(new String[0]); }
java
{ "resource": "" }
q18449
Perspective.set
train
public void set(double fov, double aspect, double zNear, double zFar) { this.fov = fov; this.aspect = aspect; this.zNear = zNear; this.zFar = zFar; }
java
{ "resource": "" }
q18450
CharRange.removeOverlap
train
public static List<CharRange> removeOverlap(CharRange r1, CharRange r2) { assert r1.intersect(r2); List<CharRange> list = new ArrayList<CharRange>(); Set<Integer> set = new TreeSet<Integer>(); set.add(r1.getFrom()); set.add(r1.getTo()); set.add(r2.getFrom()); set.add(r2.getTo()); int p = 0; for (int r : set) { if (p != 0) { list.add(new CharRange(p, r)); } p = r; } return list; }
java
{ "resource": "" }
q18451
Collection.getHrefResolved
train
public String getHrefResolved() { if (Atom10Parser.isAbsoluteURI(href)) { return href; } else if (baseURI != null && collectionElement != null) { final int lastslash = baseURI.lastIndexOf("/"); return Atom10Parser.resolveURI(baseURI.substring(0, lastslash), collectionElement, href); } return null; }
java
{ "resource": "" }
q18452
Collection.getHrefResolved
train
public String getHrefResolved(final String relativeUri) { if (Atom10Parser.isAbsoluteURI(relativeUri)) { return relativeUri; } else if (baseURI != null && collectionElement != null) { final int lastslash = baseURI.lastIndexOf("/"); return Atom10Parser.resolveURI(baseURI.substring(0, lastslash), collectionElement, relativeUri); } return null; }
java
{ "resource": "" }
q18453
Collection.accepts
train
public boolean accepts(final String ct) { for (final Object element : accepts) { final String accept = (String) element; if (accept != null && accept.trim().equals("*/*")) { return true; } final String entryType = "application/atom+xml"; final boolean entry = entryType.equals(ct); if (entry && null == accept) { return true; } else if (entry && "entry".equals(accept)) { return true; } else if (entry && entryType.equals(accept)) { return true; } else { final String[] rules = accepts.toArray(new String[accepts.size()]); for (final String rule2 : rules) { String rule = rule2.trim(); if (rule.equals(ct)) { return true; } final int slashstar = rule.indexOf("/*"); if (slashstar > 0) { rule = rule.substring(0, slashstar + 1); if (ct.startsWith(rule)) { return true; } } } } } return false; }
java
{ "resource": "" }
q18454
Collection.collectionToElement
train
public Element collectionToElement() { final Collection collection = this; final Element element = new Element("collection", AtomService.ATOM_PROTOCOL); element.setAttribute("href", collection.getHref()); final Element titleElem = new Element("title", AtomService.ATOM_FORMAT); titleElem.setText(collection.getTitle()); if (collection.getTitleType() != null && !collection.getTitleType().equals("TEXT")) { titleElem.setAttribute("type", collection.getTitleType(), AtomService.ATOM_FORMAT); } element.addContent(titleElem); // Loop to create <app:categories> elements for (final Object element2 : collection.getCategories()) { final Categories cats = (Categories) element2; element.addContent(cats.categoriesToElement()); } for (final Object element2 : collection.getAccepts()) { final String range = (String) element2; final Element acceptElem = new Element("accept", AtomService.ATOM_PROTOCOL); acceptElem.setText(range); element.addContent(acceptElem); } return element; }
java
{ "resource": "" }
q18455
Matrix2D.rotate
train
public void rotate(double angle) { double s = Math.sin(angle); double c = Math.cos(angle); double temp1 = m00; double temp2 = m01; m00 = c * temp1 + s * temp2; m01 = -s * temp1 + c * temp2; temp1 = m10; temp2 = m11; m10 = c * temp1 + s * temp2; m11 = -s * temp1 + c * temp2; }
java
{ "resource": "" }
q18456
Matrix2D.mult
train
public Vector3D mult(Vector3D source) { Vector3D result = new Vector3D(); result.setX(m00 * source.getX() + m01 * source.getY() + m02); result.setY(m10 * source.getX() + m11 * source.getY() + m12); return result; }
java
{ "resource": "" }
q18457
Matrix2D.invert
train
public boolean invert() { double determinant = determinant(); if (Math.abs(determinant) <= Double.MIN_VALUE) { return false; } double t00 = m00; double t01 = m01; double t02 = m02; double t10 = m10; double t11 = m11; double t12 = m12; m00 = t11 / determinant; m10 = -t10 / determinant; m01 = -t01 / determinant; m11 = t00 / determinant; m02 = (t01 * t12 - t11 * t02) / determinant; m12 = (t10 * t02 - t00 * t12) / determinant; return true; }
java
{ "resource": "" }
q18458
RestDocObject.setAdditionalField
train
@JsonAnySetter public void setAdditionalField(final String key, final Object value) { this.additionalFields.put(key, value); }
java
{ "resource": "" }
q18459
GenClassFactory.getGenInstance
train
public static Object getGenInstance(Class<?> cls, Object... args) throws ParserException { Class<?> parserClass = getGenClass(cls); try { if (args.length == 0) { return parserClass.newInstance(); } else { for (Constructor constructor : parserClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == args.length) { boolean match = true; int index = 0; for (Class c : parameterTypes) { if (!c.isAssignableFrom(args[index++].getClass())) { match = false; break; } } if (match) { return constructor.newInstance(args); } } } throw new IllegalArgumentException("no required constructor for "+cls); } } catch (InstantiationException | IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { throw new ParserException(ex); } }
java
{ "resource": "" }
q18460
GenClassFactory.getGenClass
train
public static Class<?> getGenClass(Class<?> cls) throws ParserException { GenClassname genClassname = cls.getAnnotation(GenClassname.class); if (genClassname == null) { throw new IllegalArgumentException("@GenClassname not set in "+cls); } try { return loadGenClass(cls); } catch (ClassNotFoundException ex) { throw new ParserException(cls+" classes implementation class not compiled.\n"+ "Possible problem with annotation processor.\n"+ "Try building the whole project and check that implementation class "+genClassname.value()+" exist!"); /* try { GenClassCompiler pc = GenClassCompiler.compile(El.getTypeElement(cls.getCanonicalName()), null); return pc.loadDynamic(); } catch (IOException ex1) { throw new ParserException(ex1); } */ } }
java
{ "resource": "" }
q18461
GenClassFactory.createDynamicInstance
train
public static Object createDynamicInstance(Class<?> cls) throws IOException { GenClassCompiler pc = GenClassCompiler.compile(El.getTypeElement(cls.getCanonicalName()), null); return pc.loadDynamic(); }
java
{ "resource": "" }
q18462
GenClassFactory.loadGenClass
train
public static Class<?> loadGenClass(Class<?> cls) throws ClassNotFoundException { Class<?> parserClass = map.get(cls); if (parserClass == null) { GenClassname genClassname = cls.getAnnotation(GenClassname.class); if (genClassname == null) { throw new IllegalArgumentException("@GenClassname not set in "+cls); } parserClass = Class.forName(genClassname.value()); map.put(cls, parserClass); } return parserClass; }
java
{ "resource": "" }
q18463
LRImporter.getObtainRequestPath
train
private String getObtainRequestPath(String requestID, Boolean byResourceID, Boolean byDocID, Boolean idsOnly, String resumptionToken) { String path = obtainPath; if (resumptionToken != null) { path += "?" + resumptionTokenParam + "=" + resumptionToken; return path; } if (requestID != null) { path += "?" + requestIDParam + "=" + requestID; } else { // error return null; } if (byResourceID) { path += "&" + byResourceIDParam + "=" + booleanTrueString; } else { path += "&" + byResourceIDParam + "=" + booleanFalseString; } if (byDocID) { path += "&" + byDocIDParam + "=" + booleanTrueString; } else { path += "&" + byDocIDParam + "=" + booleanFalseString; } if (idsOnly) { path += "&" + idsOnlyParam + "=" + booleanTrueString; } else { path += "&" + idsOnlyParam + "=" + booleanFalseString; } return path; }
java
{ "resource": "" }
q18464
LRImporter.getHarvestRequestPath
train
private String getHarvestRequestPath(String requestID, Boolean byResourceID, Boolean byDocID) { String path = harvestPath; if (requestID != null) { path += "?" + requestIDParam + "=" + requestID; } else { // error return null; } if (byResourceID) { path += "&" + byResourceIDParam + "=" + booleanTrueString; } else { path += "&" + byResourceIDParam + "=" + booleanFalseString; } if (byDocID) { path += "&" + byDocIDParam + "=" + booleanTrueString; } else { path += "&" + byDocIDParam + "=" + booleanFalseString; } return path; }
java
{ "resource": "" }
q18465
LRImporter.getObtainJSONData
train
private LRResult getObtainJSONData(String requestID, Boolean byResourceID, Boolean byDocID, Boolean idsOnly, String resumptionToken) throws LRException { String path = getObtainRequestPath(requestID, byResourceID, byDocID, idsOnly, resumptionToken); JSONObject json = getJSONFromPath(path); return new LRResult(json); }
java
{ "resource": "" }
q18466
LRImporter.getHarvestJSONData
train
public LRResult getHarvestJSONData(String requestID, Boolean byResourceID, Boolean byDocID) throws LRException { String path = getHarvestRequestPath(requestID, byResourceID, byDocID); JSONObject json = getJSONFromPath(path); return new LRResult(json); }
java
{ "resource": "" }
q18467
LRImporter.getExtractRequestPath
train
private String getExtractRequestPath(String dataServiceName, String viewName, Date from, Date until, Boolean idsOnly, String mainValue, Boolean partial, String mainName) { String path = extractPath; if (viewName != null) { path += "/" + viewName; } else { return null; } if (dataServiceName != null) { path += "/" + dataServiceName; } else { return null; } if (mainValue != null && mainName != null) { path += "?" + mainName; if (partial) { path += startsWithParam; } path += "=" + mainValue; } else { return null; } if (from != null) { path += "&" + fromParam + "=" + ISO8601.format(from); } if (until != null) { path += "&" + untilParam + "=" + ISO8601.format(until); } if (idsOnly) { path += "&" + idsOnlyParam + "=" + booleanTrueString; } return path; }
java
{ "resource": "" }
q18468
LRImporter.getJSONFromPath
train
private JSONObject getJSONFromPath(String path) throws LRException { JSONObject json = null; String jsonTxt = null; try { jsonTxt = LRClient.executeJsonGet(importProtocol + "://" + nodeHost + path); } catch(Exception e) { throw new LRException(LRException.IMPORT_FAILED); //e.printStackTrace(); } try { json = new JSONObject(jsonTxt); } catch(JSONException e) { throw new LRException(LRException.JSON_IMPORT_FAILED); //e.printStackTrace(); } return json; }
java
{ "resource": "" }
q18469
Font.fontStyleToInt
train
private static int fontStyleToInt(FontStyle style) { switch (style) { case PLAIN: return java.awt.Font.PLAIN; case BOLD: return java.awt.Font.BOLD; case ITALIC: return java.awt.Font.ITALIC; default: return java.awt.Font.PLAIN; } }
java
{ "resource": "" }
q18470
Font.intToFontStyle
train
private static FontStyle intToFontStyle(int style) { switch (style) { case java.awt.Font.PLAIN: return FontStyle.PLAIN; case java.awt.Font.BOLD: return FontStyle.BOLD; case java.awt.Font.ITALIC: return FontStyle.ITALIC; case java.awt.Font.BOLD + java.awt.Font.ITALIC: return FontStyle.BOLD_ITALIC; default: return FontStyle.PLAIN; } }
java
{ "resource": "" }
q18471
Font.stringToFontStyle
train
private static FontStyle stringToFontStyle(String style) { if (style.compareToIgnoreCase("plain") == 0) { return FontStyle.PLAIN; } else if (style.compareToIgnoreCase("bold") == 0) { return FontStyle.BOLD; } else if (style.compareToIgnoreCase("italic") == 0) { return FontStyle.ITALIC; } else { throw new IllegalArgumentException(); } }
java
{ "resource": "" }
q18472
EFapsResourceConfig.onReload
train
public void onReload(final Container _container) { final Set<Class<?>> classesToRemove = new HashSet<>(); final Set<Class<?>> classesToAdd = new HashSet<>(); for (final Class<?> c : getClasses()) { if (!this.cachedClasses.contains(c)) { classesToAdd.add(c); } } for (final Class<?> c : this.cachedClasses) { if (!getClasses().contains(c)) { classesToRemove.add(c); } } getClasses().clear(); init(); getClasses().addAll(classesToAdd); getClasses().removeAll(classesToRemove); }
java
{ "resource": "" }
q18473
Selection.addInstSelect
train
private void addInstSelect(final Select _select, final AbstractDataElement<?> _element, final Object _attrOrClass, final Type _currentType) throws CacheReloadException { if (StringUtils.isNotEmpty(_element.getPath()) && !this.instSelects.containsKey(_element.getPath())) { final Select instSelect = Select.get(); for (final AbstractElement<?> selectTmp : _select.getElements()) { if (!selectTmp.equals(_element)) { if (selectTmp instanceof LinktoElement) { instSelect.addElement(new LinktoElement().setAttribute(((LinktoElement) selectTmp) .getAttribute())); } else if (selectTmp instanceof LinkfromElement) { instSelect.addElement(new LinkfromElement().setAttribute(((LinkfromElement) selectTmp) .getAttribute()).setStartType(((LinkfromElement) selectTmp).getStartType())); } else if (selectTmp instanceof ClassElement) { instSelect.addElement(new ClassElement() .setClassification(((ClassElement) selectTmp).getClassification()) .setType(((ClassElement) selectTmp).getType())); } else if (selectTmp instanceof AttributeSetElement) { instSelect.addElement(new AttributeSetElement() .setAttributeSet(((AttributeSetElement) selectTmp).getAttributeSet()) .setType(((ClassElement) selectTmp).getType())); } } } if (_element instanceof LinkfromElement) { instSelect.addElement(new LinkfromElement().setAttribute((Attribute) _attrOrClass).setStartType( _currentType)); instSelect.addElement(new InstanceElement(((Attribute) _attrOrClass).getParent())); } else if (_element instanceof LinktoElement) { instSelect.addElement(new LinktoElement().setAttribute((Attribute) _attrOrClass)); instSelect.addElement(new InstanceElement(_currentType)); } else if (_element instanceof ClassElement) { instSelect.addElement(new ClassElement().setClassification((Classification) _attrOrClass) .setType(_currentType)); instSelect.addElement(new InstanceElement((Type) _attrOrClass)); } else if (_element instanceof AttributeSetElement) { instSelect.addElement(new AttributeSetElement().setAttributeSet((AttributeSet) _attrOrClass) .setType(_currentType)); instSelect.addElement(new InstanceElement((Type) _attrOrClass)); } this.instSelects.put(_element.getPath(), instSelect); } }
java
{ "resource": "" }
q18474
Selection.evalMainType
train
private Type evalMainType(final Collection<Type> _baseTypes) throws EFapsException { final Type ret; if (_baseTypes.size() == 1) { ret = _baseTypes.iterator().next(); } else { final List<List<Type>> typeLists = new ArrayList<>(); for (final Type type : _baseTypes) { final List<Type> typesTmp = new ArrayList<>(); typeLists.add(typesTmp); Type tmpType = type; while (tmpType != null) { typesTmp.add(tmpType); tmpType = tmpType.getParentType(); } } final Set<Type> common = new LinkedHashSet<>(); if (!typeLists.isEmpty()) { final Iterator<List<Type>> iterator = typeLists.iterator(); common.addAll(iterator.next()); while (iterator.hasNext()) { common.retainAll(iterator.next()); } } if (common.isEmpty()) { throw new EFapsException(Selection.class, "noCommon", _baseTypes); } else { // first common type ret = common.iterator().next(); } } return ret; }
java
{ "resource": "" }
q18475
Selection.getAllSelects
train
public Collection<Select> getAllSelects() { final List<Select> ret = new ArrayList<>(this.selects); ret.addAll(this.instSelects.values()); return Collections.unmodifiableCollection(ret); }
java
{ "resource": "" }
q18476
AbstractUserObject.unassignFromUserObjectInDb
train
protected void unassignFromUserObjectInDb(final Type _unassignType, final JAASSystem _jaasSystem, final AbstractUserObject _object) throws EFapsException { Connection con = null; try { con = Context.getConnection(); Statement stmt = null; final StringBuilder cmd = new StringBuilder(); try { cmd.append("delete from ").append(_unassignType.getMainTable().getSqlTable()).append(" ").append( "where USERJAASSYSTEM=").append(_jaasSystem.getId()).append(" ").append( "and USERABSTRACTFROM=").append(getId()).append(" ").append("and USERABSTRACTTO=") .append(_object.getId()); stmt = con.createStatement(); stmt.executeUpdate(cmd.toString()); } catch (final SQLException e) { AbstractUserObject.LOG.error("could not execute '" + cmd.toString() + "' to unassign user object '" + toString() + "' from object '" + _object + "' for JAAS system '" + _jaasSystem + "' ", e); throw new EFapsException(getClass(), "unassignFromUserObjectInDb.SQLException", e, cmd.toString(), getName()); } finally { try { if (stmt != null) { stmt.close(); } con.commit(); } catch (final SQLException e) { AbstractUserObject.LOG.error("Could not close a statement.", e); } } } finally { try { if (con != null && !con.isClosed()) { con.close(); } } catch (final SQLException e) { throw new CacheReloadException("Cannot read a type for an attribute.", e); } } }
java
{ "resource": "" }
q18477
AbstractUserObject.setStatusInDB
train
protected void setStatusInDB(final boolean _status) throws EFapsException { Connection con = null; try { con = Context.getConnection(); PreparedStatement stmt = null; final StringBuilder cmd = new StringBuilder(); try { cmd.append(" update T_USERABSTRACT set STATUS=? where ID=").append(getId()); stmt = con.prepareStatement(cmd.toString()); stmt.setBoolean(1, _status); final int rows = stmt.executeUpdate(); if (rows == 0) { AbstractUserObject.LOG.error("could not execute '" + cmd.toString() + "' to update status information for person '" + toString() + "'"); throw new EFapsException(getClass(), "setStatusInDB.NotUpdated", cmd.toString(), getName()); } } catch (final SQLException e) { AbstractUserObject.LOG.error("could not execute '" + cmd.toString() + "' to update status information for person '" + toString() + "'", e); throw new EFapsException(getClass(), "setStatusInDB.SQLException", e, cmd.toString(), getName()); } finally { try { if (stmt != null) { stmt.close(); } con.commit(); } catch (final SQLException e) { throw new EFapsException(getClass(), "setStatusInDB.SQLException", e, cmd.toString(), getName()); } } } finally { try { if (con != null && !con.isClosed()) { con.close(); } } catch (final SQLException e) { throw new CacheReloadException("Cannot read a type for an attribute.", e); } } }
java
{ "resource": "" }
q18478
AbstractUserInterfaceObject.readFromDB4Access
train
private void readFromDB4Access() throws CacheReloadException { Statement stmt = null; try { stmt = Context.getThreadContext().getConnectionResource().createStatement(); final ResultSet resultset = stmt.executeQuery("select " + "T_UIACCESS.USERABSTRACT " + "from T_UIACCESS " + "where T_UIACCESS.UIABSTRACT=" + getId()); while (resultset.next()) { final long userId = resultset.getLong(1); final AbstractUserObject userObject = AbstractUserObject.getUserObject(userId); if (userObject == null) { throw new CacheReloadException("user " + userId + " does not exists!"); } else { getAccess().add(userId); } } resultset.close(); } catch (final SQLException e) { throw new CacheReloadException("could not read access for " + "'" + getName() + "'", e); } catch (final EFapsException e) { throw new CacheReloadException("could not read access for " + "'" + getName() + "'", e); } finally { if (stmt != null) { try { stmt.close(); } catch (final SQLException e) { throw new CacheReloadException("could not read access for " + "'" + getName() + "'", e); } } } }
java
{ "resource": "" }
q18479
AbstractElement.getPath
train
public String getPath() { final StringBuilder path = new StringBuilder(); if (getPrevious() != null) { path.append(getPrevious().getPath()); } return path.toString(); }
java
{ "resource": "" }
q18480
PrintStmt.getEsjpSelect
train
private Map<String, IEsjpSelect> getEsjpSelect(final List<Instance> _instances) throws Exception { final Map<String, IEsjpSelect> ret = new HashMap<>(); if (!_instances.isEmpty()) { for (final Entry<String, AbstractSelect> entry : getAlias2Selects().entrySet()) { if (entry.getValue() instanceof ExecSelect) { final Class<?> clazz = Class.forName(entry.getValue().getSelect(), false, EFapsClassLoader .getInstance()); final IEsjpSelect esjp = (IEsjpSelect) clazz.newInstance(); final List<String> parameters = ((ExecSelect) entry.getValue()).getParameters(); if (parameters.isEmpty()) { esjp.initialize(_instances); } else { esjp.initialize(_instances, parameters.toArray(new String[parameters.size()])); } ret.put(entry.getKey(), esjp); } } } return ret; }
java
{ "resource": "" }
q18481
PrintStmt.getMultiPrint
train
private MultiPrintQuery getMultiPrint() throws EFapsException { final MultiPrintQuery ret; if (getInstances().isEmpty()) { ret = new MultiPrintQuery(QueryBldrUtil.getInstances(this)); } else { final List<Instance> instances = new ArrayList<>(); for (final String oid : getInstances()) { instances.add(Instance.get(oid)); } ret = new MultiPrintQuery(instances); } return ret; }
java
{ "resource": "" }
q18482
Dimension.addUoM
train
private void addUoM(final UoM _uom) { this.uoMs.add(_uom); if (_uom.getId() == this.baseUoMId) { this.baseUoM = _uom; } }
java
{ "resource": "" }
q18483
Dimension.getUoM
train
public static UoM getUoM(final Long _uoMId) { final Cache<Long, UoM> cache = InfinispanCache.get().<Long, UoM>getCache(Dimension.IDCACHE4UOM); if (!cache.containsKey(_uoMId)) { try { Dimension.getUoMFromDB(Dimension.SQL_SELECT_UOM4ID, _uoMId); } catch (final CacheReloadException e) { Dimension.LOG.error("read UoM from DB failed for id: '{}'", _uoMId); } } return cache.get(_uoMId); }
java
{ "resource": "" }
q18484
LRResult.getResumptionToken
train
public String getResumptionToken() { String resumptionToken = null; try { if (data != null && data.has(resumptionTokenParam)) { resumptionToken = data.getString(resumptionTokenParam); } } catch (JSONException e) { //This is already handled by the enclosing "has" checks } return resumptionToken; }
java
{ "resource": "" }
q18485
LRResult.getResourceData
train
public List<JSONObject> getResourceData() { List<JSONObject> resources = new ArrayList<JSONObject>(); try { if (data != null && data.has(documentsParam)) { List<JSONObject> results = getDocuments(); for(JSONObject json : results) { if (json.has(documentParam)) { JSONObject result = json.getJSONObject(documentParam); results.add(result); } } } else if (data != null && data.has(getRecordParam)) { List<JSONObject> results = getRecords(); for(JSONObject json : results) { if (json.has(resourceDataParam)) { JSONObject result = json.getJSONObject(resourceDataParam); results.add(result); } } } } catch (JSONException e) { //This is already handled by the enclosing "has" checks } return resources; }
java
{ "resource": "" }
q18486
LRResult.getDocuments
train
public List<JSONObject> getDocuments() { List<JSONObject> documents = new ArrayList<JSONObject>(); try { if (data != null && data.has(documentsParam)) { JSONArray jsonDocuments = data.getJSONArray(documentsParam); for(int i = 0; i < jsonDocuments.length(); i++) { JSONObject document = jsonDocuments.getJSONObject(i); documents.add(document); } } } catch (JSONException e) { //This is already handled by the enclosing "has" checks } return documents; }
java
{ "resource": "" }
q18487
LRResult.getRecords
train
public List<JSONObject> getRecords() { List<JSONObject> records = new ArrayList<JSONObject>(); try { if (data != null && data.has(getRecordParam)) { JSONObject jsonGetRecord = data.getJSONObject(getRecordParam); if (jsonGetRecord.has(recordParam)) { JSONArray jsonRecords = jsonGetRecord.getJSONArray(recordParam); for(int i = 0; i < jsonRecords.length(); i++) { JSONObject record = jsonRecords.getJSONObject(i); records.add(record); } } } } catch (JSONException e) { //This is already handled by the enclosing "has" checks } return records; }
java
{ "resource": "" }
q18488
StencilOperands.roundBigDecimal
train
public BigDecimal roundBigDecimal(final BigDecimal number) { int mscale = getMathScale(); if (mscale >= 0) { return number.setScale(mscale, getMathContext().getRoundingMode()); } else { return number; } }
java
{ "resource": "" }
q18489
StencilOperands.isFloatingPointType
train
protected boolean isFloatingPointType(Object left, Object right) { return left instanceof Float || left instanceof Double || right instanceof Float || right instanceof Double; }
java
{ "resource": "" }
q18490
StencilOperands.isNumberable
train
protected boolean isNumberable(final Object o) { return o instanceof Integer || o instanceof Long || o instanceof Byte || o instanceof Short || o instanceof Character; }
java
{ "resource": "" }
q18491
StencilOperands.narrowBigDecimal
train
protected Number narrowBigDecimal(Object lhs, Object rhs, BigDecimal bigd) { if (isNumberable(lhs) || isNumberable(rhs)) { try { long l = bigd.longValueExact(); // coerce to int when possible (int being so often used in method parms) if (l <= Integer.MAX_VALUE && l >= Integer.MIN_VALUE) { return Integer.valueOf((int) l); } else { return Long.valueOf(l); } } catch (ArithmeticException xa) { // ignore, no exact value possible } } return bigd; }
java
{ "resource": "" }
q18492
StencilOperands.narrowArguments
train
protected boolean narrowArguments(Object[] args) { boolean narrowed = false; for (int a = 0; a < args.length; ++a) { Object arg = args[a]; if (arg instanceof Number) { Object narg = narrow((Number) arg); if (narg != arg) { narrowed = true; } args[a] = narg; } } return narrowed; }
java
{ "resource": "" }
q18493
StencilOperands.divide
train
public Object divide(Object left, Object right) { if (left == null && right == null) { return 0; } // if either are floating point (double or float) use double if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) { double l = toDouble(left); double r = toDouble(right); if (r == 0.0) { throw new ArithmeticException("/"); } return new Double(l / r); } // if either are bigdecimal use that type if (left instanceof BigDecimal || right instanceof BigDecimal) { BigDecimal l = toBigDecimal(left); BigDecimal r = toBigDecimal(right); if (BigDecimal.ZERO.equals(r)) { throw new ArithmeticException("/"); } BigDecimal result = l.divide(r, getMathContext()); return narrowBigDecimal(left, right, result); } // otherwise treat as integers BigInteger l = toBigInteger(left); BigInteger r = toBigInteger(right); if (BigInteger.ZERO.equals(r)) { throw new ArithmeticException("/"); } BigInteger result = l.divide(r); return narrowBigInteger(left, right, result); }
java
{ "resource": "" }
q18494
StencilOperands.multiply
train
public Object multiply(Object left, Object right) { if (left == null && right == null) { return 0; } // if either are floating point (double or float) use double if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) { double l = toDouble(left); double r = toDouble(right); return new Double(l * r); } // if either are bigdecimal use that type if (left instanceof BigDecimal || right instanceof BigDecimal) { BigDecimal l = toBigDecimal(left); BigDecimal r = toBigDecimal(right); BigDecimal result = l.multiply(r, getMathContext()); return narrowBigDecimal(left, right, result); } // otherwise treat as integers BigInteger l = toBigInteger(left); BigInteger r = toBigInteger(right); BigInteger result = l.multiply(r); return narrowBigInteger(left, right, result); }
java
{ "resource": "" }
q18495
StencilOperands.matches
train
public boolean matches(Object left, Object right) { if (left == null && right == null) { // if both are null L == R return true; } if (left == null || right == null) { // we know both aren't null, therefore L != R return false; } final String arg = left.toString(); if (right instanceof java.util.regex.Pattern) { return ((java.util.regex.Pattern) right).matcher(arg).matches(); } else { return arg.matches(right.toString()); } }
java
{ "resource": "" }
q18496
StencilOperands.bitwiseOr
train
public Object bitwiseOr(Object left, Object right) { long l = toLong(left); long r = toLong(right); return Long.valueOf(l | r); }
java
{ "resource": "" }
q18497
StencilOperands.bitwiseComplement
train
public Object bitwiseComplement(Object val) { long l = toLong(val); return Long.valueOf(~l); }
java
{ "resource": "" }
q18498
StencilOperands.lessThan
train
public boolean lessThan(Object left, Object right) { if ((left == right) || (left == null) || (right == null)) { return false; } else { return compare(left, right, "<") < 0; } }
java
{ "resource": "" }
q18499
StencilOperands.greaterThan
train
public boolean greaterThan(Object left, Object right) { if ((left == right) || left == null || right == null) { return false; } else { return compare(left, right, ">") > 0; } }
java
{ "resource": "" }