code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static Object getAttribute(Object target, String name) {
try {
return InvokerHelper.getAttribute(target, name);
} catch (InvokerInvocationException e) {
ExceptionUtil.sneakyThrow(e.getCause());
return null; // never reached
}
} } | public class class_name {
public static Object getAttribute(Object target, String name) {
try {
return InvokerHelper.getAttribute(target, name); // depends on control dependency: [try], data = [none]
} catch (InvokerInvocationException e) {
ExceptionUtil.sneakyThrow(e.getCause());
return null; // never reached
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void pruneIfNeeded(int neededSpace) {
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
return;
}
// if (JusLog.DEBUG) {
// JusLog.v("Pruning old cache entries.");
// }
//todo add queue markers
long before = mTotalSize;
int prunedFiles = 0;
long startTime = System.nanoTime();
Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, CacheHeader> entry = iterator.next();
CacheHeader e = entry.getValue();
boolean deleted = getFileForKey(e.key).delete();
if (deleted) {
mTotalSize -= e.size;
} else {
//todo add queue markers
// JusLog.d("Could not delete cache entry for key=%s, filename=%s",
// e.key, getFilenameForKey(e.key));
}
iterator.remove();
prunedFiles++;
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
break;
}
}
//todo add queue markers
// if (JusLog.DEBUG) {
// JusLog.v("pruned %d files, %d bytes, %d ms",
// prunedFiles, (mTotalSize - before), System.nanoTime() - startTime);
// }
} } | public class class_name {
private void pruneIfNeeded(int neededSpace) {
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
return; // depends on control dependency: [if], data = [none]
}
// if (JusLog.DEBUG) {
// JusLog.v("Pruning old cache entries.");
// }
//todo add queue markers
long before = mTotalSize;
int prunedFiles = 0;
long startTime = System.nanoTime();
Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, CacheHeader> entry = iterator.next();
CacheHeader e = entry.getValue();
boolean deleted = getFileForKey(e.key).delete();
if (deleted) {
mTotalSize -= e.size; // depends on control dependency: [if], data = [none]
} else {
//todo add queue markers
// JusLog.d("Could not delete cache entry for key=%s, filename=%s",
// e.key, getFilenameForKey(e.key));
}
iterator.remove(); // depends on control dependency: [while], data = [none]
prunedFiles++; // depends on control dependency: [while], data = [none]
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
break;
}
}
//todo add queue markers
// if (JusLog.DEBUG) {
// JusLog.v("pruned %d files, %d bytes, %d ms",
// prunedFiles, (mTotalSize - before), System.nanoTime() - startTime);
// }
} } |
public class class_name {
public static String getInfoMsg(final String msg) {
if (msg.startsWith("ERROR")) {
return msg.replaceFirst("ERROR", "");
}
if (msg.startsWith("WARN")) {
return msg.replaceFirst("WARN", "");
}
return msg;
} } | public class class_name {
public static String getInfoMsg(final String msg) {
if (msg.startsWith("ERROR")) {
return msg.replaceFirst("ERROR", ""); // depends on control dependency: [if], data = [none]
}
if (msg.startsWith("WARN")) {
return msg.replaceFirst("WARN", ""); // depends on control dependency: [if], data = [none]
}
return msg;
} } |
public class class_name {
static String signParameters(URI serviceUri, String signatureVersion, String signatureMethod,
Map<String, String> parameters, String aswSecretKey) {
parameters.put("SignatureVersion", signatureVersion);
String algorithm = "HmacSHA1";
String stringToSign = null;
if ("0".equals(signatureVersion)) {
stringToSign = calculateStringToSignV0(parameters);
} else if ("1".equals(signatureVersion)) {
stringToSign = calculateStringToSignV1(parameters);
} else if ("2".equals(signatureVersion)) {
algorithm = signatureMethod;
parameters.put("SignatureMethod", algorithm);
stringToSign = calculateStringToSignV2(serviceUri, parameters);
} else {
throw new IllegalArgumentException("Invalid Signature Version specified");
}
return sign(stringToSign, aswSecretKey, algorithm);
} } | public class class_name {
static String signParameters(URI serviceUri, String signatureVersion, String signatureMethod,
Map<String, String> parameters, String aswSecretKey) {
parameters.put("SignatureVersion", signatureVersion);
String algorithm = "HmacSHA1";
String stringToSign = null;
if ("0".equals(signatureVersion)) {
stringToSign = calculateStringToSignV0(parameters); // depends on control dependency: [if], data = [none]
} else if ("1".equals(signatureVersion)) {
stringToSign = calculateStringToSignV1(parameters); // depends on control dependency: [if], data = [none]
} else if ("2".equals(signatureVersion)) {
algorithm = signatureMethod; // depends on control dependency: [if], data = [none]
parameters.put("SignatureMethod", algorithm); // depends on control dependency: [if], data = [none]
stringToSign = calculateStringToSignV2(serviceUri, parameters); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Invalid Signature Version specified");
}
return sign(stringToSign, aswSecretKey, algorithm);
} } |
public class class_name {
private BinaryStore selectBinaryStore( String hint ) {
BinaryStore namedBinaryStore = null;
if (hint != null) {
logger.trace("Selecting named binary store for hint: " + hint);
namedBinaryStore = namedStores.get(hint);
}
if (namedBinaryStore == null) {
namedBinaryStore = getDefaultBinaryStore();
}
logger.trace("Selected binary store: " + namedBinaryStore.toString());
return namedBinaryStore;
} } | public class class_name {
private BinaryStore selectBinaryStore( String hint ) {
BinaryStore namedBinaryStore = null;
if (hint != null) {
logger.trace("Selecting named binary store for hint: " + hint); // depends on control dependency: [if], data = [none]
namedBinaryStore = namedStores.get(hint); // depends on control dependency: [if], data = [(hint]
}
if (namedBinaryStore == null) {
namedBinaryStore = getDefaultBinaryStore(); // depends on control dependency: [if], data = [none]
}
logger.trace("Selected binary store: " + namedBinaryStore.toString());
return namedBinaryStore;
} } |
public class class_name {
public void tryVibrate() {
if (mVibrator != null && mIsGloballyEnabled) {
long now = SystemClock.uptimeMillis();
// We want to try to vibrate each individual tick discretely.
if (now - mLastVibrate >= VIBRATE_DELAY_MS) {
mVibrator.vibrate(VIBRATE_LENGTH_MS);
mLastVibrate = now;
}
}
} } | public class class_name {
public void tryVibrate() {
if (mVibrator != null && mIsGloballyEnabled) {
long now = SystemClock.uptimeMillis();
// We want to try to vibrate each individual tick discretely.
if (now - mLastVibrate >= VIBRATE_DELAY_MS) {
mVibrator.vibrate(VIBRATE_LENGTH_MS); // depends on control dependency: [if], data = [none]
mLastVibrate = now; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public Properties getConfiguration(Environment environment) {
boolean allMissEnvironment = true;
for (ConfigurationSource source : sources) {
try {
return source.getConfiguration(environment);
} catch (MissingEnvironmentException e) {
// NOP
} catch (IllegalStateException e) {
allMissEnvironment = false;
}
}
if (allMissEnvironment) {
throw new MissingEnvironmentException(environment.getName());
}
throw new IllegalStateException();
} } | public class class_name {
@Override
public Properties getConfiguration(Environment environment) {
boolean allMissEnvironment = true;
for (ConfigurationSource source : sources) {
try {
return source.getConfiguration(environment); // depends on control dependency: [try], data = [none]
} catch (MissingEnvironmentException e) {
// NOP
} catch (IllegalStateException e) { // depends on control dependency: [catch], data = [none]
allMissEnvironment = false;
} // depends on control dependency: [catch], data = [none]
}
if (allMissEnvironment) {
throw new MissingEnvironmentException(environment.getName());
}
throw new IllegalStateException();
} } |
public class class_name {
@Override
public Set<URI> getMsmType(URI elementUri) {
if (elementUri == null || !elementUri.isAbsolute()) {
log.warn("The Element URI is either absent or relative. Provide an absolute URI");
return ImmutableSet.of();
}
URI graphUri;
try {
graphUri = getGraphUriForElement(elementUri);
} catch (URISyntaxException e) {
log.warn("The namespace of the URI of the message content is incorrect.", e);
return ImmutableSet.of();
}
if (graphUri == null) {
log.warn("Could not obtain a graph URI for the element. The URI may not be managed by the server - " + elementUri);
return ImmutableSet.of();
}
String queryStr = new StringBuilder()
.append("SELECT * WHERE { \n")
.append(" GRAPH <").append(graphUri.toASCIIString()).append("> { \n")
.append("<").append(elementUri.toASCIIString()).append("> <").append(RDF.type.getURI()).append("> ?type .")
.append("FILTER(STRSTARTS(STR(?type), \"").append(MSM.NAMESPACE.getURI()).append("\"))")
.append(" } \n ")
.append("} \n ")
.toString();
return this.graphStoreManager.listResourcesByQuery(queryStr, "type");
} } | public class class_name {
@Override
public Set<URI> getMsmType(URI elementUri) {
if (elementUri == null || !elementUri.isAbsolute()) {
log.warn("The Element URI is either absent or relative. Provide an absolute URI"); // depends on control dependency: [if], data = [none]
return ImmutableSet.of(); // depends on control dependency: [if], data = [none]
}
URI graphUri;
try {
graphUri = getGraphUriForElement(elementUri); // depends on control dependency: [try], data = [none]
} catch (URISyntaxException e) {
log.warn("The namespace of the URI of the message content is incorrect.", e);
return ImmutableSet.of();
} // depends on control dependency: [catch], data = [none]
if (graphUri == null) {
log.warn("Could not obtain a graph URI for the element. The URI may not be managed by the server - " + elementUri); // depends on control dependency: [if], data = [none]
return ImmutableSet.of(); // depends on control dependency: [if], data = [none]
}
String queryStr = new StringBuilder()
.append("SELECT * WHERE { \n")
.append(" GRAPH <").append(graphUri.toASCIIString()).append("> { \n")
.append("<").append(elementUri.toASCIIString()).append("> <").append(RDF.type.getURI()).append("> ?type .")
.append("FILTER(STRSTARTS(STR(?type), \"").append(MSM.NAMESPACE.getURI()).append("\"))")
.append(" } \n ")
.append("} \n ")
.toString();
return this.graphStoreManager.listResourcesByQuery(queryStr, "type");
} } |
public class class_name {
@SuppressWarnings("unchecked")
public Map<String, Object> getOptionMap(String optName) {
Object optValue = m_options.get(optName);
if (optValue == null) {
return null;
}
if (!(optValue instanceof Map)) {
throw new IllegalArgumentException("Tenant option '" + optName + "' should be a map: " + optValue);
}
return (Map<String, Object>)optValue;
} } | public class class_name {
@SuppressWarnings("unchecked")
public Map<String, Object> getOptionMap(String optName) {
Object optValue = m_options.get(optName);
if (optValue == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (!(optValue instanceof Map)) {
throw new IllegalArgumentException("Tenant option '" + optName + "' should be a map: " + optValue);
}
return (Map<String, Object>)optValue;
} } |
public class class_name {
public void setAverageVisible(final boolean VISIBLE) {
if (null == averageVisible) {
_averageVisible = VISIBLE;
fireTileEvent(VISIBILITY_EVENT);
} else {
averageVisible.set(VISIBLE);
}
} } | public class class_name {
public void setAverageVisible(final boolean VISIBLE) {
if (null == averageVisible) {
_averageVisible = VISIBLE; // depends on control dependency: [if], data = [none]
fireTileEvent(VISIBILITY_EVENT); // depends on control dependency: [if], data = [none]
} else {
averageVisible.set(VISIBLE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String contents()
{
StringBuilder builder = new StringBuilder();
builder.append("{");
for (Map.Entry<RowPosition, AtomicBTreeColumns> entry : rows.entrySet())
{
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append(", ");
}
builder.append("}");
return builder.toString();
} } | public class class_name {
public String contents()
{
StringBuilder builder = new StringBuilder();
builder.append("{");
for (Map.Entry<RowPosition, AtomicBTreeColumns> entry : rows.entrySet())
{
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append(", "); // depends on control dependency: [for], data = [entry]
}
builder.append("}");
return builder.toString();
} } |
public class class_name {
@Deprecated
public void setOption(int option,boolean value) {
if (value) {
options |= option;
} else {
options &= (~option);
}
norm2 = mode.getNormalizer2(options);
} } | public class class_name {
@Deprecated
public void setOption(int option,boolean value) {
if (value) {
options |= option; // depends on control dependency: [if], data = [none]
} else {
options &= (~option); // depends on control dependency: [if], data = [none]
}
norm2 = mode.getNormalizer2(options);
} } |
public class class_name {
static synchronized void clearLogContext() {
final LogContext embeddedLogContext = Holder.LOG_CONTEXT;
// Remove the configurator and clear the log context
final Configurator configurator = embeddedLogContext.getLogger("").detach(Configurator.ATTACHMENT_KEY);
// If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext
if (configurator instanceof PropertyConfigurator) {
final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();
clearLogContext(logContextConfiguration);
} else if (configurator instanceof LogContextConfiguration) {
clearLogContext((LogContextConfiguration) configurator);
} else {
// Remove all the handlers and close them as well as reset the loggers
final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());
for (String name : loggerNames) {
final Logger logger = embeddedLogContext.getLoggerIfExists(name);
if (logger != null) {
final Handler[] handlers = logger.clearHandlers();
if (handlers != null) {
for (Handler handler : handlers) {
handler.close();
}
}
logger.setFilter(null);
logger.setUseParentFilters(false);
logger.setUseParentHandlers(true);
logger.setLevel(Level.INFO);
}
}
}
} } | public class class_name {
static synchronized void clearLogContext() {
final LogContext embeddedLogContext = Holder.LOG_CONTEXT;
// Remove the configurator and clear the log context
final Configurator configurator = embeddedLogContext.getLogger("").detach(Configurator.ATTACHMENT_KEY);
// If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext
if (configurator instanceof PropertyConfigurator) {
final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();
clearLogContext(logContextConfiguration); // depends on control dependency: [if], data = [none]
} else if (configurator instanceof LogContextConfiguration) {
clearLogContext((LogContextConfiguration) configurator); // depends on control dependency: [if], data = [none]
} else {
// Remove all the handlers and close them as well as reset the loggers
final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());
for (String name : loggerNames) {
final Logger logger = embeddedLogContext.getLoggerIfExists(name);
if (logger != null) {
final Handler[] handlers = logger.clearHandlers();
if (handlers != null) {
for (Handler handler : handlers) {
handler.close(); // depends on control dependency: [for], data = [handler]
}
}
logger.setFilter(null); // depends on control dependency: [if], data = [null)]
logger.setUseParentFilters(false); // depends on control dependency: [if], data = [none]
logger.setUseParentHandlers(true); // depends on control dependency: [if], data = [none]
logger.setLevel(Level.INFO); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@Around(value = "availableBrowsersCallPointcut()")
public Object availableBrowsersCalls(ProceedingJoinPoint pjp)
throws Throwable {
if (pjp.getArgs().length > 0) {
if (pjp.getArgs()[0] instanceof ITestContext) {
if (Arrays.asList(((ITestContext) pjp.getArgs()[0]).getIncludedGroups()).contains("mobile")) {
return pjp.proceed();
}
}
}
if (!"".equals(System.getProperty("FORCE_BROWSER", ""))) {
List<String[]> lData = Lists.newArrayList();
lData.add(new String[]{System.getProperty("FORCE_BROWSER")});
logger.debug("Forcing browser to {}",
System.getProperty("FORCE_BROWSER"));
return lData.iterator();
}
return pjp.proceed();
} } | public class class_name {
@Around(value = "availableBrowsersCallPointcut()")
public Object availableBrowsersCalls(ProceedingJoinPoint pjp)
throws Throwable {
if (pjp.getArgs().length > 0) {
if (pjp.getArgs()[0] instanceof ITestContext) {
if (Arrays.asList(((ITestContext) pjp.getArgs()[0]).getIncludedGroups()).contains("mobile")) {
return pjp.proceed(); // depends on control dependency: [if], data = [none]
}
}
}
if (!"".equals(System.getProperty("FORCE_BROWSER", ""))) {
List<String[]> lData = Lists.newArrayList();
lData.add(new String[]{System.getProperty("FORCE_BROWSER")});
logger.debug("Forcing browser to {}",
System.getProperty("FORCE_BROWSER"));
return lData.iterator();
}
return pjp.proceed();
} } |
public class class_name {
@NonNull
public IconicsAnimationProcessor interpolator(@NonNull TimeInterpolator interpolator) {
if (interpolator != null) {
mInterpolator = interpolator;
} else {
mInterpolator = sDefaultInterpolator;
}
return this;
} } | public class class_name {
@NonNull
public IconicsAnimationProcessor interpolator(@NonNull TimeInterpolator interpolator) {
if (interpolator != null) {
mInterpolator = interpolator; // depends on control dependency: [if], data = [none]
} else {
mInterpolator = sDefaultInterpolator; // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static void multiply( GrayU8 input , double value , GrayU8 output ) {
output.reshape(input.width,input.height);
int columns = input.width;
if(BoofConcurrency.USE_CONCURRENT ) {
ImplPixelMath_MT.multiplyU_A(input.data,input.startIndex,input.stride,value ,
output.data,output.startIndex,output.stride,
input.height,columns);
} else {
ImplPixelMath.multiplyU_A(input.data,input.startIndex,input.stride,value ,
output.data,output.startIndex,output.stride,
input.height,columns);
}
} } | public class class_name {
public static void multiply( GrayU8 input , double value , GrayU8 output ) {
output.reshape(input.width,input.height);
int columns = input.width;
if(BoofConcurrency.USE_CONCURRENT ) {
ImplPixelMath_MT.multiplyU_A(input.data,input.startIndex,input.stride,value ,
output.data,output.startIndex,output.stride,
input.height,columns); // depends on control dependency: [if], data = [none]
} else {
ImplPixelMath.multiplyU_A(input.data,input.startIndex,input.stride,value ,
output.data,output.startIndex,output.stride,
input.height,columns); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
super.validateParameter(parameterName, value);
if (value.isDefined() && value.getType() != ModelType.EXPRESSION) {
String val = value.asString();
try {
PredicateParser.parse(val, getClass().getClassLoader());
} catch (Exception e) {
throw new OperationFailedException(UndertowLogger.ROOT_LOGGER.predicateNotValid(val, e.getMessage()), e);
}
}
} } | public class class_name {
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
super.validateParameter(parameterName, value);
if (value.isDefined() && value.getType() != ModelType.EXPRESSION) {
String val = value.asString();
try {
PredicateParser.parse(val, getClass().getClassLoader()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new OperationFailedException(UndertowLogger.ROOT_LOGGER.predicateNotValid(val, e.getMessage()), e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public Task removeTask(ExecutionAttemptID executionAttemptID) {
checkInit();
TaskSlotMapping taskSlotMapping = taskSlotMappings.remove(executionAttemptID);
if (taskSlotMapping != null) {
Task task = taskSlotMapping.getTask();
TaskSlot taskSlot = taskSlotMapping.getTaskSlot();
taskSlot.remove(task.getExecutionId());
if (taskSlot.isReleasing() && taskSlot.isEmpty()) {
slotActions.freeSlot(taskSlot.getAllocationId());
}
return task;
} else {
return null;
}
} } | public class class_name {
public Task removeTask(ExecutionAttemptID executionAttemptID) {
checkInit();
TaskSlotMapping taskSlotMapping = taskSlotMappings.remove(executionAttemptID);
if (taskSlotMapping != null) {
Task task = taskSlotMapping.getTask();
TaskSlot taskSlot = taskSlotMapping.getTaskSlot();
taskSlot.remove(task.getExecutionId()); // depends on control dependency: [if], data = [none]
if (taskSlot.isReleasing() && taskSlot.isEmpty()) {
slotActions.freeSlot(taskSlot.getAllocationId()); // depends on control dependency: [if], data = [none]
}
return task; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private List<TreeNode> getSelected(TreeNode parent) {
List<TreeNode> result = new ArrayList<>();
for (TreeNode n : parent.getChildren()) {
if (n.isSelected()) {
result.add(n);
}
result.addAll(getSelected(n));
}
return result;
} } | public class class_name {
private List<TreeNode> getSelected(TreeNode parent) {
List<TreeNode> result = new ArrayList<>();
for (TreeNode n : parent.getChildren()) {
if (n.isSelected()) {
result.add(n); // depends on control dependency: [if], data = [none]
}
result.addAll(getSelected(n)); // depends on control dependency: [for], data = [n]
}
return result;
} } |
public class class_name {
public static ComputationGraphConfiguration.GraphBuilder appendGraph(
ComputationGraphConfiguration.GraphBuilder graph, String moduleLayerName, int inputSize,
int[] kernelSize, int[] kernelStride, int[] outputSize, int[] reduceSize,
SubsamplingLayer.PoolingType poolingType, int pNorm, int poolSize, int poolStride,
Activation transferFunction, String inputLayer) {
// 1x1 reduce -> nxn conv
for (int i = 0; i < kernelSize.length; i++) {
graph.addLayer(getModuleName(moduleLayerName) + "-cnn1-" + i, conv1x1(inputSize, reduceSize[i], 0.2),
inputLayer);
graph.addLayer(getModuleName(moduleLayerName) + "-batch1-" + i, batchNorm(reduceSize[i], reduceSize[i]),
getModuleName(moduleLayerName) + "-cnn1-" + i);
graph.addLayer(getModuleName(moduleLayerName) + "-transfer1-" + i,
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch1-" + i);
graph.addLayer(getModuleName(moduleLayerName) + "-reduce1-" + i,
convNxN(reduceSize[i], outputSize[i], kernelSize[i], kernelStride[i], true),
getModuleName(moduleLayerName) + "-transfer1-" + i);
graph.addLayer(getModuleName(moduleLayerName) + "-batch2-" + i, batchNorm(outputSize[i], outputSize[i]),
getModuleName(moduleLayerName) + "-reduce1-" + i);
graph.addLayer(getModuleName(moduleLayerName) + "-transfer2-" + i,
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch2-" + i);
}
// pool -> 1x1 conv
int i = kernelSize.length;
try {
int checkIndex = reduceSize[i];
switch (poolingType) {
case AVG:
graph.addLayer(getModuleName(moduleLayerName) + "-pool1", avgPoolNxN(poolSize, poolStride),
inputLayer);
break;
case MAX:
graph.addLayer(getModuleName(moduleLayerName) + "-pool1", maxPoolNxN(poolSize, poolStride),
inputLayer);
break;
case PNORM:
if (pNorm <= 0)
throw new IllegalArgumentException("p-norm must be greater than zero.");
graph.addLayer(getModuleName(moduleLayerName) + "-pool1", pNormNxN(pNorm, poolSize, poolStride),
inputLayer);
break;
default:
throw new IllegalStateException(
"You must specify a valid pooling type of avg or max for Inception module.");
}
graph.addLayer(getModuleName(moduleLayerName) + "-cnn2", convNxNreduce(inputSize, reduceSize[i], 1),
getModuleName(moduleLayerName) + "-pool1");
graph.addLayer(getModuleName(moduleLayerName) + "-batch3", batchNorm(reduceSize[i], reduceSize[i]),
getModuleName(moduleLayerName) + "-cnn2");
graph.addLayer(getModuleName(moduleLayerName) + "-transfer3",
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch3");
} catch (IndexOutOfBoundsException e) {
}
i++;
// reduce
try {
graph.addLayer(getModuleName(moduleLayerName) + "-reduce2", convNxNreduce(inputSize, reduceSize[i], 1),
inputLayer);
graph.addLayer(getModuleName(moduleLayerName) + "-batch4", batchNorm(reduceSize[i], reduceSize[i]),
getModuleName(moduleLayerName) + "-reduce2");
graph.addLayer(getModuleName(moduleLayerName) + "-transfer4",
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch4");
} catch (IndexOutOfBoundsException e) {
}
// TODO: there's a better way to do this
if (kernelSize.length == 1 && reduceSize.length == 3) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer3",
getModuleName(moduleLayerName) + "-transfer4");
} else if (kernelSize.length == 2 && reduceSize.length == 2) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer2-1");
} else if (kernelSize.length == 2 && reduceSize.length == 3) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer2-1",
getModuleName(moduleLayerName) + "-transfer3");
} else if (kernelSize.length == 2 && reduceSize.length == 4) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer2-1",
getModuleName(moduleLayerName) + "-transfer3",
getModuleName(moduleLayerName) + "-transfer4");
} else
throw new IllegalStateException(
"Only kernel of shape 1 or 2 and a reduce shape between 2 and 4 is supported.");
return graph;
} } | public class class_name {
public static ComputationGraphConfiguration.GraphBuilder appendGraph(
ComputationGraphConfiguration.GraphBuilder graph, String moduleLayerName, int inputSize,
int[] kernelSize, int[] kernelStride, int[] outputSize, int[] reduceSize,
SubsamplingLayer.PoolingType poolingType, int pNorm, int poolSize, int poolStride,
Activation transferFunction, String inputLayer) {
// 1x1 reduce -> nxn conv
for (int i = 0; i < kernelSize.length; i++) {
graph.addLayer(getModuleName(moduleLayerName) + "-cnn1-" + i, conv1x1(inputSize, reduceSize[i], 0.2),
inputLayer); // depends on control dependency: [for], data = [none]
graph.addLayer(getModuleName(moduleLayerName) + "-batch1-" + i, batchNorm(reduceSize[i], reduceSize[i]),
getModuleName(moduleLayerName) + "-cnn1-" + i); // depends on control dependency: [for], data = [i]
graph.addLayer(getModuleName(moduleLayerName) + "-transfer1-" + i,
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch1-" + i); // depends on control dependency: [for], data = [i]
graph.addLayer(getModuleName(moduleLayerName) + "-reduce1-" + i,
convNxN(reduceSize[i], outputSize[i], kernelSize[i], kernelStride[i], true),
getModuleName(moduleLayerName) + "-transfer1-" + i); // depends on control dependency: [for], data = [i]
graph.addLayer(getModuleName(moduleLayerName) + "-batch2-" + i, batchNorm(outputSize[i], outputSize[i]),
getModuleName(moduleLayerName) + "-reduce1-" + i); // depends on control dependency: [for], data = [i]
graph.addLayer(getModuleName(moduleLayerName) + "-transfer2-" + i,
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch2-" + i); // depends on control dependency: [for], data = [i]
}
// pool -> 1x1 conv
int i = kernelSize.length;
try {
int checkIndex = reduceSize[i];
switch (poolingType) {
case AVG:
graph.addLayer(getModuleName(moduleLayerName) + "-pool1", avgPoolNxN(poolSize, poolStride),
inputLayer);
break;
case MAX:
graph.addLayer(getModuleName(moduleLayerName) + "-pool1", maxPoolNxN(poolSize, poolStride),
inputLayer);
break;
case PNORM:
if (pNorm <= 0)
throw new IllegalArgumentException("p-norm must be greater than zero.");
graph.addLayer(getModuleName(moduleLayerName) + "-pool1", pNormNxN(pNorm, poolSize, poolStride),
inputLayer);
break;
default:
throw new IllegalStateException(
"You must specify a valid pooling type of avg or max for Inception module.");
}
graph.addLayer(getModuleName(moduleLayerName) + "-cnn2", convNxNreduce(inputSize, reduceSize[i], 1),
getModuleName(moduleLayerName) + "-pool1"); // depends on control dependency: [try], data = [none]
graph.addLayer(getModuleName(moduleLayerName) + "-batch3", batchNorm(reduceSize[i], reduceSize[i]),
getModuleName(moduleLayerName) + "-cnn2"); // depends on control dependency: [try], data = [none]
graph.addLayer(getModuleName(moduleLayerName) + "-transfer3",
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch3"); // depends on control dependency: [try], data = [none]
} catch (IndexOutOfBoundsException e) {
} // depends on control dependency: [catch], data = [none]
i++;
// reduce
try {
graph.addLayer(getModuleName(moduleLayerName) + "-reduce2", convNxNreduce(inputSize, reduceSize[i], 1),
inputLayer); // depends on control dependency: [try], data = [none]
graph.addLayer(getModuleName(moduleLayerName) + "-batch4", batchNorm(reduceSize[i], reduceSize[i]),
getModuleName(moduleLayerName) + "-reduce2"); // depends on control dependency: [try], data = [none]
graph.addLayer(getModuleName(moduleLayerName) + "-transfer4",
new ActivationLayer.Builder().activation(transferFunction).build(),
getModuleName(moduleLayerName) + "-batch4"); // depends on control dependency: [try], data = [none]
} catch (IndexOutOfBoundsException e) {
} // depends on control dependency: [catch], data = [none]
// TODO: there's a better way to do this
if (kernelSize.length == 1 && reduceSize.length == 3) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer3",
getModuleName(moduleLayerName) + "-transfer4"); // depends on control dependency: [if], data = [none]
} else if (kernelSize.length == 2 && reduceSize.length == 2) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer2-1"); // depends on control dependency: [if], data = [none]
} else if (kernelSize.length == 2 && reduceSize.length == 3) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer2-1",
getModuleName(moduleLayerName) + "-transfer3"); // depends on control dependency: [if], data = [none]
} else if (kernelSize.length == 2 && reduceSize.length == 4) {
graph.addVertex(getModuleName(moduleLayerName), new MergeVertex(),
getModuleName(moduleLayerName) + "-transfer2-0",
getModuleName(moduleLayerName) + "-transfer2-1",
getModuleName(moduleLayerName) + "-transfer3",
getModuleName(moduleLayerName) + "-transfer4"); // depends on control dependency: [if], data = [none]
} else
throw new IllegalStateException(
"Only kernel of shape 1 or 2 and a reduce shape between 2 and 4 is supported.");
return graph;
} } |
public class class_name {
void checkClosed() throws FetchException {
TransactionScope<Txn> scope = localTransactionScope();
// Lock out shutdown task.
scope.getLock().lock();
try {
if (mPrimaryDatabase == null) {
// If shutting down, this will force us to block forever.
try {
scope.getTxn();
} catch (Exception e) {
// Don't care.
}
// Okay, not shutting down, so throw exception.
throw new FetchException("Repository closed");
}
} finally {
scope.getLock().unlock();
}
} } | public class class_name {
void checkClosed() throws FetchException {
TransactionScope<Txn> scope = localTransactionScope();
// Lock out shutdown task.
scope.getLock().lock();
try {
if (mPrimaryDatabase == null) {
// If shutting down, this will force us to block forever.
try {
scope.getTxn();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
// Don't care.
}
// depends on control dependency: [catch], data = [none]
// Okay, not shutting down, so throw exception.
throw new FetchException("Repository closed");
}
} finally {
scope.getLock().unlock();
}
} } |
public class class_name {
public final AbstractItem next(int fromIndex) throws MessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "next( fromIndex)"+fromIndex);
AbstractItem found = null;
for (int priority = Priorities.HIGHEST_PRIORITY;
null == found && priority >= Priorities.LOWEST_PRIORITY;
priority--)
{
Subcursor subCursor = _getSubCursor(priority);
if (null != subCursor)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Search on subcursor for priority: "+priority);
if (AbstractItem.NO_LOCK_ID == _lockID)
{
found = subCursor.next(_allowUnavailableItems,fromIndex);// 673411
}
else
{
found = subCursor.next(_lockID,fromIndex); //673411
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "next( fromIndex)"+fromIndex, found);
return found;
} } | public class class_name {
public final AbstractItem next(int fromIndex) throws MessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "next( fromIndex)"+fromIndex);
AbstractItem found = null;
for (int priority = Priorities.HIGHEST_PRIORITY;
null == found && priority >= Priorities.LOWEST_PRIORITY;
priority--)
{
Subcursor subCursor = _getSubCursor(priority);
if (null != subCursor)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Search on subcursor for priority: "+priority);
if (AbstractItem.NO_LOCK_ID == _lockID)
{
found = subCursor.next(_allowUnavailableItems,fromIndex);// 673411 // depends on control dependency: [if], data = [none]
}
else
{
found = subCursor.next(_lockID,fromIndex); //673411 // depends on control dependency: [if], data = [none]
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "next( fromIndex)"+fromIndex, found);
return found;
} } |
public class class_name {
public static int binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
N.checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k >= int_biggestBinomials.length || n > int_biggestBinomials[k]) {
return Integer.MAX_VALUE;
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
long result = 1;
for (int i = 0; i < k; i++) {
result *= n - i;
result /= i + 1;
}
return (int) result;
}
} } | public class class_name {
public static int binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
N.checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
// depends on control dependency: [if], data = [none]
}
if (k >= int_biggestBinomials.length || n > int_biggestBinomials[k]) {
return Integer.MAX_VALUE;
// depends on control dependency: [if], data = [none]
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
long result = 1;
for (int i = 0; i < k; i++) {
result *= n - i;
// depends on control dependency: [for], data = [i]
result /= i + 1;
// depends on control dependency: [for], data = [i]
}
return (int) result;
}
} } |
public class class_name {
private void processAlterColumnType(Table table, ColumnSchema oldCol,
boolean fullDefinition) {
ColumnSchema newCol;
if (oldCol.isGenerated()) {
throw Error.error(ErrorCode.X_42561);
}
if (fullDefinition) {
HsqlArrayList list = new HsqlArrayList();
Constraint c = table.getPrimaryConstraint();
if (c == null) {
c = new Constraint(null, true, null, Constraint.TEMP);
}
list.add(c);
newCol = readColumnDefinitionOrNull(table, oldCol.getName(), list);
if (newCol == null) {
throw Error.error(ErrorCode.X_42000);
}
if (oldCol.isIdentity() && newCol.isIdentity()) {
throw Error.error(ErrorCode.X_42525);
}
if (list.size() > 1) {
// A VoltDB extension to support establishing or preserving the NOT NULL
// attribute of an altered column.
if (voltDBacceptNotNullConstraint(list)) {
newCol.setNullable(false);
} else
// End of VoltDB extension
throw Error.error(ErrorCode.X_42524);
}
} else {
Type type = readTypeDefinition(true);
if (oldCol.isIdentity()) {
if (!type.isIntegralType()) {
throw Error.error(ErrorCode.X_42561);
}
}
newCol = oldCol.duplicate();
newCol.setType(type);
}
TableWorks tw = new TableWorks(session, table);
tw.retypeColumn(oldCol, newCol);
} } | public class class_name {
private void processAlterColumnType(Table table, ColumnSchema oldCol,
boolean fullDefinition) {
ColumnSchema newCol;
if (oldCol.isGenerated()) {
throw Error.error(ErrorCode.X_42561);
}
if (fullDefinition) {
HsqlArrayList list = new HsqlArrayList();
Constraint c = table.getPrimaryConstraint();
if (c == null) {
c = new Constraint(null, true, null, Constraint.TEMP); // depends on control dependency: [if], data = [none]
}
list.add(c); // depends on control dependency: [if], data = [none]
newCol = readColumnDefinitionOrNull(table, oldCol.getName(), list); // depends on control dependency: [if], data = [none]
if (newCol == null) {
throw Error.error(ErrorCode.X_42000);
}
if (oldCol.isIdentity() && newCol.isIdentity()) {
throw Error.error(ErrorCode.X_42525);
}
if (list.size() > 1) {
// A VoltDB extension to support establishing or preserving the NOT NULL
// attribute of an altered column.
if (voltDBacceptNotNullConstraint(list)) {
newCol.setNullable(false); // depends on control dependency: [if], data = [none]
} else
// End of VoltDB extension
throw Error.error(ErrorCode.X_42524);
}
} else {
Type type = readTypeDefinition(true);
if (oldCol.isIdentity()) {
if (!type.isIntegralType()) {
throw Error.error(ErrorCode.X_42561);
}
}
newCol = oldCol.duplicate(); // depends on control dependency: [if], data = [none]
newCol.setType(type); // depends on control dependency: [if], data = [none]
}
TableWorks tw = new TableWorks(session, table);
tw.retypeColumn(oldCol, newCol);
} } |
public class class_name {
private static Method[] getDeclaredMethods(Class<?> clazz) {
Method[] result;
Method[] declaredMethods = clazz.getDeclaredMethods();
List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz);
if (defaultMethods != null) {
result = new Method[declaredMethods.length + defaultMethods.size()];
System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length);
int index = declaredMethods.length;
for (Method defaultMethod : defaultMethods) {
result[index] = defaultMethod;
index++;
}
} else {
result = declaredMethods;
}
return result;
} } | public class class_name {
private static Method[] getDeclaredMethods(Class<?> clazz) {
Method[] result;
Method[] declaredMethods = clazz.getDeclaredMethods();
List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz);
if (defaultMethods != null) {
result = new Method[declaredMethods.length + defaultMethods.size()]; // depends on control dependency: [if], data = [none]
System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length); // depends on control dependency: [if], data = [none]
int index = declaredMethods.length;
for (Method defaultMethod : defaultMethods) {
result[index] = defaultMethod; // depends on control dependency: [for], data = [defaultMethod]
index++; // depends on control dependency: [for], data = [none]
}
} else {
result = declaredMethods; // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public GetReservationCoverageRequest withMetrics(String... metrics) {
if (this.metrics == null) {
setMetrics(new java.util.ArrayList<String>(metrics.length));
}
for (String ele : metrics) {
this.metrics.add(ele);
}
return this;
} } | public class class_name {
public GetReservationCoverageRequest withMetrics(String... metrics) {
if (this.metrics == null) {
setMetrics(new java.util.ArrayList<String>(metrics.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : metrics) {
this.metrics.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public String url(Map<String, ?> parametersMap)
{
StringBuilder queryStringBuilder = new StringBuilder();
for (Map.Entry<String, ?> entry : parametersMap.entrySet()) {
if (entry.getKey() == null) {
// Skip the parameter if its name is null.
continue;
}
String cleanKey = this.url(entry.getKey());
Object mapValues = entry.getValue();
if (mapValues != null && mapValues.getClass().isArray()) {
// A parameter with multiple values.
Object[] values = (Object[]) mapValues;
for (Object value : values) {
addQueryStringPair(cleanKey, value, queryStringBuilder);
}
} else if (mapValues != null && Collection.class.isAssignableFrom(mapValues.getClass())) {
// A parameter with multiple values.
Collection<?> values = (Collection<?>) mapValues;
for (Object value : values) {
addQueryStringPair(cleanKey, value, queryStringBuilder);
}
} else {
addQueryStringPair(cleanKey, mapValues, queryStringBuilder);
}
}
return queryStringBuilder.toString();
} } | public class class_name {
public String url(Map<String, ?> parametersMap)
{
StringBuilder queryStringBuilder = new StringBuilder();
for (Map.Entry<String, ?> entry : parametersMap.entrySet()) {
if (entry.getKey() == null) {
// Skip the parameter if its name is null.
continue;
}
String cleanKey = this.url(entry.getKey());
Object mapValues = entry.getValue();
if (mapValues != null && mapValues.getClass().isArray()) {
// A parameter with multiple values.
Object[] values = (Object[]) mapValues;
for (Object value : values) {
addQueryStringPair(cleanKey, value, queryStringBuilder); // depends on control dependency: [for], data = [value]
}
} else if (mapValues != null && Collection.class.isAssignableFrom(mapValues.getClass())) {
// A parameter with multiple values.
Collection<?> values = (Collection<?>) mapValues;
for (Object value : values) {
addQueryStringPair(cleanKey, value, queryStringBuilder); // depends on control dependency: [for], data = [value]
}
} else {
addQueryStringPair(cleanKey, mapValues, queryStringBuilder); // depends on control dependency: [if], data = [none]
}
}
return queryStringBuilder.toString();
} } |
public class class_name {
public java.util.List<String> getCheckerIpRanges() {
if (checkerIpRanges == null) {
checkerIpRanges = new com.amazonaws.internal.SdkInternalList<String>();
}
return checkerIpRanges;
} } | public class class_name {
public java.util.List<String> getCheckerIpRanges() {
if (checkerIpRanges == null) {
checkerIpRanges = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return checkerIpRanges;
} } |
public class class_name {
public void startRecovery() throws Exception {
if (tc.isEntryEnabled())
Tr.entry(tc, "startRecovery");
// Note that _recoverDBLogStarted is always false if we are logging to a filesystem.
// If we are logging to an RDBMS, then we will start the TM which will spin off a thread
// to perform recovery processing. Unfortunately, this latter thread, as part of
// DataSource processing, will also attempt to start the TM as a result of registering
// ResourceInfo. This flag guards against that eventuality.
if (!_recoverDBLogStarted) {
synchronized (this) {
TMHelper.setTMService(this);
// Initalize trace
Tr.reinitializeTracer();
// Test whether we are logging to an RDBMS
final ConfigurationProvider cp = ConfigurationProviderManager.getConfigurationProvider();
if (cp != null && cp.isSQLRecoveryLog()) {
_recoverDBLogStarted = true;
if (tc.isDebugEnabled())
Tr.debug(tc, "Tran Logging to an RDBMS set recoverDBLogStarted flag");
}
if (getState() != TMService.TMStates.INACTIVE && getState() != TMService.TMStates.STOPPED) {
if (tc.isEntryEnabled())
Tr.exit(tc, "start", "Already started");
return;
}
setResyncException(null);
_recLogService = new RecLogServiceImpl();
// Create the Recovery Director
_recoveryDirector = RecoveryDirectorFactory.createRecoveryDirector();
// For cloud support, retrieve recovery identity from the configuration if it is defined.
if (cp != null) {
_recoveryIdentity = cp.getRecoveryIdentity();
if (tc.isDebugEnabled())
Tr.debug(tc, "RecoveryIdentity is ", _recoveryIdentity);
_recoveryGroup = cp.getRecoveryGroup();
if (tc.isDebugEnabled())
Tr.debug(tc, "recoveryGroup is ", _recoveryGroup);
}
//Add this guard to ensure that we have sufficient config to drive recovery.
boolean allowRecovery = true;
if (cp == null) {
// A null ConfigurationProvider cannot be tolerated.
allowRecovery = false;
if (tc.isDebugEnabled())
Tr.debug(tc, "Configuration Provider is null");
} else {
String sName = cp.getServerName();
if (tc.isDebugEnabled())
Tr.debug(tc, "Retrieved server name " + sName);
if (sName == null || sName.isEmpty()) {
// An empty string serverName suggests that the Location Service was unavailable
allowRecovery = false;
}
}
if (!allowRecovery) {
try {
shutdown();
} catch (RuntimeException e) {
FFDCFilter.processException(e, "com.ibm.tx.jta.util.TxTMHelper.start", "279", this);
}
final Throwable se = new SystemException();
if (tc.isEntryEnabled())
Tr.exit(tc, "start", se);
throw (SystemException) se;
}
if (_recoveryIdentity != null && !_recoveryIdentity.isEmpty()) {
_recLogService.initialize(_recoveryIdentity);
} else {
String serverName = null;
if (cp != null) {
serverName = cp.getServerName();
}
_recLogService.initialize(serverName);
}
TxRecoveryAgentImpl txAgent = createRecoveryAgent(_recoveryDirector);
// For now I'll code such that the presence of a RecoveryIdentity attribute says that we are operating in the Cloud
if (_recoveryIdentity != null && !_recoveryIdentity.isEmpty()) {
_recLogService.setPeerRecoverySupported(true);
txAgent.setPeerRecoverySupported(true);
// Override the disable2PC property if it has been set
TransactionImpl.setDisable2PCDefault(false);
Tr.audit(tc, "WTRN0108I: Server with identity " + _recoveryIdentity + " is monitoring its peers for Transaction Peer Recovery");
}
//TODO: We don't currently use the recoveryGroup....but in due course we will, so retain this
// code snippet
if (_recoveryGroup != null && !_recoveryGroup.isEmpty()) {
txAgent.setRecoveryGroup(_recoveryGroup);
_recLogService.setRecoveryGroup(_recoveryGroup);
}
setRecoveryAgent(txAgent);
// Fake recovery only mode if we're to wait
RecoveryManager._waitForRecovery = _waitForRecovery;
// Kick off recovery
_recLogService.startRecovery(_recoveryLogFactory);
// Defect RTC 99071. Don't make the STATE transition until recovery has been fully
// initialised, after replay completion but before resync completion.
setState(TMService.TMStates.RECOVERING);
if (_waitForRecovery) {
if (tc.isDebugEnabled())
Tr.debug(tc, "Waiting for completion of asynchronous recovery");
_asyncRecoverySemaphore.waitEvent();
if (tc.isDebugEnabled())
Tr.debug(tc, "Asynchronous recovery is complete");
if (_resyncException != null) {
try {
shutdown();
} catch (RuntimeException e) {
FFDCFilter.processException(e, "com.ibm.tx.jta.util.TxTMHelper.start", "137", this);
}
final Throwable se = new SystemException().initCause(_resyncException);
if (tc.isEntryEnabled())
Tr.exit(tc, "start", se);
throw (SystemException) se;
}
} // eof if waitForRecovery
} // eof synchronized block
} // eof if !_recoverDBLogStarted
else if (tc.isDebugEnabled())
Tr.debug(tc, "Tran Logging to an RDBMS and START processing is in progress");
if (tc.isEntryEnabled())
Tr.exit(tc, "startRecovery");
} } | public class class_name {
public void startRecovery() throws Exception {
if (tc.isEntryEnabled())
Tr.entry(tc, "startRecovery");
// Note that _recoverDBLogStarted is always false if we are logging to a filesystem.
// If we are logging to an RDBMS, then we will start the TM which will spin off a thread
// to perform recovery processing. Unfortunately, this latter thread, as part of
// DataSource processing, will also attempt to start the TM as a result of registering
// ResourceInfo. This flag guards against that eventuality.
if (!_recoverDBLogStarted) {
synchronized (this) {
TMHelper.setTMService(this);
// Initalize trace
Tr.reinitializeTracer();
// Test whether we are logging to an RDBMS
final ConfigurationProvider cp = ConfigurationProviderManager.getConfigurationProvider();
if (cp != null && cp.isSQLRecoveryLog()) {
_recoverDBLogStarted = true; // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled())
Tr.debug(tc, "Tran Logging to an RDBMS set recoverDBLogStarted flag");
}
if (getState() != TMService.TMStates.INACTIVE && getState() != TMService.TMStates.STOPPED) {
if (tc.isEntryEnabled())
Tr.exit(tc, "start", "Already started");
return; // depends on control dependency: [if], data = [none]
}
setResyncException(null);
_recLogService = new RecLogServiceImpl();
// Create the Recovery Director
_recoveryDirector = RecoveryDirectorFactory.createRecoveryDirector();
// For cloud support, retrieve recovery identity from the configuration if it is defined.
if (cp != null) {
_recoveryIdentity = cp.getRecoveryIdentity(); // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled())
Tr.debug(tc, "RecoveryIdentity is ", _recoveryIdentity);
_recoveryGroup = cp.getRecoveryGroup(); // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled())
Tr.debug(tc, "recoveryGroup is ", _recoveryGroup);
}
//Add this guard to ensure that we have sufficient config to drive recovery.
boolean allowRecovery = true;
if (cp == null) {
// A null ConfigurationProvider cannot be tolerated.
allowRecovery = false; // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled())
Tr.debug(tc, "Configuration Provider is null");
} else {
String sName = cp.getServerName();
if (tc.isDebugEnabled())
Tr.debug(tc, "Retrieved server name " + sName);
if (sName == null || sName.isEmpty()) {
// An empty string serverName suggests that the Location Service was unavailable
allowRecovery = false; // depends on control dependency: [if], data = [none]
}
}
if (!allowRecovery) {
try {
shutdown(); // depends on control dependency: [try], data = [none]
} catch (RuntimeException e) {
FFDCFilter.processException(e, "com.ibm.tx.jta.util.TxTMHelper.start", "279", this);
} // depends on control dependency: [catch], data = [none]
final Throwable se = new SystemException();
if (tc.isEntryEnabled())
Tr.exit(tc, "start", se);
throw (SystemException) se;
}
if (_recoveryIdentity != null && !_recoveryIdentity.isEmpty()) {
_recLogService.initialize(_recoveryIdentity); // depends on control dependency: [if], data = [(_recoveryIdentity]
} else {
String serverName = null;
if (cp != null) {
serverName = cp.getServerName(); // depends on control dependency: [if], data = [none]
}
_recLogService.initialize(serverName); // depends on control dependency: [if], data = [none]
}
TxRecoveryAgentImpl txAgent = createRecoveryAgent(_recoveryDirector);
// For now I'll code such that the presence of a RecoveryIdentity attribute says that we are operating in the Cloud
if (_recoveryIdentity != null && !_recoveryIdentity.isEmpty()) {
_recLogService.setPeerRecoverySupported(true); // depends on control dependency: [if], data = [none]
txAgent.setPeerRecoverySupported(true); // depends on control dependency: [if], data = [none]
// Override the disable2PC property if it has been set
TransactionImpl.setDisable2PCDefault(false); // depends on control dependency: [if], data = [none]
Tr.audit(tc, "WTRN0108I: Server with identity " + _recoveryIdentity + " is monitoring its peers for Transaction Peer Recovery"); // depends on control dependency: [if], data = [none]
}
//TODO: We don't currently use the recoveryGroup....but in due course we will, so retain this
// code snippet
if (_recoveryGroup != null && !_recoveryGroup.isEmpty()) {
txAgent.setRecoveryGroup(_recoveryGroup); // depends on control dependency: [if], data = [(_recoveryGroup]
_recLogService.setRecoveryGroup(_recoveryGroup); // depends on control dependency: [if], data = [(_recoveryGroup]
}
setRecoveryAgent(txAgent);
// Fake recovery only mode if we're to wait
RecoveryManager._waitForRecovery = _waitForRecovery;
// Kick off recovery
_recLogService.startRecovery(_recoveryLogFactory);
// Defect RTC 99071. Don't make the STATE transition until recovery has been fully
// initialised, after replay completion but before resync completion.
setState(TMService.TMStates.RECOVERING);
if (_waitForRecovery) {
if (tc.isDebugEnabled())
Tr.debug(tc, "Waiting for completion of asynchronous recovery");
_asyncRecoverySemaphore.waitEvent(); // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled())
Tr.debug(tc, "Asynchronous recovery is complete");
if (_resyncException != null) {
try {
shutdown(); // depends on control dependency: [try], data = [none]
} catch (RuntimeException e) {
FFDCFilter.processException(e, "com.ibm.tx.jta.util.TxTMHelper.start", "137", this);
} // depends on control dependency: [catch], data = [none]
final Throwable se = new SystemException().initCause(_resyncException);
if (tc.isEntryEnabled())
Tr.exit(tc, "start", se);
throw (SystemException) se;
}
} // eof if waitForRecovery
} // eof synchronized block
} // eof if !_recoverDBLogStarted
else if (tc.isDebugEnabled())
Tr.debug(tc, "Tran Logging to an RDBMS and START processing is in progress");
if (tc.isEntryEnabled())
Tr.exit(tc, "startRecovery");
} } |
public class class_name {
public HpackHeaderField remove() {
HpackHeaderField removed = hpackHeaderFields[tail];
if (removed == null) {
return null;
}
size -= removed.size();
hpackHeaderFields[tail++] = null;
if (tail == hpackHeaderFields.length) {
tail = 0;
}
return removed;
} } | public class class_name {
public HpackHeaderField remove() {
HpackHeaderField removed = hpackHeaderFields[tail];
if (removed == null) {
return null; // depends on control dependency: [if], data = [none]
}
size -= removed.size();
hpackHeaderFields[tail++] = null;
if (tail == hpackHeaderFields.length) {
tail = 0; // depends on control dependency: [if], data = [none]
}
return removed;
} } |
public class class_name {
public ListKeysResult withKeys(KeyListEntry... keys) {
if (this.keys == null) {
setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList<KeyListEntry>(keys.length));
}
for (KeyListEntry ele : keys) {
this.keys.add(ele);
}
return this;
} } | public class class_name {
public ListKeysResult withKeys(KeyListEntry... keys) {
if (this.keys == null) {
setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList<KeyListEntry>(keys.length)); // depends on control dependency: [if], data = [none]
}
for (KeyListEntry ele : keys) {
this.keys.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private String getExtractQuery(String schema, String entity, String inputQuery) {
String inputColProjection = this.getInputColumnProjection();
String outputColProjection = this.getOutputColumnProjection();
String query = inputQuery;
if (query == null) {
// if input query is null, build the query from metadata
query = "SELECT " + outputColProjection + " FROM " + schema + "." + entity;
} else {
// replace input column projection with output column projection
if (StringUtils.isNotBlank(inputColProjection)) {
query = query.replace(inputColProjection, outputColProjection);
}
}
query = addOptionalWatermarkPredicate(query);
return query;
} } | public class class_name {
private String getExtractQuery(String schema, String entity, String inputQuery) {
String inputColProjection = this.getInputColumnProjection();
String outputColProjection = this.getOutputColumnProjection();
String query = inputQuery;
if (query == null) {
// if input query is null, build the query from metadata
query = "SELECT " + outputColProjection + " FROM " + schema + "." + entity; // depends on control dependency: [if], data = [none]
} else {
// replace input column projection with output column projection
if (StringUtils.isNotBlank(inputColProjection)) {
query = query.replace(inputColProjection, outputColProjection); // depends on control dependency: [if], data = [none]
}
}
query = addOptionalWatermarkPredicate(query);
return query;
} } |
public class class_name {
private BufferedImage downloadImage() throws Exception {
BufferedImage image = null;
InputStream in = null;
try { // first try reading with the default class
URL url = new URL(imageUrl);
HttpURLConnection conn = null;
boolean success = false;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(followRedirects);
conn.setConnectTimeout(connectionTimeout); // TO DO: add retries when connections times out
conn.setReadTimeout(readTimeout);
conn.connect();
success = true;
} catch (Exception e) {
//System.out.println("Connection related exception at url: " + imageUrl);
//throw e;
} finally {
if (!success) {
conn.disconnect();
}
}
success = false;
try {
in = conn.getInputStream();
success = true;
} catch (Exception e) {
/*System.out.println("Exception when getting the input stream from the connection at url: "
+ imageUrl);
throw e;*/
} finally {
if (!success) {
in.close();
}
}
image = ImageIO.read(in);
} catch (IllegalArgumentException e) {
// this exception is probably thrown because of a greyscale jpeg image
System.out.println("Exception: " + e.getMessage() + " | Image: " + imageUrl);
image = ImageIOGreyScale.read(in); // retry with the modified class
} catch (MalformedURLException e) {
System.out.println("Malformed url exception. Url: " + imageUrl);
//throw e;
}
return image;
} } | public class class_name {
private BufferedImage downloadImage() throws Exception {
BufferedImage image = null;
InputStream in = null;
try { // first try reading with the default class
URL url = new URL(imageUrl);
HttpURLConnection conn = null;
boolean success = false;
try {
conn = (HttpURLConnection) url.openConnection(); // depends on control dependency: [try], data = [none]
conn.setInstanceFollowRedirects(followRedirects); // depends on control dependency: [try], data = [none]
conn.setConnectTimeout(connectionTimeout); // TO DO: add retries when connections times out // depends on control dependency: [try], data = [none]
conn.setReadTimeout(readTimeout); // depends on control dependency: [try], data = [none]
conn.connect(); // depends on control dependency: [try], data = [none]
success = true; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
//System.out.println("Connection related exception at url: " + imageUrl);
//throw e;
} finally { // depends on control dependency: [catch], data = [none]
if (!success) {
conn.disconnect(); // depends on control dependency: [if], data = [none]
}
}
success = false;
try {
in = conn.getInputStream(); // depends on control dependency: [try], data = [none]
success = true; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
/*System.out.println("Exception when getting the input stream from the connection at url: "
+ imageUrl);
throw e;*/
} finally { // depends on control dependency: [catch], data = [none]
if (!success) {
in.close(); // depends on control dependency: [if], data = [none]
}
}
image = ImageIO.read(in);
} catch (IllegalArgumentException e) {
// this exception is probably thrown because of a greyscale jpeg image
System.out.println("Exception: " + e.getMessage() + " | Image: " + imageUrl);
image = ImageIOGreyScale.read(in); // retry with the modified class
} catch (MalformedURLException e) {
System.out.println("Malformed url exception. Url: " + imageUrl);
//throw e;
}
return image;
} } |
public class class_name {
public <E> void dispatchEvent (Signal<E> signal, E event) {
try {
signal.emit(event);
} catch (Throwable cause) {
reportError("Event dispatch failure", cause);
}
} } | public class class_name {
public <E> void dispatchEvent (Signal<E> signal, E event) {
try {
signal.emit(event); // depends on control dependency: [try], data = [none]
} catch (Throwable cause) {
reportError("Event dispatch failure", cause);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static int nodeHashCode(final Node node) {
assert node != null;
int hash = 1 + node.getNodeType();
hash = (hash * 17) + Arrays.hashCode(getNodeAttributes(node));
if (node.hasAttributes()) {
NamedNodeMap nodeMap = node.getAttributes();
for (int i = 0; i < nodeMap.getLength(); ++i) {
hash = (31 * hash) + nodeHashCode(nodeMap.item(i));
}
}
if (node.hasChildNodes()) {
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); ++i) {
hash = (hash * 47) + nodeHashCode(childNodes.item(i));
}
}
return hash;
} } | public class class_name {
public static int nodeHashCode(final Node node) {
assert node != null;
int hash = 1 + node.getNodeType();
hash = (hash * 17) + Arrays.hashCode(getNodeAttributes(node));
if (node.hasAttributes()) {
NamedNodeMap nodeMap = node.getAttributes();
for (int i = 0; i < nodeMap.getLength(); ++i) {
hash = (31 * hash) + nodeHashCode(nodeMap.item(i)); // depends on control dependency: [for], data = [i]
}
}
if (node.hasChildNodes()) {
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); ++i) {
hash = (hash * 47) + nodeHashCode(childNodes.item(i)); // depends on control dependency: [for], data = [i]
}
}
return hash;
} } |
public class class_name {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:52:47+02:00", comments = "JAXB RI v2.2.11")
public StatusTyp getStatusHP() {
if (statusHP == null) {
return StatusTyp.AKTIV;
} else {
return statusHP;
}
} } | public class class_name {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:52:47+02:00", comments = "JAXB RI v2.2.11")
public StatusTyp getStatusHP() {
if (statusHP == null) {
return StatusTyp.AKTIV; // depends on control dependency: [if], data = [none]
} else {
return statusHP; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void postProcessInstance(ManagedClassSPI managedClass, Object instance) {
if (!(instance instanceof ManagedPostConstruct)) {
return;
}
ManagedPostConstruct managedInstance = (ManagedPostConstruct) instance;
log.debug("Post-construct managed instance |%s|", managedInstance.getClass());
try {
managedInstance.postConstruct();
} catch (Throwable t) {
throw new BugError("Managed instance |%s| post-construct fail: %s", instance, t);
}
} } | public class class_name {
@Override
public void postProcessInstance(ManagedClassSPI managedClass, Object instance) {
if (!(instance instanceof ManagedPostConstruct)) {
return;
// depends on control dependency: [if], data = [none]
}
ManagedPostConstruct managedInstance = (ManagedPostConstruct) instance;
log.debug("Post-construct managed instance |%s|", managedInstance.getClass());
try {
managedInstance.postConstruct();
// depends on control dependency: [try], data = [none]
} catch (Throwable t) {
throw new BugError("Managed instance |%s| post-construct fail: %s", instance, t);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void sendGrafanaDashboardAsync(final String classPathLocation) {
if (!corePlugin.isReportToElasticsearch()) {
return;
}
try {
final ObjectNode dashboard = getGrafanaDashboard(classPathLocation);
Map<String, Object> body = new HashMap<String, Object>();
body.put("dashboard", dashboard);
body.put("overwrite", true);
asyncGrafanaRequest("POST", "/api/dashboards/db", body);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
} } | public class class_name {
public void sendGrafanaDashboardAsync(final String classPathLocation) {
if (!corePlugin.isReportToElasticsearch()) {
return; // depends on control dependency: [if], data = [none]
}
try {
final ObjectNode dashboard = getGrafanaDashboard(classPathLocation);
Map<String, Object> body = new HashMap<String, Object>();
body.put("dashboard", dashboard); // depends on control dependency: [try], data = [none]
body.put("overwrite", true); // depends on control dependency: [try], data = [none]
asyncGrafanaRequest("POST", "/api/dashboards/db", body); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.warn(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void encode(long bits, StringBuilder sb) {
if (bits < 0) {
sb.append(characters[(int) ((bits % base + base) % base)]);
bits /= -base;
}
while (bits > 0) {
sb.append(characters[(int) (bits % base)]);
bits /= base;
}
} } | public class class_name {
private void encode(long bits, StringBuilder sb) {
if (bits < 0) {
sb.append(characters[(int) ((bits % base + base) % base)]); // depends on control dependency: [if], data = [(bits]
bits /= -base; // depends on control dependency: [if], data = [none]
}
while (bits > 0) {
sb.append(characters[(int) (bits % base)]); // depends on control dependency: [while], data = [(bits]
bits /= base; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
private void ensureCapacity(int wordsRequired)
{
if (words.length >= wordsRequired) {
return;
}
int newLength = Math.max(words.length << 1, wordsRequired);
words = Arrays.copyOf(words, newLength);
} } | public class class_name {
private void ensureCapacity(int wordsRequired)
{
if (words.length >= wordsRequired) {
return;
// depends on control dependency: [if], data = [none]
}
int newLength = Math.max(words.length << 1, wordsRequired);
words = Arrays.copyOf(words, newLength);
} } |
public class class_name {
public List<List<IN>> classifyFile(String filename) {
ObjectBank<List<IN>> documents =
makeObjectBankFromFile(filename, plainTextReaderAndWriter);
List<List<IN>> result = new ArrayList<List<IN>>();
for (List<IN> document : documents) {
// System.err.println(document);
classify(document);
List<IN> sentence = new ArrayList<IN>();
for (IN wi : document) {
sentence.add(wi);
// System.err.println(wi);
}
result.add(sentence);
}
return result;
} } | public class class_name {
public List<List<IN>> classifyFile(String filename) {
ObjectBank<List<IN>> documents =
makeObjectBankFromFile(filename, plainTextReaderAndWriter);
List<List<IN>> result = new ArrayList<List<IN>>();
for (List<IN> document : documents) {
// System.err.println(document);
classify(document);
// depends on control dependency: [for], data = [document]
List<IN> sentence = new ArrayList<IN>();
for (IN wi : document) {
sentence.add(wi);
// depends on control dependency: [for], data = [wi]
// System.err.println(wi);
}
result.add(sentence);
// depends on control dependency: [for], data = [none]
}
return result;
} } |
public class class_name {
@Trivial
private static boolean contains(String[] fileList, String fileName) {
if (fileList != null) {
for (String name : fileList) {
if (name.equals(fileName)) {
return true;
}
}
}
return false;
} } | public class class_name {
@Trivial
private static boolean contains(String[] fileList, String fileName) {
if (fileList != null) {
for (String name : fileList) {
if (name.equals(fileName)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
public int getZoneNaryForNodesPartition(int zoneId, int nodeId, int partitionId) {
if(cluster.getNodeById(nodeId).getZoneId() != zoneId) {
throw new VoldemortException("Node " + nodeId + " is not in zone " + zoneId
+ "! The node is in zone "
+ cluster.getNodeById(nodeId).getZoneId());
}
List<Integer> replicatingNodeIds = getReplicationNodeList(partitionId);
int zoneNAry = -1;
for(int replicatingNodeId: replicatingNodeIds) {
Node replicatingNode = cluster.getNodeById(replicatingNodeId);
// bump up the replica number once you encounter a node in the given
// zone
if(replicatingNode.getZoneId() == zoneId) {
zoneNAry++;
}
if(replicatingNodeId == nodeId) {
return zoneNAry;
}
}
if(zoneNAry > 0) {
throw new VoldemortException("Node " + nodeId + " not a replica for partition "
+ partitionId + " in given zone " + zoneId);
} else {
throw new VoldemortException("Could not find any replicas for partition Id "
+ partitionId + " in given zone " + zoneId);
}
} } | public class class_name {
public int getZoneNaryForNodesPartition(int zoneId, int nodeId, int partitionId) {
if(cluster.getNodeById(nodeId).getZoneId() != zoneId) {
throw new VoldemortException("Node " + nodeId + " is not in zone " + zoneId
+ "! The node is in zone "
+ cluster.getNodeById(nodeId).getZoneId());
}
List<Integer> replicatingNodeIds = getReplicationNodeList(partitionId);
int zoneNAry = -1;
for(int replicatingNodeId: replicatingNodeIds) {
Node replicatingNode = cluster.getNodeById(replicatingNodeId);
// bump up the replica number once you encounter a node in the given
// zone
if(replicatingNode.getZoneId() == zoneId) {
zoneNAry++; // depends on control dependency: [if], data = [none]
}
if(replicatingNodeId == nodeId) {
return zoneNAry; // depends on control dependency: [if], data = [none]
}
}
if(zoneNAry > 0) {
throw new VoldemortException("Node " + nodeId + " not a replica for partition "
+ partitionId + " in given zone " + zoneId);
} else {
throw new VoldemortException("Could not find any replicas for partition Id "
+ partitionId + " in given zone " + zoneId);
}
} } |
public class class_name {
@Override
public TokenStream tokenStream(String fieldName, Reader reader)
{
if (indexingConfig != null)
{
Analyzer propertyAnalyzer = indexingConfig.getPropertyAnalyzer(fieldName);
if (propertyAnalyzer != null)
{
return propertyAnalyzer.tokenStream(fieldName, reader);
}
}
return defaultAnalyzer.tokenStream(fieldName, reader);
} } | public class class_name {
@Override
public TokenStream tokenStream(String fieldName, Reader reader)
{
if (indexingConfig != null)
{
Analyzer propertyAnalyzer = indexingConfig.getPropertyAnalyzer(fieldName);
if (propertyAnalyzer != null)
{
return propertyAnalyzer.tokenStream(fieldName, reader); // depends on control dependency: [if], data = [none]
}
}
return defaultAnalyzer.tokenStream(fieldName, reader);
} } |
public class class_name {
public static void handleHeaderView(DrawerBuilder drawer) {
//use the AccountHeader if set
if (drawer.mAccountHeader != null) {
if (drawer.mAccountHeaderSticky) {
drawer.mStickyHeaderView = drawer.mAccountHeader.getView();
} else {
drawer.mHeaderView = drawer.mAccountHeader.getView();
drawer.mHeaderDivider = drawer.mAccountHeader.mAccountHeaderBuilder.mDividerBelowHeader;
drawer.mHeaderPadding = drawer.mAccountHeader.mAccountHeaderBuilder.mPaddingBelowHeader;
}
}
//sticky header view
if (drawer.mStickyHeaderView != null) {
//add the sticky footer view and align it to the bottom
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1);
drawer.mStickyHeaderView.setId(R.id.material_drawer_sticky_header);
drawer.mSliderLayout.addView(drawer.mStickyHeaderView, 0, layoutParams);
//now align the recyclerView below the stickyFooterView ;)
RelativeLayout.LayoutParams layoutParamsListView = (RelativeLayout.LayoutParams) drawer.mRecyclerView.getLayoutParams();
layoutParamsListView.addRule(RelativeLayout.BELOW, R.id.material_drawer_sticky_header);
drawer.mRecyclerView.setLayoutParams(layoutParamsListView);
//set a background color or the elevation will not work
drawer.mStickyHeaderView.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(drawer.mActivity, R.attr.material_drawer_background, R.color.material_drawer_background));
if (drawer.mStickyHeaderShadow) {
//add a shadow
if (Build.VERSION.SDK_INT >= 21) {
drawer.mStickyHeaderView.setElevation(UIUtils.convertDpToPixel(4, drawer.mActivity));
} else {
View view = new View(drawer.mActivity);
view.setBackgroundResource(R.drawable.material_drawer_shadow_bottom);
drawer.mSliderLayout.addView(view, RelativeLayout.LayoutParams.MATCH_PARENT, (int) UIUtils.convertDpToPixel(4, drawer.mActivity));
//now align the shadow below the stickyHeader ;)
RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) view.getLayoutParams();
lps.addRule(RelativeLayout.BELOW, R.id.material_drawer_sticky_header);
view.setLayoutParams(lps);
}
}
//remove the padding of the recyclerView again we have the header on top of it
drawer.mRecyclerView.setPadding(0, 0, 0, 0);
}
// set the header (do this before the setAdapter because some devices will crash else
if (drawer.mHeaderView != null) {
if (drawer.mRecyclerView == null) {
throw new RuntimeException("can't use a headerView without a recyclerView");
}
if (drawer.mHeaderPadding) {
drawer.getHeaderAdapter().add(new ContainerDrawerItem().withView(drawer.mHeaderView).withHeight(drawer.mHeiderHeight).withDivider(drawer.mHeaderDivider).withViewPosition(ContainerDrawerItem.Position.TOP));
} else {
drawer.getHeaderAdapter().add(new ContainerDrawerItem().withView(drawer.mHeaderView).withHeight(drawer.mHeiderHeight).withDivider(drawer.mHeaderDivider).withViewPosition(ContainerDrawerItem.Position.NONE));
}
//set the padding on the top to 0
drawer.mRecyclerView.setPadding(drawer.mRecyclerView.getPaddingLeft(), 0, drawer.mRecyclerView.getPaddingRight(), drawer.mRecyclerView.getPaddingBottom());
}
} } | public class class_name {
public static void handleHeaderView(DrawerBuilder drawer) {
//use the AccountHeader if set
if (drawer.mAccountHeader != null) {
if (drawer.mAccountHeaderSticky) {
drawer.mStickyHeaderView = drawer.mAccountHeader.getView(); // depends on control dependency: [if], data = [none]
} else {
drawer.mHeaderView = drawer.mAccountHeader.getView(); // depends on control dependency: [if], data = [none]
drawer.mHeaderDivider = drawer.mAccountHeader.mAccountHeaderBuilder.mDividerBelowHeader; // depends on control dependency: [if], data = [none]
drawer.mHeaderPadding = drawer.mAccountHeader.mAccountHeaderBuilder.mPaddingBelowHeader; // depends on control dependency: [if], data = [none]
}
}
//sticky header view
if (drawer.mStickyHeaderView != null) {
//add the sticky footer view and align it to the bottom
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1); // depends on control dependency: [if], data = [none]
drawer.mStickyHeaderView.setId(R.id.material_drawer_sticky_header); // depends on control dependency: [if], data = [none]
drawer.mSliderLayout.addView(drawer.mStickyHeaderView, 0, layoutParams); // depends on control dependency: [if], data = [(drawer.mStickyHeaderView]
//now align the recyclerView below the stickyFooterView ;)
RelativeLayout.LayoutParams layoutParamsListView = (RelativeLayout.LayoutParams) drawer.mRecyclerView.getLayoutParams();
layoutParamsListView.addRule(RelativeLayout.BELOW, R.id.material_drawer_sticky_header); // depends on control dependency: [if], data = [none]
drawer.mRecyclerView.setLayoutParams(layoutParamsListView); // depends on control dependency: [if], data = [none]
//set a background color or the elevation will not work
drawer.mStickyHeaderView.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(drawer.mActivity, R.attr.material_drawer_background, R.color.material_drawer_background)); // depends on control dependency: [if], data = [none]
if (drawer.mStickyHeaderShadow) {
//add a shadow
if (Build.VERSION.SDK_INT >= 21) {
drawer.mStickyHeaderView.setElevation(UIUtils.convertDpToPixel(4, drawer.mActivity)); // depends on control dependency: [if], data = [none]
} else {
View view = new View(drawer.mActivity);
view.setBackgroundResource(R.drawable.material_drawer_shadow_bottom); // depends on control dependency: [if], data = [none]
drawer.mSliderLayout.addView(view, RelativeLayout.LayoutParams.MATCH_PARENT, (int) UIUtils.convertDpToPixel(4, drawer.mActivity)); // depends on control dependency: [if], data = [none]
//now align the shadow below the stickyHeader ;)
RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) view.getLayoutParams();
lps.addRule(RelativeLayout.BELOW, R.id.material_drawer_sticky_header); // depends on control dependency: [if], data = [none]
view.setLayoutParams(lps); // depends on control dependency: [if], data = [none]
}
}
//remove the padding of the recyclerView again we have the header on top of it
drawer.mRecyclerView.setPadding(0, 0, 0, 0); // depends on control dependency: [if], data = [none]
}
// set the header (do this before the setAdapter because some devices will crash else
if (drawer.mHeaderView != null) {
if (drawer.mRecyclerView == null) {
throw new RuntimeException("can't use a headerView without a recyclerView");
}
if (drawer.mHeaderPadding) {
drawer.getHeaderAdapter().add(new ContainerDrawerItem().withView(drawer.mHeaderView).withHeight(drawer.mHeiderHeight).withDivider(drawer.mHeaderDivider).withViewPosition(ContainerDrawerItem.Position.TOP)); // depends on control dependency: [if], data = [none]
} else {
drawer.getHeaderAdapter().add(new ContainerDrawerItem().withView(drawer.mHeaderView).withHeight(drawer.mHeiderHeight).withDivider(drawer.mHeaderDivider).withViewPosition(ContainerDrawerItem.Position.NONE)); // depends on control dependency: [if], data = [none]
}
//set the padding on the top to 0
drawer.mRecyclerView.setPadding(drawer.mRecyclerView.getPaddingLeft(), 0, drawer.mRecyclerView.getPaddingRight(), drawer.mRecyclerView.getPaddingBottom()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public NodeSequence fromIndex(final Index index,
final long cardinalityEstimate,
final Collection<Constraint> constraints,
final Collection<JoinCondition> joinConditions,
final Map<String, Object> variables,
final Map<String, Object> parameters,
final ValueFactories valueFactories,
final int batchSize) {
if (!index.isEnabled()) {
return null;
}
final IndexConstraints indexConstraints = new IndexConstraints() {
@Override
public boolean hasConstraints() {
return !constraints.isEmpty();
}
@Override
public Collection<Constraint> getConstraints() {
return constraints;
}
@Override
public Map<String, Object> getVariables() {
return variables;
}
@Override
public ValueFactories getValueFactories() {
return valueFactories;
}
@Override
public Map<String, Object> getParameters() {
return parameters;
}
@Override
public Collection<JoinCondition> getJoinConditions() {
return joinConditions;
}
};
// Return a node sequence that will lazily get the results from the index ...
return new NodeSequence() {
private Index.Results results;
private Filter.ResultBatch currentBatch;
private boolean more = true;
private long rowCount = 0L;
@Override
public int width() {
return 1;
}
@Override
public long getRowCount() {
if (!more) return rowCount;
return -1;
}
@Override
public boolean isEmpty() {
if (rowCount > 0) return false;
if (!more) return true; // rowCount was not > 0, but there are no more
if (results == null) {
// We haven't read anything yet, so return 'false' always (even if this is not the case)
// so we can delay the loading of the results until really needed ...
return false;
}
readBatch();
return rowCount == 0;
}
@Override
public Batch nextBatch() {
if (currentBatch == null) {
if (!more) {
// make sure we always close
close();
return null;
}
readBatch();
}
Batch nextBatch = NodeSequence.batchOfKeys(currentBatch.keys().iterator(),
currentBatch.scores().iterator(),
currentBatch.size(),
workspaceName, repo);
currentBatch = null;
return nextBatch;
}
@Override
public void close() {
if (results != null) {
results.close();
results = null;
}
}
protected final void readBatch() {
if (currentBatch != null) {
return;
}
currentBatch = getResults().getNextBatch(batchSize);
more = currentBatch.hasNext();
rowCount += currentBatch.size();
}
@Override
public String toString() {
return "(from-index " + index.getName() + " with " + constraints + ")";
}
private Index.Results getResults() {
if (results != null) return results;
// Otherwise we have to initialize the results, so have the index do the filtering based upon the constraints ...
results = index.filter(indexConstraints, cardinalityEstimate);
return results;
}
};
} } | public class class_name {
public NodeSequence fromIndex(final Index index,
final long cardinalityEstimate,
final Collection<Constraint> constraints,
final Collection<JoinCondition> joinConditions,
final Map<String, Object> variables,
final Map<String, Object> parameters,
final ValueFactories valueFactories,
final int batchSize) {
if (!index.isEnabled()) {
return null; // depends on control dependency: [if], data = [none]
}
final IndexConstraints indexConstraints = new IndexConstraints() {
@Override
public boolean hasConstraints() {
return !constraints.isEmpty();
}
@Override
public Collection<Constraint> getConstraints() {
return constraints;
}
@Override
public Map<String, Object> getVariables() {
return variables;
}
@Override
public ValueFactories getValueFactories() {
return valueFactories;
}
@Override
public Map<String, Object> getParameters() {
return parameters;
}
@Override
public Collection<JoinCondition> getJoinConditions() {
return joinConditions;
}
};
// Return a node sequence that will lazily get the results from the index ...
return new NodeSequence() {
private Index.Results results;
private Filter.ResultBatch currentBatch;
private boolean more = true;
private long rowCount = 0L;
@Override
public int width() {
return 1;
}
@Override
public long getRowCount() {
if (!more) return rowCount;
return -1;
}
@Override
public boolean isEmpty() {
if (rowCount > 0) return false;
if (!more) return true; // rowCount was not > 0, but there are no more
if (results == null) {
// We haven't read anything yet, so return 'false' always (even if this is not the case)
// so we can delay the loading of the results until really needed ...
return false; // depends on control dependency: [if], data = [none]
}
readBatch();
return rowCount == 0;
}
@Override
public Batch nextBatch() {
if (currentBatch == null) {
if (!more) {
// make sure we always close
close(); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
readBatch(); // depends on control dependency: [if], data = [none]
}
Batch nextBatch = NodeSequence.batchOfKeys(currentBatch.keys().iterator(),
currentBatch.scores().iterator(),
currentBatch.size(),
workspaceName, repo);
currentBatch = null;
return nextBatch;
}
@Override
public void close() {
if (results != null) {
results.close(); // depends on control dependency: [if], data = [none]
results = null; // depends on control dependency: [if], data = [none]
}
}
protected final void readBatch() {
if (currentBatch != null) {
return; // depends on control dependency: [if], data = [none]
}
currentBatch = getResults().getNextBatch(batchSize);
more = currentBatch.hasNext();
rowCount += currentBatch.size();
}
@Override
public String toString() {
return "(from-index " + index.getName() + " with " + constraints + ")";
}
private Index.Results getResults() {
if (results != null) return results;
// Otherwise we have to initialize the results, so have the index do the filtering based upon the constraints ...
results = index.filter(indexConstraints, cardinalityEstimate);
return results;
}
};
} } |
public class class_name {
public void removeListener(CancellationListener cancellationListener) {
if (!canBeCancelled()) {
return;
}
synchronized (this) {
if (listeners != null) {
for (int i = listeners.size() - 1; i >= 0; i--) {
if (listeners.get(i).listener == cancellationListener) {
listeners.remove(i);
// Just remove the first matching listener, given that we allow duplicate
// adds we should allow for duplicates after remove.
break;
}
}
// We have no listeners so no need to listen to our parent
if (listeners.isEmpty()) {
if (cancellableAncestor != null) {
cancellableAncestor.removeListener(parentListener);
}
listeners = null;
}
}
}
} } | public class class_name {
public void removeListener(CancellationListener cancellationListener) {
if (!canBeCancelled()) {
return; // depends on control dependency: [if], data = [none]
}
synchronized (this) {
if (listeners != null) {
for (int i = listeners.size() - 1; i >= 0; i--) {
if (listeners.get(i).listener == cancellationListener) {
listeners.remove(i); // depends on control dependency: [if], data = [none]
// Just remove the first matching listener, given that we allow duplicate
// adds we should allow for duplicates after remove.
break;
}
}
// We have no listeners so no need to listen to our parent
if (listeners.isEmpty()) {
if (cancellableAncestor != null) {
cancellableAncestor.removeListener(parentListener); // depends on control dependency: [if], data = [none]
}
listeners = null; // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private byte[] generateAesIv() {
byte[] bytes = new byte[16];
if (!testMode) {
SecureRandom random = new SecureRandom();
random.nextBytes(bytes);
} else {
bytes = "TEST1234TEST1234".getBytes(MESSAGE_ENCODING);
}
return bytes;
} } | public class class_name {
private byte[] generateAesIv() {
byte[] bytes = new byte[16];
if (!testMode) {
SecureRandom random = new SecureRandom();
random.nextBytes(bytes); // depends on control dependency: [if], data = [none]
} else {
bytes = "TEST1234TEST1234".getBytes(MESSAGE_ENCODING); // depends on control dependency: [if], data = [none]
}
return bytes;
} } |
public class class_name {
public void marshall(CreatePortfolioRequest createPortfolioRequest, ProtocolMarshaller protocolMarshaller) {
if (createPortfolioRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createPortfolioRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING);
protocolMarshaller.marshall(createPortfolioRequest.getDisplayName(), DISPLAYNAME_BINDING);
protocolMarshaller.marshall(createPortfolioRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(createPortfolioRequest.getProviderName(), PROVIDERNAME_BINDING);
protocolMarshaller.marshall(createPortfolioRequest.getTags(), TAGS_BINDING);
protocolMarshaller.marshall(createPortfolioRequest.getIdempotencyToken(), IDEMPOTENCYTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreatePortfolioRequest createPortfolioRequest, ProtocolMarshaller protocolMarshaller) {
if (createPortfolioRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createPortfolioRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createPortfolioRequest.getDisplayName(), DISPLAYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createPortfolioRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createPortfolioRequest.getProviderName(), PROVIDERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createPortfolioRequest.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createPortfolioRequest.getIdempotencyToken(), IDEMPOTENCYTOKEN_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 {
@Exported
public boolean isIdle() {
lock.readLock().lock();
try {
return workUnit == null && executable == null;
} finally {
lock.readLock().unlock();
}
} } | public class class_name {
@Exported
public boolean isIdle() {
lock.readLock().lock();
try {
return workUnit == null && executable == null; // depends on control dependency: [try], data = [none]
} finally {
lock.readLock().unlock();
}
} } |
public class class_name {
protected void loadPage(int pageNum) {
int start = (pageNum - 1) * m_pageSize;
List<CmsResultItemBean> results = m_resultBeans;
int end = start + m_pageSize;
if (end > results.size()) {
end = results.size();
}
List<CmsResultItemBean> page = results.subList(start, end);
boolean showPath = SortParams.path_asc.name().equals(m_searchBean.getSortOrder())
|| SortParams.path_desc.name().equals(m_searchBean.getSortOrder());
m_resultsTab.addContentItems(page, true, showPath);
} } | public class class_name {
protected void loadPage(int pageNum) {
int start = (pageNum - 1) * m_pageSize;
List<CmsResultItemBean> results = m_resultBeans;
int end = start + m_pageSize;
if (end > results.size()) {
end = results.size();
// depends on control dependency: [if], data = [none]
}
List<CmsResultItemBean> page = results.subList(start, end);
boolean showPath = SortParams.path_asc.name().equals(m_searchBean.getSortOrder())
|| SortParams.path_desc.name().equals(m_searchBean.getSortOrder());
m_resultsTab.addContentItems(page, true, showPath);
} } |
public class class_name {
public void marshall(UsageRecord usageRecord, ProtocolMarshaller protocolMarshaller) {
if (usageRecord == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(usageRecord.getTimestamp(), TIMESTAMP_BINDING);
protocolMarshaller.marshall(usageRecord.getCustomerIdentifier(), CUSTOMERIDENTIFIER_BINDING);
protocolMarshaller.marshall(usageRecord.getDimension(), DIMENSION_BINDING);
protocolMarshaller.marshall(usageRecord.getQuantity(), QUANTITY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UsageRecord usageRecord, ProtocolMarshaller protocolMarshaller) {
if (usageRecord == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(usageRecord.getTimestamp(), TIMESTAMP_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(usageRecord.getCustomerIdentifier(), CUSTOMERIDENTIFIER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(usageRecord.getDimension(), DIMENSION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(usageRecord.getQuantity(), QUANTITY_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 {
@Override
protected void perform(final Wave wave) {
// Retrieved the model class
// final Class<? extends Model> modelClass = (Class<? extends Model>) getWaveBean(wave).getShowModelKey().getClass();
// final Object[] keyPart = getWaveBean(wave).getKeyPart() == null ? null : getWaveBean(wave).getKeyPart().toArray();
final DisplayModelWaveBean wb = waveBean(wave);
final ModelConfig<?, ?> data = wb.showModelData();
final UniqueKey<? extends Model> showModelKey = data != null ? Key.create(data.modelClass(), data) : wb.showModelKey();
if (showModelKey == null) {
LOGGER.error("ModelClass is null");
throw new CoreRuntimeException("Illegal action : Model Class is null");
}
// Retrieve the mode according to its keyPart
final Model modelInstance = localFacade().globalFacade().uiFacade().retrieve(showModelKey);
//
// if (keyPart == null) {
// modelInstance = getLocalFacade().getGlobalFacade().getUiFacade().retrieve(modelClass);
// } else {
// modelInstance = getLocalFacade().getGlobalFacade().getUiFacade().retrieve(modelClass, keyPart);
// }
if (modelInstance == null) {
LOGGER.error("Model " + showModelKey.classField().getSimpleName() + " couldn't be created");
throw new CoreRuntimeException("Illegal action : Model Instance is null: " + showModelKey.classField().getName());
}
// Attach the model to allow reuse later in the process
waveBean(wave).showModel(modelInstance);
// Build the first root node into the thread pool and link it to the waveBean
// getWaveBean(wave).setCreatedNode(modelInstance.getRootNode());
} } | public class class_name {
@Override
protected void perform(final Wave wave) {
// Retrieved the model class
// final Class<? extends Model> modelClass = (Class<? extends Model>) getWaveBean(wave).getShowModelKey().getClass();
// final Object[] keyPart = getWaveBean(wave).getKeyPart() == null ? null : getWaveBean(wave).getKeyPart().toArray();
final DisplayModelWaveBean wb = waveBean(wave);
final ModelConfig<?, ?> data = wb.showModelData();
final UniqueKey<? extends Model> showModelKey = data != null ? Key.create(data.modelClass(), data) : wb.showModelKey();
if (showModelKey == null) {
LOGGER.error("ModelClass is null"); // depends on control dependency: [if], data = [none]
throw new CoreRuntimeException("Illegal action : Model Class is null");
}
// Retrieve the mode according to its keyPart
final Model modelInstance = localFacade().globalFacade().uiFacade().retrieve(showModelKey);
//
// if (keyPart == null) {
// modelInstance = getLocalFacade().getGlobalFacade().getUiFacade().retrieve(modelClass);
// } else {
// modelInstance = getLocalFacade().getGlobalFacade().getUiFacade().retrieve(modelClass, keyPart);
// }
if (modelInstance == null) {
LOGGER.error("Model " + showModelKey.classField().getSimpleName() + " couldn't be created"); // depends on control dependency: [if], data = [none]
throw new CoreRuntimeException("Illegal action : Model Instance is null: " + showModelKey.classField().getName());
}
// Attach the model to allow reuse later in the process
waveBean(wave).showModel(modelInstance);
// Build the first root node into the thread pool and link it to the waveBean
// getWaveBean(wave).setCreatedNode(modelInstance.getRootNode());
} } |
public class class_name {
public void marshall(RestoreTableFromBackupRequest restoreTableFromBackupRequest, ProtocolMarshaller protocolMarshaller) {
if (restoreTableFromBackupRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(restoreTableFromBackupRequest.getTargetTableName(), TARGETTABLENAME_BINDING);
protocolMarshaller.marshall(restoreTableFromBackupRequest.getBackupArn(), BACKUPARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RestoreTableFromBackupRequest restoreTableFromBackupRequest, ProtocolMarshaller protocolMarshaller) {
if (restoreTableFromBackupRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(restoreTableFromBackupRequest.getTargetTableName(), TARGETTABLENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(restoreTableFromBackupRequest.getBackupArn(), BACKUPARN_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 {
public static StringBuilder appendZeros(StringBuilder buf, int zeros) {
for(int i = zeros; i > 0; i -= ZEROPADDING.length) {
buf.append(ZEROPADDING, 0, i < ZEROPADDING.length ? i : ZEROPADDING.length);
}
return buf;
} } | public class class_name {
public static StringBuilder appendZeros(StringBuilder buf, int zeros) {
for(int i = zeros; i > 0; i -= ZEROPADDING.length) {
buf.append(ZEROPADDING, 0, i < ZEROPADDING.length ? i : ZEROPADDING.length); // depends on control dependency: [for], data = [i]
}
return buf;
} } |
public class class_name {
public void setDeviceInstances(java.util.Collection<DeviceInstance> deviceInstances) {
if (deviceInstances == null) {
this.deviceInstances = null;
return;
}
this.deviceInstances = new java.util.ArrayList<DeviceInstance>(deviceInstances);
} } | public class class_name {
public void setDeviceInstances(java.util.Collection<DeviceInstance> deviceInstances) {
if (deviceInstances == null) {
this.deviceInstances = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.deviceInstances = new java.util.ArrayList<DeviceInstance>(deviceInstances);
} } |
public class class_name {
private void processAnalytics() throws SQLException
{
allocateConnection();
try
{
DatabaseMetaData meta = m_connection.getMetaData();
String productName = meta.getDatabaseProductName();
if (productName == null || productName.isEmpty())
{
productName = "DATABASE";
}
else
{
productName = productName.toUpperCase();
}
ProjectProperties properties = m_reader.getProject().getProjectProperties();
properties.setFileApplication("Primavera");
properties.setFileType(productName);
}
finally
{
releaseConnection();
}
} } | public class class_name {
private void processAnalytics() throws SQLException
{
allocateConnection();
try
{
DatabaseMetaData meta = m_connection.getMetaData();
String productName = meta.getDatabaseProductName();
if (productName == null || productName.isEmpty())
{
productName = "DATABASE"; // depends on control dependency: [if], data = [none]
}
else
{
productName = productName.toUpperCase(); // depends on control dependency: [if], data = [none]
}
ProjectProperties properties = m_reader.getProject().getProjectProperties();
properties.setFileApplication("Primavera");
properties.setFileType(productName);
}
finally
{
releaseConnection();
}
} } |
public class class_name {
private ResourceException processHandleDissociationError(int handleIndex,
ResourceException dissociationX) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(this, tc, "processHandleDissociationError", handleIndex, dissociationX.getMessage());
WSJdbcConnection handle = handlesInUse[handleIndex];
// If we receive an error for dissociating a handle which is currently in use,
// just close the handle instead , provided we can still access it.
String errCode = dissociationX.getErrorCode();
if ((errCode != null && errCode.equals("HANDLE_IN_USE")) && handle != null)
try
{
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(this, tc,
"Unable to dissociate handle because it is doing work in the database. " +
"Closing it instead.",
handlesInUse[handleIndex]);
// This is a JDBC specific error, so we can cast to java.sql.Connection.
((java.sql.Connection) handle).close();
// If the handle close is successful, this situation is NOT considered an error.
dissociationX = null;
} catch (SQLException closeX) {
// No FFDC code needed here because we do it below.
dissociationX = new DataStoreAdapterException("DSA_ERROR", closeX, getClass(), closeX);
}
if (dissociationX != null) {
FFDCFilter.processException(dissociationX,
getClass().getName() + ".processHandleDissociationError", "1024", this);
// The connection handle already signals a ConnectionError event on any fatal
// error on dissociation, so there is no need to check if the exception maps to
// connection error.
if (isTraceOn && tc.isEventEnabled())
Tr.event(this, tc,
"Error dissociating handle. Continuing...", handle);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(this, tc, "processHandleDissociationError",
dissociationX == null ? null : dissociationX.getMessage());
return dissociationX;
} } | public class class_name {
private ResourceException processHandleDissociationError(int handleIndex,
ResourceException dissociationX) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(this, tc, "processHandleDissociationError", handleIndex, dissociationX.getMessage());
WSJdbcConnection handle = handlesInUse[handleIndex];
// If we receive an error for dissociating a handle which is currently in use,
// just close the handle instead , provided we can still access it.
String errCode = dissociationX.getErrorCode();
if ((errCode != null && errCode.equals("HANDLE_IN_USE")) && handle != null)
try
{
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(this, tc,
"Unable to dissociate handle because it is doing work in the database. " +
"Closing it instead.",
handlesInUse[handleIndex]);
// This is a JDBC specific error, so we can cast to java.sql.Connection.
((java.sql.Connection) handle).close(); // depends on control dependency: [try], data = [none]
// If the handle close is successful, this situation is NOT considered an error.
dissociationX = null; // depends on control dependency: [try], data = [none]
} catch (SQLException closeX) {
// No FFDC code needed here because we do it below.
dissociationX = new DataStoreAdapterException("DSA_ERROR", closeX, getClass(), closeX);
} // depends on control dependency: [catch], data = [none]
if (dissociationX != null) {
FFDCFilter.processException(dissociationX,
getClass().getName() + ".processHandleDissociationError", "1024", this); // depends on control dependency: [if], data = [(dissociationX]
// The connection handle already signals a ConnectionError event on any fatal
// error on dissociation, so there is no need to check if the exception maps to
// connection error.
if (isTraceOn && tc.isEventEnabled())
Tr.event(this, tc,
"Error dissociating handle. Continuing...", handle);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(this, tc, "processHandleDissociationError",
dissociationX == null ? null : dissociationX.getMessage());
return dissociationX;
} } |
public class class_name {
public String getFullName() {
StringBuffer buf = new StringBuffer();
if (getParentPrivlige() != null) {
buf.append(parentPrivlige.getFullName().concat(" > "));
}
buf.append(getPriviligeName());
return buf.toString();
} } | public class class_name {
public String getFullName() {
StringBuffer buf = new StringBuffer();
if (getParentPrivlige() != null) {
buf.append(parentPrivlige.getFullName().concat(" > ")); // depends on control dependency: [if], data = [none]
}
buf.append(getPriviligeName());
return buf.toString();
} } |
public class class_name {
@Override
public JacksonWrapperSerializer createSerializer(Writer writer) {
try {
JsonGenerator generator = innerFactory.createGenerator(writer);
// generator.setPrettyPrinter(new MinimalPrettyPrinter());
return new JacksonWrapperSerializer(generator, getSupportedFormat());
} catch (IOException e) {
e.printStackTrace();
throw new KriptonRuntimeException(e);
}
} } | public class class_name {
@Override
public JacksonWrapperSerializer createSerializer(Writer writer) {
try {
JsonGenerator generator = innerFactory.createGenerator(writer);
// generator.setPrettyPrinter(new MinimalPrettyPrinter());
return new JacksonWrapperSerializer(generator, getSupportedFormat()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
throw new KriptonRuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Nullable
static Map<String, Object> jsonObjectToMap(@Nullable JSONObject jsonObject) {
if (jsonObject == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
Iterator<String> keyIterator = jsonObject.keys();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
Object value = jsonObject.opt(key);
if (NULL.equals(value) || value == null) {
continue;
}
if (value instanceof JSONObject) {
map.put(key, jsonObjectToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
map.put(key, jsonArrayToList((JSONArray) value));
} else {
map.put(key, value);
}
}
return map;
} } | public class class_name {
@Nullable
static Map<String, Object> jsonObjectToMap(@Nullable JSONObject jsonObject) {
if (jsonObject == null) {
return null; // depends on control dependency: [if], data = [none]
}
Map<String, Object> map = new HashMap<>();
Iterator<String> keyIterator = jsonObject.keys();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
Object value = jsonObject.opt(key);
if (NULL.equals(value) || value == null) {
continue;
}
if (value instanceof JSONObject) {
map.put(key, jsonObjectToMap((JSONObject) value)); // depends on control dependency: [if], data = [none]
} else if (value instanceof JSONArray) {
map.put(key, jsonArrayToList((JSONArray) value)); // depends on control dependency: [if], data = [none]
} else {
map.put(key, value); // depends on control dependency: [if], data = [none]
}
}
return map;
} } |
public class class_name {
public ArrayList<SAXRecord> getSimpleMotifs(int num) {
ArrayList<SAXRecord> res = new ArrayList<SAXRecord>(num);
DoublyLinkedSortedList<Entry<String, SAXRecord>> list = new DoublyLinkedSortedList<Entry<String, SAXRecord>>(
num, new Comparator<Entry<String, SAXRecord>>() {
@Override
public int compare(Entry<String, SAXRecord> o1, Entry<String, SAXRecord> o2) {
int f1 = o1.getValue().getIndexes().size();
int f2 = o2.getValue().getIndexes().size();
return Integer.compare(f1, f2);
}
});
for (Entry<String, SAXRecord> e : this.records.entrySet()) {
list.addElement(e);
}
Iterator<Entry<String, SAXRecord>> i = list.iterator();
while (i.hasNext()) {
res.add(i.next().getValue());
}
return res;
} } | public class class_name {
public ArrayList<SAXRecord> getSimpleMotifs(int num) {
ArrayList<SAXRecord> res = new ArrayList<SAXRecord>(num);
DoublyLinkedSortedList<Entry<String, SAXRecord>> list = new DoublyLinkedSortedList<Entry<String, SAXRecord>>(
num, new Comparator<Entry<String, SAXRecord>>() {
@Override
public int compare(Entry<String, SAXRecord> o1, Entry<String, SAXRecord> o2) {
int f1 = o1.getValue().getIndexes().size();
int f2 = o2.getValue().getIndexes().size();
return Integer.compare(f1, f2);
}
});
for (Entry<String, SAXRecord> e : this.records.entrySet()) {
list.addElement(e); // depends on control dependency: [for], data = [e]
}
Iterator<Entry<String, SAXRecord>> i = list.iterator();
while (i.hasNext()) {
res.add(i.next().getValue()); // depends on control dependency: [while], data = [none]
}
return res;
} } |
public class class_name {
public Set<String> getInvokedTables() throws ParseException {
// Read all SQL statements from input
ZStatement st;
Set<String> tables = new HashSet<String>();
while ((st = parser.readStatement()) != null) {
this.sql = st.toString();
if (st instanceof ZQuery) { // An SQL query: query the DB
getInvokedTables((ZQuery) st, tables);
}
break;
}
return tables;
} } | public class class_name {
public Set<String> getInvokedTables() throws ParseException {
// Read all SQL statements from input
ZStatement st;
Set<String> tables = new HashSet<String>();
while ((st = parser.readStatement()) != null) {
this.sql = st.toString();
if (st instanceof ZQuery) { // An SQL query: query the DB
getInvokedTables((ZQuery) st, tables); // depends on control dependency: [if], data = [none]
}
break;
}
return tables;
} } |
public class class_name {
@Override
public VertrekkendeTreinen getModel(InputStream stream) {
SimpleDateFormat format = new SimpleDateFormat(NsApi.DATETIME_FORMAT);
try {
List<VertrekkendeTrein> vertrekkendeTreinen = new LinkedList<VertrekkendeTrein>();
Xml xml = Xml.getXml(stream, "ActueleVertrekTijden");
for (Xml vertrekkendeTreinXml : xml.children("VertrekkendeTrein")) {
int ritNummer = Integer.parseInt(vertrekkendeTreinXml.child("RitNummer").content());
Date vertrekTijd = format.parse(vertrekkendeTreinXml.child("VertrekTijd").content());
String vertrekVertraging = vertrekkendeTreinXml.child("VertrekVertraging").content();
int vertrekVertragingMinuten = 0;
if (vertrekVertraging != null && !vertrekVertraging.isEmpty()) {
try {
vertrekVertragingMinuten = Integer.parseInt(vertrekVertraging.replace("PT", "")
.replace("M", ""));
}
catch (NumberFormatException e) {
logger.warn("Error parsing vertrek vertraging minuten into minutes", e);
}
}
String vertrekVertragingTekst = vertrekkendeTreinXml.child("VertrekVertragingTekst").content();
String eindBestemming = vertrekkendeTreinXml.child("EindBestemming").content();
String treinSoort = vertrekkendeTreinXml.child("TreinSoort").content();
String routeTekst = vertrekkendeTreinXml.child("RouteTekst").content();
String vervoerder = vertrekkendeTreinXml.child("Vervoerder").content();
String vertrekSpoor = vertrekkendeTreinXml.child("VertrekSpoor").content();
boolean gewijzigdVertrekspoor = Boolean.valueOf(vertrekkendeTreinXml.child("VertrekSpoor").attr(
"wijziging"));
List<String> opmerkingen = new LinkedList<String>();
for (Xml opm : vertrekkendeTreinXml.children("Opmerkingen")) {
opmerkingen.add(opm.child("Opmerking").content());
}
String reisTip = vertrekkendeTreinXml.child("ReisTip").content();
vertrekkendeTreinen.add(new VertrekkendeTrein(ritNummer, vertrekTijd, vertrekVertraging,
vertrekVertragingMinuten, vertrekVertragingTekst, eindBestemming, treinSoort, routeTekst,
vervoerder, vertrekSpoor, gewijzigdVertrekspoor, reisTip, opmerkingen));
}
return new VertrekkendeTreinen(vertrekkendeTreinen);
}
catch (ParseException e) {
logger.error("Error parsing stream to actuele vertrektijden", e);
throw new NsApiException("Error parsing stream to actuele vertrektijden", e);
}
} } | public class class_name {
@Override
public VertrekkendeTreinen getModel(InputStream stream) {
SimpleDateFormat format = new SimpleDateFormat(NsApi.DATETIME_FORMAT);
try {
List<VertrekkendeTrein> vertrekkendeTreinen = new LinkedList<VertrekkendeTrein>();
Xml xml = Xml.getXml(stream, "ActueleVertrekTijden");
for (Xml vertrekkendeTreinXml : xml.children("VertrekkendeTrein")) {
int ritNummer = Integer.parseInt(vertrekkendeTreinXml.child("RitNummer").content());
Date vertrekTijd = format.parse(vertrekkendeTreinXml.child("VertrekTijd").content());
String vertrekVertraging = vertrekkendeTreinXml.child("VertrekVertraging").content();
int vertrekVertragingMinuten = 0;
if (vertrekVertraging != null && !vertrekVertraging.isEmpty()) {
try {
vertrekVertragingMinuten = Integer.parseInt(vertrekVertraging.replace("PT", "")
.replace("M", ""));
// depends on control dependency: [try], data = [none]
}
catch (NumberFormatException e) {
logger.warn("Error parsing vertrek vertraging minuten into minutes", e);
}
// depends on control dependency: [catch], data = [none]
}
String vertrekVertragingTekst = vertrekkendeTreinXml.child("VertrekVertragingTekst").content();
String eindBestemming = vertrekkendeTreinXml.child("EindBestemming").content();
String treinSoort = vertrekkendeTreinXml.child("TreinSoort").content();
String routeTekst = vertrekkendeTreinXml.child("RouteTekst").content();
String vervoerder = vertrekkendeTreinXml.child("Vervoerder").content();
String vertrekSpoor = vertrekkendeTreinXml.child("VertrekSpoor").content();
boolean gewijzigdVertrekspoor = Boolean.valueOf(vertrekkendeTreinXml.child("VertrekSpoor").attr(
"wijziging"));
List<String> opmerkingen = new LinkedList<String>();
for (Xml opm : vertrekkendeTreinXml.children("Opmerkingen")) {
opmerkingen.add(opm.child("Opmerking").content());
// depends on control dependency: [for], data = [opm]
}
String reisTip = vertrekkendeTreinXml.child("ReisTip").content();
vertrekkendeTreinen.add(new VertrekkendeTrein(ritNummer, vertrekTijd, vertrekVertraging,
vertrekVertragingMinuten, vertrekVertragingTekst, eindBestemming, treinSoort, routeTekst,
vervoerder, vertrekSpoor, gewijzigdVertrekspoor, reisTip, opmerkingen));
// depends on control dependency: [for], data = [none]
}
return new VertrekkendeTreinen(vertrekkendeTreinen);
// depends on control dependency: [try], data = [none]
}
catch (ParseException e) {
logger.error("Error parsing stream to actuele vertrektijden", e);
throw new NsApiException("Error parsing stream to actuele vertrektijden", e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Stream<BigFloat> rangeClosed(BigFloat startInclusive, BigFloat endInclusive, BigFloat step) {
if (step.isZero()) {
throw new IllegalArgumentException("invalid step: 0");
}
if (endInclusive.subtract(startInclusive).signum() == -step.signum()) {
return Stream.empty();
}
return StreamSupport.stream(new BigFloatSpliterator(startInclusive, endInclusive, true, step), false);
} } | public class class_name {
public static Stream<BigFloat> rangeClosed(BigFloat startInclusive, BigFloat endInclusive, BigFloat step) {
if (step.isZero()) {
throw new IllegalArgumentException("invalid step: 0");
}
if (endInclusive.subtract(startInclusive).signum() == -step.signum()) {
return Stream.empty();
// depends on control dependency: [if], data = [none]
}
return StreamSupport.stream(new BigFloatSpliterator(startInclusive, endInclusive, true, step), false);
} } |
public class class_name {
@Override
public void inherit(DocFinder.Input input, DocFinder.Output output) {
Utils utils = input.utils;
Element exception;
CommentHelper ch = utils.getCommentHelper(input.element);
if (input.tagId == null) {
exception = ch.getException(utils.configuration, input.docTreeInfo.docTree);
input.tagId = exception == null
? ch.getExceptionName(input.docTreeInfo.docTree).getSignature()
: utils.getFullyQualifiedName(exception);
} else {
TypeElement element = input.utils.findClass(input.element, input.tagId);
exception = (element == null) ? null : element;
}
for (DocTree dt : input.utils.getThrowsTrees(input.element)) {
Element texception = ch.getException(utils.configuration, dt);
if (texception != null && (input.tagId.equals(utils.getSimpleName(texception)) ||
(input.tagId.equals(utils.getFullyQualifiedName(texception))))) {
output.holder = input.element;
output.holderTag = dt;
output.inlineTags = ch.getBody(input.utils.configuration, output.holderTag);
output.tagList.add(dt);
} else if (exception != null && texception != null &&
utils.isTypeElement(texception) && utils.isTypeElement(exception) &&
utils.isSubclassOf((TypeElement)texception, (TypeElement)exception)) {
output.tagList.add(dt);
}
}
} } | public class class_name {
@Override
public void inherit(DocFinder.Input input, DocFinder.Output output) {
Utils utils = input.utils;
Element exception;
CommentHelper ch = utils.getCommentHelper(input.element);
if (input.tagId == null) {
exception = ch.getException(utils.configuration, input.docTreeInfo.docTree); // depends on control dependency: [if], data = [none]
input.tagId = exception == null
? ch.getExceptionName(input.docTreeInfo.docTree).getSignature()
: utils.getFullyQualifiedName(exception); // depends on control dependency: [if], data = [none]
} else {
TypeElement element = input.utils.findClass(input.element, input.tagId);
exception = (element == null) ? null : element; // depends on control dependency: [if], data = [null)]
}
for (DocTree dt : input.utils.getThrowsTrees(input.element)) {
Element texception = ch.getException(utils.configuration, dt);
if (texception != null && (input.tagId.equals(utils.getSimpleName(texception)) ||
(input.tagId.equals(utils.getFullyQualifiedName(texception))))) {
output.holder = input.element; // depends on control dependency: [if], data = [none]
output.holderTag = dt; // depends on control dependency: [if], data = [none]
output.inlineTags = ch.getBody(input.utils.configuration, output.holderTag); // depends on control dependency: [if], data = [none]
output.tagList.add(dt); // depends on control dependency: [if], data = [none]
} else if (exception != null && texception != null &&
utils.isTypeElement(texception) && utils.isTypeElement(exception) &&
utils.isSubclassOf((TypeElement)texception, (TypeElement)exception)) {
output.tagList.add(dt); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean isInterfaceImpl(Class thisClass, Class targetInterface) {
for (Class x = thisClass; x != null; x = x.getSuperclass()) {
Class[] interfaces = x.getInterfaces();
for (Class i : interfaces) {
if (i == targetInterface) {
return true;
}
if (isInterfaceImpl(i, targetInterface)) {
return true;
}
}
}
return false;
} } | public class class_name {
public static boolean isInterfaceImpl(Class thisClass, Class targetInterface) {
for (Class x = thisClass; x != null; x = x.getSuperclass()) {
Class[] interfaces = x.getInterfaces();
for (Class i : interfaces) {
if (i == targetInterface) {
return true; // depends on control dependency: [if], data = [none]
}
if (isInterfaceImpl(i, targetInterface)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
public void marshall(KeyValuePair keyValuePair, ProtocolMarshaller protocolMarshaller) {
if (keyValuePair == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(keyValuePair.getName(), NAME_BINDING);
protocolMarshaller.marshall(keyValuePair.getValue(), VALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(KeyValuePair keyValuePair, ProtocolMarshaller protocolMarshaller) {
if (keyValuePair == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(keyValuePair.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(keyValuePair.getValue(), VALUE_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 synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject(); // read the fields
if ((handler = getDelegate().getURLStreamHandler(protocol)) == null) {
throw new IOException("unknown protocol: " + protocol);
}
// Construct authority part
if (authority == null &&
((host != null && host.length() > 0) || port != -1)) {
if (host == null)
host = "";
authority = (port == -1) ? host : host + ":" + port;
// Handle hosts with userInfo in them
int at = host.lastIndexOf('@');
if (at != -1) {
userInfo = host.substring(0, at);
host = host.substring(at+1);
}
} else if (authority != null) {
// Construct user info part
int ind = authority.indexOf('@');
if (ind != -1)
userInfo = authority.substring(0, ind);
}
// Construct path and query part
path = null;
query = null;
if (file != null) {
// Fix: only do this if hierarchical?
int q = file.lastIndexOf('?');
if (q != -1) {
query = file.substring(q+1);
path = file.substring(0, q);
} else
path = file;
}
hashCode = -1;
} } | public class class_name {
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject(); // read the fields
if ((handler = getDelegate().getURLStreamHandler(protocol)) == null) {
throw new IOException("unknown protocol: " + protocol);
}
// Construct authority part
if (authority == null &&
((host != null && host.length() > 0) || port != -1)) {
if (host == null)
host = "";
authority = (port == -1) ? host : host + ":" + port;
// Handle hosts with userInfo in them
int at = host.lastIndexOf('@');
if (at != -1) {
userInfo = host.substring(0, at); // depends on control dependency: [if], data = [none]
host = host.substring(at+1); // depends on control dependency: [if], data = [(at]
}
} else if (authority != null) {
// Construct user info part
int ind = authority.indexOf('@');
if (ind != -1)
userInfo = authority.substring(0, ind);
}
// Construct path and query part
path = null;
query = null;
if (file != null) {
// Fix: only do this if hierarchical?
int q = file.lastIndexOf('?');
if (q != -1) {
query = file.substring(q+1);
path = file.substring(0, q);
} else
path = file;
}
hashCode = -1;
} } |
public class class_name {
public static TopologyGraph getTopologyGraph(StormTopology stormTopology, List<MetricInfo> componentMetrics) {
Map<String, Bolt> bolts = stormTopology.get_bolts();
Map<String, SpoutSpec> spouts = stormTopology.get_spouts();
//remove system bolts
String[] remove_ids = new String[]{"__acker", "__system", "__topology_master"};
for (String id : remove_ids) {
bolts.remove(id);
}
//<id, node>
Map<String, TopologyNode> nodes = Maps.newHashMap();
//<from:to,edge>
Map<String, TopologyEdge> edges = Maps.newHashMap();
List<TreeNode> roots = Lists.newArrayList(); //this is used to get tree depth
Map<String, TreeNode> linkMap = Maps.newHashMap(); //this is used to get tree depth
// init the nodes
for (Map.Entry<String, SpoutSpec> entry : spouts.entrySet()) {
String componentId = entry.getKey();
nodes.put(componentId, new TopologyNode(componentId, componentId, true));
TreeNode node = new TreeNode(componentId);
roots.add(node);
linkMap.put(componentId, node);
}
for (Map.Entry<String, Bolt> entry : bolts.entrySet()) {
String componentId = entry.getKey();
nodes.put(componentId, new TopologyNode(componentId, componentId, false));
linkMap.put(componentId, new TreeNode(componentId));
}
//init the edges
int edgeId = 1;
for (Map.Entry<String, Bolt> entry : bolts.entrySet()) {
String componentId = entry.getKey();
Bolt bolt = entry.getValue();
TreeNode node = linkMap.get(componentId);
for (Map.Entry<GlobalStreamId, Grouping> input : bolt.get_common().get_inputs().entrySet()) {
GlobalStreamId streamId = input.getKey();
String src = streamId.get_componentId();
if (nodes.containsKey(src)) {
TopologyEdge edge = new TopologyEdge(src, componentId, edgeId++);
edges.put(edge.getKey(), edge);
// put into linkMap
linkMap.get(src).addChild(node);
node.addSource(src);
node.addParent(linkMap.get(src));
}
}
}
//calculate whether has circle
boolean isFixed = false;
while (!isFixed) {
isFixed = true;
for (TreeNode node : linkMap.values()) {
for (TreeNode parent : node.getParents()) {
if (!node.addSources(parent.getSources())) {
isFixed = false;
}
}
}
}
// fill value to edges
fillTPSValue2Edge(componentMetrics, edges);
fillTLCValue2Edge(componentMetrics, edges);
// fill value to nodes
fillValue2Node(componentMetrics, nodes);
// calculate notes' depth
int maxDepth = bfsDepth(roots);
// set nodes level & get max breadth
Map<Integer, Integer> counter = Maps.newHashMap();
int maxBreadth = 1;
for (Map.Entry<String, TreeNode> entry : linkMap.entrySet()) {
int layer = entry.getValue().getLayer();
nodes.get(entry.getKey()).setLevel(layer);
int breadth = 1;
if (counter.containsKey(layer)) {
breadth = counter.get(layer) + 1;
}
counter.put(layer, breadth);
if (maxBreadth < breadth) {
maxBreadth = breadth;
}
}
//adjust graph for components in one line
String PREFIX = "__adjust_prefix_";
int count = 1;
for (TreeNode node : linkMap.values()) {
int layer = node.getLayer();
node.setBreadth(counter.get(layer));
}
for (TreeNode tree : linkMap.values()) {
if (isInOneLine(tree.getChildren())) {
String id = PREFIX + count++;
TopologyNode node = new TopologyNode(id, id, false);
node.setLevel(tree.getLayer() + 1);
node.setIsHidden(true);
nodes.put(id, node);
TreeNode furthest = getFurthestNode(tree.getChildren());
TopologyEdge toEdge = new TopologyEdge(id, furthest.getComponentId(), edgeId++);
toEdge.setIsHidden(true);
edges.put(toEdge.getKey(), toEdge);
TopologyEdge fromEdge = new TopologyEdge(tree.getComponentId(), id, edgeId++);
fromEdge.setIsHidden(true);
edges.put(fromEdge.getKey(), fromEdge);
}
}
TopologyGraph graph = new TopologyGraph(Lists.newArrayList(nodes.values()), Lists.newArrayList(edges.values()));
graph.setDepth(maxDepth);
graph.setBreadth(maxBreadth);
//create graph object
return graph;
} } | public class class_name {
public static TopologyGraph getTopologyGraph(StormTopology stormTopology, List<MetricInfo> componentMetrics) {
Map<String, Bolt> bolts = stormTopology.get_bolts();
Map<String, SpoutSpec> spouts = stormTopology.get_spouts();
//remove system bolts
String[] remove_ids = new String[]{"__acker", "__system", "__topology_master"};
for (String id : remove_ids) {
bolts.remove(id); // depends on control dependency: [for], data = [id]
}
//<id, node>
Map<String, TopologyNode> nodes = Maps.newHashMap();
//<from:to,edge>
Map<String, TopologyEdge> edges = Maps.newHashMap();
List<TreeNode> roots = Lists.newArrayList(); //this is used to get tree depth
Map<String, TreeNode> linkMap = Maps.newHashMap(); //this is used to get tree depth
// init the nodes
for (Map.Entry<String, SpoutSpec> entry : spouts.entrySet()) {
String componentId = entry.getKey();
nodes.put(componentId, new TopologyNode(componentId, componentId, true)); // depends on control dependency: [for], data = [none]
TreeNode node = new TreeNode(componentId);
roots.add(node); // depends on control dependency: [for], data = [none]
linkMap.put(componentId, node); // depends on control dependency: [for], data = [none]
}
for (Map.Entry<String, Bolt> entry : bolts.entrySet()) {
String componentId = entry.getKey();
nodes.put(componentId, new TopologyNode(componentId, componentId, false)); // depends on control dependency: [for], data = [none]
linkMap.put(componentId, new TreeNode(componentId)); // depends on control dependency: [for], data = [none]
}
//init the edges
int edgeId = 1;
for (Map.Entry<String, Bolt> entry : bolts.entrySet()) {
String componentId = entry.getKey();
Bolt bolt = entry.getValue();
TreeNode node = linkMap.get(componentId);
for (Map.Entry<GlobalStreamId, Grouping> input : bolt.get_common().get_inputs().entrySet()) {
GlobalStreamId streamId = input.getKey();
String src = streamId.get_componentId();
if (nodes.containsKey(src)) {
TopologyEdge edge = new TopologyEdge(src, componentId, edgeId++);
edges.put(edge.getKey(), edge); // depends on control dependency: [if], data = [none]
// put into linkMap
linkMap.get(src).addChild(node); // depends on control dependency: [if], data = [none]
node.addSource(src); // depends on control dependency: [if], data = [none]
node.addParent(linkMap.get(src)); // depends on control dependency: [if], data = [none]
}
}
}
//calculate whether has circle
boolean isFixed = false;
while (!isFixed) {
isFixed = true; // depends on control dependency: [while], data = [none]
for (TreeNode node : linkMap.values()) {
for (TreeNode parent : node.getParents()) {
if (!node.addSources(parent.getSources())) {
isFixed = false; // depends on control dependency: [if], data = [none]
}
}
}
}
// fill value to edges
fillTPSValue2Edge(componentMetrics, edges);
fillTLCValue2Edge(componentMetrics, edges);
// fill value to nodes
fillValue2Node(componentMetrics, nodes);
// calculate notes' depth
int maxDepth = bfsDepth(roots);
// set nodes level & get max breadth
Map<Integer, Integer> counter = Maps.newHashMap();
int maxBreadth = 1;
for (Map.Entry<String, TreeNode> entry : linkMap.entrySet()) {
int layer = entry.getValue().getLayer();
nodes.get(entry.getKey()).setLevel(layer); // depends on control dependency: [for], data = [entry]
int breadth = 1;
if (counter.containsKey(layer)) {
breadth = counter.get(layer) + 1; // depends on control dependency: [if], data = [none]
}
counter.put(layer, breadth); // depends on control dependency: [for], data = [none]
if (maxBreadth < breadth) {
maxBreadth = breadth; // depends on control dependency: [if], data = [none]
}
}
//adjust graph for components in one line
String PREFIX = "__adjust_prefix_";
int count = 1;
for (TreeNode node : linkMap.values()) {
int layer = node.getLayer();
node.setBreadth(counter.get(layer)); // depends on control dependency: [for], data = [node]
}
for (TreeNode tree : linkMap.values()) {
if (isInOneLine(tree.getChildren())) {
String id = PREFIX + count++;
TopologyNode node = new TopologyNode(id, id, false);
node.setLevel(tree.getLayer() + 1); // depends on control dependency: [if], data = [none]
node.setIsHidden(true); // depends on control dependency: [if], data = [none]
nodes.put(id, node); // depends on control dependency: [if], data = [none]
TreeNode furthest = getFurthestNode(tree.getChildren());
TopologyEdge toEdge = new TopologyEdge(id, furthest.getComponentId(), edgeId++);
toEdge.setIsHidden(true); // depends on control dependency: [if], data = [none]
edges.put(toEdge.getKey(), toEdge); // depends on control dependency: [if], data = [none]
TopologyEdge fromEdge = new TopologyEdge(tree.getComponentId(), id, edgeId++);
fromEdge.setIsHidden(true); // depends on control dependency: [if], data = [none]
edges.put(fromEdge.getKey(), fromEdge); // depends on control dependency: [if], data = [none]
}
}
TopologyGraph graph = new TopologyGraph(Lists.newArrayList(nodes.values()), Lists.newArrayList(edges.values()));
graph.setDepth(maxDepth);
graph.setBreadth(maxBreadth);
//create graph object
return graph;
} } |
public class class_name {
public String save() {
Integer codeScriptId = getInt("codeScript.id");
CodeScript codeScript = null;
if (null == codeScriptId) {
codeScript = new CodeScript();
} else {
codeScript = (CodeScript) entityDao.get(CodeScript.class, codeScriptId);
}
codeScript.setUpdatedAt(new Date(System.currentTimeMillis()));
Model.populate(codeScript, Params.sub("codeScript"));
entityDao.saveOrUpdate(codeScript);
return redirect("search", "info.save.success");
} } | public class class_name {
public String save() {
Integer codeScriptId = getInt("codeScript.id");
CodeScript codeScript = null;
if (null == codeScriptId) {
codeScript = new CodeScript(); // depends on control dependency: [if], data = [none]
} else {
codeScript = (CodeScript) entityDao.get(CodeScript.class, codeScriptId); // depends on control dependency: [if], data = [codeScriptId)]
}
codeScript.setUpdatedAt(new Date(System.currentTimeMillis()));
Model.populate(codeScript, Params.sub("codeScript"));
entityDao.saveOrUpdate(codeScript);
return redirect("search", "info.save.success");
} } |
public class class_name {
public static boolean isDouble(String number) {
boolean result = false;
if (number != null) {
try {
Double.parseDouble(number);
result = true;
} catch (NumberFormatException e) {
}
}
return result;
} } | public class class_name {
public static boolean isDouble(String number) {
boolean result = false;
if (number != null) {
try {
Double.parseDouble(number); // depends on control dependency: [try], data = [none]
result = true; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
} // depends on control dependency: [catch], data = [none]
}
return result;
} } |
public class class_name {
public void sendToMe(SIBUuid8 targetME, int priority, AbstractMessage aMessage)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendToMe", new Object[] { aMessage, Integer.valueOf(priority), targetME });
// find an appropriate MPConnection
MPConnection firstChoice = findMPConnection(targetME);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "sendToMe", firstChoice);
// Minimal comms trace of the message we're trying to send
if (TraceComponent.isAnyTracingEnabled()) {
MECommsTrc.traceMessage(tc,
_messageProcessor,
aMessage.getGuaranteedTargetMessagingEngineUUID(),
MECommsTrc.OP_SEND,
firstChoice,
aMessage);
}
if(firstChoice != null)
{
//send the message
firstChoice.send(aMessage, priority);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "sendToMe");
} } | public class class_name {
public void sendToMe(SIBUuid8 targetME, int priority, AbstractMessage aMessage)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendToMe", new Object[] { aMessage, Integer.valueOf(priority), targetME });
// find an appropriate MPConnection
MPConnection firstChoice = findMPConnection(targetME);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "sendToMe", firstChoice);
// Minimal comms trace of the message we're trying to send
if (TraceComponent.isAnyTracingEnabled()) {
MECommsTrc.traceMessage(tc,
_messageProcessor,
aMessage.getGuaranteedTargetMessagingEngineUUID(),
MECommsTrc.OP_SEND,
firstChoice,
aMessage); // depends on control dependency: [if], data = [none]
}
if(firstChoice != null)
{
//send the message
firstChoice.send(aMessage, priority); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "sendToMe");
} } |
public class class_name {
private void install() {
File directory = getNPMDirectory();
if (directory.isDirectory()) {
// Check the version
String version = getVersionFromNPM(directory, log);
// Are we looking for a specific version ?
if (npmVersion != null) {
// Yes
if (!npmVersion.equals(version)) {
log.info("The NPM " + npmName + " is already installed but not in the requested version" +
" (requested: " + npmVersion + " - current: " + version + ") - uninstall it");
try {
FileUtils.deleteDirectory(directory);
} catch (IOException e) { //NOSONAR
// ignore it.
}
} else {
log.debug("NPM " + npmName + " already installed in " + directory.getAbsolutePath() +
" (" + version + ")");
return;
}
} else {
// No
log.debug("NPM " + npmName + " already installed in " + directory.getAbsolutePath() + " " +
"(" + version + ")");
return;
}
}
StringBuilder command = new StringBuilder();
command.append("install ");
if (installArguments != null) {
for (String s : installArguments) {
command.append(s);
command.append(" ");
}
}
if (npmVersion != null) {
command.append(npmName).append("@").append(npmVersion);
} else {
command.append(npmName);
}
try {
node.factoryForNPMInstallation().getNpmRunner(node.proxy()).execute(command.toString());
} catch (TaskRunnerException e) {
log.error("Error during the installation of the NPM " + npmName + " - check log", e);
}
} } | public class class_name {
private void install() {
File directory = getNPMDirectory();
if (directory.isDirectory()) {
// Check the version
String version = getVersionFromNPM(directory, log);
// Are we looking for a specific version ?
if (npmVersion != null) {
// Yes
if (!npmVersion.equals(version)) {
log.info("The NPM " + npmName + " is already installed but not in the requested version" +
" (requested: " + npmVersion + " - current: " + version + ") - uninstall it"); // depends on control dependency: [if], data = [none]
try {
FileUtils.deleteDirectory(directory); // depends on control dependency: [try], data = [none]
} catch (IOException e) { //NOSONAR
// ignore it.
} // depends on control dependency: [catch], data = [none]
} else {
log.debug("NPM " + npmName + " already installed in " + directory.getAbsolutePath() +
" (" + version + ")"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else {
// No
log.debug("NPM " + npmName + " already installed in " + directory.getAbsolutePath() + " " +
"(" + version + ")");
return;
}
}
StringBuilder command = new StringBuilder();
command.append("install ");
if (installArguments != null) {
for (String s : installArguments) {
command.append(s);
command.append(" ");
}
}
if (npmVersion != null) {
command.append(npmName).append("@").append(npmVersion);
} else {
command.append(npmName);
}
try {
node.factoryForNPMInstallation().getNpmRunner(node.proxy()).execute(command.toString());
} catch (TaskRunnerException e) {
log.error("Error during the installation of the NPM " + npmName + " - check log", e);
}
} } |
public class class_name {
public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean isNullGreater) {
if (c1 == c2) {
return 0;
} else if (c1 == null) {
return isNullGreater ? 1 : -1;
} else if (c2 == null) {
return isNullGreater ? -1 : 1;
}
return c1.compareTo(c2);
} } | public class class_name {
public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean isNullGreater) {
if (c1 == c2) {
return 0;
// depends on control dependency: [if], data = [none]
} else if (c1 == null) {
return isNullGreater ? 1 : -1;
// depends on control dependency: [if], data = [none]
} else if (c2 == null) {
return isNullGreater ? -1 : 1;
// depends on control dependency: [if], data = [none]
}
return c1.compareTo(c2);
} } |
public class class_name {
protected String captureStackTrace(String message) {
StringBuilder stringBuilder = new StringBuilder(String.format(message, Thread.currentThread().getName()));
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
for (int i = 0; i < trace.length; i++) {
stringBuilder.append(' ').append(trace[i]).append("\r\n");
}
stringBuilder.append("");
return stringBuilder.toString();
} } | public class class_name {
protected String captureStackTrace(String message) {
StringBuilder stringBuilder = new StringBuilder(String.format(message, Thread.currentThread().getName()));
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
for (int i = 0; i < trace.length; i++) {
stringBuilder.append(' ').append(trace[i]).append("\r\n"); // depends on control dependency: [for], data = [i]
}
stringBuilder.append("");
return stringBuilder.toString();
} } |
public class class_name {
public void addDocumentUriParticipantObject(String documentRetrieveUri, String documentUniqueId)
{
List<TypeValuePairType> tvp = new LinkedList<>();
if (documentUniqueId != null) {
tvp.add(getTypeValuePair("XDSDocumentEntry.uniqueId", documentUniqueId.getBytes()));
}
addParticipantObjectIdentification(
new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.URI(),
null,
null,
tvp,
documentRetrieveUri,
RFC3881ParticipantObjectTypeCodes.SYSTEM,
RFC3881ParticipantObjectTypeRoleCodes.REPORT,
null,
null);
} } | public class class_name {
public void addDocumentUriParticipantObject(String documentRetrieveUri, String documentUniqueId)
{
List<TypeValuePairType> tvp = new LinkedList<>();
if (documentUniqueId != null) {
tvp.add(getTypeValuePair("XDSDocumentEntry.uniqueId", documentUniqueId.getBytes())); // depends on control dependency: [if], data = [none]
}
addParticipantObjectIdentification(
new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.URI(),
null,
null,
tvp,
documentRetrieveUri,
RFC3881ParticipantObjectTypeCodes.SYSTEM,
RFC3881ParticipantObjectTypeRoleCodes.REPORT,
null,
null);
} } |
public class class_name {
private static void insertionSort(int array[], int offset, int end) {
for (int x=offset; x<end; ++x) {
for (int y=x; y>offset && array[y-1]>array[y]; y--) {
int temp = array[y];
array[y] = array[y-1];
array[y-1] = temp;
}
}
} } | public class class_name {
private static void insertionSort(int array[], int offset, int end) {
for (int x=offset; x<end; ++x) {
for (int y=x; y>offset && array[y-1]>array[y]; y--) {
int temp = array[y];
array[y] = array[y-1]; // depends on control dependency: [for], data = [y]
array[y-1] = temp; // depends on control dependency: [for], data = [y]
}
}
} } |
public class class_name {
public static void main(String[] args)
{
if (args.length==0 || args.length>2)
{
System.err.println
("\nUsage - java org.browsermob.proxy.jetty.http.HttpServer [<addr>:]<port>");
System.err.println
("\nUsage - java org.browsermob.proxy.jetty.http.HttpServer -r [savefile]");
System.err.println
(" Serves files from '.' directory");
System.err.println
(" Dump handler for not found requests");
System.err.println
(" Default port is 8080");
System.exit(1);
}
try{
if (args.length==1)
{
// Create the server
HttpServer server = new HttpServer();
// Default is no virtual host
String host=null;
HttpContext context = server.getContext(host,"/");
context.setResourceBase(".");
context.addHandler(new ResourceHandler());
context.addHandler(new DumpHandler());
context.addHandler(new NotFoundHandler());
InetAddrPort address = new InetAddrPort(args[0]);
server.addListener(address);
server.start();
}
else
{
Resource resource = Resource.newResource(args[1]);
ObjectInputStream in = new ObjectInputStream(resource.getInputStream());
HttpServer server = (HttpServer)in.readObject();
in.close();
server.start();
}
}
catch (Exception e)
{
log.warn(LogSupport.EXCEPTION,e);
}
} } | public class class_name {
public static void main(String[] args)
{
if (args.length==0 || args.length>2)
{
System.err.println
("\nUsage - java org.browsermob.proxy.jetty.http.HttpServer [<addr>:]<port>"); // depends on control dependency: [if], data = [none]
System.err.println
("\nUsage - java org.browsermob.proxy.jetty.http.HttpServer -r [savefile]"); // depends on control dependency: [if], data = [none]
System.err.println
(" Serves files from '.' directory"); // depends on control dependency: [if], data = [none]
System.err.println
(" Dump handler for not found requests"); // depends on control dependency: [if], data = [none]
System.err.println
(" Default port is 8080"); // depends on control dependency: [if], data = [none]
System.exit(1); // depends on control dependency: [if], data = [none]
}
try{
if (args.length==1)
{
// Create the server
HttpServer server = new HttpServer();
// Default is no virtual host
String host=null;
HttpContext context = server.getContext(host,"/");
context.setResourceBase("."); // depends on control dependency: [if], data = [none]
context.addHandler(new ResourceHandler()); // depends on control dependency: [if], data = [none]
context.addHandler(new DumpHandler()); // depends on control dependency: [if], data = [none]
context.addHandler(new NotFoundHandler()); // depends on control dependency: [if], data = [none]
InetAddrPort address = new InetAddrPort(args[0]);
server.addListener(address); // depends on control dependency: [if], data = [none]
server.start(); // depends on control dependency: [if], data = [none]
}
else
{
Resource resource = Resource.newResource(args[1]);
ObjectInputStream in = new ObjectInputStream(resource.getInputStream());
HttpServer server = (HttpServer)in.readObject();
in.close(); // depends on control dependency: [if], data = [none]
server.start(); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e)
{
log.warn(LogSupport.EXCEPTION,e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public int sendMessageToTopic(Collection<Session> sessionTargets, MessageToClient mtc, Object payload) {
int sended = 0;
logger.debug("Sending message to topic {}...", mtc);
Collection<Session> doublons = topicManager.getSessionsForTopic(mtc.getId());
if (doublons != null && !doublons.isEmpty()) {
Set<Session> sessions = new HashSet<>(doublons);
if (sessionTargets != null) {
sessions.retainAll(sessionTargets);
}
sended = sendMessageToTopicForSessions(sessions, mtc, payload);
} else {
logger.debug("No client for topic '{}'", mtc.getId());
}
return sended;
} } | public class class_name {
public int sendMessageToTopic(Collection<Session> sessionTargets, MessageToClient mtc, Object payload) {
int sended = 0;
logger.debug("Sending message to topic {}...", mtc);
Collection<Session> doublons = topicManager.getSessionsForTopic(mtc.getId());
if (doublons != null && !doublons.isEmpty()) {
Set<Session> sessions = new HashSet<>(doublons);
if (sessionTargets != null) {
sessions.retainAll(sessionTargets);
// depends on control dependency: [if], data = [(sessionTargets]
}
sended = sendMessageToTopicForSessions(sessions, mtc, payload);
// depends on control dependency: [if], data = [none]
} else {
logger.debug("No client for topic '{}'", mtc.getId());
// depends on control dependency: [if], data = [none]
}
return sended;
} } |
public class class_name {
private String getDocAsString(int numCurPara) {
if (numCurPara < 0 || allParas == null || allParas.size() < numCurPara - 1) {
return "";
}
int startPos;
int endPos;
if (numParasToCheck < 1) {
startPos = 0;
endPos = allParas.size();
} else {
startPos = numCurPara - numParasToCheck;
if(textIsChanged && doResetCheck) {
startPos -= numParasToCheck;
}
if (startPos < 0) {
startPos = 0;
}
endPos = numCurPara + 1 + numParasToCheck;
if(!textIsChanged) {
endPos += defaultParaCheck;
} else if(doResetCheck) {
endPos += numParasToCheck;
}
if (endPos > allParas.size()) {
endPos = allParas.size();
}
}
StringBuilder docText = new StringBuilder(fixLinebreak(allParas.get(startPos)));
for (int i = startPos + 1; i < endPos; i++) {
docText.append(END_OF_PARAGRAPH).append(fixLinebreak(allParas.get(i)));
}
return docText.toString();
} } | public class class_name {
private String getDocAsString(int numCurPara) {
if (numCurPara < 0 || allParas == null || allParas.size() < numCurPara - 1) {
return ""; // depends on control dependency: [if], data = [none]
}
int startPos;
int endPos;
if (numParasToCheck < 1) {
startPos = 0; // depends on control dependency: [if], data = [none]
endPos = allParas.size(); // depends on control dependency: [if], data = [none]
} else {
startPos = numCurPara - numParasToCheck; // depends on control dependency: [if], data = [none]
if(textIsChanged && doResetCheck) {
startPos -= numParasToCheck; // depends on control dependency: [if], data = [none]
}
if (startPos < 0) {
startPos = 0; // depends on control dependency: [if], data = [none]
}
endPos = numCurPara + 1 + numParasToCheck; // depends on control dependency: [if], data = [none]
if(!textIsChanged) {
endPos += defaultParaCheck; // depends on control dependency: [if], data = [none]
} else if(doResetCheck) {
endPos += numParasToCheck; // depends on control dependency: [if], data = [none]
}
if (endPos > allParas.size()) {
endPos = allParas.size(); // depends on control dependency: [if], data = [none]
}
}
StringBuilder docText = new StringBuilder(fixLinebreak(allParas.get(startPos)));
for (int i = startPos + 1; i < endPos; i++) {
docText.append(END_OF_PARAGRAPH).append(fixLinebreak(allParas.get(i))); // depends on control dependency: [for], data = [i]
}
return docText.toString();
} } |
public class class_name {
private String getRequestPath(HttpServletRequest request) {
String url = request.getServletPath();
if (request.getPathInfo() != null) {
url += request.getPathInfo();
}
return url;
} } | public class class_name {
private String getRequestPath(HttpServletRequest request) {
String url = request.getServletPath();
if (request.getPathInfo() != null) {
url += request.getPathInfo(); // depends on control dependency: [if], data = [none]
}
return url;
} } |
public class class_name {
private void markUnusedParameters(Node paramList, Scope fparamScope) {
for (Node param = paramList.getFirstChild(); param != null; param = param.getNext()) {
if (param.isUnusedParameter()) {
continue;
}
Node lValue = nameOfParam(param);
if (lValue == null) {
continue;
}
VarInfo varInfo = traverseNameNode(lValue, fparamScope);
if (varInfo.isRemovable()) {
param.setUnusedParameter(true);
compiler.reportChangeToEnclosingScope(paramList);
}
}
} } | public class class_name {
private void markUnusedParameters(Node paramList, Scope fparamScope) {
for (Node param = paramList.getFirstChild(); param != null; param = param.getNext()) {
if (param.isUnusedParameter()) {
continue;
}
Node lValue = nameOfParam(param);
if (lValue == null) {
continue;
}
VarInfo varInfo = traverseNameNode(lValue, fparamScope);
if (varInfo.isRemovable()) {
param.setUnusedParameter(true); // depends on control dependency: [if], data = [none]
compiler.reportChangeToEnclosingScope(paramList); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void addPkcs11ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPkcs11ButtonActionPerformed
String name = null;
try {
final int indexSelectedDriver = driverComboBox.getSelectedIndex();
name = driverConfig.getNames().get(indexSelectedDriver);
if (name.equals("")) {
return;
}
String library = driverConfig.getPaths().get(indexSelectedDriver);
if (library.equals("")) {
return;
}
int slot = driverConfig.getSlots().get(indexSelectedDriver);
if (slot < 0) {
return;
}
int slotListIndex = driverConfig.getSlotIndexes().get(indexSelectedDriver);
if (slotListIndex < 0) {
return;
}
String kspass = new String(pkcs11PasswordField.getPassword());
if (kspass.equals("")){
kspass = null;
}
PCKS11ConfigurationBuilder confBuilder = PKCS11Configuration.builder();
confBuilder.setName(name).setLibrary(library);
if (usePkcs11ExperimentalSliSupportCheckBox.isSelected()) {
confBuilder.setSlotListIndex(slotListIndex);
} else {
confBuilder.setSlotId(slot);
}
int ksIndex = contextManager.initPKCS11(confBuilder.build(), kspass);
if (ksIndex == -1) {
logger.error("The required PKCS#11 provider is not available ("
+ SSLContextManager.SUN_PKCS11_CANONICAL_CLASS_NAME + " or "
+ SSLContextManager.IBM_PKCS11_CONONICAL_CLASS_NAME + ").");
showErrorMessageSunPkcs11ProviderNotAvailable();
return;
}
// The PCKS11 driver/smartcard was initialized properly: reset login attempts
login_attempts = 0;
keyStoreListModel.insertElementAt(contextManager.getKeyStoreDescription(ksIndex), ksIndex);
// Issue 182
retry = true;
certificatejTabbedPane.setSelectedIndex(0);
activateFirstOnlyAliasOfKeyStore(ksIndex);
driverComboBox.setSelectedIndex(-1);
pkcs11PasswordField.setText("");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ProviderException) {
if ("Error parsing configuration".equals(e.getCause().getMessage())) {
// There was a problem with the configuration provided:
// - Missing library.
// - Malformed configuration.
// - ...
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
} else if ("Initialization failed".equals(e.getCause().getMessage())) {
// The initialisation may fail because of:
// - no smart card reader or smart card detected.
// - smart card is in use by other application.
// - ...
// Issue 182: Try to instantiate the PKCS11 provider twice if there are
// conflicts with other software (eg. Firefox), that is accessing it too.
if (retry) {
// Try two times only
retry = false;
addPkcs11ButtonActionPerformed(evt);
} else {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.pkcs11")},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
// Error message changed to explain that user should try to add it again...
retry = true;
logger.warn("Couldn't add key from "+name, e);
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} catch (java.io.IOException e) {
if (e.getMessage().equals("load failed") && e.getCause().getClass().getName().equals("javax.security.auth.login.FailedLoginException")) {
// Exception due to a failed login attempt: BAD PIN or password
login_attempts++;
String attempts = " ("+login_attempts+"/"+MAX_LOGIN_ATTEMPTS+") ";
if (login_attempts == (MAX_LOGIN_ATTEMPTS-1)) {
// Last attempt before blocking the smartcard
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.wrongpassword"),
Constant.messages.getString("options.cert.error.wrongpasswordlast"), attempts},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password"+attempts+": "+name+" *LAST TRY BEFORE BLOCKING*");
} else {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.wrongpassword"), attempts},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password"+attempts+": "+name);
}
}else{
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} catch (KeyStoreException e) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
} catch (Exception e) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(true, name, e);
}
} } | public class class_name {
private void addPkcs11ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPkcs11ButtonActionPerformed
String name = null;
try {
final int indexSelectedDriver = driverComboBox.getSelectedIndex();
name = driverConfig.getNames().get(indexSelectedDriver);
if (name.equals("")) {
return;
// depends on control dependency: [if], data = [none]
}
String library = driverConfig.getPaths().get(indexSelectedDriver);
if (library.equals("")) {
return;
// depends on control dependency: [if], data = [none]
}
int slot = driverConfig.getSlots().get(indexSelectedDriver);
if (slot < 0) {
return;
// depends on control dependency: [if], data = [none]
}
int slotListIndex = driverConfig.getSlotIndexes().get(indexSelectedDriver);
if (slotListIndex < 0) {
return;
// depends on control dependency: [if], data = [none]
}
String kspass = new String(pkcs11PasswordField.getPassword());
if (kspass.equals("")){
kspass = null;
// depends on control dependency: [if], data = [none]
}
PCKS11ConfigurationBuilder confBuilder = PKCS11Configuration.builder();
confBuilder.setName(name).setLibrary(library);
if (usePkcs11ExperimentalSliSupportCheckBox.isSelected()) {
confBuilder.setSlotListIndex(slotListIndex);
// depends on control dependency: [if], data = [none]
} else {
confBuilder.setSlotId(slot);
// depends on control dependency: [if], data = [none]
}
int ksIndex = contextManager.initPKCS11(confBuilder.build(), kspass);
if (ksIndex == -1) {
logger.error("The required PKCS#11 provider is not available ("
+ SSLContextManager.SUN_PKCS11_CANONICAL_CLASS_NAME + " or "
+ SSLContextManager.IBM_PKCS11_CONONICAL_CLASS_NAME + ").");
// depends on control dependency: [if], data = [none]
showErrorMessageSunPkcs11ProviderNotAvailable();
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
// The PCKS11 driver/smartcard was initialized properly: reset login attempts
login_attempts = 0;
keyStoreListModel.insertElementAt(contextManager.getKeyStoreDescription(ksIndex), ksIndex);
// Issue 182
retry = true;
certificatejTabbedPane.setSelectedIndex(0);
activateFirstOnlyAliasOfKeyStore(ksIndex);
driverComboBox.setSelectedIndex(-1);
pkcs11PasswordField.setText("");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ProviderException) {
if ("Error parsing configuration".equals(e.getCause().getMessage())) {
// There was a problem with the configuration provided:
// - Missing library.
// - Malformed configuration.
// - ...
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
// depends on control dependency: [if], data = [none]
} else if ("Initialization failed".equals(e.getCause().getMessage())) {
// The initialisation may fail because of:
// - no smart card reader or smart card detected.
// - smart card is in use by other application.
// - ...
// Issue 182: Try to instantiate the PKCS11 provider twice if there are
// conflicts with other software (eg. Firefox), that is accessing it too.
if (retry) {
// Try two times only
retry = false;
// depends on control dependency: [if], data = [none]
addPkcs11ButtonActionPerformed(evt);
// depends on control dependency: [if], data = [none]
} else {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.pkcs11")},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
// depends on control dependency: [if], data = [none]
// Error message changed to explain that user should try to add it again...
retry = true;
// depends on control dependency: [if], data = [none]
logger.warn("Couldn't add key from "+name, e);
// depends on control dependency: [if], data = [none]
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
// depends on control dependency: [if], data = [none]
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
// depends on control dependency: [if], data = [none]
}
} catch (java.io.IOException e) {
if (e.getMessage().equals("load failed") && e.getCause().getClass().getName().equals("javax.security.auth.login.FailedLoginException")) {
// Exception due to a failed login attempt: BAD PIN or password
login_attempts++;
String attempts = " ("+login_attempts+"/"+MAX_LOGIN_ATTEMPTS+") ";
if (login_attempts == (MAX_LOGIN_ATTEMPTS-1)) {
// Last attempt before blocking the smartcard
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.wrongpassword"),
Constant.messages.getString("options.cert.error.wrongpasswordlast"), attempts},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password"+attempts+": "+name+" *LAST TRY BEFORE BLOCKING*");
} else {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.wrongpassword"), attempts},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password"+attempts+": "+name);
}
}else{
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} catch (KeyStoreException e) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
} catch (Exception e) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(true, name, e);
}
} } |
public class class_name {
public Node.Nodes getNamedAttributeNodes() {
if (namedAttributeNodes != null) {
return namedAttributeNodes;
}
Node.Nodes result = new Node.Nodes();
// Look for the attribute in NamedAttribute children
Nodes nodes = getBody();
if( nodes != null ) {
int numChildNodes = nodes.size();
for( int i = 0; i < numChildNodes; i++ ) {
Node n = nodes.getNode( i );
if( n instanceof NamedAttribute ) {
result.add( n );
}
else if (! (n instanceof Comment)) {
// Nothing can come before jsp:attribute, and only
// jsp:body can come after it.
break;
}
}
}
namedAttributeNodes = result;
return result;
} } | public class class_name {
public Node.Nodes getNamedAttributeNodes() {
if (namedAttributeNodes != null) {
return namedAttributeNodes; // depends on control dependency: [if], data = [none]
}
Node.Nodes result = new Node.Nodes();
// Look for the attribute in NamedAttribute children
Nodes nodes = getBody();
if( nodes != null ) {
int numChildNodes = nodes.size();
for( int i = 0; i < numChildNodes; i++ ) {
Node n = nodes.getNode( i );
if( n instanceof NamedAttribute ) {
result.add( n ); // depends on control dependency: [if], data = [none]
}
else if (! (n instanceof Comment)) {
// Nothing can come before jsp:attribute, and only
// jsp:body can come after it.
break;
}
}
}
namedAttributeNodes = result;
return result;
} } |
public class class_name {
public static boolean isZip(final String filename)
{
for (final String element : FileConst.ZIP_EXTENSIONS)
{
if (filename.endsWith(element))
{
return true;
}
}
return false;
} } | public class class_name {
public static boolean isZip(final String filename)
{
for (final String element : FileConst.ZIP_EXTENSIONS)
{
if (filename.endsWith(element))
{
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Override
public Void visitType(TypeMirror t, String p) {
//System.out.printf(">> %s classValue: %s\n", p, t.toString());
if (inTasks && AnnotationAttributeType.TASK.getValue().equals(p)) {
// add value
currentValue = (currentValue == null) ? new Pair<Integer, String>() : currentValue;
currentValue.value1=t.toString();
if (currentValue.value0!=null && StringUtils.hasText(currentValue.value1)) {
tasks.add(currentValue);
currentValue=null;
}
}
return null;
} } | public class class_name {
@Override
public Void visitType(TypeMirror t, String p) {
//System.out.printf(">> %s classValue: %s\n", p, t.toString());
if (inTasks && AnnotationAttributeType.TASK.getValue().equals(p)) {
// add value
currentValue = (currentValue == null) ? new Pair<Integer, String>() : currentValue; // depends on control dependency: [if], data = [none]
currentValue.value1=t.toString(); // depends on control dependency: [if], data = [none]
if (currentValue.value0!=null && StringUtils.hasText(currentValue.value1)) {
tasks.add(currentValue); // depends on control dependency: [if], data = [none]
currentValue=null; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void remove(Channel channel)
{
synchronized (this._associatedChannels)
{
int index = findChannel(channel);
if (index != -1)
{
if (logger.isDebugEnabled())
logger.debug(
"CallTracker removing channel: " + this.toString() + " " + channel.getExtendedChannelName()); //$NON-NLS-1$ //$NON-NLS-2$
this._associatedChannels.remove(index);
}
}
} } | public class class_name {
public void remove(Channel channel)
{
synchronized (this._associatedChannels)
{
int index = findChannel(channel);
if (index != -1)
{
if (logger.isDebugEnabled())
logger.debug(
"CallTracker removing channel: " + this.toString() + " " + channel.getExtendedChannelName()); //$NON-NLS-1$ //$NON-NLS-2$
this._associatedChannels.remove(index); // depends on control dependency: [if], data = [(index]
}
}
} } |
public class class_name {
public void marshall(DisableDomainAutoRenewRequest disableDomainAutoRenewRequest, ProtocolMarshaller protocolMarshaller) {
if (disableDomainAutoRenewRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disableDomainAutoRenewRequest.getDomainName(), DOMAINNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DisableDomainAutoRenewRequest disableDomainAutoRenewRequest, ProtocolMarshaller protocolMarshaller) {
if (disableDomainAutoRenewRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disableDomainAutoRenewRequest.getDomainName(), DOMAINNAME_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 {
@Override
public List<Rectangle> getSegmentedRegions(BufferedImage bi, int pageIteratorLevel) throws TesseractException {
init();
setTessVariables();
try {
List<Rectangle> list = new ArrayList<Rectangle>();
setImage(bi, null);
Boxa boxes = TessBaseAPIGetComponentImages(handle, pageIteratorLevel, TRUE, null, null);
int boxCount = Leptonica1.boxaGetCount(boxes);
for (int i = 0; i < boxCount; i++) {
Box box = Leptonica1.boxaGetBox(boxes, i, L_CLONE);
if (box == null) {
continue;
}
list.add(new Rectangle(box.x, box.y, box.w, box.h));
PointerByReference pRef = new PointerByReference();
pRef.setValue(box.getPointer());
Leptonica1.boxDestroy(pRef);
}
PointerByReference pRef = new PointerByReference();
pRef.setValue(boxes.getPointer());
Leptonica1.boxaDestroy(pRef);
return list;
} catch (IOException ioe) {
// skip the problematic image
logger.warn(ioe.getMessage(), ioe);
throw new TesseractException(ioe);
} finally {
dispose();
}
} } | public class class_name {
@Override
public List<Rectangle> getSegmentedRegions(BufferedImage bi, int pageIteratorLevel) throws TesseractException {
init();
setTessVariables();
try {
List<Rectangle> list = new ArrayList<Rectangle>();
setImage(bi, null);
Boxa boxes = TessBaseAPIGetComponentImages(handle, pageIteratorLevel, TRUE, null, null);
int boxCount = Leptonica1.boxaGetCount(boxes);
for (int i = 0; i < boxCount; i++) {
Box box = Leptonica1.boxaGetBox(boxes, i, L_CLONE);
if (box == null) {
continue;
}
list.add(new Rectangle(box.x, box.y, box.w, box.h)); // depends on control dependency: [for], data = [none]
PointerByReference pRef = new PointerByReference();
pRef.setValue(box.getPointer()); // depends on control dependency: [for], data = [none]
Leptonica1.boxDestroy(pRef); // depends on control dependency: [for], data = [none]
}
PointerByReference pRef = new PointerByReference();
pRef.setValue(boxes.getPointer());
Leptonica1.boxaDestroy(pRef);
return list;
} catch (IOException ioe) {
// skip the problematic image
logger.warn(ioe.getMessage(), ioe);
throw new TesseractException(ioe);
} finally {
dispose();
}
} } |
public class class_name {
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Pair<String, ?>> filteredPrefs = new ArrayList<Pair<String, ?>>();
FilterResults filterFriends = new FilterResults();
if (!SharedPreferenceUtils.isEmptyString(constraint)) {
for (Pair<String, ?> keyValue : keyValSet) {
String constraintString = constraint.toString();
String prefixKey = "key: ";
String prefixValue = "value: ";
String first = keyValue.first;
Object second = keyValue.second;
if (constraintString.toLowerCase().startsWith(prefixKey)) {
if (first.toLowerCase().contains(constraintString.toLowerCase().substring(prefixKey.length()))) {
filteredPrefs.add(keyValue);
}
} else if (constraintString.toLowerCase().startsWith(prefixValue)) {
if (second != null) {
if (second.toString().contains(constraintString.toLowerCase().substring(prefixValue.length()))) {
filteredPrefs.add(keyValue);
}
}
} else {
if (first.equalsIgnoreCase(constraintString) || (second != null && second.toString()
.equalsIgnoreCase(constraintString))) {
filteredPrefs.add(keyValue);
}
}
}
} else {
filteredPrefs = keyValSet;
}
filterFriends.count = filteredPrefs.size();
filterFriends.values = filteredPrefs;
return filterFriends;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredCollection = (ArrayList<Pair<String, ?>>) results.values;
notifyDataSetChanged();
}
};
return filter;
} } | public class class_name {
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Pair<String, ?>> filteredPrefs = new ArrayList<Pair<String, ?>>();
FilterResults filterFriends = new FilterResults();
if (!SharedPreferenceUtils.isEmptyString(constraint)) {
for (Pair<String, ?> keyValue : keyValSet) {
String constraintString = constraint.toString();
String prefixKey = "key: ";
String prefixValue = "value: ";
String first = keyValue.first;
Object second = keyValue.second;
if (constraintString.toLowerCase().startsWith(prefixKey)) {
if (first.toLowerCase().contains(constraintString.toLowerCase().substring(prefixKey.length()))) {
filteredPrefs.add(keyValue); // depends on control dependency: [if], data = [none]
}
} else if (constraintString.toLowerCase().startsWith(prefixValue)) {
if (second != null) {
if (second.toString().contains(constraintString.toLowerCase().substring(prefixValue.length()))) {
filteredPrefs.add(keyValue); // depends on control dependency: [if], data = [none]
}
}
} else {
if (first.equalsIgnoreCase(constraintString) || (second != null && second.toString()
.equalsIgnoreCase(constraintString))) {
filteredPrefs.add(keyValue); // depends on control dependency: [if], data = [none]
}
}
}
} else {
filteredPrefs = keyValSet; // depends on control dependency: [if], data = [none]
}
filterFriends.count = filteredPrefs.size();
filterFriends.values = filteredPrefs;
return filterFriends;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredCollection = (ArrayList<Pair<String, ?>>) results.values;
notifyDataSetChanged();
}
};
return filter;
} } |
public class class_name {
public boolean isDocumentedAnnotation(TypeElement annotation) {
for (AnnotationMirror anno : annotation.getAnnotationMirrors()) {
if (getFullyQualifiedName(anno.getAnnotationType().asElement()).equals(
Documented.class.getName())) {
return true;
}
}
return false;
} } | public class class_name {
public boolean isDocumentedAnnotation(TypeElement annotation) {
for (AnnotationMirror anno : annotation.getAnnotationMirrors()) {
if (getFullyQualifiedName(anno.getAnnotationType().asElement()).equals(
Documented.class.getName())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public void setLogTypesToEnable(java.util.Collection<String> logTypesToEnable) {
if (logTypesToEnable == null) {
this.logTypesToEnable = null;
return;
}
this.logTypesToEnable = new java.util.ArrayList<String>(logTypesToEnable);
} } | public class class_name {
public void setLogTypesToEnable(java.util.Collection<String> logTypesToEnable) {
if (logTypesToEnable == null) {
this.logTypesToEnable = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.logTypesToEnable = new java.util.ArrayList<String>(logTypesToEnable);
} } |
public class class_name {
ClientStats generateLoadReport() {
ClientStats.Builder statsBuilder =
ClientStats.newBuilder()
.setTimestamp(Timestamps.fromNanos(time.currentTimeNanos()))
.setNumCallsStarted(callsStartedUpdater.getAndSet(this, 0))
.setNumCallsFinished(callsFinishedUpdater.getAndSet(this, 0))
.setNumCallsFinishedWithClientFailedToSend(callsFailedToSendUpdater.getAndSet(this, 0))
.setNumCallsFinishedKnownReceived(callsFinishedKnownReceivedUpdater.getAndSet(this, 0));
Map<String, LongHolder> localCallsDroppedPerToken = Collections.emptyMap();
synchronized (this) {
if (!callsDroppedPerToken.isEmpty()) {
localCallsDroppedPerToken = callsDroppedPerToken;
callsDroppedPerToken = new HashMap<>(localCallsDroppedPerToken.size());
}
}
for (Entry<String, LongHolder> entry : localCallsDroppedPerToken.entrySet()) {
statsBuilder.addCallsFinishedWithDrop(
ClientStatsPerToken.newBuilder()
.setLoadBalanceToken(entry.getKey())
.setNumCalls(entry.getValue().num)
.build());
}
return statsBuilder.build();
} } | public class class_name {
ClientStats generateLoadReport() {
ClientStats.Builder statsBuilder =
ClientStats.newBuilder()
.setTimestamp(Timestamps.fromNanos(time.currentTimeNanos()))
.setNumCallsStarted(callsStartedUpdater.getAndSet(this, 0))
.setNumCallsFinished(callsFinishedUpdater.getAndSet(this, 0))
.setNumCallsFinishedWithClientFailedToSend(callsFailedToSendUpdater.getAndSet(this, 0))
.setNumCallsFinishedKnownReceived(callsFinishedKnownReceivedUpdater.getAndSet(this, 0));
Map<String, LongHolder> localCallsDroppedPerToken = Collections.emptyMap();
synchronized (this) {
if (!callsDroppedPerToken.isEmpty()) {
localCallsDroppedPerToken = callsDroppedPerToken; // depends on control dependency: [if], data = [none]
callsDroppedPerToken = new HashMap<>(localCallsDroppedPerToken.size()); // depends on control dependency: [if], data = [none]
}
}
for (Entry<String, LongHolder> entry : localCallsDroppedPerToken.entrySet()) {
statsBuilder.addCallsFinishedWithDrop(
ClientStatsPerToken.newBuilder()
.setLoadBalanceToken(entry.getKey())
.setNumCalls(entry.getValue().num)
.build()); // depends on control dependency: [for], data = [none]
}
return statsBuilder.build();
} } |
public class class_name {
void zApplyBorderPropertiesList() {
// Skip this function if the settings have not been applied.
if (settings == null) {
return;
}
// Clear the current borders. (Set them to be invisible and black.)
CalendarBorderProperties clearBordersProperties = new CalendarBorderProperties(
new Point(1, 1), new Point(5, 5), Color.black, 0);
zApplyBorderPropertiesInstance(clearBordersProperties);
// Apply the current borderPropertiesList settings.
for (CalendarBorderProperties borderProperties : settings.getBorderPropertiesList()) {
zApplyBorderPropertiesInstance(borderProperties);
}
if (!(settings.getWeekNumbersDisplayed())) {
CalendarBorderProperties hideWeekNumberBorders = new CalendarBorderProperties(
new Point(1, 1), new Point(2, 5), Color.black, 0);
zApplyBorderPropertiesInstance(hideWeekNumberBorders);
}
drawCalendar();
} } | public class class_name {
void zApplyBorderPropertiesList() {
// Skip this function if the settings have not been applied.
if (settings == null) {
return; // depends on control dependency: [if], data = [none]
}
// Clear the current borders. (Set them to be invisible and black.)
CalendarBorderProperties clearBordersProperties = new CalendarBorderProperties(
new Point(1, 1), new Point(5, 5), Color.black, 0);
zApplyBorderPropertiesInstance(clearBordersProperties);
// Apply the current borderPropertiesList settings.
for (CalendarBorderProperties borderProperties : settings.getBorderPropertiesList()) {
zApplyBorderPropertiesInstance(borderProperties); // depends on control dependency: [for], data = [borderProperties]
}
if (!(settings.getWeekNumbersDisplayed())) {
CalendarBorderProperties hideWeekNumberBorders = new CalendarBorderProperties(
new Point(1, 1), new Point(2, 5), Color.black, 0);
zApplyBorderPropertiesInstance(hideWeekNumberBorders); // depends on control dependency: [if], data = [none]
}
drawCalendar();
} } |
public class class_name {
public char[] loadPassword(String account) {
byte[] pwBytes = loadPassword0(account.getBytes(UTF_8));
if (pwBytes == null) {
return null;
} else {
CharBuffer pwBuf = UTF_8.decode(ByteBuffer.wrap(pwBytes));
char[] pw = new char[pwBuf.remaining()];
pwBuf.get(pw);
Arrays.fill(pwBytes, (byte) 0x00);
Arrays.fill(pwBuf.array(), (char) 0x00);
return pw;
}
} } | public class class_name {
public char[] loadPassword(String account) {
byte[] pwBytes = loadPassword0(account.getBytes(UTF_8));
if (pwBytes == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
CharBuffer pwBuf = UTF_8.decode(ByteBuffer.wrap(pwBytes));
char[] pw = new char[pwBuf.remaining()];
pwBuf.get(pw); // depends on control dependency: [if], data = [none]
Arrays.fill(pwBytes, (byte) 0x00); // depends on control dependency: [if], data = [(pwBytes]
Arrays.fill(pwBuf.array(), (char) 0x00); // depends on control dependency: [if], data = [none]
return pw; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public DaoResult create(T bo) {
if (bo == null) {
return null;
}
try (Connection conn = getConnection()) {
return create(conn, bo);
} catch (SQLException e) {
throw new DaoException(e);
}
} } | public class class_name {
@Override
public DaoResult create(T bo) {
if (bo == null) {
return null; // depends on control dependency: [if], data = [none]
}
try (Connection conn = getConnection()) {
return create(conn, bo);
} catch (SQLException e) {
throw new DaoException(e);
}
} } |
public class class_name {
public void setExceptionType(String exceptionType) {
if (exceptionType != null) {
NullArgumentException.validateNotEmpty(exceptionType, "Error code");
}
this.exceptionType = exceptionType;
} } | public class class_name {
public void setExceptionType(String exceptionType) {
if (exceptionType != null) {
NullArgumentException.validateNotEmpty(exceptionType, "Error code"); // depends on control dependency: [if], data = [(exceptionType]
}
this.exceptionType = exceptionType;
} } |
public class class_name {
private synchronized boolean poll(long currentTimeMillis) {
long timeDiffMillis = currentTimeMillis - _lastPolled;
if (timeDiffMillis > POLL_THRESHOLD_MILLIS) {
final long lastModifiedBefore = _lastModified;
_lastModified = _file.lastModified();
_lastPolled = System.currentTimeMillis();
return _lastModified != lastModifiedBefore;
}
return false;
} } | public class class_name {
private synchronized boolean poll(long currentTimeMillis) {
long timeDiffMillis = currentTimeMillis - _lastPolled;
if (timeDiffMillis > POLL_THRESHOLD_MILLIS) {
final long lastModifiedBefore = _lastModified;
_lastModified = _file.lastModified(); // depends on control dependency: [if], data = [none]
_lastPolled = System.currentTimeMillis(); // depends on control dependency: [if], data = [none]
return _lastModified != lastModifiedBefore; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public String toHtmlString(final boolean rebuild, final Charset charset) {
final Charset previousCharset = this.charset;
try {
this.charset = charset;
return toHtmlString(rebuild);
} finally {
this.charset = previousCharset;
}
} } | public class class_name {
@Override
public String toHtmlString(final boolean rebuild, final Charset charset) {
final Charset previousCharset = this.charset;
try {
this.charset = charset; // depends on control dependency: [try], data = [none]
return toHtmlString(rebuild); // depends on control dependency: [try], data = [none]
} finally {
this.charset = previousCharset;
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.