code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static <T> AList<T> create(Iterable<T> elements) {
if (elements instanceof AList) {
return (AList<T>) elements;
}
if(elements instanceof List) {
return create((List<T>) elements);
}
AList<T> result = nil();
for(T el: elements) {
result = result.cons(el);
}
return result.reverse();
} } | public class class_name {
public static <T> AList<T> create(Iterable<T> elements) {
if (elements instanceof AList) {
return (AList<T>) elements; // depends on control dependency: [if], data = [none]
}
if(elements instanceof List) {
return create((List<T>) elements); // depends on control dependency: [if], data = [none]
}
AList<T> result = nil();
for(T el: elements) {
result = result.cons(el); // depends on control dependency: [for], data = [el]
}
return result.reverse();
} } |
public class class_name {
public <S, T> T convertTo(ConverterKey<S,T> key, Object object) {
if (object == null) {
return null;
}
Converter<S, T> conv = findConverter(key.getInputClass(), key.getOutputClass(), key.getQualifierAnnotation() == null ? DefaultBinding.class : key.getQualifierAnnotation());
if (conv == null) {
throw new NoConverterFoundException(key);
}
@SuppressWarnings("unchecked")
S myObject = (S)object;
return conv.convert(myObject);
} } | public class class_name {
public <S, T> T convertTo(ConverterKey<S,T> key, Object object) {
if (object == null) {
return null;
// depends on control dependency: [if], data = [none]
}
Converter<S, T> conv = findConverter(key.getInputClass(), key.getOutputClass(), key.getQualifierAnnotation() == null ? DefaultBinding.class : key.getQualifierAnnotation());
if (conv == null) {
throw new NoConverterFoundException(key);
}
@SuppressWarnings("unchecked")
S myObject = (S)object;
return conv.convert(myObject);
} } |
public class class_name {
public static String normalizeSpace(String str) {
str = strip(str);
if(str == null || str.length() <= 2) {
return str;
}
StringBuilder b = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isWhitespace(c)) {
if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {
b.append(' ');
}
} else {
b.append(c);
}
}
return b.toString();
} } | public class class_name {
public static String normalizeSpace(String str) {
str = strip(str);
if(str == null || str.length() <= 2) {
return str; // depends on control dependency: [if], data = [none]
}
StringBuilder b = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isWhitespace(c)) {
if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {
b.append(' '); // depends on control dependency: [if], data = [none]
}
} else {
b.append(c); // depends on control dependency: [if], data = [none]
}
}
return b.toString();
} } |
public class class_name {
protected String getToNames() {
List<String> users = new ArrayList<String>();
Iterator<String> itIds = idsList().iterator();
while (itIds.hasNext()) {
String id = itIds.next();
CmsSessionInfo session = OpenCms.getSessionManager().getSessionInfo(id);
if (session != null) {
try {
String userName = getCms().readUser(session.getUserId()).getFullName();
if (!users.contains(userName)) {
users.add(userName);
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
StringBuffer result = new StringBuffer(256);
Iterator<String> itUsers = users.iterator();
while (itUsers.hasNext()) {
result.append(itUsers.next());
if (itUsers.hasNext()) {
result.append("; ");
}
}
return result.toString();
} } | public class class_name {
protected String getToNames() {
List<String> users = new ArrayList<String>();
Iterator<String> itIds = idsList().iterator();
while (itIds.hasNext()) {
String id = itIds.next();
CmsSessionInfo session = OpenCms.getSessionManager().getSessionInfo(id);
if (session != null) {
try {
String userName = getCms().readUser(session.getUserId()).getFullName();
if (!users.contains(userName)) {
users.add(userName); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
StringBuffer result = new StringBuffer(256);
Iterator<String> itUsers = users.iterator();
while (itUsers.hasNext()) {
result.append(itUsers.next()); // depends on control dependency: [while], data = [none]
if (itUsers.hasNext()) {
result.append("; "); // depends on control dependency: [if], data = [none]
}
}
return result.toString();
} } |
public class class_name {
public MessageAttributeValue withStringListValues(String... stringListValues) {
if (this.stringListValues == null) {
setStringListValues(new com.amazonaws.internal.SdkInternalList<String>(stringListValues.length));
}
for (String ele : stringListValues) {
this.stringListValues.add(ele);
}
return this;
} } | public class class_name {
public MessageAttributeValue withStringListValues(String... stringListValues) {
if (this.stringListValues == null) {
setStringListValues(new com.amazonaws.internal.SdkInternalList<String>(stringListValues.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : stringListValues) {
this.stringListValues.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
public boolean isMandatoryDimension(String dimensionName) {
if (isValidDimension(dimensionName, null)) {
return mandatoryDimensionNames.contains(dimensionName.toUpperCase(Locale.ENGLISH));
}
return false;
} } | public class class_name {
@Override
public boolean isMandatoryDimension(String dimensionName) {
if (isValidDimension(dimensionName, null)) {
return mandatoryDimensionNames.contains(dimensionName.toUpperCase(Locale.ENGLISH)); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void listAlternatives(ILexNameToken name)
{
for (PDefinition possible : findMatches(name))
{
if (af.createPDefinitionAssistant().isFunctionOrOperation(possible))
{
TypeChecker.detail("Possible", possible.getName());
}
}
} } | public class class_name {
public void listAlternatives(ILexNameToken name)
{
for (PDefinition possible : findMatches(name))
{
if (af.createPDefinitionAssistant().isFunctionOrOperation(possible))
{
TypeChecker.detail("Possible", possible.getName()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected Reader generateResourceForDebug(Reader rd, GeneratorContext context) {
// Rewrite the image URL
StringWriter writer = new StringWriter();
try {
IOUtils.copy(rd, writer);
String content = rewriteUrl(context, writer.toString());
rd = new StringReader(content);
} catch (IOException e) {
throw new BundlingProcessException(e);
}
return rd;
} } | public class class_name {
protected Reader generateResourceForDebug(Reader rd, GeneratorContext context) {
// Rewrite the image URL
StringWriter writer = new StringWriter();
try {
IOUtils.copy(rd, writer); // depends on control dependency: [try], data = [none]
String content = rewriteUrl(context, writer.toString());
rd = new StringReader(content); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new BundlingProcessException(e);
} // depends on control dependency: [catch], data = [none]
return rd;
} } |
public class class_name {
public static void main(String args[]) {
if (args.length != 4) {
System.err.println("arguments: srcfile destfile1 destfile2 pagenumber");
}
else {
try {
int pagenumber = Integer.parseInt(args[3]);
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
if (pagenumber < 2 || pagenumber > n) {
throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page.");
}
// step 1: creation of a document-object
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1]));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2]));
// step 3: we open the document
document1.open();
PdfContentByte cb1 = writer1.getDirectContent();
document2.open();
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < pagenumber - 1) {
i++;
document1.setPageSize(reader.getPageSizeWithRotation(i));
document1.newPage();
page = writer1.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
}
else {
cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
while (i < n) {
i++;
document2.setPageSize(reader.getPageSizeWithRotation(i));
document2.newPage();
page = writer2.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
}
else {
cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
System.out.println("Processed page " + i);
}
// step 5: we close the document
document1.close();
document2.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
} } | public class class_name {
public static void main(String args[]) {
if (args.length != 4) {
System.err.println("arguments: srcfile destfile1 destfile2 pagenumber"); // depends on control dependency: [if], data = [none]
}
else {
try {
int pagenumber = Integer.parseInt(args[3]);
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file."); // depends on control dependency: [try], data = [none]
if (pagenumber < 2 || pagenumber > n) {
throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page.");
}
// step 1: creation of a document-object
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1]));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2]));
// step 3: we open the document
document1.open(); // depends on control dependency: [try], data = [none]
PdfContentByte cb1 = writer1.getDirectContent();
document2.open(); // depends on control dependency: [try], data = [none]
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < pagenumber - 1) {
i++; // depends on control dependency: [while], data = [none]
document1.setPageSize(reader.getPageSizeWithRotation(i)); // depends on control dependency: [while], data = [(i]
document1.newPage(); // depends on control dependency: [while], data = [none]
page = writer1.getImportedPage(reader, i); // depends on control dependency: [while], data = [none]
rotation = reader.getPageRotation(i); // depends on control dependency: [while], data = [(i]
if (rotation == 90 || rotation == 270) {
cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); // depends on control dependency: [if], data = [none]
}
else {
cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0); // depends on control dependency: [if], data = [none]
}
}
while (i < n) {
i++; // depends on control dependency: [while], data = [none]
document2.setPageSize(reader.getPageSizeWithRotation(i)); // depends on control dependency: [while], data = [(i]
document2.newPage(); // depends on control dependency: [while], data = [none]
page = writer2.getImportedPage(reader, i); // depends on control dependency: [while], data = [none]
rotation = reader.getPageRotation(i); // depends on control dependency: [while], data = [(i]
if (rotation == 90 || rotation == 270) {
cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); // depends on control dependency: [if], data = [none]
}
else {
cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0); // depends on control dependency: [if], data = [none]
}
System.out.println("Processed page " + i); // depends on control dependency: [while], data = [none]
}
// step 5: we close the document
document1.close(); // depends on control dependency: [try], data = [none]
document2.close(); // depends on control dependency: [try], data = [none]
}
catch(Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static PushNotificationPayload sound(String sound) {
if (sound == null) throw new IllegalArgumentException("Sound name cannot be null");
PushNotificationPayload payload = complex();
try {
payload.addSound(sound);
} catch (JSONException e) {
}
return payload;
} } | public class class_name {
public static PushNotificationPayload sound(String sound) {
if (sound == null) throw new IllegalArgumentException("Sound name cannot be null");
PushNotificationPayload payload = complex();
try {
payload.addSound(sound);
// depends on control dependency: [try], data = [none]
} catch (JSONException e) {
}
// depends on control dependency: [catch], data = [none]
return payload;
} } |
public class class_name {
public void prepare(String sql, com.couchbase.lite.internal.database.sqlite.SQLiteStatementInfo outStatementInfo) {
if (sql == null) {
throw new IllegalArgumentException("sql must not be null.");
}
final int cookie = mRecentOperations.beginOperation("prepare", sql, null);
try {
final PreparedStatement statement = acquirePreparedStatement(sql);
try {
if (outStatementInfo != null) {
outStatementInfo.numParameters = statement.mNumParameters;
outStatementInfo.readOnly = statement.mReadOnly;
final int columnCount = nativeGetColumnCount(
mConnectionPtr, statement.mStatementPtr);
if (columnCount == 0) {
outStatementInfo.columnNames = EMPTY_STRING_ARRAY;
} else {
outStatementInfo.columnNames = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
outStatementInfo.columnNames[i] = nativeGetColumnName(
mConnectionPtr, statement.mStatementPtr, i);
}
}
}
} finally {
releasePreparedStatement(statement);
}
} catch (RuntimeException ex) {
mRecentOperations.failOperation(cookie, ex);
throw ex;
} finally {
mRecentOperations.endOperation(cookie);
}
} } | public class class_name {
public void prepare(String sql, com.couchbase.lite.internal.database.sqlite.SQLiteStatementInfo outStatementInfo) {
if (sql == null) {
throw new IllegalArgumentException("sql must not be null.");
}
final int cookie = mRecentOperations.beginOperation("prepare", sql, null);
try {
final PreparedStatement statement = acquirePreparedStatement(sql);
try {
if (outStatementInfo != null) {
outStatementInfo.numParameters = statement.mNumParameters; // depends on control dependency: [if], data = [none]
outStatementInfo.readOnly = statement.mReadOnly; // depends on control dependency: [if], data = [none]
final int columnCount = nativeGetColumnCount(
mConnectionPtr, statement.mStatementPtr);
if (columnCount == 0) {
outStatementInfo.columnNames = EMPTY_STRING_ARRAY; // depends on control dependency: [if], data = [none]
} else {
outStatementInfo.columnNames = new String[columnCount]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < columnCount; i++) {
outStatementInfo.columnNames[i] = nativeGetColumnName(
mConnectionPtr, statement.mStatementPtr, i); // depends on control dependency: [for], data = [i]
}
}
}
} finally {
releasePreparedStatement(statement);
}
} catch (RuntimeException ex) {
mRecentOperations.failOperation(cookie, ex);
throw ex;
} finally { // depends on control dependency: [catch], data = [none]
mRecentOperations.endOperation(cookie);
}
} } |
public class class_name {
private void inject2OneConf(String key, DisconfCenterItem disconfCenterItem) {
if (disconfCenterItem == null) {
return;
}
try {
Object object = null;
//
// 静态
//
if (!disconfCenterItem.isStatic()) {
object = registry.getFirstByType(disconfCenterItem.getDeclareClass(), false, true);
}
disconfStoreProcessor.inject2Instance(object, key);
} catch (Exception e) {
LOGGER.warn(e.toString(), e);
}
} } | public class class_name {
private void inject2OneConf(String key, DisconfCenterItem disconfCenterItem) {
if (disconfCenterItem == null) {
return; // depends on control dependency: [if], data = [none]
}
try {
Object object = null;
//
// 静态
//
if (!disconfCenterItem.isStatic()) {
object = registry.getFirstByType(disconfCenterItem.getDeclareClass(), false, true); // depends on control dependency: [if], data = [none]
}
disconfStoreProcessor.inject2Instance(object, key); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOGGER.warn(e.toString(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String getCustomHandler(WaybackException exception,
WaybackRequest wbRequest) {
if((exception instanceof ResourceNotInArchiveException)
&& wbRequest.isReplayRequest()) {
String url = wbRequest.getRequestUrl();
String host = UrlOperations.urlToHost(url);
if(hosts.containsKey(host)) {
return jspHandler;
}
}
return null;
} } | public class class_name {
private String getCustomHandler(WaybackException exception,
WaybackRequest wbRequest) {
if((exception instanceof ResourceNotInArchiveException)
&& wbRequest.isReplayRequest()) {
String url = wbRequest.getRequestUrl();
String host = UrlOperations.urlToHost(url);
if(hosts.containsKey(host)) {
return jspHandler; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
private void calculateValueTextHeight() {
Rect valueRect = new Rect();
Rect legendRect = new Rect();
String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? " " + mIndicatorTextUnit : "");
// calculate the boundaries for both texts
mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);
mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);
// calculate string positions in overlay
mValueTextHeight = valueRect.height();
mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);
mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));
int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();
// check if text reaches over screen
if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {
mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding));
mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding));
} else {
mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding);
}
} } | public class class_name {
private void calculateValueTextHeight() {
Rect valueRect = new Rect();
Rect legendRect = new Rect();
String str = Utils.getFloatString(mFocusedPoint.getValue(), mShowDecimal) + (!mIndicatorTextUnit.isEmpty() ? " " + mIndicatorTextUnit : "");
// calculate the boundaries for both texts
mIndicatorPaint.getTextBounds(str, 0, str.length(), valueRect);
mLegendPaint.getTextBounds(mFocusedPoint.getLegendLabel(), 0, mFocusedPoint.getLegendLabel().length(), legendRect);
// calculate string positions in overlay
mValueTextHeight = valueRect.height();
mValueLabelY = (int) (mValueTextHeight + mIndicatorTopPadding);
mLegendLabelY = (int) (mValueTextHeight + mIndicatorTopPadding + legendRect.height() + Utils.dpToPx(7.f));
int chosenWidth = valueRect.width() > legendRect.width() ? valueRect.width() : legendRect.width();
// check if text reaches over screen
if (mFocusedPoint.getCoordinates().getX() + chosenWidth + mIndicatorLeftPadding > -Utils.getTranslationX(mDrawMatrixValues) + mGraphWidth) {
mValueLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (valueRect.width() + mIndicatorLeftPadding)); // depends on control dependency: [if], data = [none]
mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() - (legendRect.width() + mIndicatorLeftPadding)); // depends on control dependency: [if], data = [none]
} else {
mValueLabelX = mLegendLabelX = (int) (mFocusedPoint.getCoordinates().getX() + mIndicatorLeftPadding); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Iterable<String> getAllSortedTypeNames() {
synchronized (lock) {
if (lazyAllSortedTypeNames == null) {
lazyAllSortedTypeNames =
Stream.concat(BUILTIN_TYPES.keySet().stream(), descriptors.keySet().stream())
.sorted()
.collect(toImmutableList());
}
return lazyAllSortedTypeNames;
}
} } | public class class_name {
public Iterable<String> getAllSortedTypeNames() {
synchronized (lock) {
if (lazyAllSortedTypeNames == null) {
lazyAllSortedTypeNames =
Stream.concat(BUILTIN_TYPES.keySet().stream(), descriptors.keySet().stream())
.sorted()
.collect(toImmutableList()); // depends on control dependency: [if], data = [none]
}
return lazyAllSortedTypeNames;
}
} } |
public class class_name {
byte[] encodeLikeAnEngineer(final byte[] input) {
if (input == null) {
throw new NullPointerException("input");
}
final byte[] output = new byte[input.length << 1];
int index = 0; // index in output
for (int i = 0; i < input.length; i++) {
output[index++] = (byte) encodeHalf((input[i] >> 4) & 0x0F);
output[index++] = (byte) encodeHalf((input[i] & 0x0F));
}
return output;
} } | public class class_name {
byte[] encodeLikeAnEngineer(final byte[] input) {
if (input == null) {
throw new NullPointerException("input");
}
final byte[] output = new byte[input.length << 1];
int index = 0; // index in output
for (int i = 0; i < input.length; i++) {
output[index++] = (byte) encodeHalf((input[i] >> 4) & 0x0F); // depends on control dependency: [for], data = [i]
output[index++] = (byte) encodeHalf((input[i] & 0x0F)); // depends on control dependency: [for], data = [i]
}
return output;
} } |
public class class_name {
public void rollback(final OMicroTransaction microTransaction) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
try {
checkOpenness();
if (transaction.get() == null) {
return;
}
if (transaction.get().getMicroTransaction().getId() != microTransaction.getId()) {
throw new OStorageException(
"Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be "
+ "rolled back.");
}
makeStorageDirty();
rollbackStorageTx();
microTransaction.updateRecordCacheAfterRollback();
txRollback.incrementAndGet();
} catch (final IOException e) {
throw OException.wrapException(new OStorageException("Error during micro-transaction rollback"), e);
} finally {
transaction.set(null);
}
} finally {
stateLock.releaseReadLock();
}
} catch (final RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (final Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (final Throwable t) {
throw logAndPrepareForRethrow(t);
}
} } | public class class_name {
public void rollback(final OMicroTransaction microTransaction) {
try {
checkOpenness(); // depends on control dependency: [try], data = [none]
stateLock.acquireReadLock(); // depends on control dependency: [try], data = [none]
try {
try {
checkOpenness(); // depends on control dependency: [try], data = [none]
if (transaction.get() == null) {
return; // depends on control dependency: [if], data = [none]
}
if (transaction.get().getMicroTransaction().getId() != microTransaction.getId()) {
throw new OStorageException(
"Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be "
+ "rolled back.");
}
makeStorageDirty(); // depends on control dependency: [try], data = [none]
rollbackStorageTx(); // depends on control dependency: [try], data = [none]
microTransaction.updateRecordCacheAfterRollback(); // depends on control dependency: [try], data = [none]
txRollback.incrementAndGet(); // depends on control dependency: [try], data = [none]
} catch (final IOException e) {
throw OException.wrapException(new OStorageException("Error during micro-transaction rollback"), e);
} finally { // depends on control dependency: [catch], data = [none]
transaction.set(null);
}
} finally {
stateLock.releaseReadLock();
}
} catch (final RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (final Error ee) { // depends on control dependency: [catch], data = [none]
throw logAndPrepareForRethrow(ee);
} catch (final Throwable t) { // depends on control dependency: [catch], data = [none]
throw logAndPrepareForRethrow(t);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void closestPoint(Point3D_F64 P , Point3D_F64 closestPt ) {
// D = B-P
GeometryMath_F64.sub(B, P, D);
a = E0.dot(E0);
b = E0.dot(E1);
c = E1.dot(E1);
d = E0.dot(D);
e = E1.dot(D);
double det = a * c - b * b;
s = b * e - c * d;
t = b * d - a * e;
if (s + t <= det) {
if (s < 0) {
if (t < 0) {
region4();
} else {
region3();
}
} else if (t < 0) {
region5();
} else {
region0(det);
}
} else {
if (s < 0) {
region2();
} else if (t < 0) {
region6();
} else {
region1();
}
}
closestPt.x = B.x + s*E0.x + t*E1.x;
closestPt.y = B.y + s*E0.y + t*E1.y;
closestPt.z = B.z + s*E0.z + t*E1.z;
} } | public class class_name {
public void closestPoint(Point3D_F64 P , Point3D_F64 closestPt ) {
// D = B-P
GeometryMath_F64.sub(B, P, D);
a = E0.dot(E0);
b = E0.dot(E1);
c = E1.dot(E1);
d = E0.dot(D);
e = E1.dot(D);
double det = a * c - b * b;
s = b * e - c * d;
t = b * d - a * e;
if (s + t <= det) {
if (s < 0) {
if (t < 0) {
region4(); // depends on control dependency: [if], data = [none]
} else {
region3(); // depends on control dependency: [if], data = [none]
}
} else if (t < 0) {
region5(); // depends on control dependency: [if], data = [none]
} else {
region0(det); // depends on control dependency: [if], data = [none]
}
} else {
if (s < 0) {
region2(); // depends on control dependency: [if], data = [none]
} else if (t < 0) {
region6(); // depends on control dependency: [if], data = [none]
} else {
region1(); // depends on control dependency: [if], data = [none]
}
}
closestPt.x = B.x + s*E0.x + t*E1.x;
closestPt.y = B.y + s*E0.y + t*E1.y;
closestPt.z = B.z + s*E0.z + t*E1.z;
} } |
public class class_name {
public static double acos(double x) {
if (x != x) {
return Double.NaN;
}
if (x > 1.0 || x < -1.0) {
return Double.NaN;
}
if (x == -1.0) {
return Math.PI;
}
if (x == 1.0) {
return 0.0;
}
if (x == 0) {
return Math.PI/2.0;
}
/* Compute acos(x) = atan(sqrt(1-x*x)/x) */
/* Split x */
double temp = x * HEX_40000000;
final double xa = x + temp - temp;
final double xb = x - xa;
/* Square it */
double ya = xa*xa;
double yb = xa*xb*2.0 + xb*xb;
/* Subtract from 1 */
ya = -ya;
yb = -yb;
double za = 1.0 + ya;
double zb = -(za - 1.0 - ya);
temp = za + yb;
zb += -(temp - za - yb);
za = temp;
/* Square root */
double y = sqrt(za);
temp = y * HEX_40000000;
ya = y + temp - temp;
yb = y - ya;
/* Extend precision of sqrt */
yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
/* Contribution of zb to sqrt */
yb += zb / (2.0*y);
y = ya+yb;
yb = -(y - ya - yb);
// Compute ratio r = y/x
double r = y/x;
// Did r overflow?
if (Double.isInfinite(r)) { // x is effectively zero
return Math.PI/2; // so return the appropriate value
}
double ra = doubleHighPart(r);
double rb = r - ra;
rb += (y - ra*xa - ra*xb - rb*xa - rb*xb) / x; // Correct for rounding in division
rb += yb / x; // Add in effect additional bits of sqrt.
temp = ra + rb;
rb = -(temp - ra - rb);
ra = temp;
return atan(ra, rb, x<0);
} } | public class class_name {
public static double acos(double x) {
if (x != x) {
return Double.NaN; // depends on control dependency: [if], data = [none]
}
if (x > 1.0 || x < -1.0) {
return Double.NaN; // depends on control dependency: [if], data = [none]
}
if (x == -1.0) {
return Math.PI; // depends on control dependency: [if], data = [none]
}
if (x == 1.0) {
return 0.0; // depends on control dependency: [if], data = [none]
}
if (x == 0) {
return Math.PI/2.0; // depends on control dependency: [if], data = [none]
}
/* Compute acos(x) = atan(sqrt(1-x*x)/x) */
/* Split x */
double temp = x * HEX_40000000;
final double xa = x + temp - temp;
final double xb = x - xa;
/* Square it */
double ya = xa*xa;
double yb = xa*xb*2.0 + xb*xb;
/* Subtract from 1 */
ya = -ya;
yb = -yb;
double za = 1.0 + ya;
double zb = -(za - 1.0 - ya);
temp = za + yb;
zb += -(temp - za - yb);
za = temp;
/* Square root */
double y = sqrt(za);
temp = y * HEX_40000000;
ya = y + temp - temp;
yb = y - ya;
/* Extend precision of sqrt */
yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
/* Contribution of zb to sqrt */
yb += zb / (2.0*y);
y = ya+yb;
yb = -(y - ya - yb);
// Compute ratio r = y/x
double r = y/x;
// Did r overflow?
if (Double.isInfinite(r)) { // x is effectively zero
return Math.PI/2; // so return the appropriate value // depends on control dependency: [if], data = [none]
}
double ra = doubleHighPart(r);
double rb = r - ra;
rb += (y - ra*xa - ra*xb - rb*xa - rb*xb) / x; // Correct for rounding in division
rb += yb / x; // Add in effect additional bits of sqrt.
temp = ra + rb;
rb = -(temp - ra - rb);
ra = temp;
return atan(ra, rb, x<0);
} } |
public class class_name {
public void contextInitialized(ServletContextEvent servletContextEvent)
{
ServletContext ctx = servletContextEvent.getServletContext();
ctx.log("******* Mounting up GreenPepper-Server");
try
{
URL url = GPServletContextListener.class.getClassLoader().getResource(GREENPEPPER_CONFIG);
Properties sProperties = ServerConfiguration.load(url).getProperties();
injectAdditionalProperties(ctx, sProperties);
HibernateSessionService service = new HibernateSessionService(sProperties);
ctx.setAttribute(ServletContextKeys.SESSION_SERVICE, service);
ctx.log("Boostrapping datas");
new BootstrapData(service, sProperties).execute();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} } | public class class_name {
public void contextInitialized(ServletContextEvent servletContextEvent)
{
ServletContext ctx = servletContextEvent.getServletContext();
ctx.log("******* Mounting up GreenPepper-Server");
try
{
URL url = GPServletContextListener.class.getClassLoader().getResource(GREENPEPPER_CONFIG);
Properties sProperties = ServerConfiguration.load(url).getProperties();
injectAdditionalProperties(ctx, sProperties); // depends on control dependency: [try], data = [none]
HibernateSessionService service = new HibernateSessionService(sProperties);
ctx.setAttribute(ServletContextKeys.SESSION_SERVICE, service); // depends on control dependency: [try], data = [none]
ctx.log("Boostrapping datas"); // depends on control dependency: [try], data = [none]
new BootstrapData(service, sProperties).execute(); // depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public CreatePipelineResponse createPipeline(CreatePipelineRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getPipelineName(),
"The parameter pipelineName should NOT be null or empty string.");
checkStringNotEmpty(request.getSourceBucket(),
"The parameter sourceBucket should NOT be null or empty string.");
checkStringNotEmpty(request.getTargetBucket(),
"The parameter targetBucket should NOT be null or empty string.");
if (request.getConfig() == null || request.getConfig().getCapacity() == null) {
PipelineConfig config = new PipelineConfig();
config.setCapacity(DEFAULT_PIPELINE_CAPACITY);
request.setConfig(config);
}
InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, PIPELINE);
return invokeHttpClient(internalRequest, CreatePipelineResponse.class);
} } | public class class_name {
public CreatePipelineResponse createPipeline(CreatePipelineRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getPipelineName(),
"The parameter pipelineName should NOT be null or empty string.");
checkStringNotEmpty(request.getSourceBucket(),
"The parameter sourceBucket should NOT be null or empty string.");
checkStringNotEmpty(request.getTargetBucket(),
"The parameter targetBucket should NOT be null or empty string.");
if (request.getConfig() == null || request.getConfig().getCapacity() == null) {
PipelineConfig config = new PipelineConfig();
config.setCapacity(DEFAULT_PIPELINE_CAPACITY); // depends on control dependency: [if], data = [none]
request.setConfig(config); // depends on control dependency: [if], data = [none]
}
InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, PIPELINE);
return invokeHttpClient(internalRequest, CreatePipelineResponse.class);
} } |
public class class_name {
public LocalTime minusSeconds(int seconds) {
if (seconds == 0) {
return this;
}
long instant = getChronology().seconds().subtract(getLocalMillis(), seconds);
return withLocalMillis(instant);
} } | public class class_name {
public LocalTime minusSeconds(int seconds) {
if (seconds == 0) {
return this; // depends on control dependency: [if], data = [none]
}
long instant = getChronology().seconds().subtract(getLocalMillis(), seconds);
return withLocalMillis(instant);
} } |
public class class_name {
protected void findCenter() {
center = new float[]{0, 0};
int length = points.length;
for(int i=0;i<length;i+=2) {
center[0] += points[i];
center[1] += points[i + 1];
}
center[0] /= (length / 2);
center[1] /= (length / 2);
} } | public class class_name {
protected void findCenter() {
center = new float[]{0, 0};
int length = points.length;
for(int i=0;i<length;i+=2) {
center[0] += points[i];
// depends on control dependency: [for], data = [i]
center[1] += points[i + 1];
// depends on control dependency: [for], data = [i]
}
center[0] /= (length / 2);
center[1] /= (length / 2);
} } |
public class class_name {
public static ZParams.Aggregate getAggregate(ZParams params) {
Collection<byte[]> collect = params.getParams();
Iterator<byte[]> iterator = collect.iterator();
String key = new String(iterator.next());
if (!"aggregate".equals(key)) {
return ZParams.Aggregate.SUM;
}
String type = new String(iterator.next());
return ZParams.Aggregate.valueOf(type);
} } | public class class_name {
public static ZParams.Aggregate getAggregate(ZParams params) {
Collection<byte[]> collect = params.getParams();
Iterator<byte[]> iterator = collect.iterator();
String key = new String(iterator.next());
if (!"aggregate".equals(key)) {
return ZParams.Aggregate.SUM;
// depends on control dependency: [if], data = [none]
}
String type = new String(iterator.next());
return ZParams.Aggregate.valueOf(type);
} } |
public class class_name {
public void emptyManagedConnectionPool(ManagedConnectionPool mcp)
{
if (pools.values().remove(mcp))
{
mcp.shutdown();
if (Tracer.isEnabled())
Tracer.destroyManagedConnectionPool(poolConfiguration.getId(), mcp);
}
} } | public class class_name {
public void emptyManagedConnectionPool(ManagedConnectionPool mcp)
{
if (pools.values().remove(mcp))
{
mcp.shutdown(); // depends on control dependency: [if], data = [none]
if (Tracer.isEnabled())
Tracer.destroyManagedConnectionPool(poolConfiguration.getId(), mcp);
}
} } |
public class class_name {
public static LocalDate minDate(final LocalDate date0,
final LocalDate date1) {
if (date1 == null) {
return date0;
}
if (date0 == null) {
return date1;
}
if (date1.isBefore(date0)) {
return date1;
} else {
return date0;
}
} } | public class class_name {
public static LocalDate minDate(final LocalDate date0,
final LocalDate date1) {
if (date1 == null) {
return date0; // depends on control dependency: [if], data = [none]
}
if (date0 == null) {
return date1; // depends on control dependency: [if], data = [none]
}
if (date1.isBefore(date0)) {
return date1; // depends on control dependency: [if], data = [none]
} else {
return date0; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Nonnull
static String headerLetter(final int i) {
final int flags = DATA_MODEL.getDataFlags(i);
// TODO: The "magic" of how to interpret flags must be in DataModel, not here.
if (((flags >> 7) & 3) == 1) {
return Character.toString(ENCODE_CHARS[(flags >> 11) & 31]);
}
return "";
} } | public class class_name {
@Nonnull
static String headerLetter(final int i) {
final int flags = DATA_MODEL.getDataFlags(i);
// TODO: The "magic" of how to interpret flags must be in DataModel, not here.
if (((flags >> 7) & 3) == 1) {
return Character.toString(ENCODE_CHARS[(flags >> 11) & 31]); // depends on control dependency: [if], data = [1)]
}
return "";
} } |
public class class_name {
@Override
public TaskBase getTask(ProcessDefinition pd, long taskId) {
for (TaskBase task: pd.getTasks()) {
if (task.getTaskId() == taskId) {
return task;
}
}
return null;
} } | public class class_name {
@Override
public TaskBase getTask(ProcessDefinition pd, long taskId) {
for (TaskBase task: pd.getTasks()) {
if (task.getTaskId() == taskId) {
return task; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static void main(String[] args){
PDBFileReader pdbr = new PDBFileReader();
pdbr.setPath("/tmp/");
//String pdb1 = "1crl";
//String pdb2 = "1ede";
String pdb1 = "1buz";
String pdb2 = "1ali";
//String pdb1 = "5pti";
//String pdb2 = "5pti";
// NO NEED TO DO CHANGE ANYTHING BELOW HERE...
StructurePairAligner sc = new StructurePairAligner();
StrucAligParameters params = new StrucAligParameters();
params.setMaxIter(1);
sc.setParams(params);
// step1 : read molecules
try {
Structure s1 = pdbr.getStructureById(pdb1);
Structure s2 = pdbr.getStructureById(pdb2);
System.out.println("aligning " + pdb1 + " vs. " + pdb2);
System.out.println(s1);
System.out.println();
System.out.println(s2);
// step 2 : do the calculations
sc.align(s1,s2);
ScaleableMatrixPanel smp = new ScaleableMatrixPanel();
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
JFrame f = (JFrame) e.getSource();
f.setVisible(false);
f.dispose();
}
});
smp.setMatrix(sc.getDistMat());
smp.setFragmentPairs(sc.getFragmentPairs());
smp.setAlternativeAligs(sc.getAlignments());
for (int i = 0; i < sc.getAlignments().length; i++) {
AlternativeAlignment aa =sc.getAlignments()[i];
System.out.println(aa);
}
frame.getContentPane().add(smp);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
} } | public class class_name {
public static void main(String[] args){
PDBFileReader pdbr = new PDBFileReader();
pdbr.setPath("/tmp/");
//String pdb1 = "1crl";
//String pdb2 = "1ede";
String pdb1 = "1buz";
String pdb2 = "1ali";
//String pdb1 = "5pti";
//String pdb2 = "5pti";
// NO NEED TO DO CHANGE ANYTHING BELOW HERE...
StructurePairAligner sc = new StructurePairAligner();
StrucAligParameters params = new StrucAligParameters();
params.setMaxIter(1);
sc.setParams(params);
// step1 : read molecules
try {
Structure s1 = pdbr.getStructureById(pdb1);
Structure s2 = pdbr.getStructureById(pdb2);
System.out.println("aligning " + pdb1 + " vs. " + pdb2); // depends on control dependency: [try], data = [none]
System.out.println(s1); // depends on control dependency: [try], data = [none]
System.out.println(); // depends on control dependency: [try], data = [none]
System.out.println(s2); // depends on control dependency: [try], data = [none]
// step 2 : do the calculations
sc.align(s1,s2); // depends on control dependency: [try], data = [none]
ScaleableMatrixPanel smp = new ScaleableMatrixPanel();
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
JFrame f = (JFrame) e.getSource();
f.setVisible(false);
f.dispose();
}
}); // depends on control dependency: [try], data = [none]
smp.setMatrix(sc.getDistMat()); // depends on control dependency: [try], data = [none]
smp.setFragmentPairs(sc.getFragmentPairs()); // depends on control dependency: [try], data = [none]
smp.setAlternativeAligs(sc.getAlignments()); // depends on control dependency: [try], data = [none]
for (int i = 0; i < sc.getAlignments().length; i++) {
AlternativeAlignment aa =sc.getAlignments()[i];
System.out.println(aa); // depends on control dependency: [for], data = [none]
}
frame.getContentPane().add(smp); // depends on control dependency: [try], data = [none]
frame.pack(); // depends on control dependency: [try], data = [none]
frame.setVisible(true); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static byte[] concat(Bytes... listOfBytes) {
int offset = 0;
int size = 0;
for (Bytes b : listOfBytes) {
size += b.length() + checkVlen(b.length());
}
byte[] data = new byte[size];
for (Bytes b : listOfBytes) {
offset = writeVint(data, offset, b.length());
b.copyTo(0, b.length(), data, offset);
offset += b.length();
}
return data;
} } | public class class_name {
public static byte[] concat(Bytes... listOfBytes) {
int offset = 0;
int size = 0;
for (Bytes b : listOfBytes) {
size += b.length() + checkVlen(b.length()); // depends on control dependency: [for], data = [b]
}
byte[] data = new byte[size];
for (Bytes b : listOfBytes) {
offset = writeVint(data, offset, b.length()); // depends on control dependency: [for], data = [b]
b.copyTo(0, b.length(), data, offset); // depends on control dependency: [for], data = [b]
offset += b.length(); // depends on control dependency: [for], data = [b]
}
return data;
} } |
public class class_name {
private int max(Map<Integer, ModifiableDBIDs> candidates) {
int maxDim = -1, size = -1;
for(Integer nextDim : candidates.keySet()) {
int nextSet = candidates.get(nextDim).size();
if(size < nextSet) {
size = nextSet;
maxDim = nextDim;
}
}
return maxDim;
} } | public class class_name {
private int max(Map<Integer, ModifiableDBIDs> candidates) {
int maxDim = -1, size = -1;
for(Integer nextDim : candidates.keySet()) {
int nextSet = candidates.get(nextDim).size();
if(size < nextSet) {
size = nextSet; // depends on control dependency: [if], data = [none]
maxDim = nextDim; // depends on control dependency: [if], data = [none]
}
}
return maxDim;
} } |
public class class_name {
public OutlierResult run(Relation<O> relation) {
final DistanceQuery<O> distanceQuery = relation.getDistanceQuery(getDistanceFunction());
final KNNQuery<O> knnQuery = relation.getKNNQuery(distanceQuery, k);
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("kNN distance for objects", relation.size(), LOG) : null;
WritableDoubleDataStore knnDist = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
WritableDBIDDataStore neighbor = DataStoreUtil.makeDBIDStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
DBIDVar var = DBIDUtil.newVar();
// Find nearest neighbors, and store the distances.
for(DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) {
final KNNList knn = knnQuery.getKNNForDBID(it, k);
knnDist.putDouble(it, knn.getKNNDistance());
neighbor.put(it, knn.assignVar(knn.size() - 1, var));
LOG.incrementProcessed(prog);
}
LOG.ensureCompleted(prog);
prog = LOG.isVerbose() ? new FiniteProgress("kNN distance descriptor", relation.size(), LOG) : null;
WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_DB);
DoubleMinMax minmax = new DoubleMinMax();
for(DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) {
// Distance
double d = knnDist.doubleValue(it);
// Distance of neighbor
double nd = knnDist.doubleValue(neighbor.assignVar(it, var));
double knndd = nd > 0 ? d / nd : d > 0 ? Double.POSITIVE_INFINITY : 1.;
scores.put(it, knndd);
minmax.put(knndd);
LOG.incrementProcessed(prog);
}
LOG.ensureCompleted(prog);
DoubleRelation scoreres = new MaterializedDoubleRelation("kNN Data Descriptor", "knndd-outlier", scores, relation.getDBIDs());
OutlierScoreMeta meta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0., Double.POSITIVE_INFINITY, 1.);
return new OutlierResult(meta, scoreres);
} } | public class class_name {
public OutlierResult run(Relation<O> relation) {
final DistanceQuery<O> distanceQuery = relation.getDistanceQuery(getDistanceFunction());
final KNNQuery<O> knnQuery = relation.getKNNQuery(distanceQuery, k);
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("kNN distance for objects", relation.size(), LOG) : null;
WritableDoubleDataStore knnDist = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
WritableDBIDDataStore neighbor = DataStoreUtil.makeDBIDStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP);
DBIDVar var = DBIDUtil.newVar();
// Find nearest neighbors, and store the distances.
for(DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) {
final KNNList knn = knnQuery.getKNNForDBID(it, k);
knnDist.putDouble(it, knn.getKNNDistance()); // depends on control dependency: [for], data = [it]
neighbor.put(it, knn.assignVar(knn.size() - 1, var)); // depends on control dependency: [for], data = [it]
LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none]
}
LOG.ensureCompleted(prog);
prog = LOG.isVerbose() ? new FiniteProgress("kNN distance descriptor", relation.size(), LOG) : null;
WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_DB);
DoubleMinMax minmax = new DoubleMinMax();
for(DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) {
// Distance
double d = knnDist.doubleValue(it);
// Distance of neighbor
double nd = knnDist.doubleValue(neighbor.assignVar(it, var));
double knndd = nd > 0 ? d / nd : d > 0 ? Double.POSITIVE_INFINITY : 1.;
scores.put(it, knndd); // depends on control dependency: [for], data = [it]
minmax.put(knndd); // depends on control dependency: [for], data = [none]
LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none]
}
LOG.ensureCompleted(prog);
DoubleRelation scoreres = new MaterializedDoubleRelation("kNN Data Descriptor", "knndd-outlier", scores, relation.getDBIDs());
OutlierScoreMeta meta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0., Double.POSITIVE_INFINITY, 1.);
return new OutlierResult(meta, scoreres);
} } |
public class class_name {
@Override
public void debug(Object object) {
if (isDebugEnabled()) {
if (object instanceof Throwable) {
debugThrowable((Throwable) object);
} else {
debugString("" + object);
}
}
} } | public class class_name {
@Override
public void debug(Object object) {
if (isDebugEnabled()) {
if (object instanceof Throwable) {
debugThrowable((Throwable) object); // depends on control dependency: [if], data = [none]
} else {
debugString("" + object); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public boolean offer(T t) {
if (t == null) {
onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
return true;
}
PublishSubscription<T>[] array = subscribers.get();
for (PublishSubscription<T> s : array) {
if (s.isFull()) {
return false;
}
}
for (PublishSubscription<T> s : array) {
s.onNext(t);
}
return true;
} } | public class class_name {
public boolean offer(T t) {
if (t == null) {
onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.")); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
PublishSubscription<T>[] array = subscribers.get();
for (PublishSubscription<T> s : array) {
if (s.isFull()) {
return false; // depends on control dependency: [if], data = [none]
}
}
for (PublishSubscription<T> s : array) {
s.onNext(t); // depends on control dependency: [for], data = [s]
}
return true;
} } |
public class class_name {
private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
String remote = ctx.channel().remoteAddress().toString();
String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
if (supportedMechanisms.length == 0) {
throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
}
if (forceSaslPlain) {
LOGGER.trace("Got SASL Mechs {} but forcing PLAIN due to config setting.", Arrays.asList(supportedMechanisms));
supportedMechanisms = new String[] { "PLAIN" };
}
saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
selectedMechanism = saslClient.getMechanismName();
int mechanismLength = selectedMechanism.length();
byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[]{}) : null;
ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER;
FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(
selectedMechanism.getBytes(CharsetUtil.UTF_8),
Unpooled.EMPTY_BUFFER,
payload
);
initialRequest
.setOpcode(SASL_AUTH_OPCODE)
.setKeyLength((short) mechanismLength)
.setTotalBodyLength(mechanismLength + payload.readableBytes());
ChannelFuture future = ctx.writeAndFlush(initialRequest);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
}
}
});
} } | public class class_name {
private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
String remote = ctx.channel().remoteAddress().toString();
String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
if (supportedMechanisms.length == 0) {
throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
}
if (forceSaslPlain) {
LOGGER.trace("Got SASL Mechs {} but forcing PLAIN due to config setting.", Arrays.asList(supportedMechanisms));
supportedMechanisms = new String[] { "PLAIN" };
}
saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
selectedMechanism = saslClient.getMechanismName();
int mechanismLength = selectedMechanism.length();
byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[]{}) : null;
ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER;
FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(
selectedMechanism.getBytes(CharsetUtil.UTF_8),
Unpooled.EMPTY_BUFFER,
payload
);
initialRequest
.setOpcode(SASL_AUTH_OPCODE)
.setKeyLength((short) mechanismLength)
.setTotalBodyLength(mechanismLength + payload.readableBytes());
ChannelFuture future = ctx.writeAndFlush(initialRequest);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future); // depends on control dependency: [if], data = [none]
}
}
});
} } |
public class class_name {
public static boolean showedToast(CharSequence message) {
ShadowApplication shadowApplication = Shadow.extract(RuntimeEnvironment.application);
for (Toast toast : shadowApplication.getShownToasts()) {
ShadowToast shadowToast = Shadow.extract(toast);
String text = shadowToast.text;
if (text != null && text.equals(message.toString())) {
return true;
}
}
return false;
} } | public class class_name {
public static boolean showedToast(CharSequence message) {
ShadowApplication shadowApplication = Shadow.extract(RuntimeEnvironment.application);
for (Toast toast : shadowApplication.getShownToasts()) {
ShadowToast shadowToast = Shadow.extract(toast);
String text = shadowToast.text;
if (text != null && text.equals(message.toString())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Override
public void persistJoinTable(JoinTableData joinTableData)
{
String tableName = joinTableData.getJoinTableName();
String inverseJoinColumn = joinTableData.getInverseJoinColumnName();
String joinColumn = joinTableData.getJoinColumnName();
Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
Object connection = null;
Pipeline pipeline = null;
/**
* Example: join table : PERSON_ADDRESS join column : PERSON_ID (1_p)
* inverse join column : ADDRESS_ID (1_a) store in REDIS:
* PERSON_ADDRESS:1_p_1_a PERSON_ID 1_p ADDRESS_ID 1_a
*/
// String rowKey =
try
{
connection = getConnection();
if (isBoundTransaction())
{
pipeline = ((Jedis) connection).pipelined();
}
Set<Object> joinKeys = joinTableRecords.keySet();
for (Object joinKey : joinKeys)
{
String joinKeyAsStr = PropertyAccessorHelper.getString(joinKey);
Set<Object> inverseKeys = joinTableRecords.get(joinKey);
for (Object inverseKey : inverseKeys)
{
Map<byte[], byte[]> redisFields = new HashMap<byte[], byte[]>(1);
String inverseJoinKeyAsStr = PropertyAccessorHelper.getString(inverseKey);
String redisKey = getHashKey(tableName, joinKeyAsStr + "_" + inverseJoinKeyAsStr);
redisFields.put(getEncodedBytes(joinColumn), getEncodedBytes(joinKeyAsStr)); // put
// join
// column
// field.
redisFields.put(getEncodedBytes(inverseJoinColumn), getEncodedBytes(inverseJoinKeyAsStr)); // put
// inverse
// join
// column
// field
// add to hash table.
if (resource != null && resource.isActive())
{
((Transaction) connection).hmset(getEncodedBytes(redisKey), redisFields);
// add index
((Transaction) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),
getDouble(inverseJoinKeyAsStr), redisKey);
((Transaction) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),
redisKey);
}
else
{
((Jedis) connection).hmset(getEncodedBytes(redisKey), redisFields);
// add index
((Jedis) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),
getDouble(inverseJoinKeyAsStr), redisKey);
((Jedis) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),
redisKey);
}
redisFields.clear();
}
}
KunderaCoreUtils.printQuery("Persist Join Table:" + tableName, showQuery);
}
finally
{
if (pipeline != null)
{
pipeline.sync();
}
onCleanup(connection);
}
} } | public class class_name {
@Override
public void persistJoinTable(JoinTableData joinTableData)
{
String tableName = joinTableData.getJoinTableName();
String inverseJoinColumn = joinTableData.getInverseJoinColumnName();
String joinColumn = joinTableData.getJoinColumnName();
Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
Object connection = null;
Pipeline pipeline = null;
/**
* Example: join table : PERSON_ADDRESS join column : PERSON_ID (1_p)
* inverse join column : ADDRESS_ID (1_a) store in REDIS:
* PERSON_ADDRESS:1_p_1_a PERSON_ID 1_p ADDRESS_ID 1_a
*/
// String rowKey =
try
{
connection = getConnection(); // depends on control dependency: [try], data = [none]
if (isBoundTransaction())
{
pipeline = ((Jedis) connection).pipelined(); // depends on control dependency: [if], data = [none]
}
Set<Object> joinKeys = joinTableRecords.keySet();
for (Object joinKey : joinKeys)
{
String joinKeyAsStr = PropertyAccessorHelper.getString(joinKey);
Set<Object> inverseKeys = joinTableRecords.get(joinKey);
for (Object inverseKey : inverseKeys)
{
Map<byte[], byte[]> redisFields = new HashMap<byte[], byte[]>(1);
String inverseJoinKeyAsStr = PropertyAccessorHelper.getString(inverseKey);
String redisKey = getHashKey(tableName, joinKeyAsStr + "_" + inverseJoinKeyAsStr);
redisFields.put(getEncodedBytes(joinColumn), getEncodedBytes(joinKeyAsStr)); // put // depends on control dependency: [for], data = [none]
// join
// column
// field.
redisFields.put(getEncodedBytes(inverseJoinColumn), getEncodedBytes(inverseJoinKeyAsStr)); // put // depends on control dependency: [for], data = [none]
// inverse
// join
// column
// field
// add to hash table.
if (resource != null && resource.isActive())
{
((Transaction) connection).hmset(getEncodedBytes(redisKey), redisFields); // depends on control dependency: [if], data = [none]
// add index
((Transaction) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),
getDouble(inverseJoinKeyAsStr), redisKey); // depends on control dependency: [if], data = [none]
((Transaction) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),
redisKey); // depends on control dependency: [if], data = [none]
}
else
{
((Jedis) connection).hmset(getEncodedBytes(redisKey), redisFields); // depends on control dependency: [if], data = [none]
// add index
((Jedis) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),
getDouble(inverseJoinKeyAsStr), redisKey); // depends on control dependency: [if], data = [none]
((Jedis) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),
redisKey); // depends on control dependency: [if], data = [none]
}
redisFields.clear(); // depends on control dependency: [for], data = [none]
}
}
KunderaCoreUtils.printQuery("Persist Join Table:" + tableName, showQuery); // depends on control dependency: [try], data = [none]
}
finally
{
if (pipeline != null)
{
pipeline.sync(); // depends on control dependency: [if], data = [none]
}
onCleanup(connection);
}
} } |
public class class_name {
public static boolean allNotNull(final Object... values) {
if (values == null) {
return false;
}
for (final Object val : values) {
if (val == null) {
return false;
}
}
return true;
} } | public class class_name {
public static boolean allNotNull(final Object... values) {
if (values == null) {
return false; // depends on control dependency: [if], data = [none]
}
for (final Object val : values) {
if (val == null) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public void startElement(String uri, String name, String qName, Attributes atts)
{
boolean isDebug = logger.isDebugEnabled();
try
{
switch (getLiteralId(qName))
{
case JDBC_CONNECTION_DESCRIPTOR:
{
if (isDebug) logger.debug(" > " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
JdbcConnectionDescriptor newJcd = new JdbcConnectionDescriptor();
currentAttributeContainer = newJcd;
conDesList.add(newJcd);
m_CurrentJCD = newJcd;
// set the jcdAlias attribute
String jcdAlias = atts.getValue(tags.getTagById(JCD_ALIAS));
if (isDebug) logger.debug(" " + tags.getTagById(JCD_ALIAS) + ": " + jcdAlias);
m_CurrentJCD.setJcdAlias(jcdAlias);
// set the jcdAlias attribute
String defaultConnection = atts.getValue(tags.getTagById(DEFAULT_CONNECTION));
if (isDebug) logger.debug(" " + tags.getTagById(DEFAULT_CONNECTION) + ": " + defaultConnection);
m_CurrentJCD.setDefaultConnection(Boolean.valueOf(defaultConnection).booleanValue());
if (m_CurrentJCD.isDefaultConnection())
{
if (defaultConnectionFound)
{
throw new MetadataException("Found two jdbc-connection-descriptor elements with default-connection=\"true\"");
}
else
{
defaultConnectionFound = true;
}
}
// set platform attribute
String platform = atts.getValue(tags.getTagById(DBMS_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(DBMS_NAME) + ": " + platform);
m_CurrentJCD.setDbms(platform);
// set jdbc-level attribute
String level = atts.getValue(tags.getTagById(JDBC_LEVEL));
if (isDebug) logger.debug(" " + tags.getTagById(JDBC_LEVEL) + ": " + level);
m_CurrentJCD.setJdbcLevel(level);
// set driver attribute
String driver = atts.getValue(tags.getTagById(DRIVER_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(DRIVER_NAME) + ": " + driver);
m_CurrentJCD.setDriver(driver);
// set protocol attribute
String protocol = atts.getValue(tags.getTagById(URL_PROTOCOL));
if (isDebug) logger.debug(" " + tags.getTagById(URL_PROTOCOL) + ": " + protocol);
m_CurrentJCD.setProtocol(protocol);
// set subprotocol attribute
String subprotocol = atts.getValue(tags.getTagById(URL_SUBPROTOCOL));
if (isDebug) logger.debug(" " + tags.getTagById(URL_SUBPROTOCOL) + ": " + subprotocol);
m_CurrentJCD.setSubProtocol(subprotocol);
// set the dbalias attribute
String dbalias = atts.getValue(tags.getTagById(URL_DBALIAS));
if (isDebug) logger.debug(" " + tags.getTagById(URL_DBALIAS) + ": " + dbalias);
m_CurrentJCD.setDbAlias(dbalias);
// set the datasource attribute
String datasource = atts.getValue(tags.getTagById(DATASOURCE_NAME));
// check for empty String
if(datasource != null && datasource.trim().equals("")) datasource = null;
if (isDebug) logger.debug(" " + tags.getTagById(DATASOURCE_NAME) + ": " + datasource);
m_CurrentJCD.setDatasourceName(datasource);
// set the user attribute
String user = atts.getValue(tags.getTagById(USER_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(USER_NAME) + ": " + user);
m_CurrentJCD.setUserName(user);
// set the password attribute
String password = atts.getValue(tags.getTagById(USER_PASSWD));
if (isDebug) logger.debug(" " + tags.getTagById(USER_PASSWD) + ": " + password);
m_CurrentJCD.setPassWord(password);
// set eager-release attribute
String eagerRelease = atts.getValue(tags.getTagById(EAGER_RELEASE));
if (isDebug) logger.debug(" " + tags.getTagById(EAGER_RELEASE) + ": " + eagerRelease);
m_CurrentJCD.setEagerRelease(Boolean.valueOf(eagerRelease).booleanValue());
// set batch-mode attribute
String batchMode = atts.getValue(tags.getTagById(BATCH_MODE));
if (isDebug) logger.debug(" " + tags.getTagById(BATCH_MODE) + ": " + batchMode);
m_CurrentJCD.setBatchMode(Boolean.valueOf(batchMode).booleanValue());
// set useAutoCommit attribute
String useAutoCommit = atts.getValue(tags.getTagById(USE_AUTOCOMMIT));
if (isDebug) logger.debug(" " + tags.getTagById(USE_AUTOCOMMIT) + ": " + useAutoCommit);
m_CurrentJCD.setUseAutoCommit(Integer.valueOf(useAutoCommit).intValue());
// set ignoreAutoCommitExceptions attribute
String ignoreAutoCommitExceptions = atts.getValue(tags.getTagById(IGNORE_AUTOCOMMIT_EXCEPTION));
if (isDebug) logger.debug(" " + tags.getTagById(IGNORE_AUTOCOMMIT_EXCEPTION) + ": " + ignoreAutoCommitExceptions);
m_CurrentJCD.setIgnoreAutoCommitExceptions(Boolean.valueOf(ignoreAutoCommitExceptions).booleanValue());
break;
}
case CONNECTION_POOL:
{
if (m_CurrentJCD != null)
{
if (isDebug) logger.debug(" > " + tags.getTagById(CONNECTION_POOL));
final ConnectionPoolDescriptor m_CurrentCPD = m_CurrentJCD.getConnectionPoolDescriptor();
this.currentAttributeContainer = m_CurrentCPD;
String maxActive = atts.getValue(tags.getTagById(CON_MAX_ACTIVE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_ACTIVE) + ": " + maxActive);
if (checkString(maxActive)) m_CurrentCPD.setMaxActive(Integer.parseInt(maxActive));
String maxIdle = atts.getValue(tags.getTagById(CON_MAX_IDLE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_IDLE) + ": " + maxIdle);
if (checkString(maxIdle)) m_CurrentCPD.setMaxIdle(Integer.parseInt(maxIdle));
String maxWait = atts.getValue(tags.getTagById(CON_MAX_WAIT));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_WAIT) + ": " + maxWait);
if (checkString(maxWait)) m_CurrentCPD.setMaxWait(Integer.parseInt(maxWait));
String minEvictableIdleTimeMillis = atts.getValue(tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS) + ": " + minEvictableIdleTimeMillis);
if (checkString(minEvictableIdleTimeMillis)) m_CurrentCPD.setMinEvictableIdleTimeMillis(Long.parseLong(minEvictableIdleTimeMillis));
String numTestsPerEvictionRun = atts.getValue(tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN));
if (isDebug) logger.debug(" " + tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN) + ": " + numTestsPerEvictionRun);
if (checkString(numTestsPerEvictionRun)) m_CurrentCPD.setNumTestsPerEvictionRun(Integer.parseInt(numTestsPerEvictionRun));
String testOnBorrow = atts.getValue(tags.getTagById(CON_TEST_ON_BORROW));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_ON_BORROW) + ": " + testOnBorrow);
if (checkString(testOnBorrow)) m_CurrentCPD.setTestOnBorrow(Boolean.valueOf(testOnBorrow).booleanValue());
String testOnReturn = atts.getValue(tags.getTagById(CON_TEST_ON_RETURN));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_ON_RETURN) + ": " + testOnReturn);
if (checkString(testOnReturn)) m_CurrentCPD.setTestOnReturn(Boolean.valueOf(testOnReturn).booleanValue());
String testWhileIdle = atts.getValue(tags.getTagById(CON_TEST_WHILE_IDLE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_WHILE_IDLE) + ": " + testWhileIdle);
if (checkString(testWhileIdle)) m_CurrentCPD.setTestWhileIdle(Boolean.valueOf(testWhileIdle).booleanValue());
String timeBetweenEvictionRunsMillis = atts.getValue(tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS) + ": " + timeBetweenEvictionRunsMillis);
if (checkString(timeBetweenEvictionRunsMillis)) m_CurrentCPD.setTimeBetweenEvictionRunsMillis(Long.parseLong(timeBetweenEvictionRunsMillis));
String whenExhaustedAction = atts.getValue(tags.getTagById(CON_WHEN_EXHAUSTED_ACTION));
if (isDebug) logger.debug(" " + tags.getTagById(CON_WHEN_EXHAUSTED_ACTION) + ": " + whenExhaustedAction);
if (checkString(whenExhaustedAction)) m_CurrentCPD.setWhenExhaustedAction(Byte.parseByte(whenExhaustedAction));
String connectionFactoryStr = atts.getValue(tags.getTagById(CONNECTION_FACTORY));
if (isDebug) logger.debug(" " + tags.getTagById(CONNECTION_FACTORY) + ": " + connectionFactoryStr);
if (checkString(connectionFactoryStr)) m_CurrentCPD.setConnectionFactory(ClassHelper.getClass(connectionFactoryStr));
String validationQuery = atts.getValue(tags.getTagById(VALIDATION_QUERY));
if (isDebug) logger.debug(" " + tags.getTagById(VALIDATION_QUERY) + ": " + validationQuery);
if (checkString(validationQuery)) m_CurrentCPD.setValidationQuery(validationQuery);
// abandoned connection properties
String logAbandoned = atts.getValue(tags.getTagById(CON_LOG_ABANDONED));
if (isDebug) logger.debug(" " + tags.getTagById(CON_LOG_ABANDONED) + ": " + logAbandoned);
if (checkString(logAbandoned)) m_CurrentCPD.setLogAbandoned(Boolean.valueOf(logAbandoned).booleanValue());
String removeAbandoned = atts.getValue(tags.getTagById(CON_REMOVE_ABANDONED));
if (isDebug) logger.debug(" " + tags.getTagById(CON_REMOVE_ABANDONED) + ": " + removeAbandoned);
if (checkString(removeAbandoned)) m_CurrentCPD.setRemoveAbandoned(Boolean.valueOf(removeAbandoned).booleanValue());
String removeAbandonedTimeout = atts.getValue(tags.getTagById(CON_REMOVE_ABANDONED_TIMEOUT));
if (isDebug) logger.debug(" " + tags.getTagById(CON_REMOVE_ABANDONED_TIMEOUT) + ": " + removeAbandonedTimeout);
if (checkString(removeAbandonedTimeout)) m_CurrentCPD.setRemoveAbandonedTimeout(Integer.parseInt(removeAbandonedTimeout));
}
break;
}
case OBJECT_CACHE:
{
String className = atts.getValue(tags.getTagById(CLASS_NAME));
if(checkString(className) && m_CurrentJCD != null)
{
ObjectCacheDescriptor ocd = m_CurrentJCD.getObjectCacheDescriptor();
this.currentAttributeContainer = ocd;
ocd.setObjectCache(ClassHelper.getClass(className));
if (isDebug) logger.debug(" > " + tags.getTagById(OBJECT_CACHE));
if (isDebug) logger.debug(" " + tags.getTagById(CLASS_NAME) + ": " + className);
}
break;
}
case SEQUENCE_MANAGER:
{
String className = atts.getValue(tags.getTagById(SEQUENCE_MANAGER_CLASS));
if(checkString(className))
{
this.currentSequenceDescriptor = new SequenceDescriptor(this.m_CurrentJCD);
this.currentAttributeContainer = currentSequenceDescriptor;
this.m_CurrentJCD.setSequenceDescriptor(this.currentSequenceDescriptor);
if (isDebug) logger.debug(" > " + tags.getTagById(SEQUENCE_MANAGER));
if (isDebug) logger.debug(" " + tags.getTagById(SEQUENCE_MANAGER_CLASS) + ": " + className);
if (checkString(className)) currentSequenceDescriptor.setSequenceManagerClass(ClassHelper.getClass(className));
}
break;
}
case ATTRIBUTE:
{
//handle custom attributes
String attributeName = atts.getValue(tags.getTagById(ATTRIBUTE_NAME));
String attributeValue = atts.getValue(tags.getTagById(ATTRIBUTE_VALUE));
// If we have a container to store this attribute in, then do so.
if (this.currentAttributeContainer != null)
{
if (checkString(attributeName))
{
if (isDebug) logger.debug(" > " + tags.getTagById(ATTRIBUTE));
if (isDebug) logger.debug(" " + tags.getTagById(ATTRIBUTE_NAME) + ": " + attributeName
+ " "+tags.getTagById(ATTRIBUTE_VALUE) + ": " + attributeValue);
this.currentAttributeContainer.addAttribute(attributeName, attributeValue);
// logger.info("attribute ["+attributeName+"="+attributeValue+"] add to "+currentAttributeContainer.getClass());
}
else
{
logger.info("Found 'null' or 'empty' attribute object for element "+currentAttributeContainer.getClass() +
" attribute-name=" + attributeName + ", attribute-value=" + attributeValue+
" See jdbc-connection-descriptor with jcdAlias '"+m_CurrentJCD.getJcdAlias()+"'");
}
}
// else
// {
// logger.info("Found attribute (name="+attributeName+", value="+attributeValue+
// ") but I could not assign them to a descriptor");
// }
break;
}
default :
{
// noop
}
}
}
catch (Exception ex)
{
logger.error(ex);
throw new PersistenceBrokerException(ex);
}
} } | public class class_name {
public void startElement(String uri, String name, String qName, Attributes atts)
{
boolean isDebug = logger.isDebugEnabled();
try
{
switch (getLiteralId(qName))
{
case JDBC_CONNECTION_DESCRIPTOR:
{
if (isDebug) logger.debug(" > " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
JdbcConnectionDescriptor newJcd = new JdbcConnectionDescriptor();
currentAttributeContainer = newJcd;
conDesList.add(newJcd);
m_CurrentJCD = newJcd;
// set the jcdAlias attribute
String jcdAlias = atts.getValue(tags.getTagById(JCD_ALIAS));
if (isDebug) logger.debug(" " + tags.getTagById(JCD_ALIAS) + ": " + jcdAlias);
m_CurrentJCD.setJcdAlias(jcdAlias);
// set the jcdAlias attribute
String defaultConnection = atts.getValue(tags.getTagById(DEFAULT_CONNECTION));
if (isDebug) logger.debug(" " + tags.getTagById(DEFAULT_CONNECTION) + ": " + defaultConnection);
m_CurrentJCD.setDefaultConnection(Boolean.valueOf(defaultConnection).booleanValue());
if (m_CurrentJCD.isDefaultConnection())
{
if (defaultConnectionFound)
{
throw new MetadataException("Found two jdbc-connection-descriptor elements with default-connection=\"true\"");
}
else
{
defaultConnectionFound = true;
// depends on control dependency: [if], data = [none]
}
}
// set platform attribute
String platform = atts.getValue(tags.getTagById(DBMS_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(DBMS_NAME) + ": " + platform);
m_CurrentJCD.setDbms(platform);
// set jdbc-level attribute
String level = atts.getValue(tags.getTagById(JDBC_LEVEL));
if (isDebug) logger.debug(" " + tags.getTagById(JDBC_LEVEL) + ": " + level);
m_CurrentJCD.setJdbcLevel(level);
// set driver attribute
String driver = atts.getValue(tags.getTagById(DRIVER_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(DRIVER_NAME) + ": " + driver);
m_CurrentJCD.setDriver(driver);
// set protocol attribute
String protocol = atts.getValue(tags.getTagById(URL_PROTOCOL));
if (isDebug) logger.debug(" " + tags.getTagById(URL_PROTOCOL) + ": " + protocol);
m_CurrentJCD.setProtocol(protocol);
// set subprotocol attribute
String subprotocol = atts.getValue(tags.getTagById(URL_SUBPROTOCOL));
if (isDebug) logger.debug(" " + tags.getTagById(URL_SUBPROTOCOL) + ": " + subprotocol);
m_CurrentJCD.setSubProtocol(subprotocol);
// set the dbalias attribute
String dbalias = atts.getValue(tags.getTagById(URL_DBALIAS));
if (isDebug) logger.debug(" " + tags.getTagById(URL_DBALIAS) + ": " + dbalias);
m_CurrentJCD.setDbAlias(dbalias);
// set the datasource attribute
String datasource = atts.getValue(tags.getTagById(DATASOURCE_NAME));
// check for empty String
if(datasource != null && datasource.trim().equals("")) datasource = null;
if (isDebug) logger.debug(" " + tags.getTagById(DATASOURCE_NAME) + ": " + datasource);
m_CurrentJCD.setDatasourceName(datasource);
// set the user attribute
String user = atts.getValue(tags.getTagById(USER_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(USER_NAME) + ": " + user);
m_CurrentJCD.setUserName(user);
// set the password attribute
String password = atts.getValue(tags.getTagById(USER_PASSWD));
if (isDebug) logger.debug(" " + tags.getTagById(USER_PASSWD) + ": " + password);
m_CurrentJCD.setPassWord(password);
// set eager-release attribute
String eagerRelease = atts.getValue(tags.getTagById(EAGER_RELEASE));
if (isDebug) logger.debug(" " + tags.getTagById(EAGER_RELEASE) + ": " + eagerRelease);
m_CurrentJCD.setEagerRelease(Boolean.valueOf(eagerRelease).booleanValue());
// set batch-mode attribute
String batchMode = atts.getValue(tags.getTagById(BATCH_MODE));
if (isDebug) logger.debug(" " + tags.getTagById(BATCH_MODE) + ": " + batchMode);
m_CurrentJCD.setBatchMode(Boolean.valueOf(batchMode).booleanValue());
// set useAutoCommit attribute
String useAutoCommit = atts.getValue(tags.getTagById(USE_AUTOCOMMIT));
if (isDebug) logger.debug(" " + tags.getTagById(USE_AUTOCOMMIT) + ": " + useAutoCommit);
m_CurrentJCD.setUseAutoCommit(Integer.valueOf(useAutoCommit).intValue());
// set ignoreAutoCommitExceptions attribute
String ignoreAutoCommitExceptions = atts.getValue(tags.getTagById(IGNORE_AUTOCOMMIT_EXCEPTION));
if (isDebug) logger.debug(" " + tags.getTagById(IGNORE_AUTOCOMMIT_EXCEPTION) + ": " + ignoreAutoCommitExceptions);
m_CurrentJCD.setIgnoreAutoCommitExceptions(Boolean.valueOf(ignoreAutoCommitExceptions).booleanValue());
break;
}
case CONNECTION_POOL:
{
if (m_CurrentJCD != null)
{
if (isDebug) logger.debug(" > " + tags.getTagById(CONNECTION_POOL));
final ConnectionPoolDescriptor m_CurrentCPD = m_CurrentJCD.getConnectionPoolDescriptor();
this.currentAttributeContainer = m_CurrentCPD;
// depends on control dependency: [if], data = [none]
String maxActive = atts.getValue(tags.getTagById(CON_MAX_ACTIVE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_ACTIVE) + ": " + maxActive);
if (checkString(maxActive)) m_CurrentCPD.setMaxActive(Integer.parseInt(maxActive));
String maxIdle = atts.getValue(tags.getTagById(CON_MAX_IDLE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_IDLE) + ": " + maxIdle);
if (checkString(maxIdle)) m_CurrentCPD.setMaxIdle(Integer.parseInt(maxIdle));
String maxWait = atts.getValue(tags.getTagById(CON_MAX_WAIT));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_WAIT) + ": " + maxWait);
if (checkString(maxWait)) m_CurrentCPD.setMaxWait(Integer.parseInt(maxWait));
String minEvictableIdleTimeMillis = atts.getValue(tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS) + ": " + minEvictableIdleTimeMillis);
if (checkString(minEvictableIdleTimeMillis)) m_CurrentCPD.setMinEvictableIdleTimeMillis(Long.parseLong(minEvictableIdleTimeMillis));
String numTestsPerEvictionRun = atts.getValue(tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN));
if (isDebug) logger.debug(" " + tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN) + ": " + numTestsPerEvictionRun);
if (checkString(numTestsPerEvictionRun)) m_CurrentCPD.setNumTestsPerEvictionRun(Integer.parseInt(numTestsPerEvictionRun));
String testOnBorrow = atts.getValue(tags.getTagById(CON_TEST_ON_BORROW));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_ON_BORROW) + ": " + testOnBorrow);
if (checkString(testOnBorrow)) m_CurrentCPD.setTestOnBorrow(Boolean.valueOf(testOnBorrow).booleanValue());
String testOnReturn = atts.getValue(tags.getTagById(CON_TEST_ON_RETURN));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_ON_RETURN) + ": " + testOnReturn);
if (checkString(testOnReturn)) m_CurrentCPD.setTestOnReturn(Boolean.valueOf(testOnReturn).booleanValue());
String testWhileIdle = atts.getValue(tags.getTagById(CON_TEST_WHILE_IDLE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_WHILE_IDLE) + ": " + testWhileIdle);
if (checkString(testWhileIdle)) m_CurrentCPD.setTestWhileIdle(Boolean.valueOf(testWhileIdle).booleanValue());
String timeBetweenEvictionRunsMillis = atts.getValue(tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS) + ": " + timeBetweenEvictionRunsMillis);
if (checkString(timeBetweenEvictionRunsMillis)) m_CurrentCPD.setTimeBetweenEvictionRunsMillis(Long.parseLong(timeBetweenEvictionRunsMillis));
String whenExhaustedAction = atts.getValue(tags.getTagById(CON_WHEN_EXHAUSTED_ACTION));
if (isDebug) logger.debug(" " + tags.getTagById(CON_WHEN_EXHAUSTED_ACTION) + ": " + whenExhaustedAction);
if (checkString(whenExhaustedAction)) m_CurrentCPD.setWhenExhaustedAction(Byte.parseByte(whenExhaustedAction));
String connectionFactoryStr = atts.getValue(tags.getTagById(CONNECTION_FACTORY));
if (isDebug) logger.debug(" " + tags.getTagById(CONNECTION_FACTORY) + ": " + connectionFactoryStr);
if (checkString(connectionFactoryStr)) m_CurrentCPD.setConnectionFactory(ClassHelper.getClass(connectionFactoryStr));
String validationQuery = atts.getValue(tags.getTagById(VALIDATION_QUERY));
if (isDebug) logger.debug(" " + tags.getTagById(VALIDATION_QUERY) + ": " + validationQuery);
if (checkString(validationQuery)) m_CurrentCPD.setValidationQuery(validationQuery);
// abandoned connection properties
String logAbandoned = atts.getValue(tags.getTagById(CON_LOG_ABANDONED));
if (isDebug) logger.debug(" " + tags.getTagById(CON_LOG_ABANDONED) + ": " + logAbandoned);
if (checkString(logAbandoned)) m_CurrentCPD.setLogAbandoned(Boolean.valueOf(logAbandoned).booleanValue());
String removeAbandoned = atts.getValue(tags.getTagById(CON_REMOVE_ABANDONED));
if (isDebug) logger.debug(" " + tags.getTagById(CON_REMOVE_ABANDONED) + ": " + removeAbandoned);
if (checkString(removeAbandoned)) m_CurrentCPD.setRemoveAbandoned(Boolean.valueOf(removeAbandoned).booleanValue());
String removeAbandonedTimeout = atts.getValue(tags.getTagById(CON_REMOVE_ABANDONED_TIMEOUT));
if (isDebug) logger.debug(" " + tags.getTagById(CON_REMOVE_ABANDONED_TIMEOUT) + ": " + removeAbandonedTimeout);
if (checkString(removeAbandonedTimeout)) m_CurrentCPD.setRemoveAbandonedTimeout(Integer.parseInt(removeAbandonedTimeout));
}
break;
}
case OBJECT_CACHE:
{
String className = atts.getValue(tags.getTagById(CLASS_NAME));
if(checkString(className) && m_CurrentJCD != null)
{
ObjectCacheDescriptor ocd = m_CurrentJCD.getObjectCacheDescriptor();
this.currentAttributeContainer = ocd;
ocd.setObjectCache(ClassHelper.getClass(className));
if (isDebug) logger.debug(" > " + tags.getTagById(OBJECT_CACHE));
if (isDebug) logger.debug(" " + tags.getTagById(CLASS_NAME) + ": " + className);
}
break;
}
case SEQUENCE_MANAGER:
{
String className = atts.getValue(tags.getTagById(SEQUENCE_MANAGER_CLASS));
if(checkString(className))
{
this.currentSequenceDescriptor = new SequenceDescriptor(this.m_CurrentJCD);
this.currentAttributeContainer = currentSequenceDescriptor;
this.m_CurrentJCD.setSequenceDescriptor(this.currentSequenceDescriptor);
if (isDebug) logger.debug(" > " + tags.getTagById(SEQUENCE_MANAGER));
if (isDebug) logger.debug(" " + tags.getTagById(SEQUENCE_MANAGER_CLASS) + ": " + className);
if (checkString(className)) currentSequenceDescriptor.setSequenceManagerClass(ClassHelper.getClass(className));
}
break;
}
case ATTRIBUTE:
{
//handle custom attributes
String attributeName = atts.getValue(tags.getTagById(ATTRIBUTE_NAME));
String attributeValue = atts.getValue(tags.getTagById(ATTRIBUTE_VALUE));
// If we have a container to store this attribute in, then do so.
if (this.currentAttributeContainer != null)
{
if (checkString(attributeName))
{
if (isDebug) logger.debug(" > " + tags.getTagById(ATTRIBUTE));
if (isDebug) logger.debug(" " + tags.getTagById(ATTRIBUTE_NAME) + ": " + attributeName
+ " "+tags.getTagById(ATTRIBUTE_VALUE) + ": " + attributeValue);
this.currentAttributeContainer.addAttribute(attributeName, attributeValue);
// logger.info("attribute ["+attributeName+"="+attributeValue+"] add to "+currentAttributeContainer.getClass());
}
else
{
logger.info("Found 'null' or 'empty' attribute object for element "+currentAttributeContainer.getClass() +
" attribute-name=" + attributeName + ", attribute-value=" + attributeValue+
" See jdbc-connection-descriptor with jcdAlias '"+m_CurrentJCD.getJcdAlias()+"'");
}
}
// else
// {
// logger.info("Found attribute (name="+attributeName+", value="+attributeValue+
// ") but I could not assign them to a descriptor");
// }
break;
}
default :
{
// noop
}
}
}
catch (Exception ex)
{
logger.error(ex);
throw new PersistenceBrokerException(ex);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected Format getMainFormat(CmsObject cms, I_CmsXmlContentLocation location, CmsResource functionRes) {
I_CmsXmlContentValueLocation jspLoc = location.getSubValue("FunctionProvider");
CmsUUID structureId = jspLoc.asId(cms);
I_CmsXmlContentValueLocation containerSettings = location.getSubValue("ContainerSettings");
Map<String, String> parameters = parseParameters(cms, location, "Parameter");
if (containerSettings != null) {
String type = getStringValue(cms, containerSettings.getSubValue("Type"), "");
String minWidth = getStringValue(cms, containerSettings.getSubValue("MinWidth"), "");
String maxWidth = getStringValue(cms, containerSettings.getSubValue("MaxWidth"), "");
Format result = new Format(structureId, type, minWidth, maxWidth, parameters);
return result;
} else {
Format result = new Format(structureId, "", "", "", parameters);
result.setNoContainerSettings(true);
return result;
}
} } | public class class_name {
protected Format getMainFormat(CmsObject cms, I_CmsXmlContentLocation location, CmsResource functionRes) {
I_CmsXmlContentValueLocation jspLoc = location.getSubValue("FunctionProvider");
CmsUUID structureId = jspLoc.asId(cms);
I_CmsXmlContentValueLocation containerSettings = location.getSubValue("ContainerSettings");
Map<String, String> parameters = parseParameters(cms, location, "Parameter");
if (containerSettings != null) {
String type = getStringValue(cms, containerSettings.getSubValue("Type"), "");
String minWidth = getStringValue(cms, containerSettings.getSubValue("MinWidth"), "");
String maxWidth = getStringValue(cms, containerSettings.getSubValue("MaxWidth"), "");
Format result = new Format(structureId, type, minWidth, maxWidth, parameters);
return result;
// depends on control dependency: [if], data = [none]
} else {
Format result = new Format(structureId, "", "", "", parameters);
result.setNoContainerSettings(true);
// depends on control dependency: [if], data = [none]
return result;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static boolean xor(boolean... array) {
if (ArrayUtil.isEmpty(array)) {
throw new IllegalArgumentException("The Array must not be empty");
}
boolean result = false;
for (final boolean element : array) {
result ^= element;
}
return result;
} } | public class class_name {
public static boolean xor(boolean... array) {
if (ArrayUtil.isEmpty(array)) {
throw new IllegalArgumentException("The Array must not be empty");
}
boolean result = false;
for (final boolean element : array) {
result ^= element;
// depends on control dependency: [for], data = [element]
}
return result;
} } |
public class class_name {
@Override
public SparseTensor relabelDimensions(Map<Integer, Integer> relabeling) {
int[] newDimensions = new int[numDimensions()];
int[] dimensionNums = getDimensionNumbers();
for (int i = 0; i < dimensionNums.length; i++) {
Preconditions.checkArgument(relabeling.containsKey(dimensionNums[i]),
"Dimension %s not in relabeling %s", dimensionNums[i], relabeling);
newDimensions[i] = relabeling.get(dimensionNums[i]);
}
return relabelDimensions(newDimensions);
} } | public class class_name {
@Override
public SparseTensor relabelDimensions(Map<Integer, Integer> relabeling) {
int[] newDimensions = new int[numDimensions()];
int[] dimensionNums = getDimensionNumbers();
for (int i = 0; i < dimensionNums.length; i++) {
Preconditions.checkArgument(relabeling.containsKey(dimensionNums[i]),
"Dimension %s not in relabeling %s", dimensionNums[i], relabeling); // depends on control dependency: [for], data = [i]
newDimensions[i] = relabeling.get(dimensionNums[i]); // depends on control dependency: [for], data = [i]
}
return relabelDimensions(newDimensions);
} } |
public class class_name {
private Grid getGridLayout(int count) {
Grid grid = new Grid();
int x, y, z, modolo = 0;
x = count % 3;
y = count % 5;
z = count % 7;
if ((z <= y) && (z <= x)) {
modolo = 7;
} else if ((y <= z) && (y <= x)) {
modolo = 5;
} else if ((x <= z) && (x <= y)) {
modolo = 3;
}
if (count < modolo) {
grid = new Grid(count, 1);
} else if ((count % modolo) == 0) {
grid = new Grid(count / modolo, modolo);
} else {
grid = new Grid((count / modolo) + 1, modolo);
}
return grid;
} } | public class class_name {
private Grid getGridLayout(int count) {
Grid grid = new Grid();
int x, y, z, modolo = 0;
x = count % 3;
y = count % 5;
z = count % 7;
if ((z <= y) && (z <= x)) {
modolo = 7;
// depends on control dependency: [if], data = [none]
} else if ((y <= z) && (y <= x)) {
modolo = 5;
// depends on control dependency: [if], data = [none]
} else if ((x <= z) && (x <= y)) {
modolo = 3;
// depends on control dependency: [if], data = [none]
}
if (count < modolo) {
grid = new Grid(count, 1);
// depends on control dependency: [if], data = [(count]
} else if ((count % modolo) == 0) {
grid = new Grid(count / modolo, modolo);
// depends on control dependency: [if], data = [none]
} else {
grid = new Grid((count / modolo) + 1, modolo);
// depends on control dependency: [if], data = [none]
}
return grid;
} } |
public class class_name {
static void getLuma02UnsafeNoRound(byte[] pic, int picW, int picH, int[] blk, int blkOff, int blkStride, int x,
int y, int blkW, int blkH) {
int maxH = picH - 1;
int maxW = picW - 1;
for (int j = 0; j < blkH; j++) {
int offP0 = clip(y + j - 2, 0, maxH) * picW;
int offP1 = clip(y + j - 1, 0, maxH) * picW;
int offP2 = clip(y + j, 0, maxH) * picW;
int offP3 = clip(y + j + 1, 0, maxH) * picW;
int offP4 = clip(y + j + 2, 0, maxH) * picW;
int offP5 = clip(y + j + 3, 0, maxH) * picW;
for (int i = 0; i < blkW; i++) {
int pres_x = clip(x + i, 0, maxW);
int a = pic[pres_x + offP0] + pic[pres_x + offP5];
int b = pic[pres_x + offP1] + pic[pres_x + offP4];
int c = pic[pres_x + offP2] + pic[pres_x + offP3];
blk[blkOff + i] = a + 5 * ((c << 2) - b);
}
blkOff += blkStride;
}
} } | public class class_name {
static void getLuma02UnsafeNoRound(byte[] pic, int picW, int picH, int[] blk, int blkOff, int blkStride, int x,
int y, int blkW, int blkH) {
int maxH = picH - 1;
int maxW = picW - 1;
for (int j = 0; j < blkH; j++) {
int offP0 = clip(y + j - 2, 0, maxH) * picW;
int offP1 = clip(y + j - 1, 0, maxH) * picW;
int offP2 = clip(y + j, 0, maxH) * picW;
int offP3 = clip(y + j + 1, 0, maxH) * picW;
int offP4 = clip(y + j + 2, 0, maxH) * picW;
int offP5 = clip(y + j + 3, 0, maxH) * picW;
for (int i = 0; i < blkW; i++) {
int pres_x = clip(x + i, 0, maxW);
int a = pic[pres_x + offP0] + pic[pres_x + offP5];
int b = pic[pres_x + offP1] + pic[pres_x + offP4];
int c = pic[pres_x + offP2] + pic[pres_x + offP3];
blk[blkOff + i] = a + 5 * ((c << 2) - b); // depends on control dependency: [for], data = [i]
}
blkOff += blkStride; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public Configuration useDevices(@NonNull int... devices) {
List<Integer> usableDevices = new ArrayList<>();
for (int device : devices) {
if (!availableDevices.contains(device)) {
log.warn("Non-existent device [{}] requested, ignoring...", device);
} else {
if (!usableDevices.contains(device))
usableDevices.add(device);
}
}
if (usableDevices.size() > 0) {
availableDevices.clear();
availableDevices.addAll(usableDevices);
}
return this;
} } | public class class_name {
public Configuration useDevices(@NonNull int... devices) {
List<Integer> usableDevices = new ArrayList<>();
for (int device : devices) {
if (!availableDevices.contains(device)) {
log.warn("Non-existent device [{}] requested, ignoring...", device); // depends on control dependency: [if], data = [none]
} else {
if (!usableDevices.contains(device))
usableDevices.add(device);
}
}
if (usableDevices.size() > 0) {
availableDevices.clear(); // depends on control dependency: [if], data = [none]
availableDevices.addAll(usableDevices); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public void info(Marker marker, String format, Object arg) {
if (!logger.isInfoEnabled(marker))
return;
if (instanceofLAL) {
String formattedMessage = MessageFormatter.format(format, arg).getMessage();
((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
} else {
logger.info(marker, format, arg);
}
} } | public class class_name {
public void info(Marker marker, String format, Object arg) {
if (!logger.isInfoEnabled(marker))
return;
if (instanceofLAL) {
String formattedMessage = MessageFormatter.format(format, arg).getMessage();
((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null); // depends on control dependency: [if], data = [none]
} else {
logger.info(marker, format, arg); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@InternalApi
public Row createRowFromProto(com.google.bigtable.v2.Row row) {
RowBuilder<Row> builder = createRowBuilder();
builder.startRow(row.getKey());
for (Family family : row.getFamiliesList()) {
for (Column column : family.getColumnsList()) {
for (Cell cell : column.getCellsList()) {
builder.startCell(
family.getName(),
column.getQualifier(),
cell.getTimestampMicros(),
cell.getLabelsList(),
cell.getValue().size());
builder.cellValue(cell.getValue());
builder.finishCell();
}
}
}
return builder.finishRow();
} } | public class class_name {
@InternalApi
public Row createRowFromProto(com.google.bigtable.v2.Row row) {
RowBuilder<Row> builder = createRowBuilder();
builder.startRow(row.getKey());
for (Family family : row.getFamiliesList()) {
for (Column column : family.getColumnsList()) {
for (Cell cell : column.getCellsList()) {
builder.startCell(
family.getName(),
column.getQualifier(),
cell.getTimestampMicros(),
cell.getLabelsList(),
cell.getValue().size()); // depends on control dependency: [for], data = [none]
builder.cellValue(cell.getValue()); // depends on control dependency: [for], data = [cell]
builder.finishCell(); // depends on control dependency: [for], data = [none]
}
}
}
return builder.finishRow();
} } |
public class class_name {
@Override
public RecordMaterializer<T> prepareForRead(Configuration configuration,
Map<String, String> keyValueMetaData, MessageType fileSchema,
ReadSupport.ReadContext readContext) {
ThriftMetaData thriftMetaData = ThriftMetaData.fromExtraMetaData(keyValueMetaData);
try {
if (thriftClass == null) {
thriftClass = getThriftClass(keyValueMetaData, configuration);
}
ThriftType.StructType descriptor = null;
if (thriftMetaData != null) {
descriptor = thriftMetaData.getDescriptor();
} else {
ScroogeStructConverter schemaConverter = new ScroogeStructConverter();
descriptor = schemaConverter.convert(thriftClass);
}
ThriftRecordConverter<T> converter = new ScroogeRecordConverter<T>(
thriftClass,
readContext.getRequestedSchema(),
descriptor);
return converter;
} catch (Exception t) {
throw new RuntimeException("Unable to create Thrift Converter for Thrift metadata " + thriftMetaData, t);
}
} } | public class class_name {
@Override
public RecordMaterializer<T> prepareForRead(Configuration configuration,
Map<String, String> keyValueMetaData, MessageType fileSchema,
ReadSupport.ReadContext readContext) {
ThriftMetaData thriftMetaData = ThriftMetaData.fromExtraMetaData(keyValueMetaData);
try {
if (thriftClass == null) {
thriftClass = getThriftClass(keyValueMetaData, configuration); // depends on control dependency: [if], data = [none]
}
ThriftType.StructType descriptor = null;
if (thriftMetaData != null) {
descriptor = thriftMetaData.getDescriptor(); // depends on control dependency: [if], data = [none]
} else {
ScroogeStructConverter schemaConverter = new ScroogeStructConverter();
descriptor = schemaConverter.convert(thriftClass); // depends on control dependency: [if], data = [none]
}
ThriftRecordConverter<T> converter = new ScroogeRecordConverter<T>(
thriftClass,
readContext.getRequestedSchema(),
descriptor);
return converter; // depends on control dependency: [try], data = [none]
} catch (Exception t) {
throw new RuntimeException("Unable to create Thrift Converter for Thrift metadata " + thriftMetaData, t);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public java.util.List<TrafficPolicyInstance> getTrafficPolicyInstances() {
if (trafficPolicyInstances == null) {
trafficPolicyInstances = new com.amazonaws.internal.SdkInternalList<TrafficPolicyInstance>();
}
return trafficPolicyInstances;
} } | public class class_name {
public java.util.List<TrafficPolicyInstance> getTrafficPolicyInstances() {
if (trafficPolicyInstances == null) {
trafficPolicyInstances = new com.amazonaws.internal.SdkInternalList<TrafficPolicyInstance>(); // depends on control dependency: [if], data = [none]
}
return trafficPolicyInstances;
} } |
public class class_name {
void writeInterfaces(final XMLExtendedStreamWriter writer, final ModelNode modelNode) throws XMLStreamException {
writer.writeStartElement(Element.INTERFACES.getLocalName());
final Set<String> interfaces = modelNode.keys();
for (String ifaceName : interfaces) {
final ModelNode iface = modelNode.get(ifaceName);
writer.writeStartElement(Element.INTERFACE.getLocalName());
writeAttribute(writer, Attribute.NAME, ifaceName);
// <any-* /> is just handled at the root
if (iface.get(Element.ANY_ADDRESS.getLocalName()).asBoolean(false)) {
writer.writeEmptyElement(Element.ANY_ADDRESS.getLocalName());
} else {
// Write the other criteria elements
writeInterfaceCriteria(writer, iface, false);
}
writer.writeEndElement();
}
writer.writeEndElement();
} } | public class class_name {
void writeInterfaces(final XMLExtendedStreamWriter writer, final ModelNode modelNode) throws XMLStreamException {
writer.writeStartElement(Element.INTERFACES.getLocalName());
final Set<String> interfaces = modelNode.keys();
for (String ifaceName : interfaces) {
final ModelNode iface = modelNode.get(ifaceName);
writer.writeStartElement(Element.INTERFACE.getLocalName());
writeAttribute(writer, Attribute.NAME, ifaceName);
// <any-* /> is just handled at the root
if (iface.get(Element.ANY_ADDRESS.getLocalName()).asBoolean(false)) {
writer.writeEmptyElement(Element.ANY_ADDRESS.getLocalName()); // depends on control dependency: [if], data = [none]
} else {
// Write the other criteria elements
writeInterfaceCriteria(writer, iface, false); // depends on control dependency: [if], data = [none]
}
writer.writeEndElement();
}
writer.writeEndElement();
} } |
public class class_name {
@Override
public int discriminate(VirtualConnection vc, ConnectionLink currentChannel, String inputChannelName) {
Channel channel = null;
String channelName = null;
String matchString = (inputChannelName + ChannelDataImpl.CHILD_STRING);
int result = FAILURE;
// Iterate the channels of the current list.
for (int i = 0; channelList != null && i < channelList.length; i++) {
channel = channelList[i];
// Find a channel that starts with the name passed in.
// Note: Runtime channels are children channel data objects with names
// like name_CFINTERNAL_CHILD_0
// This is kept hidden from users.
channelName = channel.getName();
if (channelName != null && channelName.startsWith(matchString)) {
// Found the channel. Connect the links.
ConnectionLink link = channel.getConnectionLink(vc);
currentChannel.setApplicationCallback(link);
link.setDeviceLink(currentChannel);
result = SUCCESS;
break;
}
}
return result;
} } | public class class_name {
@Override
public int discriminate(VirtualConnection vc, ConnectionLink currentChannel, String inputChannelName) {
Channel channel = null;
String channelName = null;
String matchString = (inputChannelName + ChannelDataImpl.CHILD_STRING);
int result = FAILURE;
// Iterate the channels of the current list.
for (int i = 0; channelList != null && i < channelList.length; i++) {
channel = channelList[i]; // depends on control dependency: [for], data = [i]
// Find a channel that starts with the name passed in.
// Note: Runtime channels are children channel data objects with names
// like name_CFINTERNAL_CHILD_0
// This is kept hidden from users.
channelName = channel.getName(); // depends on control dependency: [for], data = [none]
if (channelName != null && channelName.startsWith(matchString)) {
// Found the channel. Connect the links.
ConnectionLink link = channel.getConnectionLink(vc);
currentChannel.setApplicationCallback(link); // depends on control dependency: [if], data = [none]
link.setDeviceLink(currentChannel); // depends on control dependency: [if], data = [none]
result = SUCCESS; // depends on control dependency: [if], data = [none]
break;
}
}
return result;
} } |
public class class_name {
public static void copy(InputStream inputStream, final OutputStream outputStream, byte[] buffer, final StreamHandler addtionalHandling) throws IOException {
LOGGER.trace("copy(InputStream, OutputStream, byte[], StreamHandler)");
LOGGER.debug("buffer size: {} bytes", (buffer!=null) ? buffer.length : "null");
process(inputStream, new StreamHandler() {
@Override
public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException {
outputStream.write(buffer, offset, length);
if( addtionalHandling != null ) {
addtionalHandling.handleStreamBuffer(buffer, offset, length);
}
}
}, buffer);
} } | public class class_name {
public static void copy(InputStream inputStream, final OutputStream outputStream, byte[] buffer, final StreamHandler addtionalHandling) throws IOException {
LOGGER.trace("copy(InputStream, OutputStream, byte[], StreamHandler)");
LOGGER.debug("buffer size: {} bytes", (buffer!=null) ? buffer.length : "null");
process(inputStream, new StreamHandler() {
@Override
public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException {
outputStream.write(buffer, offset, length);
if( addtionalHandling != null ) {
addtionalHandling.handleStreamBuffer(buffer, offset, length); // depends on control dependency: [if], data = [none]
}
}
}, buffer);
} } |
public class class_name {
public Status initSlicedFindPath(long startRef, long endRef, float[] startPos, float[] endPos, QueryFilter filter,
int options) {
// Init path state.
m_query = new QueryData();
m_query.status = Status.FAILURE;
m_query.startRef = startRef;
m_query.endRef = endRef;
vCopy(m_query.startPos, startPos);
vCopy(m_query.endPos, endPos);
m_query.filter = filter;
m_query.options = options;
m_query.raycastLimitSqr = Float.MAX_VALUE;
// Validate input
if (!m_nav.isValidPolyRef(startRef) || !m_nav.isValidPolyRef(endRef) || Objects.isNull(startPos)
|| !vIsFinite(startPos) || Objects.isNull(endPos) || !vIsFinite(endPos) || Objects.isNull(filter)) {
return Status.FAILURE_INVALID_PARAM;
}
// trade quality with performance?
if ((options & DT_FINDPATH_ANY_ANGLE) != 0) {
// limiting to several times the character radius yields nice results. It is not sensitive
// so it is enough to compute it from the first tile.
MeshTile tile = m_nav.getTileByRef(startRef);
float agentRadius = tile.data.header.walkableRadius;
m_query.raycastLimitSqr = sqr(agentRadius * NavMesh.DT_RAY_CAST_LIMIT_PROPORTIONS);
}
if (startRef == endRef) {
m_query.status = Status.SUCCSESS;
return Status.SUCCSESS;
}
m_nodePool.clear();
m_openList.clear();
Node startNode = m_nodePool.getNode(startRef);
vCopy(startNode.pos, startPos);
startNode.pidx = 0;
startNode.cost = 0;
startNode.total = vDist(startPos, endPos) * H_SCALE;
startNode.id = startRef;
startNode.flags = Node.DT_NODE_OPEN;
m_openList.push(startNode);
m_query.status = Status.IN_PROGRESS;
m_query.lastBestNode = startNode;
m_query.lastBestNodeCost = startNode.total;
return m_query.status;
} } | public class class_name {
public Status initSlicedFindPath(long startRef, long endRef, float[] startPos, float[] endPos, QueryFilter filter,
int options) {
// Init path state.
m_query = new QueryData();
m_query.status = Status.FAILURE;
m_query.startRef = startRef;
m_query.endRef = endRef;
vCopy(m_query.startPos, startPos);
vCopy(m_query.endPos, endPos);
m_query.filter = filter;
m_query.options = options;
m_query.raycastLimitSqr = Float.MAX_VALUE;
// Validate input
if (!m_nav.isValidPolyRef(startRef) || !m_nav.isValidPolyRef(endRef) || Objects.isNull(startPos)
|| !vIsFinite(startPos) || Objects.isNull(endPos) || !vIsFinite(endPos) || Objects.isNull(filter)) {
return Status.FAILURE_INVALID_PARAM; // depends on control dependency: [if], data = [none]
}
// trade quality with performance?
if ((options & DT_FINDPATH_ANY_ANGLE) != 0) {
// limiting to several times the character radius yields nice results. It is not sensitive
// so it is enough to compute it from the first tile.
MeshTile tile = m_nav.getTileByRef(startRef);
float agentRadius = tile.data.header.walkableRadius;
m_query.raycastLimitSqr = sqr(agentRadius * NavMesh.DT_RAY_CAST_LIMIT_PROPORTIONS); // depends on control dependency: [if], data = [none]
}
if (startRef == endRef) {
m_query.status = Status.SUCCSESS; // depends on control dependency: [if], data = [none]
return Status.SUCCSESS; // depends on control dependency: [if], data = [none]
}
m_nodePool.clear();
m_openList.clear();
Node startNode = m_nodePool.getNode(startRef);
vCopy(startNode.pos, startPos);
startNode.pidx = 0;
startNode.cost = 0;
startNode.total = vDist(startPos, endPos) * H_SCALE;
startNode.id = startRef;
startNode.flags = Node.DT_NODE_OPEN;
m_openList.push(startNode);
m_query.status = Status.IN_PROGRESS;
m_query.lastBestNode = startNode;
m_query.lastBestNodeCost = startNode.total;
return m_query.status;
} } |
public class class_name {
public URL getURL(final String pUrl) {
try {
return new URL(pUrl);
} catch (final MalformedURLException e) {
throw new ConversionException("Cannot parse URL from string " + pUrl, e);
}
} } | public class class_name {
public URL getURL(final String pUrl) {
try {
return new URL(pUrl); // depends on control dependency: [try], data = [none]
} catch (final MalformedURLException e) {
throw new ConversionException("Cannot parse URL from string " + pUrl, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public EnvEntryType<InterceptorType<T>> getOrCreateEnvEntry()
{
List<Node> nodeList = childNode.get("env-entry");
if (nodeList != null && nodeList.size() > 0)
{
return new EnvEntryTypeImpl<InterceptorType<T>>(this, "env-entry", childNode, nodeList.get(0));
}
return createEnvEntry();
} } | public class class_name {
public EnvEntryType<InterceptorType<T>> getOrCreateEnvEntry()
{
List<Node> nodeList = childNode.get("env-entry");
if (nodeList != null && nodeList.size() > 0)
{
return new EnvEntryTypeImpl<InterceptorType<T>>(this, "env-entry", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createEnvEntry();
} } |
public class class_name {
private void grow(final int minCapacity) {
final int oldCapacity = buffer.length;
int newCapacity = oldCapacity << 1;
if (newCapacity - minCapacity < 0) {
// special case, min capacity is larger then a grow
newCapacity = minCapacity + 512;
}
buffer = Arrays.copyOf(buffer, newCapacity);
} } | public class class_name {
private void grow(final int minCapacity) {
final int oldCapacity = buffer.length;
int newCapacity = oldCapacity << 1;
if (newCapacity - minCapacity < 0) {
// special case, min capacity is larger then a grow
newCapacity = minCapacity + 512; // depends on control dependency: [if], data = [none]
}
buffer = Arrays.copyOf(buffer, newCapacity);
} } |
public class class_name {
public long waitForZkTxId(long zkTxId, Object timeout)
throws TimeoutException, InterruptedException
{
long endTime = ClockUtils.toEndTime(clock, timeout);
synchronized(_lock)
{
while(_lastZkTxId < zkTxId)
{
ConcurrentUtils.awaitUntil(clock, _lock, endTime);
}
return _lastZkTxId;
}
} } | public class class_name {
public long waitForZkTxId(long zkTxId, Object timeout)
throws TimeoutException, InterruptedException
{
long endTime = ClockUtils.toEndTime(clock, timeout);
synchronized(_lock)
{
while(_lastZkTxId < zkTxId)
{
ConcurrentUtils.awaitUntil(clock, _lock, endTime); // depends on control dependency: [while], data = [none]
}
return _lastZkTxId;
}
} } |
public class class_name {
public Map<G, Integer> getGroupSizes(Predicate<G> predicate) {
Timer.Context ctx = getGroupSizesTimer.time();
try {
return this.taskQueue.getGroupSizes(predicate);
} finally {
ctx.stop();
}
} } | public class class_name {
public Map<G, Integer> getGroupSizes(Predicate<G> predicate) {
Timer.Context ctx = getGroupSizesTimer.time();
try {
return this.taskQueue.getGroupSizes(predicate); // depends on control dependency: [try], data = [none]
} finally {
ctx.stop();
}
} } |
public class class_name {
public void marshall(DocumentLocation documentLocation, ProtocolMarshaller protocolMarshaller) {
if (documentLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(documentLocation.getS3Object(), S3OBJECT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DocumentLocation documentLocation, ProtocolMarshaller protocolMarshaller) {
if (documentLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(documentLocation.getS3Object(), S3OBJECT_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 final DSLMapParser.key_chunk_return key_chunk() throws RecognitionException {
DSLMapParser.key_chunk_return retval = new DSLMapParser.key_chunk_return();
retval.start = input.LT(1);
Object root_0 = null;
ParserRuleReturnScope literal17 =null;
try {
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:5: ( ( literal )+ )
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:7: ( literal )+
{
root_0 = (Object)adaptor.nil();
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:7: ( literal )+
int cnt10=0;
loop10:
while (true) {
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==COLON||(LA10_0 >= LEFT_SQUARE && LA10_0 <= LITERAL)||LA10_0==RIGHT_SQUARE) ) {
int LA10_2 = input.LA(2);
if ( (synpred12_DSLMap()) ) {
alt10=1;
}
}
switch (alt10) {
case 1 :
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:7: literal
{
pushFollow(FOLLOW_literal_in_key_chunk646);
literal17=literal();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking==0 ) adaptor.addChild(root_0, literal17.getTree());
}
break;
default :
if ( cnt10 >= 1 ) break loop10;
if (state.backtracking>0) {state.failed=true; return retval;}
EarlyExitException eee = new EarlyExitException(10, input);
throw eee;
}
cnt10++;
}
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} } | public class class_name {
public final DSLMapParser.key_chunk_return key_chunk() throws RecognitionException {
DSLMapParser.key_chunk_return retval = new DSLMapParser.key_chunk_return();
retval.start = input.LT(1);
Object root_0 = null;
ParserRuleReturnScope literal17 =null;
try {
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:5: ( ( literal )+ )
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:7: ( literal )+
{
root_0 = (Object)adaptor.nil();
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:7: ( literal )+
int cnt10=0;
loop10:
while (true) {
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==COLON||(LA10_0 >= LEFT_SQUARE && LA10_0 <= LITERAL)||LA10_0==RIGHT_SQUARE) ) {
int LA10_2 = input.LA(2);
if ( (synpred12_DSLMap()) ) {
alt10=1; // depends on control dependency: [if], data = [none]
}
}
switch (alt10) {
case 1 :
// src/main/resources/org/drools/compiler/lang/dsl/DSLMap.g:164:7: literal
{
pushFollow(FOLLOW_literal_in_key_chunk646);
literal17=literal();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking==0 ) adaptor.addChild(root_0, literal17.getTree());
}
break;
default :
if ( cnt10 >= 1 ) break loop10;
if (state.backtracking>0) {state.failed=true; return retval;} // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
EarlyExitException eee = new EarlyExitException(10, input);
throw eee;
}
cnt10++; // depends on control dependency: [while], data = [none]
}
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (Object)adaptor.rulePostProcessing(root_0); // depends on control dependency: [if], data = [none]
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); // depends on control dependency: [if], data = [none]
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} } |
public class class_name {
private void renderScopeContent(final ContextTreeConfig config, final TreeNode root, final Class<?> scope) {
renderScopeItems(config, root, scope);
final List<Class<Object>> bundles = service.getData()
.getItems(Filters.registeredBy(scope).and(Filters.type(ConfigItem.Bundle)));
for (Class<Object> bundle : bundles) {
renderBundle(config, root, scope, bundle);
}
} } | public class class_name {
private void renderScopeContent(final ContextTreeConfig config, final TreeNode root, final Class<?> scope) {
renderScopeItems(config, root, scope);
final List<Class<Object>> bundles = service.getData()
.getItems(Filters.registeredBy(scope).and(Filters.type(ConfigItem.Bundle)));
for (Class<Object> bundle : bundles) {
renderBundle(config, root, scope, bundle); // depends on control dependency: [for], data = [bundle]
}
} } |
public class class_name {
private boolean investigateHandlesTypes(ServletContainerInitializer sci, HashMap<ServletContainerInitializer, Class[]> handleTypesHashMap, HashMap<ServletContainerInitializer, HashSet<Class<?>>> onStartupHashMap){
boolean needToScan = false;
try {
HandlesTypes handles = sci.getClass().getAnnotation(HandlesTypes.class);
//handles is the classes which we are to look for and find all implementing classes.
if (handles!=null) {
Class[] classes = handles.value();
needToScan=true;
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
for (Class c:classes) {
logger.logp(Level.FINE, CLASS_NAME, "initializeServletContainerInitializers","Handles class to look contains " + c);
}
}
handleTypesHashMap.put(sci, classes);
onStartupHashMap.put(sci, new HashSet<Class<?>>());
}
} catch (RuntimeException e) {
//the HandlesTypes class wasn't found in the classloader
if (WCCustomProperties.LOG_SERVLET_CONTAINER_INITIALIZER_CLASSLOADER_ERRORS) {
logger.logp(Level.WARNING, CLASS_NAME,"initializeServletContainerInitializers", "exception.occurred.while.initializing.ServletContainerInitializers.HandlesTypes", new Object[] {sci.getClass().getName(), this.config.getDisplayName()});
} else {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp(Level.FINE, CLASS_NAME,"initializeServletContainerInitializers", "exception.occurred.while.initializing.ServletContainerInitializers.HandlesTypes", new Object[] {sci.getClass().getName(), this.config.getDisplayName()});
}
}
}
return needToScan;
} } | public class class_name {
private boolean investigateHandlesTypes(ServletContainerInitializer sci, HashMap<ServletContainerInitializer, Class[]> handleTypesHashMap, HashMap<ServletContainerInitializer, HashSet<Class<?>>> onStartupHashMap){
boolean needToScan = false;
try {
HandlesTypes handles = sci.getClass().getAnnotation(HandlesTypes.class);
//handles is the classes which we are to look for and find all implementing classes.
if (handles!=null) {
Class[] classes = handles.value();
needToScan=true;
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
for (Class c:classes) {
logger.logp(Level.FINE, CLASS_NAME, "initializeServletContainerInitializers","Handles class to look contains " + c); // depends on control dependency: [for], data = [c]
}
}
handleTypesHashMap.put(sci, classes);
onStartupHashMap.put(sci, new HashSet<Class<?>>());
}
} catch (RuntimeException e) {
//the HandlesTypes class wasn't found in the classloader
if (WCCustomProperties.LOG_SERVLET_CONTAINER_INITIALIZER_CLASSLOADER_ERRORS) {
logger.logp(Level.WARNING, CLASS_NAME,"initializeServletContainerInitializers", "exception.occurred.while.initializing.ServletContainerInitializers.HandlesTypes", new Object[] {sci.getClass().getName(), this.config.getDisplayName()});
} else {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp(Level.FINE, CLASS_NAME,"initializeServletContainerInitializers", "exception.occurred.while.initializing.ServletContainerInitializers.HandlesTypes", new Object[] {sci.getClass().getName(), this.config.getDisplayName()});
}
}
}
return needToScan;
} } |
public class class_name {
public int numOccurrences(int year, int month, int day) {
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01");
Calendar cal = Calendar.getInstance();
cal.setTime(date.toDate());
GregorianChronology calendar = GregorianChronology.getInstance();
DateTimeField field = calendar.dayOfMonth();
int days = 0;
int count = 0;
int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));
while (days < num) {
if (cal.get(Calendar.DAY_OF_WEEK) == day) {
count++;
}
date = date.plusDays(1);
cal.setTime(date.toDate());
days++;
}
return count;
} } | public class class_name {
public int numOccurrences(int year, int month, int day) {
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01");
Calendar cal = Calendar.getInstance();
cal.setTime(date.toDate());
GregorianChronology calendar = GregorianChronology.getInstance();
DateTimeField field = calendar.dayOfMonth();
int days = 0;
int count = 0;
int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));
while (days < num) {
if (cal.get(Calendar.DAY_OF_WEEK) == day) {
count++; // depends on control dependency: [if], data = [none]
}
date = date.plusDays(1); // depends on control dependency: [while], data = [none]
cal.setTime(date.toDate()); // depends on control dependency: [while], data = [none]
days++; // depends on control dependency: [while], data = [none]
}
return count;
} } |
public class class_name {
public void unproxyRemoteObject (DObjectAddress addr)
{
Tuple<Subscriber<?>, DObject> bits = _proxies.remove(addr);
if (bits == null) {
log.warning("Requested to clear unknown proxy", "addr", addr);
return;
}
// If it's local, just remove the subscriber we added and bail
if (Objects.equal(addr.nodeName, _nodeName)) {
bits.right.removeSubscriber(bits.left);
return;
}
// clear out the local object manager's proxy mapping
_omgr.clearProxyObject(addr.oid, bits.right);
final Client peer = getPeerClient(addr.nodeName);
if (peer == null) {
log.warning("Unable to unsubscribe from proxy, missing peer", "addr", addr);
return;
}
// restore the object's omgr reference to our ClientDObjectMgr and its oid back to the
// remote oid so that it can properly finish the unsubscription process
bits.right.setOid(addr.oid);
bits.right.setManager(peer.getDObjectManager());
// finally unsubscribe from the object on our peer
peer.getDObjectManager().unsubscribeFromObject(addr.oid, bits.left);
} } | public class class_name {
public void unproxyRemoteObject (DObjectAddress addr)
{
Tuple<Subscriber<?>, DObject> bits = _proxies.remove(addr);
if (bits == null) {
log.warning("Requested to clear unknown proxy", "addr", addr); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// If it's local, just remove the subscriber we added and bail
if (Objects.equal(addr.nodeName, _nodeName)) {
bits.right.removeSubscriber(bits.left); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// clear out the local object manager's proxy mapping
_omgr.clearProxyObject(addr.oid, bits.right);
final Client peer = getPeerClient(addr.nodeName);
if (peer == null) {
log.warning("Unable to unsubscribe from proxy, missing peer", "addr", addr); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// restore the object's omgr reference to our ClientDObjectMgr and its oid back to the
// remote oid so that it can properly finish the unsubscription process
bits.right.setOid(addr.oid);
bits.right.setManager(peer.getDObjectManager());
// finally unsubscribe from the object on our peer
peer.getDObjectManager().unsubscribeFromObject(addr.oid, bits.left);
} } |
public class class_name {
public void processContent(byte[] contentBytes, PdfDictionary resources) {
this.resources.push(resources);
try {
PdfContentParser ps = new PdfContentParser(new PRTokeniser(contentBytes));
ArrayList operands = new ArrayList();
while (ps.parse(operands).size() > 0) {
PdfLiteral operator = (PdfLiteral) operands.get(operands.size() - 1);
invokeOperator(operator, operands);
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
this.resources.pop();
} } | public class class_name {
public void processContent(byte[] contentBytes, PdfDictionary resources) {
this.resources.push(resources);
try {
PdfContentParser ps = new PdfContentParser(new PRTokeniser(contentBytes));
ArrayList operands = new ArrayList();
while (ps.parse(operands).size() > 0) {
PdfLiteral operator = (PdfLiteral) operands.get(operands.size() - 1);
invokeOperator(operator, operands);
// depends on control dependency: [while], data = [none]
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
// depends on control dependency: [catch], data = [none]
this.resources.pop();
} } |
public class class_name {
public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) {
OutputStream writer = null;
File tmp = null;
try{
tmp = File.createTempFile(path,".tmp");
if (path.endsWith(".gz")) {
writer = new GZIPOutputStream(new FileOutputStream(tmp));
} else {
writer = new BufferedOutputStream(new FileOutputStream(tmp));
}
writer.write(contents.getBytes(encoding));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(writer != null){ closeIgnoringExceptions(writer); }
}
return tmp;
} } | public class class_name {
public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) {
OutputStream writer = null;
File tmp = null;
try{
tmp = File.createTempFile(path,".tmp");
// depends on control dependency: [try], data = [none]
if (path.endsWith(".gz")) {
writer = new GZIPOutputStream(new FileOutputStream(tmp));
// depends on control dependency: [if], data = [none]
} else {
writer = new BufferedOutputStream(new FileOutputStream(tmp));
// depends on control dependency: [if], data = [none]
}
writer.write(contents.getBytes(encoding));
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} finally {
// depends on control dependency: [catch], data = [none]
if(writer != null){ closeIgnoringExceptions(writer); }
// depends on control dependency: [if], data = [(writer]
}
return tmp;
} } |
public class class_name {
private boolean checkVersion(final KNXnetIPHeader h)
{
if (h.getVersion() != KNXNETIP_VERSION_10) {
status = "protocol version changed";
close(CloseEvent.INTERNAL, "protocol version changed", LogLevel.ERROR, null);
return false;
}
return true;
} } | public class class_name {
private boolean checkVersion(final KNXnetIPHeader h)
{
if (h.getVersion() != KNXNETIP_VERSION_10) {
status = "protocol version changed"; // depends on control dependency: [if], data = [none]
close(CloseEvent.INTERNAL, "protocol version changed", LogLevel.ERROR, null); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
private boolean pointPointPredicates_(int cluster, int id_a, int id_b) {
boolean bRelationKnown = true;
if (m_perform_predicates[MatrixPredicate.InteriorInterior])
{
interiorPointInteriorPoint_(cluster, id_a, id_b);
bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorInterior);
}
if (m_perform_predicates[MatrixPredicate.InteriorExterior])
{
interiorPointExteriorPoint_(cluster, id_a, id_b, MatrixPredicate.InteriorExterior);
bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorExterior);
}
if (m_perform_predicates[MatrixPredicate.ExteriorInterior])
{
interiorPointExteriorPoint_(cluster, id_b, id_a, MatrixPredicate.ExteriorInterior);
bRelationKnown &= isPredicateKnown_(MatrixPredicate.ExteriorInterior);
}
return bRelationKnown;
} } | public class class_name {
private boolean pointPointPredicates_(int cluster, int id_a, int id_b) {
boolean bRelationKnown = true;
if (m_perform_predicates[MatrixPredicate.InteriorInterior])
{
interiorPointInteriorPoint_(cluster, id_a, id_b); // depends on control dependency: [if], data = [none]
bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorInterior); // depends on control dependency: [if], data = [none]
}
if (m_perform_predicates[MatrixPredicate.InteriorExterior])
{
interiorPointExteriorPoint_(cluster, id_a, id_b, MatrixPredicate.InteriorExterior); // depends on control dependency: [if], data = [none]
bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorExterior); // depends on control dependency: [if], data = [none]
}
if (m_perform_predicates[MatrixPredicate.ExteriorInterior])
{
interiorPointExteriorPoint_(cluster, id_b, id_a, MatrixPredicate.ExteriorInterior); // depends on control dependency: [if], data = [none]
bRelationKnown &= isPredicateKnown_(MatrixPredicate.ExteriorInterior); // depends on control dependency: [if], data = [none]
}
return bRelationKnown;
} } |
public class class_name {
public EClass getIfcRectangleHollowProfileDef() {
if (ifcRectangleHollowProfileDefEClass == null) {
ifcRectangleHollowProfileDefEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(426);
}
return ifcRectangleHollowProfileDefEClass;
} } | public class class_name {
public EClass getIfcRectangleHollowProfileDef() {
if (ifcRectangleHollowProfileDefEClass == null) {
ifcRectangleHollowProfileDefEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(426);
// depends on control dependency: [if], data = [none]
}
return ifcRectangleHollowProfileDefEClass;
} } |
public class class_name {
public void setIncrementalMode(boolean incremental) {
if (this.incrementalMode == incremental)
// already set
return;
LOGGER_.trace("set incremental mode: " + incremental);
this.incrementalMode = incremental;
if (!incremental) {
clearDeletedRules();
commitAddedRules();
initClassChanges();
initIndividualChanges();
}
} } | public class class_name {
public void setIncrementalMode(boolean incremental) {
if (this.incrementalMode == incremental)
// already set
return;
LOGGER_.trace("set incremental mode: " + incremental);
this.incrementalMode = incremental;
if (!incremental) {
clearDeletedRules(); // depends on control dependency: [if], data = [none]
commitAddedRules(); // depends on control dependency: [if], data = [none]
initClassChanges(); // depends on control dependency: [if], data = [none]
initIndividualChanges(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Pair<Expr[], Context> translateExpressionsWithChecks(Tuple<WyilFile.Expr> exprs, Context context) {
// Generate expression preconditions as verification conditions
for (WyilFile.Expr expr : exprs) {
checkExpressionPreconditions(expr, context);
}
// Gather up any postconditions from function invocations.
for (WyilFile.Expr expr : exprs) {
context = assumeExpressionPostconditions(expr, context);
}
// Translate expression in the normal fashion
return new Pair<>(translateExpressions(exprs, context.getEnvironment()), context);
} } | public class class_name {
public Pair<Expr[], Context> translateExpressionsWithChecks(Tuple<WyilFile.Expr> exprs, Context context) {
// Generate expression preconditions as verification conditions
for (WyilFile.Expr expr : exprs) {
checkExpressionPreconditions(expr, context); // depends on control dependency: [for], data = [expr]
}
// Gather up any postconditions from function invocations.
for (WyilFile.Expr expr : exprs) {
context = assumeExpressionPostconditions(expr, context); // depends on control dependency: [for], data = [expr]
}
// Translate expression in the normal fashion
return new Pair<>(translateExpressions(exprs, context.getEnvironment()), context);
} } |
public class class_name {
private void loadPlugins() {
// Read the plugin class names from well known resources
try {
Enumeration<URL> pluginResources = classLoader.get().getResources(
"META-INF/services/org.springsource.reloading.agent.Plugins");
while (pluginResources.hasMoreElements()) {
URL pluginResource = pluginResources.nextElement();
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) {
log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin list file "
+ pluginResource);
}
InputStream is = pluginResource.openStream();
BufferedReader pluginClassNamesReader = new BufferedReader(new InputStreamReader(is));
try {
while (true) {
String pluginName = pluginClassNamesReader.readLine();
if (pluginName == null) {
break;
}
if (!pluginName.startsWith("#")) {
pluginClassNames.add(pluginName);
}
}
}
catch (IOException ioe) {
// eof
}
is.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Now load those plugins
for (String pluginClassName : pluginClassNames) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) {
log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin " + pluginClassName);
}
try {
Class<?> pluginClass = Class.forName(pluginClassName, false, this.classLoader.get());
Plugin pluginInstance = (Plugin) pluginClass.newInstance();
localPlugins.add(pluginInstance);
}
catch (Exception e) {
log.log(Level.WARNING, "Unable to find and instantiate plugin " + pluginClassName, e);
}
}
} } | public class class_name {
private void loadPlugins() {
// Read the plugin class names from well known resources
try {
Enumeration<URL> pluginResources = classLoader.get().getResources(
"META-INF/services/org.springsource.reloading.agent.Plugins");
while (pluginResources.hasMoreElements()) {
URL pluginResource = pluginResources.nextElement();
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) {
log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin list file "
+ pluginResource); // depends on control dependency: [if], data = [none]
}
InputStream is = pluginResource.openStream();
BufferedReader pluginClassNamesReader = new BufferedReader(new InputStreamReader(is));
try {
while (true) {
String pluginName = pluginClassNamesReader.readLine();
if (pluginName == null) {
break;
}
if (!pluginName.startsWith("#")) {
pluginClassNames.add(pluginName); // depends on control dependency: [if], data = [none]
}
}
}
catch (IOException ioe) {
// eof
} // depends on control dependency: [catch], data = [none]
is.close(); // depends on control dependency: [try], data = [none]
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
// Now load those plugins
for (String pluginClassName : pluginClassNames) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) {
log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin " + pluginClassName); // depends on control dependency: [if], data = [none]
}
try {
Class<?> pluginClass = Class.forName(pluginClassName, false, this.classLoader.get()); // depends on control dependency: [try], data = [none]
Plugin pluginInstance = (Plugin) pluginClass.newInstance();
localPlugins.add(pluginInstance); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
log.log(Level.WARNING, "Unable to find and instantiate plugin " + pluginClassName, e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private Map<String, Factory> getVisibleIDMap() {
synchronized (this) { // or idcache-only lock?
if (idcache == null) {
try {
factoryLock.acquireRead();
Map<String, Factory> mutableMap = new HashMap<String, Factory>();
ListIterator<Factory> lIter = factories.listIterator(factories.size());
while (lIter.hasPrevious()) {
Factory f = lIter.previous();
f.updateVisibleIDs(mutableMap);
}
this.idcache = Collections.unmodifiableMap(mutableMap);
} finally {
factoryLock.releaseRead();
}
}
}
return idcache;
} } | public class class_name {
private Map<String, Factory> getVisibleIDMap() {
synchronized (this) { // or idcache-only lock?
if (idcache == null) {
try {
factoryLock.acquireRead(); // depends on control dependency: [try], data = [none]
Map<String, Factory> mutableMap = new HashMap<String, Factory>();
ListIterator<Factory> lIter = factories.listIterator(factories.size());
while (lIter.hasPrevious()) {
Factory f = lIter.previous();
f.updateVisibleIDs(mutableMap); // depends on control dependency: [while], data = [none]
}
this.idcache = Collections.unmodifiableMap(mutableMap); // depends on control dependency: [try], data = [none]
} finally {
factoryLock.releaseRead();
}
}
}
return idcache;
} } |
public class class_name {
public void marshall(SetFileModeEntry setFileModeEntry, ProtocolMarshaller protocolMarshaller) {
if (setFileModeEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setFileModeEntry.getFilePath(), FILEPATH_BINDING);
protocolMarshaller.marshall(setFileModeEntry.getFileMode(), FILEMODE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(SetFileModeEntry setFileModeEntry, ProtocolMarshaller protocolMarshaller) {
if (setFileModeEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setFileModeEntry.getFilePath(), FILEPATH_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(setFileModeEntry.getFileMode(), FILEMODE_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 boolean checkResourceConstraints(String contextId, Object httpServletRequest, Permission webPerm, Subject subject) {
HttpServletRequest req = null;
if (httpServletRequest != null) {
try {
req = (HttpServletRequest) httpServletRequest;
} catch (ClassCastException cce) {
Tr.error(tc, "JACC_WEB_SPI_PARAMETER_ERROR", new Object[] { httpServletRequest.getClass().getName(), "checkDataConstraints", "HttpServletRequest" });
return false;
}
}
boolean result = false;
try {
final HashMap<String, Object> ho = new HashMap<String, Object>();
final Subject s = subject;
final String cid = contextId;
final Permission p = webPerm;
final HttpServletRequest r = req;
result = checkResourceConstraints(cid, r, p, s, ho);
} catch (PrivilegedActionException e) {
Tr.error(tc, "JACC_WEB_IMPLIES_FAILURE", new Object[] { contextId, e.getException() });
}
return result;
} } | public class class_name {
@Override
public boolean checkResourceConstraints(String contextId, Object httpServletRequest, Permission webPerm, Subject subject) {
HttpServletRequest req = null;
if (httpServletRequest != null) {
try {
req = (HttpServletRequest) httpServletRequest; // depends on control dependency: [try], data = [none]
} catch (ClassCastException cce) {
Tr.error(tc, "JACC_WEB_SPI_PARAMETER_ERROR", new Object[] { httpServletRequest.getClass().getName(), "checkDataConstraints", "HttpServletRequest" });
return false;
} // depends on control dependency: [catch], data = [none]
}
boolean result = false;
try {
final HashMap<String, Object> ho = new HashMap<String, Object>();
final Subject s = subject;
final String cid = contextId;
final Permission p = webPerm;
final HttpServletRequest r = req;
result = checkResourceConstraints(cid, r, p, s, ho); // depends on control dependency: [try], data = [none]
} catch (PrivilegedActionException e) {
Tr.error(tc, "JACC_WEB_IMPLIES_FAILURE", new Object[] { contextId, e.getException() });
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public static void initialize(
Context context,
@Nullable ImagePipelineConfig imagePipelineConfig,
@Nullable DraweeConfig draweeConfig) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("Fresco#initialize");
}
if (sIsInitialized) {
FLog.w(
TAG,
"Fresco has already been initialized! `Fresco.initialize(...)` should only be called "
+ "1 single time to avoid memory leaks!");
} else {
sIsInitialized = true;
}
try {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("Fresco.initialize->SoLoader.init");
}
SoLoader.init(context, 0);
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
} catch (IOException e) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
throw new RuntimeException("Could not initialize SoLoader", e);
}
// we should always use the application context to avoid memory leaks
context = context.getApplicationContext();
if (imagePipelineConfig == null) {
ImagePipelineFactory.initialize(context);
} else {
ImagePipelineFactory.initialize(imagePipelineConfig);
}
initializeDrawee(context, draweeConfig);
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
} } | public class class_name {
public static void initialize(
Context context,
@Nullable ImagePipelineConfig imagePipelineConfig,
@Nullable DraweeConfig draweeConfig) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("Fresco#initialize"); // depends on control dependency: [if], data = [none]
}
if (sIsInitialized) {
FLog.w(
TAG,
"Fresco has already been initialized! `Fresco.initialize(...)` should only be called "
+ "1 single time to avoid memory leaks!"); // depends on control dependency: [if], data = [none]
} else {
sIsInitialized = true; // depends on control dependency: [if], data = [none]
}
try {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("Fresco.initialize->SoLoader.init"); // depends on control dependency: [if], data = [none]
}
SoLoader.init(context, 0); // depends on control dependency: [try], data = [none]
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none]
}
throw new RuntimeException("Could not initialize SoLoader", e);
} // depends on control dependency: [catch], data = [none]
// we should always use the application context to avoid memory leaks
context = context.getApplicationContext();
if (imagePipelineConfig == null) {
ImagePipelineFactory.initialize(context); // depends on control dependency: [if], data = [none]
} else {
ImagePipelineFactory.initialize(imagePipelineConfig); // depends on control dependency: [if], data = [(imagePipelineConfig]
}
initializeDrawee(context, draweeConfig);
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long reconciliationReportId)
throws RemoteException {
ReconciliationOrderReportServiceInterface reconciliationOrderReportService =
adManagerServices.get(session, ReconciliationOrderReportServiceInterface.class);
// Create a statement to select reconciliation order reports.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("reconciliationReportId = :reconciliationReportId")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("reconciliationReportId", reconciliationReportId);
// Retrieve a small amount of reconciliation order reports at a time, paging through
// until all reconciliation order reports have been retrieved.
int totalResultSetSize = 0;
do {
ReconciliationOrderReportPage page =
reconciliationOrderReportService.getReconciliationOrderReportsByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each reconciliation order report.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ReconciliationOrderReport reconciliationOrderReport : page.getResults()) {
System.out.printf(
"%d) Reconciliation order report with ID %d and status '%s' was found.%n",
i++, reconciliationOrderReport.getId(), reconciliationOrderReport.getStatus());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} } | public class class_name {
public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long reconciliationReportId)
throws RemoteException {
ReconciliationOrderReportServiceInterface reconciliationOrderReportService =
adManagerServices.get(session, ReconciliationOrderReportServiceInterface.class);
// Create a statement to select reconciliation order reports.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("reconciliationReportId = :reconciliationReportId")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("reconciliationReportId", reconciliationReportId);
// Retrieve a small amount of reconciliation order reports at a time, paging through
// until all reconciliation order reports have been retrieved.
int totalResultSetSize = 0;
do {
ReconciliationOrderReportPage page =
reconciliationOrderReportService.getReconciliationOrderReportsByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each reconciliation order report.
totalResultSetSize = page.getTotalResultSetSize(); // depends on control dependency: [if], data = [none]
int i = page.getStartIndex();
for (ReconciliationOrderReport reconciliationOrderReport : page.getResults()) {
System.out.printf(
"%d) Reconciliation order report with ID %d and status '%s' was found.%n", // depends on control dependency: [for], data = [none]
i++, reconciliationOrderReport.getId(), reconciliationOrderReport.getStatus());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} } |
public class class_name {
@Override
public void onContainerStopped(final ContainerId containerId) {
final boolean hasContainer = this.containers.hasContainer(containerId.toString());
if (hasContainer) {
this.reefEventHandlers.onResourceStatus(
ResourceStatusEventImpl.newBuilder()
.setIdentifier(containerId.toString())
.setState(State.DONE)
.build());
}
} } | public class class_name {
@Override
public void onContainerStopped(final ContainerId containerId) {
final boolean hasContainer = this.containers.hasContainer(containerId.toString());
if (hasContainer) {
this.reefEventHandlers.onResourceStatus(
ResourceStatusEventImpl.newBuilder()
.setIdentifier(containerId.toString())
.setState(State.DONE)
.build()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void addResponseHeaders(final HttpServletResponse servletResponse) {
final String receivedParam = ofNullable(params.get("received")).orElse("");
final List<String> includes = asList(ofNullable(params.get("include")).orElse(" ").split(" "));
final List<String> omits = asList(ofNullable(params.get("omit")).orElse(" ").split(" "));
final StringBuilder includeBuilder = new StringBuilder();
final StringBuilder omitBuilder = new StringBuilder();
if (!(value.equals("minimal") || receivedParam.equals("minimal"))) {
final List<String> appliedPrefs = asList(PREFER_SERVER_MANAGED.toString(),
LDP_NAMESPACE + "PreferMinimalContainer",
LDP_NAMESPACE + "PreferMembership",
LDP_NAMESPACE + "PreferContainment");
final List<String> includePrefs = asList(EMBED_CONTAINED.toString(),
INBOUND_REFERENCES.toString());
includes.forEach(param -> includeBuilder.append(
(appliedPrefs.contains(param) || includePrefs.contains(param)) ? param + " " : ""));
// Note: include params prioritized over omits during implementation
omits.forEach(param -> omitBuilder.append(
(appliedPrefs.contains(param) && !includes.contains(param)) ? param + " " : ""));
}
// build the header for Preference Applied
final String appliedReturn = value.equals("minimal") ? "return=minimal" : "return=representation";
final String appliedReceived = receivedParam.equals("minimal") ? "received=minimal" : "";
final StringBuilder preferenceAppliedBuilder = new StringBuilder(appliedReturn);
preferenceAppliedBuilder.append(appliedReceived.length() > 0 ? "; " + appliedReceived : "");
appendHeaderParam(preferenceAppliedBuilder, "include", includeBuilder.toString().trim());
appendHeaderParam(preferenceAppliedBuilder, "omit", omitBuilder.toString().trim());
servletResponse.addHeader("Preference-Applied", preferenceAppliedBuilder.toString().trim());
servletResponse.addHeader("Vary", "Prefer");
} } | public class class_name {
public void addResponseHeaders(final HttpServletResponse servletResponse) {
final String receivedParam = ofNullable(params.get("received")).orElse("");
final List<String> includes = asList(ofNullable(params.get("include")).orElse(" ").split(" "));
final List<String> omits = asList(ofNullable(params.get("omit")).orElse(" ").split(" "));
final StringBuilder includeBuilder = new StringBuilder();
final StringBuilder omitBuilder = new StringBuilder();
if (!(value.equals("minimal") || receivedParam.equals("minimal"))) {
final List<String> appliedPrefs = asList(PREFER_SERVER_MANAGED.toString(),
LDP_NAMESPACE + "PreferMinimalContainer",
LDP_NAMESPACE + "PreferMembership",
LDP_NAMESPACE + "PreferContainment");
final List<String> includePrefs = asList(EMBED_CONTAINED.toString(),
INBOUND_REFERENCES.toString());
includes.forEach(param -> includeBuilder.append(
(appliedPrefs.contains(param) || includePrefs.contains(param)) ? param + " " : "")); // depends on control dependency: [if], data = [none]
// Note: include params prioritized over omits during implementation
omits.forEach(param -> omitBuilder.append(
(appliedPrefs.contains(param) && !includes.contains(param)) ? param + " " : "")); // depends on control dependency: [if], data = [none]
}
// build the header for Preference Applied
final String appliedReturn = value.equals("minimal") ? "return=minimal" : "return=representation";
final String appliedReceived = receivedParam.equals("minimal") ? "received=minimal" : "";
final StringBuilder preferenceAppliedBuilder = new StringBuilder(appliedReturn);
preferenceAppliedBuilder.append(appliedReceived.length() > 0 ? "; " + appliedReceived : "");
appendHeaderParam(preferenceAppliedBuilder, "include", includeBuilder.toString().trim());
appendHeaderParam(preferenceAppliedBuilder, "omit", omitBuilder.toString().trim());
servletResponse.addHeader("Preference-Applied", preferenceAppliedBuilder.toString().trim());
servletResponse.addHeader("Vary", "Prefer");
} } |
public class class_name {
@SuppressWarnings("unchecked")
public boolean postValidateInfoTopic(final InfoTopic infoTopic, final ContentSpec contentSpec) {
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true);
return false;
}
boolean valid = true;
// New Topics
if (infoTopic.isTopicANewTopic()) {
// Validate the tags
if (!validateTopicTags(infoTopic, infoTopic.getTags(false))) {
valid = false;
}
// Check Assigned Writer exists
if (!postValidateAssignedWriter(infoTopic)) {
valid = false;
}
}
// Existing Topics
else if (infoTopic.isTopicAnExistingTopic()) {
// Calculate the revision for the topic
final Integer revision;
if (infoTopic.getRevision() == null && processingOptions.getMaxRevision() != null) {
revision = processingOptions.getMaxRevision();
} else {
revision = infoTopic.getRevision();
}
// Check that the id actually exists
BaseTopicWrapper<?> topic = null;
try {
if (processingOptions.isTranslation()) {
topic = EntityUtilities.getTranslatedTopicByTopicId(factory, Integer.parseInt(infoTopic.getId()), revision,
processingOptions.getTranslationLocale() == null ? defaultLocale : processingOptions.getTranslationLocale());
} else {
topic = topicProvider.getTopic(Integer.parseInt(infoTopic.getId()), revision);
}
} catch (NotFoundException e) {
log.debug("Could not find topic for id " + infoTopic.getDBId());
}
// Check that the topic actually exists
if (topic == null) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, infoTopic.getLineNumber(), infoTopic.getText()));
valid = false;
} else {
infoTopic.setTopic(topic);
// Check to see if the topic contains the "Internal-Only" tag
if (serverEntities.getInternalOnlyTagId() != null && topic.hasTag(serverEntities.getInternalOnlyTagId())) {
log.warn(String.format(ProcessorConstants.WARN_INTERNAL_TOPIC_MSG, infoTopic.getLineNumber(), infoTopic.getText()));
}
if (!postValidateExistingTopic(infoTopic, topic, contentSpec)) {
valid = false;
}
}
// Cloned Topics
} else if (infoTopic.isTopicAClonedTopic()) {
// Get the original topic from the database
int topicId = Integer.parseInt(infoTopic.getId().substring(1));
TopicWrapper topic = null;
try {
topic = topicProvider.getTopic(topicId, infoTopic.getRevision());
} catch (NotFoundException e) {
log.debug("Could not find topic for id " + topicId);
}
// Check that the original topic was found
if (topic == null) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, infoTopic.getLineNumber(), infoTopic.getText()));
valid = false;
} else {
if (!postValidateExistingTopic(infoTopic, topic, contentSpec)) {
valid = false;
}
// Check Assigned Writer exists
if (!postValidateAssignedWriter(infoTopic)) {
valid = false;
}
}
}
return valid;
} } | public class class_name {
@SuppressWarnings("unchecked")
public boolean postValidateInfoTopic(final InfoTopic infoTopic, final ContentSpec contentSpec) {
// Check if the app should be shutdown
if (isShuttingDown.get()) {
shutdown.set(true); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
boolean valid = true;
// New Topics
if (infoTopic.isTopicANewTopic()) {
// Validate the tags
if (!validateTopicTags(infoTopic, infoTopic.getTags(false))) {
valid = false; // depends on control dependency: [if], data = [none]
}
// Check Assigned Writer exists
if (!postValidateAssignedWriter(infoTopic)) {
valid = false; // depends on control dependency: [if], data = [none]
}
}
// Existing Topics
else if (infoTopic.isTopicAnExistingTopic()) {
// Calculate the revision for the topic
final Integer revision;
if (infoTopic.getRevision() == null && processingOptions.getMaxRevision() != null) {
revision = processingOptions.getMaxRevision(); // depends on control dependency: [if], data = [none]
} else {
revision = infoTopic.getRevision(); // depends on control dependency: [if], data = [none]
}
// Check that the id actually exists
BaseTopicWrapper<?> topic = null;
try {
if (processingOptions.isTranslation()) {
topic = EntityUtilities.getTranslatedTopicByTopicId(factory, Integer.parseInt(infoTopic.getId()), revision,
processingOptions.getTranslationLocale() == null ? defaultLocale : processingOptions.getTranslationLocale()); // depends on control dependency: [if], data = [none]
} else {
topic = topicProvider.getTopic(Integer.parseInt(infoTopic.getId()), revision); // depends on control dependency: [if], data = [none]
}
} catch (NotFoundException e) {
log.debug("Could not find topic for id " + infoTopic.getDBId());
} // depends on control dependency: [catch], data = [none]
// Check that the topic actually exists
if (topic == null) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, infoTopic.getLineNumber(), infoTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
} else {
infoTopic.setTopic(topic); // depends on control dependency: [if], data = [(topic]
// Check to see if the topic contains the "Internal-Only" tag
if (serverEntities.getInternalOnlyTagId() != null && topic.hasTag(serverEntities.getInternalOnlyTagId())) {
log.warn(String.format(ProcessorConstants.WARN_INTERNAL_TOPIC_MSG, infoTopic.getLineNumber(), infoTopic.getText())); // depends on control dependency: [if], data = [none]
}
if (!postValidateExistingTopic(infoTopic, topic, contentSpec)) {
valid = false; // depends on control dependency: [if], data = [none]
}
}
// Cloned Topics
} else if (infoTopic.isTopicAClonedTopic()) {
// Get the original topic from the database
int topicId = Integer.parseInt(infoTopic.getId().substring(1));
TopicWrapper topic = null;
try {
topic = topicProvider.getTopic(topicId, infoTopic.getRevision()); // depends on control dependency: [try], data = [none]
} catch (NotFoundException e) {
log.debug("Could not find topic for id " + topicId);
} // depends on control dependency: [catch], data = [none]
// Check that the original topic was found
if (topic == null) {
log.error(String.format(ProcessorConstants.ERROR_TOPIC_NONEXIST_MSG, infoTopic.getLineNumber(), infoTopic.getText())); // depends on control dependency: [if], data = [none]
valid = false; // depends on control dependency: [if], data = [none]
} else {
if (!postValidateExistingTopic(infoTopic, topic, contentSpec)) {
valid = false; // depends on control dependency: [if], data = [none]
}
// Check Assigned Writer exists
if (!postValidateAssignedWriter(infoTopic)) {
valid = false; // depends on control dependency: [if], data = [none]
}
}
}
return valid;
} } |
public class class_name {
@Override
public Map<String, Object> toSource() {
Map<String, Object> sourceMap = new HashMap<>();
if (configId != null) {
addFieldToSource(sourceMap, "configId", configId);
}
if (errorCount != null) {
addFieldToSource(sourceMap, "errorCount", errorCount);
}
if (errorLog != null) {
addFieldToSource(sourceMap, "errorLog", errorLog);
}
if (errorName != null) {
addFieldToSource(sourceMap, "errorName", errorName);
}
if (lastAccessTime != null) {
addFieldToSource(sourceMap, "lastAccessTime", lastAccessTime);
}
if (threadName != null) {
addFieldToSource(sourceMap, "threadName", threadName);
}
if (url != null) {
addFieldToSource(sourceMap, "url", url);
}
return sourceMap;
} } | public class class_name {
@Override
public Map<String, Object> toSource() {
Map<String, Object> sourceMap = new HashMap<>();
if (configId != null) {
addFieldToSource(sourceMap, "configId", configId); // depends on control dependency: [if], data = [none]
}
if (errorCount != null) {
addFieldToSource(sourceMap, "errorCount", errorCount); // depends on control dependency: [if], data = [none]
}
if (errorLog != null) {
addFieldToSource(sourceMap, "errorLog", errorLog); // depends on control dependency: [if], data = [none]
}
if (errorName != null) {
addFieldToSource(sourceMap, "errorName", errorName); // depends on control dependency: [if], data = [none]
}
if (lastAccessTime != null) {
addFieldToSource(sourceMap, "lastAccessTime", lastAccessTime); // depends on control dependency: [if], data = [none]
}
if (threadName != null) {
addFieldToSource(sourceMap, "threadName", threadName); // depends on control dependency: [if], data = [none]
}
if (url != null) {
addFieldToSource(sourceMap, "url", url); // depends on control dependency: [if], data = [none]
}
return sourceMap;
} } |
public class class_name {
public List<RawEntry> toRawList(){
if (t == null || t.size() == 0){
return Collections.emptyList();
}
List<RawEntry> result = new ArrayList<RawEntry>(t.size());
int lastDuration = 0;
for (int i = 0; i < t.size(); i ++){
long timestamp = t.get(i);
int duration = -1;
if (i < d.size()){
duration = d.get(i);
}
if (duration == -1){
duration = lastDuration;
}
lastDuration = duration;
long timestampMillis;
long durationMillis;
if (u == null || u.equals("m")){
timestampMillis = 1000L * 60 * timestamp;
durationMillis = 1000L * 60 * duration;
}else if (u.equals("s")){
timestampMillis = 1000L * timestamp;
durationMillis = 1000L * duration;
}else if (u.equals("S")){
timestampMillis = timestamp;
durationMillis = duration;
}else{
throw new IllegalArgumentException("Unit not supported: " + u);
}
result.add(new RawEntry(timestampMillis, durationMillis,
c == null || i >= c.size() ? null : c.get(i),
s == null || i >= s.size() ? null : s.get(i),
a == null || i >= a.size() ? null : a.get(i),
m == null || i >= m.size() ? null : m.get(i),
x == null || i >= x.size() ? null : x.get(i),
n == null || i >= n.size() ? null : n.get(i),
o == null || i >= o.size() ? null : o.get(i)
));
}
return result;
} } | public class class_name {
public List<RawEntry> toRawList(){
if (t == null || t.size() == 0){
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
List<RawEntry> result = new ArrayList<RawEntry>(t.size());
int lastDuration = 0;
for (int i = 0; i < t.size(); i ++){
long timestamp = t.get(i);
int duration = -1;
if (i < d.size()){
duration = d.get(i); // depends on control dependency: [if], data = [(i]
}
if (duration == -1){
duration = lastDuration; // depends on control dependency: [if], data = [none]
}
lastDuration = duration; // depends on control dependency: [for], data = [none]
long timestampMillis;
long durationMillis;
if (u == null || u.equals("m")){
timestampMillis = 1000L * 60 * timestamp; // depends on control dependency: [if], data = [none]
durationMillis = 1000L * 60 * duration; // depends on control dependency: [if], data = [none]
}else if (u.equals("s")){
timestampMillis = 1000L * timestamp; // depends on control dependency: [if], data = [none]
durationMillis = 1000L * duration; // depends on control dependency: [if], data = [none]
}else if (u.equals("S")){
timestampMillis = timestamp; // depends on control dependency: [if], data = [none]
durationMillis = duration; // depends on control dependency: [if], data = [none]
}else{
throw new IllegalArgumentException("Unit not supported: " + u);
}
result.add(new RawEntry(timestampMillis, durationMillis,
c == null || i >= c.size() ? null : c.get(i),
s == null || i >= s.size() ? null : s.get(i),
a == null || i >= a.size() ? null : a.get(i),
m == null || i >= m.size() ? null : m.get(i),
x == null || i >= x.size() ? null : x.get(i),
n == null || i >= n.size() ? null : n.get(i),
o == null || i >= o.size() ? null : o.get(i)
)); // depends on control dependency: [for], data = [none]
}
return result;
} } |
public class class_name {
public static Expression select(String field, String operator, Val<Expression>[] args, EbeanExprInvoker invoker) {
if (args.length > 0) {
EbeanServer server = invoker.getServer();
Class type = Filters.getBeanTypeByName(field, (SpiEbeanServer) server);
if (type == null) {
throw new QuerySyntaxException(Messages.get("dsl.bean.type.err", field));
}
Query q = Filters.createQuery(type, server);
ExpressionList<?> et = q.select(args[0].string()).where();
for (int i = 1; i < args.length; i++) {
Object o = args[i].object();
if (o instanceof HavingExpression) {
ExpressionList having = q.having();
((HavingExpression) o).expressionList.forEach(having::add);
} else if (o instanceof DistinctExpression) {
et.setDistinct(((DistinctExpression) o).distinct);
} else if (o instanceof Expression) {
et.add(args[i].expr());
} else {
throw new QuerySyntaxException(Messages.get("dsl.arguments.error3", operator));
}
}
EbeanUtils.checkQuery(q, invoker.getInjectionManager());
return QueryExpression.of(q);
}
throw new QuerySyntaxException(Messages.get("dsl.arguments.error0", operator));
} } | public class class_name {
public static Expression select(String field, String operator, Val<Expression>[] args, EbeanExprInvoker invoker) {
if (args.length > 0) {
EbeanServer server = invoker.getServer();
Class type = Filters.getBeanTypeByName(field, (SpiEbeanServer) server);
if (type == null) {
throw new QuerySyntaxException(Messages.get("dsl.bean.type.err", field));
}
Query q = Filters.createQuery(type, server);
ExpressionList<?> et = q.select(args[0].string()).where();
for (int i = 1; i < args.length; i++) {
Object o = args[i].object();
if (o instanceof HavingExpression) {
ExpressionList having = q.having();
((HavingExpression) o).expressionList.forEach(having::add); // depends on control dependency: [if], data = [none]
} else if (o instanceof DistinctExpression) {
et.setDistinct(((DistinctExpression) o).distinct); // depends on control dependency: [if], data = [none]
} else if (o instanceof Expression) {
et.add(args[i].expr()); // depends on control dependency: [if], data = [none]
} else {
throw new QuerySyntaxException(Messages.get("dsl.arguments.error3", operator));
}
}
EbeanUtils.checkQuery(q, invoker.getInjectionManager()); // depends on control dependency: [if], data = [none]
return QueryExpression.of(q); // depends on control dependency: [if], data = [none]
}
throw new QuerySyntaxException(Messages.get("dsl.arguments.error0", operator));
} } |
public class class_name {
private int computePk2Measure(double[] objectiveScores) {
LOGGER.fine("Computing the PK2 measure");
// Compute each Pk2 score and the average score.
double average = 0;
for (int k = objectiveScores.length - 1; k > 0; --k) {
objectiveScores[k] /= objectiveScores[k-1];
average += objectiveScores[k];
}
average /= (objectiveScores.length - 1);
// Compute the standard deviation of the PK2 scores.
double stdev = 0;
for (int k = 1; k < objectiveScores.length; ++k)
stdev += Math.pow(objectiveScores[k] - average, 2);
stdev /= (objectiveScores.length - 2);
stdev = Math.sqrt(stdev);
// Find the point where the score is the smallest value greater than 1 +
// stdev of the PK1 scores.
double referencePoint = 1 + stdev;
int bestIndex = 0;
double bestScore = Double.MAX_VALUE;
for (int k = 1; k < objectiveScores.length; ++k) {
if (objectiveScores[k] < bestScore &&
objectiveScores[k] >= referencePoint) {
bestIndex = k;
bestScore = objectiveScores[k];
}
}
return bestIndex;
} } | public class class_name {
private int computePk2Measure(double[] objectiveScores) {
LOGGER.fine("Computing the PK2 measure");
// Compute each Pk2 score and the average score.
double average = 0;
for (int k = objectiveScores.length - 1; k > 0; --k) {
objectiveScores[k] /= objectiveScores[k-1]; // depends on control dependency: [for], data = [k]
average += objectiveScores[k]; // depends on control dependency: [for], data = [k]
}
average /= (objectiveScores.length - 1);
// Compute the standard deviation of the PK2 scores.
double stdev = 0;
for (int k = 1; k < objectiveScores.length; ++k)
stdev += Math.pow(objectiveScores[k] - average, 2);
stdev /= (objectiveScores.length - 2);
stdev = Math.sqrt(stdev);
// Find the point where the score is the smallest value greater than 1 +
// stdev of the PK1 scores.
double referencePoint = 1 + stdev;
int bestIndex = 0;
double bestScore = Double.MAX_VALUE;
for (int k = 1; k < objectiveScores.length; ++k) {
if (objectiveScores[k] < bestScore &&
objectiveScores[k] >= referencePoint) {
bestIndex = k; // depends on control dependency: [if], data = [none]
bestScore = objectiveScores[k]; // depends on control dependency: [if], data = [none]
}
}
return bestIndex;
} } |
public class class_name {
private static boolean isEmpty(MsgNode msg) {
for (SoyNode child : msg.getChildren()) {
if (child instanceof RawTextNode && ((RawTextNode) child).getRawText().isEmpty()) {
continue;
}
return false;
}
return true;
} } | public class class_name {
private static boolean isEmpty(MsgNode msg) {
for (SoyNode child : msg.getChildren()) {
if (child instanceof RawTextNode && ((RawTextNode) child).getRawText().isEmpty()) {
continue;
}
return false; // depends on control dependency: [for], data = [none]
}
return true;
} } |
public class class_name {
public String formatDiagnostic(JCDiagnostic d, Locale l) {
try {
StringBuilder buf = new StringBuilder();
if (d.getPosition() != Position.NOPOS) {
buf.append(formatSource(d, false, null));
buf.append(':');
buf.append(formatPosition(d, LINE, null));
buf.append(':');
buf.append(formatPosition(d, COLUMN, null));
buf.append(':');
}
else if (d.getSource() != null && d.getSource().getKind() == JavaFileObject.Kind.CLASS) {
buf.append(formatSource(d, false, null));
buf.append(":-:-:");
}
else
buf.append('-');
buf.append(' ');
buf.append(formatMessage(d, null));
if (displaySource(d)) {
buf.append("\n");
buf.append(formatSourceLine(d, 0));
}
return buf.toString();
}
catch (Exception e) {
//e.printStackTrace();
return null;
}
} } | public class class_name {
public String formatDiagnostic(JCDiagnostic d, Locale l) {
try {
StringBuilder buf = new StringBuilder();
if (d.getPosition() != Position.NOPOS) {
buf.append(formatSource(d, false, null)); // depends on control dependency: [if], data = [none]
buf.append(':'); // depends on control dependency: [if], data = [none]
buf.append(formatPosition(d, LINE, null)); // depends on control dependency: [if], data = [none]
buf.append(':'); // depends on control dependency: [if], data = [none]
buf.append(formatPosition(d, COLUMN, null)); // depends on control dependency: [if], data = [none]
buf.append(':'); // depends on control dependency: [if], data = [none]
}
else if (d.getSource() != null && d.getSource().getKind() == JavaFileObject.Kind.CLASS) {
buf.append(formatSource(d, false, null)); // depends on control dependency: [if], data = [none]
buf.append(":-:-:"); // depends on control dependency: [if], data = [none]
}
else
buf.append('-');
buf.append(' '); // depends on control dependency: [try], data = [none]
buf.append(formatMessage(d, null)); // depends on control dependency: [try], data = [none]
if (displaySource(d)) {
buf.append("\n"); // depends on control dependency: [if], data = [none]
buf.append(formatSourceLine(d, 0)); // depends on control dependency: [if], data = [none]
}
return buf.toString(); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
//e.printStackTrace();
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<T> first(final int n) {
N.checkArgument(n >= 0, "'n' can't be negative: " + n);
if (N.isNullOrEmpty(coll) || n == 0) {
return new ArrayList<>();
} else if (coll.size() <= n) {
return new ArrayList<>(coll);
} else if (coll instanceof List) {
return new ArrayList<>(((List<T>) coll).subList(0, n));
} else {
final List<T> result = new ArrayList<>(N.min(n, coll.size()));
int cnt = 0;
for (T e : coll) {
result.add(e);
if (++cnt == n) {
break;
}
}
return result;
}
} } | public class class_name {
public List<T> first(final int n) {
N.checkArgument(n >= 0, "'n' can't be negative: " + n);
if (N.isNullOrEmpty(coll) || n == 0) {
return new ArrayList<>();
// depends on control dependency: [if], data = [none]
} else if (coll.size() <= n) {
return new ArrayList<>(coll);
// depends on control dependency: [if], data = [none]
} else if (coll instanceof List) {
return new ArrayList<>(((List<T>) coll).subList(0, n));
// depends on control dependency: [if], data = [none]
} else {
final List<T> result = new ArrayList<>(N.min(n, coll.size()));
int cnt = 0;
for (T e : coll) {
result.add(e);
// depends on control dependency: [for], data = [e]
if (++cnt == n) {
break;
}
}
return result;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public <DatastoreType, Instance> InstanceInvocationHandler<DatastoreType> getInvocationHandler(Instance instance) {
Instance effectiveInstance;
if (interceptorFactory.hasInterceptor(instance)) {
effectiveInstance = interceptorFactory.removeInterceptor(instance);
} else {
effectiveInstance = instance;
}
InvocationHandler invocationHandler = Proxy.getInvocationHandler(effectiveInstance);
if (!(invocationHandler instanceof InstanceInvocationHandler)) {
throw new XOException("Instance " + instance + " implementing " + Arrays.asList(instance.getClass().getInterfaces()) + " is not a "
+ InstanceInvocationHandler.class.getName());
}
return (InstanceInvocationHandler<DatastoreType>) invocationHandler;
} } | public class class_name {
public <DatastoreType, Instance> InstanceInvocationHandler<DatastoreType> getInvocationHandler(Instance instance) {
Instance effectiveInstance;
if (interceptorFactory.hasInterceptor(instance)) {
effectiveInstance = interceptorFactory.removeInterceptor(instance); // depends on control dependency: [if], data = [none]
} else {
effectiveInstance = instance; // depends on control dependency: [if], data = [none]
}
InvocationHandler invocationHandler = Proxy.getInvocationHandler(effectiveInstance);
if (!(invocationHandler instanceof InstanceInvocationHandler)) {
throw new XOException("Instance " + instance + " implementing " + Arrays.asList(instance.getClass().getInterfaces()) + " is not a "
+ InstanceInvocationHandler.class.getName());
}
return (InstanceInvocationHandler<DatastoreType>) invocationHandler;
} } |
public class class_name {
@Override
public ContentSerializer getBestSerializer(Collection<MediaType> mediaTypes) {
if (mediaTypes == null || mediaTypes.isEmpty()) {
mediaTypes = ImmutableList.of(MediaType.HTML_UTF_8);
}
for (MediaType type : mediaTypes) {
for (ContentSerializer ser : serializers) {
MediaType mt = MediaType.parse(ser.getContentType());
if (mt.is(type.withoutParameters())) {
return ser;
}
}
}
return null;
} } | public class class_name {
@Override
public ContentSerializer getBestSerializer(Collection<MediaType> mediaTypes) {
if (mediaTypes == null || mediaTypes.isEmpty()) {
mediaTypes = ImmutableList.of(MediaType.HTML_UTF_8); // depends on control dependency: [if], data = [none]
}
for (MediaType type : mediaTypes) {
for (ContentSerializer ser : serializers) {
MediaType mt = MediaType.parse(ser.getContentType());
if (mt.is(type.withoutParameters())) {
return ser; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public Affordance build() {
Assert.state(!(rels.isEmpty() && reverseRels.isEmpty()),
"no rels or reverse rels found, call rel() or rev() before building the affordance");
final Affordance affordance;
affordance = new Affordance(new PartialUriTemplate(this.toString()), actionDescriptors,
rels.toArray(new String[rels.size()]));
for (Map.Entry<String, List<String>> linkParamEntry : linkParams.entrySet()) {
final List<String> values = linkParamEntry.getValue();
for (String value : values) {
affordance.addLinkParam(linkParamEntry.getKey(), value);
}
}
for (String reverseRel : reverseRels) {
affordance.addRev(reverseRel);
}
affordance.setCollectionHolder(collectionHolder);
return affordance;
} } | public class class_name {
public Affordance build() {
Assert.state(!(rels.isEmpty() && reverseRels.isEmpty()),
"no rels or reverse rels found, call rel() or rev() before building the affordance");
final Affordance affordance;
affordance = new Affordance(new PartialUriTemplate(this.toString()), actionDescriptors,
rels.toArray(new String[rels.size()]));
for (Map.Entry<String, List<String>> linkParamEntry : linkParams.entrySet()) {
final List<String> values = linkParamEntry.getValue();
for (String value : values) {
affordance.addLinkParam(linkParamEntry.getKey(), value); // depends on control dependency: [for], data = [value]
}
}
for (String reverseRel : reverseRels) {
affordance.addRev(reverseRel); // depends on control dependency: [for], data = [reverseRel]
}
affordance.setCollectionHolder(collectionHolder);
return affordance;
} } |
public class class_name {
public void setResourceAccessPolicies(java.util.Collection<ResourceAccessPolicy> resourceAccessPolicies) {
if (resourceAccessPolicies == null) {
this.resourceAccessPolicies = null;
return;
}
this.resourceAccessPolicies = new java.util.ArrayList<ResourceAccessPolicy>(resourceAccessPolicies);
} } | public class class_name {
public void setResourceAccessPolicies(java.util.Collection<ResourceAccessPolicy> resourceAccessPolicies) {
if (resourceAccessPolicies == null) {
this.resourceAccessPolicies = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourceAccessPolicies = new java.util.ArrayList<ResourceAccessPolicy>(resourceAccessPolicies);
} } |
public class class_name {
private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) {
if (data == null || data.length == 0 || key == null || key.length == 0) return null;
try {
SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKey);
return mac.doFinal(data);
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
} } | public class class_name {
private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) {
if (data == null || data.length == 0 || key == null || key.length == 0) return null;
try {
SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKey); // depends on control dependency: [try], data = [none]
return mac.doFinal(data); // depends on control dependency: [try], data = [none]
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Nullable
public <R> R collect(@NotNull Supplier<R> supplier,
@NotNull ObjLongConsumer<R> accumulator) {
final R result = supplier.get();
while (iterator.hasNext()) {
final long value = iterator.nextLong();
accumulator.accept(result, value);
}
return result;
} } | public class class_name {
@Nullable
public <R> R collect(@NotNull Supplier<R> supplier,
@NotNull ObjLongConsumer<R> accumulator) {
final R result = supplier.get();
while (iterator.hasNext()) {
final long value = iterator.nextLong();
accumulator.accept(result, value); // depends on control dependency: [while], data = [none]
}
return result;
} } |
public class class_name {
public void freeTopology(String topId, Cluster cluster) {
Set<WorkerSlot> slots = _topIdToUsedSlots.get(topId);
if (slots == null || slots.isEmpty())
return;
for (WorkerSlot ws : slots) {
cluster.freeSlot(ws);
if (_isAlive) {
_freeSlots.add(ws);
}
}
_topIdToUsedSlots.remove(topId);
} } | public class class_name {
public void freeTopology(String topId, Cluster cluster) {
Set<WorkerSlot> slots = _topIdToUsedSlots.get(topId);
if (slots == null || slots.isEmpty())
return;
for (WorkerSlot ws : slots) {
cluster.freeSlot(ws); // depends on control dependency: [for], data = [ws]
if (_isAlive) {
_freeSlots.add(ws); // depends on control dependency: [if], data = [none]
}
}
_topIdToUsedSlots.remove(topId);
} } |
public class class_name {
public RevokeIpRulesRequest withUserRules(String... userRules) {
if (this.userRules == null) {
setUserRules(new com.amazonaws.internal.SdkInternalList<String>(userRules.length));
}
for (String ele : userRules) {
this.userRules.add(ele);
}
return this;
} } | public class class_name {
public RevokeIpRulesRequest withUserRules(String... userRules) {
if (this.userRules == null) {
setUserRules(new com.amazonaws.internal.SdkInternalList<String>(userRules.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : userRules) {
this.userRules.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private ResourceBundle getResourceBundle(@NotNull final Annotation annotation, @NotNull final Locale locale,
@NotNull final Class<?> clasz) {
if (getBundle(annotation).equals("")) {
final String path = clasz.getPackage().getName().replace('.', '/');
final String baseName = path + "/" + clasz.getSimpleName();
return ResourceBundle.getBundle(baseName, locale);
}
return ResourceBundle.getBundle(getBundle(annotation), locale);
} } | public class class_name {
private ResourceBundle getResourceBundle(@NotNull final Annotation annotation, @NotNull final Locale locale,
@NotNull final Class<?> clasz) {
if (getBundle(annotation).equals("")) {
final String path = clasz.getPackage().getName().replace('.', '/');
final String baseName = path + "/" + clasz.getSimpleName();
return ResourceBundle.getBundle(baseName, locale);
// depends on control dependency: [if], data = [none]
}
return ResourceBundle.getBundle(getBundle(annotation), locale);
} } |
public class class_name {
public ListStacksRequest withStackStatusFilters(StackStatus... stackStatusFilters) {
com.amazonaws.internal.SdkInternalList<String> stackStatusFiltersCopy = new com.amazonaws.internal.SdkInternalList<String>(stackStatusFilters.length);
for (StackStatus value : stackStatusFilters) {
stackStatusFiltersCopy.add(value.toString());
}
if (getStackStatusFilters() == null) {
setStackStatusFilters(stackStatusFiltersCopy);
} else {
getStackStatusFilters().addAll(stackStatusFiltersCopy);
}
return this;
} } | public class class_name {
public ListStacksRequest withStackStatusFilters(StackStatus... stackStatusFilters) {
com.amazonaws.internal.SdkInternalList<String> stackStatusFiltersCopy = new com.amazonaws.internal.SdkInternalList<String>(stackStatusFilters.length);
for (StackStatus value : stackStatusFilters) {
stackStatusFiltersCopy.add(value.toString()); // depends on control dependency: [for], data = [value]
}
if (getStackStatusFilters() == null) {
setStackStatusFilters(stackStatusFiltersCopy); // depends on control dependency: [if], data = [none]
} else {
getStackStatusFilters().addAll(stackStatusFiltersCopy); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {
Type resolvedType = genericType;
if (genericType instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) genericType;
resolvedType = typeVariableMap.get(tv);
if (resolvedType == null) {
resolvedType = extractBoundForTypeVariable(tv);
}
}
if (resolvedType instanceof ParameterizedType) {
return ((ParameterizedType) resolvedType).getRawType();
}
else {
return resolvedType;
}
} } | public class class_name {
static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {
Type resolvedType = genericType;
if (genericType instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) genericType;
resolvedType = typeVariableMap.get(tv); // depends on control dependency: [if], data = [none]
if (resolvedType == null) {
resolvedType = extractBoundForTypeVariable(tv); // depends on control dependency: [if], data = [none]
}
}
if (resolvedType instanceof ParameterizedType) {
return ((ParameterizedType) resolvedType).getRawType(); // depends on control dependency: [if], data = [none]
}
else {
return resolvedType; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Duration withDurationAdded(ReadableDuration durationToAdd, int scalar) {
if (durationToAdd == null || scalar == 0) {
return this;
}
return withDurationAdded(durationToAdd.getMillis(), scalar);
} } | public class class_name {
public Duration withDurationAdded(ReadableDuration durationToAdd, int scalar) {
if (durationToAdd == null || scalar == 0) {
return this; // depends on control dependency: [if], data = [none]
}
return withDurationAdded(durationToAdd.getMillis(), scalar);
} } |
public class class_name {
public final int getIndex(String name, Object... args) {
Integer defaultIndex = methodIndexs.get(name);
if (null != defaultIndex) return defaultIndex.intValue();
else {
final List<MethodInfo> exists = methods.get(name);
if (null != exists) {
for (MethodInfo info : exists)
if (info.matches(args)) return info.index;
}
return -1;
}
} } | public class class_name {
public final int getIndex(String name, Object... args) {
Integer defaultIndex = methodIndexs.get(name);
if (null != defaultIndex) return defaultIndex.intValue();
else {
final List<MethodInfo> exists = methods.get(name);
if (null != exists) {
for (MethodInfo info : exists)
if (info.matches(args)) return info.index;
}
return -1; // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.