code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public String quoteLiteral(String string) {
if (needingQuoteCharacters == null) {
needingQuoteCharacters = new UnicodeSet().addAll(syntaxCharacters).addAll(ignorableCharacters).addAll(extraQuotingCharacters); // .addAll(quoteCharacters)
if (usingSlash) needingQuoteCharacters.add(BACK_SLASH);
if (usingQuote) needingQuoteCharacters.add(SINGLE_QUOTE);
}
StringBuffer result = new StringBuffer();
int quotedChar = NO_QUOTE;
int cp;
for (int i = 0; i < string.length(); i += UTF16.getCharCount(cp)) {
cp = UTF16.charAt(string, i);
if (escapeCharacters.contains(cp)) {
// we may have to fix up previous characters
if (quotedChar == IN_QUOTE) {
result.append(SINGLE_QUOTE);
quotedChar = NO_QUOTE;
}
appendEscaped(result, cp);
continue;
}
if (needingQuoteCharacters.contains(cp)) {
// if we have already started a quote
if (quotedChar == IN_QUOTE) {
UTF16.append(result, cp);
if (usingQuote && cp == SINGLE_QUOTE) { // double it
result.append(SINGLE_QUOTE);
}
continue;
}
// otherwise not already in quote
if (usingSlash) {
result.append(BACK_SLASH);
UTF16.append(result, cp);
continue;
}
if (usingQuote) {
if (cp == SINGLE_QUOTE) { // double it and continue
result.append(SINGLE_QUOTE);
result.append(SINGLE_QUOTE);
continue;
}
result.append(SINGLE_QUOTE);
UTF16.append(result, cp);
quotedChar = IN_QUOTE;
continue;
}
// we have no choice but to use \\u or \\U
appendEscaped(result, cp);
continue;
}
// otherwise cp doesn't need quoting
// we may have to fix up previous characters
if (quotedChar == IN_QUOTE) {
result.append(SINGLE_QUOTE);
quotedChar = NO_QUOTE;
}
UTF16.append(result, cp);
}
// all done.
// we may have to fix up previous characters
if (quotedChar == IN_QUOTE) {
result.append(SINGLE_QUOTE);
}
return result.toString();
} } | public class class_name {
public String quoteLiteral(String string) {
if (needingQuoteCharacters == null) {
needingQuoteCharacters = new UnicodeSet().addAll(syntaxCharacters).addAll(ignorableCharacters).addAll(extraQuotingCharacters); // .addAll(quoteCharacters) // depends on control dependency: [if], data = [none]
if (usingSlash) needingQuoteCharacters.add(BACK_SLASH);
if (usingQuote) needingQuoteCharacters.add(SINGLE_QUOTE);
}
StringBuffer result = new StringBuffer();
int quotedChar = NO_QUOTE;
int cp;
for (int i = 0; i < string.length(); i += UTF16.getCharCount(cp)) {
cp = UTF16.charAt(string, i); // depends on control dependency: [for], data = [i]
if (escapeCharacters.contains(cp)) {
// we may have to fix up previous characters
if (quotedChar == IN_QUOTE) {
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [none]
quotedChar = NO_QUOTE; // depends on control dependency: [if], data = [none]
}
appendEscaped(result, cp); // depends on control dependency: [if], data = [none]
continue;
}
if (needingQuoteCharacters.contains(cp)) {
// if we have already started a quote
if (quotedChar == IN_QUOTE) {
UTF16.append(result, cp); // depends on control dependency: [if], data = [none]
if (usingQuote && cp == SINGLE_QUOTE) { // double it
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [SINGLE_QUOTE)]
}
continue;
}
// otherwise not already in quote
if (usingSlash) {
result.append(BACK_SLASH); // depends on control dependency: [if], data = [none]
UTF16.append(result, cp); // depends on control dependency: [if], data = [none]
continue;
}
if (usingQuote) {
if (cp == SINGLE_QUOTE) { // double it and continue
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [SINGLE_QUOTE)]
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [SINGLE_QUOTE)]
continue;
}
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [none]
UTF16.append(result, cp); // depends on control dependency: [if], data = [none]
quotedChar = IN_QUOTE; // depends on control dependency: [if], data = [none]
continue;
}
// we have no choice but to use \\u or \\U
appendEscaped(result, cp); // depends on control dependency: [if], data = [none]
continue;
}
// otherwise cp doesn't need quoting
// we may have to fix up previous characters
if (quotedChar == IN_QUOTE) {
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [none]
quotedChar = NO_QUOTE; // depends on control dependency: [if], data = [none]
}
UTF16.append(result, cp); // depends on control dependency: [for], data = [none]
}
// all done.
// we may have to fix up previous characters
if (quotedChar == IN_QUOTE) {
result.append(SINGLE_QUOTE); // depends on control dependency: [if], data = [none]
}
return result.toString();
} } |
public class class_name {
public static <E> int drainQueue(Queue<E> queue,
int elementsToDrain,
Predicate<E> drainedCountFilter) {
int drained = 0;
boolean drainMore = true;
for (int i = 0; i < elementsToDrain && drainMore; i++) {
E polled = queue.poll();
if (polled != null) {
if (drainedCountFilter == null || drainedCountFilter.test(polled)) {
drained++;
}
} else {
drainMore = false;
}
}
return drained;
} } | public class class_name {
public static <E> int drainQueue(Queue<E> queue,
int elementsToDrain,
Predicate<E> drainedCountFilter) {
int drained = 0;
boolean drainMore = true;
for (int i = 0; i < elementsToDrain && drainMore; i++) {
E polled = queue.poll();
if (polled != null) {
if (drainedCountFilter == null || drainedCountFilter.test(polled)) {
drained++; // depends on control dependency: [if], data = [none]
}
} else {
drainMore = false; // depends on control dependency: [if], data = [none]
}
}
return drained;
} } |
public class class_name {
synchronized String evaluateInterval() {
// During shutdown, threadpool may have been nulled out. In that case, don't bother analyzing.
// (We could log this in FFDC, but it isn't clear that it's worth doing so.)
if (threadPool == null)
return "threadPool == null";
int poolSize = threadPool.getPoolSize();
// Bail when there are no threads in the pool (unlikely)
if (poolSize <= 0) {
return "poolSize <= 0";
}
// we can't even think about adjusting the pool size until the underlying executor has aggressively
// grown the pool to the coreThreads value, so if that hasn't happened yet we should just bail
if (poolSize < coreThreads) {
return "poolSize < coreThreads";
}
long currentTime = System.currentTimeMillis();
long completedWork = threadPool.getCompletedTaskCount();
// Calculate work done for the current interval
long deltaTime = Math.max(currentTime - lastTimerPop, interval);
long deltaCompleted = completedWork - previousCompleted;
double throughput = 1000.0 * deltaCompleted / deltaTime;
try {
queueDepth = threadPool.getQueue().size();
boolean queueEmpty = (queueDepth <= 0);
// Count the number of consecutive times we've seen an empty queue
if (!queueEmpty) {
consecutiveQueueEmptyCount = 0;
} else if (lastAction != LastAction.SHRINK) { // 9/5/2012
consecutiveQueueEmptyCount++;
}
// update cpu utilization info
boolean cpuHigh = false;
processCpuUtil = CpuInfo.getJavaCpuUsage();
systemCpuUtil = CpuInfo.getSystemCpuUsage();
cpuUtil = Math.max(systemCpuUtil, processCpuUtil);
if (cpuUtil > highCpu) {
cpuHigh = true;
}
// Handle pausing the task if the pool has been idle
if (manageIdlePool(threadPool, deltaCompleted)) {
return "monitoring paused";
}
if (resolveHang(deltaCompleted, queueEmpty, poolSize)) {
/**
* Sleep the controller thread briefly after increasing the poolsize
* then update task count before returning to reduce the likelihood
* of a false negative hang check next cycle due to a few non-hung
* tasks executing on the newly created threads
*/
try {
Thread.sleep(10);
} catch (Exception ex) {
// do nothing
}
completedWork = threadPool.getCompletedTaskCount();
return "action take to resolve hang";
}
if (checkTargetPoolSize(poolSize)) {
return "poolSize != targetPoolSize";
}
controllerCycle++;
ThroughputDistribution currentStats = getThroughputDistribution(poolSize, true);
// handleOutliers will mark this 'true' if it resets the distribution
distributionReset = false;
// Reset statistics based on abnormal data points
if (handleOutliers(currentStats, throughput)) {
return "aberrant workload";
}
// If the distribution was reset we don't need to add the datapoint because
// handleOutliers already did that.
// If throughput was 0 we will not include that datapoint
if (!distributionReset && throughput > 0) {
currentStats.addDataPoint(throughput, controllerCycle);
}
boolean lowTput = false;
if (queueDepth == 0 && throughput < poolSize * lowTputThreadsRatio) {
lowTput = true;
if (tc.isEventEnabled()) {
Tr.event(tc, "low tput flag set: throughput: " + throughput + ", poolSize: "
+ poolSize + ", queueDepth: " + queueDepth,
threadPool);
}
}
setPoolIncrementDecrement(poolSize);
double forecast = currentStats.getMovingAverage();
double shrinkScore = getShrinkScore(poolSize, forecast, throughput, cpuHigh, lowTput);
double growScore = getGrowScore(poolSize, forecast, throughput, cpuHigh, lowTput);
// Adjust the poolsize only if one of the scores is both larger than the scoreFilterLevel
// and sufficiently larger than the other score. These conditions reduce poolsize fluctuation
// which might arise due to a weak or noisy signal from the historical throughput data.
int poolAdjustment = 0;
if (growScore >= growScoreFilterLevel && (growScore - growShrinkDiffFilter) > shrinkScore) {
poolAdjustment = poolIncrement;
} else if (shrinkScore >= shrinkScoreFilterLevel && (shrinkScore - growShrinkDiffFilter) > growScore) {
poolAdjustment = -poolDecrement;
}
// Force some random variation into the pool size algorithm
poolAdjustment = forceVariation(poolSize, poolAdjustment, deltaCompleted, lowTput);
// Format an event level trace point with the most useful data
if (tc.isEventEnabled()) {
Tr.event(tc, "Interval data", toIntervalData(throughput, forecast, shrinkScore, growScore, poolSize, poolAdjustment));
}
// Change the pool size and save the result, will check it at start of next control cycle
targetPoolSize = adjustPoolSize(poolSize, poolAdjustment);
} finally {
lastTimerPop = currentTime;
previousCompleted = completedWork;
previousThroughput = throughput;
}
return "";
} } | public class class_name {
synchronized String evaluateInterval() {
// During shutdown, threadpool may have been nulled out. In that case, don't bother analyzing.
// (We could log this in FFDC, but it isn't clear that it's worth doing so.)
if (threadPool == null)
return "threadPool == null";
int poolSize = threadPool.getPoolSize();
// Bail when there are no threads in the pool (unlikely)
if (poolSize <= 0) {
return "poolSize <= 0"; // depends on control dependency: [if], data = [none]
}
// we can't even think about adjusting the pool size until the underlying executor has aggressively
// grown the pool to the coreThreads value, so if that hasn't happened yet we should just bail
if (poolSize < coreThreads) {
return "poolSize < coreThreads"; // depends on control dependency: [if], data = [none]
}
long currentTime = System.currentTimeMillis();
long completedWork = threadPool.getCompletedTaskCount();
// Calculate work done for the current interval
long deltaTime = Math.max(currentTime - lastTimerPop, interval);
long deltaCompleted = completedWork - previousCompleted;
double throughput = 1000.0 * deltaCompleted / deltaTime;
try {
queueDepth = threadPool.getQueue().size(); // depends on control dependency: [try], data = [none]
boolean queueEmpty = (queueDepth <= 0);
// Count the number of consecutive times we've seen an empty queue
if (!queueEmpty) {
consecutiveQueueEmptyCount = 0; // depends on control dependency: [if], data = [none]
} else if (lastAction != LastAction.SHRINK) { // 9/5/2012
consecutiveQueueEmptyCount++; // depends on control dependency: [if], data = [none]
}
// update cpu utilization info
boolean cpuHigh = false;
processCpuUtil = CpuInfo.getJavaCpuUsage(); // depends on control dependency: [try], data = [none]
systemCpuUtil = CpuInfo.getSystemCpuUsage(); // depends on control dependency: [try], data = [none]
cpuUtil = Math.max(systemCpuUtil, processCpuUtil); // depends on control dependency: [try], data = [none]
if (cpuUtil > highCpu) {
cpuHigh = true; // depends on control dependency: [if], data = [none]
}
// Handle pausing the task if the pool has been idle
if (manageIdlePool(threadPool, deltaCompleted)) {
return "monitoring paused"; // depends on control dependency: [if], data = [none]
}
if (resolveHang(deltaCompleted, queueEmpty, poolSize)) {
/**
* Sleep the controller thread briefly after increasing the poolsize
* then update task count before returning to reduce the likelihood
* of a false negative hang check next cycle due to a few non-hung
* tasks executing on the newly created threads
*/
try {
Thread.sleep(10); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
// do nothing
} // depends on control dependency: [catch], data = [none]
completedWork = threadPool.getCompletedTaskCount(); // depends on control dependency: [if], data = [none]
return "action take to resolve hang"; // depends on control dependency: [if], data = [none]
}
if (checkTargetPoolSize(poolSize)) {
return "poolSize != targetPoolSize"; // depends on control dependency: [if], data = [none]
}
controllerCycle++; // depends on control dependency: [try], data = [none]
ThroughputDistribution currentStats = getThroughputDistribution(poolSize, true);
// handleOutliers will mark this 'true' if it resets the distribution
distributionReset = false; // depends on control dependency: [try], data = [none]
// Reset statistics based on abnormal data points
if (handleOutliers(currentStats, throughput)) {
return "aberrant workload"; // depends on control dependency: [if], data = [none]
}
// If the distribution was reset we don't need to add the datapoint because
// handleOutliers already did that.
// If throughput was 0 we will not include that datapoint
if (!distributionReset && throughput > 0) {
currentStats.addDataPoint(throughput, controllerCycle); // depends on control dependency: [if], data = [none]
}
boolean lowTput = false;
if (queueDepth == 0 && throughput < poolSize * lowTputThreadsRatio) {
lowTput = true; // depends on control dependency: [if], data = [none]
if (tc.isEventEnabled()) {
Tr.event(tc, "low tput flag set: throughput: " + throughput + ", poolSize: "
+ poolSize + ", queueDepth: " + queueDepth,
threadPool); // depends on control dependency: [if], data = [none]
}
}
setPoolIncrementDecrement(poolSize); // depends on control dependency: [try], data = [none]
double forecast = currentStats.getMovingAverage();
double shrinkScore = getShrinkScore(poolSize, forecast, throughput, cpuHigh, lowTput);
double growScore = getGrowScore(poolSize, forecast, throughput, cpuHigh, lowTput);
// Adjust the poolsize only if one of the scores is both larger than the scoreFilterLevel
// and sufficiently larger than the other score. These conditions reduce poolsize fluctuation
// which might arise due to a weak or noisy signal from the historical throughput data.
int poolAdjustment = 0;
if (growScore >= growScoreFilterLevel && (growScore - growShrinkDiffFilter) > shrinkScore) {
poolAdjustment = poolIncrement; // depends on control dependency: [if], data = [none]
} else if (shrinkScore >= shrinkScoreFilterLevel && (shrinkScore - growShrinkDiffFilter) > growScore) {
poolAdjustment = -poolDecrement; // depends on control dependency: [if], data = [none]
}
// Force some random variation into the pool size algorithm
poolAdjustment = forceVariation(poolSize, poolAdjustment, deltaCompleted, lowTput); // depends on control dependency: [try], data = [none]
// Format an event level trace point with the most useful data
if (tc.isEventEnabled()) {
Tr.event(tc, "Interval data", toIntervalData(throughput, forecast, shrinkScore, growScore, poolSize, poolAdjustment)); // depends on control dependency: [if], data = [none]
}
// Change the pool size and save the result, will check it at start of next control cycle
targetPoolSize = adjustPoolSize(poolSize, poolAdjustment); // depends on control dependency: [try], data = [none]
} finally {
lastTimerPop = currentTime;
previousCompleted = completedWork;
previousThroughput = throughput;
}
return "";
} } |
public class class_name {
private void a2(StringBuilder sb, int x) {
if (x < 10) {
sb.append('0');
}
sb.append(x);
} } | public class class_name {
private void a2(StringBuilder sb, int x) {
if (x < 10) {
sb.append('0'); // depends on control dependency: [if], data = [none]
}
sb.append(x);
} } |
public class class_name {
private void readNextPage() throws IOException {
processNextPage();
while (currentPageType != PAGE_META_TYPE_1 && currentPageType != PAGE_META_TYPE_2
&& currentPageType != PAGE_MIX_TYPE && currentPageType != PAGE_DATA_TYPE) {
if (eof) {
return;
}
processNextPage();
}
} } | public class class_name {
private void readNextPage() throws IOException {
processNextPage();
while (currentPageType != PAGE_META_TYPE_1 && currentPageType != PAGE_META_TYPE_2
&& currentPageType != PAGE_MIX_TYPE && currentPageType != PAGE_DATA_TYPE) {
if (eof) {
return; // depends on control dependency: [if], data = [none]
}
processNextPage();
}
} } |
public class class_name {
public static String convertToHumanFriendlyByteSize(long size) {
if (size < 1024) {
return size + " B";
}
int z = (63 - Long.numberOfLeadingZeros(size)) / 10;
double d = (double)size / (1L << (z * 10));
String format = (d % 1.0 == 0) ? "%.0f %sB" : "%.1f %sB";
return String.format(format, d, " KMGTPE".charAt(z));
} } | public class class_name {
public static String convertToHumanFriendlyByteSize(long size) {
if (size < 1024) {
return size + " B"; // depends on control dependency: [if], data = [none]
}
int z = (63 - Long.numberOfLeadingZeros(size)) / 10;
double d = (double)size / (1L << (z * 10));
String format = (d % 1.0 == 0) ? "%.0f %sB" : "%.1f %sB";
return String.format(format, d, " KMGTPE".charAt(z));
} } |
public class class_name {
@Override
public Matrix applyCommon(Matrix a, Matrix b) {
int n = a.rows() * b.rows();
int m = a.columns() * b.columns();
int p = b.rows();
int q = b.columns();
Matrix result = a.blankOfShape(n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
result.set(i, j, a.get(i / p, j / q) * b.get(i % p, j % q));
}
}
return result;
} } | public class class_name {
@Override
public Matrix applyCommon(Matrix a, Matrix b) {
int n = a.rows() * b.rows();
int m = a.columns() * b.columns();
int p = b.rows();
int q = b.columns();
Matrix result = a.blankOfShape(n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
result.set(i, j, a.get(i / p, j / q) * b.get(i % p, j % q)); // depends on control dependency: [for], data = [j]
}
}
return result;
} } |
public class class_name {
public boolean onItemClick(IDrawerItem selectedDrawerItem) {
//We only need to clear if the new item is selectable
if (selectedDrawerItem.isSelectable()) {
//crossfade if we are cross faded
if (mCrossFader != null) {
if (mCrossFader.isCrossfaded()) {
mCrossFader.crossfade();
}
}
//update everything
setSelection(selectedDrawerItem.getIdentifier());
return false;
} else {
return true;
}
} } | public class class_name {
public boolean onItemClick(IDrawerItem selectedDrawerItem) {
//We only need to clear if the new item is selectable
if (selectedDrawerItem.isSelectable()) {
//crossfade if we are cross faded
if (mCrossFader != null) {
if (mCrossFader.isCrossfaded()) {
mCrossFader.crossfade(); // depends on control dependency: [if], data = [none]
}
}
//update everything
setSelection(selectedDrawerItem.getIdentifier()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
} else {
return true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void close() {
LOG.debug("closing " + getClass().getCanonicalName());
if (session != null) {
session.close();
}
} } | public class class_name {
@Override
public void close() {
LOG.debug("closing " + getClass().getCanonicalName());
if (session != null) {
session.close(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String paramsToString(String charset, Map<String, String> params) {
StringBuffer sb = new StringBuffer();
try {
for (Map.Entry<String, String> item : params.entrySet()) {
sb.append("&");
sb.append(URLEncoder.encode(item.getKey(), charset));
sb.append("=");
sb.append(URLEncoder.encode(item.getValue(), charset));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return sb.substring(1);
} } | public class class_name {
public static String paramsToString(String charset, Map<String, String> params) {
StringBuffer sb = new StringBuffer();
try {
for (Map.Entry<String, String> item : params.entrySet()) {
sb.append("&"); // depends on control dependency: [for], data = [none]
sb.append(URLEncoder.encode(item.getKey(), charset)); // depends on control dependency: [for], data = [item]
sb.append("="); // depends on control dependency: [for], data = [none]
sb.append(URLEncoder.encode(item.getValue(), charset)); // depends on control dependency: [for], data = [item]
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return sb.substring(1);
} } |
public class class_name {
public static String rewriteMethodSignature(ClassNameRewriter classNameRewriter, String methodSignature) {
if (classNameRewriter != IdentityClassNameRewriter.instance()) {
SignatureParser parser = new SignatureParser(methodSignature);
StringBuilder buf = new StringBuilder();
buf.append('(');
for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext();) {
buf.append(rewriteSignature(classNameRewriter, i.next()));
}
buf.append(')');
buf.append(rewriteSignature(classNameRewriter, parser.getReturnTypeSignature()));
methodSignature = buf.toString();
}
return methodSignature;
} } | public class class_name {
public static String rewriteMethodSignature(ClassNameRewriter classNameRewriter, String methodSignature) {
if (classNameRewriter != IdentityClassNameRewriter.instance()) {
SignatureParser parser = new SignatureParser(methodSignature);
StringBuilder buf = new StringBuilder();
buf.append('('); // depends on control dependency: [if], data = [none]
for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext();) {
buf.append(rewriteSignature(classNameRewriter, i.next())); // depends on control dependency: [for], data = [i]
}
buf.append(')'); // depends on control dependency: [if], data = [none]
buf.append(rewriteSignature(classNameRewriter, parser.getReturnTypeSignature())); // depends on control dependency: [if], data = [(classNameRewriter]
methodSignature = buf.toString(); // depends on control dependency: [if], data = [none]
}
return methodSignature;
} } |
public class class_name {
private void generateSources() {
try {
ExecutorService pool = Executors.newFixedThreadPool(context.getSettings().getNbThread());
for (Java4CppType type : context.getClassesAlreadyDone()) {
Class<?> clazz = type.getRawClass();
if (isValid(clazz)) {
pool.execute(new SourceExecutor(context, type));
}
}
pool.shutdown();
while (!pool.isTerminated()) {
pool.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted " + e.getMessage());
}
} } | public class class_name {
private void generateSources() {
try {
ExecutorService pool = Executors.newFixedThreadPool(context.getSettings().getNbThread());
for (Java4CppType type : context.getClassesAlreadyDone()) {
Class<?> clazz = type.getRawClass();
if (isValid(clazz)) {
pool.execute(new SourceExecutor(context, type)); // depends on control dependency: [if], data = [none]
}
}
pool.shutdown(); // depends on control dependency: [try], data = [none]
while (!pool.isTerminated()) {
pool.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS); // depends on control dependency: [while], data = [none]
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void initialize(String scheme, String authority, String path) {
try {
this.uri = new URI(scheme, authority, normalizePath(path), null, null).normalize();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
} } | public class class_name {
private void initialize(String scheme, String authority, String path) {
try {
this.uri = new URI(scheme, authority, normalizePath(path), null, null).normalize(); // depends on control dependency: [try], data = [none]
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private V findSmallest(Node node) {
if (node == null) {
return null;
}
while (node.left != null) {
node = node.left;
}
return node.item;
} } | public class class_name {
private V findSmallest(Node node) {
if (node == null) {
return null; // depends on control dependency: [if], data = [none]
}
while (node.left != null) {
node = node.left; // depends on control dependency: [while], data = [none]
}
return node.item;
} } |
public class class_name {
public static double[][] transposeDiagonalTimes(double[][] m1, double[] d2, double[][] m3) {
final int innerdim = d2.length;
assert m1.length == innerdim : ERR_MATRIX_INNERDIM;
assert m3.length == innerdim : ERR_MATRIX_INNERDIM;
final int coldim1 = getColumnDimensionality(m1);
final int coldim2 = getColumnDimensionality(m3);
final double[][] r = new double[coldim1][coldim2];
final double[] Acoli = new double[innerdim]; // Buffer
// multiply it with each row from A
for(int i = 0; i < coldim1; i++) {
final double[] r_i = r[i]; // Output row
// Make a linear copy of column i from A
for(int k = 0; k < innerdim; k++) {
Acoli[k] = m1[k][i] * d2[k];
}
for(int j = 0; j < coldim2; j++) {
double s = 0;
for(int k = 0; k < innerdim; k++) {
s += Acoli[k] * m3[k][j];
}
r_i[j] = s;
}
}
return r;
} } | public class class_name {
public static double[][] transposeDiagonalTimes(double[][] m1, double[] d2, double[][] m3) {
final int innerdim = d2.length;
assert m1.length == innerdim : ERR_MATRIX_INNERDIM;
assert m3.length == innerdim : ERR_MATRIX_INNERDIM;
final int coldim1 = getColumnDimensionality(m1);
final int coldim2 = getColumnDimensionality(m3);
final double[][] r = new double[coldim1][coldim2];
final double[] Acoli = new double[innerdim]; // Buffer
// multiply it with each row from A
for(int i = 0; i < coldim1; i++) {
final double[] r_i = r[i]; // Output row
// Make a linear copy of column i from A
for(int k = 0; k < innerdim; k++) {
Acoli[k] = m1[k][i] * d2[k]; // depends on control dependency: [for], data = [k]
}
for(int j = 0; j < coldim2; j++) {
double s = 0;
for(int k = 0; k < innerdim; k++) {
s += Acoli[k] * m3[k][j]; // depends on control dependency: [for], data = [k]
}
r_i[j] = s; // depends on control dependency: [for], data = [j]
}
}
return r;
} } |
public class class_name {
protected List<IAlias> loadAliases(Scriptable cfg) throws IOException {
Object aliasList = cfg.get(ALIASES_CONFIGPARAM, cfg);
List<IAlias> aliases = new LinkedList<IAlias>();
if (aliasList instanceof Scriptable) {
for (Object id : ((Scriptable)aliasList).getIds()) {
if (id instanceof Number) {
Number i = (Number)id;
Object entry = ((Scriptable)aliasList).get((Integer)i, (Scriptable)aliasList);
if (entry instanceof Scriptable) {
Scriptable vec = (Scriptable)entry;
Object pattern = vec.get(0, vec);
Object replacement = vec.get(1, vec);
if (pattern == Scriptable.NOT_FOUND || replacement == Scriptable.NOT_FOUND) {
throw new IllegalArgumentException(toString(entry));
}
if (pattern instanceof Scriptable && "RegExp".equals(((Scriptable)pattern).getClassName())) { //$NON-NLS-1$
String regexlit = toString(pattern);
String regex = regexlit.substring(1, regexlit.lastIndexOf("/")); //$NON-NLS-1$
String flags = regexlit.substring(regexlit.lastIndexOf("/")+1); //$NON-NLS-1$
int options = 0;
if (flags.contains("i")) { //$NON-NLS-1$
options |= Pattern.CASE_INSENSITIVE;
}
pattern = Pattern.compile(regex, options);
} else {
pattern = toString(pattern);
}
if (!(replacement instanceof Scriptable) || !"Function".equals(((Scriptable)replacement).getClassName())) { //$NON-NLS-1$
replacement = toString(replacement);
}
aliases.add(newAlias(pattern, replacement));
} else {
throw new IllegalArgumentException(Context.toString(ALIASES_CONFIGPARAM + "[" + i + "] = " + Context.toString(entry))); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
throw new IllegalArgumentException("Unrecognized type for " + ALIASES_CONFIGPARAM + " - " + aliasList.getClass().toString()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
return aliases;
} } | public class class_name {
protected List<IAlias> loadAliases(Scriptable cfg) throws IOException {
Object aliasList = cfg.get(ALIASES_CONFIGPARAM, cfg);
List<IAlias> aliases = new LinkedList<IAlias>();
if (aliasList instanceof Scriptable) {
for (Object id : ((Scriptable)aliasList).getIds()) {
if (id instanceof Number) {
Number i = (Number)id;
Object entry = ((Scriptable)aliasList).get((Integer)i, (Scriptable)aliasList);
if (entry instanceof Scriptable) {
Scriptable vec = (Scriptable)entry;
Object pattern = vec.get(0, vec);
Object replacement = vec.get(1, vec);
if (pattern == Scriptable.NOT_FOUND || replacement == Scriptable.NOT_FOUND) {
throw new IllegalArgumentException(toString(entry));
}
if (pattern instanceof Scriptable && "RegExp".equals(((Scriptable)pattern).getClassName())) { //$NON-NLS-1$
String regexlit = toString(pattern);
String regex = regexlit.substring(1, regexlit.lastIndexOf("/")); //$NON-NLS-1$
String flags = regexlit.substring(regexlit.lastIndexOf("/")+1); //$NON-NLS-1$
int options = 0;
if (flags.contains("i")) { //$NON-NLS-1$
options |= Pattern.CASE_INSENSITIVE;
// depends on control dependency: [if], data = [none]
}
pattern = Pattern.compile(regex, options);
// depends on control dependency: [if], data = [none]
} else {
pattern = toString(pattern);
// depends on control dependency: [if], data = [none]
}
if (!(replacement instanceof Scriptable) || !"Function".equals(((Scriptable)replacement).getClassName())) { //$NON-NLS-1$
replacement = toString(replacement);
// depends on control dependency: [if], data = [none]
}
aliases.add(newAlias(pattern, replacement));
// depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException(Context.toString(ALIASES_CONFIGPARAM + "[" + i + "] = " + Context.toString(entry))); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
throw new IllegalArgumentException("Unrecognized type for " + ALIASES_CONFIGPARAM + " - " + aliasList.getClass().toString()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
return aliases;
} } |
public class class_name {
private static void getExplicitOverrides(Channel channel, Member member, AtomicLong allow, AtomicLong deny)
{
PermissionOverride override = channel.getPermissionOverride(member.getGuild().getPublicRole());
long allowRaw = 0;
long denyRaw = 0;
if (override != null)
{
denyRaw = override.getDeniedRaw();
allowRaw = override.getAllowedRaw();
}
long allowRole = 0;
long denyRole = 0;
// create temporary bit containers for role cascade
for (Role role : member.getRoles())
{
override = channel.getPermissionOverride(role);
if (override != null)
{
// important to update role cascade not others
denyRole |= override.getDeniedRaw();
allowRole |= override.getAllowedRaw();
}
}
// Override the raw values of public role then apply role cascade
allowRaw = (allowRaw & ~denyRole) | allowRole;
denyRaw = (denyRaw & ~allowRole) | denyRole;
override = channel.getPermissionOverride(member);
if (override != null)
{
// finally override the role cascade with member overrides
final long oDeny = override.getDeniedRaw();
final long oAllow = override.getAllowedRaw();
allowRaw = (allowRaw & ~oDeny) | oAllow;
denyRaw = (denyRaw & ~oAllow) | oDeny;
// this time we need to exclude new allowed bits from old denied ones and OR the new denied bits as final overrides
}
// set as resulting values
allow.set(allowRaw);
deny.set(denyRaw);
} } | public class class_name {
private static void getExplicitOverrides(Channel channel, Member member, AtomicLong allow, AtomicLong deny)
{
PermissionOverride override = channel.getPermissionOverride(member.getGuild().getPublicRole());
long allowRaw = 0;
long denyRaw = 0;
if (override != null)
{
denyRaw = override.getDeniedRaw(); // depends on control dependency: [if], data = [none]
allowRaw = override.getAllowedRaw(); // depends on control dependency: [if], data = [none]
}
long allowRole = 0;
long denyRole = 0;
// create temporary bit containers for role cascade
for (Role role : member.getRoles())
{
override = channel.getPermissionOverride(role); // depends on control dependency: [for], data = [role]
if (override != null)
{
// important to update role cascade not others
denyRole |= override.getDeniedRaw(); // depends on control dependency: [if], data = [none]
allowRole |= override.getAllowedRaw(); // depends on control dependency: [if], data = [none]
}
}
// Override the raw values of public role then apply role cascade
allowRaw = (allowRaw & ~denyRole) | allowRole;
denyRaw = (denyRaw & ~allowRole) | denyRole;
override = channel.getPermissionOverride(member);
if (override != null)
{
// finally override the role cascade with member overrides
final long oDeny = override.getDeniedRaw();
final long oAllow = override.getAllowedRaw();
allowRaw = (allowRaw & ~oDeny) | oAllow; // depends on control dependency: [if], data = [none]
denyRaw = (denyRaw & ~oAllow) | oDeny; // depends on control dependency: [if], data = [none]
// this time we need to exclude new allowed bits from old denied ones and OR the new denied bits as final overrides
}
// set as resulting values
allow.set(allowRaw);
deny.set(denyRaw);
} } |
public class class_name {
public boolean isPathAvailable(Path path) {
try {
Configuration conf = HadoopUtils.newConfiguration();
FileSystem fs = FileSystem.get(this.getFsURI(), conf);
if (fs.exists(path)) {
return true;
} else {
log.warn("The data path [" + path + "] is not available on FileSystem: " + this.getFsURI());
return false;
}
} catch (IOException ioe) {
log.warn("Errors occurred while checking path [" + path + "] existence " + this.getFsURI(), ioe);
return false;
}
} } | public class class_name {
public boolean isPathAvailable(Path path) {
try {
Configuration conf = HadoopUtils.newConfiguration();
FileSystem fs = FileSystem.get(this.getFsURI(), conf);
if (fs.exists(path)) {
return true; // depends on control dependency: [if], data = [none]
} else {
log.warn("The data path [" + path + "] is not available on FileSystem: " + this.getFsURI()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
} catch (IOException ioe) {
log.warn("Errors occurred while checking path [" + path + "] existence " + this.getFsURI(), ioe);
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String removeTrailingZeros(final String str) {
String result = str;
if (str != null && str.length() != 0) {
int endIndex = str.length();
while (endIndex > 1) {
final char ch = str.charAt(endIndex - 1);
if (ch != '0') {
break;
}
endIndex--;
}
if (endIndex < str.length()) {
result = str.substring(0, endIndex);
}
}
return result;
} } | public class class_name {
public static String removeTrailingZeros(final String str) {
String result = str;
if (str != null && str.length() != 0) {
int endIndex = str.length();
while (endIndex > 1) {
final char ch = str.charAt(endIndex - 1);
if (ch != '0') {
break;
}
endIndex--; // depends on control dependency: [while], data = [none]
}
if (endIndex < str.length()) {
result = str.substring(0, endIndex); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
@RequestMapping(value = "**", method = RequestMethod.GET)
public void
doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
try {
setup(req, res);
String sresult = null;
switch (this.params.command) {
case DOWNLOAD:
try {
String fulltargetpath = download();
if(this.params.fromform) {
sendForm("Download succeeded: result file: " + fulltargetpath);
} else {
Map<String, String> result = new HashMap<>();
result.put("download", fulltargetpath);
sresult = mapToString(result, true, "download");
sendOK(sresult);
}
} catch (SendError se) {
if(this.params.fromform) {
// Send back the download form with error msg
sendForm("Download failed: " + se.getMessage());
} else
throw se;
}
break;
case INQUIRE:
sresult = inquire();
// Send back the inquiry answers
sendOK(sresult);
break;
case NONE: // Use form-based download
// Send back the download form
sendForm("No files downloaded");
break;
}
} catch (SendError se) {
sendError(se);
} catch (Exception e) {
String msg = getStackTrace(e);
sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
} } | public class class_name {
@RequestMapping(value = "**", method = RequestMethod.GET)
public void
doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
try {
setup(req, res);
String sresult = null;
switch (this.params.command) {
case DOWNLOAD:
try {
String fulltargetpath = download();
if(this.params.fromform) {
sendForm("Download succeeded: result file: " + fulltargetpath); // depends on control dependency: [if], data = [none]
} else {
Map<String, String> result = new HashMap<>();
result.put("download", fulltargetpath); // depends on control dependency: [if], data = [none]
sresult = mapToString(result, true, "download"); // depends on control dependency: [if], data = [none]
sendOK(sresult); // depends on control dependency: [if], data = [none]
}
} catch (SendError se) {
if(this.params.fromform) {
// Send back the download form with error msg
sendForm("Download failed: " + se.getMessage()); // depends on control dependency: [if], data = [none]
} else
throw se;
} // depends on control dependency: [catch], data = [none]
break;
case INQUIRE:
sresult = inquire();
// Send back the inquiry answers
sendOK(sresult);
break;
case NONE: // Use form-based download
// Send back the download form
sendForm("No files downloaded");
break;
}
} catch (SendError se) {
sendError(se);
} catch (Exception e) {
String msg = getStackTrace(e);
sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
} } |
public class class_name {
public boolean shouldYieldFocus(JComponent input) {
boolean isValidInput = verify(input);
if (isValidInput) {
input.setBackground(background);
} else {
input.setBackground(warningBackground);
}
return isValidInput;
} } | public class class_name {
public boolean shouldYieldFocus(JComponent input) {
boolean isValidInput = verify(input);
if (isValidInput) {
input.setBackground(background); // depends on control dependency: [if], data = [none]
} else {
input.setBackground(warningBackground); // depends on control dependency: [if], data = [none]
}
return isValidInput;
} } |
public class class_name {
public static Treenode findNode(Treeview tree, String path, boolean create, Class<? extends Treenode> clazz,
MatchMode matchMode) {
if (tree.getChildCount() == 0 && !create) {
return null;
}
return CWFUtil.findNode(tree, clazz, path, create, matchMode);
} } | public class class_name {
public static Treenode findNode(Treeview tree, String path, boolean create, Class<? extends Treenode> clazz,
MatchMode matchMode) {
if (tree.getChildCount() == 0 && !create) {
return null; // depends on control dependency: [if], data = [none]
}
return CWFUtil.findNode(tree, clazz, path, create, matchMode);
} } |
public class class_name {
Filter getFilterProperty(String name, Filter defaultValue) {
String val = getProperty(name);
try {
if (val != null) {
return (Filter) getClassInstance(val).newInstance();
}
} catch (Exception ex) {
// We got one of a variety of exceptions in creating the
// class or creating an instance.
// Drop through.
}
// We got an exception. Return the defaultValue.
return defaultValue;
} } | public class class_name {
Filter getFilterProperty(String name, Filter defaultValue) {
String val = getProperty(name);
try {
if (val != null) {
return (Filter) getClassInstance(val).newInstance(); // depends on control dependency: [if], data = [(val]
}
} catch (Exception ex) {
// We got one of a variety of exceptions in creating the
// class or creating an instance.
// Drop through.
} // depends on control dependency: [catch], data = [none]
// We got an exception. Return the defaultValue.
return defaultValue;
} } |
public class class_name {
public Drawable downloadTile(final long pMapTileIndex, final int redirectCount, final String targetUrl,
final IFilesystemCache pFilesystemCache, final OnlineTileSourceBase pTileSource) throws CantContinueException {
//prevent infinite looping of redirects, rare but very possible for misconfigured servers
if (redirectCount>3) {
return null;
}
String userAgent = null;
if (pTileSource.getTileSourcePolicy().normalizesUserAgent()) {
userAgent = Configuration.getInstance().getNormalizedUserAgent();
}
if (userAgent == null) {
userAgent = Configuration.getInstance().getUserAgentValue();
}
if (!pTileSource.getTileSourcePolicy().acceptsUserAgent(userAgent)) {
Log.e(IMapView.LOGTAG,"Please configure a relevant user agent; current value is: " + userAgent);
return null;
}
InputStream in = null;
OutputStream out = null;
HttpURLConnection c=null;
ByteArrayInputStream byteStream = null;
ByteArrayOutputStream dataStream = null;
try {
final String tileURLString = targetUrl;
if (Configuration.getInstance().isDebugMode()) {
Log.d(IMapView.LOGTAG,"Downloading Maptile from url: " + tileURLString);
}
if (TextUtils.isEmpty(tileURLString)) {
return null;
}
//TODO in the future, it may be necessary to allow app's using this library to override the SSL socket factory. It would here somewhere
if (Configuration.getInstance().getHttpProxy() != null) {
c = (HttpURLConnection) new URL(tileURLString).openConnection(Configuration.getInstance().getHttpProxy());
} else {
c = (HttpURLConnection) new URL(tileURLString).openConnection();
}
c.setUseCaches(true);
c.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), userAgent);
for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
c.setRequestProperty(entry.getKey(), entry.getValue());
}
c.connect();
// Check to see if we got success
if (c.getResponseCode() != 200) {
switch (c.getResponseCode()) {
case 301:
case 302:
case 307:
case 308:
if (Configuration.getInstance().isMapTileDownloaderFollowRedirects()) {
//this is a redirect, check the header for a 'Location' header
String redirectUrl = c.getHeaderField("Location");
if (redirectUrl != null) {
if (redirectUrl.startsWith("/")) {
//in this case we need to stitch together a full url
URL old = new URL(targetUrl);
int port = old.getPort();
boolean secure = targetUrl.toLowerCase().startsWith("https://");
if (port == -1)
if (targetUrl.toLowerCase().startsWith("http://")) {
port = 80;
} else {
port = 443;
}
redirectUrl = (secure ? "https://" : "http") + old.getHost() + ":" + port + redirectUrl;
}
Log.i(IMapView.LOGTAG, "Http redirect for MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage() + " to url " + redirectUrl);
return downloadTile(pMapTileIndex, redirectCount + 1, redirectUrl, pFilesystemCache, pTileSource);
}
break;
} //else follow through the normal path of aborting the download
default: {
Log.w(IMapView.LOGTAG, "Problem downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage());
if (Configuration.getInstance().isDebugMapTileDownloader()) {
Log.d(IMapView.LOGTAG, tileURLString);
}
Counters.tileDownloadErrors++;
in = c.getErrorStream(); // in order to have the error stream purged by the finally block
return null;
}
}
}
String mime = c.getHeaderField("Content-Type");
if (Configuration.getInstance().isDebugMapTileDownloader()) {
Log.d(IMapView.LOGTAG, tileURLString + " success, mime is " + mime );
}
if (mime!=null && !mime.toLowerCase().contains("image")) {
Log.w(IMapView.LOGTAG, tileURLString + " success, however the mime type does not appear to be an image " + mime );
}
in = c.getInputStream();
dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
final long expirationTime = computeExpirationTime(
c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_EXPIRES_HEADER),
c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_CACHECONTROL_HEADER),
System.currentTimeMillis());
StreamUtils.copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
byteStream = new ByteArrayInputStream(data);
// Save the data to the cache
//this is the only point in which we insert tiles to the db or local file system.
if (pFilesystemCache != null) {
pFilesystemCache.saveFile(pTileSource, pMapTileIndex, byteStream, expirationTime);
byteStream.reset();
}
return pTileSource.getDrawable(byteStream);
} catch (final UnknownHostException e) {
Log.w(IMapView.LOGTAG,"UnknownHostException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
Counters.tileDownloadErrors++;
} catch (final BitmapTileSourceBase.LowMemoryException e) {
// low memory so empty the queue
Counters.countOOM++;
Log.w(IMapView.LOGTAG,"LowMemoryException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
throw new CantContinueException(e);
} catch (final FileNotFoundException e) {
Counters.tileDownloadErrors++;
Log.w(IMapView.LOGTAG,"Tile not found: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
} catch (final IOException e) {
Counters.tileDownloadErrors++;
Log.w(IMapView.LOGTAG,"IOException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
} catch (final Throwable e) {
Counters.tileDownloadErrors++;
Log.e(IMapView.LOGTAG,"Error downloading MapTile: " + MapTileIndex.toString(pMapTileIndex), e);
} finally {
StreamUtils.closeStream(in);
StreamUtils.closeStream(out);
StreamUtils.closeStream(byteStream);
StreamUtils.closeStream(dataStream);
try{
c.disconnect();
} catch (Exception ex){}
}
return null;
} } | public class class_name {
public Drawable downloadTile(final long pMapTileIndex, final int redirectCount, final String targetUrl,
final IFilesystemCache pFilesystemCache, final OnlineTileSourceBase pTileSource) throws CantContinueException {
//prevent infinite looping of redirects, rare but very possible for misconfigured servers
if (redirectCount>3) {
return null;
}
String userAgent = null;
if (pTileSource.getTileSourcePolicy().normalizesUserAgent()) {
userAgent = Configuration.getInstance().getNormalizedUserAgent();
}
if (userAgent == null) {
userAgent = Configuration.getInstance().getUserAgentValue();
}
if (!pTileSource.getTileSourcePolicy().acceptsUserAgent(userAgent)) {
Log.e(IMapView.LOGTAG,"Please configure a relevant user agent; current value is: " + userAgent);
return null;
}
InputStream in = null;
OutputStream out = null;
HttpURLConnection c=null;
ByteArrayInputStream byteStream = null;
ByteArrayOutputStream dataStream = null;
try {
final String tileURLString = targetUrl;
if (Configuration.getInstance().isDebugMode()) {
Log.d(IMapView.LOGTAG,"Downloading Maptile from url: " + tileURLString); // depends on control dependency: [if], data = [none]
}
if (TextUtils.isEmpty(tileURLString)) {
return null; // depends on control dependency: [if], data = [none]
}
//TODO in the future, it may be necessary to allow app's using this library to override the SSL socket factory. It would here somewhere
if (Configuration.getInstance().getHttpProxy() != null) {
c = (HttpURLConnection) new URL(tileURLString).openConnection(Configuration.getInstance().getHttpProxy()); // depends on control dependency: [if], data = [(Configuration.getInstance().getHttpProxy()]
} else {
c = (HttpURLConnection) new URL(tileURLString).openConnection(); // depends on control dependency: [if], data = [none]
}
c.setUseCaches(true);
c.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), userAgent);
for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
c.setRequestProperty(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
c.connect();
// Check to see if we got success
if (c.getResponseCode() != 200) {
switch (c.getResponseCode()) {
case 301:
case 302:
case 307:
case 308:
if (Configuration.getInstance().isMapTileDownloaderFollowRedirects()) {
//this is a redirect, check the header for a 'Location' header
String redirectUrl = c.getHeaderField("Location");
if (redirectUrl != null) {
if (redirectUrl.startsWith("/")) {
//in this case we need to stitch together a full url
URL old = new URL(targetUrl);
int port = old.getPort();
boolean secure = targetUrl.toLowerCase().startsWith("https://");
if (port == -1)
if (targetUrl.toLowerCase().startsWith("http://")) {
port = 80;
} else {
port = 443;
}
redirectUrl = (secure ? "https://" : "http") + old.getHost() + ":" + port + redirectUrl;
}
Log.i(IMapView.LOGTAG, "Http redirect for MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage() + " to url " + redirectUrl);
return downloadTile(pMapTileIndex, redirectCount + 1, redirectUrl, pFilesystemCache, pTileSource);
}
break;
} //else follow through the normal path of aborting the download
default: {
Log.w(IMapView.LOGTAG, "Problem downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage());
if (Configuration.getInstance().isDebugMapTileDownloader()) {
Log.d(IMapView.LOGTAG, tileURLString);
}
Counters.tileDownloadErrors++;
in = c.getErrorStream(); // in order to have the error stream purged by the finally block
return null;
}
}
}
String mime = c.getHeaderField("Content-Type");
if (Configuration.getInstance().isDebugMapTileDownloader()) {
Log.d(IMapView.LOGTAG, tileURLString + " success, mime is " + mime );
}
if (mime!=null && !mime.toLowerCase().contains("image")) {
Log.w(IMapView.LOGTAG, tileURLString + " success, however the mime type does not appear to be an image " + mime );
}
in = c.getInputStream();
dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
final long expirationTime = computeExpirationTime(
c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_EXPIRES_HEADER),
c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_CACHECONTROL_HEADER),
System.currentTimeMillis());
StreamUtils.copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
byteStream = new ByteArrayInputStream(data);
// Save the data to the cache
//this is the only point in which we insert tiles to the db or local file system.
if (pFilesystemCache != null) {
pFilesystemCache.saveFile(pTileSource, pMapTileIndex, byteStream, expirationTime);
byteStream.reset();
}
return pTileSource.getDrawable(byteStream);
} catch (final UnknownHostException e) {
Log.w(IMapView.LOGTAG,"UnknownHostException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
Counters.tileDownloadErrors++;
} catch (final BitmapTileSourceBase.LowMemoryException e) {
// low memory so empty the queue
Counters.countOOM++;
Log.w(IMapView.LOGTAG,"LowMemoryException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
throw new CantContinueException(e);
} catch (final FileNotFoundException e) {
Counters.tileDownloadErrors++;
Log.w(IMapView.LOGTAG,"Tile not found: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
} catch (final IOException e) {
Counters.tileDownloadErrors++;
Log.w(IMapView.LOGTAG,"IOException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
} catch (final Throwable e) {
Counters.tileDownloadErrors++;
Log.e(IMapView.LOGTAG,"Error downloading MapTile: " + MapTileIndex.toString(pMapTileIndex), e);
} finally {
StreamUtils.closeStream(in);
StreamUtils.closeStream(out);
StreamUtils.closeStream(byteStream);
StreamUtils.closeStream(dataStream);
try{
c.disconnect();
} catch (Exception ex){}
}
return null;
} } |
public class class_name {
public ListAccountSettingsResult withSettings(Setting... settings) {
if (this.settings == null) {
setSettings(new com.amazonaws.internal.SdkInternalList<Setting>(settings.length));
}
for (Setting ele : settings) {
this.settings.add(ele);
}
return this;
} } | public class class_name {
public ListAccountSettingsResult withSettings(Setting... settings) {
if (this.settings == null) {
setSettings(new com.amazonaws.internal.SdkInternalList<Setting>(settings.length)); // depends on control dependency: [if], data = [none]
}
for (Setting ele : settings) {
this.settings.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private String doPasswdAuth(HttpServletRequest request, String authType)
throws HttpAuthenticationException {
String userName = getUsername(request, authType);
// No-op when authType is NOSASL
if (!authType.equalsIgnoreCase(HiveAuthFactory.AuthTypes.NOSASL.toString())) {
try {
AuthMethods authMethod = AuthMethods.getValidAuthMethod(authType);
PasswdAuthenticationProvider provider =
AuthenticationProviderFactory.getAuthenticationProvider(authMethod);
provider.Authenticate(userName, getPassword(request, authType));
} catch (Exception e) {
throw new HttpAuthenticationException(e);
}
}
return userName;
} } | public class class_name {
private String doPasswdAuth(HttpServletRequest request, String authType)
throws HttpAuthenticationException {
String userName = getUsername(request, authType);
// No-op when authType is NOSASL
if (!authType.equalsIgnoreCase(HiveAuthFactory.AuthTypes.NOSASL.toString())) {
try {
AuthMethods authMethod = AuthMethods.getValidAuthMethod(authType);
PasswdAuthenticationProvider provider =
AuthenticationProviderFactory.getAuthenticationProvider(authMethod);
provider.Authenticate(userName, getPassword(request, authType)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new HttpAuthenticationException(e);
} // depends on control dependency: [catch], data = [none]
}
return userName;
} } |
public class class_name {
public <S extends F> Pattern<T, S> subtype(final Class<S> subtypeClass) {
Preconditions.checkNotNull(subtypeClass, "The class cannot be null.");
if (condition == null) {
this.condition = new SubtypeCondition<F>(subtypeClass);
} else {
this.condition = new RichAndCondition<>(condition, new SubtypeCondition<F>(subtypeClass));
}
@SuppressWarnings("unchecked")
Pattern<T, S> result = (Pattern<T, S>) this;
return result;
} } | public class class_name {
public <S extends F> Pattern<T, S> subtype(final Class<S> subtypeClass) {
Preconditions.checkNotNull(subtypeClass, "The class cannot be null.");
if (condition == null) {
this.condition = new SubtypeCondition<F>(subtypeClass); // depends on control dependency: [if], data = [none]
} else {
this.condition = new RichAndCondition<>(condition, new SubtypeCondition<F>(subtypeClass)); // depends on control dependency: [if], data = [(condition]
}
@SuppressWarnings("unchecked")
Pattern<T, S> result = (Pattern<T, S>) this;
return result;
} } |
public class class_name {
public ClusterDbRevision withRevisionTargets(RevisionTarget... revisionTargets) {
if (this.revisionTargets == null) {
setRevisionTargets(new com.amazonaws.internal.SdkInternalList<RevisionTarget>(revisionTargets.length));
}
for (RevisionTarget ele : revisionTargets) {
this.revisionTargets.add(ele);
}
return this;
} } | public class class_name {
public ClusterDbRevision withRevisionTargets(RevisionTarget... revisionTargets) {
if (this.revisionTargets == null) {
setRevisionTargets(new com.amazonaws.internal.SdkInternalList<RevisionTarget>(revisionTargets.length)); // depends on control dependency: [if], data = [none]
}
for (RevisionTarget ele : revisionTargets) {
this.revisionTargets.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private void addTypesToFunctions(
Node objLit, String thisType, PolymerClassDefinition.DefinitionType defType) {
checkState(objLit.isObjectLit());
for (Node keyNode : objLit.children()) {
Node value = keyNode.getLastChild();
if (value != null && value.isFunction()) {
JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(keyNode.getJSDocInfo());
fnDoc.recordThisType(
new JSTypeExpression(new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE));
keyNode.setJSDocInfo(fnDoc.build());
}
}
// Add @this and @return to default property values.
for (MemberDefinition property :
PolymerPassStaticUtils.extractProperties(
objLit,
defType,
compiler,
/** constructor= */
null)) {
if (!property.value.isObjectLit()) {
continue;
}
Node defaultValue = NodeUtil.getFirstPropMatchingKey(property.value, "value");
if (defaultValue == null || !defaultValue.isFunction()) {
continue;
}
Node defaultValueKey = defaultValue.getParent();
JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(defaultValueKey.getJSDocInfo());
fnDoc.recordThisType(
new JSTypeExpression(new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE));
fnDoc.recordReturnType(PolymerPassStaticUtils.getTypeFromProperty(property, compiler));
defaultValueKey.setJSDocInfo(fnDoc.build());
}
} } | public class class_name {
private void addTypesToFunctions(
Node objLit, String thisType, PolymerClassDefinition.DefinitionType defType) {
checkState(objLit.isObjectLit());
for (Node keyNode : objLit.children()) {
Node value = keyNode.getLastChild();
if (value != null && value.isFunction()) {
JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(keyNode.getJSDocInfo());
fnDoc.recordThisType(
new JSTypeExpression(new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE)); // depends on control dependency: [if], data = [none]
keyNode.setJSDocInfo(fnDoc.build()); // depends on control dependency: [if], data = [none]
}
}
// Add @this and @return to default property values.
for (MemberDefinition property :
PolymerPassStaticUtils.extractProperties(
objLit,
defType,
compiler,
/** constructor= */
null)) {
if (!property.value.isObjectLit()) {
continue;
}
Node defaultValue = NodeUtil.getFirstPropMatchingKey(property.value, "value");
if (defaultValue == null || !defaultValue.isFunction()) {
continue;
}
Node defaultValueKey = defaultValue.getParent();
JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(defaultValueKey.getJSDocInfo());
fnDoc.recordThisType(
new JSTypeExpression(new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE)); // depends on control dependency: [for], data = [none]
fnDoc.recordReturnType(PolymerPassStaticUtils.getTypeFromProperty(property, compiler)); // depends on control dependency: [for], data = [property]
defaultValueKey.setJSDocInfo(fnDoc.build()); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public boolean containsHeaderOut(String name)
{
ArrayList<String> headerKeys = _headerKeysOut;
int size = headerKeys.size();
for (int i = 0; i < size; i++) {
String oldKey = headerKeys.get(i);
if (oldKey.equalsIgnoreCase(name)) {
return true;
}
}
if (name.equalsIgnoreCase("content-type")) {
return _contentTypeOut != null;
}
if (name.equalsIgnoreCase("content-length")) {
return _contentLengthOut >= 0;
}
return false;
} } | public class class_name {
public boolean containsHeaderOut(String name)
{
ArrayList<String> headerKeys = _headerKeysOut;
int size = headerKeys.size();
for (int i = 0; i < size; i++) {
String oldKey = headerKeys.get(i);
if (oldKey.equalsIgnoreCase(name)) {
return true; // depends on control dependency: [if], data = [none]
}
}
if (name.equalsIgnoreCase("content-type")) {
return _contentTypeOut != null; // depends on control dependency: [if], data = [none]
}
if (name.equalsIgnoreCase("content-length")) {
return _contentLengthOut >= 0; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public String getParameterIgnoreCase(String name) {
for (Map.Entry<String, String[]> entry : customParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase(name)) {
return StringUtils.join(entry.getValue(), ",");
}
}
return null;
} } | public class class_name {
public String getParameterIgnoreCase(String name) {
for (Map.Entry<String, String[]> entry : customParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase(name)) {
return StringUtils.join(entry.getValue(), ","); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
private void ensureBufferAvailable(TableBlock block) throws IOException {
if (!block.hasBuffer()) {
synchronized (this) {
if (!block.hasBuffer()) {
ByteBuffer buffer = getBuffer();
block.setBuffer(buffer);
}
}
}
} } | public class class_name {
private void ensureBufferAvailable(TableBlock block) throws IOException {
if (!block.hasBuffer()) {
synchronized (this) {
if (!block.hasBuffer()) {
ByteBuffer buffer = getBuffer();
block.setBuffer(buffer); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
final Table SYSTEM_BESTROWIDENTIFIER() {
Table t = sysTables[SYSTEM_BESTROWIDENTIFIER];
if (t == null) {
t = createBlankTable(sysTableHsqlNames[SYSTEM_BESTROWIDENTIFIER]);
addColumn(t, "SCOPE", Type.SQL_SMALLINT); // not null
addColumn(t, "COLUMN_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "DATA_TYPE", Type.SQL_SMALLINT); // not null
addColumn(t, "TYPE_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "COLUMN_SIZE", Type.SQL_INTEGER);
addColumn(t, "BUFFER_LENGTH", Type.SQL_INTEGER);
addColumn(t, "DECIMAL_DIGITS", Type.SQL_SMALLINT);
addColumn(t, "PSEUDO_COLUMN", Type.SQL_SMALLINT); // not null
addColumn(t, "TABLE_CAT", SQL_IDENTIFIER);
addColumn(t, "TABLE_SCHEM", SQL_IDENTIFIER);
addColumn(t, "TABLE_NAME", SQL_IDENTIFIER); // not null
addColumn(t, "NULLABLE", Type.SQL_SMALLINT); // not null
addColumn(t, "IN_KEY", Type.SQL_BOOLEAN); // not null
// order: SCOPE
// for unique: TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME
// false PK, as TABLE_CAT and/or TABLE_SCHEM may be null
HsqlName name = HsqlNameManager.newInfoSchemaObjectName(
sysTableHsqlNames[SYSTEM_BESTROWIDENTIFIER].name, false,
SchemaObject.INDEX);
t.createPrimaryKey(name, new int[] {
0, 8, 9, 10, 1
}, false);
return t;
}
PersistentStore store = database.persistentStoreCollection.getStore(t);
// calculated column values
Integer scope; // { temp, transaction, session }
Integer pseudo;
//-------------------------------------------
// required for restriction of results via
// DatabaseMetaData filter parameters, but
// not actually required to be included in
// DatabaseMetaData.getBestRowIdentifier()
// result set
//-------------------------------------------
String tableCatalog; // table calalog
String tableSchema; // table schema
String tableName; // table name
Boolean inKey; // column participates in PK or AK?
//-------------------------------------------
/**
* @todo - Maybe include: - backing index (constraint) name?
* - column sequence in index (constraint)?
*/
//-------------------------------------------
// Intermediate holders
Iterator tables;
Table table;
DITableInfo ti;
int[] cols;
Object[] row;
HsqlProperties p;
// Column number mappings
final int iscope = 0;
final int icolumn_name = 1;
final int idata_type = 2;
final int itype_name = 3;
final int icolumn_size = 4;
final int ibuffer_length = 5;
final int idecimal_digits = 6;
final int ipseudo_column = 7;
final int itable_cat = 8;
final int itable_schem = 9;
final int itable_name = 10;
final int inullable = 11;
final int iinKey = 12;
// Initialization
ti = new DITableInfo();
tables =
database.schemaManager.databaseObjectIterator(SchemaObject.TABLE);
// Do it.
while (tables.hasNext()) {
table = (Table) tables.next();
/** @todo - requires access to the actual columns */
if (table.isView() || !isAccessibleTable(table)) {
continue;
}
cols = table.getBestRowIdentifiers();
if (cols == null) {
continue;
}
ti.setTable(table);
inKey = ValuePool.getBoolean(table.isBestRowIdentifiersStrict());
tableCatalog = table.getCatalogName().name;
tableSchema = table.getSchemaName().name;
tableName = table.getName().name;
Type[] types = table.getColumnTypes();
scope = ti.getBRIScope();
pseudo = ti.getBRIPseudo();
for (int i = 0; i < cols.length; i++) {
ColumnSchema column = table.getColumn(i);
row = t.getEmptyRowData();
row[iscope] = scope;
row[icolumn_name] = column.getName().name;
row[idata_type] = ValuePool.getInt(types[i].getJDBCTypeCode());
row[itype_name] = types[i].getNameString();
row[icolumn_size] = types[i].getJDBCPrecision();
row[ibuffer_length] = null;
row[idecimal_digits] = types[i].getJDBCScale();
row[ipseudo_column] = pseudo;
row[itable_cat] = tableCatalog;
row[itable_schem] = tableSchema;
row[itable_name] = tableName;
row[inullable] = column.getNullability();
row[iinKey] = inKey;
t.insertSys(store, row);
}
}
return t;
} } | public class class_name {
final Table SYSTEM_BESTROWIDENTIFIER() {
Table t = sysTables[SYSTEM_BESTROWIDENTIFIER];
if (t == null) {
t = createBlankTable(sysTableHsqlNames[SYSTEM_BESTROWIDENTIFIER]); // depends on control dependency: [if], data = [none]
addColumn(t, "SCOPE", Type.SQL_SMALLINT); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "COLUMN_NAME", SQL_IDENTIFIER); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "DATA_TYPE", Type.SQL_SMALLINT); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "TYPE_NAME", SQL_IDENTIFIER); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "COLUMN_SIZE", Type.SQL_INTEGER); // depends on control dependency: [if], data = [(t]
addColumn(t, "BUFFER_LENGTH", Type.SQL_INTEGER); // depends on control dependency: [if], data = [(t]
addColumn(t, "DECIMAL_DIGITS", Type.SQL_SMALLINT); // depends on control dependency: [if], data = [(t]
addColumn(t, "PSEUDO_COLUMN", Type.SQL_SMALLINT); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "TABLE_CAT", SQL_IDENTIFIER); // depends on control dependency: [if], data = [(t]
addColumn(t, "TABLE_SCHEM", SQL_IDENTIFIER); // depends on control dependency: [if], data = [(t]
addColumn(t, "TABLE_NAME", SQL_IDENTIFIER); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "NULLABLE", Type.SQL_SMALLINT); // not null // depends on control dependency: [if], data = [(t]
addColumn(t, "IN_KEY", Type.SQL_BOOLEAN); // not null // depends on control dependency: [if], data = [(t]
// order: SCOPE
// for unique: TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME
// false PK, as TABLE_CAT and/or TABLE_SCHEM may be null
HsqlName name = HsqlNameManager.newInfoSchemaObjectName(
sysTableHsqlNames[SYSTEM_BESTROWIDENTIFIER].name, false,
SchemaObject.INDEX);
t.createPrimaryKey(name, new int[] {
0, 8, 9, 10, 1
}, false); // depends on control dependency: [if], data = [none]
return t; // depends on control dependency: [if], data = [none]
}
PersistentStore store = database.persistentStoreCollection.getStore(t);
// calculated column values
Integer scope; // { temp, transaction, session }
Integer pseudo;
//-------------------------------------------
// required for restriction of results via
// DatabaseMetaData filter parameters, but
// not actually required to be included in
// DatabaseMetaData.getBestRowIdentifier()
// result set
//-------------------------------------------
String tableCatalog; // table calalog
String tableSchema; // table schema
String tableName; // table name
Boolean inKey; // column participates in PK or AK?
//-------------------------------------------
/**
* @todo - Maybe include: - backing index (constraint) name?
* - column sequence in index (constraint)?
*/
//-------------------------------------------
// Intermediate holders
Iterator tables;
Table table;
DITableInfo ti;
int[] cols;
Object[] row;
HsqlProperties p;
// Column number mappings
final int iscope = 0;
final int icolumn_name = 1;
final int idata_type = 2;
final int itype_name = 3;
final int icolumn_size = 4;
final int ibuffer_length = 5;
final int idecimal_digits = 6;
final int ipseudo_column = 7;
final int itable_cat = 8;
final int itable_schem = 9;
final int itable_name = 10;
final int inullable = 11;
final int iinKey = 12;
// Initialization
ti = new DITableInfo();
tables =
database.schemaManager.databaseObjectIterator(SchemaObject.TABLE);
// Do it.
while (tables.hasNext()) {
table = (Table) tables.next(); // depends on control dependency: [while], data = [none]
/** @todo - requires access to the actual columns */
if (table.isView() || !isAccessibleTable(table)) {
continue;
}
cols = table.getBestRowIdentifiers(); // depends on control dependency: [while], data = [none]
if (cols == null) {
continue;
}
ti.setTable(table); // depends on control dependency: [while], data = [none]
inKey = ValuePool.getBoolean(table.isBestRowIdentifiersStrict()); // depends on control dependency: [while], data = [none]
tableCatalog = table.getCatalogName().name; // depends on control dependency: [while], data = [none]
tableSchema = table.getSchemaName().name; // depends on control dependency: [while], data = [none]
tableName = table.getName().name; // depends on control dependency: [while], data = [none]
Type[] types = table.getColumnTypes();
scope = ti.getBRIScope(); // depends on control dependency: [while], data = [none]
pseudo = ti.getBRIPseudo(); // depends on control dependency: [while], data = [none]
for (int i = 0; i < cols.length; i++) {
ColumnSchema column = table.getColumn(i);
row = t.getEmptyRowData(); // depends on control dependency: [for], data = [none]
row[iscope] = scope; // depends on control dependency: [for], data = [none]
row[icolumn_name] = column.getName().name; // depends on control dependency: [for], data = [none]
row[idata_type] = ValuePool.getInt(types[i].getJDBCTypeCode()); // depends on control dependency: [for], data = [i]
row[itype_name] = types[i].getNameString(); // depends on control dependency: [for], data = [i]
row[icolumn_size] = types[i].getJDBCPrecision(); // depends on control dependency: [for], data = [i]
row[ibuffer_length] = null; // depends on control dependency: [for], data = [none]
row[idecimal_digits] = types[i].getJDBCScale(); // depends on control dependency: [for], data = [i]
row[ipseudo_column] = pseudo; // depends on control dependency: [for], data = [none]
row[itable_cat] = tableCatalog; // depends on control dependency: [for], data = [none]
row[itable_schem] = tableSchema; // depends on control dependency: [for], data = [none]
row[itable_name] = tableName; // depends on control dependency: [for], data = [none]
row[inullable] = column.getNullability(); // depends on control dependency: [for], data = [none]
row[iinKey] = inKey; // depends on control dependency: [for], data = [none]
t.insertSys(store, row); // depends on control dependency: [for], data = [none]
}
}
return t;
} } |
public class class_name {
@Deprecated
public Detector[] instantiateDetectorsInPass(BugReporter bugReporter) {
int count;
count = 0;
for (DetectorFactory factory : orderedFactoryList) {
if (factory.isDetectorClassSubtypeOf(Detector.class)) {
count++;
}
}
Detector[] detectorList = new Detector[count];
count = 0;
for (DetectorFactory factory : orderedFactoryList) {
if (factory.isDetectorClassSubtypeOf(Detector.class)) {
detectorList[count++] = factory.create(bugReporter);
}
}
return detectorList;
} } | public class class_name {
@Deprecated
public Detector[] instantiateDetectorsInPass(BugReporter bugReporter) {
int count;
count = 0;
for (DetectorFactory factory : orderedFactoryList) {
if (factory.isDetectorClassSubtypeOf(Detector.class)) {
count++; // depends on control dependency: [if], data = [none]
}
}
Detector[] detectorList = new Detector[count];
count = 0;
for (DetectorFactory factory : orderedFactoryList) {
if (factory.isDetectorClassSubtypeOf(Detector.class)) {
detectorList[count++] = factory.create(bugReporter); // depends on control dependency: [if], data = [none]
}
}
return detectorList;
} } |
public class class_name {
protected void set(double values[][])
{
this.nRows = values.length;
this.nCols = values[0].length;
this.values = values;
for (int r = 1; r < nRows; ++r) {
nCols = Math.min(nCols, values[r].length);
}
} } | public class class_name {
protected void set(double values[][])
{
this.nRows = values.length;
this.nCols = values[0].length;
this.values = values;
for (int r = 1; r < nRows; ++r) {
nCols = Math.min(nCols, values[r].length); // depends on control dependency: [for], data = [r]
}
} } |
public class class_name {
private RhinoScriptBuilder initScriptBuilder() {
try {
RhinoScriptBuilder builder = null;
if (scope == null) {
builder = RhinoScriptBuilder.newChain().evaluateChain(getCoffeeScriptAsStream(), DEFAULT_COFFE_SCRIPT);
scope = builder.getScope();
} else {
builder = RhinoScriptBuilder.newChain(scope);
}
return builder;
} catch (final IOException ex) {
throw new IllegalStateException("Failed reading init script", ex);
}
} } | public class class_name {
private RhinoScriptBuilder initScriptBuilder() {
try {
RhinoScriptBuilder builder = null;
if (scope == null) {
builder = RhinoScriptBuilder.newChain().evaluateChain(getCoffeeScriptAsStream(), DEFAULT_COFFE_SCRIPT);
// depends on control dependency: [if], data = [none]
scope = builder.getScope();
// depends on control dependency: [if], data = [none]
} else {
builder = RhinoScriptBuilder.newChain(scope);
// depends on control dependency: [if], data = [(scope]
}
return builder;
// depends on control dependency: [try], data = [none]
} catch (final IOException ex) {
throw new IllegalStateException("Failed reading init script", ex);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static IdentityTemplateLibrary loadFromResource(String resource) {
InputStream in = IdentityTemplateLibrary.class.getResourceAsStream(resource);
try {
return load(in);
} catch (IOException e) {
throw new IllegalArgumentException("Could not load template library from resource " + resource, e);
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
// ignored
}
}
} } | public class class_name {
static IdentityTemplateLibrary loadFromResource(String resource) {
InputStream in = IdentityTemplateLibrary.class.getResourceAsStream(resource);
try {
return load(in); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new IllegalArgumentException("Could not load template library from resource " + resource, e);
} finally { // depends on control dependency: [catch], data = [none]
try {
if (in != null) in.close();
} catch (IOException e) {
// ignored
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("squid:S2259") // Null pointers should not be dereferenced
void setCellValue(Cell cell, Object value) {
if (value instanceof Boolean) {
cell.setCellValue(toBoolean(value));
} else if (value instanceof LocalDate) {
Instant instant = toLocalDate(value).atStartOfDay(timeZone.toZoneId()).toInstant();
cell.setCellValue(simpleDateFormat.format(Date.from(instant)));
} else if (value instanceof Instant) {
cell.setCellValue(simpleDateTimeFormat.format(Date.from((Instant) value)));
} else if (value instanceof Double) {
cell.setCellValue(toDouble(value));
} else if (value instanceof Integer) {
cell.setCellValue(toInt(value));
} else if (value instanceof Long) {
cell.setCellValue(toLong(value));
} else if (value instanceof String) {
cell.setCellValue(value.toString());
} else {
throw new UnsupportedValueException(value);
}
} } | public class class_name {
@SuppressWarnings("squid:S2259") // Null pointers should not be dereferenced
void setCellValue(Cell cell, Object value) {
if (value instanceof Boolean) {
cell.setCellValue(toBoolean(value)); // depends on control dependency: [if], data = [none]
} else if (value instanceof LocalDate) {
Instant instant = toLocalDate(value).atStartOfDay(timeZone.toZoneId()).toInstant();
cell.setCellValue(simpleDateFormat.format(Date.from(instant))); // depends on control dependency: [if], data = [none]
} else if (value instanceof Instant) {
cell.setCellValue(simpleDateTimeFormat.format(Date.from((Instant) value))); // depends on control dependency: [if], data = [none]
} else if (value instanceof Double) {
cell.setCellValue(toDouble(value)); // depends on control dependency: [if], data = [none]
} else if (value instanceof Integer) {
cell.setCellValue(toInt(value)); // depends on control dependency: [if], data = [none]
} else if (value instanceof Long) {
cell.setCellValue(toLong(value)); // depends on control dependency: [if], data = [none]
} else if (value instanceof String) {
cell.setCellValue(value.toString()); // depends on control dependency: [if], data = [none]
} else {
throw new UnsupportedValueException(value);
}
} } |
public class class_name {
@SuppressWarnings("static-method")
protected boolean generatePythonClassDeclaration(String typeName, boolean isAbstract,
List<? extends JvmTypeReference> superTypes, String comment, boolean ignoreObjectType, PyAppendable it,
IExtraLanguageGeneratorContext context) {
if (!Strings.isEmpty(typeName)) {
it.append("class ").append(typeName).append("("); //$NON-NLS-1$ //$NON-NLS-2$
boolean isOtherSuperType = false;
boolean first = true;
for (final JvmTypeReference reference : superTypes) {
if (!ignoreObjectType || !Strings.equal(reference.getQualifiedName(), Object.class.getCanonicalName())) {
isOtherSuperType = true;
if (first) {
first = false;
} else {
it.append(","); //$NON-NLS-1$
}
it.append(reference.getType());
}
}
if (isOtherSuperType) {
it.append(","); //$NON-NLS-1$
}
// Add "object to avoid a bug within the Python interpreter.
it.append("object):"); //$NON-NLS-1$
it.increaseIndentation().newLine();
generateDocString(comment, it);
return true;
}
return false;
} } | public class class_name {
@SuppressWarnings("static-method")
protected boolean generatePythonClassDeclaration(String typeName, boolean isAbstract,
List<? extends JvmTypeReference> superTypes, String comment, boolean ignoreObjectType, PyAppendable it,
IExtraLanguageGeneratorContext context) {
if (!Strings.isEmpty(typeName)) {
it.append("class ").append(typeName).append("("); //$NON-NLS-1$ //$NON-NLS-2$ // depends on control dependency: [if], data = [none]
boolean isOtherSuperType = false;
boolean first = true;
for (final JvmTypeReference reference : superTypes) {
if (!ignoreObjectType || !Strings.equal(reference.getQualifiedName(), Object.class.getCanonicalName())) {
isOtherSuperType = true; // depends on control dependency: [if], data = [none]
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
it.append(","); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
it.append(reference.getType()); // depends on control dependency: [if], data = [none]
}
}
if (isOtherSuperType) {
it.append(","); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
// Add "object to avoid a bug within the Python interpreter.
it.append("object):"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
it.increaseIndentation().newLine(); // depends on control dependency: [if], data = [none]
generateDocString(comment, it); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public int exactMatchSearch(byte[] key)
{
int unit = _array[0];
int nodePos = 0;
for (byte b : key)
{
// nodePos ^= unit.offset() ^ b
nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)) ^ (b & 0xFF);
unit = _array[nodePos];
// if (unit.label() != b)
if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff))
{
return -1;
}
}
// if (!unit.has_leaf()) {
if (((unit >>> 8) & 1) != 1)
{
return -1;
}
// unit = _array[nodePos ^ unit.offset()];
unit = _array[nodePos ^ ((unit >>> 10) << ((unit & (1 << 9)) >>> 6))];
// return unit.value();
return unit & ((1 << 31) - 1);
} } | public class class_name {
public int exactMatchSearch(byte[] key)
{
int unit = _array[0];
int nodePos = 0;
for (byte b : key)
{
// nodePos ^= unit.offset() ^ b
nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)) ^ (b & 0xFF); // depends on control dependency: [for], data = [b]
unit = _array[nodePos]; // depends on control dependency: [for], data = [none]
// if (unit.label() != b)
if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff))
{
return -1; // depends on control dependency: [if], data = [none]
}
}
// if (!unit.has_leaf()) {
if (((unit >>> 8) & 1) != 1)
{
return -1; // depends on control dependency: [if], data = [none]
}
// unit = _array[nodePos ^ unit.offset()];
unit = _array[nodePos ^ ((unit >>> 10) << ((unit & (1 << 9)) >>> 6))];
// return unit.value();
return unit & ((1 << 31) - 1);
} } |
public class class_name {
public void showCorner(boolean leftTop, boolean rightTop, boolean leftBottom, boolean rightBottom) {
if (SDK_LOLLIPOP) {
((OptRoundRectDrawable) getBackground()).showCorner(leftTop, rightTop, leftBottom, rightBottom);
} else {
((OptRoundRectDrawableWithShadow) getBackground()).showCorner(leftTop, rightTop, leftBottom, rightBottom);
}
} } | public class class_name {
public void showCorner(boolean leftTop, boolean rightTop, boolean leftBottom, boolean rightBottom) {
if (SDK_LOLLIPOP) {
((OptRoundRectDrawable) getBackground()).showCorner(leftTop, rightTop, leftBottom, rightBottom); // depends on control dependency: [if], data = [none]
} else {
((OptRoundRectDrawableWithShadow) getBackground()).showCorner(leftTop, rightTop, leftBottom, rightBottom); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean toPostInit()
{
synchronized (this) {
if (_state == STOPPED) {
_state = INIT;
_lastChangeTime = CurrentTime.currentTime();
notifyListeners(STOPPED, INIT);
return true;
}
else {
return _state.isInit();
}
}
} } | public class class_name {
public boolean toPostInit()
{
synchronized (this) {
if (_state == STOPPED) {
_state = INIT; // depends on control dependency: [if], data = [none]
_lastChangeTime = CurrentTime.currentTime(); // depends on control dependency: [if], data = [none]
notifyListeners(STOPPED, INIT); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
else {
return _state.isInit(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void marshall(UpdateInstanceProfileRequest updateInstanceProfileRequest, ProtocolMarshaller protocolMarshaller) {
if (updateInstanceProfileRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateInstanceProfileRequest.getArn(), ARN_BINDING);
protocolMarshaller.marshall(updateInstanceProfileRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(updateInstanceProfileRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(updateInstanceProfileRequest.getPackageCleanup(), PACKAGECLEANUP_BINDING);
protocolMarshaller.marshall(updateInstanceProfileRequest.getExcludeAppPackagesFromCleanup(), EXCLUDEAPPPACKAGESFROMCLEANUP_BINDING);
protocolMarshaller.marshall(updateInstanceProfileRequest.getRebootAfterUse(), REBOOTAFTERUSE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateInstanceProfileRequest updateInstanceProfileRequest, ProtocolMarshaller protocolMarshaller) {
if (updateInstanceProfileRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateInstanceProfileRequest.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateInstanceProfileRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateInstanceProfileRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateInstanceProfileRequest.getPackageCleanup(), PACKAGECLEANUP_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateInstanceProfileRequest.getExcludeAppPackagesFromCleanup(), EXCLUDEAPPPACKAGESFROMCLEANUP_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateInstanceProfileRequest.getRebootAfterUse(), REBOOTAFTERUSE_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 int getClassIndex(Instances instances, MiningSchema miningSchema) {
String className = null;
for (MiningField miningField : miningSchema.getMiningFields()) {
if (miningField.getUsageType() == FieldUsageType.PREDICTED) {
className = miningField.getName().getValue();
break;
}
}
return instances.attribute(className).index();
} } | public class class_name {
public static int getClassIndex(Instances instances, MiningSchema miningSchema) {
String className = null;
for (MiningField miningField : miningSchema.getMiningFields()) {
if (miningField.getUsageType() == FieldUsageType.PREDICTED) {
className = miningField.getName().getValue(); // depends on control dependency: [if], data = [none]
break;
}
}
return instances.attribute(className).index();
} } |
public class class_name {
@Override
public long getNextIncludedTime (final long timeInMillis)
{
long nextIncludedTime = timeInMillis + 1; // plus on millisecond
while (!isTimeIncluded (nextIncludedTime))
{
// If the time is in a range excluded by this calendar, we can
// move to the end of the excluded time range and continue testing
// from there. Otherwise, if nextIncludedTime is excluded by the
// baseCalendar, ask it the next time it includes and begin testing
// from there. Failing this, add one millisecond and continue
// testing.
if (m_aCronExpression.isSatisfiedBy (new Date (nextIncludedTime)))
{
nextIncludedTime = m_aCronExpression.getNextInvalidTimeAfter (new Date (nextIncludedTime)).getTime ();
}
else
if ((getBaseCalendar () != null) && (!getBaseCalendar ().isTimeIncluded (nextIncludedTime)))
{
nextIncludedTime = getBaseCalendar ().getNextIncludedTime (nextIncludedTime);
}
else
{
nextIncludedTime++;
}
}
return nextIncludedTime;
} } | public class class_name {
@Override
public long getNextIncludedTime (final long timeInMillis)
{
long nextIncludedTime = timeInMillis + 1; // plus on millisecond
while (!isTimeIncluded (nextIncludedTime))
{
// If the time is in a range excluded by this calendar, we can
// move to the end of the excluded time range and continue testing
// from there. Otherwise, if nextIncludedTime is excluded by the
// baseCalendar, ask it the next time it includes and begin testing
// from there. Failing this, add one millisecond and continue
// testing.
if (m_aCronExpression.isSatisfiedBy (new Date (nextIncludedTime)))
{
nextIncludedTime = m_aCronExpression.getNextInvalidTimeAfter (new Date (nextIncludedTime)).getTime (); // depends on control dependency: [if], data = [none]
}
else
if ((getBaseCalendar () != null) && (!getBaseCalendar ().isTimeIncluded (nextIncludedTime)))
{
nextIncludedTime = getBaseCalendar ().getNextIncludedTime (nextIncludedTime); // depends on control dependency: [if], data = [none]
}
else
{
nextIncludedTime++; // depends on control dependency: [if], data = [none]
}
}
return nextIncludedTime;
} } |
public class class_name {
private boolean allTypesExist(Collection<? extends Element> elements) {
for (Element element : elements) {
if (element.asType().getKind() == TypeKind.ERROR) {
return false;
}
}
return true;
} } | public class class_name {
private boolean allTypesExist(Collection<? extends Element> elements) {
for (Element element : elements) {
if (element.asType().getKind() == TypeKind.ERROR) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public void marshall(CreateProductRequest createProductRequest, ProtocolMarshaller protocolMarshaller) {
if (createProductRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createProductRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING);
protocolMarshaller.marshall(createProductRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(createProductRequest.getOwner(), OWNER_BINDING);
protocolMarshaller.marshall(createProductRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(createProductRequest.getDistributor(), DISTRIBUTOR_BINDING);
protocolMarshaller.marshall(createProductRequest.getSupportDescription(), SUPPORTDESCRIPTION_BINDING);
protocolMarshaller.marshall(createProductRequest.getSupportEmail(), SUPPORTEMAIL_BINDING);
protocolMarshaller.marshall(createProductRequest.getSupportUrl(), SUPPORTURL_BINDING);
protocolMarshaller.marshall(createProductRequest.getProductType(), PRODUCTTYPE_BINDING);
protocolMarshaller.marshall(createProductRequest.getTags(), TAGS_BINDING);
protocolMarshaller.marshall(createProductRequest.getProvisioningArtifactParameters(), PROVISIONINGARTIFACTPARAMETERS_BINDING);
protocolMarshaller.marshall(createProductRequest.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(CreateProductRequest createProductRequest, ProtocolMarshaller protocolMarshaller) {
if (createProductRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createProductRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getOwner(), OWNER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getDistributor(), DISTRIBUTOR_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getSupportDescription(), SUPPORTDESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getSupportEmail(), SUPPORTEMAIL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getSupportUrl(), SUPPORTURL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getProductType(), PRODUCTTYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.getProvisioningArtifactParameters(), PROVISIONINGARTIFACTPARAMETERS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createProductRequest.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 {
@Override
public EEnum getIfcElectricTimeControlTypeEnum() {
if (ifcElectricTimeControlTypeEnumEEnum == null) {
ifcElectricTimeControlTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(979);
}
return ifcElectricTimeControlTypeEnumEEnum;
} } | public class class_name {
@Override
public EEnum getIfcElectricTimeControlTypeEnum() {
if (ifcElectricTimeControlTypeEnumEEnum == null) {
ifcElectricTimeControlTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(979);
// depends on control dependency: [if], data = [none]
}
return ifcElectricTimeControlTypeEnumEEnum;
} } |
public class class_name {
private void optimizeStart() {
if (configuration.isPayloadCache()) {
if (configuration.getOptimizerStoreClass() == null) {
store = new CacheOptimizerStore();
store.start(configuration);
return;
}
try {
store = (OptimizerStore) Class.forName(configuration.getOptimizerStoreClass()).newInstance();
store.start(configuration);
} catch (ClassNotFoundException cnfe) {
LOGGER.warn("Unable to find the class {}. The payload will be sent without optimizations.", configuration.getOptimizerStoreClass());
} catch (InstantiationException ex) {
LOGGER.warn("Unable to instantiate the class {}. Concrete class required.", configuration.getOptimizerStoreClass());
} catch (IllegalAccessException ex) {
LOGGER.warn("Unable to instantiate the class {}. Empty constructor required.", configuration.getOptimizerStoreClass());
}
}
} } | public class class_name {
private void optimizeStart() {
if (configuration.isPayloadCache()) {
if (configuration.getOptimizerStoreClass() == null) {
store = new CacheOptimizerStore(); // depends on control dependency: [if], data = [none]
store.start(configuration); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
try {
store = (OptimizerStore) Class.forName(configuration.getOptimizerStoreClass()).newInstance(); // depends on control dependency: [try], data = [none]
store.start(configuration); // depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException cnfe) {
LOGGER.warn("Unable to find the class {}. The payload will be sent without optimizations.", configuration.getOptimizerStoreClass());
} catch (InstantiationException ex) { // depends on control dependency: [catch], data = [none]
LOGGER.warn("Unable to instantiate the class {}. Concrete class required.", configuration.getOptimizerStoreClass());
} catch (IllegalAccessException ex) { // depends on control dependency: [catch], data = [none]
LOGGER.warn("Unable to instantiate the class {}. Empty constructor required.", configuration.getOptimizerStoreClass());
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
protected void createContainerXML(final BuildData buildData, final Level container, final Document doc, final Element parentNode,
final String parentFileLocation, final Boolean flattenStructure) throws BuildProcessingException {
final List<org.jboss.pressgang.ccms.contentspec.Node> levelData = container.getChildNodes();
// Get the name of the element based on the type
final String elementName = container.getLevelType() == LevelType.PROCESS ? "chapter" : container.getLevelType().getTitle()
.toLowerCase(Locale.ENGLISH);
final Element intro = doc.createElement(elementName + "intro");
// Storage container to hold the levels so they can be added in proper order with the intro
final LinkedList<Node> childNodes = new LinkedList<Node>();
// Add the section and topics for this level to the chapter.xml
for (final org.jboss.pressgang.ccms.contentspec.Node node : levelData) {
// Check if the app should be shutdown
if (isShuttingDown.get()) {
return;
}
if (node instanceof Level && node.getParent() != null && (((Level) node).getParent().getLevelType() == LevelType.BASE || (
(Level) node).getParent().getLevelType() == LevelType.PART) && ((Level) node).getLevelType() != LevelType
.INITIAL_CONTENT) {
final Level childContainer = (Level) node;
// Create a new file for the Chapter/Appendix
final Element xiInclude = createSubRootContainerXML(buildData, doc, childContainer, parentFileLocation, flattenStructure);
if (xiInclude != null) {
childNodes.add(xiInclude);
}
} else if (node instanceof Level && ((Level) node).getLevelType() == LevelType.INITIAL_CONTENT) {
if (container.getLevelType() == LevelType.PART) {
addLevelsInitialContent(buildData, (InitialContent) node, doc, intro, false);
} else {
addLevelsInitialContent(buildData, (InitialContent) node, doc, parentNode, false);
}
} else if (node instanceof Level) {
final Level childLevel = (Level) node;
// Create the section and its title
final Element sectionNode = doc.createElement("section");
setUpRootElement(buildData, childLevel, doc, sectionNode);
// Ignore sections that have no spec topics
if (!childLevel.hasSpecTopics() && !childLevel.hasCommonContents()) {
if (buildData.getBuildOptions().isAllowEmptySections()) {
Element warning = doc.createElement("warning");
warning.setTextContent("No Content");
sectionNode.appendChild(warning);
} else {
continue;
}
} else {
// Add this sections child sections/topics
createContainerXML(buildData, childLevel, doc, sectionNode, parentFileLocation, flattenStructure);
}
childNodes.add(sectionNode);
} else if (node instanceof CommonContent) {
final CommonContent commonContent = (CommonContent) node;
final Node xiInclude = XMLUtilities.createXIInclude(doc, "Common_Content/" + commonContent.getFixedTitle());
if (commonContent.getParent() != null && commonContent.getParent().getLevelType() == LevelType.PART) {
intro.appendChild(xiInclude);
} else {
childNodes.add(xiInclude);
}
} else if (node instanceof SpecTopic) {
final SpecTopic specTopic = (SpecTopic) node;
final Node topicNode = createTopicDOMNode(specTopic, doc, flattenStructure, parentFileLocation);
// Add the node to the chapter
if (topicNode != null) {
if (specTopic.getParent() != null && ((Level) specTopic.getParent()).getLevelType() == LevelType.PART) {
intro.appendChild(topicNode);
} else {
childNodes.add(topicNode);
}
}
}
}
// Add the child nodes and intro to the parent
if (intro.hasChildNodes()) {
parentNode.appendChild(intro);
}
for (final Node node : childNodes) {
parentNode.appendChild(node);
}
} } | public class class_name {
protected void createContainerXML(final BuildData buildData, final Level container, final Document doc, final Element parentNode,
final String parentFileLocation, final Boolean flattenStructure) throws BuildProcessingException {
final List<org.jboss.pressgang.ccms.contentspec.Node> levelData = container.getChildNodes();
// Get the name of the element based on the type
final String elementName = container.getLevelType() == LevelType.PROCESS ? "chapter" : container.getLevelType().getTitle()
.toLowerCase(Locale.ENGLISH);
final Element intro = doc.createElement(elementName + "intro");
// Storage container to hold the levels so they can be added in proper order with the intro
final LinkedList<Node> childNodes = new LinkedList<Node>();
// Add the section and topics for this level to the chapter.xml
for (final org.jboss.pressgang.ccms.contentspec.Node node : levelData) {
// Check if the app should be shutdown
if (isShuttingDown.get()) {
return; // depends on control dependency: [if], data = [none]
}
if (node instanceof Level && node.getParent() != null && (((Level) node).getParent().getLevelType() == LevelType.BASE || (
(Level) node).getParent().getLevelType() == LevelType.PART) && ((Level) node).getLevelType() != LevelType
.INITIAL_CONTENT) {
final Level childContainer = (Level) node;
// Create a new file for the Chapter/Appendix
final Element xiInclude = createSubRootContainerXML(buildData, doc, childContainer, parentFileLocation, flattenStructure);
if (xiInclude != null) {
childNodes.add(xiInclude); // depends on control dependency: [if], data = [(xiInclude]
}
} else if (node instanceof Level && ((Level) node).getLevelType() == LevelType.INITIAL_CONTENT) {
if (container.getLevelType() == LevelType.PART) {
addLevelsInitialContent(buildData, (InitialContent) node, doc, intro, false); // depends on control dependency: [if], data = [none]
} else {
addLevelsInitialContent(buildData, (InitialContent) node, doc, parentNode, false); // depends on control dependency: [if], data = [none]
}
} else if (node instanceof Level) {
final Level childLevel = (Level) node;
// Create the section and its title
final Element sectionNode = doc.createElement("section");
setUpRootElement(buildData, childLevel, doc, sectionNode); // depends on control dependency: [if], data = [none]
// Ignore sections that have no spec topics
if (!childLevel.hasSpecTopics() && !childLevel.hasCommonContents()) {
if (buildData.getBuildOptions().isAllowEmptySections()) {
Element warning = doc.createElement("warning");
warning.setTextContent("No Content"); // depends on control dependency: [if], data = [none]
sectionNode.appendChild(warning); // depends on control dependency: [if], data = [none]
} else {
continue;
}
} else {
// Add this sections child sections/topics
createContainerXML(buildData, childLevel, doc, sectionNode, parentFileLocation, flattenStructure); // depends on control dependency: [if], data = [none]
}
childNodes.add(sectionNode); // depends on control dependency: [if], data = [none]
} else if (node instanceof CommonContent) {
final CommonContent commonContent = (CommonContent) node;
final Node xiInclude = XMLUtilities.createXIInclude(doc, "Common_Content/" + commonContent.getFixedTitle());
if (commonContent.getParent() != null && commonContent.getParent().getLevelType() == LevelType.PART) {
intro.appendChild(xiInclude); // depends on control dependency: [if], data = [none]
} else {
childNodes.add(xiInclude); // depends on control dependency: [if], data = [none]
}
} else if (node instanceof SpecTopic) {
final SpecTopic specTopic = (SpecTopic) node;
final Node topicNode = createTopicDOMNode(specTopic, doc, flattenStructure, parentFileLocation);
// Add the node to the chapter
if (topicNode != null) {
if (specTopic.getParent() != null && ((Level) specTopic.getParent()).getLevelType() == LevelType.PART) {
intro.appendChild(topicNode); // depends on control dependency: [if], data = [none]
} else {
childNodes.add(topicNode); // depends on control dependency: [if], data = [none]
}
}
}
}
// Add the child nodes and intro to the parent
if (intro.hasChildNodes()) {
parentNode.appendChild(intro);
}
for (final Node node : childNodes) {
parentNode.appendChild(node);
}
} } |
public class class_name {
protected Escalation findEscalationForEscalationEventDefinition(Element escalationEventDefinition) {
String escalationRef = escalationEventDefinition.attribute("escalationRef");
if (escalationRef == null) {
addError("escalationEventDefinition does not have required attribute 'escalationRef'", escalationEventDefinition);
} else if (!escalations.containsKey(escalationRef)) {
addError("could not find escalation with id '" + escalationRef + "'", escalationEventDefinition);
} else {
return escalations.get(escalationRef);
}
return null;
} } | public class class_name {
protected Escalation findEscalationForEscalationEventDefinition(Element escalationEventDefinition) {
String escalationRef = escalationEventDefinition.attribute("escalationRef");
if (escalationRef == null) {
addError("escalationEventDefinition does not have required attribute 'escalationRef'", escalationEventDefinition); // depends on control dependency: [if], data = [none]
} else if (!escalations.containsKey(escalationRef)) {
addError("could not find escalation with id '" + escalationRef + "'", escalationEventDefinition); // depends on control dependency: [if], data = [none]
} else {
return escalations.get(escalationRef); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public void render(final String word, BufferedImage image) {
Graphics2D g = image.createGraphics();
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
g.setRenderingHints(hints);
FontRenderContext frc = g.getFontRenderContext();
int xBaseline = (int) Math.round(image.getWidth() * XOFFSET);
int yBaseline = image.getHeight() - (int) Math.round(image.getHeight() * YOFFSET);
char[] chars = new char[1];
for (char c : word.toCharArray()) {
chars[0] = c;
g.setColor(_colors.get(RAND.nextInt(_colors.size())));
int choiceFont = RAND.nextInt(_fonts.size());
Font font = _fonts.get(choiceFont);
g.setFont(font);
GlyphVector gv = font.createGlyphVector(frc, chars);
g.drawChars(chars, 0, chars.length, xBaseline, yBaseline);
int width = (int) gv.getVisualBounds().getWidth();
xBaseline = xBaseline + width;
}
} } | public class class_name {
@Override
public void render(final String word, BufferedImage image) {
Graphics2D g = image.createGraphics();
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
g.setRenderingHints(hints);
FontRenderContext frc = g.getFontRenderContext();
int xBaseline = (int) Math.round(image.getWidth() * XOFFSET);
int yBaseline = image.getHeight() - (int) Math.round(image.getHeight() * YOFFSET);
char[] chars = new char[1];
for (char c : word.toCharArray()) {
chars[0] = c; // depends on control dependency: [for], data = [c]
g.setColor(_colors.get(RAND.nextInt(_colors.size()))); // depends on control dependency: [for], data = [c]
int choiceFont = RAND.nextInt(_fonts.size());
Font font = _fonts.get(choiceFont);
g.setFont(font); // depends on control dependency: [for], data = [none]
GlyphVector gv = font.createGlyphVector(frc, chars);
g.drawChars(chars, 0, chars.length, xBaseline, yBaseline); // depends on control dependency: [for], data = [c]
int width = (int) gv.getVisualBounds().getWidth();
xBaseline = xBaseline + width; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private String getIndentation() {
final StringBuilder buf = new StringBuilder();
for (int i=0; i<indentLevel; i++) {
buf.append("\t");
}
return buf.toString();
} } | public class class_name {
private String getIndentation() {
final StringBuilder buf = new StringBuilder();
for (int i=0; i<indentLevel; i++) {
buf.append("\t"); // depends on control dependency: [for], data = [none]
}
return buf.toString();
} } |
public class class_name {
private <T extends Snippet> Stream<T> argsToSnippets(Supplier<Stream<T>> snippetSupplier,
List<String> args) {
Stream<T> result = null;
for (String arg : args) {
// Find the best match
Stream<T> st = layeredSnippetSearch(snippetSupplier, arg);
if (st == null) {
Stream<Snippet> est = layeredSnippetSearch(state::snippets, arg);
if (est == null) {
errormsg("jshell.err.no.such.snippets", arg);
} else {
errormsg("jshell.err.the.snippet.cannot.be.used.with.this.command",
arg, est.findFirst().get().source());
}
return null;
}
if (result == null) {
result = st;
} else {
result = Stream.concat(result, st);
}
}
return result;
} } | public class class_name {
private <T extends Snippet> Stream<T> argsToSnippets(Supplier<Stream<T>> snippetSupplier,
List<String> args) {
Stream<T> result = null;
for (String arg : args) {
// Find the best match
Stream<T> st = layeredSnippetSearch(snippetSupplier, arg);
if (st == null) {
Stream<Snippet> est = layeredSnippetSearch(state::snippets, arg);
if (est == null) {
errormsg("jshell.err.no.such.snippets", arg); // depends on control dependency: [if], data = [none]
} else {
errormsg("jshell.err.the.snippet.cannot.be.used.with.this.command",
arg, est.findFirst().get().source()); // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
}
if (result == null) {
result = st; // depends on control dependency: [if], data = [none]
} else {
result = Stream.concat(result, st); // depends on control dependency: [if], data = [(result]
}
}
return result;
} } |
public class class_name {
public BatchDeleteConnectionRequest withConnectionNameList(String... connectionNameList) {
if (this.connectionNameList == null) {
setConnectionNameList(new java.util.ArrayList<String>(connectionNameList.length));
}
for (String ele : connectionNameList) {
this.connectionNameList.add(ele);
}
return this;
} } | public class class_name {
public BatchDeleteConnectionRequest withConnectionNameList(String... connectionNameList) {
if (this.connectionNameList == null) {
setConnectionNameList(new java.util.ArrayList<String>(connectionNameList.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : connectionNameList) {
this.connectionNameList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
static LinkedList<Change> changesFromDelta(String text1, String delta)
throws IllegalArgumentException {
LinkedList<Change> diffs = new LinkedList<>();
int pointer = 0; // Cursor in text1
String[] tokens = delta.split("\t");
for (String token : tokens) {
if (token.length() == 0) {
// Blank tokens are ok (from a trailing \t).
continue;
}
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
String param = token.substring(1);
switch (token.charAt(0)) {
case '+':
// decode would change all "+" to " "
param = param.replace("+", "%2B");
try {
param = URLDecoder.decode(param, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Not likely on modern system.
throw new Error("This system does not support UTF-8.", e);
} catch (IllegalArgumentException e) {
// Malformed URI sequence.
throw new IllegalArgumentException(
"Illegal escape in diff_fromDelta: " + param, e);
}
diffs.add(new Change(Operation.INSERT, param));
break;
case '-':
// Fall through.
case '=':
int n;
try {
n = Integer.parseInt(param);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Invalid number in diff_fromDelta: " + param, e);
}
if (n < 0) {
throw new IllegalArgumentException(
"Negative number in diff_fromDelta: " + param);
}
String text;
try {
text = text1.substring(pointer, pointer += n);
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Delta length (" + pointer
+ ") larger than source text length (" + text1.length()
+ ").", e);
}
if (token.charAt(0) == '=') {
diffs.add(new Change(Operation.EQUAL, text));
} else {
diffs.add(new Change(Operation.DELETE, text));
}
break;
default:
// Anything else is an error.
throw new IllegalArgumentException(
"Invalid diff operation in diff_fromDelta: " + token.charAt(0));
}
}
if (pointer != text1.length()) {
throw new IllegalArgumentException("Delta length (" + pointer
+ ") smaller than source text length (" + text1.length() + ").");
}
return diffs;
} } | public class class_name {
static LinkedList<Change> changesFromDelta(String text1, String delta)
throws IllegalArgumentException {
LinkedList<Change> diffs = new LinkedList<>();
int pointer = 0; // Cursor in text1
String[] tokens = delta.split("\t");
for (String token : tokens) {
if (token.length() == 0) {
// Blank tokens are ok (from a trailing \t).
continue;
}
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
String param = token.substring(1);
switch (token.charAt(0)) {
case '+':
// decode would change all "+" to " "
param = param.replace("+", "%2B");
try {
param = URLDecoder.decode(param, "UTF-8"); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
// Not likely on modern system.
throw new Error("This system does not support UTF-8.", e);
} catch (IllegalArgumentException e) { // depends on control dependency: [catch], data = [none]
// Malformed URI sequence.
throw new IllegalArgumentException(
"Illegal escape in diff_fromDelta: " + param, e);
} // depends on control dependency: [catch], data = [none]
diffs.add(new Change(Operation.INSERT, param));
break;
case '-':
// Fall through.
case '=':
int n;
try {
n = Integer.parseInt(param); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Invalid number in diff_fromDelta: " + param, e);
} // depends on control dependency: [catch], data = [none]
if (n < 0) {
throw new IllegalArgumentException(
"Negative number in diff_fromDelta: " + param);
}
String text;
try {
text = text1.substring(pointer, pointer += n); // depends on control dependency: [try], data = [none]
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Delta length (" + pointer
+ ") larger than source text length (" + text1.length()
+ ").", e);
} // depends on control dependency: [catch], data = [none]
if (token.charAt(0) == '=') {
diffs.add(new Change(Operation.EQUAL, text)); // depends on control dependency: [if], data = [none]
} else {
diffs.add(new Change(Operation.DELETE, text)); // depends on control dependency: [if], data = [none]
}
break;
default:
// Anything else is an error.
throw new IllegalArgumentException(
"Invalid diff operation in diff_fromDelta: " + token.charAt(0));
}
}
if (pointer != text1.length()) {
throw new IllegalArgumentException("Delta length (" + pointer
+ ") smaller than source text length (" + text1.length() + ").");
}
return diffs;
} } |
public class class_name {
private void stop() {
if (m_bRunning) {
instance().m_logger.info("Doradus Server shutting down");
stopServices();
ServerParams.unload();
m_bRunning = false;
m_bInitialized = false;
}
} } | public class class_name {
private void stop() {
if (m_bRunning) {
instance().m_logger.info("Doradus Server shutting down");
// depends on control dependency: [if], data = [none]
stopServices();
// depends on control dependency: [if], data = [none]
ServerParams.unload();
// depends on control dependency: [if], data = [none]
m_bRunning = false;
// depends on control dependency: [if], data = [none]
m_bInitialized = false;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public String update(EntityUpdateOperation updater) throws ServiceException {
updater.setProxyData(createProxyData());
ClientResponse clientResponse = getResource(updater).header("X-HTTP-METHOD",
"MERGE").post(ClientResponse.class,
updater.getRequestContents());
PipelineHelpers.throwIfNotSuccess(clientResponse);
updater.processResponse(clientResponse);
if (clientResponse.getHeaders().containsKey("operation-id")) {
List<String> operationIds = clientResponse.getHeaders().get("operation-id");
if (operationIds.size() >= 0) {
return operationIds.get(0);
}
}
return null;
} } | public class class_name {
@Override
public String update(EntityUpdateOperation updater) throws ServiceException {
updater.setProxyData(createProxyData());
ClientResponse clientResponse = getResource(updater).header("X-HTTP-METHOD",
"MERGE").post(ClientResponse.class,
updater.getRequestContents());
PipelineHelpers.throwIfNotSuccess(clientResponse);
updater.processResponse(clientResponse);
if (clientResponse.getHeaders().containsKey("operation-id")) {
List<String> operationIds = clientResponse.getHeaders().get("operation-id");
if (operationIds.size() >= 0) {
return operationIds.get(0); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public Response submitRequest(ProtocolHeader h, Protocol request,
WatcherRegistration wr){
Packet packet = queuePacket(h, request, null, null, null, wr);
synchronized (packet) {
while (!packet.finished) {
try {
packet.wait();
} catch (InterruptedException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(ErrorCode.REQUEST_INTERUPTED);
throw new ServiceException(sde, e);
}
}
}
if(! packet.respHeader.getErr().equals(ErrorCode.OK)){
ServiceDirectoryError sde = new ServiceDirectoryError(packet.respHeader.getErr());
throw new ServiceException(sde);
}
return packet.response;
} } | public class class_name {
public Response submitRequest(ProtocolHeader h, Protocol request,
WatcherRegistration wr){
Packet packet = queuePacket(h, request, null, null, null, wr);
synchronized (packet) {
while (!packet.finished) {
try {
packet.wait(); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(ErrorCode.REQUEST_INTERUPTED);
throw new ServiceException(sde, e);
} // depends on control dependency: [catch], data = [none]
}
}
if(! packet.respHeader.getErr().equals(ErrorCode.OK)){
ServiceDirectoryError sde = new ServiceDirectoryError(packet.respHeader.getErr());
throw new ServiceException(sde);
}
return packet.response;
} } |
public class class_name {
public void setBinaryMediaTypes(java.util.Collection<String> binaryMediaTypes) {
if (binaryMediaTypes == null) {
this.binaryMediaTypes = null;
return;
}
this.binaryMediaTypes = new java.util.ArrayList<String>(binaryMediaTypes);
} } | public class class_name {
public void setBinaryMediaTypes(java.util.Collection<String> binaryMediaTypes) {
if (binaryMediaTypes == null) {
this.binaryMediaTypes = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.binaryMediaTypes = new java.util.ArrayList<String>(binaryMediaTypes);
} } |
public class class_name {
@SuppressWarnings("static-method")
public String findStringValue(JvmAnnotationReference reference) {
assert reference != null;
for (final JvmAnnotationValue value : reference.getValues()) {
if (value instanceof JvmStringAnnotationValue) {
for (final String strValue : ((JvmStringAnnotationValue) value).getValues()) {
if (strValue != null) {
return strValue;
}
}
}
}
return null;
} } | public class class_name {
@SuppressWarnings("static-method")
public String findStringValue(JvmAnnotationReference reference) {
assert reference != null;
for (final JvmAnnotationValue value : reference.getValues()) {
if (value instanceof JvmStringAnnotationValue) {
for (final String strValue : ((JvmStringAnnotationValue) value).getValues()) {
if (strValue != null) {
return strValue; // depends on control dependency: [if], data = [none]
}
}
}
}
return null;
} } |
public class class_name {
@ConditionBlock
public void within(double seconds, Closure<?> conditions) throws InterruptedException {
long timeoutMillis = toMillis(seconds);
long start = System.currentTimeMillis();
long lastAttempt = 0;
Thread.sleep(toMillis(initialDelay));
long currDelay = toMillis(delay);
int attempts = 0;
while(true) {
try {
attempts++;
lastAttempt = System.currentTimeMillis();
GroovyRuntimeUtil.invokeClosure(conditions);
return;
} catch (Throwable e) {
long elapsedTime = lastAttempt - start;
if (elapsedTime >= timeoutMillis) {
String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts);
throw new SpockTimeoutError(seconds, msg, e);
}
final long timeout = Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis());
if (timeout > 0) {
Thread.sleep(timeout);
}
currDelay *= factor;
}
}
} } | public class class_name {
@ConditionBlock
public void within(double seconds, Closure<?> conditions) throws InterruptedException {
long timeoutMillis = toMillis(seconds);
long start = System.currentTimeMillis();
long lastAttempt = 0;
Thread.sleep(toMillis(initialDelay));
long currDelay = toMillis(delay);
int attempts = 0;
while(true) {
try {
attempts++; // depends on control dependency: [try], data = [none]
lastAttempt = System.currentTimeMillis(); // depends on control dependency: [try], data = [none]
GroovyRuntimeUtil.invokeClosure(conditions); // depends on control dependency: [try], data = [none]
return; // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
long elapsedTime = lastAttempt - start;
if (elapsedTime >= timeoutMillis) {
String msg = String.format("Condition not satisfied after %1.2f seconds and %d attempts", elapsedTime / 1000d, attempts);
throw new SpockTimeoutError(seconds, msg, e);
}
final long timeout = Math.min(currDelay, start + timeoutMillis - System.currentTimeMillis());
if (timeout > 0) {
Thread.sleep(timeout); // depends on control dependency: [if], data = [(timeout]
}
currDelay *= factor;
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public ModifiableHyperBoundingBox computeMBR() {
E firstEntry = getEntry(0);
if(firstEntry == null) {
return null;
}
// Note: we deliberately get a cloned copy here, since we will modify it.
ModifiableHyperBoundingBox mbr = new ModifiableHyperBoundingBox(firstEntry);
for(int i = 1; i < numEntries; i++) {
mbr.extend(getEntry(i));
}
return mbr;
} } | public class class_name {
public ModifiableHyperBoundingBox computeMBR() {
E firstEntry = getEntry(0);
if(firstEntry == null) {
return null; // depends on control dependency: [if], data = [none]
}
// Note: we deliberately get a cloned copy here, since we will modify it.
ModifiableHyperBoundingBox mbr = new ModifiableHyperBoundingBox(firstEntry);
for(int i = 1; i < numEntries; i++) {
mbr.extend(getEntry(i)); // depends on control dependency: [for], data = [i]
}
return mbr;
} } |
public class class_name {
protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
if (traceEnabled) {
LOGGER.trace(logIdent(ctx, endpoint) + "keepAlive was answered, status "
+ keepAliveResponse.status());
}
} } | public class class_name {
protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
if (traceEnabled) {
LOGGER.trace(logIdent(ctx, endpoint) + "keepAlive was answered, status "
+ keepAliveResponse.status()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static void validateEntityId(EntityType entityType) {
// validate entity name (e.g. illegal characters, length)
String id = entityType.getId();
if (!id.equals(ATTRIBUTE_META_DATA)
&& !id.equals(ENTITY_TYPE_META_DATA)
&& !id.equals(PACKAGE)) {
try {
NameValidator.validateEntityName(entityType.getId());
} catch (MolgenisDataException e) {
throw new MolgenisValidationException(new ConstraintViolation(e.getMessage()));
}
}
} } | public class class_name {
static void validateEntityId(EntityType entityType) {
// validate entity name (e.g. illegal characters, length)
String id = entityType.getId();
if (!id.equals(ATTRIBUTE_META_DATA)
&& !id.equals(ENTITY_TYPE_META_DATA)
&& !id.equals(PACKAGE)) {
try {
NameValidator.validateEntityName(entityType.getId()); // depends on control dependency: [try], data = [none]
} catch (MolgenisDataException e) {
throw new MolgenisValidationException(new ConstraintViolation(e.getMessage()));
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private BigDecimal toBigDecimal(Object value) {
if (value instanceof Long) {
return new BigDecimal((Long) value);
} else if (value instanceof Integer) {
return new BigDecimal((Integer) value);
} else if (value instanceof BigInteger) {
return new BigDecimal((BigInteger) value);
} else if(value instanceof Boolean) {
return new BigDecimal((boolean)value ? 1 : 0);
}
//对于Double类型,先要转换为String,避免精度问题
final String valueStr = convertToStr(value);
if (StrUtil.isBlank(valueStr)) {
return null;
}
return new BigDecimal(valueStr);
} } | public class class_name {
private BigDecimal toBigDecimal(Object value) {
if (value instanceof Long) {
return new BigDecimal((Long) value);
// depends on control dependency: [if], data = [none]
} else if (value instanceof Integer) {
return new BigDecimal((Integer) value);
// depends on control dependency: [if], data = [none]
} else if (value instanceof BigInteger) {
return new BigDecimal((BigInteger) value);
// depends on control dependency: [if], data = [none]
} else if(value instanceof Boolean) {
return new BigDecimal((boolean)value ? 1 : 0);
// depends on control dependency: [if], data = [none]
}
//对于Double类型,先要转换为String,避免精度问题
final String valueStr = convertToStr(value);
if (StrUtil.isBlank(valueStr)) {
return null;
// depends on control dependency: [if], data = [none]
}
return new BigDecimal(valueStr);
} } |
public class class_name {
private void update() {
if (!uptodate) {
summary.clear();
distinctTraces.clear();
traces.clear();
addTraces(allTraces, false);
uptodate = true;
}
} } | public class class_name {
private void update() {
if (!uptodate) {
summary.clear(); // depends on control dependency: [if], data = [none]
distinctTraces.clear(); // depends on control dependency: [if], data = [none]
traces.clear(); // depends on control dependency: [if], data = [none]
addTraces(allTraces, false); // depends on control dependency: [if], data = [none]
uptodate = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String newNonce(HttpRequest request)
{
long ts=request.getTimeStamp();
long sk=nonceSecret;
byte[] nounce = new byte[24];
for (int i=0;i<8;i++)
{
nounce[i]=(byte)(ts&0xff);
ts=ts>>8;
nounce[8+i]=(byte)(sk&0xff);
sk=sk>>8;
}
byte[] hash=null;
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(nounce,0,16);
hash = md.digest();
}
catch(Exception e)
{
log.fatal(this,e);
}
for (int i=0;i<hash.length;i++)
{
nounce[8+i]=hash[i];
if (i==23)
break;
}
return new String(B64Code.encode(nounce));
} } | public class class_name {
public String newNonce(HttpRequest request)
{
long ts=request.getTimeStamp();
long sk=nonceSecret;
byte[] nounce = new byte[24];
for (int i=0;i<8;i++)
{
nounce[i]=(byte)(ts&0xff); // depends on control dependency: [for], data = [i]
ts=ts>>8; // depends on control dependency: [for], data = [none]
nounce[8+i]=(byte)(sk&0xff); // depends on control dependency: [for], data = [i]
sk=sk>>8; // depends on control dependency: [for], data = [none]
}
byte[] hash=null;
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset(); // depends on control dependency: [try], data = [none]
md.update(nounce,0,16); // depends on control dependency: [try], data = [none]
hash = md.digest(); // depends on control dependency: [try], data = [none]
}
catch(Exception e)
{
log.fatal(this,e);
} // depends on control dependency: [catch], data = [none]
for (int i=0;i<hash.length;i++)
{
nounce[8+i]=hash[i]; // depends on control dependency: [for], data = [i]
if (i==23)
break;
}
return new String(B64Code.encode(nounce));
} } |
public class class_name {
@Transactional
public TaskBase findInterruptedTask(ProcessInstance processInstance) {
TaskBase ret = null;
for (Audit audit : processInstance.getAudits()) {
if (audit.isInterrupted()) {
ret = getTask(
audit.getProcessDefinitionName(), audit.getTaskId());
audit.setInterrupted(false);
break;
}
}
return ret;
} } | public class class_name {
@Transactional
public TaskBase findInterruptedTask(ProcessInstance processInstance) {
TaskBase ret = null;
for (Audit audit : processInstance.getAudits()) {
if (audit.isInterrupted()) {
ret = getTask(
audit.getProcessDefinitionName(), audit.getTaskId()); // depends on control dependency: [if], data = [none]
audit.setInterrupted(false); // depends on control dependency: [if], data = [none]
break;
}
}
return ret;
} } |
public class class_name {
public HashMap<String, DependencyInfo> parseMixLoc(File mixLock){
logger.info("Hex - parsing " + mixLock.getPath());
HashMap<String, DependencyInfo> dependencyInfoHashMap = new HashMap<>();
FileReader fileReader;
BufferedReader bufferedReader;
/*
lines of the mix.lock file can be of 2 types - hex of git
"artificery": {:hex, :artificery, "0.2.6", "f602909757263f7897130cbd006b0e40514a541b148d366ad65b89236b93497a", [:mix], [], "hexpm"},
"aruspex": {:git, "https://github.com/oyeb/aruspex.git", "5ca5ca6057b61b2bc19a58abd3a5a656c39d0249", [branch: "tweaks"]},
using regex to identify the name, version in case of hex, and commit id in case git
* */
try {
Pattern hexPattern = Pattern.compile(HEX_REGEX);
Pattern gitPattern = Pattern.compile(GIT_REGEX);
Matcher matcher;
fileReader = new FileReader(mixLock);
bufferedReader = new BufferedReader(fileReader);
String currLine;
while ((currLine = bufferedReader.readLine()) != null) {
if (currLine.startsWith(Constants.WHITESPACE)) {
logger.debug("parsing line {}", currLine);
try {
DependencyInfo dependencyInfo = null;
String name = null;
if (currLine.contains(GIT)) {
matcher = gitPattern.matcher(currLine);
if (matcher.find()) {
name = matcher.group(1);
String commitId = matcher.group(3);
dependencyInfo = new DependencyInfo();
dependencyInfo.setArtifactId(name);
dependencyInfo.setCommit(commitId);
}else {
logger.debug("Failed matching GIT pattern on this line");
}
} else {
matcher = hexPattern.matcher(currLine);
if (matcher.find()) {
name = matcher.group(1);
String version = matcher.group(2);
String sha1 = getSha1(name, version);
if (sha1 == null) {
dependencyInfo = new DependencyInfo();
} else {
dependencyInfo = new DependencyInfo(sha1);
}
dependencyInfo.setArtifactId(name);
dependencyInfo.setVersion(version);
dependencyInfo.setSystemPath(dotHexCachePath + fileSeparator + name + Constants.DASH + version + TAR_EXTENSION);
dependencyInfo.setFilename(name + Constants.DASH + version + TAR_EXTENSION);
} else {
logger.debug("Failed matching HEX pattern on this line");
}
}
if (dependencyInfo != null) {
dependencyInfo.setDependencyFile(mixLock.getParent() + fileSeparator + MIX_EXS);
dependencyInfo.setDependencyType(DependencyType.HEX);
dependencyInfoHashMap.put(name, dependencyInfo);
}
} catch (Exception e){
logger.warn("Failed parsing this line, error: {}", e.getMessage());
logger.debug("Exception: {}", e.getStackTrace());
}
}
}
} catch (FileNotFoundException e) {
logger.warn("Can't find {}, error: {}", mixLock.getPath(), e.getMessage());
logger.debug("Error: {}", e.getStackTrace());
} catch (IOException e) {
logger.warn("Can't parse {}, error: {}", mixLock.getPath(), e.getMessage());
logger.debug("Error: {}", e.getStackTrace());
}
return dependencyInfoHashMap;
} } | public class class_name {
public HashMap<String, DependencyInfo> parseMixLoc(File mixLock){
logger.info("Hex - parsing " + mixLock.getPath());
HashMap<String, DependencyInfo> dependencyInfoHashMap = new HashMap<>();
FileReader fileReader;
BufferedReader bufferedReader;
/*
lines of the mix.lock file can be of 2 types - hex of git
"artificery": {:hex, :artificery, "0.2.6", "f602909757263f7897130cbd006b0e40514a541b148d366ad65b89236b93497a", [:mix], [], "hexpm"},
"aruspex": {:git, "https://github.com/oyeb/aruspex.git", "5ca5ca6057b61b2bc19a58abd3a5a656c39d0249", [branch: "tweaks"]},
using regex to identify the name, version in case of hex, and commit id in case git
* */
try {
Pattern hexPattern = Pattern.compile(HEX_REGEX);
Pattern gitPattern = Pattern.compile(GIT_REGEX);
Matcher matcher;
fileReader = new FileReader(mixLock); // depends on control dependency: [try], data = [none]
bufferedReader = new BufferedReader(fileReader); // depends on control dependency: [try], data = [none]
String currLine;
while ((currLine = bufferedReader.readLine()) != null) {
if (currLine.startsWith(Constants.WHITESPACE)) {
logger.debug("parsing line {}", currLine); // depends on control dependency: [if], data = [none]
try {
DependencyInfo dependencyInfo = null;
String name = null;
if (currLine.contains(GIT)) {
matcher = gitPattern.matcher(currLine); // depends on control dependency: [if], data = [none]
if (matcher.find()) {
name = matcher.group(1); // depends on control dependency: [if], data = [none]
String commitId = matcher.group(3);
dependencyInfo = new DependencyInfo(); // depends on control dependency: [if], data = [none]
dependencyInfo.setArtifactId(name); // depends on control dependency: [if], data = [none]
dependencyInfo.setCommit(commitId); // depends on control dependency: [if], data = [none]
}else {
logger.debug("Failed matching GIT pattern on this line"); // depends on control dependency: [if], data = [none]
}
} else {
matcher = hexPattern.matcher(currLine); // depends on control dependency: [if], data = [none]
if (matcher.find()) {
name = matcher.group(1); // depends on control dependency: [if], data = [none]
String version = matcher.group(2);
String sha1 = getSha1(name, version);
if (sha1 == null) {
dependencyInfo = new DependencyInfo(); // depends on control dependency: [if], data = [none]
} else {
dependencyInfo = new DependencyInfo(sha1); // depends on control dependency: [if], data = [(sha1]
}
dependencyInfo.setArtifactId(name); // depends on control dependency: [if], data = [none]
dependencyInfo.setVersion(version); // depends on control dependency: [if], data = [none]
dependencyInfo.setSystemPath(dotHexCachePath + fileSeparator + name + Constants.DASH + version + TAR_EXTENSION); // depends on control dependency: [if], data = [none]
dependencyInfo.setFilename(name + Constants.DASH + version + TAR_EXTENSION); // depends on control dependency: [if], data = [none]
} else {
logger.debug("Failed matching HEX pattern on this line"); // depends on control dependency: [if], data = [none]
}
}
if (dependencyInfo != null) {
dependencyInfo.setDependencyFile(mixLock.getParent() + fileSeparator + MIX_EXS); // depends on control dependency: [if], data = [none]
dependencyInfo.setDependencyType(DependencyType.HEX); // depends on control dependency: [if], data = [none]
dependencyInfoHashMap.put(name, dependencyInfo); // depends on control dependency: [if], data = [none]
}
} catch (Exception e){
logger.warn("Failed parsing this line, error: {}", e.getMessage());
logger.debug("Exception: {}", e.getStackTrace());
} // depends on control dependency: [catch], data = [none]
}
}
} catch (FileNotFoundException e) {
logger.warn("Can't find {}, error: {}", mixLock.getPath(), e.getMessage());
logger.debug("Error: {}", e.getStackTrace());
} catch (IOException e) {
logger.warn("Can't parse {}, error: {}", mixLock.getPath(), e.getMessage());
logger.debug("Error: {}", e.getStackTrace());
} // depends on control dependency: [catch], data = [none]
return dependencyInfoHashMap;
} } |
public class class_name {
private void init1() {
try (BufferedReader br = MyStaticValue.getPersonReader()) {
pnMap = new HashMap<>();
String temp = null;
String[] strs = null;
PersonNatureAttr pna = null;
while ((temp = br.readLine()) != null) {
pna = new PersonNatureAttr();
strs = temp.split("\t");
pna = pnMap.get(strs[0]);
if (pna == null) {
pna = new PersonNatureAttr();
}
pna.addFreq(Integer.parseInt(strs[1]), Integer.parseInt(strs[2]));
pnMap.put(strs[0], pna);
}
} catch (NumberFormatException e) {
logger.warn("数字格式不正确", e);
} catch (IOException e) {
logger.warn("IO异常", e);
}
} } | public class class_name {
private void init1() {
try (BufferedReader br = MyStaticValue.getPersonReader()) {
pnMap = new HashMap<>();
String temp = null;
String[] strs = null;
PersonNatureAttr pna = null;
while ((temp = br.readLine()) != null) {
pna = new PersonNatureAttr(); // depends on control dependency: [while], data = [none]
strs = temp.split("\t"); // depends on control dependency: [while], data = [none]
pna = pnMap.get(strs[0]); // depends on control dependency: [while], data = [none]
if (pna == null) {
pna = new PersonNatureAttr(); // depends on control dependency: [if], data = [none]
}
pna.addFreq(Integer.parseInt(strs[1]), Integer.parseInt(strs[2])); // depends on control dependency: [while], data = [none]
pnMap.put(strs[0], pna); // depends on control dependency: [while], data = [none]
}
} catch (NumberFormatException e) {
logger.warn("数字格式不正确", e);
} catch (IOException e) {
logger.warn("IO异常", e);
}
} } |
public class class_name {
public boolean remove(int vertex) {
// If we can remove the vertex from the global set, then at least one of
// the type-specific graphs has this vertex.
SparseDirectedTypedEdgeSet<T> edges = vertexToEdges.remove(vertex);
if (edges != null) {
size -= edges.size();
for (int other : edges.connected()) {
vertexToEdges.get(other).disconnect(vertex);
}
// Check whether removing this vertex has caused us to remove
// the last edge for this type in the graph. If so, the graph
// no longer has this type and we need to update the state.
for (DirectedTypedEdge<T> e : edges)
updateTypeCounts(e.edgeType(), -1);
// Update any of the subgraphs that had this vertex to notify them
// that it was removed
Iterator<WeakReference<Subgraph>> iter = subgraphs.iterator();
while (iter.hasNext()) {
WeakReference<Subgraph> ref = iter.next();
Subgraph s = ref.get();
// Check whether this subgraph was already gc'd (the subgraph
// was no longer in use) and if so, remove the ref from the list
// to avoid iterating over it again
if (s == null) {
iter.remove();
continue;
}
// If we removed the vertex from the subgraph, then check
// whether we also removed any of the types in that subgraph
if (s.vertexSubset.remove(vertex)) {
Iterator<T> subgraphTypesIter = s.validTypes.iterator();
while (subgraphTypesIter.hasNext()) {
if (!typeCounts.containsKey(subgraphTypesIter.next()))
subgraphTypesIter.remove();
}
}
}
return true;
}
return false;
} } | public class class_name {
public boolean remove(int vertex) {
// If we can remove the vertex from the global set, then at least one of
// the type-specific graphs has this vertex.
SparseDirectedTypedEdgeSet<T> edges = vertexToEdges.remove(vertex);
if (edges != null) {
size -= edges.size(); // depends on control dependency: [if], data = [none]
for (int other : edges.connected()) {
vertexToEdges.get(other).disconnect(vertex); // depends on control dependency: [for], data = [other]
}
// Check whether removing this vertex has caused us to remove
// the last edge for this type in the graph. If so, the graph
// no longer has this type and we need to update the state.
for (DirectedTypedEdge<T> e : edges)
updateTypeCounts(e.edgeType(), -1);
// Update any of the subgraphs that had this vertex to notify them
// that it was removed
Iterator<WeakReference<Subgraph>> iter = subgraphs.iterator();
while (iter.hasNext()) {
WeakReference<Subgraph> ref = iter.next();
Subgraph s = ref.get();
// Check whether this subgraph was already gc'd (the subgraph
// was no longer in use) and if so, remove the ref from the list
// to avoid iterating over it again
if (s == null) {
iter.remove(); // depends on control dependency: [if], data = [none]
continue;
}
// If we removed the vertex from the subgraph, then check
// whether we also removed any of the types in that subgraph
if (s.vertexSubset.remove(vertex)) {
Iterator<T> subgraphTypesIter = s.validTypes.iterator();
while (subgraphTypesIter.hasNext()) {
if (!typeCounts.containsKey(subgraphTypesIter.next()))
subgraphTypesIter.remove();
}
}
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public boolean addProperty(String propertyName) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(propertyName)) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_PROP_1, propertyName));
}
return m_properties.add(propertyName);
} else {
return false;
}
} } | public class class_name {
public boolean addProperty(String propertyName) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(propertyName)) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_PROP_1, propertyName)); // depends on control dependency: [if], data = [none]
}
return m_properties.add(propertyName); // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectoryName)
{
removeEmptyDirectories(new File(outputDirectoryName));
boolean useFrames = System.getProperty(FRAMES_PROPERTY, "true").equals("true");
boolean onlyFailures = System.getProperty(ONLY_FAILURES_PROPERTY, "false").equals("true");
File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);
outputDirectory.mkdirs();
try
{
if (useFrames)
{
createFrameset(outputDirectory);
}
createOverview(suites, outputDirectory, !useFrames, onlyFailures);
createSuiteList(suites, outputDirectory, onlyFailures);
createGroups(suites, outputDirectory);
createResults(suites, outputDirectory, onlyFailures);
createLog(outputDirectory, onlyFailures);
copyResources(outputDirectory);
}
catch (Exception ex)
{
throw new ReportNGException("Failed generating HTML report.", ex);
}
} } | public class class_name {
public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectoryName)
{
removeEmptyDirectories(new File(outputDirectoryName));
boolean useFrames = System.getProperty(FRAMES_PROPERTY, "true").equals("true");
boolean onlyFailures = System.getProperty(ONLY_FAILURES_PROPERTY, "false").equals("true");
File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);
outputDirectory.mkdirs();
try
{
if (useFrames)
{
createFrameset(outputDirectory); // depends on control dependency: [if], data = [none]
}
createOverview(suites, outputDirectory, !useFrames, onlyFailures); // depends on control dependency: [try], data = [none]
createSuiteList(suites, outputDirectory, onlyFailures); // depends on control dependency: [try], data = [none]
createGroups(suites, outputDirectory); // depends on control dependency: [try], data = [none]
createResults(suites, outputDirectory, onlyFailures); // depends on control dependency: [try], data = [none]
createLog(outputDirectory, onlyFailures); // depends on control dependency: [try], data = [none]
copyResources(outputDirectory); // depends on control dependency: [try], data = [none]
}
catch (Exception ex)
{
throw new ReportNGException("Failed generating HTML report.", ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
protected int getColor(Context ctx) {
int color;
if (this.isEnabled()) {
color = ColorHolder.color(getTextColor(), ctx, R.attr.material_drawer_secondary_text, R.color.material_drawer_secondary_text);
} else {
color = ColorHolder.color(getDisabledTextColor(), ctx, R.attr.material_drawer_hint_text, R.color.material_drawer_hint_text);
}
return color;
} } | public class class_name {
@Override
protected int getColor(Context ctx) {
int color;
if (this.isEnabled()) {
color = ColorHolder.color(getTextColor(), ctx, R.attr.material_drawer_secondary_text, R.color.material_drawer_secondary_text); // depends on control dependency: [if], data = [none]
} else {
color = ColorHolder.color(getDisabledTextColor(), ctx, R.attr.material_drawer_hint_text, R.color.material_drawer_hint_text); // depends on control dependency: [if], data = [none]
}
return color;
} } |
public class class_name {
protected Map<Integer, Class<?>> prepareOptionalGenericTypeMap(Method executeMethod) {
final Parameter[] parameters = executeMethod.getParameters();
if (parameters.length == 0) {
return Collections.emptyMap();
}
final Map<Integer, Class<?>> optionalGenericTypeMap = new LinkedHashMap<Integer, Class<?>>(4);
int index = 0;
for (Parameter parameter : parameters) {
if (isOptionalParameterType(parameter.getType())) {
final Type paramedType = parameter.getParameterizedType();
final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(paramedType);
checkExecuteMethodOptionalParameter(executeMethod, paramedType, genericType);
optionalGenericTypeMap.put(index, genericType);
}
++index;
}
return Collections.unmodifiableMap(optionalGenericTypeMap);
} } | public class class_name {
protected Map<Integer, Class<?>> prepareOptionalGenericTypeMap(Method executeMethod) {
final Parameter[] parameters = executeMethod.getParameters();
if (parameters.length == 0) {
return Collections.emptyMap(); // depends on control dependency: [if], data = [none]
}
final Map<Integer, Class<?>> optionalGenericTypeMap = new LinkedHashMap<Integer, Class<?>>(4);
int index = 0;
for (Parameter parameter : parameters) {
if (isOptionalParameterType(parameter.getType())) {
final Type paramedType = parameter.getParameterizedType();
final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(paramedType);
checkExecuteMethodOptionalParameter(executeMethod, paramedType, genericType);
optionalGenericTypeMap.put(index, genericType);
}
++index;
}
return Collections.unmodifiableMap(optionalGenericTypeMap);
} } |
public class class_name {
private static EvaluationContext buildEvaluationContext(final String expression) {
return new DDRSpelEvaluationContext() {
@Override
public Object lookupVariable(String name) {
Object val = null;
if (isReservedWords(name)) {
val = super.lookupVariable(name);
if (val == null) {
throw new ExpressionValueNotFoundException("Value of '" + name
+ "' is not found when parsing expression '"
+ expression + "'");
}
} else {
val = ShardRouteRuleExpressionContext.lookupVariable(name);
}
return val;
}
};
} } | public class class_name {
private static EvaluationContext buildEvaluationContext(final String expression) {
return new DDRSpelEvaluationContext() {
@Override
public Object lookupVariable(String name) {
Object val = null;
if (isReservedWords(name)) {
val = super.lookupVariable(name); // depends on control dependency: [if], data = [none]
if (val == null) {
throw new ExpressionValueNotFoundException("Value of '" + name
+ "' is not found when parsing expression '"
+ expression + "'");
}
} else {
val = ShardRouteRuleExpressionContext.lookupVariable(name); // depends on control dependency: [if], data = [none]
}
return val;
}
};
} } |
public class class_name {
public static long bytesToLong(byte[] bytes) {
// Magic number 8 should be defined as Long.SIZE / Byte.SIZE
long values = 0;
for (int i = 0; i < 8; i++) {
values <<= 8;
values |= (bytes[i] & 0xff);
}
return values;
} } | public class class_name {
public static long bytesToLong(byte[] bytes) {
// Magic number 8 should be defined as Long.SIZE / Byte.SIZE
long values = 0;
for (int i = 0; i < 8; i++) {
values <<= 8;
// depends on control dependency: [for], data = [none]
values |= (bytes[i] & 0xff);
// depends on control dependency: [for], data = [i]
}
return values;
} } |
public class class_name {
public static String ordinal(final int origI) {
final int i = (origI < 0) ? -origI : origI;
final int modTen = i % 10;
if ( (modTen < 4) && (modTen > 0)) {
int modHundred = i % 100;
if ( (modHundred < 21) && (modHundred > 3) ) {
return Integer.toString(origI) + "th";
}
switch (modTen) {
case 1: return Integer.toString(origI) + "st";
case 2: return Integer.toString(origI) + "nd";
case 3: return Integer.toString(origI) + "rd";
}
}
return Integer.toString(origI) + "th";
} } | public class class_name {
public static String ordinal(final int origI) {
final int i = (origI < 0) ? -origI : origI;
final int modTen = i % 10;
if ( (modTen < 4) && (modTen > 0)) {
int modHundred = i % 100;
if ( (modHundred < 21) && (modHundred > 3) ) {
return Integer.toString(origI) + "th"; // depends on control dependency: [if], data = [none]
}
switch (modTen) {
case 1: return Integer.toString(origI) + "st";
case 2: return Integer.toString(origI) + "nd";
case 3: return Integer.toString(origI) + "rd";
}
}
return Integer.toString(origI) + "th";
} } |
public class class_name {
protected void set (final float values[][])
{
m_nRows = values.length;
m_nCols = values[0].length;
m_aValues = values;
for (int r = 1; r < m_nRows; ++r)
{
m_nCols = Math.min (m_nCols, values[r].length);
}
} } | public class class_name {
protected void set (final float values[][])
{
m_nRows = values.length;
m_nCols = values[0].length;
m_aValues = values;
for (int r = 1; r < m_nRows; ++r)
{
m_nCols = Math.min (m_nCols, values[r].length); // depends on control dependency: [for], data = [r]
}
} } |
public class class_name {
static protected int SFSSelectFeature(Set<Integer> available,
DataSet dataSet, Set<Integer> catToRemove, Set<Integer> numToRemove,
Set<Integer> catSelecteed, Set<Integer> numSelected,
Object evaluater, int folds, Random rand, double[] PbestScore,
int minFeatures)
{
int nCat = dataSet.getNumCategoricalVars();
int curBest = -1;
double curBestScore = Double.POSITIVE_INFINITY;
for(int feature : available)
{
removeFeature(feature, nCat, catToRemove, numToRemove);
DataSet workOn = dataSet.shallowClone();
RemoveAttributeTransform remove = new RemoveAttributeTransform(workOn, catToRemove, numToRemove);
workOn.applyTransform(remove);
double score = getScore(workOn, evaluater, folds, rand);
if(score < curBestScore)
{
curBestScore = score;
curBest = feature;
}
addFeature(feature, nCat, catToRemove, numToRemove);
}
if(curBestScore <= 1e-14 && PbestScore[0] <= 1e-14
&& catSelecteed.size() + numSelected.size() >= minFeatures )
return -1;
if (curBestScore < PbestScore[0]
|| catSelecteed.size() + numSelected.size() < minFeatures
|| Math.abs(PbestScore[0]-curBestScore) < 1e-3)
{
PbestScore[0] = curBestScore;
addFeature(curBest, nCat, catSelecteed, numSelected);
removeFeature(curBest, nCat, catToRemove, numToRemove);
available.remove(curBest);
return curBest;
}
else
return -1; //No possible improvment & weve got enough
} } | public class class_name {
static protected int SFSSelectFeature(Set<Integer> available,
DataSet dataSet, Set<Integer> catToRemove, Set<Integer> numToRemove,
Set<Integer> catSelecteed, Set<Integer> numSelected,
Object evaluater, int folds, Random rand, double[] PbestScore,
int minFeatures)
{
int nCat = dataSet.getNumCategoricalVars();
int curBest = -1;
double curBestScore = Double.POSITIVE_INFINITY;
for(int feature : available)
{
removeFeature(feature, nCat, catToRemove, numToRemove); // depends on control dependency: [for], data = [feature]
DataSet workOn = dataSet.shallowClone();
RemoveAttributeTransform remove = new RemoveAttributeTransform(workOn, catToRemove, numToRemove);
workOn.applyTransform(remove); // depends on control dependency: [for], data = [none]
double score = getScore(workOn, evaluater, folds, rand);
if(score < curBestScore)
{
curBestScore = score; // depends on control dependency: [if], data = [none]
curBest = feature; // depends on control dependency: [if], data = [none]
}
addFeature(feature, nCat, catToRemove, numToRemove); // depends on control dependency: [for], data = [feature]
}
if(curBestScore <= 1e-14 && PbestScore[0] <= 1e-14
&& catSelecteed.size() + numSelected.size() >= minFeatures )
return -1;
if (curBestScore < PbestScore[0]
|| catSelecteed.size() + numSelected.size() < minFeatures
|| Math.abs(PbestScore[0]-curBestScore) < 1e-3)
{
PbestScore[0] = curBestScore; // depends on control dependency: [if], data = [PbestScore[0]]
addFeature(curBest, nCat, catSelecteed, numSelected); // depends on control dependency: [if], data = [none]
removeFeature(curBest, nCat, catToRemove, numToRemove); // depends on control dependency: [if], data = [none]
available.remove(curBest); // depends on control dependency: [if], data = [none]
return curBest; // depends on control dependency: [if], data = [none]
}
else
return -1; //No possible improvment & weve got enough
} } |
public class class_name {
public void addPoi(final Poi BLIP) {
if (pois.keySet().contains(BLIP.getName())) {
updatePoi(BLIP.getName(), BLIP.getLocation());
} else {
pois.put(BLIP.getName(), BLIP);
}
checkForBlips();
} } | public class class_name {
public void addPoi(final Poi BLIP) {
if (pois.keySet().contains(BLIP.getName())) {
updatePoi(BLIP.getName(), BLIP.getLocation()); // depends on control dependency: [if], data = [none]
} else {
pois.put(BLIP.getName(), BLIP); // depends on control dependency: [if], data = [none]
}
checkForBlips();
} } |
public class class_name {
public java.lang.String getJobName() {
java.lang.Object ref = jobName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
jobName_ = s;
return s;
}
} } | public class class_name {
public java.lang.String getJobName() {
java.lang.Object ref = jobName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref; // depends on control dependency: [if], data = [none]
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
jobName_ = s; // depends on control dependency: [if], data = [none]
return s; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized VersionedFile get(String fileName, Version version) {
VersionedFile entry = cache.get(fileName);
if (entry != null) {
if (entry.version().equals(version)) {
// Make a defensive copy since the caller might run further passes on it.
return entry.copy();
} else {
// Aggressively purge to save memory.
cache.remove(fileName);
}
}
return null;
} } | public class class_name {
public synchronized VersionedFile get(String fileName, Version version) {
VersionedFile entry = cache.get(fileName);
if (entry != null) {
if (entry.version().equals(version)) {
// Make a defensive copy since the caller might run further passes on it.
return entry.copy(); // depends on control dependency: [if], data = [none]
} else {
// Aggressively purge to save memory.
cache.remove(fileName); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void setResourcesToSkip(java.util.Collection<String> resourcesToSkip) {
if (resourcesToSkip == null) {
this.resourcesToSkip = null;
return;
}
this.resourcesToSkip = new com.amazonaws.internal.SdkInternalList<String>(resourcesToSkip);
} } | public class class_name {
public void setResourcesToSkip(java.util.Collection<String> resourcesToSkip) {
if (resourcesToSkip == null) {
this.resourcesToSkip = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourcesToSkip = new com.amazonaws.internal.SdkInternalList<String>(resourcesToSkip);
} } |
public class class_name {
protected InjectionPoint buildInjectionPoint(
final String annotationValue,
final String propertyName,
final Class propertyType,
final Class<? extends MadvocScope> scope) {
final String value = annotationValue.trim();
final String name, targetName;
if (StringUtil.isNotBlank(value)) {
name = value;
targetName = propertyName;
}
else {
name = propertyName;
targetName = null;
}
return new InjectionPoint(propertyType, name, targetName, scopeResolver.defaultOrScopeType(scope));
} } | public class class_name {
protected InjectionPoint buildInjectionPoint(
final String annotationValue,
final String propertyName,
final Class propertyType,
final Class<? extends MadvocScope> scope) {
final String value = annotationValue.trim();
final String name, targetName;
if (StringUtil.isNotBlank(value)) {
name = value; // depends on control dependency: [if], data = [none]
targetName = propertyName; // depends on control dependency: [if], data = [none]
}
else {
name = propertyName; // depends on control dependency: [if], data = [none]
targetName = null; // depends on control dependency: [if], data = [none]
}
return new InjectionPoint(propertyType, name, targetName, scopeResolver.defaultOrScopeType(scope));
} } |
public class class_name {
public static Fastq convert(final Fastq fastq, final FastqVariant variant)
{
if (fastq == null)
{
throw new IllegalArgumentException("fastq must not be null");
}
if (variant == null)
{
throw new IllegalArgumentException("variant must not be null");
}
if (fastq.getVariant().equals(variant))
{
return fastq;
}
return new Fastq(fastq.getDescription(), fastq.getSequence(), convertQualities(fastq, variant), variant);
} } | public class class_name {
public static Fastq convert(final Fastq fastq, final FastqVariant variant)
{
if (fastq == null)
{
throw new IllegalArgumentException("fastq must not be null");
}
if (variant == null)
{
throw new IllegalArgumentException("variant must not be null");
}
if (fastq.getVariant().equals(variant))
{
return fastq; // depends on control dependency: [if], data = [none]
}
return new Fastq(fastq.getDescription(), fastq.getSequence(), convertQualities(fastq, variant), variant);
} } |
public class class_name {
private int skipArc(int offset) {
if (isNextSet(offset)) {
if (isLabelCompressed(offset)) {
offset++;
} else {
offset += 1 + 1;
}
} else {
offset += 1 + gtl;
}
return offset;
} } | public class class_name {
private int skipArc(int offset) {
if (isNextSet(offset)) {
if (isLabelCompressed(offset)) {
offset++;
// depends on control dependency: [if], data = [none]
} else {
offset += 1 + 1;
// depends on control dependency: [if], data = [none]
}
} else {
offset += 1 + gtl;
// depends on control dependency: [if], data = [none]
}
return offset;
} } |
public class class_name {
static final TimeBasedRollStrategy findRollStrategy(
final AppenderRollingProperties properties) {
if (properties.getDatePattern() == null) {
LogLog.error("null date pattern");
return ROLL_ERROR;
}
// Strip out quoted sections so that we may safely scan the undecorated
// pattern for characters that are meaningful to SimpleDateFormat.
final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(
properties.getDatePatternLocale());
final String undecoratedDatePattern = localizedDateFormatPatternHelper
.excludeQuoted(properties.getDatePattern());
if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_MINUTE;
}
if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_HOUR;
}
if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_HALF_DAY;
}
if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_DAY;
}
if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_WEEK;
}
if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_MONTH;
}
return ROLL_ERROR;
} } | public class class_name {
static final TimeBasedRollStrategy findRollStrategy(
final AppenderRollingProperties properties) {
if (properties.getDatePattern() == null) {
LogLog.error("null date pattern"); // depends on control dependency: [if], data = [none]
return ROLL_ERROR; // depends on control dependency: [if], data = [none]
}
// Strip out quoted sections so that we may safely scan the undecorated
// pattern for characters that are meaningful to SimpleDateFormat.
final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(
properties.getDatePatternLocale());
final String undecoratedDatePattern = localizedDateFormatPatternHelper
.excludeQuoted(properties.getDatePattern());
if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_MINUTE; // depends on control dependency: [if], data = [none]
}
if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_HOUR; // depends on control dependency: [if], data = [none]
}
if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_HALF_DAY; // depends on control dependency: [if], data = [none]
}
if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_DAY; // depends on control dependency: [if], data = [none]
}
if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_WEEK; // depends on control dependency: [if], data = [none]
}
if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_MONTH; // depends on control dependency: [if], data = [none]
}
return ROLL_ERROR;
} } |
public class class_name {
public LocatedBlock recoverBlock(int namespaceId, Block block,
boolean keepLength, DatanodeID[] datanodeids, boolean closeFile,
long deadline) throws IOException {
int errorCount = 0;
// Number of "replicasBeingWritten" in 0.21 parlance - these are replicas
// on DNs that are still alive from when the write was happening
int rbwCount = 0;
// Number of "replicasWaitingRecovery" in 0.21 parlance - these replicas
// have survived a DN restart, and thus might be truncated (eg if the
// DN died because of a machine power failure, and when the ext3 journal
// replayed, it truncated the file
int rwrCount = 0;
List<BlockRecord> blockRecords = new ArrayList<BlockRecord>();
List<InterDatanodeProtocol> datanodeProxies = new ArrayList<InterDatanodeProtocol>();
// check generation stamps
for (DatanodeID id : datanodeids) {
try {
InterDatanodeProtocol datanode;
if (dnr!= null && dnr.equals(id)) {
LOG.info("Skipping IDNPP creation for local id " + id
+ " when recovering " + block);
datanode = dn;
} else {
LOG.info("Creating IDNPP for non-local id " + id + " (dnReg="
+ dnr + ") when recovering "
+ block);
datanode = DataNode.createInterDataNodeProtocolProxy(id, conf,
socketTimeout);
datanodeProxies.add(datanode);
}
BlockSyncer.throwIfAfterTime(deadline);
BlockRecoveryInfo info = datanode
.startBlockRecovery(namespaceId, block);
if (info == null) {
LOG.info("No block metadata found for block " + block
+ " on datanode " + id);
continue;
}
if (info.getBlock().getGenerationStamp() < block.getGenerationStamp()) {
LOG.info("Only old generation stamp "
+ info.getBlock().getGenerationStamp() + " found on datanode "
+ id + " (needed block=" + block + ")");
continue;
}
blockRecords.add(new BlockRecord(id, datanode, info));
if (info.wasRecoveredOnStartup()) {
rwrCount++;
} else {
rbwCount++;
}
} catch (BlockRecoveryTimeoutException e) {
throw e;
} catch (IOException e) {
++errorCount;
InterDatanodeProtocol.LOG.warn(
"Failed to getBlockMetaDataInfo for block (=" + block
+ ") from datanode (=" + id + ")", e);
}
}
// If we *only* have replicas from post-DN-restart, then we should
// include them in determining length. Otherwise they might cause us
// to truncate too short.
boolean shouldRecoverRwrs = (rbwCount == 0);
List<BlockRecord> syncList = new ArrayList<BlockRecord>();
long minlength = Long.MAX_VALUE;
for (BlockRecord record : blockRecords) {
BlockRecoveryInfo info = record.info;
assert (info != null && info.getBlock().getGenerationStamp() >= block
.getGenerationStamp());
if (!shouldRecoverRwrs && info.wasRecoveredOnStartup()) {
LOG.info("Not recovering replica " + record
+ " since it was recovered on "
+ "startup and we have better replicas");
continue;
}
if (keepLength) {
if (info.getBlock().getNumBytes() == block.getNumBytes()) {
syncList.add(record);
}
} else {
syncList.add(record);
if (info.getBlock().getNumBytes() < minlength) {
minlength = info.getBlock().getNumBytes();
}
}
}
if (syncList.isEmpty() && errorCount > 0) {
DataNode.stopAllProxies(datanodeProxies);
throw new IOException("All datanodes failed: block=" + block
+ ", datanodeids=" + Arrays.asList(datanodeids));
}
if (!keepLength) {
block.setNumBytes(minlength);
}
return blockSyncer.syncBlock(block, syncList, closeFile, datanodeProxies,
deadline);
} } | public class class_name {
public LocatedBlock recoverBlock(int namespaceId, Block block,
boolean keepLength, DatanodeID[] datanodeids, boolean closeFile,
long deadline) throws IOException {
int errorCount = 0;
// Number of "replicasBeingWritten" in 0.21 parlance - these are replicas
// on DNs that are still alive from when the write was happening
int rbwCount = 0;
// Number of "replicasWaitingRecovery" in 0.21 parlance - these replicas
// have survived a DN restart, and thus might be truncated (eg if the
// DN died because of a machine power failure, and when the ext3 journal
// replayed, it truncated the file
int rwrCount = 0;
List<BlockRecord> blockRecords = new ArrayList<BlockRecord>();
List<InterDatanodeProtocol> datanodeProxies = new ArrayList<InterDatanodeProtocol>();
// check generation stamps
for (DatanodeID id : datanodeids) {
try {
InterDatanodeProtocol datanode;
if (dnr!= null && dnr.equals(id)) {
LOG.info("Skipping IDNPP creation for local id " + id
+ " when recovering " + block); // depends on control dependency: [if], data = [none]
datanode = dn; // depends on control dependency: [if], data = [none]
} else {
LOG.info("Creating IDNPP for non-local id " + id + " (dnReg="
+ dnr + ") when recovering "
+ block);
datanode = DataNode.createInterDataNodeProtocolProxy(id, conf,
socketTimeout);
datanodeProxies.add(datanode); // depends on control dependency: [if], data = [none]
}
BlockSyncer.throwIfAfterTime(deadline);
BlockRecoveryInfo info = datanode
.startBlockRecovery(namespaceId, block);
if (info == null) {
LOG.info("No block metadata found for block " + block
+ " on datanode " + id); // depends on control dependency: [if], data = [none]
continue;
}
if (info.getBlock().getGenerationStamp() < block.getGenerationStamp()) {
LOG.info("Only old generation stamp "
+ info.getBlock().getGenerationStamp() + " found on datanode "
+ id + " (needed block=" + block + ")");
continue;
}
blockRecords.add(new BlockRecord(id, datanode, info));
if (info.wasRecoveredOnStartup()) {
rwrCount++;
} else {
rbwCount++;
}
} catch (BlockRecoveryTimeoutException e) {
throw e;
} catch (IOException e) {
++errorCount;
InterDatanodeProtocol.LOG.warn(
"Failed to getBlockMetaDataInfo for block (=" + block
+ ") from datanode (=" + id + ")", e);
}
}
// If we *only* have replicas from post-DN-restart, then we should
// include them in determining length. Otherwise they might cause us
// to truncate too short.
boolean shouldRecoverRwrs = (rbwCount == 0);
List<BlockRecord> syncList = new ArrayList<BlockRecord>();
long minlength = Long.MAX_VALUE;
for (BlockRecord record : blockRecords) {
BlockRecoveryInfo info = record.info;
assert (info != null && info.getBlock().getGenerationStamp() >= block
.getGenerationStamp());
if (!shouldRecoverRwrs && info.wasRecoveredOnStartup()) {
LOG.info("Not recovering replica " + record
+ " since it was recovered on "
+ "startup and we have better replicas");
continue;
}
if (keepLength) {
if (info.getBlock().getNumBytes() == block.getNumBytes()) {
syncList.add(record);
}
} else {
syncList.add(record);
if (info.getBlock().getNumBytes() < minlength) {
minlength = info.getBlock().getNumBytes();
}
}
}
if (syncList.isEmpty() && errorCount > 0) {
DataNode.stopAllProxies(datanodeProxies);
throw new IOException("All datanodes failed: block=" + block
+ ", datanodeids=" + Arrays.asList(datanodeids));
}
if (!keepLength) {
block.setNumBytes(minlength);
}
return blockSyncer.syncBlock(block, syncList, closeFile, datanodeProxies,
deadline);
} } |
public class class_name {
public boolean limit() {
//get connection
Object connection = getConnection();
Object result = limitRequest(connection);
if (FAIL_CODE != (Long) result) {
return true;
} else {
return false;
}
} } | public class class_name {
public boolean limit() {
//get connection
Object connection = getConnection();
Object result = limitRequest(connection);
if (FAIL_CODE != (Long) result) {
return true; // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String formatNameForClassLoading(String name) {
if (name.equals("int")
|| name.equals("long")
|| name.equals("short")
|| name.equals("float")
|| name.equals("double")
|| name.equals("byte")
|| name.equals("char")
|| name.equals("boolean")
|| name.equals("void")
) {
return name;
}
if (name == null) {
return "java.lang.Object;";
}
if (name.startsWith("[")) {
return name.replace('/', '.');
}
if (name.startsWith("L")) {
name = name.substring(1);
if (name.endsWith(";")) {
name = name.substring(0, name.length() - 1);
}
return name.replace('/', '.');
}
String prefix = "";
if (name.endsWith("[]")) { // todo need process multi
prefix = "[";
name = name.substring(0, name.length() - 2);
if (name.equals("int")) {
return prefix + "I";
} else if (name.equals("long")) {
return prefix + "J";
} else if (name.equals("short")) {
return prefix + "S";
} else if (name.equals("float")) {
return prefix + "F";
} else if (name.equals("double")) {
return prefix + "D";
} else if (name.equals("byte")) {
return prefix + "B";
} else if (name.equals("char")) {
return prefix + "C";
} else if (name.equals("boolean")) {
return prefix + "Z";
} else {
return prefix + "L" + name.replace('/', '.') + ";";
}
}
return name.replace('/', '.');
} } | public class class_name {
public static String formatNameForClassLoading(String name) {
if (name.equals("int")
|| name.equals("long")
|| name.equals("short")
|| name.equals("float")
|| name.equals("double")
|| name.equals("byte")
|| name.equals("char")
|| name.equals("boolean")
|| name.equals("void")
) {
return name; // depends on control dependency: [if], data = [none]
}
if (name == null) {
return "java.lang.Object;"; // depends on control dependency: [if], data = [none]
}
if (name.startsWith("[")) {
return name.replace('/', '.'); // depends on control dependency: [if], data = [none]
}
if (name.startsWith("L")) {
name = name.substring(1); // depends on control dependency: [if], data = [none]
if (name.endsWith(";")) {
name = name.substring(0, name.length() - 1); // depends on control dependency: [if], data = [none]
}
return name.replace('/', '.'); // depends on control dependency: [if], data = [none]
}
String prefix = "";
if (name.endsWith("[]")) { // todo need process multi
prefix = "["; // depends on control dependency: [if], data = [none]
name = name.substring(0, name.length() - 2); // depends on control dependency: [if], data = [none]
if (name.equals("int")) {
return prefix + "I"; // depends on control dependency: [if], data = [none]
} else if (name.equals("long")) {
return prefix + "J"; // depends on control dependency: [if], data = [none]
} else if (name.equals("short")) {
return prefix + "S"; // depends on control dependency: [if], data = [none]
} else if (name.equals("float")) {
return prefix + "F"; // depends on control dependency: [if], data = [none]
} else if (name.equals("double")) {
return prefix + "D"; // depends on control dependency: [if], data = [none]
} else if (name.equals("byte")) {
return prefix + "B"; // depends on control dependency: [if], data = [none]
} else if (name.equals("char")) {
return prefix + "C"; // depends on control dependency: [if], data = [none]
} else if (name.equals("boolean")) {
return prefix + "Z"; // depends on control dependency: [if], data = [none]
} else {
return prefix + "L" + name.replace('/', '.') + ";"; // depends on control dependency: [if], data = [none]
}
}
return name.replace('/', '.');
} } |
public class class_name {
public static boolean call(PageContext pc, String str) {
try {
return pc.evaluate(str) == null;
}
catch (PageException e) {
return true;
}
} } | public class class_name {
public static boolean call(PageContext pc, String str) {
try {
return pc.evaluate(str) == null; // depends on control dependency: [try], data = [none]
}
catch (PageException e) {
return true;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String encodeHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
} } | public class class_name {
public static String encodeHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4]; // depends on control dependency: [for], data = [j]
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // depends on control dependency: [for], data = [j]
}
return new String(hexChars);
} } |
public class class_name {
private Optional<String> getPreferredRack(final List<String> rackNames) {
for (final String rackName : getRackNamesOrDefault(rackNames)) {
// if it does not end with the any modifier, then we should do an exact match
if (!rackName.endsWith(Constants.ANY_RACK)) {
if (freeNodesPerRack.containsKey(rackName) && freeNodesPerRack.get(rackName).size() > 0) {
return Optional.of(rackName);
}
} else {
// if ends with the any modifier, we do a prefix match
for (final String possibleRackName : this.availableRacks) {
// remove the any modifier
final String newRackName = rackName.substring(0, rackName.length() - 1);
if (possibleRackName.startsWith(newRackName) &&
this.freeNodesPerRack.get(possibleRackName).size() > 0) {
return Optional.of(possibleRackName);
}
}
}
}
return Optional.empty();
} } | public class class_name {
private Optional<String> getPreferredRack(final List<String> rackNames) {
for (final String rackName : getRackNamesOrDefault(rackNames)) {
// if it does not end with the any modifier, then we should do an exact match
if (!rackName.endsWith(Constants.ANY_RACK)) {
if (freeNodesPerRack.containsKey(rackName) && freeNodesPerRack.get(rackName).size() > 0) {
return Optional.of(rackName); // depends on control dependency: [if], data = [none]
}
} else {
// if ends with the any modifier, we do a prefix match
for (final String possibleRackName : this.availableRacks) {
// remove the any modifier
final String newRackName = rackName.substring(0, rackName.length() - 1);
if (possibleRackName.startsWith(newRackName) &&
this.freeNodesPerRack.get(possibleRackName).size() > 0) {
return Optional.of(possibleRackName); // depends on control dependency: [if], data = [none]
}
}
}
}
return Optional.empty();
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <K, V> K[] mapKeyToArray(Map<K, V> map, Class<K> clazz) {
if (Checker.isNotEmpty(map)) {
K[] array = (K[]) Array.newInstance(clazz, map.size());
int i = 0;
for (K k : map.keySet()) {
array[i++] = k;
}
return array;
}
return null;
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <K, V> K[] mapKeyToArray(Map<K, V> map, Class<K> clazz) {
if (Checker.isNotEmpty(map)) {
K[] array = (K[]) Array.newInstance(clazz, map.size());
int i = 0;
for (K k : map.keySet()) {
array[i++] = k; // depends on control dependency: [for], data = [k]
}
return array; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public ServiceFuture<List<NodeFile>> listFromTaskAsync(final String jobId, final String taskId, final Boolean recursive, final FileListFromTaskOptions fileListFromTaskOptions, final ListOperationCallback<NodeFile> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listFromTaskSinglePageAsync(jobId, taskId, recursive, fileListFromTaskOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>> call(String nextPageLink) {
FileListFromTaskNextOptions fileListFromTaskNextOptions = null;
if (fileListFromTaskOptions != null) {
fileListFromTaskNextOptions = new FileListFromTaskNextOptions();
fileListFromTaskNextOptions.withClientRequestId(fileListFromTaskOptions.clientRequestId());
fileListFromTaskNextOptions.withReturnClientRequestId(fileListFromTaskOptions.returnClientRequestId());
fileListFromTaskNextOptions.withOcpDate(fileListFromTaskOptions.ocpDate());
}
return listFromTaskNextSinglePageAsync(nextPageLink, fileListFromTaskNextOptions);
}
},
serviceCallback);
} } | public class class_name {
public ServiceFuture<List<NodeFile>> listFromTaskAsync(final String jobId, final String taskId, final Boolean recursive, final FileListFromTaskOptions fileListFromTaskOptions, final ListOperationCallback<NodeFile> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listFromTaskSinglePageAsync(jobId, taskId, recursive, fileListFromTaskOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>> call(String nextPageLink) {
FileListFromTaskNextOptions fileListFromTaskNextOptions = null;
if (fileListFromTaskOptions != null) {
fileListFromTaskNextOptions = new FileListFromTaskNextOptions(); // depends on control dependency: [if], data = [none]
fileListFromTaskNextOptions.withClientRequestId(fileListFromTaskOptions.clientRequestId()); // depends on control dependency: [if], data = [(fileListFromTaskOptions]
fileListFromTaskNextOptions.withReturnClientRequestId(fileListFromTaskOptions.returnClientRequestId()); // depends on control dependency: [if], data = [(fileListFromTaskOptions]
fileListFromTaskNextOptions.withOcpDate(fileListFromTaskOptions.ocpDate()); // depends on control dependency: [if], data = [(fileListFromTaskOptions]
}
return listFromTaskNextSinglePageAsync(nextPageLink, fileListFromTaskNextOptions);
}
},
serviceCallback);
} } |
public class class_name {
private void sortAndCacheEvents(List<? extends WeekViewEvent> events) {
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
} } | public class class_name {
private void sortAndCacheEvents(List<? extends WeekViewEvent> events) {
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event); // depends on control dependency: [for], data = [event]
}
} } |
public class class_name {
public void marshall(GetVoiceConnectorOriginationRequest getVoiceConnectorOriginationRequest, ProtocolMarshaller protocolMarshaller) {
if (getVoiceConnectorOriginationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getVoiceConnectorOriginationRequest.getVoiceConnectorId(), VOICECONNECTORID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetVoiceConnectorOriginationRequest getVoiceConnectorOriginationRequest, ProtocolMarshaller protocolMarshaller) {
if (getVoiceConnectorOriginationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getVoiceConnectorOriginationRequest.getVoiceConnectorId(), VOICECONNECTORID_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 RiskExceptionConfigurationType withBlockedIPRangeList(String... blockedIPRangeList) {
if (this.blockedIPRangeList == null) {
setBlockedIPRangeList(new java.util.ArrayList<String>(blockedIPRangeList.length));
}
for (String ele : blockedIPRangeList) {
this.blockedIPRangeList.add(ele);
}
return this;
} } | public class class_name {
public RiskExceptionConfigurationType withBlockedIPRangeList(String... blockedIPRangeList) {
if (this.blockedIPRangeList == null) {
setBlockedIPRangeList(new java.util.ArrayList<String>(blockedIPRangeList.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : blockedIPRangeList) {
this.blockedIPRangeList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.