code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static String replaceCRToken(final String original) {
String toReplace = original;
if (original != null && original.indexOf(NEWLINE_TOKEN) >= 0) {
toReplace = StringUtil.replace(NEWLINE_TOKEN, NEW_LINE, original);
}
return toReplace;
} } | public class class_name {
public static String replaceCRToken(final String original) {
String toReplace = original;
if (original != null && original.indexOf(NEWLINE_TOKEN) >= 0) {
toReplace = StringUtil.replace(NEWLINE_TOKEN, NEW_LINE, original);
// depends on control dependency: [if], data = [none]
}
return toReplace;
} } |
public class class_name {
int visitFrameStart(final int offset, final int numLocal, final int numStack) {
int frameLength = 3 + numLocal + numStack;
if (currentFrame == null || currentFrame.length < frameLength) {
currentFrame = new int[frameLength];
}
currentFrame[0] = offset;
currentFrame[1] = numLocal;
currentFrame[2] = numStack;
return 3;
} } | public class class_name {
int visitFrameStart(final int offset, final int numLocal, final int numStack) {
int frameLength = 3 + numLocal + numStack;
if (currentFrame == null || currentFrame.length < frameLength) {
currentFrame = new int[frameLength]; // depends on control dependency: [if], data = [none]
}
currentFrame[0] = offset;
currentFrame[1] = numLocal;
currentFrame[2] = numStack;
return 3;
} } |
public class class_name {
public boolean isValidating() {
if (validating && isEnabled()) {
if (getParent() instanceof ValidatingFormModel)
{
return ((ValidatingFormModel)getParent()).isValidating();
}
return true;
}
return false;
} } | public class class_name {
public boolean isValidating() {
if (validating && isEnabled()) {
if (getParent() instanceof ValidatingFormModel)
{
return ((ValidatingFormModel)getParent()).isValidating(); // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
private E[][] createAbar(E[][] array, int i, int j)
{
E[][] ret = createSameSize(array);
int height = ret.length;
int width = ret[0].length;
for (int r = 0; r < height; r++)
{
for (int s = 0; s < width; s++)
{
if ((r != i) && (s != j))
{
E det = determinant(array, r, s, i, j);
E oneOverAij = reciprocal(array[i][j]);
ret[r][s] = multiply(det, oneOverAij);
}
else if ((r != i) && (s == j))
{
E oneOverAij = reciprocal(array[i][j]);
ret[r][s] = multiply(array[r][j], oneOverAij);
}
else if ((r == i) && (s != j))
{
E oneOverAij = reciprocal(array[i][j]);
E negAis = negate(array[i][s]);
ret[r][s] = multiply(negAis, oneOverAij);
}
else if ((r == i) && (s == j))
{
E oneOverAij = reciprocal(array[i][j]);
ret[r][s] = oneOverAij;
}
else
{
throw new SecretShareException("Programmer error");
}
//System.out.println("h=" + height + " w=" + width +
// " r=" + r + " s=" + s + " val=" + ret[r][s]);
}
}
return ret;
} } | public class class_name {
private E[][] createAbar(E[][] array, int i, int j)
{
E[][] ret = createSameSize(array);
int height = ret.length;
int width = ret[0].length;
for (int r = 0; r < height; r++)
{
for (int s = 0; s < width; s++)
{
if ((r != i) && (s != j))
{
E det = determinant(array, r, s, i, j);
E oneOverAij = reciprocal(array[i][j]);
ret[r][s] = multiply(det, oneOverAij); // depends on control dependency: [if], data = [none]
}
else if ((r != i) && (s == j))
{
E oneOverAij = reciprocal(array[i][j]);
ret[r][s] = multiply(array[r][j], oneOverAij); // depends on control dependency: [if], data = [none]
}
else if ((r == i) && (s != j))
{
E oneOverAij = reciprocal(array[i][j]);
E negAis = negate(array[i][s]);
ret[r][s] = multiply(negAis, oneOverAij); // depends on control dependency: [if], data = [none]
}
else if ((r == i) && (s == j))
{
E oneOverAij = reciprocal(array[i][j]);
ret[r][s] = oneOverAij; // depends on control dependency: [if], data = [none]
}
else
{
throw new SecretShareException("Programmer error");
}
//System.out.println("h=" + height + " w=" + width +
// " r=" + r + " s=" + s + " val=" + ret[r][s]);
}
}
return ret;
} } |
public class class_name {
public static int nthOccurrenceOf(final String s, final char needle, int n) {
checkNotNull(s);
checkArgument(n > 0);
for (int i = 0; i < s.length(); ++i) {
if (needle == s.charAt(i)) {
--n;
if (n == 0) {
return i;
}
}
}
return -1;
} } | public class class_name {
public static int nthOccurrenceOf(final String s, final char needle, int n) {
checkNotNull(s);
checkArgument(n > 0);
for (int i = 0; i < s.length(); ++i) {
if (needle == s.charAt(i)) {
--n; // depends on control dependency: [if], data = [none]
if (n == 0) {
return i; // depends on control dependency: [if], data = [none]
}
}
}
return -1;
} } |
public class class_name {
public void union(GeneralSubtrees other) {
if (other != null) {
for (int i = 0, n = other.size(); i < n; i++) {
add(other.get(i));
}
// Minimize this
minimize();
}
} } | public class class_name {
public void union(GeneralSubtrees other) {
if (other != null) {
for (int i = 0, n = other.size(); i < n; i++) {
add(other.get(i)); // depends on control dependency: [for], data = [i]
}
// Minimize this
minimize(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Reference(title = "Fast and accurate computation of binomial probabilities", //
authors = "C. Loader", booktitle = "", //
url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf", //
bibkey = "web/Loader00")
private static double stirlingError(double n) {
if(n < 16.0) {
// Our table has a step size of 0.5
final double n2 = 2.0 * n;
if(FastMath.floor(n2) == n2) { // Exact match
return STIRLING_EXACT_ERROR[(int) n2];
}
else {
return GammaDistribution.logGamma(n + 1.0) - (n + 0.5) * FastMath.log(n) + n - MathUtil.LOGSQRTTWOPI;
}
}
final double nn = n * n;
if(n > 500.0) {
return (S0 - S1 / nn) / n;
}
if(n > 80.0) {
return ((S0 - (S1 - S2 / nn)) / nn) / n;
}
if(n > 35.0) {
return ((S0 - (S1 - (S2 - S3 / nn) / nn) / nn) / n);
}
return ((S0 - (S1 - (S2 - (S3 - S4 / nn) / nn) / nn) / nn) / n);
} } | public class class_name {
@Reference(title = "Fast and accurate computation of binomial probabilities", //
authors = "C. Loader", booktitle = "", //
url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf", //
bibkey = "web/Loader00")
private static double stirlingError(double n) {
if(n < 16.0) {
// Our table has a step size of 0.5
final double n2 = 2.0 * n;
if(FastMath.floor(n2) == n2) { // Exact match
return STIRLING_EXACT_ERROR[(int) n2]; // depends on control dependency: [if], data = [none]
}
else {
return GammaDistribution.logGamma(n + 1.0) - (n + 0.5) * FastMath.log(n) + n - MathUtil.LOGSQRTTWOPI; // depends on control dependency: [if], data = [none]
}
}
final double nn = n * n;
if(n > 500.0) {
return (S0 - S1 / nn) / n; // depends on control dependency: [if], data = [none]
}
if(n > 80.0) {
return ((S0 - (S1 - S2 / nn)) / nn) / n; // depends on control dependency: [if], data = [none]
}
if(n > 35.0) {
return ((S0 - (S1 - (S2 - S3 / nn) / nn) / nn) / n); // depends on control dependency: [if], data = [none]
}
return ((S0 - (S1 - (S2 - (S3 - S4 / nn) / nn) / nn) / nn) / n);
} } |
public class class_name {
public static Schema getSchema(String resource) {
Schema schema;
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(XmlHelper.class.getResource(resource));
} catch (SAXException e) {
throw new IllegalStateException("Cannot read rules schema.", e);
}
return schema;
} } | public class class_name {
public static Schema getSchema(String resource) {
Schema schema;
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(XmlHelper.class.getResource(resource)); // depends on control dependency: [try], data = [none]
} catch (SAXException e) {
throw new IllegalStateException("Cannot read rules schema.", e);
} // depends on control dependency: [catch], data = [none]
return schema;
} } |
public class class_name {
public RemoteEditLogManifest getEditLogManifest(long firstTxId) throws IOException {
File currentDir = sd.getCurrentDir();
List<EditLogFile> allLogFiles = matchEditLogs(
FileUtil.listFiles(currentDir));
if (LOG.isDebugEnabled()) {
LOG.debug(allLogFiles);
}
List<RemoteEditLog> ret = new ArrayList<RemoteEditLog>(
allLogFiles.size());
for (EditLogFile elf : allLogFiles) {
if (elf.isCorrupt()) continue;
if (elf.getFirstTxId() >= firstTxId) {
ret.add(new RemoteEditLog(elf.firstTxId,
elf.lastTxId,
elf.isInProgress));
} else if ((firstTxId > elf.getFirstTxId()) &&
(firstTxId <= elf.getLastTxId())) {
throw new IOException("Asked for firstTxId " + firstTxId
+ " which is in the middle of file " + elf.file);
}
}
Collections.sort(ret);
return new RemoteEditLogManifest(ret);
} } | public class class_name {
public RemoteEditLogManifest getEditLogManifest(long firstTxId) throws IOException {
File currentDir = sd.getCurrentDir();
List<EditLogFile> allLogFiles = matchEditLogs(
FileUtil.listFiles(currentDir));
if (LOG.isDebugEnabled()) {
LOG.debug(allLogFiles);
}
List<RemoteEditLog> ret = new ArrayList<RemoteEditLog>(
allLogFiles.size());
for (EditLogFile elf : allLogFiles) {
if (elf.isCorrupt()) continue;
if (elf.getFirstTxId() >= firstTxId) {
ret.add(new RemoteEditLog(elf.firstTxId,
elf.lastTxId,
elf.isInProgress)); // depends on control dependency: [if], data = [none]
} else if ((firstTxId > elf.getFirstTxId()) &&
(firstTxId <= elf.getLastTxId())) {
throw new IOException("Asked for firstTxId " + firstTxId
+ " which is in the middle of file " + elf.file);
}
}
Collections.sort(ret);
return new RemoteEditLogManifest(ret);
} } |
public class class_name {
private List<Rule> getStyleRules(final String styleProperty) {
final List<Rule> styleRules = new ArrayList<>(this.json.size());
for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {
String styleKey = iterator.next();
if (styleKey.equals(JSON_STYLE_PROPERTY) ||
styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {
continue;
}
PJsonObject styleJson = this.json.getJSONObject(styleKey);
final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);
for (Rule currentRule: currentRules) {
if (currentRule != null) {
styleRules.add(currentRule);
}
}
}
return styleRules;
} } | public class class_name {
private List<Rule> getStyleRules(final String styleProperty) {
final List<Rule> styleRules = new ArrayList<>(this.json.size());
for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {
String styleKey = iterator.next();
if (styleKey.equals(JSON_STYLE_PROPERTY) ||
styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {
continue;
}
PJsonObject styleJson = this.json.getJSONObject(styleKey);
final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);
for (Rule currentRule: currentRules) {
if (currentRule != null) {
styleRules.add(currentRule); // depends on control dependency: [if], data = [(currentRule]
}
}
}
return styleRules;
} } |
public class class_name {
public boolean addIfAbsent(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// Copy while checking if already present.
// This wins in the most common case where it is not present
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = new Object[len + 1];
for (int i = 0; i < len; ++i) {
if (eq(e, elements[i]))
return false; // exit, throwing away copy
else
newElements[i] = elements[i];
}
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
} } | public class class_name {
public boolean addIfAbsent(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// Copy while checking if already present.
// This wins in the most common case where it is not present
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = new Object[len + 1];
for (int i = 0; i < len; ++i) {
if (eq(e, elements[i]))
return false; // exit, throwing away copy
else
newElements[i] = elements[i];
}
newElements[len] = e; // depends on control dependency: [try], data = [none]
setArray(newElements); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} } |
public class class_name {
public CmsEntity createDeepCopy(String entityId) {
CmsEntity result = new CmsEntity(entityId, getTypeName());
for (CmsEntityAttribute attribute : getAttributes()) {
if (attribute.isSimpleValue()) {
List<String> values = attribute.getSimpleValues();
for (String value : values) {
result.addAttributeValue(attribute.getAttributeName(), value);
}
} else {
List<CmsEntity> values = attribute.getComplexValues();
for (CmsEntity value : values) {
result.addAttributeValue(attribute.getAttributeName(), value.createDeepCopy(null));
}
}
}
return result;
} } | public class class_name {
public CmsEntity createDeepCopy(String entityId) {
CmsEntity result = new CmsEntity(entityId, getTypeName());
for (CmsEntityAttribute attribute : getAttributes()) {
if (attribute.isSimpleValue()) {
List<String> values = attribute.getSimpleValues();
for (String value : values) {
result.addAttributeValue(attribute.getAttributeName(), value);
// depends on control dependency: [for], data = [value]
}
} else {
List<CmsEntity> values = attribute.getComplexValues();
for (CmsEntity value : values) {
result.addAttributeValue(attribute.getAttributeName(), value.createDeepCopy(null));
// depends on control dependency: [for], data = [value]
}
}
}
return result;
} } |
public class class_name {
public static boolean isSnapshotableStreamedTableView(Database db, Table table) {
Table materializer = table.getMaterializer();
if (materializer == null) {
// Return false if it is not a materialized view.
return false;
}
if (! CatalogUtil.isTableExportOnly(db, materializer)) {
// Test if the view source table is a streamed table.
return false;
}
// Non-partitioned export table are not allowed so it should not get here.
Column sourcePartitionColumn = materializer.getPartitioncolumn();
if (sourcePartitionColumn == null) {
return false;
}
// Make sure the partition column is present in the view.
// Export table views are special, we use column names to match..
Column pc = table.getColumns().get(sourcePartitionColumn.getName());
if (pc == null) {
return false;
}
return true;
} } | public class class_name {
public static boolean isSnapshotableStreamedTableView(Database db, Table table) {
Table materializer = table.getMaterializer();
if (materializer == null) {
// Return false if it is not a materialized view.
return false; // depends on control dependency: [if], data = [none]
}
if (! CatalogUtil.isTableExportOnly(db, materializer)) {
// Test if the view source table is a streamed table.
return false; // depends on control dependency: [if], data = [none]
}
// Non-partitioned export table are not allowed so it should not get here.
Column sourcePartitionColumn = materializer.getPartitioncolumn();
if (sourcePartitionColumn == null) {
return false; // depends on control dependency: [if], data = [none]
}
// Make sure the partition column is present in the view.
// Export table views are special, we use column names to match..
Column pc = table.getColumns().get(sourcePartitionColumn.getName());
if (pc == null) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public static boolean requireIfAvailable(Ruby ruby, String requirement, boolean logErrors) {
boolean success = false;
try {
StringBuilder script = new StringBuilder();
script.append("require %q(");
script.append(requirement);
script.append(")\n");
evalScriptlet( ruby, script.toString(), false );
success = true;
} catch (Throwable t) {
success = false;
if (logErrors) {
log.debug( "Error encountered. Unable to require file: " + requirement, t );
}
}
return success;
} } | public class class_name {
public static boolean requireIfAvailable(Ruby ruby, String requirement, boolean logErrors) {
boolean success = false;
try {
StringBuilder script = new StringBuilder();
script.append("require %q(");
script.append(requirement);
script.append(")\n"); // depends on control dependency: [try], data = [none]
evalScriptlet( ruby, script.toString(), false ); // depends on control dependency: [try], data = [none]
success = true; // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
success = false;
if (logErrors) {
log.debug( "Error encountered. Unable to require file: " + requirement, t ); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return success;
} } |
public class class_name {
public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {
final HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);
if( innerMap1 != null ) {
return new TwoDHashMap<K2, K3, V>(innerMap1);
} else {
return new TwoDHashMap<K2, K3, V>();
}
} } | public class class_name {
public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {
final HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);
if( innerMap1 != null ) {
return new TwoDHashMap<K2, K3, V>(innerMap1); // depends on control dependency: [if], data = [none]
} else {
return new TwoDHashMap<K2, K3, V>(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static void installPear(File localPearFile, File installationDir) {
InstallationController.setLocalMode(true);
InstallationDescriptorHandler installationDescriptorHandler = new InstallationDescriptorHandler();
printInConsole(false, "");
// check input parameters
if (localPearFile != null && !localPearFile.exists()) {
errorFlag = true;
message = localPearFile.getAbsolutePath() + "file not found \n";
printInConsole(errorFlag, message);
} else {
if (localPearFile != null) {
pearConsole.append("PEAR file to install is => " + localPearFile.getAbsolutePath() + "\n");
}
}
/* setting current working directory by default */
if (installationDir == null) {
installationDir = new File("./");
}
pearConsole.append("Installation directory is => " + installationDir.getAbsolutePath() + "\n");
try {
JarFile jarFile = new JarFile(localPearFile);
installationDescriptorHandler.parseInstallationDescriptor(jarFile);
insdObject = installationDescriptorHandler.getInstallationDescriptor();
if (insdObject != null)
mainComponentId = insdObject.getMainComponentId();
else {
// pearConsole.setForeground(new Color(0xFF0000));
throw new FileNotFoundException("installation descriptor not found \n");
}
// this version does not support separate delegate components
if (insdObject.getDelegateComponents().size() > 0) {
throw new RuntimeException("separate delegate components not supported \n");
}
} catch (Exception err) {
errorFlag = true;
message = " terminated \n" + err.toString();
printInConsole(errorFlag, message);
System.exit(-1);
}
InstallationController installationController = new InstallationController(mainComponentId,
localPearFile, installationDir);
// adding installation controller message listener
installationController.addMsgListener(new MessageRouter.StdChannelListener() {
public void errMsgPosted(String errMsg) {
printInConsole(true, errMsg);
}
public void outMsgPosted(String outMsg) {
printInConsole(false, outMsg);
}
});
insdObject = installationController.installComponent();
if (insdObject == null) {
// runButton.setEnabled(false);
/* installation failed */
errorFlag = true;
message = " \nInstallation of " + mainComponentId + " failed => \n "
+ installationController.getInstallationMsg();
printInConsole(errorFlag, message);
} else {
try {
/* save modified installation descriptor file */
installationController.saveInstallationDescriptorFile();
mainComponentRootPath = insdObject.getMainComponentRoot();
errorFlag = false;
message = " \nInstallation of " + mainComponentId + " completed \n";
printInConsole(errorFlag, message);
message = "The " + mainComponentRootPath + "/" + SET_ENV_FILE
+ " \n file contains required " + "environment variables for this component\n";
printInConsole(errorFlag, message);
/* 2nd step: verification of main component installation */
if (installationController.verifyComponent()) {
// enable 'run' button only for AE
File xmlDescFile = new File(insdObject.getMainComponentDesc());
try {
String uimaCompCtg = UIMAUtil.identifyUimaComponentCategory(xmlDescFile);
} catch (Exception e) {
// Ignore exceptions!
}
errorFlag = false;
message = "Verification of " + mainComponentId + " completed \n";
printInConsole(errorFlag, message);
} else {
errorFlag = true;
message = "Verification of " + mainComponentId + " failed => \n "
+ installationController.getVerificationMsg();
printInConsole(errorFlag, message);
}
} catch (Exception exc) {
errorFlag = true;
message = "Error in InstallationController.main(): " + exc.toString();
printInConsole(errorFlag, message);
} finally {
installationController.terminate();
}
}
if(errorFlag) {
System.exit(-1);
}
} } | public class class_name {
private static void installPear(File localPearFile, File installationDir) {
InstallationController.setLocalMode(true);
InstallationDescriptorHandler installationDescriptorHandler = new InstallationDescriptorHandler();
printInConsole(false, "");
// check input parameters
if (localPearFile != null && !localPearFile.exists()) {
errorFlag = true; // depends on control dependency: [if], data = [none]
message = localPearFile.getAbsolutePath() + "file not found \n"; // depends on control dependency: [if], data = [none]
printInConsole(errorFlag, message); // depends on control dependency: [if], data = [none]
} else {
if (localPearFile != null) {
pearConsole.append("PEAR file to install is => " + localPearFile.getAbsolutePath() + "\n"); // depends on control dependency: [if], data = [none]
}
}
/* setting current working directory by default */
if (installationDir == null) {
installationDir = new File("./"); // depends on control dependency: [if], data = [none]
}
pearConsole.append("Installation directory is => " + installationDir.getAbsolutePath() + "\n");
try {
JarFile jarFile = new JarFile(localPearFile);
installationDescriptorHandler.parseInstallationDescriptor(jarFile); // depends on control dependency: [try], data = [none]
insdObject = installationDescriptorHandler.getInstallationDescriptor(); // depends on control dependency: [try], data = [none]
if (insdObject != null)
mainComponentId = insdObject.getMainComponentId();
else {
// pearConsole.setForeground(new Color(0xFF0000));
throw new FileNotFoundException("installation descriptor not found \n");
}
// this version does not support separate delegate components
if (insdObject.getDelegateComponents().size() > 0) {
throw new RuntimeException("separate delegate components not supported \n");
}
} catch (Exception err) {
errorFlag = true;
message = " terminated \n" + err.toString();
printInConsole(errorFlag, message);
System.exit(-1);
} // depends on control dependency: [catch], data = [none]
InstallationController installationController = new InstallationController(mainComponentId,
localPearFile, installationDir);
// adding installation controller message listener
installationController.addMsgListener(new MessageRouter.StdChannelListener() {
public void errMsgPosted(String errMsg) {
printInConsole(true, errMsg);
}
public void outMsgPosted(String outMsg) {
printInConsole(false, outMsg);
}
});
insdObject = installationController.installComponent();
if (insdObject == null) {
// runButton.setEnabled(false);
/* installation failed */
errorFlag = true; // depends on control dependency: [if], data = [none]
message = " \nInstallation of " + mainComponentId + " failed => \n "
+ installationController.getInstallationMsg(); // depends on control dependency: [if], data = [none]
printInConsole(errorFlag, message); // depends on control dependency: [if], data = [none]
} else {
try {
/* save modified installation descriptor file */
installationController.saveInstallationDescriptorFile(); // depends on control dependency: [try], data = [none]
mainComponentRootPath = insdObject.getMainComponentRoot(); // depends on control dependency: [try], data = [none]
errorFlag = false; // depends on control dependency: [try], data = [none]
message = " \nInstallation of " + mainComponentId + " completed \n"; // depends on control dependency: [try], data = [none]
printInConsole(errorFlag, message); // depends on control dependency: [try], data = [none]
message = "The " + mainComponentRootPath + "/" + SET_ENV_FILE
+ " \n file contains required " + "environment variables for this component\n"; // depends on control dependency: [try], data = [none]
printInConsole(errorFlag, message); // depends on control dependency: [try], data = [none]
/* 2nd step: verification of main component installation */
if (installationController.verifyComponent()) {
// enable 'run' button only for AE
File xmlDescFile = new File(insdObject.getMainComponentDesc());
try {
String uimaCompCtg = UIMAUtil.identifyUimaComponentCategory(xmlDescFile);
} catch (Exception e) {
// Ignore exceptions!
} // depends on control dependency: [catch], data = [none]
errorFlag = false; // depends on control dependency: [if], data = [none]
message = "Verification of " + mainComponentId + " completed \n"; // depends on control dependency: [if], data = [none]
printInConsole(errorFlag, message); // depends on control dependency: [if], data = [none]
} else {
errorFlag = true; // depends on control dependency: [if], data = [none]
message = "Verification of " + mainComponentId + " failed => \n "
+ installationController.getVerificationMsg(); // depends on control dependency: [if], data = [none]
printInConsole(errorFlag, message); // depends on control dependency: [if], data = [none]
}
} catch (Exception exc) {
errorFlag = true;
message = "Error in InstallationController.main(): " + exc.toString();
printInConsole(errorFlag, message);
} finally { // depends on control dependency: [catch], data = [none]
installationController.terminate();
}
}
if(errorFlag) {
System.exit(-1); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static BufferedImage toBufferedImage(Image image, String imageType) {
BufferedImage bufferedImage;
if (false == imageType.equalsIgnoreCase(IMAGE_TYPE_PNG)) {
// 当目标为非PNG类图片时,源图片统一转换为RGB格式
if (image instanceof BufferedImage) {
bufferedImage = (BufferedImage) image;
if (BufferedImage.TYPE_INT_RGB != bufferedImage.getType()) {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
}
} else {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
}
} else {
bufferedImage = toBufferedImage(image);
}
return bufferedImage;
} } | public class class_name {
public static BufferedImage toBufferedImage(Image image, String imageType) {
BufferedImage bufferedImage;
if (false == imageType.equalsIgnoreCase(IMAGE_TYPE_PNG)) {
// 当目标为非PNG类图片时,源图片统一转换为RGB格式
if (image instanceof BufferedImage) {
bufferedImage = (BufferedImage) image;
// depends on control dependency: [if], data = [none]
if (BufferedImage.TYPE_INT_RGB != bufferedImage.getType()) {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
// depends on control dependency: [if], data = [none]
}
} else {
bufferedImage = copyImage(image, BufferedImage.TYPE_INT_RGB);
// depends on control dependency: [if], data = [none]
}
} else {
bufferedImage = toBufferedImage(image);
// depends on control dependency: [if], data = [none]
}
return bufferedImage;
} } |
public class class_name {
@Override
public DMatrixRMaj getR(DMatrixRMaj R, boolean compact) {
if( compact ) {
R = UtilDecompositons_DDRM.checkZerosLT(R,minLength,numCols);
} else {
R = UtilDecompositons_DDRM.checkZerosLT(R,numRows,numCols);
}
for( int j = 0; j < numCols; j++ ) {
double colR[] = dataQR[j];
int l = Math.min(j,numRows-1);
for( int i = 0; i <= l; i++ ) {
double val = colR[i];
R.set(i,j,val);
}
}
return R;
} } | public class class_name {
@Override
public DMatrixRMaj getR(DMatrixRMaj R, boolean compact) {
if( compact ) {
R = UtilDecompositons_DDRM.checkZerosLT(R,minLength,numCols); // depends on control dependency: [if], data = [none]
} else {
R = UtilDecompositons_DDRM.checkZerosLT(R,numRows,numCols); // depends on control dependency: [if], data = [none]
}
for( int j = 0; j < numCols; j++ ) {
double colR[] = dataQR[j];
int l = Math.min(j,numRows-1);
for( int i = 0; i <= l; i++ ) {
double val = colR[i];
R.set(i,j,val); // depends on control dependency: [for], data = [i]
}
}
return R;
} } |
public class class_name {
private static boolean inRing(Point pt, List<Point> ring) {
boolean isInside = false;
for (int i = 0, j = ring.size() - 1; i < ring.size(); j = i++) {
double xi = ring.get(i).longitude();
double yi = ring.get(i).latitude();
double xj = ring.get(j).longitude();
double yj = ring.get(j).latitude();
boolean intersect = (
(yi > pt.latitude()) != (yj > pt.latitude()))
&& (pt.longitude() < (xj - xi) * (pt.latitude() - yi) / (yj - yi) + xi);
if (intersect) {
isInside = !isInside;
}
}
return isInside;
} } | public class class_name {
private static boolean inRing(Point pt, List<Point> ring) {
boolean isInside = false;
for (int i = 0, j = ring.size() - 1; i < ring.size(); j = i++) {
double xi = ring.get(i).longitude();
double yi = ring.get(i).latitude();
double xj = ring.get(j).longitude();
double yj = ring.get(j).latitude();
boolean intersect = (
(yi > pt.latitude()) != (yj > pt.latitude()))
&& (pt.longitude() < (xj - xi) * (pt.latitude() - yi) / (yj - yi) + xi);
if (intersect) {
isInside = !isInside; // depends on control dependency: [if], data = [none]
}
}
return isInside;
} } |
public class class_name {
public CreateJobQueueRequest withComputeEnvironmentOrder(ComputeEnvironmentOrder... computeEnvironmentOrder) {
if (this.computeEnvironmentOrder == null) {
setComputeEnvironmentOrder(new java.util.ArrayList<ComputeEnvironmentOrder>(computeEnvironmentOrder.length));
}
for (ComputeEnvironmentOrder ele : computeEnvironmentOrder) {
this.computeEnvironmentOrder.add(ele);
}
return this;
} } | public class class_name {
public CreateJobQueueRequest withComputeEnvironmentOrder(ComputeEnvironmentOrder... computeEnvironmentOrder) {
if (this.computeEnvironmentOrder == null) {
setComputeEnvironmentOrder(new java.util.ArrayList<ComputeEnvironmentOrder>(computeEnvironmentOrder.length)); // depends on control dependency: [if], data = [none]
}
for (ComputeEnvironmentOrder ele : computeEnvironmentOrder) {
this.computeEnvironmentOrder.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void release(AndroidDevice device, AndroidApp aut) {
log.info("Releasing device " + device);
if (devicesInUse.contains(device)) {
if (aut != null) {
// stop the app anyway - better in case people do use snapshots
try {
device.kill(aut);
} catch (Exception e) {
log.log(Level.WARNING, "Failed to kill android application when releasing device", e);
}
if (clearData) {
try {
device.clearUserData(aut);
} catch (AndroidSdkException e) {
log.log(Level.WARNING, "Failed to clear user data of application", e);
}
}
}
if (device instanceof AndroidEmulator && !(aut instanceof InstalledAndroidApp) && !keepEmulator) {
AndroidEmulator emulator = (AndroidEmulator) device;
try {
emulator.stop();
} catch (AndroidDeviceException e) {
log.severe("Failed to stop emulator: " + e.getMessage());
}
androidEmulatorPortFinder.release(emulator.getPort());
}
devicesInUse.remove(device);
}
} } | public class class_name {
public void release(AndroidDevice device, AndroidApp aut) {
log.info("Releasing device " + device);
if (devicesInUse.contains(device)) {
if (aut != null) {
// stop the app anyway - better in case people do use snapshots
try {
device.kill(aut); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.log(Level.WARNING, "Failed to kill android application when releasing device", e);
} // depends on control dependency: [catch], data = [none]
if (clearData) {
try {
device.clearUserData(aut); // depends on control dependency: [try], data = [none]
} catch (AndroidSdkException e) {
log.log(Level.WARNING, "Failed to clear user data of application", e);
} // depends on control dependency: [catch], data = [none]
}
}
if (device instanceof AndroidEmulator && !(aut instanceof InstalledAndroidApp) && !keepEmulator) {
AndroidEmulator emulator = (AndroidEmulator) device;
try {
emulator.stop(); // depends on control dependency: [try], data = [none]
} catch (AndroidDeviceException e) {
log.severe("Failed to stop emulator: " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
androidEmulatorPortFinder.release(emulator.getPort()); // depends on control dependency: [if], data = [none]
}
devicesInUse.remove(device); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void received(ByteBuffer deflated) {
if (ended) {
throw new IllegalStateException();
}
if (deflated.remaining() >= FOOTER_LENGTH) {
for (ByteBuffer b : previewFooter) {
if (!read(b)) {
return;
}
}
previewFooter.clear();
currentPreviewFooterLength = 0;
ByteBuffer deflatedKeepingFooter = deflated.duplicate();
deflatedKeepingFooter.limit(deflatedKeepingFooter.limit() - FOOTER_LENGTH);
deflated.position(deflated.position() + deflatedKeepingFooter.remaining());
if (!read(deflatedKeepingFooter)) {
return;
}
currentPreviewFooterLength += deflated.remaining();
previewFooter.addLast(deflated.duplicate());
deflated.position(deflated.position() + deflated.remaining());
return;
} else {
currentPreviewFooterLength += deflated.remaining();
previewFooter.addLast(deflated.duplicate());
deflated.position(deflated.position() + deflated.remaining());
int toFlush = FOOTER_LENGTH - currentPreviewFooterLength;
while (toFlush > 0) {
ByteBuffer b = previewFooter.getFirst();
ByteBuffer d = b.duplicate();
d.limit(Math.min(d.limit(), toFlush));
b.position(b.position() + d.remaining());
toFlush -= d.remaining();
if (!read(d)) {
return;
}
if (!b.hasRemaining()) {
previewFooter.removeFirst();
}
}
}
} } | public class class_name {
@Override
public void received(ByteBuffer deflated) {
if (ended) {
throw new IllegalStateException();
}
if (deflated.remaining() >= FOOTER_LENGTH) {
for (ByteBuffer b : previewFooter) {
if (!read(b)) {
return; // depends on control dependency: [if], data = [none]
}
}
previewFooter.clear(); // depends on control dependency: [if], data = [none]
currentPreviewFooterLength = 0; // depends on control dependency: [if], data = [none]
ByteBuffer deflatedKeepingFooter = deflated.duplicate();
deflatedKeepingFooter.limit(deflatedKeepingFooter.limit() - FOOTER_LENGTH); // depends on control dependency: [if], data = [none]
deflated.position(deflated.position() + deflatedKeepingFooter.remaining()); // depends on control dependency: [if], data = [none]
if (!read(deflatedKeepingFooter)) {
return; // depends on control dependency: [if], data = [none]
}
currentPreviewFooterLength += deflated.remaining(); // depends on control dependency: [if], data = [none]
previewFooter.addLast(deflated.duplicate()); // depends on control dependency: [if], data = [none]
deflated.position(deflated.position() + deflated.remaining()); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
} else {
currentPreviewFooterLength += deflated.remaining(); // depends on control dependency: [if], data = [none]
previewFooter.addLast(deflated.duplicate()); // depends on control dependency: [if], data = [none]
deflated.position(deflated.position() + deflated.remaining()); // depends on control dependency: [if], data = [none]
int toFlush = FOOTER_LENGTH - currentPreviewFooterLength;
while (toFlush > 0) {
ByteBuffer b = previewFooter.getFirst();
ByteBuffer d = b.duplicate();
d.limit(Math.min(d.limit(), toFlush)); // depends on control dependency: [while], data = [none]
b.position(b.position() + d.remaining()); // depends on control dependency: [while], data = [none]
toFlush -= d.remaining(); // depends on control dependency: [while], data = [none]
if (!read(d)) {
return; // depends on control dependency: [if], data = [none]
}
if (!b.hasRemaining()) {
previewFooter.removeFirst(); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private T select(T[] population) {
double worst = population[0].fitness();
double[] fitness = new double[size];
switch (selection) {
case ROULETTE_WHEEL:
if (worst > 0.0) {
worst = 0.0;
}
// In Roulete wheel selection, we don't do such scaling in
// general. However, in case of negative fitness socres,
// we need scale them to positive.
for (int i = 0; i < size; i++) {
fitness[i] = population[i].fitness() - worst;
}
Math.unitize1(fitness);
return population[Math.random(fitness)];
case SCALED_ROULETTE_WHEEL:
for (int i = 0; i < size; i++) {
fitness[i] = population[i].fitness() - worst;
}
Math.unitize1(fitness);
return population[Math.random(fitness)];
case RANK:
for (int i = 0; i < size; i++) {
fitness[i] = i + 1;
}
Math.unitize1(fitness);
return population[Math.random(fitness)];
case TOURNAMENT:
Chromosome[] pool = new Chromosome[tournamentSize];
for (int i = 0; i < tournamentSize; i++) {
pool[i] = population[Math.randomInt(size)];
}
Arrays.sort(pool);
for (int i = 1; i <= tournamentSize; i++) {
double p = Math.random();
if (p < tournamentProbability) {
return (T) pool[tournamentSize - i];
}
}
return (T) pool[tournamentSize - 1];
}
return null;
} } | public class class_name {
@SuppressWarnings("unchecked")
private T select(T[] population) {
double worst = population[0].fitness();
double[] fitness = new double[size];
switch (selection) {
case ROULETTE_WHEEL:
if (worst > 0.0) {
worst = 0.0; // depends on control dependency: [if], data = [none]
}
// In Roulete wheel selection, we don't do such scaling in
// general. However, in case of negative fitness socres,
// we need scale them to positive.
for (int i = 0; i < size; i++) {
fitness[i] = population[i].fitness() - worst; // depends on control dependency: [for], data = [i]
}
Math.unitize1(fitness);
return population[Math.random(fitness)];
case SCALED_ROULETTE_WHEEL:
for (int i = 0; i < size; i++) {
fitness[i] = population[i].fitness() - worst; // depends on control dependency: [for], data = [i]
}
Math.unitize1(fitness);
return population[Math.random(fitness)];
case RANK:
for (int i = 0; i < size; i++) {
fitness[i] = i + 1; // depends on control dependency: [for], data = [i]
}
Math.unitize1(fitness);
return population[Math.random(fitness)];
case TOURNAMENT:
Chromosome[] pool = new Chromosome[tournamentSize];
for (int i = 0; i < tournamentSize; i++) {
pool[i] = population[Math.randomInt(size)]; // depends on control dependency: [for], data = [i]
}
Arrays.sort(pool);
for (int i = 1; i <= tournamentSize; i++) {
double p = Math.random();
if (p < tournamentProbability) {
return (T) pool[tournamentSize - i]; // depends on control dependency: [if], data = [none]
}
}
return (T) pool[tournamentSize - 1];
}
return null;
} } |
public class class_name {
public void setTimeZone(TimeZone timeZone) {
if ( this.cronEx != null ) {
this.cronEx.setTimeZone( timeZone );
}
this.timeZone = timeZone;
} } | public class class_name {
public void setTimeZone(TimeZone timeZone) {
if ( this.cronEx != null ) {
this.cronEx.setTimeZone( timeZone ); // depends on control dependency: [if], data = [none]
}
this.timeZone = timeZone;
} } |
public class class_name {
public static ImageIcon loadImageIcon(final String iconName, final Class<?> clazz) {
ImageIcon icon = null;
if (iconName != null) {
final URL iconResource = clazz.getResource(iconName);
if (iconResource == null) {
LOGGER.error("Icon could not be loaded: '" + iconName);
icon = null;
} else {
icon = new ImageIcon(iconResource);
}
}
return icon;
} } | public class class_name {
public static ImageIcon loadImageIcon(final String iconName, final Class<?> clazz) {
ImageIcon icon = null;
if (iconName != null) {
final URL iconResource = clazz.getResource(iconName);
if (iconResource == null) {
LOGGER.error("Icon could not be loaded: '" + iconName); // depends on control dependency: [if], data = [none]
icon = null; // depends on control dependency: [if], data = [none]
} else {
icon = new ImageIcon(iconResource); // depends on control dependency: [if], data = [(iconResource]
}
}
return icon;
} } |
public class class_name {
private boolean shouldSkipScan() {
if (this.getExtension() == null) {
return true;
}
List<ScriptWrapper> scripts = getActiveScripts();
if (scripts.isEmpty()) {
return true;
}
for (ScriptWrapper script : scripts) {
if (script.isEnabled()) {
return false;
}
}
return true;
} } | public class class_name {
private boolean shouldSkipScan() {
if (this.getExtension() == null) {
return true;
// depends on control dependency: [if], data = [none]
}
List<ScriptWrapper> scripts = getActiveScripts();
if (scripts.isEmpty()) {
return true;
// depends on control dependency: [if], data = [none]
}
for (ScriptWrapper script : scripts) {
if (script.isEnabled()) {
return false;
// depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private void onSetSubComparator(CfDef cfDef, Properties cfProperties, StringBuilder builder)
{
String subComparatorType = cfProperties.getProperty(CassandraConstants.SUBCOMPARATOR_TYPE);
if (subComparatorType != null && ColumnFamilyType.valueOf(cfDef.getColumn_type()) == ColumnFamilyType.Super)
{
if (builder != null)
{
// super column are not supported for composite key as of
// now, leaving blank place holder..
}
else
{
cfDef.setSubcomparator_type(subComparatorType);
}
}
} } | public class class_name {
private void onSetSubComparator(CfDef cfDef, Properties cfProperties, StringBuilder builder)
{
String subComparatorType = cfProperties.getProperty(CassandraConstants.SUBCOMPARATOR_TYPE);
if (subComparatorType != null && ColumnFamilyType.valueOf(cfDef.getColumn_type()) == ColumnFamilyType.Super)
{
if (builder != null)
{
// super column are not supported for composite key as of
// now, leaving blank place holder..
}
else
{
cfDef.setSubcomparator_type(subComparatorType); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean isTokenValid(final HttpServletRequest request, final String key) {
String token = request.getParameter(key);
if (StringUtils.isBlank(token)) {
return false;
}
String session = (String) request.getSession(true).getAttribute(key);
return token.equals(session);
} } | public class class_name {
public static boolean isTokenValid(final HttpServletRequest request, final String key) {
String token = request.getParameter(key);
if (StringUtils.isBlank(token)) {
return false; // depends on control dependency: [if], data = [none]
}
String session = (String) request.getSession(true).getAttribute(key);
return token.equals(session);
} } |
public class class_name {
public void marshall(GetKeyPairsRequest getKeyPairsRequest, ProtocolMarshaller protocolMarshaller) {
if (getKeyPairsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getKeyPairsRequest.getPageToken(), PAGETOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetKeyPairsRequest getKeyPairsRequest, ProtocolMarshaller protocolMarshaller) {
if (getKeyPairsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getKeyPairsRequest.getPageToken(), PAGETOKEN_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 void startElement(final String uri, final String localName, final String qName, final Attributes atts)
throws SAXException {
depth++;
if (depth == 1) {
super.startPrefixMapping(DITA_OT_NS_PREFIX, DITA_OT_NS);
}
AttributesImpl res = null;
final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (MAP_MAP.matches(cls)) {
if (atts.getIndex(ATTRIBUTE_NAME_CASCADE) == -1) {
if (res == null) {
res = new AttributesImpl(atts);
}
XMLUtils.addOrSetAttribute(res, ATTRIBUTE_NAME_CASCADE,
configuration.getOrDefault("default.cascade", ATTRIBUTE_CASCADE_VALUE_MERGE));
}
}
if (MAP_MAP.matches(cls) || TOPIC_TOPIC.matches(cls)) {
final String domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS);
if (domains != null) {
final String normalized = whitespace.matcher(domains.trim()).replaceAll(" ");
if (res == null) {
res = new AttributesImpl(atts);
}
XMLUtils.addOrSetAttribute(res, ATTRIBUTE_NAME_DOMAINS, normalized);
}
}
getContentHandler().startElement(uri, localName, qName, res != null ? res : atts);
} } | public class class_name {
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts)
throws SAXException {
depth++;
if (depth == 1) {
super.startPrefixMapping(DITA_OT_NS_PREFIX, DITA_OT_NS);
}
AttributesImpl res = null;
final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS);
if (MAP_MAP.matches(cls)) {
if (atts.getIndex(ATTRIBUTE_NAME_CASCADE) == -1) {
if (res == null) {
res = new AttributesImpl(atts); // depends on control dependency: [if], data = [none]
}
XMLUtils.addOrSetAttribute(res, ATTRIBUTE_NAME_CASCADE,
configuration.getOrDefault("default.cascade", ATTRIBUTE_CASCADE_VALUE_MERGE)); // depends on control dependency: [if], data = [none]
}
}
if (MAP_MAP.matches(cls) || TOPIC_TOPIC.matches(cls)) {
final String domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS);
if (domains != null) {
final String normalized = whitespace.matcher(domains.trim()).replaceAll(" ");
if (res == null) {
res = new AttributesImpl(atts);
}
XMLUtils.addOrSetAttribute(res, ATTRIBUTE_NAME_DOMAINS, normalized);
}
}
getContentHandler().startElement(uri, localName, qName, res != null ? res : atts);
} } |
public class class_name {
private static boolean isBinary(InputStream in) {
try {
int size = in.available();
if (size > 1024) size = 1024;
byte[] data = new byte[size];
in.read(data);
in.close();
int ascii = 0;
int other = 0;
for (int i = 0; i < data.length; i++) {
byte b = data[i];
if (b < 0x09) return true;
if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++;
else if (b >= 0x20 && b <= 0x7E) ascii++;
else other++;
}
return other != 0 && 100 * other / (ascii + other) > 95;
} catch (IOException e) {
throw E.ioException(e);
}
} } | public class class_name {
private static boolean isBinary(InputStream in) {
try {
int size = in.available();
if (size > 1024) size = 1024;
byte[] data = new byte[size];
in.read(data); // depends on control dependency: [try], data = [none]
in.close(); // depends on control dependency: [try], data = [none]
int ascii = 0;
int other = 0;
for (int i = 0; i < data.length; i++) {
byte b = data[i];
if (b < 0x09) return true;
if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++;
else if (b >= 0x20 && b <= 0x7E) ascii++;
else other++;
}
return other != 0 && 100 * other / (ascii + other) > 95; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw E.ioException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String readFileToString(File file) {
byte[] bts = null;
try {
bts = readFileToBytes(file);
} catch (Exception e) {
e.printStackTrace();
}
String content = null;
try {
content = new String(bts, getEncode(file));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return content;
} } | public class class_name {
public static String readFileToString(File file) {
byte[] bts = null;
try {
bts = readFileToBytes(file); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
String content = null;
try {
content = new String(bts, getEncode(file)); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return content;
} } |
public class class_name {
@Override
protected Observable resumeWithFallback() {
if (commandActions.hasFallbackAction()) {
MetaHolder metaHolder = commandActions.getFallbackAction().getMetaHolder();
Throwable cause = getExecutionException();
if (cause instanceof CommandActionExecutionException) {
cause = cause.getCause();
}
Object[] args = createArgsForFallback(metaHolder, cause);
try {
Object res = commandActions.getFallbackAction().executeWithArgs(executionType, args);
if (res instanceof Observable) {
return (Observable) res;
} else if (res instanceof Single) {
return ((Single) res).toObservable();
} else if (res instanceof Completable) {
return ((Completable) res).toObservable();
} else {
return Observable.just(res);
}
} catch (Exception e) {
LOGGER.error(AbstractHystrixCommand.FallbackErrorMessageBuilder.create()
.append(commandActions.getFallbackAction(), e).build());
throw new FallbackInvocationException(e.getCause());
}
}
return super.resumeWithFallback();
} } | public class class_name {
@Override
protected Observable resumeWithFallback() {
if (commandActions.hasFallbackAction()) {
MetaHolder metaHolder = commandActions.getFallbackAction().getMetaHolder();
Throwable cause = getExecutionException();
if (cause instanceof CommandActionExecutionException) {
cause = cause.getCause(); // depends on control dependency: [if], data = [none]
}
Object[] args = createArgsForFallback(metaHolder, cause);
try {
Object res = commandActions.getFallbackAction().executeWithArgs(executionType, args);
if (res instanceof Observable) {
return (Observable) res; // depends on control dependency: [if], data = [none]
} else if (res instanceof Single) {
return ((Single) res).toObservable(); // depends on control dependency: [if], data = [none]
} else if (res instanceof Completable) {
return ((Completable) res).toObservable(); // depends on control dependency: [if], data = [none]
} else {
return Observable.just(res); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
LOGGER.error(AbstractHystrixCommand.FallbackErrorMessageBuilder.create()
.append(commandActions.getFallbackAction(), e).build());
throw new FallbackInvocationException(e.getCause());
} // depends on control dependency: [catch], data = [none]
}
return super.resumeWithFallback();
} } |
public class class_name {
public final synchronized void deleteAttribute(String view, String attribute) {
if (attributes != null) {
attributes.remove(view, attribute);
}
} } | public class class_name {
public final synchronized void deleteAttribute(String view, String attribute) {
if (attributes != null) {
attributes.remove(view, attribute); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void rebuildIndexOneEntity(String entityTypeId, String untypedEntityId) {
LOG.trace("Indexing [{}].[{}]... ", entityTypeId, untypedEntityId);
// convert entity id string to typed entity id
EntityType entityType = dataService.getEntityType(entityTypeId);
if (null != entityType) {
Object entityId = getTypedValue(untypedEntityId, entityType.getIdAttribute());
String entityFullName = entityType.getId();
Entity actualEntity = dataService.findOneById(entityFullName, entityId);
if (null == actualEntity) {
// Delete
LOG.debug("Index delete [{}].[{}].", entityFullName, entityId);
indexService.deleteById(entityType, entityId);
return;
}
boolean indexEntityExists = indexService.hasIndex(entityType);
if (!indexEntityExists) {
LOG.debug("Create mapping of repository [{}] because it was not exist yet", entityTypeId);
indexService.createIndex(entityType);
}
LOG.debug("Index [{}].[{}].", entityTypeId, entityId);
indexService.index(actualEntity.getEntityType(), actualEntity);
} else {
throw new MolgenisDataException("Unknown EntityType for entityTypeId: " + entityTypeId);
}
} } | public class class_name {
private void rebuildIndexOneEntity(String entityTypeId, String untypedEntityId) {
LOG.trace("Indexing [{}].[{}]... ", entityTypeId, untypedEntityId);
// convert entity id string to typed entity id
EntityType entityType = dataService.getEntityType(entityTypeId);
if (null != entityType) {
Object entityId = getTypedValue(untypedEntityId, entityType.getIdAttribute());
String entityFullName = entityType.getId();
Entity actualEntity = dataService.findOneById(entityFullName, entityId);
if (null == actualEntity) {
// Delete
LOG.debug("Index delete [{}].[{}].", entityFullName, entityId); // depends on control dependency: [if], data = [none]
indexService.deleteById(entityType, entityId); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
boolean indexEntityExists = indexService.hasIndex(entityType);
if (!indexEntityExists) {
LOG.debug("Create mapping of repository [{}] because it was not exist yet", entityTypeId); // depends on control dependency: [if], data = [none]
indexService.createIndex(entityType); // depends on control dependency: [if], data = [none]
}
LOG.debug("Index [{}].[{}].", entityTypeId, entityId); // depends on control dependency: [if], data = [none]
indexService.index(actualEntity.getEntityType(), actualEntity); // depends on control dependency: [if], data = [none]
} else {
throw new MolgenisDataException("Unknown EntityType for entityTypeId: " + entityTypeId);
}
} } |
public class class_name {
public static ProtectionDomain getScriptProtectionDomain() {
final SecurityManager securityManager = System.getSecurityManager();
if (securityManager instanceof RhinoSecurityManager) {
return AccessController.doPrivileged(
new PrivilegedAction<ProtectionDomain>() {
@Override
public ProtectionDomain run() {
Class<?> c = ((RhinoSecurityManager) securityManager)
.getCurrentScriptClass();
return c == null ? null : c.getProtectionDomain();
}
}
);
}
return null;
} } | public class class_name {
public static ProtectionDomain getScriptProtectionDomain() {
final SecurityManager securityManager = System.getSecurityManager();
if (securityManager instanceof RhinoSecurityManager) {
return AccessController.doPrivileged(
new PrivilegedAction<ProtectionDomain>() {
@Override
public ProtectionDomain run() {
Class<?> c = ((RhinoSecurityManager) securityManager)
.getCurrentScriptClass();
return c == null ? null : c.getProtectionDomain();
}
}
); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public void start(BundleContext pBundleContext) {
bundleContext = pBundleContext;
//Track ConfigurationAdmin service
configAdminTracker = new ServiceTracker(pBundleContext,
"org.osgi.service.cm.ConfigurationAdmin",
null);
configAdminTracker.open();
if (Boolean.parseBoolean(getConfiguration(USE_RESTRICTOR_SERVICE))) {
// If no restrictor is set in the constructor and we are enabled to listen for a restrictor
// service, a delegating restrictor is installed
restrictor = new DelegatingRestrictor(bundleContext);
}
// Track HttpService
if (Boolean.parseBoolean(getConfiguration(LISTEN_FOR_HTTP_SERVICE))) {
httpServiceTracker = new ServiceTracker(pBundleContext,
buildHttpServiceFilter(pBundleContext),
new HttpServiceCustomizer(pBundleContext));
httpServiceTracker.open();
// Register us as JolokiaContext
jolokiaServiceRegistration = pBundleContext.registerService(JolokiaContext.class.getCanonicalName(), this, null);
}
} } | public class class_name {
public void start(BundleContext pBundleContext) {
bundleContext = pBundleContext;
//Track ConfigurationAdmin service
configAdminTracker = new ServiceTracker(pBundleContext,
"org.osgi.service.cm.ConfigurationAdmin",
null);
configAdminTracker.open();
if (Boolean.parseBoolean(getConfiguration(USE_RESTRICTOR_SERVICE))) {
// If no restrictor is set in the constructor and we are enabled to listen for a restrictor
// service, a delegating restrictor is installed
restrictor = new DelegatingRestrictor(bundleContext); // depends on control dependency: [if], data = [none]
}
// Track HttpService
if (Boolean.parseBoolean(getConfiguration(LISTEN_FOR_HTTP_SERVICE))) {
httpServiceTracker = new ServiceTracker(pBundleContext,
buildHttpServiceFilter(pBundleContext),
new HttpServiceCustomizer(pBundleContext)); // depends on control dependency: [if], data = [none]
httpServiceTracker.open(); // depends on control dependency: [if], data = [none]
// Register us as JolokiaContext
jolokiaServiceRegistration = pBundleContext.registerService(JolokiaContext.class.getCanonicalName(), this, null); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void close() {
mIODevice = null;
GVRSceneObject owner = getOwnerObject();
if (owner.getParent() != null) {
owner.getParent().removeChildObject(owner);
}
} } | public class class_name {
void close() {
mIODevice = null;
GVRSceneObject owner = getOwnerObject();
if (owner.getParent() != null) {
owner.getParent().removeChildObject(owner); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static boolean checkAlreadyCompactedBasedOnSourceDirName (FileSystem fs, Dataset dataset) {
try {
Set<Path> renamedDirs = getDeepestLevelRenamedDirsWithFileExistence(fs, dataset.inputPaths());
return !renamedDirs.isEmpty();
} catch (IOException e) {
LOG.error("Failed to get deepest directories from source", e);
return false;
}
} } | public class class_name {
private static boolean checkAlreadyCompactedBasedOnSourceDirName (FileSystem fs, Dataset dataset) {
try {
Set<Path> renamedDirs = getDeepestLevelRenamedDirsWithFileExistence(fs, dataset.inputPaths());
return !renamedDirs.isEmpty(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LOG.error("Failed to get deepest directories from source", e);
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Object newInstance(Class target, Class[] types, Object[] args, boolean makeAccessible) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
Constructor con;
if (makeAccessible)
{
con = target.getDeclaredConstructor(types);
if (makeAccessible && !con.isAccessible())
{
con.setAccessible(true);
}
}
else
{
con = target.getConstructor(types);
}
return con.newInstance(args);
} } | public class class_name {
public static Object newInstance(Class target, Class[] types, Object[] args, boolean makeAccessible) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
Constructor con;
if (makeAccessible)
{
con = target.getDeclaredConstructor(types);
if (makeAccessible && !con.isAccessible())
{
con.setAccessible(true);
// depends on control dependency: [if], data = [none]
}
}
else
{
con = target.getConstructor(types);
}
return con.newInstance(args);
} } |
public class class_name {
public void close()
{
selector.wakeup();
try
{
selector.close();
}
catch (final IOException ex)
{
LangUtil.rethrowUnchecked(ex);
}
} } | public class class_name {
public void close()
{
selector.wakeup();
try
{
selector.close(); // depends on control dependency: [try], data = [none]
}
catch (final IOException ex)
{
LangUtil.rethrowUnchecked(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String getFullURI(HttpServletRequest request) {
StringBuilder buffer = new StringBuilder(request.getMethod());
buffer.append(" ");
buffer.append(request.getRequestURI());
String queryParam = request.getQueryString();
if (!Utils.isEmpty(queryParam)) {
buffer.append("?");
buffer.append(queryParam);
}
return buffer.toString();
} } | public class class_name {
private String getFullURI(HttpServletRequest request) {
StringBuilder buffer = new StringBuilder(request.getMethod());
buffer.append(" ");
buffer.append(request.getRequestURI());
String queryParam = request.getQueryString();
if (!Utils.isEmpty(queryParam)) {
buffer.append("?");
// depends on control dependency: [if], data = [none]
buffer.append(queryParam);
// depends on control dependency: [if], data = [none]
}
return buffer.toString();
} } |
public class class_name {
@Deprecated
@Override
public void writeBytes( String str ) {
CharacterIterator iter = new StringCharacterIterator(str);
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
writeByte(c);
}
} } | public class class_name {
@Deprecated
@Override
public void writeBytes( String str ) {
CharacterIterator iter = new StringCharacterIterator(str);
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
writeByte(c); // depends on control dependency: [for], data = [c]
}
} } |
public class class_name {
public RuleDto persistAndIndex(DbSession dbSession, NewAdHocRule adHoc, OrganizationDto organizationDto) {
RuleDao dao = dbClient.ruleDao();
Optional<RuleDto> existingRuleDtoOpt = dao.selectByKey(dbSession, organizationDto, adHoc.getKey());
RuleMetadataDto metadata;
long now = system2.now();
if (!existingRuleDtoOpt.isPresent()) {
RuleDefinitionDto dto = new RuleDefinitionDto()
.setRuleKey(adHoc.getKey())
.setIsExternal(true)
.setIsAdHoc(true)
.setName(adHoc.getEngineId() + ":" + adHoc.getRuleId())
.setScope(ALL)
.setStatus(READY)
.setCreatedAt(now)
.setUpdatedAt(now);
dao.insert(dbSession, dto);
metadata = new RuleMetadataDto()
.setRuleId(dto.getId())
.setOrganizationUuid(organizationDto.getUuid());
} else {
// No need to update the rule, only org specific metadata
RuleDto ruleDto = existingRuleDtoOpt.get();
Preconditions.checkState(ruleDto.isExternal() && ruleDto.isAdHoc());
metadata = ruleDto.getMetadata();
}
if (adHoc.hasDetails()) {
boolean changed = false;
if (!Objects.equals(metadata.getAdHocName(), adHoc.getName())) {
metadata.setAdHocName(substring(adHoc.getName(), 0, MAX_LENGTH_AD_HOC_NAME));
changed = true;
}
if (!Objects.equals(metadata.getAdHocDescription(), adHoc.getDescription())) {
metadata.setAdHocDescription(substring(adHoc.getDescription(), 0, MAX_LENGTH_AD_HOC_DESC));
changed = true;
}
if (!Objects.equals(metadata.getAdHocSeverity(), adHoc.getSeverity())) {
metadata.setAdHocSeverity(adHoc.getSeverity());
changed = true;
}
RuleType ruleType = requireNonNull(adHoc.getRuleType(), "Rule type should not be null");
if (!Objects.equals(metadata.getAdHocType(), ruleType.getDbConstant())) {
metadata.setAdHocType(ruleType);
changed = true;
}
if (changed) {
metadata.setUpdatedAt(now);
metadata.setCreatedAt(now);
dao.insertOrUpdate(dbSession, metadata);
}
}
RuleDto ruleDto = dao.selectOrFailByKey(dbSession, organizationDto, adHoc.getKey());
ruleIndexer.commitAndIndex(dbSession, ruleDto.getId());
return ruleDto;
} } | public class class_name {
public RuleDto persistAndIndex(DbSession dbSession, NewAdHocRule adHoc, OrganizationDto organizationDto) {
RuleDao dao = dbClient.ruleDao();
Optional<RuleDto> existingRuleDtoOpt = dao.selectByKey(dbSession, organizationDto, adHoc.getKey());
RuleMetadataDto metadata;
long now = system2.now();
if (!existingRuleDtoOpt.isPresent()) {
RuleDefinitionDto dto = new RuleDefinitionDto()
.setRuleKey(adHoc.getKey())
.setIsExternal(true)
.setIsAdHoc(true)
.setName(adHoc.getEngineId() + ":" + adHoc.getRuleId())
.setScope(ALL)
.setStatus(READY)
.setCreatedAt(now)
.setUpdatedAt(now);
dao.insert(dbSession, dto); // depends on control dependency: [if], data = [none]
metadata = new RuleMetadataDto()
.setRuleId(dto.getId())
.setOrganizationUuid(organizationDto.getUuid()); // depends on control dependency: [if], data = [none]
} else {
// No need to update the rule, only org specific metadata
RuleDto ruleDto = existingRuleDtoOpt.get();
Preconditions.checkState(ruleDto.isExternal() && ruleDto.isAdHoc()); // depends on control dependency: [if], data = [none]
metadata = ruleDto.getMetadata(); // depends on control dependency: [if], data = [none]
}
if (adHoc.hasDetails()) {
boolean changed = false;
if (!Objects.equals(metadata.getAdHocName(), adHoc.getName())) {
metadata.setAdHocName(substring(adHoc.getName(), 0, MAX_LENGTH_AD_HOC_NAME)); // depends on control dependency: [if], data = [none]
changed = true; // depends on control dependency: [if], data = [none]
}
if (!Objects.equals(metadata.getAdHocDescription(), adHoc.getDescription())) {
metadata.setAdHocDescription(substring(adHoc.getDescription(), 0, MAX_LENGTH_AD_HOC_DESC)); // depends on control dependency: [if], data = [none]
changed = true; // depends on control dependency: [if], data = [none]
}
if (!Objects.equals(metadata.getAdHocSeverity(), adHoc.getSeverity())) {
metadata.setAdHocSeverity(adHoc.getSeverity()); // depends on control dependency: [if], data = [none]
changed = true; // depends on control dependency: [if], data = [none]
}
RuleType ruleType = requireNonNull(adHoc.getRuleType(), "Rule type should not be null");
if (!Objects.equals(metadata.getAdHocType(), ruleType.getDbConstant())) {
metadata.setAdHocType(ruleType); // depends on control dependency: [if], data = [none]
changed = true; // depends on control dependency: [if], data = [none]
}
if (changed) {
metadata.setUpdatedAt(now); // depends on control dependency: [if], data = [none]
metadata.setCreatedAt(now); // depends on control dependency: [if], data = [none]
dao.insertOrUpdate(dbSession, metadata); // depends on control dependency: [if], data = [none]
}
}
RuleDto ruleDto = dao.selectOrFailByKey(dbSession, organizationDto, adHoc.getKey());
ruleIndexer.commitAndIndex(dbSession, ruleDto.getId());
return ruleDto;
} } |
public class class_name {
public static String hashKey(String key) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(key.getBytes(StandardCharsets.UTF_8));
md.update(MAGIC);
return new String(B64Code.encode(md.digest()));
} catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static String hashKey(String key) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(key.getBytes(StandardCharsets.UTF_8)); // depends on control dependency: [try], data = [none]
md.update(MAGIC); // depends on control dependency: [try], data = [none]
return new String(B64Code.encode(md.digest())); // 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 {
private static Point getScreenSize(Context context, Point p) {
if (p == null) {
p = new Point();
}
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
display.getSize(p);
return p;
} } | public class class_name {
private static Point getScreenSize(Context context, Point p) {
if (p == null) {
p = new Point(); // depends on control dependency: [if], data = [none]
}
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
display.getSize(p);
return p;
} } |
public class class_name {
@Override
public void setContainer( final Container container ) {
// De-register from the old Container (if any)
if ( this.container != null && this.container instanceof Context ) {
( (Context) this.container ).removePropertyChangeListener( this );
}
// Default processing provided by our superclass
super.setContainer( container );
// Register with the new Container (if any)
if ( this.container != null && this.container instanceof Context ) {
setMaxInactiveInterval( ( (Context) this.container ).getSessionTimeout() * 60 );
( (Context) this.container ).addPropertyChangeListener( this );
}
} } | public class class_name {
@Override
public void setContainer( final Container container ) {
// De-register from the old Container (if any)
if ( this.container != null && this.container instanceof Context ) {
( (Context) this.container ).removePropertyChangeListener( this ); // depends on control dependency: [if], data = [none]
}
// Default processing provided by our superclass
super.setContainer( container );
// Register with the new Container (if any)
if ( this.container != null && this.container instanceof Context ) {
setMaxInactiveInterval( ( (Context) this.container ).getSessionTimeout() * 60 ); // depends on control dependency: [if], data = [none]
( (Context) this.container ).addPropertyChangeListener( this ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public long getLong(String name, long defaultValue) {
String valueString = getTrimmed(name);
if (valueString == null)
return defaultValue;
String hexString = getHexDigits(valueString);
if (hexString != null) {
return Long.parseLong(hexString, 16);
}
return Long.parseLong(valueString);
} } | public class class_name {
public long getLong(String name, long defaultValue) {
String valueString = getTrimmed(name);
if (valueString == null)
return defaultValue;
String hexString = getHexDigits(valueString);
if (hexString != null) {
return Long.parseLong(hexString, 16); // depends on control dependency: [if], data = [(hexString]
}
return Long.parseLong(valueString);
} } |
public class class_name {
public static void apply(@NonNull View view) {
if (view.isInEditMode()) {
return;
}
final AssetManager assets = view.getContext().getAssets();
if (view instanceof TextView) {
setTypeface((TextView) view, getFontFromTag(assets, view, false));
} else if (view instanceof ViewGroup) {
applyAllRecursively((ViewGroup) view, assets);
}
} } | public class class_name {
public static void apply(@NonNull View view) {
if (view.isInEditMode()) {
return; // depends on control dependency: [if], data = [none]
}
final AssetManager assets = view.getContext().getAssets();
if (view instanceof TextView) {
setTypeface((TextView) view, getFontFromTag(assets, view, false)); // depends on control dependency: [if], data = [none]
} else if (view instanceof ViewGroup) {
applyAllRecursively((ViewGroup) view, assets); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Object getValue(Object obj, String field) {
Method getter = getGetterMethod(obj.getClass(), field);
try {
return getter.invoke(obj);
} catch (IllegalAccessException | InvocationTargetException e) {
return null;
}
} } | public class class_name {
public static Object getValue(Object obj, String field) {
Method getter = getGetterMethod(obj.getClass(), field);
try {
return getter.invoke(obj); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException | InvocationTargetException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static CommandImpl getCommand(final String name, final List<CommandImpl> commandList) throws DevFailed {
CommandImpl result = null;
for (final CommandImpl command : commandList) {
if (command.getName().equalsIgnoreCase(name)) {
result = command;
break;
}
}
if (result == null) {
throw DevFailedUtils.newDevFailed(ExceptionMessages.COMMAND_NOT_FOUND, "Command " + name + " not found");
}
return result;
} } | public class class_name {
public static CommandImpl getCommand(final String name, final List<CommandImpl> commandList) throws DevFailed {
CommandImpl result = null;
for (final CommandImpl command : commandList) {
if (command.getName().equalsIgnoreCase(name)) {
result = command;
// depends on control dependency: [if], data = [none]
break;
}
}
if (result == null) {
throw DevFailedUtils.newDevFailed(ExceptionMessages.COMMAND_NOT_FOUND, "Command " + name + " not found");
}
return result;
} } |
public class class_name {
public void setFontScale(float fontScale) {
this.fontScale = fontScale;
for (CaptioningChangeListener captioningChangeListener : listeners) {
captioningChangeListener.onFontScaleChanged(fontScale);
}
} } | public class class_name {
public void setFontScale(float fontScale) {
this.fontScale = fontScale;
for (CaptioningChangeListener captioningChangeListener : listeners) {
captioningChangeListener.onFontScaleChanged(fontScale); // depends on control dependency: [for], data = [captioningChangeListener]
}
} } |
public class class_name {
public void cleanThreadLocals(Thread thread) {
try {
svThreadLocalsField.set(thread, null);
} catch (IllegalAccessException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Unable to clear java.lang.ThreadLocals: ", e);
}
} } | public class class_name {
public void cleanThreadLocals(Thread thread) {
try {
svThreadLocalsField.set(thread, null); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Unable to clear java.lang.ThreadLocals: ", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void unIndex(final Object connection, final AttributeWrapper wrapper, final String member)
{
Set<String> keys = wrapper.getIndexes().keySet();
for (String key : keys)
{
if (resource != null && resource.isActive())
{
((Transaction) connection).zrem(key, member);
}
else
{
((Pipeline) connection).zrem(key, member);
}
}
} } | public class class_name {
private void unIndex(final Object connection, final AttributeWrapper wrapper, final String member)
{
Set<String> keys = wrapper.getIndexes().keySet();
for (String key : keys)
{
if (resource != null && resource.isActive())
{
((Transaction) connection).zrem(key, member); // depends on control dependency: [if], data = [none]
}
else
{
((Pipeline) connection).zrem(key, member); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void dump(final PrintStream ps) {
String str =
"Reported error: \"" + message + "\"";
if (lineNumber != -1) {
str += " at line " + lineNumber + " column " + colNumber;
}
ps.println(str);
if (exception != null) {
exception.printStackTrace(ps);
}
} } | public class class_name {
public void dump(final PrintStream ps) {
String str =
"Reported error: \"" + message + "\"";
if (lineNumber != -1) {
str += " at line " + lineNumber + " column " + colNumber; // depends on control dependency: [if], data = [none]
}
ps.println(str);
if (exception != null) {
exception.printStackTrace(ps); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public JsonElement serialize(List<JobExecutionPlan> src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray jsonArray = new JsonArray();
for (JobExecutionPlan jobExecutionPlan: src) {
JsonObject jobExecutionPlanJson = new JsonObject();
JsonObject jobSpecJson = new JsonObject();
JobSpec jobSpec = jobExecutionPlan.getJobSpec();
String uri = (jobSpec.getUri() != null) ? jobSpec.getUri().toString() : null;
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_URI_KEY, uri);
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_VERSION_KEY, jobSpec.getVersion());
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_DESCRIPTION_KEY, jobSpec.getDescription());
String jobSpecTemplateURI = (jobSpec.getTemplateURI().isPresent()) ? jobSpec.getTemplateURI().get().toString() : null;
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_TEMPLATE_URI_KEY, jobSpecTemplateURI);
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_CONFIG_KEY, jobSpec.getConfig().root().render(ConfigRenderOptions.concise()));
jobExecutionPlanJson.add(SerializationConstants.JOB_SPEC_KEY, jobSpecJson);
Config specExecutorConfig;
try {
specExecutorConfig = jobExecutionPlan.getSpecExecutor().getConfig().get();
} catch (InterruptedException | ExecutionException e) {
log.error("Error serializing JobExecutionPlan {}", jobExecutionPlan.toString());
throw new RuntimeException(e);
}
JsonObject specExecutorJson = new JsonObject();
specExecutorJson.addProperty(SerializationConstants.SPEC_EXECUTOR_CONFIG_KEY,
specExecutorConfig.root().render(ConfigRenderOptions.concise()));
specExecutorJson.addProperty(SerializationConstants.SPEC_EXECUTOR_CLASS_KEY,
jobExecutionPlan.getSpecExecutor().getClass().getName());
jobExecutionPlanJson.add(SerializationConstants.SPEC_EXECUTOR_KEY, specExecutorJson);
String executionStatus = jobExecutionPlan.getExecutionStatus().name();
jobExecutionPlanJson.addProperty(SerializationConstants.EXECUTION_STATUS_KEY, executionStatus);
jsonArray.add(jobExecutionPlanJson);
}
return jsonArray;
} } | public class class_name {
@Override
public JsonElement serialize(List<JobExecutionPlan> src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray jsonArray = new JsonArray();
for (JobExecutionPlan jobExecutionPlan: src) {
JsonObject jobExecutionPlanJson = new JsonObject();
JsonObject jobSpecJson = new JsonObject();
JobSpec jobSpec = jobExecutionPlan.getJobSpec();
String uri = (jobSpec.getUri() != null) ? jobSpec.getUri().toString() : null;
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_URI_KEY, uri); // depends on control dependency: [for], data = [none]
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_VERSION_KEY, jobSpec.getVersion()); // depends on control dependency: [for], data = [none]
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_DESCRIPTION_KEY, jobSpec.getDescription()); // depends on control dependency: [for], data = [none]
String jobSpecTemplateURI = (jobSpec.getTemplateURI().isPresent()) ? jobSpec.getTemplateURI().get().toString() : null;
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_TEMPLATE_URI_KEY, jobSpecTemplateURI); // depends on control dependency: [for], data = [none]
jobSpecJson.addProperty(SerializationConstants.JOB_SPEC_CONFIG_KEY, jobSpec.getConfig().root().render(ConfigRenderOptions.concise())); // depends on control dependency: [for], data = [none]
jobExecutionPlanJson.add(SerializationConstants.JOB_SPEC_KEY, jobSpecJson); // depends on control dependency: [for], data = [jobExecutionPlan]
Config specExecutorConfig;
try {
specExecutorConfig = jobExecutionPlan.getSpecExecutor().getConfig().get(); // depends on control dependency: [try], data = [none]
} catch (InterruptedException | ExecutionException e) {
log.error("Error serializing JobExecutionPlan {}", jobExecutionPlan.toString());
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
JsonObject specExecutorJson = new JsonObject();
specExecutorJson.addProperty(SerializationConstants.SPEC_EXECUTOR_CONFIG_KEY,
specExecutorConfig.root().render(ConfigRenderOptions.concise())); // depends on control dependency: [for], data = [none]
specExecutorJson.addProperty(SerializationConstants.SPEC_EXECUTOR_CLASS_KEY,
jobExecutionPlan.getSpecExecutor().getClass().getName()); // depends on control dependency: [for], data = [none]
jobExecutionPlanJson.add(SerializationConstants.SPEC_EXECUTOR_KEY, specExecutorJson); // depends on control dependency: [for], data = [jobExecutionPlan]
String executionStatus = jobExecutionPlan.getExecutionStatus().name();
jobExecutionPlanJson.addProperty(SerializationConstants.EXECUTION_STATUS_KEY, executionStatus); // depends on control dependency: [for], data = [jobExecutionPlan]
jsonArray.add(jobExecutionPlanJson); // depends on control dependency: [for], data = [jobExecutionPlan]
}
return jsonArray;
} } |
public class class_name {
private void suppressSeleniumJavaUtilLogging() {
if ( ! seleniumLoggingSuppressed.getAndSet(true) ) {
try {
// Log4j logging is annoyingly difficult to turn off, it usually requires a config file but we can also do it with an InputStream
Properties properties = new Properties();
properties.setProperty("org.openqa.selenium.remote.ProtocolHandshake.level", "OFF");
properties.setProperty("org.openqa.selenium.remote.ProtocolHandshake.useParentHandlers", "false");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
properties.store(byteArrayOutputStream, "seleniumLoggingProperties");
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
LogManager.getLogManager().readConfiguration(byteArrayInputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
} } | public class class_name {
private void suppressSeleniumJavaUtilLogging() {
if ( ! seleniumLoggingSuppressed.getAndSet(true) ) {
try {
// Log4j logging is annoyingly difficult to turn off, it usually requires a config file but we can also do it with an InputStream
Properties properties = new Properties();
properties.setProperty("org.openqa.selenium.remote.ProtocolHandshake.level", "OFF"); // depends on control dependency: [try], data = [none]
properties.setProperty("org.openqa.selenium.remote.ProtocolHandshake.useParentHandlers", "false"); // depends on control dependency: [try], data = [none]
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
properties.store(byteArrayOutputStream, "seleniumLoggingProperties"); // depends on control dependency: [try], data = [none]
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
LogManager.getLogManager().readConfiguration(byteArrayInputStream); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static boolean checkCropRegionContainsFocalPoint(CmsImageScaler scaler, CmsPoint focalPoint) {
if (!scaler.isCropping()) {
return true;
}
double x = focalPoint.getX();
double y = focalPoint.getY();
return (scaler.getCropX() <= x)
&& (x < (scaler.getCropX() + scaler.getCropWidth()))
&& (scaler.getCropY() <= y)
&& (y < (scaler.getCropY() + scaler.getCropHeight()));
} } | public class class_name {
private static boolean checkCropRegionContainsFocalPoint(CmsImageScaler scaler, CmsPoint focalPoint) {
if (!scaler.isCropping()) {
return true; // depends on control dependency: [if], data = [none]
}
double x = focalPoint.getX();
double y = focalPoint.getY();
return (scaler.getCropX() <= x)
&& (x < (scaler.getCropX() + scaler.getCropWidth()))
&& (scaler.getCropY() <= y)
&& (y < (scaler.getCropY() + scaler.getCropHeight()));
} } |
public class class_name {
@Override
public void save(final SagaState state) {
checkNotNull(state, "State not allowed to be null.");
checkNotNull(state.getSagaId(), "State saga id not allowed to be null.");
checkNotNull(state.getType(), "Saga type must not be null.");
synchronized (sync) {
String sagaId = state.getSagaId();
StateStorageItem stateStorageItem = storedStates.get(sagaId);
if (stateStorageItem == null) {
stateStorageItem = StateStorageItem.withCurrentInstanceKeys(state);
storedStates.put(state.getSagaId(), stateStorageItem);
} else {
// remove previous stored keys from map
// some entries may have been removed from the state during
// saga execution
removeInstancesForItem(stateStorageItem);
// once old values have been removed update item with current
// values
stateStorageItem.updateInstanceKeys();
}
for (SagaMultiKey key : stateStorageItem.instanceKeys()) {
instanceKeyMap.put(key, state);
}
}
} } | public class class_name {
@Override
public void save(final SagaState state) {
checkNotNull(state, "State not allowed to be null.");
checkNotNull(state.getSagaId(), "State saga id not allowed to be null.");
checkNotNull(state.getType(), "Saga type must not be null.");
synchronized (sync) {
String sagaId = state.getSagaId();
StateStorageItem stateStorageItem = storedStates.get(sagaId);
if (stateStorageItem == null) {
stateStorageItem = StateStorageItem.withCurrentInstanceKeys(state); // depends on control dependency: [if], data = [none]
storedStates.put(state.getSagaId(), stateStorageItem); // depends on control dependency: [if], data = [none]
} else {
// remove previous stored keys from map
// some entries may have been removed from the state during
// saga execution
removeInstancesForItem(stateStorageItem); // depends on control dependency: [if], data = [(stateStorageItem]
// once old values have been removed update item with current
// values
stateStorageItem.updateInstanceKeys(); // depends on control dependency: [if], data = [none]
}
for (SagaMultiKey key : stateStorageItem.instanceKeys()) {
instanceKeyMap.put(key, state); // depends on control dependency: [for], data = [key]
}
}
} } |
public class class_name {
public static void encodeLength(ByteArrayOutputStream out, int length) {
LOG.entering(CLASS_NAME, "encodeLength", new Object[] { out, length });
int byteCount = 0;
long encodedLength = 0;
do {
// left shift one byte to make room for new data
encodedLength <<= 8;
// set 7 bits of length
encodedLength |= (byte) (length & 0x7f);
// right shift out the 7 bits we just set
length >>= 7;
// increment the byte count that we need to encode
byteCount++;
}
// continue if there are remaining set length bits
while (length > 0);
do {
// get byte from encoded length
byte encodedByte = (byte) (encodedLength & 0xff);
// right shift encoded length past byte we just got
encodedLength >>= 8;
// The last length byte does not have the highest bit set
if (byteCount != 1) {
// set highest bit if this is not the last
encodedByte |= (byte) 0x80;
}
// write encoded byte
out.write(encodedByte);
}
// decrement and continue if we have more bytes left
while (--byteCount > 0);
} } | public class class_name {
public static void encodeLength(ByteArrayOutputStream out, int length) {
LOG.entering(CLASS_NAME, "encodeLength", new Object[] { out, length });
int byteCount = 0;
long encodedLength = 0;
do {
// left shift one byte to make room for new data
encodedLength <<= 8;
// set 7 bits of length
encodedLength |= (byte) (length & 0x7f);
// right shift out the 7 bits we just set
length >>= 7;
// increment the byte count that we need to encode
byteCount++;
}
// continue if there are remaining set length bits
while (length > 0);
do {
// get byte from encoded length
byte encodedByte = (byte) (encodedLength & 0xff);
// right shift encoded length past byte we just got
encodedLength >>= 8;
// The last length byte does not have the highest bit set
if (byteCount != 1) {
// set highest bit if this is not the last
encodedByte |= (byte) 0x80; // depends on control dependency: [if], data = [none]
}
// write encoded byte
out.write(encodedByte);
}
// decrement and continue if we have more bytes left
while (--byteCount > 0);
} } |
public class class_name {
public String getIndependentParentLink(String style)
throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource(new StringReader(style));
Document doc = builder.parse(src);
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); ++i) {
Node n = links.item(i);
Node relAttr = n.getAttributes().getNamedItem("rel");
if (relAttr != null) {
if ("independent-parent".equals(relAttr.getTextContent())) {
Node hrefAttr = n.getAttributes().getNamedItem("href");
if (hrefAttr != null) {
return hrefAttr.getTextContent();
}
}
}
}
return null;
} } | public class class_name {
public String getIndependentParentLink(String style)
throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource(new StringReader(style));
Document doc = builder.parse(src);
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); ++i) {
Node n = links.item(i);
Node relAttr = n.getAttributes().getNamedItem("rel");
if (relAttr != null) {
if ("independent-parent".equals(relAttr.getTextContent())) {
Node hrefAttr = n.getAttributes().getNamedItem("href");
if (hrefAttr != null) {
return hrefAttr.getTextContent(); // depends on control dependency: [if], data = [none]
}
}
}
}
return null;
} } |
public class class_name {
public String dialogTitle() {
StringBuffer html = new StringBuffer(512);
String toolPath = getCurrentToolPath();
String parentPath = getParentPath();
String rootKey = getToolManager().getCurrentRoot(this).getKey();
String upLevelLink = computeUpLevelLink();
html.append(getToolManager().generateNavBar(toolPath, this));
// build title
html.append("<div class='screenTitle'>\n");
html.append("\t<table width='100%' cellspacing='0'>\n");
html.append("\t\t<tr>\n");
html.append("\t\t\t<td>\n");
html.append(CmsEncoder.decode(CmsToolMacroResolver.resolveMacros(getAdminTool().getHandler().getName(), this)));
html.append("\n\t\t\t</td>");
// uplevel button only if needed
if ((upLevelLink != null) && !getParentPath().equals(toolPath)) {
String parentName = getToolManager().resolveAdminTool(rootKey, parentPath).getHandler().getName();
html.append("\t\t\t<td class='uplevel'>\n\t\t\t\t");
html.append(
A_CmsHtmlIconButton.defaultButtonHtml(
CmsHtmlIconButtonStyleEnum.SMALL_ICON_TEXT,
"id-up-level",
Messages.get().getBundle(getLocale()).key(Messages.GUI_ADMIN_VIEW_UPLEVEL_0),
parentName,
true,
"admin/images/up.png",
null,
"openPage('" + upLevelLink + "');"));
html.append("\n\t\t\t</td>\n");
}
html.append("\t\t</tr>\n");
html.append("\t</table>\n");
html.append("</div>\n");
return CmsToolMacroResolver.resolveMacros(html.toString(), this);
} } | public class class_name {
public String dialogTitle() {
StringBuffer html = new StringBuffer(512);
String toolPath = getCurrentToolPath();
String parentPath = getParentPath();
String rootKey = getToolManager().getCurrentRoot(this).getKey();
String upLevelLink = computeUpLevelLink();
html.append(getToolManager().generateNavBar(toolPath, this));
// build title
html.append("<div class='screenTitle'>\n");
html.append("\t<table width='100%' cellspacing='0'>\n");
html.append("\t\t<tr>\n");
html.append("\t\t\t<td>\n");
html.append(CmsEncoder.decode(CmsToolMacroResolver.resolveMacros(getAdminTool().getHandler().getName(), this)));
html.append("\n\t\t\t</td>");
// uplevel button only if needed
if ((upLevelLink != null) && !getParentPath().equals(toolPath)) {
String parentName = getToolManager().resolveAdminTool(rootKey, parentPath).getHandler().getName();
html.append("\t\t\t<td class='uplevel'>\n\t\t\t\t"); // depends on control dependency: [if], data = [none]
html.append(
A_CmsHtmlIconButton.defaultButtonHtml(
CmsHtmlIconButtonStyleEnum.SMALL_ICON_TEXT,
"id-up-level",
Messages.get().getBundle(getLocale()).key(Messages.GUI_ADMIN_VIEW_UPLEVEL_0),
parentName,
true,
"admin/images/up.png",
null,
"openPage('" + upLevelLink + "');")); // depends on control dependency: [if], data = [none]
html.append("\n\t\t\t</td>\n"); // depends on control dependency: [if], data = [none]
}
html.append("\t\t</tr>\n");
html.append("\t</table>\n");
html.append("</div>\n");
return CmsToolMacroResolver.resolveMacros(html.toString(), this);
} } |
public class class_name {
public final List<URI> getModelResources() {
if ((modelResources == null) && (modelPath != null)) {
modelResources = new ArrayList<>();
modelResources = paths().stream().filter(XtextParserConfig::isResource).map(XtextParserConfig::asResource)
.collect(Collectors.toList());
}
return modelResources;
} } | public class class_name {
public final List<URI> getModelResources() {
if ((modelResources == null) && (modelPath != null)) {
modelResources = new ArrayList<>();
// depends on control dependency: [if], data = [none]
modelResources = paths().stream().filter(XtextParserConfig::isResource).map(XtextParserConfig::asResource)
.collect(Collectors.toList());
// depends on control dependency: [if], data = [none]
}
return modelResources;
} } |
public class class_name {
public static java.sql.Timestamp getTimestamp(Object value) {
try {
return toTimestamp(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} } | public class class_name {
public static java.sql.Timestamp getTimestamp(Object value) {
try {
return toTimestamp(value); // depends on control dependency: [try], data = [none]
} catch (ParseException pe) {
pe.printStackTrace();
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public FormatSettingsManager getFormatSettingsManager() {
if (formatSettingsManager != null) {
return formatSettingsManager;
}
formatSettingsManager = (FormatSettingsManager) ContainerManager.getComponent("formatSettingsManager");
return formatSettingsManager;
} } | public class class_name {
public FormatSettingsManager getFormatSettingsManager() {
if (formatSettingsManager != null) {
return formatSettingsManager; // depends on control dependency: [if], data = [none]
}
formatSettingsManager = (FormatSettingsManager) ContainerManager.getComponent("formatSettingsManager");
return formatSettingsManager;
} } |
public class class_name {
public void setDnsIpAddrs(java.util.Collection<String> dnsIpAddrs) {
if (dnsIpAddrs == null) {
this.dnsIpAddrs = null;
return;
}
this.dnsIpAddrs = new com.amazonaws.internal.SdkInternalList<String>(dnsIpAddrs);
} } | public class class_name {
public void setDnsIpAddrs(java.util.Collection<String> dnsIpAddrs) {
if (dnsIpAddrs == null) {
this.dnsIpAddrs = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.dnsIpAddrs = new com.amazonaws.internal.SdkInternalList<String>(dnsIpAddrs);
} } |
public class class_name {
private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,
final boolean failIfPassive) {
// First check if we are using cached data for this slot.
MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));
if (cache != null) {
final AlbumArt result = cache.getAlbumArt(null, artReference);
if (result != null) {
artCache.put(artReference, result);
}
return result;
}
// Then see if any registered metadata providers can offer it for us.
final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());
if (sourceDetails != null) {
final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);
if (provided != null) {
return provided;
}
}
// At this point, unless we are allowed to actively request the data, we are done. We can always actively
// request tracks from rekordbox.
if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {
return null;
}
// We have to actually request the art using the dbserver protocol.
ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {
@Override
public AlbumArt useClient(Client client) throws Exception {
return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);
}
};
try {
AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, "requesting artwork");
if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.
artCache.put(artReference, artwork);
}
return artwork;
} catch (Exception e) {
logger.error("Problem requesting album art, returning null", e);
}
return null;
} } | public class class_name {
private AlbumArt requestArtworkInternal(final DataReference artReference, final CdjStatus.TrackType trackType,
final boolean failIfPassive) {
// First check if we are using cached data for this slot.
MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(artReference));
if (cache != null) {
final AlbumArt result = cache.getAlbumArt(null, artReference);
if (result != null) {
artCache.put(artReference, result); // depends on control dependency: [if], data = [none]
}
return result; // depends on control dependency: [if], data = [none]
}
// Then see if any registered metadata providers can offer it for us.
final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(artReference.getSlotReference());
if (sourceDetails != null) {
final AlbumArt provided = MetadataFinder.getInstance().allMetadataProviders.getAlbumArt(sourceDetails, artReference);
if (provided != null) {
return provided; // depends on control dependency: [if], data = [none]
}
}
// At this point, unless we are allowed to actively request the data, we are done. We can always actively
// request tracks from rekordbox.
if (MetadataFinder.getInstance().isPassive() && failIfPassive && artReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) {
return null; // depends on control dependency: [if], data = [none]
}
// We have to actually request the art using the dbserver protocol.
ConnectionManager.ClientTask<AlbumArt> task = new ConnectionManager.ClientTask<AlbumArt>() {
@Override
public AlbumArt useClient(Client client) throws Exception {
return getArtwork(artReference.rekordboxId, SlotReference.getSlotReference(artReference), trackType, client);
}
};
try {
AlbumArt artwork = ConnectionManager.getInstance().invokeWithClientSession(artReference.player, task, "requesting artwork");
if (artwork != null) { // Our cache file load or network request succeeded, so add to the level 2 cache.
artCache.put(artReference, artwork); // depends on control dependency: [if], data = [none]
}
return artwork; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Problem requesting album art, returning null", e);
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
@Override
public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
throw new IllegalArgumentException("Internal error: wrong types: "
+ nodes[0].getClass().getName() + " / " + nodes[1].getClass().getName());
}
AnnotationNode node = (AnnotationNode) nodes[0];
AnnotatedNode parent = (AnnotatedNode) nodes[1];
ClassNode declaringClass = parent.getDeclaringClass();
if (parent instanceof FieldNode) {
int modifiers = ((FieldNode) parent).getModifiers();
if ((modifiers & Modifier.FINAL) != 0) {
String msg = "@griffon.transform.FXBindable cannot annotate a final property.";
generateSyntaxErrorMessage(sourceUnit, node, msg);
}
addJavaFXProperty(sourceUnit, node, declaringClass, (FieldNode) parent);
} else {
addJavaFXPropertyToClass(sourceUnit, node, (ClassNode) parent);
}
} } | public class class_name {
@Override
public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
throw new IllegalArgumentException("Internal error: wrong types: "
+ nodes[0].getClass().getName() + " / " + nodes[1].getClass().getName());
}
AnnotationNode node = (AnnotationNode) nodes[0];
AnnotatedNode parent = (AnnotatedNode) nodes[1];
ClassNode declaringClass = parent.getDeclaringClass();
if (parent instanceof FieldNode) {
int modifiers = ((FieldNode) parent).getModifiers();
if ((modifiers & Modifier.FINAL) != 0) {
String msg = "@griffon.transform.FXBindable cannot annotate a final property."; // depends on control dependency: [if], data = [none]
generateSyntaxErrorMessage(sourceUnit, node, msg); // depends on control dependency: [if], data = [none]
}
addJavaFXProperty(sourceUnit, node, declaringClass, (FieldNode) parent); // depends on control dependency: [if], data = [none]
} else {
addJavaFXPropertyToClass(sourceUnit, node, (ClassNode) parent); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(InventoryDeletionStatusItem inventoryDeletionStatusItem, ProtocolMarshaller protocolMarshaller) {
if (inventoryDeletionStatusItem == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(inventoryDeletionStatusItem.getDeletionId(), DELETIONID_BINDING);
protocolMarshaller.marshall(inventoryDeletionStatusItem.getTypeName(), TYPENAME_BINDING);
protocolMarshaller.marshall(inventoryDeletionStatusItem.getDeletionStartTime(), DELETIONSTARTTIME_BINDING);
protocolMarshaller.marshall(inventoryDeletionStatusItem.getLastStatus(), LASTSTATUS_BINDING);
protocolMarshaller.marshall(inventoryDeletionStatusItem.getLastStatusMessage(), LASTSTATUSMESSAGE_BINDING);
protocolMarshaller.marshall(inventoryDeletionStatusItem.getDeletionSummary(), DELETIONSUMMARY_BINDING);
protocolMarshaller.marshall(inventoryDeletionStatusItem.getLastStatusUpdateTime(), LASTSTATUSUPDATETIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(InventoryDeletionStatusItem inventoryDeletionStatusItem, ProtocolMarshaller protocolMarshaller) {
if (inventoryDeletionStatusItem == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(inventoryDeletionStatusItem.getDeletionId(), DELETIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(inventoryDeletionStatusItem.getTypeName(), TYPENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(inventoryDeletionStatusItem.getDeletionStartTime(), DELETIONSTARTTIME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(inventoryDeletionStatusItem.getLastStatus(), LASTSTATUS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(inventoryDeletionStatusItem.getLastStatusMessage(), LASTSTATUSMESSAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(inventoryDeletionStatusItem.getDeletionSummary(), DELETIONSUMMARY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(inventoryDeletionStatusItem.getLastStatusUpdateTime(), LASTSTATUSUPDATETIME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String getStringForDay(int day) {
if(fDates == null) {
loadDates();
}
for(URelativeString dayItem : fDates) {
if(dayItem.offset == day) {
return dayItem.string;
}
}
return null;
} } | public class class_name {
private String getStringForDay(int day) {
if(fDates == null) {
loadDates(); // depends on control dependency: [if], data = [none]
}
for(URelativeString dayItem : fDates) {
if(dayItem.offset == day) {
return dayItem.string; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
Symbol symbol = ASTHelpers.getSymbol(tree);
// Match symbol's owner to android.R.string separately because couldn't get fully qualified
// "android.R.string.yes" out of symbol, just "yes"
if (symbol == null
|| symbol.owner == null
|| symbol.getKind() != ElementKind.FIELD
|| !symbol.isStatic()
|| !R_STRING_CLASSNAME.contentEquals(symbol.owner.getQualifiedName())) {
return Description.NO_MATCH;
}
String misleading = symbol.getSimpleName().toString();
String preferred = MISLEADING.get(misleading);
if (preferred == null) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(
String.format(
"%s.%s is not \"%s\" but \"%s\"; prefer %s.%s for clarity",
R_STRING_CLASSNAME,
misleading,
ASSUMED_MEANINGS.get(misleading),
ASSUMED_MEANINGS.get(preferred),
R_STRING_CLASSNAME,
preferred))
// Keep the way tree refers to android.R.string as it is but replace the identifier
.addFix(
SuggestedFix.replace(
tree, state.getSourceForNode(tree.getExpression()) + "." + preferred))
.build();
} } | public class class_name {
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
Symbol symbol = ASTHelpers.getSymbol(tree);
// Match symbol's owner to android.R.string separately because couldn't get fully qualified
// "android.R.string.yes" out of symbol, just "yes"
if (symbol == null
|| symbol.owner == null
|| symbol.getKind() != ElementKind.FIELD
|| !symbol.isStatic()
|| !R_STRING_CLASSNAME.contentEquals(symbol.owner.getQualifiedName())) {
return Description.NO_MATCH; // depends on control dependency: [if], data = [none]
}
String misleading = symbol.getSimpleName().toString();
String preferred = MISLEADING.get(misleading);
if (preferred == null) {
return Description.NO_MATCH; // depends on control dependency: [if], data = [none]
}
return buildDescription(tree)
.setMessage(
String.format(
"%s.%s is not \"%s\" but \"%s\"; prefer %s.%s for clarity",
R_STRING_CLASSNAME,
misleading,
ASSUMED_MEANINGS.get(misleading),
ASSUMED_MEANINGS.get(preferred),
R_STRING_CLASSNAME,
preferred))
// Keep the way tree refers to android.R.string as it is but replace the identifier
.addFix(
SuggestedFix.replace(
tree, state.getSourceForNode(tree.getExpression()) + "." + preferred))
.build();
} } |
public class class_name {
public void visit(LiteralType literal)
{
if (traverser.isEnteringContext())
{
enterLiteral(literal);
}
else if (traverser.isLeavingContext())
{
leaveLiteral(literal);
literal.setTermTraverser(null);
}
} } | public class class_name {
public void visit(LiteralType literal)
{
if (traverser.isEnteringContext())
{
enterLiteral(literal); // depends on control dependency: [if], data = [none]
}
else if (traverser.isLeavingContext())
{
leaveLiteral(literal); // depends on control dependency: [if], data = [none]
literal.setTermTraverser(null); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public KryoInstantiator setReferences(final boolean ref) {
return new KryoInstantiator() {
public Kryo newKryo() {
Kryo k = KryoInstantiator.this.newKryo();
/**
* Kryo 2.17, used in storm, has this method returning void,
* 2.21 has it returning boolean.
* Try not to call the method if you don't need to.
*/
if(k.getReferences() != ref) { k.setReferences(ref); }
return k;
}
};
} } | public class class_name {
public KryoInstantiator setReferences(final boolean ref) {
return new KryoInstantiator() {
public Kryo newKryo() {
Kryo k = KryoInstantiator.this.newKryo();
/**
* Kryo 2.17, used in storm, has this method returning void,
* 2.21 has it returning boolean.
* Try not to call the method if you don't need to.
*/
if(k.getReferences() != ref) { k.setReferences(ref); } // depends on control dependency: [if], data = [ref)]
return k;
}
};
} } |
public class class_name {
public static void moveChildren(Element from, Element to) {
if (from == null || to == null || from == to) return;
for (int k = from.getChildCount() - 1; k >= 0; k--) {
Node node = from.getChild(k);
from.removeChild(node);
to.insertFirst(node);
}
} } | public class class_name {
public static void moveChildren(Element from, Element to) {
if (from == null || to == null || from == to) return;
for (int k = from.getChildCount() - 1; k >= 0; k--) {
Node node = from.getChild(k);
from.removeChild(node); // depends on control dependency: [for], data = [none]
to.insertFirst(node); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public Future<?> doSnapshotWork(SystemProcedureExecutionContext context, boolean noSchedule) {
// TRAIL [SnapSave:10] 6 [all SP] Do work when the task gets its turn.
ListenableFuture<?> retval = null;
/*
* This thread will null out the reference to m_snapshotTableTasks when
* a snapshot is finished. If the snapshot buffer is loaned out that means
* it is pending I/O somewhere so there is no work to do until it comes back.
*/
if (m_snapshotTableTasks == null) {
return retval;
}
if (m_snapshotTargets == null) {
return null;
}
/*
* Try to serialize a block from a table, if the table is finished,
* remove the tasks from the task map and move on to the next table. If a block is
* successfully serialized, break out of the loop and release the site thread for more
* transaction work.
*/
Iterator<Map.Entry<Integer, Collection<SnapshotTableTask>>> taskIter =
m_snapshotTableTasks.asMap().entrySet().iterator();
while (taskIter.hasNext()) {
Map.Entry<Integer, Collection<SnapshotTableTask>> taskEntry = taskIter.next();
final int tableId = taskEntry.getKey();
final Collection<SnapshotTableTask> tableTasks = taskEntry.getValue();
final List<BBContainer> outputBuffers = getOutputBuffers(tableTasks, noSchedule);
if (outputBuffers == null) {
// Not enough buffers available
if (!noSchedule) {
rescheduleSnapshotWork();
}
break;
}
// Stream more and add a listener to handle any failures
Pair<ListenableFuture<?>, Boolean> streamResult =
m_streamers.get(tableId).streamMore(context, outputBuffers, null);
if (streamResult.getFirst() != null) {
final ListenableFuture<?> writeFutures = streamResult.getFirst();
writeFutures.addListener(new Runnable() {
@Override
public void run()
{
try {
writeFutures.get();
} catch (Throwable t) {
if (m_perSiteLastSnapshotSucceded) {
if (t instanceof StreamSnapshotTimeoutException ||
t.getCause() instanceof StreamSnapshotTimeoutException) {
//This error is already logged by the watchdog when it generates the exception
} else {
if (m_isTruncation) {
VoltDB.crashLocalVoltDB("Unexpected exception while attempting to create truncation snapshot",
true, t);
}
SNAP_LOG.error("Error while attempting to write snapshot data", t);
}
m_perSiteLastSnapshotSucceded = false;
}
}
}
}, CoreUtils.SAMETHREADEXECUTOR);
}
/**
* The table streamer will return false when there is no more data left to pull from that table. The
* enclosing loop ensures that the next table is then addressed.
*/
if (!streamResult.getSecond()) {
asyncTerminateReplicatedTableTasks(tableTasks);
// XXX: Guava's multimap will clear the tableTasks collection when the entry is
// removed from the containing map, so don't use the collection after removal!
taskIter.remove();
SNAP_LOG.debug("Finished snapshot tasks for table " + tableId +
": " + tableTasks);
} else {
break;
}
}
/**
* If there are no more tasks then this particular EE is finished doing snapshot work
* Check the AtomicInteger to find out if this is the last one.
*/
if (m_snapshotTableTasks.isEmpty()) {
SNAP_LOG.debug("Finished with tasks");
// In case this is a non-blocking snapshot, do the post-snapshot tasks here.
runPostSnapshotTasks(context);
final ArrayList<SnapshotDataTarget> snapshotTargets = m_snapshotTargets;
m_snapshotTargets = null;
m_snapshotTableTasks = null;
boolean IamLast = false;
synchronized (ExecutionSitesCurrentlySnapshotting) {
if (!ExecutionSitesCurrentlySnapshotting.contains(this)) {
VoltDB.crashLocalVoltDB(
"Currently snapshotting site didn't find itself in set of snapshotting sites", true, null);
}
IamLast = ExecutionSitesCurrentlySnapshotting.size() == 1;
if (!IamLast) {
ExecutionSitesCurrentlySnapshotting.remove(this);
}
}
/**
* If this is the last one then this EE must close all the SnapshotDataTargets.
* Done in a separate thread so the EE can go and do other work. It will
* sync every file descriptor and that may block for a while.
*/
if (IamLast) {
SNAP_LOG.debug("I AM LAST!");
final long txnId = m_lastSnapshotTxnId;
final ExtensibleSnapshotDigestData snapshotDataForZookeeper = m_extraSnapshotData;
m_extraSnapshotData = null;
final Thread terminatorThread =
new Thread("Snapshot terminator") {
@Override
public void run() {
// TRAIL [SnapSave:11] 7 [1 site/host] The last finished site wlll close the targets.
boolean snapshotSucceeded = true;
try {
/*
* Be absolutely sure the snapshot is finished
* and synced to disk before another is started
*/
for (Thread t : m_snapshotTargetTerminators){
if (t == this) {
continue;
}
try {
t.join();
} catch (InterruptedException e) {
return;
}
}
for (final SnapshotDataTarget t : snapshotTargets) {
try {
t.close();
} catch (IOException e) {
snapshotSucceeded = false;
throw new RuntimeException(e);
} catch (InterruptedException e) {
snapshotSucceeded = false;
throw new RuntimeException(e);
}
}
Runnable r = null;
while ((r = m_tasksOnSnapshotCompletion.poll()) != null) {
try {
r.run();
} catch (Exception e) {
SNAP_LOG.error("Error running snapshot completion task", e);
}
}
} finally {
// Caching the value here before the site removes itself from the
// ExecutionSitesCurrentlySnapshotting set, so
// logSnapshotCompletionToZK() will not see incorrect values
// from the next snapshot
try {
VoltDB.instance().getHostMessenger().getZK().delete(
VoltZK.nodes_currently_snapshotting + "/" + VoltDB.instance().getHostMessenger().getHostId(), -1);
} catch (NoNodeException e) {
SNAP_LOG.warn("Expect the snapshot node to already exist during deletion", e);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
} finally {
/**
* Remove this last site from the set here after the terminator has run
* so that new snapshots won't start until
* everything is on disk for the previous snapshot. This prevents a really long
* snapshot initiation procedure from occurring because it has to contend for
* filesystem resources
*
* Do this before logSnapshotCompleteToZK() because the ZK operations are slow,
* and they can trigger snapshot completion interests to fire before this site
* removes itself from the set. The next snapshot request may come in and see
* this snapshot is still in progress.
*/
ExecutionSitesCurrentlySnapshotting.remove(SnapshotSiteProcessor.this);
}
logSnapshotCompleteToZK(txnId,
snapshotSucceeded,
snapshotDataForZookeeper);
}
}
};
m_snapshotTargetTerminators.add(terminatorThread);
terminatorThread.start();
}
}
return retval;
} } | public class class_name {
public Future<?> doSnapshotWork(SystemProcedureExecutionContext context, boolean noSchedule) {
// TRAIL [SnapSave:10] 6 [all SP] Do work when the task gets its turn.
ListenableFuture<?> retval = null;
/*
* This thread will null out the reference to m_snapshotTableTasks when
* a snapshot is finished. If the snapshot buffer is loaned out that means
* it is pending I/O somewhere so there is no work to do until it comes back.
*/
if (m_snapshotTableTasks == null) {
return retval; // depends on control dependency: [if], data = [none]
}
if (m_snapshotTargets == null) {
return null; // depends on control dependency: [if], data = [none]
}
/*
* Try to serialize a block from a table, if the table is finished,
* remove the tasks from the task map and move on to the next table. If a block is
* successfully serialized, break out of the loop and release the site thread for more
* transaction work.
*/
Iterator<Map.Entry<Integer, Collection<SnapshotTableTask>>> taskIter =
m_snapshotTableTasks.asMap().entrySet().iterator();
while (taskIter.hasNext()) {
Map.Entry<Integer, Collection<SnapshotTableTask>> taskEntry = taskIter.next();
final int tableId = taskEntry.getKey();
final Collection<SnapshotTableTask> tableTasks = taskEntry.getValue();
final List<BBContainer> outputBuffers = getOutputBuffers(tableTasks, noSchedule);
if (outputBuffers == null) {
// Not enough buffers available
if (!noSchedule) {
rescheduleSnapshotWork(); // depends on control dependency: [if], data = [none]
}
break;
}
// Stream more and add a listener to handle any failures
Pair<ListenableFuture<?>, Boolean> streamResult =
m_streamers.get(tableId).streamMore(context, outputBuffers, null);
if (streamResult.getFirst() != null) {
final ListenableFuture<?> writeFutures = streamResult.getFirst();
writeFutures.addListener(new Runnable() {
@Override
public void run()
{
try {
writeFutures.get(); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
if (m_perSiteLastSnapshotSucceded) {
if (t instanceof StreamSnapshotTimeoutException ||
t.getCause() instanceof StreamSnapshotTimeoutException) {
//This error is already logged by the watchdog when it generates the exception
} else {
if (m_isTruncation) {
VoltDB.crashLocalVoltDB("Unexpected exception while attempting to create truncation snapshot",
true, t); // depends on control dependency: [if], data = [none]
}
SNAP_LOG.error("Error while attempting to write snapshot data", t); // depends on control dependency: [if], data = [none]
}
m_perSiteLastSnapshotSucceded = false; // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
}, CoreUtils.SAMETHREADEXECUTOR); // depends on control dependency: [if], data = [none]
}
/**
* The table streamer will return false when there is no more data left to pull from that table. The
* enclosing loop ensures that the next table is then addressed.
*/
if (!streamResult.getSecond()) {
asyncTerminateReplicatedTableTasks(tableTasks); // depends on control dependency: [if], data = [none]
// XXX: Guava's multimap will clear the tableTasks collection when the entry is
// removed from the containing map, so don't use the collection after removal!
taskIter.remove(); // depends on control dependency: [if], data = [none]
SNAP_LOG.debug("Finished snapshot tasks for table " + tableId +
": " + tableTasks); // depends on control dependency: [if], data = [none]
} else {
break;
}
}
/**
* If there are no more tasks then this particular EE is finished doing snapshot work
* Check the AtomicInteger to find out if this is the last one.
*/
if (m_snapshotTableTasks.isEmpty()) {
SNAP_LOG.debug("Finished with tasks"); // depends on control dependency: [if], data = [none]
// In case this is a non-blocking snapshot, do the post-snapshot tasks here.
runPostSnapshotTasks(context); // depends on control dependency: [if], data = [none]
final ArrayList<SnapshotDataTarget> snapshotTargets = m_snapshotTargets;
m_snapshotTargets = null; // depends on control dependency: [if], data = [none]
m_snapshotTableTasks = null; // depends on control dependency: [if], data = [none]
boolean IamLast = false;
synchronized (ExecutionSitesCurrentlySnapshotting) { // depends on control dependency: [if], data = [none]
if (!ExecutionSitesCurrentlySnapshotting.contains(this)) {
VoltDB.crashLocalVoltDB(
"Currently snapshotting site didn't find itself in set of snapshotting sites", true, null);
}
IamLast = ExecutionSitesCurrentlySnapshotting.size() == 1;
if (!IamLast) {
ExecutionSitesCurrentlySnapshotting.remove(this);
}
}
/**
* If this is the last one then this EE must close all the SnapshotDataTargets.
* Done in a separate thread so the EE can go and do other work. It will
* sync every file descriptor and that may block for a while.
*/
if (IamLast) {
SNAP_LOG.debug("I AM LAST!");
final long txnId = m_lastSnapshotTxnId;
final ExtensibleSnapshotDigestData snapshotDataForZookeeper = m_extraSnapshotData;
m_extraSnapshotData = null;
final Thread terminatorThread =
new Thread("Snapshot terminator") {
@Override
public void run() {
// TRAIL [SnapSave:11] 7 [1 site/host] The last finished site wlll close the targets.
boolean snapshotSucceeded = true;
try {
/*
* Be absolutely sure the snapshot is finished
* and synced to disk before another is started
*/
for (Thread t : m_snapshotTargetTerminators){
if (t == this) {
continue;
}
try {
t.join();
} catch (InterruptedException e) {
return;
}
}
for (final SnapshotDataTarget t : snapshotTargets) {
try {
t.close();
} catch (IOException e) {
snapshotSucceeded = false;
throw new RuntimeException(e);
} catch (InterruptedException e) {
snapshotSucceeded = false;
throw new RuntimeException(e);
}
}
Runnable r = null;
while ((r = m_tasksOnSnapshotCompletion.poll()) != null) {
try {
r.run();
} catch (Exception e) {
SNAP_LOG.error("Error running snapshot completion task", e);
}
}
} finally {
// Caching the value here before the site removes itself from the
// ExecutionSitesCurrentlySnapshotting set, so
// logSnapshotCompletionToZK() will not see incorrect values
// from the next snapshot
try {
VoltDB.instance().getHostMessenger().getZK().delete(
VoltZK.nodes_currently_snapshotting + "/" + VoltDB.instance().getHostMessenger().getHostId(), -1);
} catch (NoNodeException e) {
SNAP_LOG.warn("Expect the snapshot node to already exist during deletion", e);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
} finally {
/**
* Remove this last site from the set here after the terminator has run
* so that new snapshots won't start until
* everything is on disk for the previous snapshot. This prevents a really long
* snapshot initiation procedure from occurring because it has to contend for
* filesystem resources
*
* Do this before logSnapshotCompleteToZK() because the ZK operations are slow,
* and they can trigger snapshot completion interests to fire before this site
* removes itself from the set. The next snapshot request may come in and see
* this snapshot is still in progress.
*/
ExecutionSitesCurrentlySnapshotting.remove(SnapshotSiteProcessor.this); // depends on control dependency: [if], data = [none]
}
logSnapshotCompleteToZK(txnId,
snapshotSucceeded,
snapshotDataForZookeeper);
}
}
};
m_snapshotTargetTerminators.add(terminatorThread);
terminatorThread.start();
}
}
return retval;
} } |
public class class_name {
public void normalize(Model model) {
if(model.getLevel() != BioPAXLevel.L3)
throw new IllegalArgumentException("Not Level3 model. " +
"Consider converting it first (e.g., with the PaxTools).");
//if set, update the xml:base
if(xmlBase != null && !xmlBase.isEmpty())
model.setXmlBase(xmlBase);
// Normalize/merge xrefs, first, and then CVs
// (also because some of original xrefs might have "normalized" URIs
// that, in fact, must be used for other biopax types, such as CV or ProteinReference)
log.info("Normalizing xrefs..." + description);
normalizeXrefs(model);
// fix displayName where possible
if(fixDisplayName) {
log.info("Normalizing display names..." + description);
fixDisplayName(model);
}
log.info("Normalizing CVs..." + description);
normalizeCVs(model);
//normalize BioSource objects (better, as it is here, go after Xrefs and CVs)
log.info("Normalizing organisms..." + description);
normalizeBioSources(model);
// auto-generate missing entity references:
for(SimplePhysicalEntity spe : new HashSet<SimplePhysicalEntity>(model.getObjects(SimplePhysicalEntity.class))) {
//it skips if spe has entityReference or memberPE already
ModelUtils.addMissingEntityReference(model, spe);
}
log.info("Normalizing entity references..." + description);
normalizeERs(model);
// find/add lost (in replace) children
log.info("Repairing..." + description);
model.repair(); // it does not remove dangling utility class objects (can be done separately, later, if needed)
log.info("Optional tasks (reasoning)..." + description);
} } | public class class_name {
public void normalize(Model model) {
if(model.getLevel() != BioPAXLevel.L3)
throw new IllegalArgumentException("Not Level3 model. " +
"Consider converting it first (e.g., with the PaxTools).");
//if set, update the xml:base
if(xmlBase != null && !xmlBase.isEmpty())
model.setXmlBase(xmlBase);
// Normalize/merge xrefs, first, and then CVs
// (also because some of original xrefs might have "normalized" URIs
// that, in fact, must be used for other biopax types, such as CV or ProteinReference)
log.info("Normalizing xrefs..." + description);
normalizeXrefs(model);
// fix displayName where possible
if(fixDisplayName) {
log.info("Normalizing display names..." + description); // depends on control dependency: [if], data = [none]
fixDisplayName(model); // depends on control dependency: [if], data = [none]
}
log.info("Normalizing CVs..." + description);
normalizeCVs(model);
//normalize BioSource objects (better, as it is here, go after Xrefs and CVs)
log.info("Normalizing organisms..." + description);
normalizeBioSources(model);
// auto-generate missing entity references:
for(SimplePhysicalEntity spe : new HashSet<SimplePhysicalEntity>(model.getObjects(SimplePhysicalEntity.class))) {
//it skips if spe has entityReference or memberPE already
ModelUtils.addMissingEntityReference(model, spe); // depends on control dependency: [for], data = [spe]
}
log.info("Normalizing entity references..." + description);
normalizeERs(model);
// find/add lost (in replace) children
log.info("Repairing..." + description);
model.repair(); // it does not remove dangling utility class objects (can be done separately, later, if needed)
log.info("Optional tasks (reasoning)..." + description);
} } |
public class class_name {
public final boolean isVerticalCoordinate(GridRecord gr) {
if (cust != null) {
return cust.isVerticalCoordinate(gr.getLevelType1());
}
int type = gr.getLevelType1();
if (((McIDASGridRecord) gr).hasGribInfo()) {
if (type == 20) {
return true;
}
if (type == 100) {
return true;
}
if (type == 101) {
return true;
}
if ((type >= 103) && (type <= 128)) {
return true;
}
if (type == 141) {
return true;
}
if (type == 160) {
return true;
}
} else if (getLevelUnit(gr).equals("hPa")) {
return true;
}
return false;
} } | public class class_name {
public final boolean isVerticalCoordinate(GridRecord gr) {
if (cust != null) {
return cust.isVerticalCoordinate(gr.getLevelType1()); // depends on control dependency: [if], data = [none]
}
int type = gr.getLevelType1();
if (((McIDASGridRecord) gr).hasGribInfo()) {
if (type == 20) {
return true; // depends on control dependency: [if], data = [none]
}
if (type == 100) {
return true; // depends on control dependency: [if], data = [none]
}
if (type == 101) {
return true; // depends on control dependency: [if], data = [none]
}
if ((type >= 103) && (type <= 128)) {
return true; // depends on control dependency: [if], data = [none]
}
if (type == 141) {
return true; // depends on control dependency: [if], data = [none]
}
if (type == 160) {
return true; // depends on control dependency: [if], data = [none]
}
} else if (getLevelUnit(gr).equals("hPa")) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static boolean parseReturningKeyword(final char[] query, int offset) {
if (query.length < (offset + 9)) {
return false;
}
return (query[offset] | 32) == 'r'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 't'
&& (query[offset + 3] | 32) == 'u'
&& (query[offset + 4] | 32) == 'r'
&& (query[offset + 5] | 32) == 'n'
&& (query[offset + 6] | 32) == 'i'
&& (query[offset + 7] | 32) == 'n'
&& (query[offset + 8] | 32) == 'g';
} } | public class class_name {
public static boolean parseReturningKeyword(final char[] query, int offset) {
if (query.length < (offset + 9)) {
return false; // depends on control dependency: [if], data = [none]
}
return (query[offset] | 32) == 'r'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 't'
&& (query[offset + 3] | 32) == 'u'
&& (query[offset + 4] | 32) == 'r'
&& (query[offset + 5] | 32) == 'n'
&& (query[offset + 6] | 32) == 'i'
&& (query[offset + 7] | 32) == 'n'
&& (query[offset + 8] | 32) == 'g';
} } |
public class class_name {
private WebChromeClient getCurrentWebChromeClient(){
WebChromeClient currentWebChromeClient = null;
Object currentWebView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.class, true));
if (android.os.Build.VERSION.SDK_INT >= 16) {
try{
currentWebView = new Reflect(currentWebView).field("mProvider").out(Object.class);
}catch(IllegalArgumentException ignored) {}
}
try{
if (android.os.Build.VERSION.SDK_INT >= 19) {
Object mClientAdapter = new Reflect(currentWebView).field("mContentsClientAdapter").out(Object.class);
currentWebChromeClient = new Reflect(mClientAdapter).field("mWebChromeClient").out(WebChromeClient.class);
}
else {
Object mCallbackProxy = new Reflect(currentWebView).field("mCallbackProxy").out(Object.class);
currentWebChromeClient = new Reflect(mCallbackProxy).field("mWebChromeClient").out(WebChromeClient.class);
}
}catch(Exception ignored){}
return currentWebChromeClient;
} } | public class class_name {
private WebChromeClient getCurrentWebChromeClient(){
WebChromeClient currentWebChromeClient = null;
Object currentWebView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.class, true));
if (android.os.Build.VERSION.SDK_INT >= 16) {
try{
currentWebView = new Reflect(currentWebView).field("mProvider").out(Object.class); // depends on control dependency: [try], data = [none]
}catch(IllegalArgumentException ignored) {} // depends on control dependency: [catch], data = [none]
}
try{
if (android.os.Build.VERSION.SDK_INT >= 19) {
Object mClientAdapter = new Reflect(currentWebView).field("mContentsClientAdapter").out(Object.class);
currentWebChromeClient = new Reflect(mClientAdapter).field("mWebChromeClient").out(WebChromeClient.class); // depends on control dependency: [if], data = [none]
}
else {
Object mCallbackProxy = new Reflect(currentWebView).field("mCallbackProxy").out(Object.class);
currentWebChromeClient = new Reflect(mCallbackProxy).field("mWebChromeClient").out(WebChromeClient.class); // depends on control dependency: [if], data = [none]
}
}catch(Exception ignored){} // depends on control dependency: [catch], data = [none]
return currentWebChromeClient;
} } |
public class class_name {
private Collection parseTreeCollection(Element collectionElement) {
Collection collection = new Collection();
parseCommonFields(collectionElement, collection);
collection.setTitle(collectionElement.getAttribute("title"));
collection.setDescription(collectionElement.getAttribute("description"));
// Collections can contain either sets or collections (but not both)
NodeList childCollectionElements = collectionElement.getElementsByTagName("collection");
for (int i = 0; i < childCollectionElements.getLength(); i++) {
Element childCollectionElement = (Element) childCollectionElements.item(i);
collection.addCollection(parseTreeCollection(childCollectionElement));
}
NodeList childPhotosetElements = collectionElement.getElementsByTagName("set");
for (int i = 0; i < childPhotosetElements.getLength(); i++) {
Element childPhotosetElement = (Element) childPhotosetElements.item(i);
collection.addPhotoset(createPhotoset(childPhotosetElement));
}
return collection;
} } | public class class_name {
private Collection parseTreeCollection(Element collectionElement) {
Collection collection = new Collection();
parseCommonFields(collectionElement, collection);
collection.setTitle(collectionElement.getAttribute("title"));
collection.setDescription(collectionElement.getAttribute("description"));
// Collections can contain either sets or collections (but not both)
NodeList childCollectionElements = collectionElement.getElementsByTagName("collection");
for (int i = 0; i < childCollectionElements.getLength(); i++) {
Element childCollectionElement = (Element) childCollectionElements.item(i);
collection.addCollection(parseTreeCollection(childCollectionElement)); // depends on control dependency: [for], data = [none]
}
NodeList childPhotosetElements = collectionElement.getElementsByTagName("set");
for (int i = 0; i < childPhotosetElements.getLength(); i++) {
Element childPhotosetElement = (Element) childPhotosetElements.item(i);
collection.addPhotoset(createPhotoset(childPhotosetElement)); // depends on control dependency: [for], data = [none]
}
return collection;
} } |
public class class_name {
protected IScope createAnonymousClassConstructorScope(final JvmGenericType anonymousType, EObject context, final IFeatureScopeSession session) {
// we don't care about the type scope since the type is well known here
IVisibilityHelper protectedIsVisible = new IVisibilityHelper() {
@Override
public boolean isVisible(/* @NonNull */ JvmMember member) {
return member.getVisibility() != JvmVisibility.PRIVATE;
}
};
return new ConstructorTypeScopeWrapper(context, protectedIsVisible, IScope.NULLSCOPE) {
@Override
public Iterable<IEObjectDescription> getElements(EObject object) {
throw new UnsupportedOperationException("TODO implement as necessary");
}
@Override
public Iterable<IEObjectDescription> getElements(QualifiedName name) {
JvmTypeReference superType = Iterables.getLast(anonymousType.getSuperTypes(), null);
if (superType == null)
return Collections.emptyList();
JvmType type = superType.getType();
if (type == null)
return Collections.emptyList();
QualifiedName typeName = qualifiedNameConverter.toQualifiedName(type.getQualifiedName('.'));
if (typeName.getSegmentCount() > name.getSegmentCount()) {
typeName = typeName.skipFirst(typeName.getSegmentCount() - name.getSegmentCount());
}
if (!typeName.equals(name)) {
if (name.getSegmentCount() == 1 && name.getFirstSegment().indexOf('$') > 0) {
QualifiedName splitted = QualifiedName.create(Strings.split(name.getFirstSegment(), '$'));
typeName = qualifiedNameConverter.toQualifiedName(type.getQualifiedName('.'));
if (typeName.getSegmentCount() > splitted.getSegmentCount()) {
typeName = typeName.skipFirst(typeName.getSegmentCount() - splitted.getSegmentCount());
}
if (!typeName.equals(splitted)) {
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
}
IEObjectDescription typeDescription = EObjectDescription.create(name, anonymousType);
return createFeatureDescriptions(Collections.singletonList(typeDescription));
}
@Override
protected ConstructorDescription createConstructorDescription(IEObjectDescription typeDescription, JvmConstructor constructor, boolean visible) {
return createAnonmousClassConstructorDescription(typeDescription.getName(), constructor, visible);
}
};
} } | public class class_name {
protected IScope createAnonymousClassConstructorScope(final JvmGenericType anonymousType, EObject context, final IFeatureScopeSession session) {
// we don't care about the type scope since the type is well known here
IVisibilityHelper protectedIsVisible = new IVisibilityHelper() {
@Override
public boolean isVisible(/* @NonNull */ JvmMember member) {
return member.getVisibility() != JvmVisibility.PRIVATE;
}
};
return new ConstructorTypeScopeWrapper(context, protectedIsVisible, IScope.NULLSCOPE) {
@Override
public Iterable<IEObjectDescription> getElements(EObject object) {
throw new UnsupportedOperationException("TODO implement as necessary");
}
@Override
public Iterable<IEObjectDescription> getElements(QualifiedName name) {
JvmTypeReference superType = Iterables.getLast(anonymousType.getSuperTypes(), null);
if (superType == null)
return Collections.emptyList();
JvmType type = superType.getType();
if (type == null)
return Collections.emptyList();
QualifiedName typeName = qualifiedNameConverter.toQualifiedName(type.getQualifiedName('.'));
if (typeName.getSegmentCount() > name.getSegmentCount()) {
typeName = typeName.skipFirst(typeName.getSegmentCount() - name.getSegmentCount()); // depends on control dependency: [if], data = [(typeName.getSegmentCount()]
}
if (!typeName.equals(name)) {
if (name.getSegmentCount() == 1 && name.getFirstSegment().indexOf('$') > 0) {
QualifiedName splitted = QualifiedName.create(Strings.split(name.getFirstSegment(), '$'));
typeName = qualifiedNameConverter.toQualifiedName(type.getQualifiedName('.')); // depends on control dependency: [if], data = [none]
if (typeName.getSegmentCount() > splitted.getSegmentCount()) {
typeName = typeName.skipFirst(typeName.getSegmentCount() - splitted.getSegmentCount()); // depends on control dependency: [if], data = [(typeName.getSegmentCount()]
}
if (!typeName.equals(splitted)) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
} else {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
}
IEObjectDescription typeDescription = EObjectDescription.create(name, anonymousType);
return createFeatureDescriptions(Collections.singletonList(typeDescription));
}
@Override
protected ConstructorDescription createConstructorDescription(IEObjectDescription typeDescription, JvmConstructor constructor, boolean visible) {
return createAnonmousClassConstructorDescription(typeDescription.getName(), constructor, visible);
}
};
} } |
public class class_name {
protected T authenticateUserViaToken(final ActionRequest actionRequest) {
final HttpServletRequest servletRequest = actionRequest.getHttpServletRequest();
// then try the auth token
final String token = ServletUtil.resolveAuthBearerToken(servletRequest);
if (token == null) {
return null;
}
final T authToken = userAuth().validateToken(token);
if (authToken == null) {
return null;
}
// granted
final T newAuthToken = userAuth().rotateToken(authToken);
actionRequest.getHttpServletResponse().setHeader("Authentication", "Bearer: " + userAuth().tokenValue(newAuthToken));
return newAuthToken;
} } | public class class_name {
protected T authenticateUserViaToken(final ActionRequest actionRequest) {
final HttpServletRequest servletRequest = actionRequest.getHttpServletRequest();
// then try the auth token
final String token = ServletUtil.resolveAuthBearerToken(servletRequest);
if (token == null) {
return null; // depends on control dependency: [if], data = [none]
}
final T authToken = userAuth().validateToken(token);
if (authToken == null) {
return null; // depends on control dependency: [if], data = [none]
}
// granted
final T newAuthToken = userAuth().rotateToken(authToken);
actionRequest.getHttpServletResponse().setHeader("Authentication", "Bearer: " + userAuth().tokenValue(newAuthToken));
return newAuthToken;
} } |
public class class_name {
private static int decodeBasicProperties(JmsDestination newDest, byte[] msgForm) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "decodeBasicProperties", new Object[]{newDest, msgForm});
int offset = 0;
// The 2nd half of the first byte carries the DeliveryMode
byte delMode = (byte)(msgForm[0] & DM_MASK);
if (delMode == DM_PERSISTENT) {
newDest.setDeliveryMode(ApiJmsConstants.DELIVERY_MODE_PERSISTENT);
}
else if (delMode == DM_NON_PERSISTENT) {
newDest.setDeliveryMode(ApiJmsConstants.DELIVERY_MODE_NONPERSISTENT);
}
else {
newDest.setDeliveryMode(ApiJmsConstants.DELIVERY_MODE_APP);
}
// Next we get a half-byte for priority
byte priority = (byte)(msgForm[1] & PRIORITY_MASK);
if (priority != PRIORITY_NOT_SET) {
int pri = 0x0F & (priority >>> 4);
newDest.setPriority(pri);
}
// Next we establish if we have a TimeToLive, & decode it if we have
if ((msgForm[1] & TTL_SET) == TTL_SET) {
long ttl = ArrayUtil.readLong(msgForm, 2);
newDest.setTimeToLive(ttl);
offset = 10;
}
else {
offset = 2;
};
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "decodeBasicProperties", offset);
return offset;
} } | public class class_name {
private static int decodeBasicProperties(JmsDestination newDest, byte[] msgForm) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "decodeBasicProperties", new Object[]{newDest, msgForm});
int offset = 0;
// The 2nd half of the first byte carries the DeliveryMode
byte delMode = (byte)(msgForm[0] & DM_MASK);
if (delMode == DM_PERSISTENT) {
newDest.setDeliveryMode(ApiJmsConstants.DELIVERY_MODE_PERSISTENT); // depends on control dependency: [if], data = [none]
}
else if (delMode == DM_NON_PERSISTENT) {
newDest.setDeliveryMode(ApiJmsConstants.DELIVERY_MODE_NONPERSISTENT); // depends on control dependency: [if], data = [none]
}
else {
newDest.setDeliveryMode(ApiJmsConstants.DELIVERY_MODE_APP); // depends on control dependency: [if], data = [none]
}
// Next we get a half-byte for priority
byte priority = (byte)(msgForm[1] & PRIORITY_MASK);
if (priority != PRIORITY_NOT_SET) {
int pri = 0x0F & (priority >>> 4);
newDest.setPriority(pri); // depends on control dependency: [if], data = [none]
}
// Next we establish if we have a TimeToLive, & decode it if we have
if ((msgForm[1] & TTL_SET) == TTL_SET) {
long ttl = ArrayUtil.readLong(msgForm, 2);
newDest.setTimeToLive(ttl); // depends on control dependency: [if], data = [none]
offset = 10; // depends on control dependency: [if], data = [none]
}
else {
offset = 2; // depends on control dependency: [if], data = [none]
};
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "decodeBasicProperties", offset);
return offset;
} } |
public class class_name {
public void marshall(GetDeviceRequest getDeviceRequest, ProtocolMarshaller protocolMarshaller) {
if (getDeviceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getDeviceRequest.getDeviceArn(), DEVICEARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetDeviceRequest getDeviceRequest, ProtocolMarshaller protocolMarshaller) {
if (getDeviceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getDeviceRequest.getDeviceArn(), DEVICEARN_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 void disconnectOnChange(@Observes final iOSVariantUpdateEvent iOSVariantUpdateEvent) {
final iOSVariant variant = iOSVariantUpdateEvent.getiOSVariant();
final String connectionKey = extractConnectionKey(variant);
final ApnsClient client = apnsClientExpiringMap.remove(connectionKey);
logger.debug("Removed client from cache for {}", variant.getVariantID());
if (client != null) {
tearDownApnsHttp2Connection(client);
}
} } | public class class_name {
public void disconnectOnChange(@Observes final iOSVariantUpdateEvent iOSVariantUpdateEvent) {
final iOSVariant variant = iOSVariantUpdateEvent.getiOSVariant();
final String connectionKey = extractConnectionKey(variant);
final ApnsClient client = apnsClientExpiringMap.remove(connectionKey);
logger.debug("Removed client from cache for {}", variant.getVariantID());
if (client != null) {
tearDownApnsHttp2Connection(client); // depends on control dependency: [if], data = [(client]
}
} } |
public class class_name {
public void setType(java.util.Collection<StringFilter> type) {
if (type == null) {
this.type = null;
return;
}
this.type = new java.util.ArrayList<StringFilter>(type);
} } | public class class_name {
public void setType(java.util.Collection<StringFilter> type) {
if (type == null) {
this.type = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.type = new java.util.ArrayList<StringFilter>(type);
} } |
public class class_name {
private static void parseValueElement(Element element,
ConfigurableEmitter.Value value) {
if (element == null) {
return;
}
String type = element.getAttribute("type");
String v = element.getAttribute("value");
if (type == null || type.length() == 0) {
// support for old style which did not write the type
if (value instanceof SimpleValue) {
((SimpleValue) value).setValue(Float.parseFloat(v));
} else if (value instanceof RandomValue) {
((RandomValue) value).setValue(Float.parseFloat(v));
} else {
Log.warn("problems reading element, skipping: " + element);
}
} else {
// type given: this is the new style
if (type.equals("simple")) {
((SimpleValue) value).setValue(Float.parseFloat(v));
} else if (type.equals("random")) {
((RandomValue) value).setValue(Float.parseFloat(v));
} else if (type.equals("linear")) {
String min = element.getAttribute("min");
String max = element.getAttribute("max");
String active = element.getAttribute("active");
NodeList points = element.getElementsByTagName("point");
ArrayList curve = new ArrayList();
for (int i = 0; i < points.getLength(); i++) {
Element point = (Element) points.item(i);
float x = Float.parseFloat(point.getAttribute("x"));
float y = Float.parseFloat(point.getAttribute("y"));
curve.add(new Vector2f(x, y));
}
((LinearInterpolator) value).setCurve(curve);
((LinearInterpolator) value).setMin(Integer.parseInt(min));
((LinearInterpolator) value).setMax(Integer.parseInt(max));
((LinearInterpolator) value).setActive("true".equals(active));
} else {
Log.warn("unkown type detected: " + type);
}
}
} } | public class class_name {
private static void parseValueElement(Element element,
ConfigurableEmitter.Value value) {
if (element == null) {
return;
// depends on control dependency: [if], data = [none]
}
String type = element.getAttribute("type");
String v = element.getAttribute("value");
if (type == null || type.length() == 0) {
// support for old style which did not write the type
if (value instanceof SimpleValue) {
((SimpleValue) value).setValue(Float.parseFloat(v));
// depends on control dependency: [if], data = [none]
} else if (value instanceof RandomValue) {
((RandomValue) value).setValue(Float.parseFloat(v));
// depends on control dependency: [if], data = [none]
} else {
Log.warn("problems reading element, skipping: " + element);
// depends on control dependency: [if], data = [none]
}
} else {
// type given: this is the new style
if (type.equals("simple")) {
((SimpleValue) value).setValue(Float.parseFloat(v));
// depends on control dependency: [if], data = [none]
} else if (type.equals("random")) {
((RandomValue) value).setValue(Float.parseFloat(v));
// depends on control dependency: [if], data = [none]
} else if (type.equals("linear")) {
String min = element.getAttribute("min");
String max = element.getAttribute("max");
String active = element.getAttribute("active");
NodeList points = element.getElementsByTagName("point");
ArrayList curve = new ArrayList();
for (int i = 0; i < points.getLength(); i++) {
Element point = (Element) points.item(i);
float x = Float.parseFloat(point.getAttribute("x"));
float y = Float.parseFloat(point.getAttribute("y"));
curve.add(new Vector2f(x, y));
// depends on control dependency: [for], data = [none]
}
((LinearInterpolator) value).setCurve(curve);
// depends on control dependency: [if], data = [none]
((LinearInterpolator) value).setMin(Integer.parseInt(min));
// depends on control dependency: [if], data = [none]
((LinearInterpolator) value).setMax(Integer.parseInt(max));
// depends on control dependency: [if], data = [none]
((LinearInterpolator) value).setActive("true".equals(active));
// depends on control dependency: [if], data = [none]
} else {
Log.warn("unkown type detected: " + type);
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static AcceptPreference fromHeaders(Collection<AcceptPreference> headers) {
if (headers.isEmpty()) {
throw new IllegalArgumentException("Header list must contain at least one element.");
}
TreeSet<AcceptHeaderEntry> entries = new TreeSet<>();
for (AcceptPreference header : headers) {
// It's OK to do this as AcceptHeaderEntry is immutable.
entries.addAll(header.entries);
}
return new AcceptPreference(entries);
} } | public class class_name {
public static AcceptPreference fromHeaders(Collection<AcceptPreference> headers) {
if (headers.isEmpty()) {
throw new IllegalArgumentException("Header list must contain at least one element.");
}
TreeSet<AcceptHeaderEntry> entries = new TreeSet<>();
for (AcceptPreference header : headers) {
// It's OK to do this as AcceptHeaderEntry is immutable.
entries.addAll(header.entries); // depends on control dependency: [for], data = [header]
}
return new AcceptPreference(entries);
} } |
public class class_name {
@Override
public Date[] getDatastreamVersions(String datastreamID) {
ArrayList<Date> versionDates = new ArrayList<Date>();
for (Datastream d : m_obj.datastreams(datastreamID)) {
versionDates.add(d.DSCreateDT);
}
return versionDates.toArray(DATE_TYPE);
} } | public class class_name {
@Override
public Date[] getDatastreamVersions(String datastreamID) {
ArrayList<Date> versionDates = new ArrayList<Date>();
for (Datastream d : m_obj.datastreams(datastreamID)) {
versionDates.add(d.DSCreateDT); // depends on control dependency: [for], data = [d]
}
return versionDates.toArray(DATE_TYPE);
} } |
public class class_name {
private void updatePropertiesData(Property bridge) {
Property selectedItem = getSelectedEntity();
if (bridge != null) { selectedItem = bridge; }
if (selectedItem != null) {
ModelNode sourceContextNode = selectedItem.getValue().get("source-context");
ModelNode targetContextNode = selectedItem.getValue().get("target-context");
sourceContextEditor.update(sourceContextNode.asPropertyList());
targetContextEditor.update(targetContextNode.asPropertyList());
formAssets.getForm().edit(selectedItem.getValue());
sourceCredentialRefForm.getForm().edit(selectedItem.getValue().get("source-credential-reference"));
targetCredentialRefForm.getForm().edit(selectedItem.getValue().get("target-credential-reference"));
} else {
formAssets.getForm().clearValues();
sourceContextEditor.clearValues();
targetContextEditor.clearValues();
sourceCredentialRefForm.getForm().clearValues();
targetCredentialRefForm.getForm().clearValues();
}
sourceContextEditor.enableToolButtons(selectedItem != null);
targetContextEditor.enableToolButtons(selectedItem != null);
} } | public class class_name {
private void updatePropertiesData(Property bridge) {
Property selectedItem = getSelectedEntity();
if (bridge != null) { selectedItem = bridge; } // depends on control dependency: [if], data = [none]
if (selectedItem != null) {
ModelNode sourceContextNode = selectedItem.getValue().get("source-context");
ModelNode targetContextNode = selectedItem.getValue().get("target-context");
sourceContextEditor.update(sourceContextNode.asPropertyList()); // depends on control dependency: [if], data = [none]
targetContextEditor.update(targetContextNode.asPropertyList()); // depends on control dependency: [if], data = [none]
formAssets.getForm().edit(selectedItem.getValue()); // depends on control dependency: [if], data = [(selectedItem]
sourceCredentialRefForm.getForm().edit(selectedItem.getValue().get("source-credential-reference")); // depends on control dependency: [if], data = [(selectedItem]
targetCredentialRefForm.getForm().edit(selectedItem.getValue().get("target-credential-reference")); // depends on control dependency: [if], data = [(selectedItem]
} else {
formAssets.getForm().clearValues(); // depends on control dependency: [if], data = [none]
sourceContextEditor.clearValues(); // depends on control dependency: [if], data = [none]
targetContextEditor.clearValues(); // depends on control dependency: [if], data = [none]
sourceCredentialRefForm.getForm().clearValues(); // depends on control dependency: [if], data = [none]
targetCredentialRefForm.getForm().clearValues(); // depends on control dependency: [if], data = [none]
}
sourceContextEditor.enableToolButtons(selectedItem != null);
targetContextEditor.enableToolButtons(selectedItem != null);
} } |
public class class_name {
@Override
public boolean observesDaylightTime() {
long time = System.currentTimeMillis();
// Check if daylight saving time is observed now.
int[] offsets = new int[2];
getOffset(time, false, offsets);
if (offsets[1] != 0) {
return true;
}
// If DST is not used now, check if DST is used after each transition.
BitSet checkFinals = finalRules == null ? null : new BitSet(finalRules.length);
while (true) {
TimeZoneTransition tt = getNextTransition(time, false);
if (tt == null) {
// no more transition
break;
}
TimeZoneRule toRule = tt.getTo();
if (toRule.getDSTSavings() != 0) {
return true;
}
if (checkFinals != null) {
// final rules exist - check if we saw all of them
for (int i = 0; i < finalRules.length; i++) {
if (finalRules[i].equals(toRule)) {
checkFinals.set(i);
}
}
if (checkFinals.cardinality() == finalRules.length) {
// already saw all final rules
break;
}
}
time = tt.getTime();
}
return false;
} } | public class class_name {
@Override
public boolean observesDaylightTime() {
long time = System.currentTimeMillis();
// Check if daylight saving time is observed now.
int[] offsets = new int[2];
getOffset(time, false, offsets);
if (offsets[1] != 0) {
return true; // depends on control dependency: [if], data = [none]
}
// If DST is not used now, check if DST is used after each transition.
BitSet checkFinals = finalRules == null ? null : new BitSet(finalRules.length);
while (true) {
TimeZoneTransition tt = getNextTransition(time, false);
if (tt == null) {
// no more transition
break;
}
TimeZoneRule toRule = tt.getTo();
if (toRule.getDSTSavings() != 0) {
return true; // depends on control dependency: [if], data = [none]
}
if (checkFinals != null) {
// final rules exist - check if we saw all of them
for (int i = 0; i < finalRules.length; i++) {
if (finalRules[i].equals(toRule)) {
checkFinals.set(i); // depends on control dependency: [if], data = [none]
}
}
if (checkFinals.cardinality() == finalRules.length) {
// already saw all final rules
break;
}
}
time = tt.getTime(); // depends on control dependency: [while], data = [none]
}
return false;
} } |
public class class_name {
public String getDirectConnectionCipherSuite() {
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse();
}
Class<? extends IRequest> requestClass = _request.getClass();
String cipherSuite = null;
if(checkAssignableFromIRequestImpl(requestClass)){
Method method;
try {
method = requestClass.getMethod("getConnectionCipherSuite", null);
cipherSuite = (String) method.invoke(_request, null);
} catch (Exception e) {
com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.srt.SRTServletRequest.getDirectConnectionCipherSuite", "587", this);
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"getDirectConnectionCipherSuite", "failed to retrieve direction connection cipher suite",e);
}
}
}
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"getDirectConnectionCipherSuite", "this->"+this+": "+" value --> " + cipherSuite);
}
return cipherSuite;
} } | public class class_name {
public String getDirectConnectionCipherSuite() {
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse(); // depends on control dependency: [if], data = [none]
}
Class<? extends IRequest> requestClass = _request.getClass();
String cipherSuite = null;
if(checkAssignableFromIRequestImpl(requestClass)){
Method method;
try {
method = requestClass.getMethod("getConnectionCipherSuite", null); // depends on control dependency: [try], data = [none]
cipherSuite = (String) method.invoke(_request, null); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.srt.SRTServletRequest.getDirectConnectionCipherSuite", "587", this);
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"getDirectConnectionCipherSuite", "failed to retrieve direction connection cipher suite",e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"getDirectConnectionCipherSuite", "this->"+this+": "+" value --> " + cipherSuite); // depends on control dependency: [if], data = [none]
}
return cipherSuite;
} } |
public class class_name {
public static String generateMD5(final String input) {
try {
return generateMD5(input.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
LOG.debug("An error occurred generating the MD5 Hash of the input string", e);
return null;
}
} } | public class class_name {
public static String generateMD5(final String input) {
try {
return generateMD5(input.getBytes("UTF-8")); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
LOG.debug("An error occurred generating the MD5 Hash of the input string", e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void createRadioButtons() {
node.getChildren().clear();
radioButtons.clear();
for (int i = 0; i < field.getItems().size(); i++) {
RadioButton rb = new RadioButton();
rb.setText(field.getItems().get(i).toString());
rb.setToggleGroup(toggleGroup);
radioButtons.add(rb);
}
if (field.getSelection() != null) {
radioButtons.get(field.getItems().indexOf(field.getSelection())).setSelected(true);
}
node.getChildren().addAll(radioButtons);
} } | public class class_name {
private void createRadioButtons() {
node.getChildren().clear();
radioButtons.clear();
for (int i = 0; i < field.getItems().size(); i++) {
RadioButton rb = new RadioButton();
rb.setText(field.getItems().get(i).toString()); // depends on control dependency: [for], data = [i]
rb.setToggleGroup(toggleGroup); // depends on control dependency: [for], data = [none]
radioButtons.add(rb); // depends on control dependency: [for], data = [none]
}
if (field.getSelection() != null) {
radioButtons.get(field.getItems().indexOf(field.getSelection())).setSelected(true); // depends on control dependency: [if], data = [(field.getSelection()]
}
node.getChildren().addAll(radioButtons);
} } |
public class class_name {
public static boolean isConversionEnabled(String conversionMode) {
boolean value = true;
if ((conversionMode == null) || (conversionMode.indexOf(PARAM_DISABLED) != -1)) {
value = false;
}
return value;
} } | public class class_name {
public static boolean isConversionEnabled(String conversionMode) {
boolean value = true;
if ((conversionMode == null) || (conversionMode.indexOf(PARAM_DISABLED) != -1)) {
value = false; // depends on control dependency: [if], data = [none]
}
return value;
} } |
public class class_name {
public Q setFetchSize(final int rows) {
checkNotClosed();
this.fetchSize = rows;
if (statement != null) {
try {
statement.setFetchSize(fetchSize);
} catch (SQLException sex) {
throw new DbSqlException(this, "Unable to set fetch size: " + fetchSize, sex);
}
}
return _this();
} } | public class class_name {
public Q setFetchSize(final int rows) {
checkNotClosed();
this.fetchSize = rows;
if (statement != null) {
try {
statement.setFetchSize(fetchSize); // depends on control dependency: [try], data = [none]
} catch (SQLException sex) {
throw new DbSqlException(this, "Unable to set fetch size: " + fetchSize, sex);
} // depends on control dependency: [catch], data = [none]
}
return _this();
} } |
public class class_name {
@Override
public void draw(Canvas c, Projection projection) {
final double zoomLevel = projection.getZoomLevel();
if (zoomLevel < minZoom) {
return;
}
final Rect rect = projection.getIntrinsicScreenRect();
int _screenWidth = rect.width();
int _screenHeight = rect.height();
boolean screenSizeChanged = _screenHeight!=screenHeight || _screenWidth != screenWidth;
screenHeight = _screenHeight;
screenWidth = _screenWidth;
final IGeoPoint center = projection.fromPixels(screenWidth / 2, screenHeight / 2, null);
if (zoomLevel != lastZoomLevel || center.getLatitude() != lastLatitude || screenSizeChanged) {
lastZoomLevel = zoomLevel;
lastLatitude = center.getLatitude();
rebuildBarPath(projection);
}
int offsetX = xOffset;
int offsetY = yOffset;
if (alignBottom) offsetY *=-1;
if (alignRight ) offsetX *=-1;
if (centred && latitudeBar)
offsetX += -latitudeBarRect.width() / 2;
if (centred && longitudeBar)
offsetY += -longitudeBarRect.height() / 2;
projection.save(c, false, true);
c.translate(offsetX, offsetY);
if (latitudeBar && bgPaint != null)
c.drawRect(latitudeBarRect, bgPaint);
if (longitudeBar && bgPaint != null) {
// Don't draw on top of latitude background...
int offsetTop = latitudeBar ? latitudeBarRect.height() : 0;
c.drawRect(longitudeBarRect.left, longitudeBarRect.top + offsetTop,
longitudeBarRect.right, longitudeBarRect.bottom, bgPaint);
}
c.drawPath(barPath, barPaint);
if (latitudeBar) {
drawLatitudeText(c, projection);
}
if (longitudeBar) {
drawLongitudeText(c, projection);
}
projection.restore(c, true);
} } | public class class_name {
@Override
public void draw(Canvas c, Projection projection) {
final double zoomLevel = projection.getZoomLevel();
if (zoomLevel < minZoom) {
return; // depends on control dependency: [if], data = [none]
}
final Rect rect = projection.getIntrinsicScreenRect();
int _screenWidth = rect.width();
int _screenHeight = rect.height();
boolean screenSizeChanged = _screenHeight!=screenHeight || _screenWidth != screenWidth;
screenHeight = _screenHeight;
screenWidth = _screenWidth;
final IGeoPoint center = projection.fromPixels(screenWidth / 2, screenHeight / 2, null);
if (zoomLevel != lastZoomLevel || center.getLatitude() != lastLatitude || screenSizeChanged) {
lastZoomLevel = zoomLevel; // depends on control dependency: [if], data = [none]
lastLatitude = center.getLatitude(); // depends on control dependency: [if], data = [none]
rebuildBarPath(projection); // depends on control dependency: [if], data = [none]
}
int offsetX = xOffset;
int offsetY = yOffset;
if (alignBottom) offsetY *=-1;
if (alignRight ) offsetX *=-1;
if (centred && latitudeBar)
offsetX += -latitudeBarRect.width() / 2;
if (centred && longitudeBar)
offsetY += -longitudeBarRect.height() / 2;
projection.save(c, false, true);
c.translate(offsetX, offsetY);
if (latitudeBar && bgPaint != null)
c.drawRect(latitudeBarRect, bgPaint);
if (longitudeBar && bgPaint != null) {
// Don't draw on top of latitude background...
int offsetTop = latitudeBar ? latitudeBarRect.height() : 0;
c.drawRect(longitudeBarRect.left, longitudeBarRect.top + offsetTop,
longitudeBarRect.right, longitudeBarRect.bottom, bgPaint); // depends on control dependency: [if], data = [none]
}
c.drawPath(barPath, barPaint);
if (latitudeBar) {
drawLatitudeText(c, projection); // depends on control dependency: [if], data = [none]
}
if (longitudeBar) {
drawLongitudeText(c, projection); // depends on control dependency: [if], data = [none]
}
projection.restore(c, true);
} } |
public class class_name {
@PreDestroy
public void destroy() {
if (executorService != null) {
LOGGER.info("Shutting down message provider cache cleanup thread");
cleanupJob.cancel(true);
executorService.shutdown();
}
} } | public class class_name {
@PreDestroy
public void destroy() {
if (executorService != null) {
LOGGER.info("Shutting down message provider cache cleanup thread"); // depends on control dependency: [if], data = [none]
cleanupJob.cancel(true); // depends on control dependency: [if], data = [none]
executorService.shutdown(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void setProperty(Object bean, String field, Object value) {
INSTANCE.checkParameters(bean, field);
try {
INSTANCE.setPropertyValue(bean, field, value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw handleReflectionException(bean.getClass(), field, e);
}
} } | public class class_name {
public static void setProperty(Object bean, String field, Object value) {
INSTANCE.checkParameters(bean, field);
try {
INSTANCE.setPropertyValue(bean, field, value); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw handleReflectionException(bean.getClass(), field, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
void initTabEventHandler(final ToggleButton tabButton) {
try {
tabButton.setOnDragDetected(getHandler(MouseEvent.DRAG_DETECTED));
tabButton.setOnAction(getHandler(ActionEvent.ACTION));
} catch (final CoreException ce) {
LOGGER.error("Error while attaching event handler", ce);
}
} } | public class class_name {
void initTabEventHandler(final ToggleButton tabButton) {
try {
tabButton.setOnDragDetected(getHandler(MouseEvent.DRAG_DETECTED)); // depends on control dependency: [try], data = [none]
tabButton.setOnAction(getHandler(ActionEvent.ACTION)); // depends on control dependency: [try], data = [none]
} catch (final CoreException ce) {
LOGGER.error("Error while attaching event handler", ce);
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.