_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13400 | EKBCommit.addDeletes | train | public EKBCommit addDeletes(Collection<?> deletes) {
if (deletes != null) {
for (Object delete : deletes) {
checkIfModel(delete);
this.deletes.add((OpenEngSBModel) delete);
}
}
return this;
} | java | {
"resource": ""
} |
q13401 | Explanation.getNestedClassExpressions | train | public Set<OWLClassExpression> getNestedClassExpressions() {
Set<OWLClassExpression> subConcepts = new HashSet<OWLClassExpression>();
for (OWLAxiom ax : justification) {
subConcepts.addAll(ax.getNestedClassExpressions());
}
return subConcepts;
} | java | {
"resource": ""
} |
q13402 | Explanation.store | train | public static void store(Explanation<OWLAxiom> explanation, OutputStream os) throws IOException {
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.createOntology(explanation.getAxioms());
OWLDataFactory df = manager.getOWLDataFactory();
OWLAnnotationProperty entailmentMarkerAnnotationProperty = df.getOWLAnnotationProperty(ENTAILMENT_MARKER_IRI);
OWLAnnotation entailmentAnnotation = df.getOWLAnnotation(entailmentMarkerAnnotationProperty, df.getOWLLiteral(true));
OWLAxiom annotatedEntailment = explanation.getEntailment().getAnnotatedAxiom(Collections.singleton(entailmentAnnotation));
manager.addAxiom(ontology, annotatedEntailment);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);
OWLXMLDocumentFormat justificationOntologyFormat = new OWLXMLDocumentFormat();
manager.saveOntology(ontology, justificationOntologyFormat, bufferedOutputStream);
}
catch (OWLOntologyStorageException | OWLOntologyCreationException e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q13403 | Explanation.load | train | public static Explanation<OWLAxiom> load(InputStream is) throws IOException {
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new BufferedInputStream(is));
OWLDataFactory df = manager.getOWLDataFactory();
OWLAnnotationProperty entailmentMarkerAnnotationProperty = df.getOWLAnnotationProperty(ENTAILMENT_MARKER_IRI);
Set<OWLAxiom> justificationAxioms = new HashSet<OWLAxiom>();
OWLAxiom entailment = null;
for(OWLAxiom ax : ontology.getAxioms()) {
boolean isEntailmentAxiom = !ax.getAnnotations(entailmentMarkerAnnotationProperty).isEmpty();
if(!isEntailmentAxiom) {
justificationAxioms.add(ax);
}
else {
entailment = ax.getAxiomWithoutAnnotations();
}
}
if(entailment == null) {
throw new IllegalStateException("Not a serialisation of an Explanation");
}
return new Explanation<OWLAxiom>(entailment, justificationAxioms);
}
catch (OWLOntologyCreationException e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q13404 | JavassistUtils.hasAnnotation | train | public static boolean hasAnnotation(CtClass clazz, String annotationName) {
ClassFile cf = clazz.getClassFile2();
AnnotationsAttribute ainfo = (AnnotationsAttribute)
cf.getAttribute(AnnotationsAttribute.invisibleTag);
AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
cf.getAttribute(AnnotationsAttribute.visibleTag);
return checkAnnotation(ainfo, ainfo2, annotationName);
} | java | {
"resource": ""
} |
q13405 | JavassistUtils.hasAnnotation | train | public static boolean hasAnnotation(CtField field, String annotationName) {
FieldInfo info = field.getFieldInfo();
AnnotationsAttribute ainfo = (AnnotationsAttribute)
info.getAttribute(AnnotationsAttribute.invisibleTag);
AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
info.getAttribute(AnnotationsAttribute.visibleTag);
return checkAnnotation(ainfo, ainfo2, annotationName);
} | java | {
"resource": ""
} |
q13406 | JavassistUtils.checkAnnotation | train | private static boolean checkAnnotation(AnnotationsAttribute invisible, AnnotationsAttribute visible,
String annotationName) {
boolean exist1 = false;
boolean exist2 = false;
if (invisible != null) {
exist1 = invisible.getAnnotation(annotationName) != null;
}
if (visible != null) {
exist2 = visible.getAnnotation(annotationName) != null;
}
return exist1 || exist2;
} | java | {
"resource": ""
} |
q13407 | SubStringOperation.checkBounds | train | private void checkBounds(String source, Integer from, Integer to) throws TransformationOperationException {
Integer length = source.length();
if (from > to) {
throw new TransformationOperationException(
"The from parameter is bigger than the to parameter");
}
if (from < 0 || from > length) {
throw new TransformationOperationException(
"The from parameter is not fitting to the size of the source");
}
if (to < 0 || to > length) {
throw new TransformationOperationException(
"The to parameter is not fitting to the size of the source");
}
} | java | {
"resource": ""
} |
q13408 | SubStringOperation.getFromParameter | train | private Integer getFromParameter(Map<String, String> parameters) throws TransformationOperationException {
return getSubStringParameter(parameters, fromParam, 0);
} | java | {
"resource": ""
} |
q13409 | SubStringOperation.getToParameter | train | private Integer getToParameter(Map<String, String> parameters, Integer defaultValue)
throws TransformationOperationException {
return getSubStringParameter(parameters, toParam, defaultValue);
} | java | {
"resource": ""
} |
q13410 | SubStringOperation.getSubStringParameter | train | private Integer getSubStringParameter(Map<String, String> parameters, String parameterName, Integer defaultValue)
throws TransformationOperationException {
String parameter = parameters.get(parameterName);
if (parameter == null) {
getLogger().debug("The {} parameter is not set, so the default value {} is taken.", parameterName,
defaultValue);
return defaultValue;
}
try {
return Integer.parseInt(parameter);
} catch (NumberFormatException e) {
throw new TransformationOperationException("The " + parameterName + " parameter is not a number");
}
} | java | {
"resource": ""
} |
q13411 | AbstractBatchingCacheStore.storeAll | train | @Override
public void storeAll(Map mapEntries) {
int batchSize = getBatchSize();
if (batchSize == 0 || mapEntries.size() < batchSize) {
storeBatch(mapEntries);
}
else {
Map batch = new HashMap(batchSize);
while (!mapEntries.isEmpty()) {
Iterator iter = mapEntries.entrySet().iterator();
while (iter.hasNext() && batch.size() < batchSize) {
Map.Entry entry = (Map.Entry) iter.next();
batch.put(entry.getKey(), entry.getValue());
}
storeBatch(batch);
mapEntries.keySet().removeAll(batch.keySet());
batch.clear();
}
}
} | java | {
"resource": ""
} |
q13412 | BlackBoxExplanationGenerator.getOrderedJustifications | train | private static <E> List<OWLAxiom> getOrderedJustifications(List<OWLAxiom> mups, final Set<Explanation<E>> allJustifications) {
Comparator<OWLAxiom> mupsComparator = new Comparator<OWLAxiom>() {
public int compare(OWLAxiom o1, OWLAxiom o2) {
// The checker that appears in most MUPS has the lowest index
// in the list
int occ1 = getOccurrences(o1, allJustifications);
int occ2 = getOccurrences(o2, allJustifications);
return -occ1 + occ2;
}
};
Collections.sort(mups, mupsComparator);
return mups;
} | java | {
"resource": ""
} |
q13413 | BlackBoxExplanationGenerator.getOccurrences | train | private static <E> int getOccurrences(OWLAxiom ax, Set<Explanation<E>> axiomSets) {
int count = 0;
for (Explanation<E> explanation : axiomSets) {
if (explanation.getAxioms().contains(ax)) {
count++;
}
}
return count;
} | java | {
"resource": ""
} |
q13414 | BlackBoxExplanationGenerator.constructHittingSetTree | train | private void constructHittingSetTree(E entailment, Explanation<E> justification, Set<Explanation<E>> allJustifications,
Set<Set<OWLAxiom>> satPaths, Set<OWLAxiom> currentPathContents,
int maxExplanations) throws OWLException {
// dumpHSTNodeDiagnostics(entailment, justification, allJustifications, currentPathContents);
// We go through the current justifications, checker by checker, and extend the tree
// with edges for each checker
List<OWLAxiom> orderedJustification = getOrderedJustifications(new ArrayList<OWLAxiom>(justification.getAxioms()), allJustifications);
while (!orderedJustification.isEmpty()) {
OWLAxiom axiom = orderedJustification.get(0);
orderedJustification.remove(0);
if (allJustifications.size() == maxExplanations) {
return;
}
// Remove the current checker from all the ontologies it is included
// in
module.remove(axiom);
currentPathContents.add(axiom);
boolean earlyTermination = false;
// Early path termination. If our path contents are the superset of
// the contents of a path then we can terminate here.
for (Set<OWLAxiom> satPath : satPaths) {
if (currentPathContents.containsAll(satPath)) {
earlyTermination = true;
break;
}
}
if (!earlyTermination) {
Explanation<E> newJustification = null;
for (Explanation<E> foundJustification : allJustifications) {
Set<OWLAxiom> foundMUPSCopy = new HashSet<OWLAxiom>(foundJustification.getAxioms());
foundMUPSCopy.retainAll(currentPathContents);
if (foundMUPSCopy.isEmpty()) {
// Justification reuse
newJustification = foundJustification;
break;
}
}
if (newJustification == null) {
newJustification = computeExplanation(entailment);//getExplanation();
}
// Generate a new node - i.e. a new justification set
if (axiom.isLogicalAxiom() && newJustification.contains(axiom)) {
// How can this be the case???
throw new OWLRuntimeException("Explanation contains removed axiom: " + axiom + " (Working axioms contains axiom: " + module.contains(axiom) + ")");
}
if (!newJustification.isEmpty()) {
// Note that getting a previous justification does not mean
// we
// can stop. stopping here causes some justifications to be
// missed
boolean added = allJustifications.add(newJustification);
if (added) {
progressMonitor.foundExplanation(this, newJustification, allJustifications);
}
if (progressMonitor.isCancelled()) {
return;
}
// Recompute priority here?
// MutableTree<Explanation> node = new MutableTree<Explanation>(newJustification);
// currentNode.addChild(node, checker);
constructHittingSetTree(entailment,
newJustification,
allJustifications,
satPaths,
currentPathContents,
maxExplanations);
// We have found a new MUPS, so recalculate the ordering
// axioms in the MUPS at the current level
orderedJustification = getOrderedJustifications(orderedJustification, allJustifications);
} else {
// End of current path - add it to the list of paths
satPaths.add(new HashSet<OWLAxiom>(currentPathContents));
Explanation exp = new Explanation<E>(entailment, new HashSet<OWLAxiom>(0));
MutableTree<Explanation> node = new MutableTree<Explanation>(exp);
// currentNode.addChild(node, checker);
// increment(checker);
}
}
// Back track - go one level up the tree and run for the next checker
currentPathContents.remove(axiom);
// Done with the checker that was removed. Add it back in
module.add(axiom);
}
} | java | {
"resource": ""
} |
q13415 | AbstractTableFactory.onMissingTypeVisit | train | protected void onMissingTypeVisit(Table table, IndexField<?> field) {
if (!Introspector.isModelClass(field.getType())) {
return;
}
Field idField = Introspector.getOpenEngSBModelIdField(field.getType());
if (idField == null) {
LOG.warn("@Model class {} does not have an @OpenEngSBModelId", field.getType());
return;
}
DataType type = getTypeMap().getType(idField.getType());
if (type == null) {
LOG.warn("@OpenEngSBModelId field {} has an unmapped type {}", field.getName(), field.getType());
return;
}
((JdbcIndexField) field).setMappedType(type);
Column column = new Column(getColumnNameTranslator().translate(field), type);
table.addElement(column); // will hold the models OID
onAfterFieldVisit(table, column, field);
} | java | {
"resource": ""
} |
q13416 | Column.set | train | public Column set(Option option, boolean set) {
if (set) {
options.add(option);
} else {
options.remove(option);
}
return this;
} | java | {
"resource": ""
} |
q13417 | CurvedArrow.setStart | train | public void setStart(int x1, int y1) {
start.x = x1;
start.y = y1;
needsRefresh = true;
} | java | {
"resource": ""
} |
q13418 | CurvedArrow.setEnd | train | public void setEnd(int x2, int y2) {
end.x = x2;
end.y = y2;
needsRefresh = true;
} | java | {
"resource": ""
} |
q13419 | CurvedArrow.draw | train | public void draw(Graphics2D g) {
if (needsRefresh)
refreshCurve();
g.draw(curve); // Draws the main part of the arrow.
drawArrow(g, end, control); // Draws the arrow head.
drawText(g);
} | java | {
"resource": ""
} |
q13420 | CurvedArrow.drawHighlight | train | public void drawHighlight(Graphics2D g) {
if (needsRefresh)
refreshCurve();
Graphics2D g2 = (Graphics2D) g.create();
g2.setStroke(new java.awt.BasicStroke(6.0f));
g2.setColor(HIGHLIGHT_COLOR);
g2.draw(curve);
g2.transform(affineToText);
g2.fill(bounds);
g2.dispose();
} | java | {
"resource": ""
} |
q13421 | CurvedArrow.setLabel | train | public void setLabel(String label) {
this.label = label;
// if (GRAPHICS == null) return;
bounds = METRICS.getStringBounds(getLabel(), GRAPHICS);
boolean upsideDown = end.x < start.x;
float dx = (float) bounds.getWidth() / 2.0f;
float dy = (curvy < 0.0f) ^ upsideDown ? METRICS.getAscent() : -METRICS
.getDescent();
bounds.setRect(bounds.getX() - dx, bounds.getY() + dy, bounds
.getWidth(), bounds.getHeight());
//System.out.println("Setting label" + label);
} | java | {
"resource": ""
} |
q13422 | CurvedArrow.drawArrow | train | private void drawArrow(Graphics g, Point head, Point away) {
int endX, endY;
double angle = Math.atan2((double) (away.x - head.x),
(double) (away.y - head.y));
angle += ARROW_ANGLE;
endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x;
endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y;
g.drawLine(head.x, head.y, endX, endY);
angle -= 2 * ARROW_ANGLE;
endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x;
endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y;
g.drawLine(head.x, head.y, endX, endY);
} | java | {
"resource": ""
} |
q13423 | CurvedArrow.refreshCurve | train | public void refreshCurve() {
// System.out.println("Curve refreshing");
needsRefresh = false;
double lengthx = end.x - start.x;
double lengthy = end.y - start.y;
double centerx = ((double) (start.x + end.x)) / 2.0;
double centery = ((double) (start.y + end.y)) / 2.0;
double length = Math.sqrt(lengthx * lengthx + lengthy * lengthy);
double factorx = length == 0.0 ? 0.0 : lengthx / length;
double factory = length == 0.0 ? 0.0 : lengthy / length;
control.x = (int) (centerx + curvy * HEIGHT * factory);
control.y = (int) (centery - curvy * HEIGHT * factorx);
high.x = (int) (centerx + curvy * HEIGHT * factory / 2.0);
high.y = (int) (centery - curvy * HEIGHT * factorx / 2.0);
curve.setCurve((float) start.x, (float) start.y, (float) control.x,
(float) control.y, (float) end.x, (float) end.y);
affineToText = new AffineTransform();
affineToText.translate(high.x, high.y);
affineToText.rotate(Math.atan2(lengthy, lengthx));
if (end.x < start.x)
affineToText.rotate(Math.PI);
} | java | {
"resource": ""
} |
q13424 | CurvedArrow.getBounds | train | public Rectangle2D getBounds() {
if (needsRefresh)
refreshCurve();
Rectangle2D b = curve.getBounds();
Area area = new Area(bounds);
area.transform(affineToText);
b.add(area.getBounds());
return b;
} | java | {
"resource": ""
} |
q13425 | CurvedArrow.intersects | train | private boolean intersects(Point point, int fudge, QuadCurve2D.Float c) {
if (!c.intersects(point.x - fudge, point.y - fudge, fudge << 1,
fudge << 1))
return false;
if (c.getFlatness() < fudge)
return true;
QuadCurve2D.Float f1 = new QuadCurve2D.Float(), f2 = new QuadCurve2D.Float();
c.subdivide(f1, f2);
return intersects(point, fudge, f1) || intersects(point, fudge, f2);
} | java | {
"resource": ""
} |
q13426 | MultiDomain.chooseValues | train | public HashMap<Variable,Object> chooseValues() {
MultiVariable mv = (MultiVariable)myVariable;
Variable[] internalVars = mv.getInternalVariables();
HashMap<Variable,Object> values = new HashMap<Variable,Object>();
for (Variable v: internalVars) {
if (v instanceof MultiVariable) {
MultiVariable nestedMv = (MultiVariable)v;
MultiDomain nestedMd = nestedMv.getDomain();
HashMap<Variable,Object> nested = nestedMd.chooseValues();
for (Entry<Variable,Object> e : nested.entrySet()) {
values.put(e.getKey(), e.getValue());
}
}
else {
values.put(v,v.getDomain().chooseValue());
}
}
return values;
} | java | {
"resource": ""
} |
q13427 | BoundingBox.getMinRectabgle | train | public Rectangle getMinRectabgle(){
return new Rectangle((int)xLB.min, (int)yLB.min, (int)(xUB.min - xLB.min), (int)(yUB.min - yLB.min));
} | java | {
"resource": ""
} |
q13428 | BoundingBox.getMaxRectabgle | train | public Rectangle getMaxRectabgle(){
return new Rectangle((int)xLB.max, (int)yLB.max, (int)(xUB.max - xLB.max), (int)(yUB.max - yLB.max));
} | java | {
"resource": ""
} |
q13429 | WiringPage.setLocation | train | private boolean setLocation(String global, String context, Map<String, Object> properties) {
String locationKey = "location." + context;
Object propvalue = properties.get(locationKey);
if (propvalue == null) {
properties.put(locationKey, global);
} else if (propvalue.getClass().isArray()) {
Object[] locations = (Object[]) propvalue;
if (ArrayUtils.contains(locations, global)) {
return false;
}
Object[] newArray = Arrays.copyOf(locations, locations.length + 1);
newArray[locations.length] = global;
properties.put(locationKey, newArray);
} else {
if (((String) propvalue).equals(global)) {
return false;
}
Object[] newArray = new Object[2];
newArray[0] = propvalue;
newArray[1] = global;
properties.put(locationKey, newArray);
}
return true;
} | java | {
"resource": ""
} |
q13430 | BinaryVersionedPut.processAll | train | @SuppressWarnings({"unchecked"})
@Override
public Map processAll(Set setEntries) {
Map results = new LiteMap();
for (BinaryEntry entry : (Set<BinaryEntry>) setEntries) {
Object result = processEntry(entry);
if (result != NO_RESULT) {
results.put(entry.getKey(), result);
}
}
return results;
} | java | {
"resource": ""
} |
q13431 | BinaryVersionedPut.processEntry | train | protected Object processEntry(BinaryEntry entry) {
Binary binCurrent = entry.getBinaryValue();
if (binCurrent == null && !fAllowInsert) {
return fReturn ? null : NO_RESULT;
}
PofValue pvCurrent = getPofValue(binCurrent);
PofValue pvNew = getPofValue("newValue");
Integer versionCurrent = (Integer) get(pvCurrent);
Integer versionNew = (Integer) get(pvNew);
if (versionCurrent.equals(versionNew)) {
set(pvNew, versionNew + 1);
entry.updateBinaryValue(pvNew.applyChanges());
return NO_RESULT;
}
return fReturn ? pvCurrent.getValue() : NO_RESULT;
} | java | {
"resource": ""
} |
q13432 | ManipulationUtils.enhanceModel | train | public static byte[] enhanceModel(byte[] byteCode, ClassLoader... loaders) throws IOException,
CannotCompileException {
return enhanceModel(byteCode, new Version("1.0.0"), loaders);
} | java | {
"resource": ""
} |
q13433 | ManipulationUtils.enhanceModel | train | public static byte[] enhanceModel(byte[] byteCode, Version modelVersion, ClassLoader... loaders)
throws IOException, CannotCompileException {
CtClass cc = doModelModifications(byteCode, modelVersion, loaders);
if (cc == null) {
return null;
}
byte[] newClass = cc.toBytecode();
cc.defrost();
cc.detach();
return newClass;
} | java | {
"resource": ""
} |
q13434 | ManipulationUtils.doModelModifications | train | private static CtClass doModelModifications(byte[] byteCode, Version modelVersion, ClassLoader... loaders) {
if (!initiated) {
initiate();
}
CtClass cc = null;
LoaderClassPath[] classloaders = new LoaderClassPath[loaders.length];
try {
InputStream stream = new ByteArrayInputStream(byteCode);
cc = cp.makeClass(stream);
if (!JavassistUtils.hasAnnotation(cc, Model.class.getName())) {
return null;
}
LOGGER.debug("Model to enhance: {}", cc.getName());
for (int i = 0; i < loaders.length; i++) {
classloaders[i] = new LoaderClassPath(loaders[i]);
cp.appendClassPath(classloaders[i]);
}
doEnhancement(cc, modelVersion);
LOGGER.info("Finished model enhancing for class {}", cc.getName());
} catch (IOException e) {
LOGGER.error("IOException while trying to enhance model", e);
} catch (RuntimeException e) {
LOGGER.error("RuntimeException while trying to enhance model", e);
} catch (CannotCompileException e) {
LOGGER.error("CannotCompileException while trying to enhance model", e);
} catch (NotFoundException e) {
LOGGER.error("NotFoundException while trying to enhance model", e);
} catch (ClassNotFoundException e) {
LOGGER.error("ClassNotFoundException while trying to enhance model", e);
} finally {
for (int i = 0; i < loaders.length; i++) {
if (classloaders[i] != null) {
cp.removeClassPath(classloaders[i]);
}
}
}
return cc;
} | java | {
"resource": ""
} |
q13435 | ManipulationUtils.doEnhancement | train | private static void doEnhancement(CtClass cc, Version modelVersion) throws CannotCompileException,
NotFoundException, ClassNotFoundException {
CtClass inter = cp.get(OpenEngSBModel.class.getName());
cc.addInterface(inter);
addFields(cc);
addGetOpenEngSBModelTail(cc);
addSetOpenEngSBModelTail(cc);
addRetrieveModelName(cc);
addRetrieveModelVersion(cc, modelVersion);
addOpenEngSBModelEntryMethod(cc);
addRemoveOpenEngSBModelEntryMethod(cc);
addRetrieveInternalModelId(cc);
addRetrieveInternalModelTimestamp(cc);
addRetrieveInternalModelVersion(cc);
addToOpenEngSBModelValues(cc);
addToOpenEngSBModelEntries(cc);
cc.setModifiers(cc.getModifiers() & ~Modifier.ABSTRACT);
} | java | {
"resource": ""
} |
q13436 | ManipulationUtils.addFields | train | private static void addFields(CtClass clazz) throws CannotCompileException, NotFoundException {
CtField tail = CtField.make(String.format("private Map %s = new HashMap();", TAIL_FIELD), clazz);
clazz.addField(tail);
String loggerDefinition = "private static final Logger %s = LoggerFactory.getLogger(%s.class.getName());";
CtField logger = CtField.make(String.format(loggerDefinition, LOGGER_FIELD, clazz.getName()), clazz);
clazz.addField(logger);
} | java | {
"resource": ""
} |
q13437 | ManipulationUtils.addGetOpenEngSBModelTail | train | private static void addGetOpenEngSBModelTail(CtClass clazz) throws CannotCompileException, NotFoundException {
CtClass[] params = generateClassField();
CtMethod method = new CtMethod(cp.get(List.class.getName()), "getOpenEngSBModelTail", params, clazz);
StringBuilder body = new StringBuilder();
body.append(createTrace("Called getOpenEngSBModelTail"))
.append(String.format("return new ArrayList(%s.values());", TAIL_FIELD));
method.setBody(createMethodBody(body.toString()));
clazz.addMethod(method);
} | java | {
"resource": ""
} |
q13438 | ManipulationUtils.addSetOpenEngSBModelTail | train | private static void addSetOpenEngSBModelTail(CtClass clazz) throws CannotCompileException, NotFoundException {
CtClass[] params = generateClassField(List.class);
CtMethod method = new CtMethod(CtClass.voidType, "setOpenEngSBModelTail", params, clazz);
StringBuilder builder = new StringBuilder();
builder.append(createTrace("Called setOpenEngSBModelTail"))
.append("if($1 != null) {for(int i = 0; i < $1.size(); i++) {")
.append("OpenEngSBModelEntry entry = (OpenEngSBModelEntry) $1.get(i);")
.append(String.format("%s.put(entry.getKey(), entry); } }", TAIL_FIELD));
method.setBody(createMethodBody(builder.toString()));
clazz.addMethod(method);
} | java | {
"resource": ""
} |
q13439 | ManipulationUtils.addRetrieveModelName | train | private static void addRetrieveModelName(CtClass clazz) throws CannotCompileException, NotFoundException {
CtClass[] params = generateClassField();
CtMethod method = new CtMethod(cp.get(String.class.getName()), "retrieveModelName", params, clazz);
StringBuilder builder = new StringBuilder();
builder.append(createTrace("Called retrieveModelName"))
.append(String.format("return \"%s\";", clazz.getName()));
method.setBody(createMethodBody(builder.toString()));
clazz.addMethod(method);
} | java | {
"resource": ""
} |
q13440 | ManipulationUtils.addRetrieveInternalModelId | train | private static void addRetrieveInternalModelId(CtClass clazz) throws NotFoundException,
CannotCompileException {
CtField modelIdField = null;
CtClass temp = clazz;
while (temp != null) {
for (CtField field : temp.getDeclaredFields()) {
if (JavassistUtils.hasAnnotation(field, OpenEngSBModelId.class.getName())) {
modelIdField = field;
break;
}
}
temp = temp.getSuperclass();
}
CtClass[] params = generateClassField();
CtMethod valueMethod = new CtMethod(cp.get(Object.class.getName()), "retrieveInternalModelId", params, clazz);
StringBuilder builder = new StringBuilder();
builder.append(createTrace("Called retrieveInternalModelId"));
CtMethod idFieldGetter = getFieldGetter(modelIdField, clazz);
if (modelIdField == null || idFieldGetter == null) {
builder.append("return null;");
} else {
builder.append(String.format("return %s();", idFieldGetter.getName()));
}
valueMethod.setBody(createMethodBody(builder.toString()));
clazz.addMethod(valueMethod);
CtMethod nameMethod =
new CtMethod(cp.get(String.class.getName()), "retrieveInternalModelIdName", generateClassField(), clazz);
if (modelIdField == null) {
nameMethod.setBody(createMethodBody("return null;"));
} else {
nameMethod.setBody(createMethodBody("return \"" + modelIdField.getName() + "\";"));
}
clazz.addMethod(nameMethod);
} | java | {
"resource": ""
} |
q13441 | ManipulationUtils.addRetrieveInternalModelTimestamp | train | private static void addRetrieveInternalModelTimestamp(CtClass clazz) throws NotFoundException,
CannotCompileException {
CtClass[] params = generateClassField();
CtMethod method = new CtMethod(cp.get(Long.class.getName()), "retrieveInternalModelTimestamp", params, clazz);
StringBuilder builder = new StringBuilder();
builder.append(createTrace("Called retrieveInternalModelTimestamp"))
.append(String.format("return (Long) ((OpenEngSBModelEntry)%s.get(\"%s\")).getValue();",
TAIL_FIELD, EDBConstants.MODEL_TIMESTAMP));
method.setBody(createMethodBody(builder.toString()));
clazz.addMethod(method);
} | java | {
"resource": ""
} |
q13442 | ManipulationUtils.addRetrieveInternalModelVersion | train | private static void addRetrieveInternalModelVersion(CtClass clazz) throws NotFoundException,
CannotCompileException {
CtClass[] params = generateClassField();
CtMethod method = new CtMethod(cp.get(Integer.class.getName()), "retrieveInternalModelVersion", params, clazz);
StringBuilder builder = new StringBuilder();
builder.append(createTrace("Called retrieveInternalModelVersion"))
.append(String.format("return (Integer) ((OpenEngSBModelEntry)%s.get(\"%s\")).getValue();",
TAIL_FIELD, EDBConstants.MODEL_VERSION));
method.setBody(createMethodBody(builder.toString()));
clazz.addMethod(method);
} | java | {
"resource": ""
} |
q13443 | ManipulationUtils.addToOpenEngSBModelValues | train | private static void addToOpenEngSBModelValues(CtClass clazz) throws NotFoundException,
CannotCompileException, ClassNotFoundException {
StringBuilder builder = new StringBuilder();
CtClass[] params = generateClassField();
CtMethod m = new CtMethod(cp.get(List.class.getName()), "toOpenEngSBModelValues", params, clazz);
builder.append(createTrace("Add elements of the model tail"))
.append("List elements = new ArrayList();\n")
.append(createTrace("Add properties of the model"))
.append(createModelEntryList(clazz))
.append("return elements;");
m.setBody(createMethodBody(builder.toString()));
clazz.addMethod(m);
} | java | {
"resource": ""
} |
q13444 | ManipulationUtils.addToOpenEngSBModelEntries | train | private static void addToOpenEngSBModelEntries(CtClass clazz) throws NotFoundException,
CannotCompileException, ClassNotFoundException {
CtClass[] params = generateClassField();
CtMethod m = new CtMethod(cp.get(List.class.getName()), "toOpenEngSBModelEntries", params, clazz);
StringBuilder builder = new StringBuilder();
builder.append(createTrace("Add elements of the model tail"))
.append("List elements = new ArrayList();\n")
.append(String.format("elements.addAll(%s.values());\n", TAIL_FIELD))
.append("elements.addAll(toOpenEngSBModelValues());\n")
.append("return elements;");
m.setBody(createMethodBody(builder.toString()));
clazz.addMethod(m);
} | java | {
"resource": ""
} |
q13445 | ManipulationUtils.createModelEntryList | train | private static String createModelEntryList(CtClass clazz) throws NotFoundException, CannotCompileException {
StringBuilder builder = new StringBuilder();
CtClass tempClass = clazz;
while (tempClass != null) {
for (CtField field : tempClass.getDeclaredFields()) {
String property = field.getName();
if (property.equals(TAIL_FIELD) || property.equals(LOGGER_FIELD)
|| JavassistUtils.hasAnnotation(field, IgnoredModelField.class.getName())) {
builder.append(createTrace(String.format("Skip property '%s' of the model", property)));
continue;
}
builder.append(handleField(field, clazz));
}
tempClass = tempClass.getSuperclass();
}
return builder.toString();
} | java | {
"resource": ""
} |
q13446 | ManipulationUtils.handleField | train | private static String handleField(CtField field, CtClass clazz) throws NotFoundException, CannotCompileException {
StringBuilder builder = new StringBuilder();
CtClass fieldType = field.getType();
String property = field.getName();
if (fieldType.equals(cp.get(File.class.getName()))) {
return handleFileField(property, clazz);
}
CtMethod getter = getFieldGetter(field, clazz);
if (getter == null) {
LOGGER.warn(String.format("Ignoring property '%s' since there is no getter for it defined", property));
} else if (fieldType.isPrimitive()) {
builder.append(createTrace(String.format("Handle primitive type property '%s'", property)));
CtPrimitiveType primitiveType = (CtPrimitiveType) fieldType;
String wrapperName = primitiveType.getWrapperName();
builder.append(String.format(
"elements.add(new OpenEngSBModelEntry(\"%s\", %s.valueOf(%s()), %s.class));\n",
property, wrapperName, getter.getName(), wrapperName));
} else {
builder.append(createTrace(String.format("Handle property '%s'", property)))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\", %s(), %s.class));\n",
property, getter.getName(), fieldType.getName()));
}
return builder.toString();
} | java | {
"resource": ""
} |
q13447 | ManipulationUtils.handleFileField | train | private static String handleFileField(String property, CtClass clazz) throws NotFoundException,
CannotCompileException {
String wrapperName = property + "wrapper";
StringBuilder builder = new StringBuilder();
builder.append(createTrace(String.format("Handle File type property '%s'", property)))
.append(String.format("if(%s == null) {", property))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\"", wrapperName))
.append(", null, FileWrapper.class));}\n else {")
.append(String.format("FileWrapper %s = new FileWrapper(%s);\n", wrapperName, property))
.append(String.format("%s.serialize();\n", wrapperName))
.append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\",%s,%s.getClass()));}\n",
wrapperName, wrapperName, wrapperName));
addFileFunction(clazz, property);
return builder.toString();
} | java | {
"resource": ""
} |
q13448 | ManipulationUtils.getFieldGetter | train | private static CtMethod getFieldGetter(CtField field, CtClass clazz) throws NotFoundException {
if (field == null) {
return null;
}
return getFieldGetter(field, clazz, false);
} | java | {
"resource": ""
} |
q13449 | ManipulationUtils.getFieldGetter | train | private static CtMethod getFieldGetter(CtField field, CtClass clazz, boolean failover) throws NotFoundException {
CtMethod method = new CtMethod(field.getType(), "descCreateMethod", new CtClass[]{}, clazz);
String desc = method.getSignature();
String getter = getPropertyGetter(field, failover);
try {
return clazz.getMethod(getter, desc);
} catch (NotFoundException e) {
// try once again with getXXX instead of isXXX
if (isBooleanType(field)) {
return getFieldGetter(field, clazz, true);
}
LOGGER.debug(String.format("No getter with the name '%s' and the description '%s' found", getter, desc));
return null;
}
} | java | {
"resource": ""
} |
q13450 | ManipulationUtils.getPropertyGetter | train | private static String getPropertyGetter(CtField field, boolean failover) throws NotFoundException {
String property = field.getName();
if (!failover && isBooleanType(field)) {
return String.format("is%s%s", Character.toUpperCase(property.charAt(0)), property.substring(1));
} else {
return String.format("get%s%s", Character.toUpperCase(property.charAt(0)), property.substring(1));
}
} | java | {
"resource": ""
} |
q13451 | ManipulationUtils.generateClassField | train | private static CtClass[] generateClassField(Class<?>... classes) throws NotFoundException {
CtClass[] result = new CtClass[classes.length];
for (int i = 0; i < classes.length; i++) {
result[i] = cp.get(classes[i].getName());
}
return result;
} | java | {
"resource": ""
} |
q13452 | ManipulationUtils.addFileFunction | train | private static void addFileFunction(CtClass clazz, String property)
throws NotFoundException, CannotCompileException {
String wrapperName = property + "wrapper";
String funcName = "set";
funcName = funcName + Character.toUpperCase(wrapperName.charAt(0));
funcName = funcName + wrapperName.substring(1);
String setterName = "set";
setterName = setterName + Character.toUpperCase(property.charAt(0));
setterName = setterName + property.substring(1);
CtClass[] params = generateClassField(FileWrapper.class);
CtMethod newFunc = new CtMethod(CtClass.voidType, funcName, params, clazz);
newFunc.setBody("{ " + setterName + "($1.returnFile());\n }");
clazz.addMethod(newFunc);
} | java | {
"resource": ""
} |
q13453 | XLinkConnectorManagerImpl.urlEncodeParameter | train | private static String urlEncodeParameter(String parameter) {
try {
return URLEncoder.encode(parameter, "UTF-8");
} catch (UnsupportedEncodingException ex) {
log.warn("Could not encode parameter.", ex);
}
return parameter;
} | java | {
"resource": ""
} |
q13454 | SwingFrontend.runWithContext | train | public static void runWithContext(Runnable r) {
try {
browserStack.push(SwingFrame.getActiveWindow().getVisibleTab());
Subject.setCurrent(SwingFrame.getActiveWindow().getSubject());
r.run();
} finally {
Subject.setCurrent(null);
browserStack.pop();
}
} | java | {
"resource": ""
} |
q13455 | AbstractBaseSource.createResourceReader | train | protected Reader createResourceReader(Resource resource) {
try {
return new InputStreamReader(resource.getInputStream());
}
catch (IOException e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q13456 | OrientModelGraph.shutdown | train | public void shutdown() {
ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
try {
ClassLoader orientClassLoader = OIndexes.class.getClassLoader();
Thread.currentThread().setContextClassLoader(orientClassLoader);
graph.close();
} finally {
Thread.currentThread().setContextClassLoader(origClassLoader);
}
} | java | {
"resource": ""
} |
q13457 | OrientModelGraph.cleanDatabase | train | public void cleanDatabase() {
lockingMechanism.writeLock().lock();
try {
for (ODocument edge : graph.browseEdges()) {
edge.delete();
}
for (ODocument node : graph.browseVertices()) {
node.delete();
}
} finally {
lockingMechanism.writeLock().unlock();
}
} | java | {
"resource": ""
} |
q13458 | OrientModelGraph.checkTransformationDescriptionId | train | private void checkTransformationDescriptionId(TransformationDescription description) {
if (description.getId() == null) {
description.setId("EKBInternal-" + counter.incrementAndGet());
}
} | java | {
"resource": ""
} |
q13459 | OrientModelGraph.getEdgesBetweenModels | train | private List<ODocument> getEdgesBetweenModels(String source, String target) {
ODocument from = getModel(source);
ODocument to = getModel(target);
String query = "select from E where out = ? AND in = ?";
return graph.query(new OSQLSynchQuery<ODocument>(query), from, to);
} | java | {
"resource": ""
} |
q13460 | OrientModelGraph.getNeighborsOfModel | train | private List<ODocument> getNeighborsOfModel(String model) {
String query = String.format("select from Models where in.out.%s in [?]", OGraphDatabase.LABEL);
List<ODocument> neighbors = graph.query(new OSQLSynchQuery<ODocument>(query), model);
return neighbors;
} | java | {
"resource": ""
} |
q13461 | OrientModelGraph.getOrCreateModel | train | private ODocument getOrCreateModel(String model) {
ODocument node = getModel(model);
if (node == null) {
node = graph.createVertex("Models");
OrientModelGraphUtils.setIdFieldValue(node, model.toString());
OrientModelGraphUtils.setActiveFieldValue(node, false);
node.save();
}
return node;
} | java | {
"resource": ""
} |
q13462 | OrientModelGraph.getModel | train | private ODocument getModel(String model) {
String query = String.format("select from Models where %s = ?", OGraphDatabase.LABEL);
List<ODocument> from = graph.query(new OSQLSynchQuery<ODocument>(query), model);
if (from.size() > 0) {
return from.get(0);
} else {
return null;
}
} | java | {
"resource": ""
} |
q13463 | OrientModelGraph.recursivePathSearch | train | private List<ODocument> recursivePathSearch(String start, String end, List<String> ids, ODocument... steps) {
List<ODocument> neighbors = getNeighborsOfModel(start);
for (ODocument neighbor : neighbors) {
if (alreadyVisited(neighbor, steps) || !OrientModelGraphUtils.getActiveFieldValue(neighbor)) {
continue;
}
ODocument nextStep = getEdgeWithPossibleId(start, OrientModelGraphUtils.getIdFieldValue(neighbor), ids);
if (nextStep == null) {
continue;
}
if (OrientModelGraphUtils.getIdFieldValue(neighbor).equals(end)) {
List<ODocument> result = new ArrayList<ODocument>();
List<String> copyIds = new ArrayList<String>(ids);
for (ODocument step : steps) {
String id = OrientModelGraphUtils.getIdFieldValue(step);
if (id != null && copyIds.contains(id)) {
copyIds.remove(id);
}
result.add(step);
}
String id = OrientModelGraphUtils.getIdFieldValue(nextStep);
if (id != null && copyIds.contains(id)) {
copyIds.remove(id);
}
result.add(nextStep);
if (copyIds.isEmpty()) {
return result;
}
}
ODocument[] path = Arrays.copyOf(steps, steps.length + 1);
path[path.length - 1] = nextStep;
List<ODocument> check =
recursivePathSearch(OrientModelGraphUtils.getIdFieldValue(neighbor), end, ids, path);
if (check != null) {
return check;
}
}
return null;
} | java | {
"resource": ""
} |
q13464 | OrientModelGraph.getEdgeWithPossibleId | train | private ODocument getEdgeWithPossibleId(String start, String end, List<String> ids) {
List<ODocument> edges = getEdgesBetweenModels(start, end);
for (ODocument edge : edges) {
if (ids.contains(OrientModelGraphUtils.getIdFieldValue(edge))) {
return edge;
}
}
return edges.size() != 0 ? edges.get(0) : null;
} | java | {
"resource": ""
} |
q13465 | OrientModelGraph.alreadyVisited | train | private boolean alreadyVisited(ODocument neighbor, ODocument[] steps) {
for (ODocument step : steps) {
ODocument out = graph.getOutVertex(step);
if (out.equals(neighbor)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q13466 | OrientModelGraph.isModelActive | train | public boolean isModelActive(ModelDescription model) {
lockingMechanism.readLock().lock();
try {
ODocument node = getModel(model.toString());
return OrientModelGraphUtils.getActiveFieldValue(node);
} finally {
lockingMechanism.readLock().unlock();
}
} | java | {
"resource": ""
} |
q13467 | DefaultWebResourceFactoryImpl.getJerseyClient | train | protected com.sun.jersey.api.client.Client getJerseyClient() {
final ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(clientConfig);
if(this.debug) {
client.addFilter(new LoggingFilter(System.out));
}
return client;
} | java | {
"resource": ""
} |
q13468 | StringUtils.isEmpty | train | public static boolean isEmpty(final Collection<String> c) {
if (c == null || c.isEmpty()) {
return false;
}
for (final String text : c) {
if (isNotEmpty(text)) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q13469 | StringUtils.isBlank | train | public static boolean isBlank(final Collection<String> c) {
if (c == null || c.isEmpty()) {
return false;
}
for (final String text : c) {
if (isNotBlank(text)) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q13470 | Device.hello | train | private boolean hello(InetAddress broadcast) {
if (socket == null) return false;
Command hello = new Command();
byte[] helloMsg = hello.create();
DatagramPacket packet;
if (ip == null){
if (this.acceptableModels == null) return false;
packet = new DatagramPacket(helloMsg, helloMsg.length, broadcast, PORT);
} else {
packet = new DatagramPacket(helloMsg, helloMsg.length, ip, PORT);
}
try {
socket.send(packet);
} catch (IOException e) {
return false;
}
packet = new DatagramPacket(rcv, rcv.length);
try {
socket.receive(packet);
} catch (IOException e) {
return false;
}
if (ip == null){
ip = packet.getAddress();
}
byte[] worker = new byte[2];
System.arraycopy(rcv, 2, worker, 0, 2);
int length = (int)ByteArray.fromBytes(worker);
worker = new byte[length];
System.arraycopy(rcv, 0, worker, 0, length);
Response response;
try {
response = new Response(worker, null);
} catch (CommandExecutionException e) {
return false;
}
if (token == null){
if (!(response.getToken().equals(new Token("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",16)) || response.getToken().equals(new Token("00000000000000000000000000000000",16)))) {
token = response.getToken();
} else {
return false;
}
}
if (!((response.getDeviceID() == -1) || (response.getTimeStamp() == -1))){
deviceID = response.getDeviceID();
timeStamp = response.getTimeStamp();
methodID = timeStamp & 0b1111111111111; // Possible collision about every 2 hours > acceptable
if (this.acceptableModels != null){
boolean modelOk = false;
for (String s: this.acceptableModels) {
try {
if (s.equals(model())) modelOk = true;
} catch (CommandExecutionException ignored) {
}
}
return modelOk;
}
return true;
}
return false;
} | java | {
"resource": ""
} |
q13471 | Device.discover | train | public boolean discover(){
boolean helloResponse = false;
for (int helloRetries = this.retries; helloRetries >= 0; helloRetries--) {
List<InetAddress> broadcast = listAllBroadcastAddresses();
if (broadcast == null) return false;
for (InetAddress i : broadcast) {
if (hello(i)) {
helloResponse = true;
break;
}
}
if (helloResponse) break;
}
return helloResponse;
} | java | {
"resource": ""
} |
q13472 | Device.send | train | public String send(String payload) throws CommandExecutionException {
if (payload == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS);
if (deviceID == -1 || timeStamp == -1 || token == null || ip == null) {
if (!discover()) throw new CommandExecutionException(CommandExecutionException.Error.DEVICE_NOT_FOUND);
}
if (methodID >= 10000) methodID = 1;
if (ip == null || token == null) throw new CommandExecutionException(CommandExecutionException.Error.IP_OR_TOKEN_UNKNOWN);
if (socket == null) return null;
timeStamp++;
Command msg = new Command(this.token,this.deviceID,timeStamp,this.methodID,"", null);
methodID++;
int retriesLeft = this.retries;
while (true) {
try {
byte[] resp = send(msg.create(payload));
if (!Response.testMessage(resp, this.token)) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_RESPONSE);
if (resp.length > 0x20) {
byte[] pl = new byte[resp.length - 0x20];
System.arraycopy(resp, 0x20, pl, 0, pl.length);
String payloadString = Response.decryptPayload(pl, this.token);
if (payloadString == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_RESPONSE);
return payloadString;
}
} catch (CommandExecutionException e) {
if (retriesLeft > 0){
retriesLeft--;
continue;
}
throw e;
}
}
} | java | {
"resource": ""
} |
q13473 | Device.update | train | public boolean update(String url, String md5) throws CommandExecutionException {
if (url == null || md5 == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS);
if (md5.length() != 32) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_PARAMETERS);
JSONObject params = new JSONObject();
params.put("mode","normal");
params.put("install", "1");
params.put("app_url", url);
params.put("file_md5", md5);
params.put("proc", "dnld install");
return sendOk("miIO.ota", params);
} | java | {
"resource": ""
} |
q13474 | Device.updateProgress | train | public int updateProgress() throws CommandExecutionException {
int resp = sendToArray("miIO.get_ota_progress").optInt(0, -1);
if ((resp < 0) || (resp > 100)) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_RESPONSE);
return resp;
} | java | {
"resource": ""
} |
q13475 | Device.updateStatus | train | public String updateStatus() throws CommandExecutionException {
String resp = sendToArray("miIO.get_ota_state").optString(0, null);
if (resp == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_RESPONSE);
return resp;
} | java | {
"resource": ""
} |
q13476 | Device.model | train | public String model() throws CommandExecutionException {
JSONObject in = info();
if (in == null) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_RESPONSE);
return in.optString("model");
} | java | {
"resource": ""
} |
q13477 | ByteArray.hexToBytes | train | public static byte[] hexToBytes(String s) {
try {
if (s == null) return new byte[0];
s = s.toUpperCase();
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
} catch (StringIndexOutOfBoundsException e) {
return null;
}
} | java | {
"resource": ""
} |
q13478 | ByteArray.append | train | public static byte[] append(byte[] first, byte[] second) {
if ((first == null) || (second == null)) return null;
byte[] output = new byte[first.length + second.length];
System.arraycopy(first, 0, output, 0, first.length);
System.arraycopy(second, 0, output, first.length, second.length);
return output;
} | java | {
"resource": ""
} |
q13479 | ByteArray.toBytes | train | public static byte[] toBytes(long value, int length) {
if (length <= 0) return new byte[0];
if (length > 8) length = 8;
byte[] out = new byte[length];
for (int i = length - 1; i >= 0; i--){
out[i] = (byte)(value & 0xFFL);
value = value >> 8;
}
return out;
} | java | {
"resource": ""
} |
q13480 | ByteArray.fromBytes | train | public static long fromBytes(byte[] value){
if (value == null) return 0;
long out = 0;
int length = value.length;
if (length > 8) length = 8;
for (int i = 0; i < length; i++){
out = (out << 8) + (value[i] & 0xff);
}
return out;
} | java | {
"resource": ""
} |
q13481 | AbstractInsnNode.acceptAnnotations | train | protected final void acceptAnnotations(final MethodVisitor mv) {
int n = visibleTypeAnnotations == null ? 0 : visibleTypeAnnotations
.size();
for (int i = 0; i < n; ++i) {
TypeAnnotationNode an = visibleTypeAnnotations.get(i);
an.accept(mv.visitInsnAnnotation(an.typeRef, an.typePath, an.desc,
true));
}
n = invisibleTypeAnnotations == null ? 0 : invisibleTypeAnnotations
.size();
for (int i = 0; i < n; ++i) {
TypeAnnotationNode an = invisibleTypeAnnotations.get(i);
an.accept(mv.visitInsnAnnotation(an.typeRef, an.typePath, an.desc,
false));
}
} | java | {
"resource": ""
} |
q13482 | AbstractInsnNode.cloneAnnotations | train | protected final AbstractInsnNode cloneAnnotations(
final AbstractInsnNode insn) {
if (insn.visibleTypeAnnotations != null) {
this.visibleTypeAnnotations = new ArrayList<TypeAnnotationNode>();
for (int i = 0; i < insn.visibleTypeAnnotations.size(); ++i) {
TypeAnnotationNode src = insn.visibleTypeAnnotations.get(i);
TypeAnnotationNode ann = new TypeAnnotationNode(src.typeRef,
src.typePath, src.desc);
src.accept(ann);
this.visibleTypeAnnotations.add(ann);
}
}
if (insn.invisibleTypeAnnotations != null) {
this.invisibleTypeAnnotations = new ArrayList<TypeAnnotationNode>();
for (int i = 0; i < insn.invisibleTypeAnnotations.size(); ++i) {
TypeAnnotationNode src = insn.invisibleTypeAnnotations.get(i);
TypeAnnotationNode ann = new TypeAnnotationNode(src.typeRef,
src.typePath, src.desc);
src.accept(ann);
this.invisibleTypeAnnotations.add(ann);
}
}
return this;
} | java | {
"resource": ""
} |
q13483 | BeanBox.getDebugInfo | train | public String getDebugInfo() {
StringBuilder sb = new StringBuilder("\r\n========BeanBox Debug for " + this + "===========\r\n");
sb.append("target=" + this.target).append("\r\n");
sb.append("pureValue=" + this.pureValue).append("\r\n");
sb.append("type=" + this.type).append("\r\n");
sb.append("required=" + this.required).append("\r\n");
sb.append("beanClass=" + this.beanClass).append("\r\n");
sb.append("singleton=" + this.singleton).append("\r\n");
sb.append("methodAops=" + this.methodAops).append("\r\n");
sb.append("methodAopRules=" + this.aopRules).append("\r\n");
sb.append("constructor=" + this.constructor).append("\r\n");
sb.append("constructorParams=" + this.constructorParams).append("\r\n");
sb.append("postConstructs=" + this.postConstruct).append("\r\n");
sb.append("preDestorys=" + this.preDestroy).append("\r\n");
sb.append("fieldInjects=" + this.fieldInjects).append("\r\n");
sb.append("methodInjects=" + this.methodInjects).append("\r\n");
sb.append("createMethod=" + this.createMethod).append("\r\n");
sb.append("configMethod=" + this.configMethod).append("\r\n");
sb.append("========BeanBox Debug Info End===========");
return sb.toString();
} | java | {
"resource": ""
} |
q13484 | BeanBox.addBeanAop | train | public synchronized BeanBox addBeanAop(Object aop, String methodNameRegex) {
checkOrCreateMethodAopRules();
aopRules.add(new Object[] { BeanBoxUtils.checkAOP(aop), methodNameRegex });
return this;
} | java | {
"resource": ""
} |
q13485 | BeanBox.injectField | train | public BeanBox injectField(String fieldName, Object inject) {
BeanBox box = BeanBoxUtils.wrapParamToBox(inject);
checkOrCreateFieldInjects();
Field f = ReflectionUtils.findField(beanClass, fieldName);
box.setType(f.getType());
ReflectionUtils.makeAccessible(f);
this.getFieldInjects().put(f, box);
return this;
} | java | {
"resource": ""
} |
q13486 | BeanBox.injectValue | train | public BeanBox injectValue(String fieldName, Object constValue) {
checkOrCreateFieldInjects();
Field f = ReflectionUtils.findField(beanClass, fieldName);
BeanBox inject = new BeanBox();
inject.setTarget(constValue);
inject.setType(f.getType());
inject.setPureValue(true);
ReflectionUtils.makeAccessible(f);
this.getFieldInjects().put(f, inject);
return this;
} | java | {
"resource": ""
} |
q13487 | TryCatchBlockNode.updateIndex | train | public void updateIndex(final int index) {
int newTypeRef = 0x42000000 | (index << 8);
if (visibleTypeAnnotations != null) {
for (TypeAnnotationNode tan : visibleTypeAnnotations) {
tan.typeRef = newTypeRef;
}
}
if (invisibleTypeAnnotations != null) {
for (TypeAnnotationNode tan : invisibleTypeAnnotations) {
tan.typeRef = newTypeRef;
}
}
} | java | {
"resource": ""
} |
q13488 | TryCatchBlockNode.accept | train | public void accept(final MethodVisitor mv) {
mv.visitTryCatchBlock(start.getLabel(), end.getLabel(),
handler == null ? null : handler.getLabel(), type);
int n = visibleTypeAnnotations == null ? 0 : visibleTypeAnnotations
.size();
for (int i = 0; i < n; ++i) {
TypeAnnotationNode an = visibleTypeAnnotations.get(i);
an.accept(mv.visitTryCatchAnnotation(an.typeRef, an.typePath,
an.desc, true));
}
n = invisibleTypeAnnotations == null ? 0 : invisibleTypeAnnotations
.size();
for (int i = 0; i < n; ++i) {
TypeAnnotationNode an = invisibleTypeAnnotations.get(i);
an.accept(mv.visitTryCatchAnnotation(an.typeRef, an.typePath,
an.desc, false));
}
} | java | {
"resource": ""
} |
q13489 | CheckSignatureAdapter.visitFormalTypeParameter | train | @Override
public void visitFormalTypeParameter(final String name) {
if (type == TYPE_SIGNATURE
|| (state != EMPTY && state != FORMAL && state != BOUND)) {
throw new IllegalStateException();
}
CheckMethodAdapter.checkIdentifier(name, "formal type parameter");
state = FORMAL;
if (sv != null) {
sv.visitFormalTypeParameter(name);
}
} | java | {
"resource": ""
} |
q13490 | ASMifier.appendConstant | train | static void appendConstant(final StringBuffer buf, final Object cst) {
if (cst == null) {
buf.append("null");
} else if (cst instanceof String) {
appendString(buf, (String) cst);
} else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type) cst).getDescriptor());
buf.append("\")");
} else if (cst instanceof Handle) {
buf.append("new Handle(");
Handle h = (Handle) cst;
buf.append("Opcodes.").append(HANDLE_TAG[h.getTag()])
.append(", \"");
buf.append(h.getOwner()).append("\", \"");
buf.append(h.getName()).append("\", \"");
buf.append(h.getDesc()).append("\")");
} else if (cst instanceof Byte) {
buf.append("new Byte((byte)").append(cst).append(')');
} else if (cst instanceof Boolean) {
buf.append(((Boolean) cst).booleanValue() ? "Boolean.TRUE"
: "Boolean.FALSE");
} else if (cst instanceof Short) {
buf.append("new Short((short)").append(cst).append(')');
} else if (cst instanceof Character) {
int c = ((Character) cst).charValue();
buf.append("new Character((char)").append(c).append(')');
} else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(')');
} else if (cst instanceof Float) {
buf.append("new Float(\"").append(cst).append("\")");
} else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
} else if (cst instanceof Double) {
buf.append("new Double(\"").append(cst).append("\")");
} else if (cst instanceof byte[]) {
byte[] v = (byte[]) cst;
buf.append("new byte[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
} | java | {
"resource": ""
} |
q13491 | CheckClassAdapter.verify | train | public static void verify(final ClassReader cr, final ClassLoader loader,
final boolean dump, final PrintWriter pw) {
ClassNode cn = new ClassNode();
cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);
Type syperType = cn.superName == null ? null : Type
.getObjectType(cn.superName);
List<MethodNode> methods = cn.methods;
List<Type> interfaces = new ArrayList<Type>();
for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
interfaces.add(Type.getObjectType(i.next()));
}
for (int i = 0; i < methods.size(); ++i) {
MethodNode method = methods.get(i);
SimpleVerifier verifier = new SimpleVerifier(
Type.getObjectType(cn.name), syperType, interfaces,
(cn.access & Opcodes.ACC_INTERFACE) != 0);
Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
if (loader != null) {
verifier.setClassLoader(loader);
}
try {
a.analyze(cn.name, method);
if (!dump) {
continue;
}
} catch (Exception e) {
e.printStackTrace(pw);
}
printAnalyzerResult(method, a, pw);
}
pw.flush();
} | java | {
"resource": ""
} |
q13492 | CheckClassAdapter.verify | train | public static void verify(final ClassReader cr, final boolean dump,
final PrintWriter pw) {
verify(cr, null, dump, pw);
} | java | {
"resource": ""
} |
q13493 | CheckClassAdapter.checkAccess | train | static void checkAccess(final int access, final int possibleAccess) {
if ((access & ~possibleAccess) != 0) {
throw new IllegalArgumentException("Invalid access flags: "
+ access);
}
int pub = (access & Opcodes.ACC_PUBLIC) == 0 ? 0 : 1;
int pri = (access & Opcodes.ACC_PRIVATE) == 0 ? 0 : 1;
int pro = (access & Opcodes.ACC_PROTECTED) == 0 ? 0 : 1;
if (pub + pri + pro > 1) {
throw new IllegalArgumentException(
"public private and protected are mutually exclusive: "
+ access);
}
int fin = (access & Opcodes.ACC_FINAL) == 0 ? 0 : 1;
int abs = (access & Opcodes.ACC_ABSTRACT) == 0 ? 0 : 1;
if (fin + abs > 1) {
throw new IllegalArgumentException(
"final and abstract are mutually exclusive: " + access);
}
} | java | {
"resource": ""
} |
q13494 | CheckClassAdapter.checkClassSignature | train | public static void checkClassSignature(final String signature) {
// ClassSignature:
// FormalTypeParameters? ClassTypeSignature ClassTypeSignature*
int pos = 0;
if (getChar(signature, 0) == '<') {
pos = checkFormalTypeParameters(signature, pos);
}
pos = checkClassTypeSignature(signature, pos);
while (getChar(signature, pos) == 'L') {
pos = checkClassTypeSignature(signature, pos);
}
if (pos != signature.length()) {
throw new IllegalArgumentException(signature + ": error at index "
+ pos);
}
} | java | {
"resource": ""
} |
q13495 | CheckClassAdapter.checkMethodSignature | train | public static void checkMethodSignature(final String signature) {
// MethodTypeSignature:
// FormalTypeParameters? ( TypeSignature* ) ( TypeSignature | V ) (
// ^ClassTypeSignature | ^TypeVariableSignature )*
int pos = 0;
if (getChar(signature, 0) == '<') {
pos = checkFormalTypeParameters(signature, pos);
}
pos = checkChar('(', signature, pos);
while ("ZCBSIFJDL[T".indexOf(getChar(signature, pos)) != -1) {
pos = checkTypeSignature(signature, pos);
}
pos = checkChar(')', signature, pos);
if (getChar(signature, pos) == 'V') {
++pos;
} else {
pos = checkTypeSignature(signature, pos);
}
while (getChar(signature, pos) == '^') {
++pos;
if (getChar(signature, pos) == 'L') {
pos = checkClassTypeSignature(signature, pos);
} else {
pos = checkTypeVariableSignature(signature, pos);
}
}
if (pos != signature.length()) {
throw new IllegalArgumentException(signature + ": error at index "
+ pos);
}
} | java | {
"resource": ""
} |
q13496 | CheckClassAdapter.checkFieldSignature | train | public static void checkFieldSignature(final String signature) {
int pos = checkFieldTypeSignature(signature, 0);
if (pos != signature.length()) {
throw new IllegalArgumentException(signature + ": error at index "
+ pos);
}
} | java | {
"resource": ""
} |
q13497 | CheckClassAdapter.checkTypeRefAndPath | train | static void checkTypeRefAndPath(int typeRef, TypePath typePath) {
int mask = 0;
switch (typeRef >>> 24) {
case TypeReference.CLASS_TYPE_PARAMETER:
case TypeReference.METHOD_TYPE_PARAMETER:
case TypeReference.METHOD_FORMAL_PARAMETER:
mask = 0xFFFF0000;
break;
case TypeReference.FIELD:
case TypeReference.METHOD_RETURN:
case TypeReference.METHOD_RECEIVER:
case TypeReference.LOCAL_VARIABLE:
case TypeReference.RESOURCE_VARIABLE:
case TypeReference.INSTANCEOF:
case TypeReference.NEW:
case TypeReference.CONSTRUCTOR_REFERENCE:
case TypeReference.METHOD_REFERENCE:
mask = 0xFF000000;
break;
case TypeReference.CLASS_EXTENDS:
case TypeReference.CLASS_TYPE_PARAMETER_BOUND:
case TypeReference.METHOD_TYPE_PARAMETER_BOUND:
case TypeReference.THROWS:
case TypeReference.EXCEPTION_PARAMETER:
mask = 0xFFFFFF00;
break;
case TypeReference.CAST:
case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:
case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:
mask = 0xFF0000FF;
break;
default:
throw new IllegalArgumentException("Invalid type reference sort 0x"
+ Integer.toHexString(typeRef >>> 24));
}
if ((typeRef & ~mask) != 0) {
throw new IllegalArgumentException("Invalid type reference 0x"
+ Integer.toHexString(typeRef));
}
if (typePath != null) {
for (int i = 0; i < typePath.getLength(); ++i) {
int step = typePath.getStep(i);
if (step != TypePath.ARRAY_ELEMENT
&& step != TypePath.INNER_TYPE
&& step != TypePath.TYPE_ARGUMENT
&& step != TypePath.WILDCARD_BOUND) {
throw new IllegalArgumentException(
"Invalid type path step " + i + " in " + typePath);
}
if (step != TypePath.TYPE_ARGUMENT
&& typePath.getStepArgument(i) != 0) {
throw new IllegalArgumentException(
"Invalid type path step argument for step " + i
+ " in " + typePath);
}
}
}
} | java | {
"resource": ""
} |
q13498 | CheckClassAdapter.checkFormalTypeParameters | train | private static int checkFormalTypeParameters(final String signature, int pos) {
// FormalTypeParameters:
// < FormalTypeParameter+ >
pos = checkChar('<', signature, pos);
pos = checkFormalTypeParameter(signature, pos);
while (getChar(signature, pos) != '>') {
pos = checkFormalTypeParameter(signature, pos);
}
return pos + 1;
} | java | {
"resource": ""
} |
q13499 | CheckClassAdapter.checkFormalTypeParameter | train | private static int checkFormalTypeParameter(final String signature, int pos) {
// FormalTypeParameter:
// Identifier : FieldTypeSignature? (: FieldTypeSignature)*
pos = checkIdentifier(signature, pos);
pos = checkChar(':', signature, pos);
if ("L[T".indexOf(getChar(signature, pos)) != -1) {
pos = checkFieldTypeSignature(signature, pos);
}
while (getChar(signature, pos) == ':') {
pos = checkFieldTypeSignature(signature, pos + 1);
}
return pos;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.