code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public TimeZone getTimeZone()
{
// If the TimeZone object is shared by other Calendar instances, then
// create a clone.
if (sharedZone) {
zone = (TimeZone) zone.clone();
sharedZone = false;
}
return zone;
} } | public class class_name {
public TimeZone getTimeZone()
{
// If the TimeZone object is shared by other Calendar instances, then
// create a clone.
if (sharedZone) {
zone = (TimeZone) zone.clone(); // depends on control dependency: [if], data = [none]
sharedZone = false; // depends on control dependency: [if], data = [none]
}
return zone;
} } |
public class class_name {
@Override
protected void paintComponent(final RenderContext renderContext) {
if (getState() == DISPLAY_STATE) {
setState(ACTIVE_STATE);
showWindow(renderContext);
} else if (getState() == ACTIVE_STATE && isTargeted()) {
getComponentModel().wrappedContent.paint(renderContext);
}
} } | public class class_name {
@Override
protected void paintComponent(final RenderContext renderContext) {
if (getState() == DISPLAY_STATE) {
setState(ACTIVE_STATE); // depends on control dependency: [if], data = [none]
showWindow(renderContext); // depends on control dependency: [if], data = [none]
} else if (getState() == ACTIVE_STATE && isTargeted()) {
getComponentModel().wrappedContent.paint(renderContext); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected ExtractedFileInformation extractFileFromArchive(String fileName,
String regex) throws RepositoryArchiveException, RepositoryArchiveEntryNotFoundException, RepositoryArchiveIOException {
JarFile jarFile = null;
ExtractedFileInformation result = null;
File outputFile = null;
File sourceArchive = new File(fileName);
try {
try {
jarFile = new JarFile(sourceArchive);
} catch (FileNotFoundException | NoSuchFileException fne) {
throw new RepositoryArchiveException("Unable to locate archive " + fileName, sourceArchive, fne);
} catch (IOException ioe) {
throw new RepositoryArchiveIOException("Error opening archive ", sourceArchive, ioe);
}
Enumeration<JarEntry> enumEntries = jarFile.entries();
// Iterate through the files in the jar file searching for one we
// are interested in
while (enumEntries.hasMoreElements()) {
JarEntry entry = enumEntries.nextElement();
String name = entry.getName();
if (Pattern.matches(regex, name)) {
// Don't want to use the entire path to the file so create a
// file
// and then recreate it using just the "name" part of the
// filename
outputFile = new File(name);
outputFile = new File(outputFile.getName());
outputFile.deleteOnExit();
try {
copyStreams(jarFile.getInputStream(entry),
new FileOutputStream(outputFile));
} catch (IOException ioe) {
throw new RepositoryArchiveIOException("Failed to extract file " + name + " inside "
+ fileName + " to "
+ outputFile.getAbsolutePath(), sourceArchive, ioe);
}
result = new ExtractedFileInformation(outputFile, sourceArchive, name);
break;
}
}
} finally {
try {
if (null != jarFile) {
jarFile.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new RepositoryArchiveIOException("Error closing archive ", sourceArchive, e);
}
}
// Make sure we have found a file
if (null == outputFile) {
throw new RepositoryArchiveEntryNotFoundException("Failed to find file matching regular expression <" + regex
+ "> inside archive " + fileName, sourceArchive, regex);
}
return result;
} } | public class class_name {
protected ExtractedFileInformation extractFileFromArchive(String fileName,
String regex) throws RepositoryArchiveException, RepositoryArchiveEntryNotFoundException, RepositoryArchiveIOException {
JarFile jarFile = null;
ExtractedFileInformation result = null;
File outputFile = null;
File sourceArchive = new File(fileName);
try {
try {
jarFile = new JarFile(sourceArchive); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException | NoSuchFileException fne) {
throw new RepositoryArchiveException("Unable to locate archive " + fileName, sourceArchive, fne);
} catch (IOException ioe) { // depends on control dependency: [catch], data = [none]
throw new RepositoryArchiveIOException("Error opening archive ", sourceArchive, ioe);
} // depends on control dependency: [catch], data = [none]
Enumeration<JarEntry> enumEntries = jarFile.entries();
// Iterate through the files in the jar file searching for one we
// are interested in
while (enumEntries.hasMoreElements()) {
JarEntry entry = enumEntries.nextElement();
String name = entry.getName();
if (Pattern.matches(regex, name)) {
// Don't want to use the entire path to the file so create a
// file
// and then recreate it using just the "name" part of the
// filename
outputFile = new File(name); // depends on control dependency: [if], data = [none]
outputFile = new File(outputFile.getName()); // depends on control dependency: [if], data = [none]
outputFile.deleteOnExit(); // depends on control dependency: [if], data = [none]
try {
copyStreams(jarFile.getInputStream(entry),
new FileOutputStream(outputFile)); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
throw new RepositoryArchiveIOException("Failed to extract file " + name + " inside "
+ fileName + " to "
+ outputFile.getAbsolutePath(), sourceArchive, ioe);
} // depends on control dependency: [catch], data = [none]
result = new ExtractedFileInformation(outputFile, sourceArchive, name); // depends on control dependency: [if], data = [none]
break;
}
}
} finally {
try {
if (null != jarFile) {
jarFile.close(); // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
e.printStackTrace();
throw new RepositoryArchiveIOException("Error closing archive ", sourceArchive, e);
} // depends on control dependency: [catch], data = [none]
}
// Make sure we have found a file
if (null == outputFile) {
throw new RepositoryArchiveEntryNotFoundException("Failed to find file matching regular expression <" + regex
+ "> inside archive " + fileName, sourceArchive, regex);
}
return result;
} } |
public class class_name {
private static int findEndTrimWhitespace(CharSequence s)
{
for (int i = s.length(); i > 0; i--)
{
if (!Character.isWhitespace(s.charAt(i - 1)))
{
return i;
}
}
return 0;
} } | public class class_name {
private static int findEndTrimWhitespace(CharSequence s)
{
for (int i = s.length(); i > 0; i--)
{
if (!Character.isWhitespace(s.charAt(i - 1)))
{
return i; // depends on control dependency: [if], data = [none]
}
}
return 0;
} } |
public class class_name {
public void replaceChildOutputSchemaNames(AbstractPlanNode child) {
NodeSchema childSchema = child.getTrueOutputSchema(false);
NodeSchema mySchema = getOutputSchema();
assert(childSchema.size() == mySchema.size());
for (int idx = 0; idx < childSchema.size(); idx += 1) {
SchemaColumn cCol = childSchema.getColumn(idx);
SchemaColumn myCol = mySchema.getColumn(idx);
assert(cCol.getValueType() == myCol.getValueType());
assert(cCol.getExpression() instanceof TupleValueExpression);
assert(myCol.getExpression() instanceof TupleValueExpression);
cCol.reset(myCol.getTableName(),
myCol.getTableAlias(),
myCol.getColumnName(),
myCol.getColumnAlias());
}
} } | public class class_name {
public void replaceChildOutputSchemaNames(AbstractPlanNode child) {
NodeSchema childSchema = child.getTrueOutputSchema(false);
NodeSchema mySchema = getOutputSchema();
assert(childSchema.size() == mySchema.size());
for (int idx = 0; idx < childSchema.size(); idx += 1) {
SchemaColumn cCol = childSchema.getColumn(idx);
SchemaColumn myCol = mySchema.getColumn(idx);
assert(cCol.getValueType() == myCol.getValueType()); // depends on control dependency: [for], data = [none]
assert(cCol.getExpression() instanceof TupleValueExpression); // depends on control dependency: [for], data = [none]
assert(myCol.getExpression() instanceof TupleValueExpression); // depends on control dependency: [for], data = [none]
cCol.reset(myCol.getTableName(),
myCol.getTableAlias(),
myCol.getColumnName(),
myCol.getColumnAlias()); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public void init(StateMachineExecutor executor) {
this.executor = Assert.notNull(executor, "executor");
this.context = executor.context();
this.clock = context.clock();
this.sessions = context.sessions();
if (this instanceof SessionListener) {
executor.context().sessions().addListener((SessionListener) this);
}
configure(executor);
} } | public class class_name {
public void init(StateMachineExecutor executor) {
this.executor = Assert.notNull(executor, "executor");
this.context = executor.context();
this.clock = context.clock();
this.sessions = context.sessions();
if (this instanceof SessionListener) {
executor.context().sessions().addListener((SessionListener) this); // depends on control dependency: [if], data = [none]
}
configure(executor);
} } |
public class class_name {
public void blockingRun(final Task<?> task, final String planClass) {
try {
acquirePermit(planClass);
runWithPermit(task, planClass);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} } | public class class_name {
public void blockingRun(final Task<?> task, final String planClass) {
try {
acquirePermit(planClass); // depends on control dependency: [try], data = [none]
runWithPermit(task, planClass); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String toPlain(String input) {
Matcher matcher = SPACE_PATTERN.matcher(input);
if (matcher.find()) {
return matcher.replaceAll("");
} else {
return input;
}
} } | public class class_name {
public static String toPlain(String input) {
Matcher matcher = SPACE_PATTERN.matcher(input);
if (matcher.find()) {
return matcher.replaceAll(""); // depends on control dependency: [if], data = [none]
} else {
return input; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void increaseEncryptedBuffer() throws IOException {
final int packetSize = getConnLink().getPacketBufferSize();
if (null == this.encryptedAppBuffer) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Allocating encryptedAppBuffer, size=" + packetSize);
}
this.encryptedAppBuffer = SSLUtils.allocateByteBuffer(
packetSize, getConfig().getEncryptBuffersDirect());
} else {
// The existing buffer isn't big enough, add another packet size to it
final int cap = this.encryptedAppBuffer.capacity();
final int newsize = cap + packetSize;
if (0 > newsize) {
// wrapped over max-int
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Unable to increase encrypted buffer beyond " + cap);
}
throw new IOException("Unable to increase buffer beyond " + cap);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Increasing encryptedAppBuffer to " + newsize);
}
WsByteBuffer temp = SSLUtils.allocateByteBuffer(
newsize, this.encryptedAppBuffer.isDirect());
this.encryptedAppBuffer.flip();
SSLUtils.copyBuffer(this.encryptedAppBuffer, temp, this.encryptedAppBuffer.remaining());
this.encryptedAppBuffer.release();
this.encryptedAppBuffer = temp;
}
} } | public class class_name {
protected void increaseEncryptedBuffer() throws IOException {
final int packetSize = getConnLink().getPacketBufferSize();
if (null == this.encryptedAppBuffer) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Allocating encryptedAppBuffer, size=" + packetSize); // depends on control dependency: [if], data = [none]
}
this.encryptedAppBuffer = SSLUtils.allocateByteBuffer(
packetSize, getConfig().getEncryptBuffersDirect());
} else {
// The existing buffer isn't big enough, add another packet size to it
final int cap = this.encryptedAppBuffer.capacity();
final int newsize = cap + packetSize;
if (0 > newsize) {
// wrapped over max-int
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Unable to increase encrypted buffer beyond " + cap); // depends on control dependency: [if], data = [none]
}
throw new IOException("Unable to increase buffer beyond " + cap);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Increasing encryptedAppBuffer to " + newsize); // depends on control dependency: [if], data = [none]
}
WsByteBuffer temp = SSLUtils.allocateByteBuffer(
newsize, this.encryptedAppBuffer.isDirect());
this.encryptedAppBuffer.flip();
SSLUtils.copyBuffer(this.encryptedAppBuffer, temp, this.encryptedAppBuffer.remaining());
this.encryptedAppBuffer.release();
this.encryptedAppBuffer = temp;
}
} } |
public class class_name {
@Override
public void getFlatComparator(List<TypeComparator> flatComparators) {
for (NullAwareComparator<Object> c : comparators) {
Collections.addAll(flatComparators, c.getFlatComparators());
}
} } | public class class_name {
@Override
public void getFlatComparator(List<TypeComparator> flatComparators) {
for (NullAwareComparator<Object> c : comparators) {
Collections.addAll(flatComparators, c.getFlatComparators()); // depends on control dependency: [for], data = [c]
}
} } |
public class class_name {
public double getWorstCaseSubstituteAll() {
double worstCase = -1;
// make a copy of editDistanceGraph
SimpleDirectedWeightedGraph worstCaseGraph = new SimpleDirectedWeightedGraph();
Set vertices = editDistanceGraph.vertexSet();
Set edges = editDistanceGraph.edgeSet();
worstCaseGraph.addAllVertices(vertices);
worstCaseGraph.addAllEdges(edges);
edges = worstCaseGraph.edgeSet();
for (Object o : edges) {
Edge edge = (Edge) o;
GraphVertexTuple vertex1 = (GraphVertexTuple) edge.getSource();
GraphVertexTuple vertex2 = (GraphVertexTuple) edge.getTarget();
// check if this edge is a diagonal
if (vertex2.getLeft() == vertex1.getLeft() + 1
&& vertex2.getRight() == vertex1.getRight() + 1) {
edge.setWeight(weightSubstitute);
}
}
DijkstraShortestPath shortestPath = new DijkstraShortestPath(worstCaseGraph, firstVertex, lastVertex, pathLengthLimit);
worstCase = shortestPath.getPathLength();
return worstCase;
} } | public class class_name {
public double getWorstCaseSubstituteAll() {
double worstCase = -1;
// make a copy of editDistanceGraph
SimpleDirectedWeightedGraph worstCaseGraph = new SimpleDirectedWeightedGraph();
Set vertices = editDistanceGraph.vertexSet();
Set edges = editDistanceGraph.edgeSet();
worstCaseGraph.addAllVertices(vertices);
worstCaseGraph.addAllEdges(edges);
edges = worstCaseGraph.edgeSet();
for (Object o : edges) {
Edge edge = (Edge) o;
GraphVertexTuple vertex1 = (GraphVertexTuple) edge.getSource();
GraphVertexTuple vertex2 = (GraphVertexTuple) edge.getTarget();
// check if this edge is a diagonal
if (vertex2.getLeft() == vertex1.getLeft() + 1
&& vertex2.getRight() == vertex1.getRight() + 1) {
edge.setWeight(weightSubstitute);
// depends on control dependency: [if], data = [none]
}
}
DijkstraShortestPath shortestPath = new DijkstraShortestPath(worstCaseGraph, firstVertex, lastVertex, pathLengthLimit);
worstCase = shortestPath.getPathLength();
return worstCase;
} } |
public class class_name {
@Override
protected void setMoments() {
super.setMoments();
for(Integer degree: momentDegrees) {
momentObservation.get(degree).addValue(moments.get(degree));
}
} } | public class class_name {
@Override
protected void setMoments() {
super.setMoments();
for(Integer degree: momentDegrees) {
momentObservation.get(degree).addValue(moments.get(degree));
// depends on control dependency: [for], data = [degree]
}
} } |
public class class_name {
private static final int find(final DirectHllArray host, final int slotNo) {
final int lgAuxArrInts = extractLgArr(host.mem);
assert lgAuxArrInts < host.lgConfigK : lgAuxArrInts;
final int auxInts = 1 << lgAuxArrInts;
final int auxArrMask = auxInts - 1;
final int configKmask = (1 << host.lgConfigK) - 1;
int probe = slotNo & auxArrMask;
final int loopIndex = probe;
do {
final int arrVal = host.mem.getInt(host.auxStart + (probe << 2));
if (arrVal == EMPTY) {
return ~probe; //empty
}
else if (slotNo == (arrVal & configKmask)) { //found given slotNo
return probe; //return aux array index
}
final int stride = (slotNo >>> lgAuxArrInts) | 1;
probe = (probe + stride) & auxArrMask;
} while (probe != loopIndex);
throw new SketchesArgumentException("Key not found and no empty slots!");
} } | public class class_name {
private static final int find(final DirectHllArray host, final int slotNo) {
final int lgAuxArrInts = extractLgArr(host.mem);
assert lgAuxArrInts < host.lgConfigK : lgAuxArrInts;
final int auxInts = 1 << lgAuxArrInts;
final int auxArrMask = auxInts - 1;
final int configKmask = (1 << host.lgConfigK) - 1;
int probe = slotNo & auxArrMask;
final int loopIndex = probe;
do {
final int arrVal = host.mem.getInt(host.auxStart + (probe << 2));
if (arrVal == EMPTY) {
return ~probe; //empty // depends on control dependency: [if], data = [none]
}
else if (slotNo == (arrVal & configKmask)) { //found given slotNo
return probe; //return aux array index // depends on control dependency: [if], data = [none]
}
final int stride = (slotNo >>> lgAuxArrInts) | 1;
probe = (probe + stride) & auxArrMask;
} while (probe != loopIndex);
throw new SketchesArgumentException("Key not found and no empty slots!");
} } |
public class class_name {
private void appendEvaluated(StringBuffer buffer, String s) {
boolean escape = false;
boolean dollar = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' && !escape) {
escape = true;
} else if (c == '$' && !escape) {
dollar = true;
} else if (c >= '0' && c <= '9' && dollar) {
buffer.append(group(c - '0'));
dollar = false;
} else {
buffer.append(c);
dollar = false;
escape = false;
}
}
if (escape) {
throw new ArrayIndexOutOfBoundsException(s.length());
}
} } | public class class_name {
private void appendEvaluated(StringBuffer buffer, String s) {
boolean escape = false;
boolean dollar = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' && !escape) {
escape = true; // depends on control dependency: [if], data = [none]
} else if (c == '$' && !escape) {
dollar = true; // depends on control dependency: [if], data = [none]
} else if (c >= '0' && c <= '9' && dollar) {
buffer.append(group(c - '0')); // depends on control dependency: [if], data = [(c]
dollar = false; // depends on control dependency: [if], data = [none]
} else {
buffer.append(c); // depends on control dependency: [if], data = [(c]
dollar = false; // depends on control dependency: [if], data = [none]
escape = false; // depends on control dependency: [if], data = [none]
}
}
if (escape) {
throw new ArrayIndexOutOfBoundsException(s.length());
}
} } |
public class class_name {
protected WorkflowStatusResult executeWorkflowItemsForNodeSet(
final StepExecutionContext executionContext,
final Map<Integer, StepExecutionResult> failedMap,
final List<StepExecutionResult> resultList,
final List<StepExecutionItem> iWorkflowCmdItems,
final boolean keepgoing,
final int beginStepIndex,
WFSharedContext sharedContext
)
{
boolean workflowsuccess = true;
String statusString = null;
ControlBehavior controlBehavior = null;
final WorkflowExecutionListener wlistener = getWorkflowListener(executionContext);
int c = beginStepIndex;
WFSharedContext currentData = new WFSharedContext(sharedContext);
StepExecutionContext newContext =
ExecutionContextImpl.builder(executionContext)
.sharedDataContext(currentData)
.build();
for (final StepExecutionItem cmd : iWorkflowCmdItems) {
StepResultCapture stepResultCapture = executeWorkflowStep(
newContext,
failedMap,
resultList,
keepgoing,
wlistener,
c,
cmd
);
statusString = stepResultCapture.getStatusString();
controlBehavior = stepResultCapture.getControlBehavior();
currentData.merge(stepResultCapture.getResultData());
if (!stepResultCapture.isSuccess()) {
workflowsuccess = false;
}
if (stepResultCapture.getControlBehavior() == ControlBehavior.Halt ||
!stepResultCapture.isSuccess() && !keepgoing) {
break;
}
c++;
}
return workflowResult(
workflowsuccess,
statusString,
null != controlBehavior ? controlBehavior : ControlBehavior.Continue,
currentData
);
} } | public class class_name {
protected WorkflowStatusResult executeWorkflowItemsForNodeSet(
final StepExecutionContext executionContext,
final Map<Integer, StepExecutionResult> failedMap,
final List<StepExecutionResult> resultList,
final List<StepExecutionItem> iWorkflowCmdItems,
final boolean keepgoing,
final int beginStepIndex,
WFSharedContext sharedContext
)
{
boolean workflowsuccess = true;
String statusString = null;
ControlBehavior controlBehavior = null;
final WorkflowExecutionListener wlistener = getWorkflowListener(executionContext);
int c = beginStepIndex;
WFSharedContext currentData = new WFSharedContext(sharedContext);
StepExecutionContext newContext =
ExecutionContextImpl.builder(executionContext)
.sharedDataContext(currentData)
.build();
for (final StepExecutionItem cmd : iWorkflowCmdItems) {
StepResultCapture stepResultCapture = executeWorkflowStep(
newContext,
failedMap,
resultList,
keepgoing,
wlistener,
c,
cmd
);
statusString = stepResultCapture.getStatusString(); // depends on control dependency: [for], data = [none]
controlBehavior = stepResultCapture.getControlBehavior(); // depends on control dependency: [for], data = [none]
currentData.merge(stepResultCapture.getResultData()); // depends on control dependency: [for], data = [none]
if (!stepResultCapture.isSuccess()) {
workflowsuccess = false; // depends on control dependency: [if], data = [none]
}
if (stepResultCapture.getControlBehavior() == ControlBehavior.Halt ||
!stepResultCapture.isSuccess() && !keepgoing) {
break;
}
c++; // depends on control dependency: [for], data = [none]
}
return workflowResult(
workflowsuccess,
statusString,
null != controlBehavior ? controlBehavior : ControlBehavior.Continue,
currentData
);
} } |
public class class_name {
@Override
public void visit(NormalAnnotationExpr anno, ControllerModel controller) {
//org.wisdom.api.annotations.Path (There is only one pair ->value="")
if(anno.getName().getName().equals(ANNOTATION_PATH)){
java.lang.String path = asString(anno.getPairs().get(0).getValue());
controller.setBasePath(path);
}
} } | public class class_name {
@Override
public void visit(NormalAnnotationExpr anno, ControllerModel controller) {
//org.wisdom.api.annotations.Path (There is only one pair ->value="")
if(anno.getName().getName().equals(ANNOTATION_PATH)){
java.lang.String path = asString(anno.getPairs().get(0).getValue());
controller.setBasePath(path); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private void processClassTraceOptionsAnnotation(ClassTraceInfo info) {
// Get class annotation
AnnotationNode traceOptionsAnnotation = getAnnotation(TRACE_OPTIONS_TYPE.getDescriptor(), info.classNode.visibleAnnotations);
if (traceOptionsAnnotation != null) {
TraceOptionsAnnotationVisitor optionsVisitor = new TraceOptionsAnnotationVisitor();
traceOptionsAnnotation.accept(optionsVisitor);
TraceOptionsData traceOptions = optionsVisitor.getTraceOptionsData();
// Merge with package annotation's defaults
TraceOptionsData packageData = info.packageInfo != null ? info.packageInfo.getTraceOptionsData() : null;
if (packageData != null) {
// Remove the current annotation if present
if (traceOptionsAnnotation != null) {
info.classNode.visibleAnnotations.remove(traceOptionsAnnotation);
}
// If the class trace options differ from the package trace
// options, merge them and add a class annotation.
if (!traceOptions.equals(packageData)) {
if (traceOptions.getMessageBundle() == null && packageData.getMessageBundle() != null) {
traceOptions.setMessageBundle(packageData.getMessageBundle());
}
if (traceOptions.getTraceGroups().isEmpty() && !packageData.getTraceGroups().isEmpty()) {
for (String group : packageData.getTraceGroups()) {
traceOptions.addTraceGroup(group);
}
}
traceOptionsAnnotation = (AnnotationNode) info.classNode.visitAnnotation(TRACE_OPTIONS_TYPE.getDescriptor(), true);
AnnotationVisitor groupsVisitor = traceOptionsAnnotation.visitArray("traceGroups");
for (String group : traceOptions.getTraceGroups()) {
groupsVisitor.visit(null, group);
}
groupsVisitor.visitEnd();
traceOptionsAnnotation.visit("traceGroup", "");
traceOptionsAnnotation.visit("messageBundle", traceOptions.getMessageBundle() == null ? "" : traceOptions.getMessageBundle());
traceOptionsAnnotation.visit("traceExceptionThrow", Boolean.valueOf(traceOptions.isTraceExceptionThrow()));
traceOptionsAnnotation.visit("traceExceptionHandling", Boolean.valueOf(traceOptions.isTraceExceptionHandling()));
traceOptionsAnnotation.visitEnd();
}
}
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private void processClassTraceOptionsAnnotation(ClassTraceInfo info) {
// Get class annotation
AnnotationNode traceOptionsAnnotation = getAnnotation(TRACE_OPTIONS_TYPE.getDescriptor(), info.classNode.visibleAnnotations);
if (traceOptionsAnnotation != null) {
TraceOptionsAnnotationVisitor optionsVisitor = new TraceOptionsAnnotationVisitor();
traceOptionsAnnotation.accept(optionsVisitor); // depends on control dependency: [if], data = [none]
TraceOptionsData traceOptions = optionsVisitor.getTraceOptionsData();
// Merge with package annotation's defaults
TraceOptionsData packageData = info.packageInfo != null ? info.packageInfo.getTraceOptionsData() : null;
if (packageData != null) {
// Remove the current annotation if present
if (traceOptionsAnnotation != null) {
info.classNode.visibleAnnotations.remove(traceOptionsAnnotation); // depends on control dependency: [if], data = [(traceOptionsAnnotation]
}
// If the class trace options differ from the package trace
// options, merge them and add a class annotation.
if (!traceOptions.equals(packageData)) {
if (traceOptions.getMessageBundle() == null && packageData.getMessageBundle() != null) {
traceOptions.setMessageBundle(packageData.getMessageBundle()); // depends on control dependency: [if], data = [none]
}
if (traceOptions.getTraceGroups().isEmpty() && !packageData.getTraceGroups().isEmpty()) {
for (String group : packageData.getTraceGroups()) {
traceOptions.addTraceGroup(group); // depends on control dependency: [for], data = [group]
}
}
traceOptionsAnnotation = (AnnotationNode) info.classNode.visitAnnotation(TRACE_OPTIONS_TYPE.getDescriptor(), true); // depends on control dependency: [if], data = [none]
AnnotationVisitor groupsVisitor = traceOptionsAnnotation.visitArray("traceGroups");
for (String group : traceOptions.getTraceGroups()) {
groupsVisitor.visit(null, group); // depends on control dependency: [for], data = [group]
}
groupsVisitor.visitEnd(); // depends on control dependency: [if], data = [none]
traceOptionsAnnotation.visit("traceGroup", ""); // depends on control dependency: [if], data = [none]
traceOptionsAnnotation.visit("messageBundle", traceOptions.getMessageBundle() == null ? "" : traceOptions.getMessageBundle()); // depends on control dependency: [if], data = [none]
traceOptionsAnnotation.visit("traceExceptionThrow", Boolean.valueOf(traceOptions.isTraceExceptionThrow())); // depends on control dependency: [if], data = [none]
traceOptionsAnnotation.visit("traceExceptionHandling", Boolean.valueOf(traceOptions.isTraceExceptionHandling())); // depends on control dependency: [if], data = [none]
traceOptionsAnnotation.visitEnd(); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public Object execute(final Map<Object, Object> iArgs) {
if (indexName == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseDocument database = getDatabase();
final OIndex<?> idx;
List<OCollate> collatesList = null;
if (collates != null) {
collatesList = new ArrayList<OCollate>();
for (String collate : collates) {
if (collate != null) {
final OCollate col = OSQLEngine.getCollate(collate);
collatesList.add(col);
} else
collatesList.add(null);
}
}
if (fields == null || fields.length == 0) {
OIndexFactory factory = OIndexes.getFactory(indexType.toString(), null);
if (keyTypes != null)
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes, collatesList), null, null,
metadataDoc, engine);
else if (serializerKeyId != 0) {
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId), null, null, metadataDoc,
engine);
} else {
throw new ODatabaseException("Impossible to create an index without specify the key type or the associated property");
}
} else {
if ((keyTypes == null || keyTypes.length == 0) && collates == null) {
idx = oClass.createIndex(indexName, indexType.toString(), null, metadataDoc, engine, fields);
} else {
final List<OType> fieldTypeList;
if (keyTypes == null) {
for (final String fieldName : fields) {
if (!fieldName.equals("@rid") && !oClass.existsProperty(fieldName))
throw new OIndexException(
"Index with name : '" + indexName + "' cannot be created on class : '" + oClass.getName() + "' because field: '"
+ fieldName + "' is absent in class definition.");
}
fieldTypeList = ((OClassImpl) oClass).extractFieldTypes(fields);
} else
fieldTypeList = Arrays.asList(keyTypes);
final OIndexDefinition idxDef = OIndexDefinitionFactory
.createIndexDefinition(oClass, Arrays.asList(fields), fieldTypeList, collatesList, indexType.toString(), null);
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.name(), idxDef, oClass.getPolymorphicClusterIds(), null, metadataDoc, engine);
}
}
if (idx != null)
return idx.getSize();
return null;
} } | public class class_name {
@SuppressWarnings("rawtypes")
public Object execute(final Map<Object, Object> iArgs) {
if (indexName == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseDocument database = getDatabase();
final OIndex<?> idx;
List<OCollate> collatesList = null;
if (collates != null) {
collatesList = new ArrayList<OCollate>(); // depends on control dependency: [if], data = [none]
for (String collate : collates) {
if (collate != null) {
final OCollate col = OSQLEngine.getCollate(collate);
collatesList.add(col); // depends on control dependency: [if], data = [none]
} else
collatesList.add(null);
}
}
if (fields == null || fields.length == 0) {
OIndexFactory factory = OIndexes.getFactory(indexType.toString(), null);
if (keyTypes != null)
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes, collatesList), null, null,
metadataDoc, engine);
else if (serializerKeyId != 0) {
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId), null, null, metadataDoc,
engine); // depends on control dependency: [if], data = [none]
} else {
throw new ODatabaseException("Impossible to create an index without specify the key type or the associated property");
}
} else {
if ((keyTypes == null || keyTypes.length == 0) && collates == null) {
idx = oClass.createIndex(indexName, indexType.toString(), null, metadataDoc, engine, fields); // depends on control dependency: [if], data = [none]
} else {
final List<OType> fieldTypeList;
if (keyTypes == null) {
for (final String fieldName : fields) {
if (!fieldName.equals("@rid") && !oClass.existsProperty(fieldName))
throw new OIndexException(
"Index with name : '" + indexName + "' cannot be created on class : '" + oClass.getName() + "' because field: '"
+ fieldName + "' is absent in class definition.");
}
fieldTypeList = ((OClassImpl) oClass).extractFieldTypes(fields); // depends on control dependency: [if], data = [none]
} else
fieldTypeList = Arrays.asList(keyTypes);
final OIndexDefinition idxDef = OIndexDefinitionFactory
.createIndexDefinition(oClass, Arrays.asList(fields), fieldTypeList, collatesList, indexType.toString(), null);
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.name(), idxDef, oClass.getPolymorphicClusterIds(), null, metadataDoc, engine); // depends on control dependency: [if], data = [none]
}
}
if (idx != null)
return idx.getSize();
return null;
} } |
public class class_name {
protected String getTypeName(JvmType type) {
if (type != null) {
if (type instanceof JvmDeclaredType) {
final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
return owner.toLightweightTypeReference(type).getHumanReadableName();
}
return type.getSimpleName();
}
return Messages.SARLHoverSignatureProvider_1;
} } | public class class_name {
protected String getTypeName(JvmType type) {
if (type != null) {
if (type instanceof JvmDeclaredType) {
final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
return owner.toLightweightTypeReference(type).getHumanReadableName(); // depends on control dependency: [if], data = [none]
}
return type.getSimpleName(); // depends on control dependency: [if], data = [none]
}
return Messages.SARLHoverSignatureProvider_1;
} } |
public class class_name {
public Form updateFormDefinition(Form formDefinitionParam)
{
if(formDefinitionParam != null && this.serviceTicket != null)
{
formDefinitionParam.setServiceTicket(this.serviceTicket);
}
return new Form(this.postJson(
formDefinitionParam,
WS.Path.FormDefinition.Version1.formDefinitionUpdate()));
} } | public class class_name {
public Form updateFormDefinition(Form formDefinitionParam)
{
if(formDefinitionParam != null && this.serviceTicket != null)
{
formDefinitionParam.setServiceTicket(this.serviceTicket); // depends on control dependency: [if], data = [none]
}
return new Form(this.postJson(
formDefinitionParam,
WS.Path.FormDefinition.Version1.formDefinitionUpdate()));
} } |
public class class_name {
public final void setConfigFile(@Nonnull final String pConfigFile)
{
mdlConfigCallable = new CallableNoEx<MdlConfig>()
{
@Override
@Nonnull
public MdlConfig call()
{
MdlConfig result = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(Util.canonize(new File(pConfigFile)));
result = activateConfigFile(fis, pConfigFile);
}
catch (IllegalArgumentException e) {
result = activateConfigFile(null, null);
throw e;
}
catch (FileNotFoundException e) {
result = activateConfigFile(null, null);
if (!failQuietly) {
throw new IllegalArgumentException(
"Config file not found for " + ModuleDirectoryLayoutCheck.class.getSimpleName() + ": "
+ pConfigFile, e);
}
}
finally {
Util.closeQuietly(fis);
}
return result;
}
};
} } | public class class_name {
public final void setConfigFile(@Nonnull final String pConfigFile)
{
mdlConfigCallable = new CallableNoEx<MdlConfig>()
{
@Override
@Nonnull
public MdlConfig call()
{
MdlConfig result = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(Util.canonize(new File(pConfigFile))); // depends on control dependency: [try], data = [none]
result = activateConfigFile(fis, pConfigFile); // depends on control dependency: [try], data = [none]
}
catch (IllegalArgumentException e) {
result = activateConfigFile(null, null);
throw e;
} // depends on control dependency: [catch], data = [none]
catch (FileNotFoundException e) {
result = activateConfigFile(null, null);
if (!failQuietly) {
throw new IllegalArgumentException(
"Config file not found for " + ModuleDirectoryLayoutCheck.class.getSimpleName() + ": "
+ pConfigFile, e);
}
} // depends on control dependency: [catch], data = [none]
finally {
Util.closeQuietly(fis);
}
return result;
}
};
} } |
public class class_name {
public void setActiveProfile(long identifier, boolean fireOnProfileChanged) {
if (mAccountHeaderBuilder.mProfiles != null) {
for (IProfile profile : mAccountHeaderBuilder.mProfiles) {
if (profile != null) {
if (profile.getIdentifier() == identifier) {
setActiveProfile(profile, fireOnProfileChanged);
return;
}
}
}
}
} } | public class class_name {
public void setActiveProfile(long identifier, boolean fireOnProfileChanged) {
if (mAccountHeaderBuilder.mProfiles != null) {
for (IProfile profile : mAccountHeaderBuilder.mProfiles) {
if (profile != null) {
if (profile.getIdentifier() == identifier) {
setActiveProfile(profile, fireOnProfileChanged); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public static ConvexPolygon updateConvexPolygon(ConvexPolygon polygon, DenseMatrix64F points)
{
assert points.numCols == 2;
int rows = points.numRows;
double[] d = points.data;
for (int row=0;row<rows;row++)
{
polygon.addPoint(d[2*row], d[2*row+1]);
}
return polygon;
} } | public class class_name {
public static ConvexPolygon updateConvexPolygon(ConvexPolygon polygon, DenseMatrix64F points)
{
assert points.numCols == 2;
int rows = points.numRows;
double[] d = points.data;
for (int row=0;row<rows;row++)
{
polygon.addPoint(d[2*row], d[2*row+1]);
// depends on control dependency: [for], data = [row]
}
return polygon;
} } |
public class class_name {
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// write ra entity name
out.writeUTF(raEntity.getName());
// write activity handle
if (activityHandle.getClass() == ActivityHandleReference.class) {
// a reference
out.writeBoolean(true);
final ActivityHandleReference reference = (ActivityHandleReference) activityHandle;
out.writeObject(reference.getAddress());
out.writeUTF(reference.getId());
}
else {
out.writeBoolean(false);
final Marshaler marshaler = raEntity.getMarshaler();
if (marshaler != null) {
marshaler.marshalHandle(activityHandle, out);
}
else {
throw new IOException("marshaller from RA is null");
}
}
} } | public class class_name {
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// write ra entity name
out.writeUTF(raEntity.getName());
// write activity handle
if (activityHandle.getClass() == ActivityHandleReference.class) {
// a reference
out.writeBoolean(true);
final ActivityHandleReference reference = (ActivityHandleReference) activityHandle;
out.writeObject(reference.getAddress());
out.writeUTF(reference.getId());
}
else {
out.writeBoolean(false);
final Marshaler marshaler = raEntity.getMarshaler();
if (marshaler != null) {
marshaler.marshalHandle(activityHandle, out); // depends on control dependency: [if], data = [none]
}
else {
throw new IOException("marshaller from RA is null");
}
}
} } |
public class class_name {
public void setWeekDay(String dayString) {
final WeekDay day = WeekDay.valueOf(dayString);
if (m_model.getWeekDay() != day) {
removeExceptionsOnChange(new Command() {
public void execute() {
m_model.setWeekDay(day);
onValueChange();
}
});
}
} } | public class class_name {
public void setWeekDay(String dayString) {
final WeekDay day = WeekDay.valueOf(dayString);
if (m_model.getWeekDay() != day) {
removeExceptionsOnChange(new Command() {
public void execute() {
m_model.setWeekDay(day);
onValueChange();
}
}); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static int intersectSphereTriangle(
double sX, double sY, double sZ, double sR,
double v0X, double v0Y, double v0Z,
double v1X, double v1Y, double v1Z,
double v2X, double v2Y, double v2Z,
Vector3d result) {
int closest = findClosestPointOnTriangle(v0X, v0Y, v0Z, v1X, v1Y, v1Z, v2X, v2Y, v2Z, sX, sY, sZ, result);
double vX = result.x - sX, vY = result.y - sY, vZ = result.z - sZ;
double dot = vX * vX + vY * vY + vZ * vZ;
if (dot <= sR * sR) {
return closest;
}
return 0;
} } | public class class_name {
public static int intersectSphereTriangle(
double sX, double sY, double sZ, double sR,
double v0X, double v0Y, double v0Z,
double v1X, double v1Y, double v1Z,
double v2X, double v2Y, double v2Z,
Vector3d result) {
int closest = findClosestPointOnTriangle(v0X, v0Y, v0Z, v1X, v1Y, v1Z, v2X, v2Y, v2Z, sX, sY, sZ, result);
double vX = result.x - sX, vY = result.y - sY, vZ = result.z - sZ;
double dot = vX * vX + vY * vY + vZ * vZ;
if (dot <= sR * sR) {
return closest; // depends on control dependency: [if], data = [none]
}
return 0;
} } |
public class class_name {
protected void onRPCError(int asyncHandle, int asyncError, String text) {
IAsyncRPCEvent callback = getCallback(asyncHandle);
if (callback != null) {
callback.onRPCError(asyncHandle, asyncError, text);
}
} } | public class class_name {
protected void onRPCError(int asyncHandle, int asyncError, String text) {
IAsyncRPCEvent callback = getCallback(asyncHandle);
if (callback != null) {
callback.onRPCError(asyncHandle, asyncError, text); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected <T extends OperationResponse> void completeOperation(OperationResult result, OperationResponse.Builder<?, T> builder, Throwable error, CompletableFuture<T> future) {
if (result != null) {
builder.withIndex(result.index());
builder.withEventIndex(result.eventIndex());
if (result.failed()) {
error = result.error();
}
}
if (error == null) {
if (result == null) {
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build());
} else {
future.complete(builder.withStatus(RaftResponse.Status.OK)
.withResult(result.result())
.build());
}
} else if (error instanceof CompletionException && error.getCause() instanceof RaftException) {
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error.getCause()).getType(), error.getMessage())
.build());
} else if (error instanceof RaftException) {
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error).getType(), error.getMessage())
.build());
} else if (error instanceof PrimitiveException.ServiceException) {
log.warn("An application error occurred: {}", error.getCause());
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.APPLICATION_ERROR)
.build());
} else {
log.warn("An unexpected error occurred: {}", error);
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, error.getMessage())
.build());
}
} } | public class class_name {
protected <T extends OperationResponse> void completeOperation(OperationResult result, OperationResponse.Builder<?, T> builder, Throwable error, CompletableFuture<T> future) {
if (result != null) {
builder.withIndex(result.index()); // depends on control dependency: [if], data = [(result]
builder.withEventIndex(result.eventIndex()); // depends on control dependency: [if], data = [(result]
if (result.failed()) {
error = result.error(); // depends on control dependency: [if], data = [none]
}
}
if (error == null) {
if (result == null) {
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()); // depends on control dependency: [if], data = [none]
} else {
future.complete(builder.withStatus(RaftResponse.Status.OK)
.withResult(result.result())
.build()); // depends on control dependency: [if], data = [none]
}
} else if (error instanceof CompletionException && error.getCause() instanceof RaftException) {
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error.getCause()).getType(), error.getMessage())
.build()); // depends on control dependency: [if], data = [none]
} else if (error instanceof RaftException) {
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error).getType(), error.getMessage())
.build()); // depends on control dependency: [if], data = [none]
} else if (error instanceof PrimitiveException.ServiceException) {
log.warn("An application error occurred: {}", error.getCause()); // depends on control dependency: [if], data = [none]
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.APPLICATION_ERROR)
.build()); // depends on control dependency: [if], data = [none]
} else {
log.warn("An unexpected error occurred: {}", error); // depends on control dependency: [if], data = [none]
future.complete(builder.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, error.getMessage())
.build()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean containsEliminated(final CLClause c) {
for (int i = 0; i < c.lits().size(); i++) { if (var(c.lits().get(i)).state() == CLVar.State.ELIMINATED) { return true; } }
return false;
} } | public class class_name {
private boolean containsEliminated(final CLClause c) {
for (int i = 0; i < c.lits().size(); i++) { if (var(c.lits().get(i)).state() == CLVar.State.ELIMINATED) { return true; } } // depends on control dependency: [if], data = [none]
return false;
} } |
public class class_name {
public static String encrypt(CharSequence data, CharSequence cipherKey) {
final int dataLen = data.length();
final int cipherKeyLen = cipherKey.length();
final char[] cipherArray = new char[dataLen];
for (int i = 0; i < dataLen / cipherKeyLen + 1; i++) {
for (int t = 0; t < cipherKeyLen; t++) {
if (t + i * cipherKeyLen < dataLen) {
final char dataChar = data.charAt(t + i * cipherKeyLen);
final char cipherKeyChar = cipherKey.charAt(t);
cipherArray[t + i * cipherKeyLen] = (char) ((dataChar + cipherKeyChar - 64) % 95 + 32);
}
}
}
return String.valueOf(cipherArray);
} } | public class class_name {
public static String encrypt(CharSequence data, CharSequence cipherKey) {
final int dataLen = data.length();
final int cipherKeyLen = cipherKey.length();
final char[] cipherArray = new char[dataLen];
for (int i = 0; i < dataLen / cipherKeyLen + 1; i++) {
for (int t = 0; t < cipherKeyLen; t++) {
if (t + i * cipherKeyLen < dataLen) {
final char dataChar = data.charAt(t + i * cipherKeyLen);
final char cipherKeyChar = cipherKey.charAt(t);
cipherArray[t + i * cipherKeyLen] = (char) ((dataChar + cipherKeyChar - 64) % 95 + 32);
// depends on control dependency: [if], data = [none]
}
}
}
return String.valueOf(cipherArray);
} } |
public class class_name {
protected List<FacesConfig> getPostOrderedList(final List<FacesConfig> appConfigResources) throws FacesException
{
//0. Clean up: remove all not found resource references from the ordering
//descriptions.
List<String> availableReferences = new ArrayList<String>();
for (FacesConfig resource : appConfigResources)
{
String name = resource.getName();
if (name != null && !"".equals(name))
{
availableReferences.add(name);
}
}
for (FacesConfig resource : appConfigResources)
{
Ordering ordering = resource.getOrdering();
if (ordering != null)
{
for (Iterator<OrderSlot> it = resource.getOrdering().getBeforeList().iterator();it.hasNext();)
{
OrderSlot slot = it.next();
if (slot instanceof FacesConfigNameSlot)
{
String name = ((FacesConfigNameSlot) slot).getName();
if (!availableReferences.contains(name))
{
it.remove();
}
}
}
for (Iterator<OrderSlot> it = resource.getOrdering().getAfterList().iterator();it.hasNext();)
{
OrderSlot slot = it.next();
if (slot instanceof FacesConfigNameSlot)
{
String name = ((FacesConfigNameSlot) slot).getName();
if (!availableReferences.contains(name))
{
it.remove();
}
}
}
}
}
List<FacesConfig> appFilteredConfigResources = null;
//1. Pre filtering: Sort nodes according to its weight. The weight is the number of named
//nodes containing in both before and after lists. The sort is done from the more complex
//to the most simple
if (appConfigResources instanceof ArrayList)
{
appFilteredConfigResources = (List<FacesConfig>)
((ArrayList<FacesConfig>)appConfigResources).clone();
}
else
{
appFilteredConfigResources = new ArrayList<FacesConfig>();
appFilteredConfigResources.addAll(appConfigResources);
}
Collections.sort(appFilteredConfigResources,
new Comparator<FacesConfig>()
{
public int compare(FacesConfig o1, FacesConfig o2)
{
int o1Weight = 0;
int o2Weight = 0;
if (o1.getOrdering() != null)
{
for (OrderSlot slot : o1.getOrdering()
.getBeforeList())
{
if (slot instanceof FacesConfigNameSlot)
{
o1Weight++;
}
}
for (OrderSlot slot : o1.getOrdering()
.getAfterList())
{
if (slot instanceof FacesConfigNameSlot)
{
o1Weight++;
}
}
}
if (o2.getOrdering() != null)
{
for (OrderSlot slot : o2.getOrdering()
.getBeforeList())
{
if (slot instanceof FacesConfigNameSlot)
{
o2Weight++;
}
}
for (OrderSlot slot : o2.getOrdering()
.getAfterList())
{
if (slot instanceof FacesConfigNameSlot)
{
o2Weight++;
}
}
}
return o2Weight - o1Weight;
}
});
List<FacesConfig> postOrderedList = new LinkedList<FacesConfig>();
List<FacesConfig> othersList = new ArrayList<FacesConfig>();
List<String> nameBeforeStack = new ArrayList<String>();
List<String> nameAfterStack = new ArrayList<String>();
boolean[] visitedSlots = new boolean[appFilteredConfigResources.size()];
//2. Scan and resolve conflicts
for (int i = 0; i < appFilteredConfigResources.size(); i++)
{
if (!visitedSlots[i])
{
resolveConflicts(appFilteredConfigResources, i, visitedSlots,
nameBeforeStack, nameAfterStack, postOrderedList, othersList, false);
}
}
//Add othersList to postOrderedList so <before><others/></before> and <after><others/></after>
//ordering conditions are handled at last if there are not referenced by anyone
postOrderedList.addAll(othersList);
return postOrderedList;
} } | public class class_name {
protected List<FacesConfig> getPostOrderedList(final List<FacesConfig> appConfigResources) throws FacesException
{
//0. Clean up: remove all not found resource references from the ordering
//descriptions.
List<String> availableReferences = new ArrayList<String>();
for (FacesConfig resource : appConfigResources)
{
String name = resource.getName();
if (name != null && !"".equals(name))
{
availableReferences.add(name); // depends on control dependency: [if], data = [(name]
}
}
for (FacesConfig resource : appConfigResources)
{
Ordering ordering = resource.getOrdering();
if (ordering != null)
{
for (Iterator<OrderSlot> it = resource.getOrdering().getBeforeList().iterator();it.hasNext();)
{
OrderSlot slot = it.next();
if (slot instanceof FacesConfigNameSlot)
{
String name = ((FacesConfigNameSlot) slot).getName();
if (!availableReferences.contains(name))
{
it.remove(); // depends on control dependency: [if], data = [none]
}
}
}
for (Iterator<OrderSlot> it = resource.getOrdering().getAfterList().iterator();it.hasNext();)
{
OrderSlot slot = it.next();
if (slot instanceof FacesConfigNameSlot)
{
String name = ((FacesConfigNameSlot) slot).getName();
if (!availableReferences.contains(name))
{
it.remove(); // depends on control dependency: [if], data = [none]
}
}
}
}
}
List<FacesConfig> appFilteredConfigResources = null;
//1. Pre filtering: Sort nodes according to its weight. The weight is the number of named
//nodes containing in both before and after lists. The sort is done from the more complex
//to the most simple
if (appConfigResources instanceof ArrayList)
{
appFilteredConfigResources = (List<FacesConfig>)
((ArrayList<FacesConfig>)appConfigResources).clone();
}
else
{
appFilteredConfigResources = new ArrayList<FacesConfig>();
appFilteredConfigResources.addAll(appConfigResources);
}
Collections.sort(appFilteredConfigResources,
new Comparator<FacesConfig>()
{
public int compare(FacesConfig o1, FacesConfig o2)
{
int o1Weight = 0;
int o2Weight = 0;
if (o1.getOrdering() != null)
{
for (OrderSlot slot : o1.getOrdering()
.getBeforeList())
{
if (slot instanceof FacesConfigNameSlot)
{
o1Weight++; // depends on control dependency: [if], data = [none]
}
}
for (OrderSlot slot : o1.getOrdering()
.getAfterList())
{
if (slot instanceof FacesConfigNameSlot)
{
o1Weight++; // depends on control dependency: [if], data = [none]
}
}
}
if (o2.getOrdering() != null)
{
for (OrderSlot slot : o2.getOrdering()
.getBeforeList())
{
if (slot instanceof FacesConfigNameSlot)
{
o2Weight++; // depends on control dependency: [if], data = [none]
}
}
for (OrderSlot slot : o2.getOrdering()
.getAfterList())
{
if (slot instanceof FacesConfigNameSlot)
{
o2Weight++; // depends on control dependency: [if], data = [none]
}
}
}
return o2Weight - o1Weight;
}
});
List<FacesConfig> postOrderedList = new LinkedList<FacesConfig>();
List<FacesConfig> othersList = new ArrayList<FacesConfig>();
List<String> nameBeforeStack = new ArrayList<String>();
List<String> nameAfterStack = new ArrayList<String>();
boolean[] visitedSlots = new boolean[appFilteredConfigResources.size()];
//2. Scan and resolve conflicts
for (int i = 0; i < appFilteredConfigResources.size(); i++)
{
if (!visitedSlots[i])
{
resolveConflicts(appFilteredConfigResources, i, visitedSlots,
nameBeforeStack, nameAfterStack, postOrderedList, othersList, false);
}
}
//Add othersList to postOrderedList so <before><others/></before> and <after><others/></after>
//ordering conditions are handled at last if there are not referenced by anyone
postOrderedList.addAll(othersList);
return postOrderedList;
} } |
public class class_name {
public static boolean equalsIgnoreCase(String str1, String... strs) {
if (strs != null) {
for (String element : strs) {
if ((str1 != null && str1.equalsIgnoreCase(element)) || (str1 == null && element == null)) {
return true; // found
}
}
return false;
} else {
return str1 == null; // if both are null, it means equal
}
} } | public class class_name {
public static boolean equalsIgnoreCase(String str1, String... strs) {
if (strs != null) {
for (String element : strs) {
if ((str1 != null && str1.equalsIgnoreCase(element)) || (str1 == null && element == null)) {
return true; // found // depends on control dependency: [if], data = [none]
}
}
return false; // depends on control dependency: [if], data = [none]
} else {
return str1 == null; // if both are null, it means equal // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public FullTypeSignature getTypeErasureSignature() {
if (typeErasureSignature == null) {
typeErasureSignature = new ClassTypeSignature(binaryName,
new TypeArgSignature[0], ownerTypeSignature == null ? null
: (ClassTypeSignature) ownerTypeSignature
.getTypeErasureSignature());
}
return typeErasureSignature;
} } | public class class_name {
public FullTypeSignature getTypeErasureSignature() {
if (typeErasureSignature == null) {
typeErasureSignature = new ClassTypeSignature(binaryName,
new TypeArgSignature[0], ownerTypeSignature == null ? null
: (ClassTypeSignature) ownerTypeSignature
.getTypeErasureSignature());
// depends on control dependency: [if], data = [none]
}
return typeErasureSignature;
} } |
public class class_name {
public CacheEntry putIfAbsent(String key, CacheEntry value, boolean update) {
final String sourceMethod = "putIfAbsent"; //$NON-NLS-1$
key = keyPrefix + key;
CacheEntry existingValue = null;
boolean incrementCount = false;
SignalUtil.lock(cloneLock.readLock(), sourceClass, sourceMethod);
try {
while (true) {
if (evictionLatch.isLatched()) {
value.delete(cacheMgr);
return null;
}
existingValue = map.putIfAbsent(key, value);
if (existingValue == null) {
incrementCount = true;
} else {
if (update &&
value.lastModified > existingValue.lastModified) {
/*
* Replace the expired value with the new value. If the replace fails,
* then another thread replaced or removed the value between the time
* putIfAbsent returned and the time we called replace. In that case,
* continue in the while loop and try calling putIfAbsent again to get
* the updated entry.
*/
if (map.replace(key, existingValue, value)) {
existingValue.delete(cacheMgr);
existingValue = null;
} else {
continue;
}
}
}
break;
}
if (incrementCount) {
// value was added to the cache. Increment the counter
Boolean evicted = evictionLatch.increment();
if (evicted) {
map.remove(key, value);
value.delete(cacheMgr);
}
}
} finally {
cloneLock.readLock().unlock();
}
return existingValue;
} } | public class class_name {
public CacheEntry putIfAbsent(String key, CacheEntry value, boolean update) {
final String sourceMethod = "putIfAbsent"; //$NON-NLS-1$
key = keyPrefix + key;
CacheEntry existingValue = null;
boolean incrementCount = false;
SignalUtil.lock(cloneLock.readLock(), sourceClass, sourceMethod);
try {
while (true) {
if (evictionLatch.isLatched()) {
value.delete(cacheMgr);
// depends on control dependency: [if], data = [none]
return null;
// depends on control dependency: [if], data = [none]
}
existingValue = map.putIfAbsent(key, value);
// depends on control dependency: [while], data = [none]
if (existingValue == null) {
incrementCount = true;
// depends on control dependency: [if], data = [none]
} else {
if (update &&
value.lastModified > existingValue.lastModified) {
/*
* Replace the expired value with the new value. If the replace fails,
* then another thread replaced or removed the value between the time
* putIfAbsent returned and the time we called replace. In that case,
* continue in the while loop and try calling putIfAbsent again to get
* the updated entry.
*/
if (map.replace(key, existingValue, value)) {
existingValue.delete(cacheMgr);
// depends on control dependency: [if], data = [none]
existingValue = null;
// depends on control dependency: [if], data = [none]
} else {
continue;
}
}
}
break;
}
if (incrementCount) {
// value was added to the cache. Increment the counter
Boolean evicted = evictionLatch.increment();
if (evicted) {
map.remove(key, value);
// depends on control dependency: [if], data = [none]
value.delete(cacheMgr);
// depends on control dependency: [if], data = [none]
}
}
} finally {
cloneLock.readLock().unlock();
}
return existingValue;
} } |
public class class_name {
@Override
public SIBUuid12 getGuaranteedStreamUuid()
{
if (!guaranteedStreamUuidSet)
{
JsMessage localMsg = getJSMessage(true);
guaranteedStreamUuidSet = true;
guaranteedStreamUuid = localMsg.getGuaranteedStreamUUID();
}
return guaranteedStreamUuid;
} } | public class class_name {
@Override
public SIBUuid12 getGuaranteedStreamUuid()
{
if (!guaranteedStreamUuidSet)
{
JsMessage localMsg = getJSMessage(true);
guaranteedStreamUuidSet = true; // depends on control dependency: [if], data = [none]
guaranteedStreamUuid = localMsg.getGuaranteedStreamUUID(); // depends on control dependency: [if], data = [none]
}
return guaranteedStreamUuid;
} } |
public class class_name {
public Properties getAttributes(Attributes attrs) {
Properties attributes = new Properties();
attributes.putAll(attributeValues);
if (defaultContent != null) {
attributes.put(ElementTags.ITEXT, defaultContent);
}
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = getName(attrs.getQName(i));
attributes.setProperty(attribute, attrs.getValue(i));
}
}
return attributes;
} } | public class class_name {
public Properties getAttributes(Attributes attrs) {
Properties attributes = new Properties();
attributes.putAll(attributeValues);
if (defaultContent != null) {
attributes.put(ElementTags.ITEXT, defaultContent); // depends on control dependency: [if], data = [none]
}
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = getName(attrs.getQName(i));
attributes.setProperty(attribute, attrs.getValue(i)); // depends on control dependency: [for], data = [i]
}
}
return attributes;
} } |
public class class_name {
@Override
protected List<ConfigIssue> init() {
// Validate configuration values and open any required resources.
List<ConfigIssue> issues = super.init();
if (getConfig().equals("invalidValue")) {
issues.add(
getContext().createConfigIssue(
Groups.SAMPLE.name(), "config", Errors.SAMPLE_00, "Here's what's wrong..."
)
);
}
// If issues is not empty, the UI will inform the user of each configuration issue in the list.
return issues;
} } | public class class_name {
@Override
protected List<ConfigIssue> init() {
// Validate configuration values and open any required resources.
List<ConfigIssue> issues = super.init();
if (getConfig().equals("invalidValue")) {
issues.add(
getContext().createConfigIssue(
Groups.SAMPLE.name(), "config", Errors.SAMPLE_00, "Here's what's wrong..."
)
); // depends on control dependency: [if], data = [none]
}
// If issues is not empty, the UI will inform the user of each configuration issue in the list.
return issues;
} } |
public class class_name {
private void saveTiles(FileWriting file, int widthInTile, int step, int s) throws IOException
{
for (int tx = 0; tx < widthInTile; tx++)
{
for (int ty = 0; ty < map.getInTileHeight(); ty++)
{
final Tile tile = map.getTile(tx + s * step, ty);
if (tile != null)
{
saveTile(file, tile);
}
}
}
} } | public class class_name {
private void saveTiles(FileWriting file, int widthInTile, int step, int s) throws IOException
{
for (int tx = 0; tx < widthInTile; tx++)
{
for (int ty = 0; ty < map.getInTileHeight(); ty++)
{
final Tile tile = map.getTile(tx + s * step, ty);
if (tile != null)
{
saveTile(file, tile);
// depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
protected void pullTranslations(final ContentSpec contentSpec, final String locale) throws BuildProcessingException {
final CollectionWrapper<TranslatedContentSpecWrapper> translatedContentSpecs = providerFactory.getProvider(
TranslatedContentSpecProvider.class).getTranslatedContentSpecsWithQuery("query;" +
CommonFilterConstants.ZANATA_IDS_FILTER_VAR + "=CS" + contentSpec.getId() + "-" + contentSpec.getRevision());
// Ensure that the passed content spec has a translation
if (translatedContentSpecs == null || translatedContentSpecs.isEmpty()) {
throw new BuildProcessingException(
"Unable to find any translations for Content Spec " + contentSpec.getId() + (contentSpec.getRevision() == null ? "" :
(", Revision " + contentSpec.getRevision())));
}
final TranslatedContentSpecWrapper translatedContentSpec = translatedContentSpecs.getItems().get(0);
if (translatedContentSpec.getTranslatedNodes() != null) {
final Map<String, String> translations = new HashMap<String, String>();
// Iterate over each translated node and build up the list of translated strings for the content spec.
final List<TranslatedCSNodeWrapper> translatedCSNodes = translatedContentSpec.getTranslatedNodes().getItems();
for (final TranslatedCSNodeWrapper translatedCSNode : translatedCSNodes) {
// Only process nodes that have content pushed to Zanata
if (!isNullOrEmpty(translatedCSNode.getOriginalString())) {
if (translatedCSNode.getTranslatedStrings() != null) {
final List<TranslatedCSNodeStringWrapper> translatedCSNodeStrings = translatedCSNode.getTranslatedStrings()
.getItems();
for (final TranslatedCSNodeStringWrapper translatedCSNodeString : translatedCSNodeStrings) {
if (translatedCSNodeString.getLocale().getValue().equals(locale)) {
translations.put(translatedCSNode.getOriginalString(), translatedCSNodeString.getTranslatedString());
}
}
}
}
}
// Resolve any entities to make sure that the source string match
final List<Entity> entities = XMLUtilities.parseEntitiesFromString(contentSpec.getEntities());
TranslationUtilities.resolveCustomContentSpecEntities(entities, translatedContentSpec.getContentSpec());
// Replace all the translated strings
TranslationUtilities.replaceTranslatedStrings(translatedContentSpec.getContentSpec(), contentSpec, translations);
// Set the Unique Ids so that they can be used later
setTranslationUniqueIds(contentSpec, translatedContentSpec);
}
} } | public class class_name {
protected void pullTranslations(final ContentSpec contentSpec, final String locale) throws BuildProcessingException {
final CollectionWrapper<TranslatedContentSpecWrapper> translatedContentSpecs = providerFactory.getProvider(
TranslatedContentSpecProvider.class).getTranslatedContentSpecsWithQuery("query;" +
CommonFilterConstants.ZANATA_IDS_FILTER_VAR + "=CS" + contentSpec.getId() + "-" + contentSpec.getRevision());
// Ensure that the passed content spec has a translation
if (translatedContentSpecs == null || translatedContentSpecs.isEmpty()) {
throw new BuildProcessingException(
"Unable to find any translations for Content Spec " + contentSpec.getId() + (contentSpec.getRevision() == null ? "" :
(", Revision " + contentSpec.getRevision())));
}
final TranslatedContentSpecWrapper translatedContentSpec = translatedContentSpecs.getItems().get(0);
if (translatedContentSpec.getTranslatedNodes() != null) {
final Map<String, String> translations = new HashMap<String, String>();
// Iterate over each translated node and build up the list of translated strings for the content spec.
final List<TranslatedCSNodeWrapper> translatedCSNodes = translatedContentSpec.getTranslatedNodes().getItems();
for (final TranslatedCSNodeWrapper translatedCSNode : translatedCSNodes) {
// Only process nodes that have content pushed to Zanata
if (!isNullOrEmpty(translatedCSNode.getOriginalString())) {
if (translatedCSNode.getTranslatedStrings() != null) {
final List<TranslatedCSNodeStringWrapper> translatedCSNodeStrings = translatedCSNode.getTranslatedStrings()
.getItems();
for (final TranslatedCSNodeStringWrapper translatedCSNodeString : translatedCSNodeStrings) {
if (translatedCSNodeString.getLocale().getValue().equals(locale)) {
translations.put(translatedCSNode.getOriginalString(), translatedCSNodeString.getTranslatedString()); // depends on control dependency: [if], data = [none]
}
}
}
}
}
// Resolve any entities to make sure that the source string match
final List<Entity> entities = XMLUtilities.parseEntitiesFromString(contentSpec.getEntities());
TranslationUtilities.resolveCustomContentSpecEntities(entities, translatedContentSpec.getContentSpec());
// Replace all the translated strings
TranslationUtilities.replaceTranslatedStrings(translatedContentSpec.getContentSpec(), contentSpec, translations);
// Set the Unique Ids so that they can be used later
setTranslationUniqueIds(contentSpec, translatedContentSpec);
}
} } |
public class class_name {
protected Converter findConverter(Class<?> type) {
for (Converter c : converters) {
if (c.handles(type)) {
return c;
}
}
return null;
} } | public class class_name {
protected Converter findConverter(Class<?> type) {
for (Converter c : converters) {
if (c.handles(type)) {
return c; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public synchronized void incrAllCounters(Counters other) {
for (Group otherGroup: other) {
Group group = getGroup(otherGroup.getName());
group.displayName = otherGroup.displayName;
for (Counter otherCounter : otherGroup) {
Counter counter = group.getCounterForName(otherCounter.getName());
counter.setDisplayName(otherCounter.getDisplayName());
counter.increment(otherCounter.getValue());
}
}
} } | public class class_name {
public synchronized void incrAllCounters(Counters other) {
for (Group otherGroup: other) {
Group group = getGroup(otherGroup.getName());
group.displayName = otherGroup.displayName; // depends on control dependency: [for], data = [otherGroup]
for (Counter otherCounter : otherGroup) {
Counter counter = group.getCounterForName(otherCounter.getName());
counter.setDisplayName(otherCounter.getDisplayName()); // depends on control dependency: [for], data = [otherCounter]
counter.increment(otherCounter.getValue()); // depends on control dependency: [for], data = [otherCounter]
}
}
} } |
public class class_name {
public long getAttrAsLongObjectNotNull(ZooClassDef clsDef, ZooFieldDef field) {
int skip = readHeader(clsDef);
skip += field.getOffset();
in.skipRead(skip);
if (in.readByte() == -1) {
return BitTools.NULL;
}
switch (field.getJdoType()) {
case DATE: return in.readLong();
case STRING: return in.readLong();
case REFERENCE:
in.readLong();//schema id
return in.readLong();
default:
throw new IllegalArgumentException(field.getJdoType() + " " + field.getName());
}
} } | public class class_name {
public long getAttrAsLongObjectNotNull(ZooClassDef clsDef, ZooFieldDef field) {
int skip = readHeader(clsDef);
skip += field.getOffset();
in.skipRead(skip);
if (in.readByte() == -1) {
return BitTools.NULL; // depends on control dependency: [if], data = [none]
}
switch (field.getJdoType()) {
case DATE: return in.readLong();
case STRING: return in.readLong();
case REFERENCE:
in.readLong();//schema id
return in.readLong();
default:
throw new IllegalArgumentException(field.getJdoType() + " " + field.getName());
}
} } |
public class class_name {
public Request param(String name, Iterable<Object> values) {
if (params == null) {
params = new LinkedHashMap<String, Object>();
}
params.put(name, values);
return this;
} } | public class class_name {
public Request param(String name, Iterable<Object> values) {
if (params == null) {
params = new LinkedHashMap<String, Object>(); // depends on control dependency: [if], data = [none]
}
params.put(name, values);
return this;
} } |
public class class_name {
public final void setTarget(Matcher m, int groupId) {
MemReg mr = m.bounds(groupId);
if (mr == null) throw new IllegalArgumentException("group #" + groupId + " is not assigned");
data = m.data;
offset = mr.in;
end = mr.out;
cache = m.cache;
cacheLength = m.cacheLength;
cacheOffset = m.cacheOffset;
if (m != this) {
shared = true;
m.shared = true;
}
init();
} } | public class class_name {
public final void setTarget(Matcher m, int groupId) {
MemReg mr = m.bounds(groupId);
if (mr == null) throw new IllegalArgumentException("group #" + groupId + " is not assigned");
data = m.data;
offset = mr.in;
end = mr.out;
cache = m.cache;
cacheLength = m.cacheLength;
cacheOffset = m.cacheOffset;
if (m != this) {
shared = true; // depends on control dependency: [if], data = [none]
m.shared = true; // depends on control dependency: [if], data = [none]
}
init();
} } |
public class class_name {
public boolean isConnectionValid() {
//Init the session to get the salt...
try {
this.getJson(
false,
WS.Path.Test.Version1.testConnection());
} catch (FluidClientException flowJobExcept) {
//Connect problem...
if(flowJobExcept.getErrorCode() == FluidClientException.ErrorCode.CONNECT_ERROR) {
return false;
}
throw flowJobExcept;
}
return true;
} } | public class class_name {
public boolean isConnectionValid() {
//Init the session to get the salt...
try {
this.getJson(
false,
WS.Path.Test.Version1.testConnection()); // depends on control dependency: [try], data = [none]
} catch (FluidClientException flowJobExcept) {
//Connect problem...
if(flowJobExcept.getErrorCode() == FluidClientException.ErrorCode.CONNECT_ERROR) {
return false; // depends on control dependency: [if], data = [none]
}
throw flowJobExcept;
} // depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
public void setAttribute(final String name, final Attribute attribute) {
if (name.equals("datasource")) {
this.allAttributes.putAll(((DataSourceAttribute) attribute).getAttributes());
} else if (this.copyAttributes.contains(name)) {
this.allAttributes.put(name, attribute);
}
} } | public class class_name {
public void setAttribute(final String name, final Attribute attribute) {
if (name.equals("datasource")) {
this.allAttributes.putAll(((DataSourceAttribute) attribute).getAttributes()); // depends on control dependency: [if], data = [none]
} else if (this.copyAttributes.contains(name)) {
this.allAttributes.put(name, attribute); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void writeToFile(Path path) {
try {
try (OutputStream os = Files.newOutputStream(path)) {
InputStreams.transferTo(body(), os);
}
} catch (IOException e) {
throw new RequestsException(e);
} finally {
close();
}
} } | public class class_name {
public void writeToFile(Path path) {
try {
try (OutputStream os = Files.newOutputStream(path)) {
InputStreams.transferTo(body(), os);
}
} catch (IOException e) {
throw new RequestsException(e);
} finally { // depends on control dependency: [catch], data = [none]
close();
}
} } |
public class class_name {
private synchronized void startWeakRefCleaner() {
weakRefCleaner = new Thread(() -> {
boolean running = true;
while (running) {
try {
// just wait, no need to get the - gc'ed object
weakReferenceQueue.remove();
// clean up the coordinateLines entries
final Set<String> coordinateLinesToRemove = new HashSet<>();
synchronized (coordinateLines) {
coordinateLines.forEach((k, v) -> {
if (null == v.get()) {
coordinateLinesToRemove.add(k);
if (logger.isTraceEnabled()) {
logger.trace("need to cleanup gc'ed coordinate line {}", k);
}
}
});
}
// run on the JavaFX thread, as removeCoordinateLineWithId() calls methods from the WebView
Platform.runLater(() -> coordinateLinesToRemove.forEach(this::removeCoordinateLineWithId));
// clean up the MapCoordinateElement entries
final Set<String> mapCoordinateElementsToRemove = new HashSet<>();
synchronized (mapCoordinateElements) {
mapCoordinateElements.forEach((k, v) -> {
if (null == v.get()) {
mapCoordinateElementsToRemove.add(k);
if (logger.isTraceEnabled()) {
logger.trace("need to cleanup gc'ed element {}", k);
}
}
});
}
// run on the JavaFX thread, as removeCoordinateLineWithId() calls methods from the WebView
Platform.runLater(
() -> mapCoordinateElementsToRemove.forEach(this::removeMapCoordinateElementWithId));
} catch (InterruptedException e) {
if (logger.isDebugEnabled()) {
logger.debug("thread interrupted");
}
running = false;
}
}
});
weakRefCleaner.setName("MapView-WeakRef-Cleaner");
weakRefCleaner.setDaemon(true);
weakRefCleaner.start();
} } | public class class_name {
private synchronized void startWeakRefCleaner() {
weakRefCleaner = new Thread(() -> {
boolean running = true;
while (running) {
try {
// just wait, no need to get the - gc'ed object
weakReferenceQueue.remove(); // depends on control dependency: [try], data = [none]
// clean up the coordinateLines entries
final Set<String> coordinateLinesToRemove = new HashSet<>();
synchronized (coordinateLines) { // depends on control dependency: [try], data = [none]
coordinateLines.forEach((k, v) -> {
if (null == v.get()) {
coordinateLinesToRemove.add(k); // depends on control dependency: [if], data = [none]
if (logger.isTraceEnabled()) {
logger.trace("need to cleanup gc'ed coordinate line {}", k);
}
}
});
}
// run on the JavaFX thread, as removeCoordinateLineWithId() calls methods from the WebView
Platform.runLater(() -> coordinateLinesToRemove.forEach(this::removeCoordinateLineWithId));
// clean up the MapCoordinateElement entries
final Set<String> mapCoordinateElementsToRemove = new HashSet<>();
synchronized (mapCoordinateElements) {
mapCoordinateElements.forEach((k, v) -> {
if (null == v.get()) {
mapCoordinateElementsToRemove.add(k);
if (logger.isTraceEnabled()) {
logger.trace("need to cleanup gc'ed element {}", k); // depends on control dependency: [if], data = [none]
}
}
});
}
// run on the JavaFX thread, as removeCoordinateLineWithId() calls methods from the WebView
Platform.runLater(
() -> mapCoordinateElementsToRemove.forEach(this::removeMapCoordinateElementWithId)); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
if (logger.isDebugEnabled()) {
logger.debug("thread interrupted"); // depends on control dependency: [if], data = [none]
}
running = false;
} // depends on control dependency: [catch], data = [none]
}
});
weakRefCleaner.setName("MapView-WeakRef-Cleaner");
weakRefCleaner.setDaemon(true);
weakRefCleaner.start();
} } |
public class class_name {
public int getValueForPosition(int p)
{
int pt = nPoints - 1;
for (int i=0; i<pt; i++)
{
if (p <= position[i])
{
pt = i;
break;
}
}
int x2 = position[pt];
int x1, v;
if (p>=x2)
{
v = value[pt]<<SHIFT;
x1 = x2;
}
else
if (pt>0)
{
v = value[pt-1]<<SHIFT;
x1 = position[pt-1];
}
else
{
v = x1 = 0;
}
if (p>x2) p=x2;
if ((x2>x1) && (p>x1))
{
v += ((p - x1) * ((value[pt]<<SHIFT) - v)) / (x2 - x1);
}
if (v<0) v=0;
else
if (v>MAXVALUE) v = MAXVALUE;
return v;
} } | public class class_name {
public int getValueForPosition(int p)
{
int pt = nPoints - 1;
for (int i=0; i<pt; i++)
{
if (p <= position[i])
{
pt = i; // depends on control dependency: [if], data = [none]
break;
}
}
int x2 = position[pt];
int x1, v;
if (p>=x2)
{
v = value[pt]<<SHIFT; // depends on control dependency: [if], data = [none]
x1 = x2; // depends on control dependency: [if], data = [none]
}
else
if (pt>0)
{
v = value[pt-1]<<SHIFT; // depends on control dependency: [if], data = [none]
x1 = position[pt-1]; // depends on control dependency: [if], data = [none]
}
else
{
v = x1 = 0; // depends on control dependency: [if], data = [none]
}
if (p>x2) p=x2;
if ((x2>x1) && (p>x1))
{
v += ((p - x1) * ((value[pt]<<SHIFT) - v)) / (x2 - x1); // depends on control dependency: [if], data = [none]
}
if (v<0) v=0;
else
if (v>MAXVALUE) v = MAXVALUE;
return v;
} } |
public class class_name {
public void setUserErrors(java.util.Collection<UserError> userErrors) {
if (userErrors == null) {
this.userErrors = null;
return;
}
this.userErrors = new java.util.ArrayList<UserError>(userErrors);
} } | public class class_name {
public void setUserErrors(java.util.Collection<UserError> userErrors) {
if (userErrors == null) {
this.userErrors = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.userErrors = new java.util.ArrayList<UserError>(userErrors);
} } |
public class class_name {
static Set<String> readServiceFile(InputStream input) throws IOException {
HashSet<String> serviceClasses = new HashSet<String>();
Closer closer = Closer.create();
try {
// TODO(gak): use CharStreams
BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
String line;
while ((line = r.readLine()) != null) {
int commentStart = line.indexOf('#');
if (commentStart >= 0) {
line = line.substring(0, commentStart);
}
line = line.trim();
if (!line.isEmpty()) {
serviceClasses.add(line);
}
}
return serviceClasses;
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
} } | public class class_name {
static Set<String> readServiceFile(InputStream input) throws IOException {
HashSet<String> serviceClasses = new HashSet<String>();
Closer closer = Closer.create();
try {
// TODO(gak): use CharStreams
BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
String line;
while ((line = r.readLine()) != null) {
int commentStart = line.indexOf('#');
if (commentStart >= 0) {
line = line.substring(0, commentStart); // depends on control dependency: [if], data = [none]
}
line = line.trim(); // depends on control dependency: [while], data = [none]
if (!line.isEmpty()) {
serviceClasses.add(line); // depends on control dependency: [if], data = [none]
}
}
return serviceClasses;
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
} } |
public class class_name {
public static String join(String[] strings, String separator) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : strings) {
if (first) {
first = false;
} else {
sb.append(separator);
}
sb.append(s);
}
return sb.toString();
} } | public class class_name {
public static String join(String[] strings, String separator) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : strings) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
sb.append(separator); // depends on control dependency: [if], data = [none]
}
sb.append(s); // depends on control dependency: [for], data = [s]
}
return sb.toString();
} } |
public class class_name {
public boolean classMatch(String targetClass, String templateClass)
{
//x if (targetClass.startsWith(Constants.ROOT_PACKAGE)) // Always
//x targetClass = targetClass.substring(Constants.ROOT_PACKAGE.length() - 1);
//x if (templateClass.startsWith(Constants.ROOT_PACKAGE)) // Never
//x templateClass = templateClass.substring(Constants.ROOT_PACKAGE.length() - 1);
//x if (targetClass.startsWith(Constants.THIN_SUBPACKAGE))
//x if (!templateClass.startsWith(THIN_CLASS))
//x targetClass = targetClass.substring(THIN_CLASS.length()); // Include thin classes
if (targetClass.startsWith(BASE_CLASS))
return true; // Allow access to all base classes
if (templateClass.endsWith("*"))
{
if (templateClass.startsWith("*"))
return targetClass.indexOf(templateClass.substring(1, templateClass.length() - 1)) != -1;
return targetClass.startsWith(templateClass.substring(0, templateClass.length() - 1));
}
else
{ // Exact match
return templateClass.equalsIgnoreCase(targetClass);
}
} } | public class class_name {
public boolean classMatch(String targetClass, String templateClass)
{
//x if (targetClass.startsWith(Constants.ROOT_PACKAGE)) // Always
//x targetClass = targetClass.substring(Constants.ROOT_PACKAGE.length() - 1);
//x if (templateClass.startsWith(Constants.ROOT_PACKAGE)) // Never
//x templateClass = templateClass.substring(Constants.ROOT_PACKAGE.length() - 1);
//x if (targetClass.startsWith(Constants.THIN_SUBPACKAGE))
//x if (!templateClass.startsWith(THIN_CLASS))
//x targetClass = targetClass.substring(THIN_CLASS.length()); // Include thin classes
if (targetClass.startsWith(BASE_CLASS))
return true; // Allow access to all base classes
if (templateClass.endsWith("*"))
{
if (templateClass.startsWith("*"))
return targetClass.indexOf(templateClass.substring(1, templateClass.length() - 1)) != -1;
return targetClass.startsWith(templateClass.substring(0, templateClass.length() - 1)); // depends on control dependency: [if], data = [none]
}
else
{ // Exact match
return templateClass.equalsIgnoreCase(targetClass); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void updateGeneralSettings(
CmsObject cms,
String defaultUri,
List<String> workplaceServersList,
String sharedFolder)
throws CmsException {
Map<String, CmsSSLMode> workplaceServers = new LinkedHashMap<String, CmsSSLMode>();
for (String server : workplaceServersList) {
if (m_workplaceServers.containsKey(server)) {
workplaceServers.put(server, m_workplaceServers.get(server));
} else {
workplaceServers.put(server, CmsSSLMode.NO);
}
}
updateGeneralSettings(cms, defaultUri, workplaceServers, sharedFolder);
} } | public class class_name {
public void updateGeneralSettings(
CmsObject cms,
String defaultUri,
List<String> workplaceServersList,
String sharedFolder)
throws CmsException {
Map<String, CmsSSLMode> workplaceServers = new LinkedHashMap<String, CmsSSLMode>();
for (String server : workplaceServersList) {
if (m_workplaceServers.containsKey(server)) {
workplaceServers.put(server, m_workplaceServers.get(server)); // depends on control dependency: [if], data = [none]
} else {
workplaceServers.put(server, CmsSSLMode.NO); // depends on control dependency: [if], data = [none]
}
}
updateGeneralSettings(cms, defaultUri, workplaceServers, sharedFolder);
} } |
public class class_name {
public RoleDetail withRolePolicyList(PolicyDetail... rolePolicyList) {
if (this.rolePolicyList == null) {
setRolePolicyList(new com.amazonaws.internal.SdkInternalList<PolicyDetail>(rolePolicyList.length));
}
for (PolicyDetail ele : rolePolicyList) {
this.rolePolicyList.add(ele);
}
return this;
} } | public class class_name {
public RoleDetail withRolePolicyList(PolicyDetail... rolePolicyList) {
if (this.rolePolicyList == null) {
setRolePolicyList(new com.amazonaws.internal.SdkInternalList<PolicyDetail>(rolePolicyList.length)); // depends on control dependency: [if], data = [none]
}
for (PolicyDetail ele : rolePolicyList) {
this.rolePolicyList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static BigDecimal parsePriceValue(String value) {
value = StringUtils.trimToNull(value);
if (value == null) return null;
try {
return DatatypeConverter.parseDecimal(value);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Can't parse price value '" + value + "'!", ex);
}
} } | public class class_name {
public static BigDecimal parsePriceValue(String value) {
value = StringUtils.trimToNull(value);
if (value == null) return null;
try {
return DatatypeConverter.parseDecimal(value); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Can't parse price value '" + value + "'!", ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
Segment getSegment(int vertex) {
if (m_segments != null) {
int vindex = getVertexIndex(vertex);
return m_segments.get(vindex);
}
return null;
} } | public class class_name {
Segment getSegment(int vertex) {
if (m_segments != null) {
int vindex = getVertexIndex(vertex);
return m_segments.get(vindex); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public final void destroy() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
if (destroyed || (nthreads > 0)) {
throw new IllegalThreadStateException();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
if (parent != null) {
destroyed = true;
ngroups = 0;
groups = null;
nthreads = 0;
threads = null;
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i += 1) {
groupsSnapshot[i].destroy();
}
if (parent != null) {
parent.remove(this);
}
} } | public class class_name {
public final void destroy() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
if (destroyed || (nthreads > 0)) {
throw new IllegalThreadStateException();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot); // depends on control dependency: [if], data = [(groups]
} else {
groupsSnapshot = null; // depends on control dependency: [if], data = [none]
}
if (parent != null) {
destroyed = true; // depends on control dependency: [if], data = [none]
ngroups = 0; // depends on control dependency: [if], data = [none]
groups = null; // depends on control dependency: [if], data = [none]
nthreads = 0; // depends on control dependency: [if], data = [none]
threads = null; // depends on control dependency: [if], data = [none]
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i += 1) {
groupsSnapshot[i].destroy(); // depends on control dependency: [for], data = [i]
}
if (parent != null) {
parent.remove(this); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void serviceActive(ServiceID serviceID) {
try {
ReceivableService receivableService = resourceAdaptorContext
.getServiceLookupFacility().getReceivableService(serviceID);
if (receivableService.getReceivableEvents().length > 0) {
object.serviceActive(receivableService);
}
} catch (Throwable e) {
logger.warn("invocation resulted in unchecked exception", e);
}
} } | public class class_name {
public void serviceActive(ServiceID serviceID) {
try {
ReceivableService receivableService = resourceAdaptorContext
.getServiceLookupFacility().getReceivableService(serviceID);
if (receivableService.getReceivableEvents().length > 0) {
object.serviceActive(receivableService);
// depends on control dependency: [if], data = [none]
}
} catch (Throwable e) {
logger.warn("invocation resulted in unchecked exception", e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private double getMolecularWeight(IAtomContainer atomContainer) throws CDKException {
double mw = 0.0;
try {
final IsotopeFactory isotopeFactory = Isotopes.getInstance();
for (IAtom atom : atomContainer.atoms()) {
if (!atom.getSymbol().equals("H")) {
final IIsotope majorIsotope = isotopeFactory.getMajorIsotope(atom.getSymbol());
if (majorIsotope != null && majorIsotope.getExactMass() != null) {
mw += majorIsotope.getExactMass().doubleValue();
}
}
}
} catch (IOException e) {
throw new CDKException(e.getMessage(), e);
}
return mw;
} } | public class class_name {
private double getMolecularWeight(IAtomContainer atomContainer) throws CDKException {
double mw = 0.0;
try {
final IsotopeFactory isotopeFactory = Isotopes.getInstance();
for (IAtom atom : atomContainer.atoms()) {
if (!atom.getSymbol().equals("H")) {
final IIsotope majorIsotope = isotopeFactory.getMajorIsotope(atom.getSymbol());
if (majorIsotope != null && majorIsotope.getExactMass() != null) {
mw += majorIsotope.getExactMass().doubleValue(); // depends on control dependency: [if], data = [none]
}
}
}
} catch (IOException e) {
throw new CDKException(e.getMessage(), e);
}
return mw;
} } |
public class class_name {
private Map<Resourcepart, Presence> getPresencesInternal(BareJid entity) {
Map<Resourcepart, Presence> entityPresences = presenceMap.get(entity);
if (entityPresences == null) {
entityPresences = nonRosterPresenceMap.lookup(entity);
}
return entityPresences;
} } | public class class_name {
private Map<Resourcepart, Presence> getPresencesInternal(BareJid entity) {
Map<Resourcepart, Presence> entityPresences = presenceMap.get(entity);
if (entityPresences == null) {
entityPresences = nonRosterPresenceMap.lookup(entity); // depends on control dependency: [if], data = [none]
}
return entityPresences;
} } |
public class class_name {
public Multimap<TextAnnotation, EntityAnnotation> getBestAnnotations() {
Ordering<EntityAnnotation> o = new Ordering<EntityAnnotation>() {
@Override
public int compare(EntityAnnotation left, EntityAnnotation right) {
return Doubles.compare(left.confidence, right.confidence);
}
}.reverse();
Multimap<TextAnnotation, EntityAnnotation> result = ArrayListMultimap.create();
for (TextAnnotation ta : getTextAnnotations()) {
List<EntityAnnotation> eas = o.sortedCopy(getEntityAnnotations(ta));
if (!eas.isEmpty()) {
Collection<EntityAnnotation> highest = new HashSet<>();
Double confidence = eas.get(0).getConfidence();
for (EntityAnnotation ea : eas) {
if (ea.confidence < confidence) {
break;
} else {
highest.add(ea);
}
}
result.putAll(ta, highest);
}
}
return result;
} } | public class class_name {
public Multimap<TextAnnotation, EntityAnnotation> getBestAnnotations() {
Ordering<EntityAnnotation> o = new Ordering<EntityAnnotation>() {
@Override
public int compare(EntityAnnotation left, EntityAnnotation right) {
return Doubles.compare(left.confidence, right.confidence);
}
}.reverse();
Multimap<TextAnnotation, EntityAnnotation> result = ArrayListMultimap.create();
for (TextAnnotation ta : getTextAnnotations()) {
List<EntityAnnotation> eas = o.sortedCopy(getEntityAnnotations(ta));
if (!eas.isEmpty()) {
Collection<EntityAnnotation> highest = new HashSet<>();
Double confidence = eas.get(0).getConfidence();
for (EntityAnnotation ea : eas) {
if (ea.confidence < confidence) {
break;
} else {
highest.add(ea); // depends on control dependency: [if], data = [none]
}
}
result.putAll(ta, highest); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected void removeSREs() {
final IStructuredSelection selection = (IStructuredSelection) this.sresList.getSelection();
final ISREInstall[] vms = new ISREInstall[selection.size()];
final Iterator<ISREInstall> iter = selection.iterator();
int i = 0;
while (iter.hasNext()) {
vms[i] = iter.next();
i++;
}
removeSREs(vms);
} } | public class class_name {
@SuppressWarnings("unchecked")
protected void removeSREs() {
final IStructuredSelection selection = (IStructuredSelection) this.sresList.getSelection();
final ISREInstall[] vms = new ISREInstall[selection.size()];
final Iterator<ISREInstall> iter = selection.iterator();
int i = 0;
while (iter.hasNext()) {
vms[i] = iter.next(); // depends on control dependency: [while], data = [none]
i++; // depends on control dependency: [while], data = [none]
}
removeSREs(vms);
} } |
public class class_name {
@Override
public void decorateMethodPreClassHandler(MutableClass mutableClass, MethodNode originalMethod,
String originalMethodName, RobolectricGeneratorAdapter generator) {
boolean isNormalInstanceMethod = !generator.isStatic
&& !originalMethodName.equals(ShadowConstants.CONSTRUCTOR_METHOD_NAME);
// maybe perform direct call...
if (isNormalInstanceMethod) {
int exceptionLocalVar = generator.newLocal(THROWABLE_TYPE);
Label notInstanceOfThis = new Label();
generator.loadThis(); // this
generator.getField(mutableClass.classType, ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME, OBJECT_TYPE); // contents of this.__robo_data__
generator.instanceOf(mutableClass.classType); // __robo_data__, is instance of same class?
generator.visitJumpInsn(Opcodes.IFEQ, notInstanceOfThis); // jump if no (is not instance)
TryCatch tryCatchForProxyCall = generator.tryStart(THROWABLE_TYPE);
generator.loadThis(); // this
generator.getField(mutableClass.classType, ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME, OBJECT_TYPE); // contents of this.__robo_data__
generator.checkCast(mutableClass.classType); // __robo_data__ but cast to my class
generator.loadArgs(); // __robo_data__ instance, [args]
generator.visitMethodInsn(Opcodes.INVOKESPECIAL, mutableClass.internalClassName, originalMethod.name, originalMethod.desc, false);
tryCatchForProxyCall.end();
generator.returnValue();
// catch(Throwable)
tryCatchForProxyCall.handler();
generator.storeLocal(exceptionLocalVar);
generator.loadLocal(exceptionLocalVar);
generator.invokeStatic(ROBOLECTRIC_INTERNALS_TYPE, HANDLE_EXCEPTION_METHOD);
generator.throwException();
// callClassHandler...
generator.mark(notInstanceOfThis);
}
} } | public class class_name {
@Override
public void decorateMethodPreClassHandler(MutableClass mutableClass, MethodNode originalMethod,
String originalMethodName, RobolectricGeneratorAdapter generator) {
boolean isNormalInstanceMethod = !generator.isStatic
&& !originalMethodName.equals(ShadowConstants.CONSTRUCTOR_METHOD_NAME);
// maybe perform direct call...
if (isNormalInstanceMethod) {
int exceptionLocalVar = generator.newLocal(THROWABLE_TYPE);
Label notInstanceOfThis = new Label();
generator.loadThis(); // this // depends on control dependency: [if], data = [none]
generator.getField(mutableClass.classType, ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME, OBJECT_TYPE); // contents of this.__robo_data__ // depends on control dependency: [if], data = [none]
generator.instanceOf(mutableClass.classType); // __robo_data__, is instance of same class? // depends on control dependency: [if], data = [none]
generator.visitJumpInsn(Opcodes.IFEQ, notInstanceOfThis); // jump if no (is not instance) // depends on control dependency: [if], data = [none]
TryCatch tryCatchForProxyCall = generator.tryStart(THROWABLE_TYPE);
generator.loadThis(); // this // depends on control dependency: [if], data = [none]
generator.getField(mutableClass.classType, ShadowConstants.CLASS_HANDLER_DATA_FIELD_NAME, OBJECT_TYPE); // contents of this.__robo_data__ // depends on control dependency: [if], data = [none]
generator.checkCast(mutableClass.classType); // __robo_data__ but cast to my class // depends on control dependency: [if], data = [none]
generator.loadArgs(); // __robo_data__ instance, [args] // depends on control dependency: [if], data = [none]
generator.visitMethodInsn(Opcodes.INVOKESPECIAL, mutableClass.internalClassName, originalMethod.name, originalMethod.desc, false); // depends on control dependency: [if], data = [none]
tryCatchForProxyCall.end(); // depends on control dependency: [if], data = [none]
generator.returnValue(); // depends on control dependency: [if], data = [none]
// catch(Throwable)
tryCatchForProxyCall.handler(); // depends on control dependency: [if], data = [none]
generator.storeLocal(exceptionLocalVar); // depends on control dependency: [if], data = [none]
generator.loadLocal(exceptionLocalVar); // depends on control dependency: [if], data = [none]
generator.invokeStatic(ROBOLECTRIC_INTERNALS_TYPE, HANDLE_EXCEPTION_METHOD); // depends on control dependency: [if], data = [none]
generator.throwException(); // depends on control dependency: [if], data = [none]
// callClassHandler...
generator.mark(notInstanceOfThis); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void visitCode(Code obj) {
Method m = getMethod();
if (isIgnorableMethod(m)) {
return;
}
stack.resetForMethodEntry(this);
syncBlockBranchResetValues.clear();
syncBlockCount = 0;
super.visitCode(obj);
} } | public class class_name {
@Override
public void visitCode(Code obj) {
Method m = getMethod();
if (isIgnorableMethod(m)) {
return; // depends on control dependency: [if], data = [none]
}
stack.resetForMethodEntry(this);
syncBlockBranchResetValues.clear();
syncBlockCount = 0;
super.visitCode(obj);
} } |
public class class_name {
public String build() {
String fieldsString = this.fields == null ? null : Helpers.quote(this.fields);
String sortString = this.sort == null ? null : quoteSort(this.sort);
String limitString = this.limit == null ? null : Helpers.quote(this.limit);
String skipString = this.skip == null ? null : Helpers.quote(this.skip);
String bookmarkString = this.bookmark == null ? null : Helpers.quote(this.bookmark);
String useIndexString = this.useIndex == null ? null : Helpers.quote(this.useIndex);
StringBuilder builder = new StringBuilder();
// build up components...
// selector
builder.append(Helpers.withKey(Helpers.SELECTOR, this.selector));
// fields
if (fieldsString != null) {
builder.append(String.format(", \"fields\": %s", fieldsString));
}
// sort
if (sortString != null) {
builder.append(String.format(", \"sort\": %s", sortString));
}
// limit
if (limitString != null) {
builder.append(String.format(", \"limit\": %s", limitString));
}
// skip
if (skipString != null) {
builder.append(String.format(", \"skip\": %s", skipString));
}
if (bookmarkString != null) {
builder.append(String.format(", \"bookmark\": %s", bookmarkString));
}
if (!this.update) {
builder.append(", \"update\": false");
}
if (this.stable) {
builder.append(", \"stable\": true");
}
// execution_stats
if (this.executionStats) {
builder.append(", \"execution_stats\": true");
}
if (useIndexString != null) {
builder.append(String.format(", \"use_index\": %s", useIndexString));
}
return String.format("{%s}", builder.toString());
} } | public class class_name {
public String build() {
String fieldsString = this.fields == null ? null : Helpers.quote(this.fields);
String sortString = this.sort == null ? null : quoteSort(this.sort);
String limitString = this.limit == null ? null : Helpers.quote(this.limit);
String skipString = this.skip == null ? null : Helpers.quote(this.skip);
String bookmarkString = this.bookmark == null ? null : Helpers.quote(this.bookmark);
String useIndexString = this.useIndex == null ? null : Helpers.quote(this.useIndex);
StringBuilder builder = new StringBuilder();
// build up components...
// selector
builder.append(Helpers.withKey(Helpers.SELECTOR, this.selector));
// fields
if (fieldsString != null) {
builder.append(String.format(", \"fields\": %s", fieldsString)); // depends on control dependency: [if], data = [none]
}
// sort
if (sortString != null) {
builder.append(String.format(", \"sort\": %s", sortString)); // depends on control dependency: [if], data = [none]
}
// limit
if (limitString != null) {
builder.append(String.format(", \"limit\": %s", limitString)); // depends on control dependency: [if], data = [none]
}
// skip
if (skipString != null) {
builder.append(String.format(", \"skip\": %s", skipString)); // depends on control dependency: [if], data = [none]
}
if (bookmarkString != null) {
builder.append(String.format(", \"bookmark\": %s", bookmarkString)); // depends on control dependency: [if], data = [none]
}
if (!this.update) {
builder.append(", \"update\": false"); // depends on control dependency: [if], data = [none]
}
if (this.stable) {
builder.append(", \"stable\": true"); // depends on control dependency: [if], data = [none]
}
// execution_stats
if (this.executionStats) {
builder.append(", \"execution_stats\": true"); // depends on control dependency: [if], data = [none]
}
if (useIndexString != null) {
builder.append(String.format(", \"use_index\": %s", useIndexString)); // depends on control dependency: [if], data = [none]
}
return String.format("{%s}", builder.toString());
} } |
public class class_name {
private boolean compatibleTypes(TypeMirror parameterType, TypeMirror memberType) {
if (typeUtils.isAssignable(parameterType, memberType)) {
// parameterType assignable to memberType, which in the restricted world of annotations
// means they are the same type, or maybe memberType is an annotation type and parameterType
// is a subtype of that annotation interface (why would you do that?).
return true;
}
// They're not the same, but we could still consider them compatible if for example
// parameterType is List<Integer> and memberType is int[]. We accept any type that is assignable
// to Collection<Integer> (in this example).
if (memberType.getKind() != TypeKind.ARRAY) {
return false;
}
TypeMirror arrayElementType = ((ArrayType) memberType).getComponentType();
TypeMirror wrappedArrayElementType =
arrayElementType.getKind().isPrimitive()
? typeUtils.boxedClass((PrimitiveType) arrayElementType).asType()
: arrayElementType;
TypeElement javaUtilCollection =
elementUtils.getTypeElement(Collection.class.getCanonicalName());
DeclaredType collectionOfElement =
typeUtils.getDeclaredType(javaUtilCollection, wrappedArrayElementType);
return typeUtils.isAssignable(parameterType, collectionOfElement);
} } | public class class_name {
private boolean compatibleTypes(TypeMirror parameterType, TypeMirror memberType) {
if (typeUtils.isAssignable(parameterType, memberType)) {
// parameterType assignable to memberType, which in the restricted world of annotations
// means they are the same type, or maybe memberType is an annotation type and parameterType
// is a subtype of that annotation interface (why would you do that?).
return true; // depends on control dependency: [if], data = [none]
}
// They're not the same, but we could still consider them compatible if for example
// parameterType is List<Integer> and memberType is int[]. We accept any type that is assignable
// to Collection<Integer> (in this example).
if (memberType.getKind() != TypeKind.ARRAY) {
return false; // depends on control dependency: [if], data = [none]
}
TypeMirror arrayElementType = ((ArrayType) memberType).getComponentType();
TypeMirror wrappedArrayElementType =
arrayElementType.getKind().isPrimitive()
? typeUtils.boxedClass((PrimitiveType) arrayElementType).asType()
: arrayElementType;
TypeElement javaUtilCollection =
elementUtils.getTypeElement(Collection.class.getCanonicalName());
DeclaredType collectionOfElement =
typeUtils.getDeclaredType(javaUtilCollection, wrappedArrayElementType);
return typeUtils.isAssignable(parameterType, collectionOfElement);
} } |
public class class_name {
public void setChangedNodes( Set<NodeKey> keys ) {
if (keys != null) {
this.nodeKeys = Collections.unmodifiableSet(new HashSet<NodeKey>(keys));
}
} } | public class class_name {
public void setChangedNodes( Set<NodeKey> keys ) {
if (keys != null) {
this.nodeKeys = Collections.unmodifiableSet(new HashSet<NodeKey>(keys)); // depends on control dependency: [if], data = [(keys]
}
} } |
public class class_name {
public void setText (int row, int column, String text, String style)
{
setText(row, column, text);
if (style != null) {
getCellFormatter().setStyleName(row, column, style);
}
} } | public class class_name {
public void setText (int row, int column, String text, String style)
{
setText(row, column, text);
if (style != null) {
getCellFormatter().setStyleName(row, column, style); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private List<ModelMetadataKey> getAllMetadataKeysForSync(){
List<ModelMetadataKey> allKeys = new ArrayList<ModelMetadataKey>();
allKeys.addAll(this.metaKeyCache.values());
List<ModelMetadataKey> syncKeys = new ArrayList<ModelMetadataKey>();
for(ModelMetadataKey service : allKeys){
ModelMetadataKey syncKey = new ModelMetadataKey(service.getName(), service.getId(), service.getModifiedTime(), service.getCreateTime());
syncKeys.add(syncKey);
}
return syncKeys;
} } | public class class_name {
private List<ModelMetadataKey> getAllMetadataKeysForSync(){
List<ModelMetadataKey> allKeys = new ArrayList<ModelMetadataKey>();
allKeys.addAll(this.metaKeyCache.values());
List<ModelMetadataKey> syncKeys = new ArrayList<ModelMetadataKey>();
for(ModelMetadataKey service : allKeys){
ModelMetadataKey syncKey = new ModelMetadataKey(service.getName(), service.getId(), service.getModifiedTime(), service.getCreateTime());
syncKeys.add(syncKey); // depends on control dependency: [for], data = [none]
}
return syncKeys;
} } |
public class class_name {
public void marshall(DeleteFileEntry deleteFileEntry, ProtocolMarshaller protocolMarshaller) {
if (deleteFileEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteFileEntry.getFilePath(), FILEPATH_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteFileEntry deleteFileEntry, ProtocolMarshaller protocolMarshaller) {
if (deleteFileEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteFileEntry.getFilePath(), FILEPATH_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void initializeExecutor() {
if (!this.executorInitialized) {
this.executorInitialized = true;
this.asyncCreateConnectionExecutor = new ThreadPoolExecutor(minPoolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize),
new NamedThreadFactory("Bolt-conn-warmup-executor", true));
}
} } | public class class_name {
private void initializeExecutor() {
if (!this.executorInitialized) {
this.executorInitialized = true; // depends on control dependency: [if], data = [none]
this.asyncCreateConnectionExecutor = new ThreadPoolExecutor(minPoolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize),
new NamedThreadFactory("Bolt-conn-warmup-executor", true)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static List<CmsRelationType> filterUserDefined(Collection<CmsRelationType> relationTypes) {
List<CmsRelationType> result = new ArrayList<CmsRelationType>(relationTypes);
Iterator<CmsRelationType> it = result.iterator();
while (it.hasNext()) {
CmsRelationType type = it.next();
if (type.isInternal()) {
it.remove();
}
}
return result;
} } | public class class_name {
public static List<CmsRelationType> filterUserDefined(Collection<CmsRelationType> relationTypes) {
List<CmsRelationType> result = new ArrayList<CmsRelationType>(relationTypes);
Iterator<CmsRelationType> it = result.iterator();
while (it.hasNext()) {
CmsRelationType type = it.next();
if (type.isInternal()) {
it.remove(); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public static String render(List<Token> tokens, Map<String, Object> arguments) {
StringBuilder builder = new StringBuilder();
for (Token token : tokens) {
builder.append(token.render(arguments));
}
return builder.toString();
} } | public class class_name {
public static String render(List<Token> tokens, Map<String, Object> arguments) {
StringBuilder builder = new StringBuilder();
for (Token token : tokens) {
builder.append(token.render(arguments));
// depends on control dependency: [for], data = [token]
}
return builder.toString();
} } |
public class class_name {
@POST
@Path("/segment/allocate")
@Produces(SmileMediaTypes.APPLICATION_JACKSON_SMILE)
@Consumes(SmileMediaTypes.APPLICATION_JACKSON_SMILE)
public Response allocateSegment(DateTime timestamp, @Context final HttpServletRequest req)
{
ChatHandlers.authorizationCheck(
req,
Action.READ,
getDataSource(),
authorizerMapper
);
if (toolbox == null) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("task is not running yet").build();
}
try {
final SegmentIdWithShardSpec segmentIdentifier = allocateNewSegment(timestamp);
return Response.ok(toolbox.getObjectMapper().writeValueAsBytes(segmentIdentifier)).build();
}
catch (IOException | IllegalStateException e) {
return Response.serverError().entity(Throwables.getStackTraceAsString(e)).build();
}
catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(Throwables.getStackTraceAsString(e)).build();
}
} } | public class class_name {
@POST
@Path("/segment/allocate")
@Produces(SmileMediaTypes.APPLICATION_JACKSON_SMILE)
@Consumes(SmileMediaTypes.APPLICATION_JACKSON_SMILE)
public Response allocateSegment(DateTime timestamp, @Context final HttpServletRequest req)
{
ChatHandlers.authorizationCheck(
req,
Action.READ,
getDataSource(),
authorizerMapper
);
if (toolbox == null) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("task is not running yet").build(); // depends on control dependency: [if], data = [none]
}
try {
final SegmentIdWithShardSpec segmentIdentifier = allocateNewSegment(timestamp);
return Response.ok(toolbox.getObjectMapper().writeValueAsBytes(segmentIdentifier)).build(); // depends on control dependency: [try], data = [none]
}
catch (IOException | IllegalStateException e) {
return Response.serverError().entity(Throwables.getStackTraceAsString(e)).build();
} // depends on control dependency: [catch], data = [none]
catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(Throwables.getStackTraceAsString(e)).build();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
void setPrimitiveParameterSpecs(EntitySpec[] primitiveParameterSpecs) {
if (primitiveParameterSpecs == null) {
this.primitiveParameterSpecs = EMPTY_ES_ARR;
} else {
this.primitiveParameterSpecs = primitiveParameterSpecs.clone();
}
} } | public class class_name {
void setPrimitiveParameterSpecs(EntitySpec[] primitiveParameterSpecs) {
if (primitiveParameterSpecs == null) {
this.primitiveParameterSpecs = EMPTY_ES_ARR; // depends on control dependency: [if], data = [none]
} else {
this.primitiveParameterSpecs = primitiveParameterSpecs.clone(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public EList<XVariableDeclaration> getResources()
{
if (resources == null)
{
resources = new EObjectContainmentEList<XVariableDeclaration>(XVariableDeclaration.class, this, XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__RESOURCES);
}
return resources;
} } | public class class_name {
public EList<XVariableDeclaration> getResources()
{
if (resources == null)
{
resources = new EObjectContainmentEList<XVariableDeclaration>(XVariableDeclaration.class, this, XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__RESOURCES); // depends on control dependency: [if], data = [none]
}
return resources;
} } |
public class class_name {
public static Date getCanonicalTime(Date date)
{
if (date != null)
{
Calendar cal = popCalendar(date);
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.YEAR, 1);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
pushCalendar(cal);
}
return (date);
} } | public class class_name {
public static Date getCanonicalTime(Date date)
{
if (date != null)
{
Calendar cal = popCalendar(date);
cal.set(Calendar.DAY_OF_YEAR, 1); // depends on control dependency: [if], data = [none]
cal.set(Calendar.YEAR, 1); // depends on control dependency: [if], data = [none]
cal.set(Calendar.MILLISECOND, 0); // depends on control dependency: [if], data = [none]
date = cal.getTime(); // depends on control dependency: [if], data = [none]
pushCalendar(cal); // depends on control dependency: [if], data = [none]
}
return (date);
} } |
public class class_name {
private void ensureLengthForWrite(int ilength) {
if (ilength > mLength) {
if (ilength <= mData.length) {
mLength = ilength;
} else {
int newLength = mData.length * 2;
if (newLength < ilength) {
newLength = ilength;
}
byte[] newData = new byte[newLength];
System.arraycopy(mData, 0, newData, 0, mLength);
mData = newData;
}
mLength = ilength;
}
} } | public class class_name {
private void ensureLengthForWrite(int ilength) {
if (ilength > mLength) {
if (ilength <= mData.length) {
mLength = ilength;
// depends on control dependency: [if], data = [none]
} else {
int newLength = mData.length * 2;
if (newLength < ilength) {
newLength = ilength;
// depends on control dependency: [if], data = [none]
}
byte[] newData = new byte[newLength];
System.arraycopy(mData, 0, newData, 0, mLength);
// depends on control dependency: [if], data = [none]
mData = newData;
// depends on control dependency: [if], data = [none]
}
mLength = ilength;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private ScriptText createScriptText(int key, BMRule rule)
{
StringBuilder builder = new StringBuilder();
builder.append("# BMUnit autogenerated script: ").append(rule.name());
builder.append("\nRULE ");
builder.append(rule.name());
if (rule.isInterface())
{
builder.append("\nINTERFACE ");
}
else
{
builder.append("\nCLASS ");
}
builder.append(rule.targetClass());
builder.append("\nMETHOD ");
builder.append(rule.targetMethod());
String location = rule.targetLocation();
if (location != null && location.length() > 0)
{
builder.append("\nAT ");
builder.append(location);
}
String binding = rule.binding();
if (binding != null && binding.length() > 0)
{
builder.append("\nBIND ");
builder.append(binding);
}
String helper = rule.helper();
if (helper != null && helper.length() > 0)
{
builder.append("\nHELPER ");
builder.append(helper);
}
builder.append("\nIF ");
builder.append(rule.condition());
builder.append("\nDO ");
builder.append(rule.action());
builder.append("\nENDRULE\n");
return new ScriptText("IronJacamarWithByteman" + key, builder.toString());
} } | public class class_name {
private ScriptText createScriptText(int key, BMRule rule)
{
StringBuilder builder = new StringBuilder();
builder.append("# BMUnit autogenerated script: ").append(rule.name());
builder.append("\nRULE ");
builder.append(rule.name());
if (rule.isInterface())
{
builder.append("\nINTERFACE "); // depends on control dependency: [if], data = [none]
}
else
{
builder.append("\nCLASS "); // depends on control dependency: [if], data = [none]
}
builder.append(rule.targetClass());
builder.append("\nMETHOD ");
builder.append(rule.targetMethod());
String location = rule.targetLocation();
if (location != null && location.length() > 0)
{
builder.append("\nAT "); // depends on control dependency: [if], data = [none]
builder.append(location); // depends on control dependency: [if], data = [(location]
}
String binding = rule.binding();
if (binding != null && binding.length() > 0)
{
builder.append("\nBIND "); // depends on control dependency: [if], data = [none]
builder.append(binding); // depends on control dependency: [if], data = [(binding]
}
String helper = rule.helper();
if (helper != null && helper.length() > 0)
{
builder.append("\nHELPER "); // depends on control dependency: [if], data = [none]
builder.append(helper); // depends on control dependency: [if], data = [(helper]
}
builder.append("\nIF ");
builder.append(rule.condition());
builder.append("\nDO ");
builder.append(rule.action());
builder.append("\nENDRULE\n");
return new ScriptText("IronJacamarWithByteman" + key, builder.toString());
} } |
public class class_name {
@UiThread
protected void collapseView() {
setExpanded(false);
onExpansionToggled(true);
if (mParentViewHolderExpandCollapseListener != null) {
mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition());
}
} } | public class class_name {
@UiThread
protected void collapseView() {
setExpanded(false);
onExpansionToggled(true);
if (mParentViewHolderExpandCollapseListener != null) {
mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Object newInstance(Class clazz, ArgumentResolver resolver){
Validate.argumentIsNotNull(clazz);
for (Constructor constructor : clazz.getDeclaredConstructors()) {
if (isPrivate(constructor) || isProtected(constructor)) {
continue;
}
Class [] types = constructor.getParameterTypes();
Object[] params = new Object[types.length];
for (int i=0; i<types.length; i++){
try {
params[i] = resolver.resolve(types[i]);
} catch (JaversException e){
logger.error("failed to create new instance of "+clazz.getName()+", argument resolver for arg["+i+"] " +
types[i].getName() + " thrown exception: "+e.getMessage());
throw e;
}
}
try {
constructor.setAccessible(true);
return constructor.newInstance(params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
throw new JaversException(JaversExceptionCode.NO_PUBLIC_CONSTRUCTOR,clazz.getName());
} } | public class class_name {
public static Object newInstance(Class clazz, ArgumentResolver resolver){
Validate.argumentIsNotNull(clazz);
for (Constructor constructor : clazz.getDeclaredConstructors()) {
if (isPrivate(constructor) || isProtected(constructor)) {
continue;
}
Class [] types = constructor.getParameterTypes();
Object[] params = new Object[types.length];
for (int i=0; i<types.length; i++){
try {
params[i] = resolver.resolve(types[i]); // depends on control dependency: [try], data = [none]
} catch (JaversException e){
logger.error("failed to create new instance of "+clazz.getName()+", argument resolver for arg["+i+"] " +
types[i].getName() + " thrown exception: "+e.getMessage());
throw e;
} // depends on control dependency: [catch], data = [none]
}
try {
constructor.setAccessible(true); // depends on control dependency: [try], data = [none]
return constructor.newInstance(params); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
}
throw new JaversException(JaversExceptionCode.NO_PUBLIC_CONSTRUCTOR,clazz.getName());
} } |
public class class_name {
public static String decrypt(String data, byte[] key)
{
try
{
Key k = toSecretKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
byte[] toByteArray = Hex.decodeHex(data.toCharArray());
byte[] decrypted = cipher.doFinal(toByteArray);
return new String(decrypted, "UTF-8");
}
catch (GeneralSecurityException e)
{
throw new RuntimeException("Failed to decrypt.", e);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
catch (DecoderException e)
{
throw new RuntimeException(e);
}
} } | public class class_name {
public static String decrypt(String data, byte[] key)
{
try
{
Key k = toSecretKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k); // depends on control dependency: [try], data = [none]
byte[] toByteArray = Hex.decodeHex(data.toCharArray());
byte[] decrypted = cipher.doFinal(toByteArray);
return new String(decrypted, "UTF-8"); // depends on control dependency: [try], data = [none]
}
catch (GeneralSecurityException e)
{
throw new RuntimeException("Failed to decrypt.", e);
} // depends on control dependency: [catch], data = [none]
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
catch (DecoderException e)
{
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ServiceRequestContext build() {
// Determine the client address; use remote address unless overridden.
final InetAddress clientAddress;
if (this.clientAddress != null) {
clientAddress = this.clientAddress;
} else {
clientAddress = remoteAddress().getAddress();
}
// Build a fake server which never starts up.
final ServerBuilder serverBuilder = new ServerBuilder().meterRegistry(meterRegistry())
.workerGroup(eventLoop(), false)
.service(path(), service);
serverConfigurators.forEach(configurator -> configurator.accept(serverBuilder));
final Server server = serverBuilder.build();
server.addListener(rejectingListener);
// Retrieve the ServiceConfig of the fake service.
final ServiceConfig serviceCfg = findServiceConfig(server, path(), service);
// Build a fake object related with path mapping.
final PathMappingContext pathMappingCtx = DefaultPathMappingContext.of(
server.config().defaultVirtualHost(),
localAddress().getHostString(),
path(),
query(),
((HttpRequest) request()).headers(),
null);
final PathMappingResult pathMappingResult =
this.pathMappingResult != null ? this.pathMappingResult
: PathMappingResult.of(path(), query());
// Build the context with the properties set by a user and the fake objects.
if (isRequestStartTimeSet()) {
return new DefaultServiceRequestContext(
serviceCfg, fakeChannel(), meterRegistry(), sessionProtocol(), pathMappingCtx,
pathMappingResult, request(), sslSession(), proxiedAddresses, clientAddress,
requestStartTimeNanos(), requestStartTimeMicros());
} else {
return new DefaultServiceRequestContext(
serviceCfg, fakeChannel(), meterRegistry(), sessionProtocol(), pathMappingCtx,
pathMappingResult, request(), sslSession(), proxiedAddresses, clientAddress);
}
} } | public class class_name {
public ServiceRequestContext build() {
// Determine the client address; use remote address unless overridden.
final InetAddress clientAddress;
if (this.clientAddress != null) {
clientAddress = this.clientAddress; // depends on control dependency: [if], data = [none]
} else {
clientAddress = remoteAddress().getAddress(); // depends on control dependency: [if], data = [none]
}
// Build a fake server which never starts up.
final ServerBuilder serverBuilder = new ServerBuilder().meterRegistry(meterRegistry())
.workerGroup(eventLoop(), false)
.service(path(), service);
serverConfigurators.forEach(configurator -> configurator.accept(serverBuilder));
final Server server = serverBuilder.build();
server.addListener(rejectingListener);
// Retrieve the ServiceConfig of the fake service.
final ServiceConfig serviceCfg = findServiceConfig(server, path(), service);
// Build a fake object related with path mapping.
final PathMappingContext pathMappingCtx = DefaultPathMappingContext.of(
server.config().defaultVirtualHost(),
localAddress().getHostString(),
path(),
query(),
((HttpRequest) request()).headers(),
null);
final PathMappingResult pathMappingResult =
this.pathMappingResult != null ? this.pathMappingResult
: PathMappingResult.of(path(), query());
// Build the context with the properties set by a user and the fake objects.
if (isRequestStartTimeSet()) {
return new DefaultServiceRequestContext(
serviceCfg, fakeChannel(), meterRegistry(), sessionProtocol(), pathMappingCtx,
pathMappingResult, request(), sslSession(), proxiedAddresses, clientAddress,
requestStartTimeNanos(), requestStartTimeMicros()); // depends on control dependency: [if], data = [none]
} else {
return new DefaultServiceRequestContext(
serviceCfg, fakeChannel(), meterRegistry(), sessionProtocol(), pathMappingCtx,
pathMappingResult, request(), sslSession(), proxiedAddresses, clientAddress); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Set<CmsResource> getPublishListFiles() throws CmsException {
String context = "[" + RandomStringUtils.randomAlphabetic(8) + "] ";
List<CmsResource> offlineResults = computeCollectorResults(OFFLINE);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Offline collector results for " + m_info + ": " + resourcesToString(offlineResults));
}
List<CmsResource> onlineResults = computeCollectorResults(ONLINE);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Online collector results for " + m_info + ": " + resourcesToString(onlineResults));
}
Set<CmsResource> result = Sets.newHashSet();
for (CmsResource offlineRes : offlineResults) {
if (!(offlineRes.getState().isUnchanged())) {
result.add(offlineRes);
}
}
Set<CmsResource> onlineAndNotOffline = Sets.newHashSet(onlineResults);
onlineAndNotOffline.removeAll(offlineResults);
for (CmsResource res : onlineAndNotOffline) {
try {
// Because the resources have state 'unchanged' in the Online project, we need to read them again in the Offline project
res = getCmsObject(OFFLINE).readResource(res.getStructureId(), CmsResourceFilter.ALL);
result.add(res);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
result.addAll(onlineAndNotOffline);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Publish list contributions for " + m_info + ": " + resourcesToString(result));
}
return result;
} } | public class class_name {
public Set<CmsResource> getPublishListFiles() throws CmsException {
String context = "[" + RandomStringUtils.randomAlphabetic(8) + "] ";
List<CmsResource> offlineResults = computeCollectorResults(OFFLINE);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Offline collector results for " + m_info + ": " + resourcesToString(offlineResults));
}
List<CmsResource> onlineResults = computeCollectorResults(ONLINE);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Online collector results for " + m_info + ": " + resourcesToString(onlineResults));
}
Set<CmsResource> result = Sets.newHashSet();
for (CmsResource offlineRes : offlineResults) {
if (!(offlineRes.getState().isUnchanged())) {
result.add(offlineRes); // depends on control dependency: [if], data = [none]
}
}
Set<CmsResource> onlineAndNotOffline = Sets.newHashSet(onlineResults);
onlineAndNotOffline.removeAll(offlineResults);
for (CmsResource res : onlineAndNotOffline) {
try {
// Because the resources have state 'unchanged' in the Online project, we need to read them again in the Offline project
res = getCmsObject(OFFLINE).readResource(res.getStructureId(), CmsResourceFilter.ALL); // depends on control dependency: [try], data = [none]
result.add(res); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
result.addAll(onlineAndNotOffline);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Publish list contributions for " + m_info + ": " + resourcesToString(result));
}
return result;
} } |
public class class_name {
public static CoreMap getMergedChunk(List<? extends CoreMap> chunkList, String origText,
int chunkIndexStart, int chunkIndexEnd)
{
CoreMap firstChunk = chunkList.get(chunkIndexStart);
CoreMap lastChunk = chunkList.get(chunkIndexEnd-1);
int firstCharOffset = firstChunk.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class);
int lastCharOffset = lastChunk.get(CoreAnnotations.CharacterOffsetEndAnnotation.class);
int firstTokenIndex = firstChunk.get(CoreAnnotations.TokenBeginAnnotation.class);
int lastTokenIndex = lastChunk.get(CoreAnnotations.TokenEndAnnotation.class);
String chunkText = origText.substring(firstCharOffset, lastCharOffset);
CoreMap newChunk = new Annotation(chunkText);
newChunk.set(CoreAnnotations.CharacterOffsetBeginAnnotation.class, firstCharOffset);
newChunk.set(CoreAnnotations.CharacterOffsetEndAnnotation.class, lastCharOffset);
newChunk.set(CoreAnnotations.TokenBeginAnnotation.class, firstTokenIndex);
newChunk.set(CoreAnnotations.TokenEndAnnotation.class, lastTokenIndex);
List<CoreLabel> tokens = new ArrayList<CoreLabel>(lastTokenIndex-firstTokenIndex);
for (int i = chunkIndexStart; i < chunkIndexEnd; i++) {
CoreMap chunk = chunkList.get(i);
tokens.addAll(chunk.get(CoreAnnotations.TokensAnnotation.class));
}
newChunk.set(CoreAnnotations.TokensAnnotation.class, tokens);
// TODO: merge other keys into this new chunk ??
return newChunk;
} } | public class class_name {
public static CoreMap getMergedChunk(List<? extends CoreMap> chunkList, String origText,
int chunkIndexStart, int chunkIndexEnd)
{
CoreMap firstChunk = chunkList.get(chunkIndexStart);
CoreMap lastChunk = chunkList.get(chunkIndexEnd-1);
int firstCharOffset = firstChunk.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class);
int lastCharOffset = lastChunk.get(CoreAnnotations.CharacterOffsetEndAnnotation.class);
int firstTokenIndex = firstChunk.get(CoreAnnotations.TokenBeginAnnotation.class);
int lastTokenIndex = lastChunk.get(CoreAnnotations.TokenEndAnnotation.class);
String chunkText = origText.substring(firstCharOffset, lastCharOffset);
CoreMap newChunk = new Annotation(chunkText);
newChunk.set(CoreAnnotations.CharacterOffsetBeginAnnotation.class, firstCharOffset);
newChunk.set(CoreAnnotations.CharacterOffsetEndAnnotation.class, lastCharOffset);
newChunk.set(CoreAnnotations.TokenBeginAnnotation.class, firstTokenIndex);
newChunk.set(CoreAnnotations.TokenEndAnnotation.class, lastTokenIndex);
List<CoreLabel> tokens = new ArrayList<CoreLabel>(lastTokenIndex-firstTokenIndex);
for (int i = chunkIndexStart; i < chunkIndexEnd; i++) {
CoreMap chunk = chunkList.get(i);
tokens.addAll(chunk.get(CoreAnnotations.TokensAnnotation.class));
// depends on control dependency: [for], data = [none]
}
newChunk.set(CoreAnnotations.TokensAnnotation.class, tokens);
// TODO: merge other keys into this new chunk ??
return newChunk;
} } |
public class class_name {
public int[][] getClusterLabel() {
if (y == null) {
throw new IllegalStateException("Neuron cluster labels are not available. Call partition() first.");
}
int[][] clusterLabels = new int[height][width];
for (int i = 0, l = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
clusterLabels[i][j] = y[i*width + j];
}
}
return clusterLabels;
} } | public class class_name {
public int[][] getClusterLabel() {
if (y == null) {
throw new IllegalStateException("Neuron cluster labels are not available. Call partition() first.");
}
int[][] clusterLabels = new int[height][width];
for (int i = 0, l = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
clusterLabels[i][j] = y[i*width + j]; // depends on control dependency: [for], data = [j]
}
}
return clusterLabels;
} } |
public class class_name {
public static Func1<Iterable<String>, String> toJoinedString(final String delimiter) {
return new Func1<Iterable<String>, String>() {
@Override
public String call(Iterable<String> iterable) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String string : iterable) {
if (first)
first = false;
else
builder.append(delimiter);
builder.append(string);
}
return builder.toString();
}
};
} } | public class class_name {
public static Func1<Iterable<String>, String> toJoinedString(final String delimiter) {
return new Func1<Iterable<String>, String>() {
@Override
public String call(Iterable<String> iterable) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String string : iterable) {
if (first)
first = false;
else
builder.append(delimiter);
builder.append(string); // depends on control dependency: [for], data = [string]
}
return builder.toString();
}
};
} } |
public class class_name {
public static Object getValueToRender(FacesContext context, UIComponent component) {
if (component instanceof ValueHolder) {
if (component instanceof EditableValueHolder) {
EditableValueHolder input = (EditableValueHolder) component;
Object submittedValue = input.getSubmittedValue();
ConfigContainer config = RequestContext.getCurrentInstance().getApplicationContext().getConfig();
if (config.isInterpretEmptyStringAsNull() && submittedValue == null && context.isValidationFailed() && !input.isValid()) {
return null;
} else if (submittedValue != null) {
return submittedValue;
}
}
ValueHolder valueHolder = (ValueHolder) component;
Object value = valueHolder.getValue();
return value;
}
// component it not a value holder
return null;
} } | public class class_name {
public static Object getValueToRender(FacesContext context, UIComponent component) {
if (component instanceof ValueHolder) {
if (component instanceof EditableValueHolder) {
EditableValueHolder input = (EditableValueHolder) component;
Object submittedValue = input.getSubmittedValue();
ConfigContainer config = RequestContext.getCurrentInstance().getApplicationContext().getConfig();
if (config.isInterpretEmptyStringAsNull() && submittedValue == null && context.isValidationFailed() && !input.isValid()) {
return null; // depends on control dependency: [if], data = [none]
} else if (submittedValue != null) {
return submittedValue; // depends on control dependency: [if], data = [none]
}
}
ValueHolder valueHolder = (ValueHolder) component;
Object value = valueHolder.getValue();
return value; // depends on control dependency: [if], data = [none]
}
// component it not a value holder
return null;
} } |
public class class_name {
public static void main(@NotNull String[] args) throws MetadataException, IOException
{
Collection<String> argList = new ArrayList<String>(Arrays.asList(args));
boolean markdownFormat = argList.remove("-markdown");
boolean showHex = argList.remove("-hex");
if (argList.size() < 1) {
String version = ImageMetadataReader.class.getPackage().getImplementationVersion();
System.out.println("metadata-extractor version " + version);
System.out.println();
System.out.println(String.format("Usage: java -jar metadata-extractor-%s.jar <filename> [<filename>] [-thumb] [-markdown] [-hex]", version == null ? "a.b.c" : version));
System.exit(1);
}
for (String filePath : argList) {
long startTime = System.nanoTime();
File file = new File(filePath);
if (!markdownFormat && argList.size()>1)
System.out.printf("\n***** PROCESSING: %s%n%n", filePath);
Metadata metadata = null;
try {
metadata = ImageMetadataReader.readMetadata(file);
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
long took = System.nanoTime() - startTime;
if (!markdownFormat)
System.out.printf("Processed %.3f MB file in %.2f ms%n%n", file.length() / (1024d * 1024), took / 1000000d);
if (markdownFormat) {
String fileName = file.getName();
String urlName = StringUtil.urlEncode(filePath);
ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
String make = exifIFD0Directory == null ? "" : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MAKE);
String model = exifIFD0Directory == null ? "" : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MODEL);
System.out.println();
System.out.println("---");
System.out.println();
System.out.printf("# %s - %s%n", make, model);
System.out.println();
System.out.printf("<a href=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\">%n", urlName);
System.out.printf("<img src=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\" width=\"300\"/><br/>%n", urlName);
System.out.println(fileName);
System.out.println("</a>");
System.out.println();
System.out.println("Directory | Tag Id | Tag Name | Extracted Value");
System.out.println(":--------:|-------:|----------|----------------");
}
// iterate over the metadata and print to System.out
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
for (Tag tag : directory.getTags()) {
String tagName = tag.getTagName();
String description = tag.getDescription();
// truncate the description if it's too long
if (description != null && description.length() > 1024) {
description = description.substring(0, 1024) + "...";
}
if (markdownFormat) {
System.out.printf("%s|0x%s|%s|%s%n",
directoryName,
Integer.toHexString(tag.getTagType()),
tagName,
description);
} else {
// simple formatting
if (showHex) {
System.out.printf("[%s - %s] %s = %s%n", directoryName, tag.getTagTypeHex(), tagName, description);
} else {
System.out.printf("[%s] %s = %s%n", directoryName, tagName, description);
}
}
}
if (directory instanceof XmpDirectory) {
Map<String, String> xmpProperties = ((XmpDirectory)directory).getXmpProperties();
for (Map.Entry<String, String> property : xmpProperties.entrySet()) {
String key = property.getKey();
String value = property.getValue();
if (value != null && value.length() > 1024) {
value = value.substring(0, 1024) + "...";
}
if (markdownFormat) {
System.out.printf("%s||%s|%s%n", directoryName, key, value);
} else {
System.out.printf("[%s] %s = %s%n", directoryName, key, value);
}
}
}
// print out any errors
for (String error : directory.getErrors())
System.err.println("ERROR: " + error);
}
}
} } | public class class_name {
public static void main(@NotNull String[] args) throws MetadataException, IOException
{
Collection<String> argList = new ArrayList<String>(Arrays.asList(args));
boolean markdownFormat = argList.remove("-markdown");
boolean showHex = argList.remove("-hex");
if (argList.size() < 1) {
String version = ImageMetadataReader.class.getPackage().getImplementationVersion();
System.out.println("metadata-extractor version " + version);
System.out.println();
System.out.println(String.format("Usage: java -jar metadata-extractor-%s.jar <filename> [<filename>] [-thumb] [-markdown] [-hex]", version == null ? "a.b.c" : version));
System.exit(1);
}
for (String filePath : argList) {
long startTime = System.nanoTime();
File file = new File(filePath);
if (!markdownFormat && argList.size()>1)
System.out.printf("\n***** PROCESSING: %s%n%n", filePath);
Metadata metadata = null;
try {
metadata = ImageMetadataReader.readMetadata(file);
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
long took = System.nanoTime() - startTime;
if (!markdownFormat)
System.out.printf("Processed %.3f MB file in %.2f ms%n%n", file.length() / (1024d * 1024), took / 1000000d);
if (markdownFormat) {
String fileName = file.getName();
String urlName = StringUtil.urlEncode(filePath);
ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
String make = exifIFD0Directory == null ? "" : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MAKE);
String model = exifIFD0Directory == null ? "" : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MODEL);
System.out.println();
System.out.println("---");
System.out.println();
System.out.printf("# %s - %s%n", make, model);
System.out.println();
System.out.printf("<a href=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\">%n", urlName);
System.out.printf("<img src=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\" width=\"300\"/><br/>%n", urlName);
System.out.println(fileName);
System.out.println("</a>");
System.out.println();
System.out.println("Directory | Tag Id | Tag Name | Extracted Value");
System.out.println(":--------:|-------:|----------|----------------");
}
// iterate over the metadata and print to System.out
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
for (Tag tag : directory.getTags()) {
String tagName = tag.getTagName();
String description = tag.getDescription();
// truncate the description if it's too long
if (description != null && description.length() > 1024) {
description = description.substring(0, 1024) + "...";
}
if (markdownFormat) {
System.out.printf("%s|0x%s|%s|%s%n",
directoryName,
Integer.toHexString(tag.getTagType()),
tagName,
description);
} else {
// simple formatting
if (showHex) {
System.out.printf("[%s - %s] %s = %s%n", directoryName, tag.getTagTypeHex(), tagName, description); // depends on control dependency: [if], data = [none]
} else {
System.out.printf("[%s] %s = %s%n", directoryName, tagName, description); // depends on control dependency: [if], data = [none]
}
}
}
if (directory instanceof XmpDirectory) {
Map<String, String> xmpProperties = ((XmpDirectory)directory).getXmpProperties();
for (Map.Entry<String, String> property : xmpProperties.entrySet()) {
String key = property.getKey();
String value = property.getValue();
if (value != null && value.length() > 1024) {
value = value.substring(0, 1024) + "...";
}
if (markdownFormat) {
System.out.printf("%s||%s|%s%n", directoryName, key, value);
} else {
System.out.printf("[%s] %s = %s%n", directoryName, key, value);
}
}
}
// print out any errors
for (String error : directory.getErrors())
System.err.println("ERROR: " + error);
}
}
} } |
public class class_name {
@Override
public void shutdown() {
synchronized (nextRunnableLock) {
isShutdown = true;
if (workers == null) {
return;
}
// signal each worker thread to shut down
Iterator<WorkerThread> workerThreads = workers.iterator();
while (workerThreads.hasNext()) {
WorkerThread wt = workerThreads.next();
JobRunShell jobRunShell = wt.getRunnable();
if (jobRunShell != null) {
log.info("Waiting for Job to shutdown: {}", wt.getRunnable().getJobName());
}
wt.shutdown();
availWorkers.remove(wt);
}
// Active worker threads will shut down after finishing their
// current job.
nextRunnableLock.notifyAll();
}
} } | public class class_name {
@Override
public void shutdown() {
synchronized (nextRunnableLock) {
isShutdown = true;
if (workers == null) {
return; // depends on control dependency: [if], data = [none]
}
// signal each worker thread to shut down
Iterator<WorkerThread> workerThreads = workers.iterator();
while (workerThreads.hasNext()) {
WorkerThread wt = workerThreads.next();
JobRunShell jobRunShell = wt.getRunnable();
if (jobRunShell != null) {
log.info("Waiting for Job to shutdown: {}", wt.getRunnable().getJobName()); // depends on control dependency: [if], data = [none]
}
wt.shutdown(); // depends on control dependency: [while], data = [none]
availWorkers.remove(wt); // depends on control dependency: [while], data = [none]
}
// Active worker threads will shut down after finishing their
// current job.
nextRunnableLock.notifyAll();
}
} } |
public class class_name {
public ModelNode toModelNode() {
final ModelNode node = new ModelNode().setEmptyList();
for (PathElement element : pathAddressList) {
final String value;
if (element.isMultiTarget() && !element.isWildcard()) {
value = '[' + element.getValue() + ']';
} else {
value = element.getValue();
}
node.add(element.getKey(), value);
}
return node;
} } | public class class_name {
public ModelNode toModelNode() {
final ModelNode node = new ModelNode().setEmptyList();
for (PathElement element : pathAddressList) {
final String value;
if (element.isMultiTarget() && !element.isWildcard()) {
value = '[' + element.getValue() + ']'; // depends on control dependency: [if], data = [none]
} else {
value = element.getValue(); // depends on control dependency: [if], data = [none]
}
node.add(element.getKey(), value); // depends on control dependency: [for], data = [element]
}
return node;
} } |
public class class_name {
@Override
public double getDaycountFraction(LocalDate startDate, LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate);
}
double daysPerYear = 365.0;
// Check startDate for leap year
if (startDate.isLeapYear()) {
LocalDate leapDayStart = LocalDate.of(startDate.getYear(), Month.FEBRUARY, 29);
if(startDate.isBefore(leapDayStart) && !endDate.isBefore(leapDayStart)) {
daysPerYear = 366.0;
}
}
// Check endDate for leap year
if (endDate.isLeapYear()){
LocalDate leapDayEnd = LocalDate.of(endDate.getYear(), Month.FEBRUARY, 29);
if(startDate.isBefore(leapDayEnd) && !endDate.isBefore(leapDayEnd)) {
daysPerYear = 366.0;
}
}
// Check in-between years for leap year
for(int year = startDate.getYear()+1; year < endDate.getYear(); year++) {
if(IsoChronology.INSTANCE.isLeapYear(year)) {
daysPerYear = 366.0;
}
}
double daycountFraction = getDaycount(startDate, endDate) / daysPerYear;
return daycountFraction;
} } | public class class_name {
@Override
public double getDaycountFraction(LocalDate startDate, LocalDate endDate) {
if(startDate.isAfter(endDate)) {
return -getDaycountFraction(endDate,startDate); // depends on control dependency: [if], data = [none]
}
double daysPerYear = 365.0;
// Check startDate for leap year
if (startDate.isLeapYear()) {
LocalDate leapDayStart = LocalDate.of(startDate.getYear(), Month.FEBRUARY, 29);
if(startDate.isBefore(leapDayStart) && !endDate.isBefore(leapDayStart)) {
daysPerYear = 366.0; // depends on control dependency: [if], data = [none]
}
}
// Check endDate for leap year
if (endDate.isLeapYear()){
LocalDate leapDayEnd = LocalDate.of(endDate.getYear(), Month.FEBRUARY, 29);
if(startDate.isBefore(leapDayEnd) && !endDate.isBefore(leapDayEnd)) {
daysPerYear = 366.0; // depends on control dependency: [if], data = [none]
}
}
// Check in-between years for leap year
for(int year = startDate.getYear()+1; year < endDate.getYear(); year++) {
if(IsoChronology.INSTANCE.isLeapYear(year)) {
daysPerYear = 366.0; // depends on control dependency: [if], data = [none]
}
}
double daycountFraction = getDaycount(startDate, endDate) / daysPerYear;
return daycountFraction;
} } |
public class class_name {
public void activityEnded(ActivityHandle activityHandle) {
final Wrapper activity = activityManagement.remove((SipActivityHandle) activityHandle);
if (activity != null) {
activity.clear();
}
} } | public class class_name {
public void activityEnded(ActivityHandle activityHandle) {
final Wrapper activity = activityManagement.remove((SipActivityHandle) activityHandle);
if (activity != null) {
activity.clear(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public EClass getIfcReinforcementDefinitionProperties() {
if (ifcReinforcementDefinitionPropertiesEClass == null) {
ifcReinforcementDefinitionPropertiesEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(433);
}
return ifcReinforcementDefinitionPropertiesEClass;
} } | public class class_name {
public EClass getIfcReinforcementDefinitionProperties() {
if (ifcReinforcementDefinitionPropertiesEClass == null) {
ifcReinforcementDefinitionPropertiesEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(433);
// depends on control dependency: [if], data = [none]
}
return ifcReinforcementDefinitionPropertiesEClass;
} } |
public class class_name {
public static boolean allNull(final Object... o1s) {
if (o1s != null && o1s.length > 0) {
for (final Object o1 : o1s) {
if (o1 != null) {
return false;
}
}
}
return true;
} } | public class class_name {
public static boolean allNull(final Object... o1s) {
if (o1s != null && o1s.length > 0) {
for (final Object o1 : o1s) {
if (o1 != null) {
return false;
// depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
public static DayPeriod of(Map<PlainTime, String> timeToLabels) {
if (timeToLabels.isEmpty()) {
throw new IllegalArgumentException("Label map is empty.");
}
SortedMap<PlainTime, String> map = new TreeMap<>(timeToLabels);
for (PlainTime key : timeToLabels.keySet()) {
if (key.getHour() == 24) {
map.put(PlainTime.midnightAtStartOfDay(), timeToLabels.get(key));
map.remove(key);
} else if (timeToLabels.get(key).isEmpty()) {
throw new IllegalArgumentException("Map has empty label: " + timeToLabels);
}
}
return new DayPeriod(null, "", map);
} } | public class class_name {
public static DayPeriod of(Map<PlainTime, String> timeToLabels) {
if (timeToLabels.isEmpty()) {
throw new IllegalArgumentException("Label map is empty.");
}
SortedMap<PlainTime, String> map = new TreeMap<>(timeToLabels);
for (PlainTime key : timeToLabels.keySet()) {
if (key.getHour() == 24) {
map.put(PlainTime.midnightAtStartOfDay(), timeToLabels.get(key)); // depends on control dependency: [if], data = [none]
map.remove(key); // depends on control dependency: [if], data = [none]
} else if (timeToLabels.get(key).isEmpty()) {
throw new IllegalArgumentException("Map has empty label: " + timeToLabels);
}
}
return new DayPeriod(null, "", map);
} } |
public class class_name {
private void setCellType(Attributes attribute) {
// 重置numFmtIndex,numFmtString的值
numFmtIndex = 0;
numFmtString = "";
this.cellDataType = CellDataType.of(attribute.getValue(T_ATTR_VALUE));
// 获取单元格的xf索引,对应style.xml中cellXfs的子元素xf
final String xfIndexStr = attribute.getValue(S_ATTR_VALUE);
if (xfIndexStr != null) {
int xfIndex = Integer.parseInt(xfIndexStr);
XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(xfIndex);
numFmtIndex = xssfCellStyle.getDataFormat();
numFmtString = xssfCellStyle.getDataFormatString();
if (numFmtString == null) {
cellDataType = CellDataType.NULL;
numFmtString = BuiltinFormats.getBuiltinFormat(numFmtIndex);
} else if (org.apache.poi.ss.usermodel.DateUtil.isADateFormat(numFmtIndex, numFmtString)) {
cellDataType = CellDataType.DATE;
}
}
} } | public class class_name {
private void setCellType(Attributes attribute) {
// 重置numFmtIndex,numFmtString的值
numFmtIndex = 0;
numFmtString = "";
this.cellDataType = CellDataType.of(attribute.getValue(T_ATTR_VALUE));
// 获取单元格的xf索引,对应style.xml中cellXfs的子元素xf
final String xfIndexStr = attribute.getValue(S_ATTR_VALUE);
if (xfIndexStr != null) {
int xfIndex = Integer.parseInt(xfIndexStr);
XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(xfIndex);
numFmtIndex = xssfCellStyle.getDataFormat();
// depends on control dependency: [if], data = [none]
numFmtString = xssfCellStyle.getDataFormatString();
// depends on control dependency: [if], data = [none]
if (numFmtString == null) {
cellDataType = CellDataType.NULL;
// depends on control dependency: [if], data = [none]
numFmtString = BuiltinFormats.getBuiltinFormat(numFmtIndex);
// depends on control dependency: [if], data = [none]
} else if (org.apache.poi.ss.usermodel.DateUtil.isADateFormat(numFmtIndex, numFmtString)) {
cellDataType = CellDataType.DATE;
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private float[] generateParticleTimeStamps(float totalTime)
{
float timeStamps[] = new float[mEmitRate * 2];
for ( int i = 0; i < mEmitRate * 2; i +=2 )
{
timeStamps[i] = totalTime + mRandom.nextFloat();
timeStamps[i + 1] = 0;
}
return timeStamps;
} } | public class class_name {
private float[] generateParticleTimeStamps(float totalTime)
{
float timeStamps[] = new float[mEmitRate * 2];
for ( int i = 0; i < mEmitRate * 2; i +=2 )
{
timeStamps[i] = totalTime + mRandom.nextFloat(); // depends on control dependency: [for], data = [i]
timeStamps[i + 1] = 0; // depends on control dependency: [for], data = [i]
}
return timeStamps;
} } |
public class class_name {
public void commitStaged(SuggestionStage staging) {
if (this.deletes == null) {
this.deletes = new HashMap<>(staging.deletes.size());
}
staging.commitTo(deletes);
} } | public class class_name {
public void commitStaged(SuggestionStage staging) {
if (this.deletes == null) {
this.deletes = new HashMap<>(staging.deletes.size()); // depends on control dependency: [if], data = [none]
}
staging.commitTo(deletes);
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.